muzzman_lib/local_session/
session.rs

1use std::{
2    collections::hash_map::DefaultHasher,
3    hash::{Hash, Hasher},
4    ops::Range,
5    path::PathBuf,
6    sync::{Arc, RwLock},
7};
8
9use crate::prelude::*;
10
11#[derive(Default)]
12pub struct LocalSession {
13    pub location: Option<LRow>,
14    pub modules: Vec<MRow>,
15    pub actions: Vec<Arc<RwLock<Action>>>,
16    pub callback: Option<Box<dyn Fn(SessionEvent)>>,
17}
18
19impl LocalSession {
20    pub fn new_session(self) -> Box<dyn TSession> {
21        let session = self;
22
23        let session = Arc::new(RwLock::new(session));
24
25        let location_info = Arc::new(RwLock::new(RefLocation {
26            session: Some(session.c()),
27            id: Default::default(),
28        }));
29
30        let location = Arc::new(RwLock::new(Location {
31            name: String::from("Default Location"),
32            desc: String::from("Default Location"),
33            where_is: WhereIsLocation::Local(LocalLocation {
34                path: PathBuf::from("."),
35            }),
36            shoud_save: false,
37            elements: Vec::new(),
38            locations: Vec::new(),
39            info: location_info,
40            module: None,
41            path: PathBuf::from("."),
42            thread: None,
43            events: Arc::new(RwLock::new(Events::default())),
44        }));
45        session.write().unwrap().location = Some(location);
46        session.c()
47    }
48}
49
50trait TLocalSession {
51    fn get_location(&self, info: &LocationId) -> Result<LRow, SessionError>;
52    fn get_element(&self, info: &ElementId) -> Result<ERow, SessionError>;
53    fn get_module(&self, info: &ModuleId) -> Result<MRow, SessionError>;
54
55    fn add_module(&self, module: Box<dyn TModule>) -> Result<MRef, SessionError>;
56
57    fn notify_all(&self, event: SessionEvent) -> Result<(), SessionError>;
58}
59
60impl TLocalSession for Arc<RwLock<LocalSession>> {
61    fn get_location(&self, info: &LocationId) -> Result<LRow, SessionError> {
62        if let Some(location) = &mut self.write().unwrap().location {
63            let mut loc = location.clone();
64            for i in info.0.clone() {
65                let tmp_loc;
66                if let Some(location) = loc.read().unwrap().locations.get(i as usize) {
67                    tmp_loc = location.clone()
68                } else {
69                    return Err(SessionError::InvalidLocation);
70                }
71                loc = tmp_loc
72            }
73
74            return Ok(loc);
75        }
76        Err(SessionError::InvalidLocation)
77    }
78
79    fn get_element(&self, info: &ElementId) -> Result<ERow, SessionError> {
80        if let Some(element) = self
81            .get_location(&info.location_id)?
82            .read()
83            .unwrap()
84            .elements
85            .get(info.uid as usize)
86        {
87            Ok(element.clone())
88        } else {
89            Err(SessionError::ElementDoNotExist)
90        }
91    }
92
93    fn get_module(&self, info: &ModuleId) -> Result<MRow, SessionError> {
94        if let Some(module) = self.read().unwrap().modules.get(info.0 as usize) {
95            Ok(module.clone())
96        } else {
97            Err(SessionError::InvalidModule)
98        }
99    }
100
101    fn add_module(&self, module: Box<dyn TModule>) -> Result<MRef, SessionError> {
102        // if other module has the same default name with the new module will be replaced and will
103        // be returned as the new module
104        {
105            let len = self.get_modules_len()?;
106            let name = module.get_name();
107            for m in self.get_modules(0..len)? {
108                if m.get_default_name()? == name {
109                    self.get_module(&m.id())?.write().unwrap().module = module;
110                    return Ok(m);
111                }
112            }
113        }
114
115        let info = Arc::new(RwLock::new(RefModule {
116            uid: ModuleId(self.get_modules_len()? as u64),
117            session: Some(self.c()),
118        }));
119
120        let mut settings = Data::new();
121        let mut element_data = Data::new();
122
123        module.init_settings(&mut settings);
124        module.init_element_settings(&mut element_data);
125
126        let module = Module {
127            name: module.get_name(),
128            desc: module.get_desc(),
129            module,
130            proxy: 0,
131            settings,
132            element_data,
133            info: info.clone(),
134        };
135
136        if let Err(error) = module.module.init(info.clone()) {
137            return Err(SessionError::CannotInstallModule(error));
138        }
139
140        self.write()
141            .unwrap()
142            .modules
143            .push(Arc::new(RwLock::new(module)));
144
145        let _ = self.notify_all(SessionEvent::NewModule(info.read().unwrap().uid));
146
147        Ok(info)
148    }
149
150    fn notify_all(&self, event: SessionEvent) -> Result<(), SessionError> {
151        let mut locations = vec![self.get_default_location()?];
152        let mut new_range = 0..1;
153
154        while !new_range.is_empty() {
155            let start_pos = locations.len();
156            let locat = locations[new_range.clone()].to_vec();
157            for location in locat {
158                let len = location.get_locations_len()?;
159                for loc in location.get_locations(0..len)? {
160                    locations.push(loc);
161                }
162            }
163
164            new_range = start_pos..locations.len();
165        }
166
167        for location in locations {
168            let _ = location.notify(Event::SessionEvent(event.clone()));
169            let len = location.get_elements_len()?;
170            for element in location.get_elements(0..len)? {
171                let _ = element.notify(Event::SessionEvent(event.clone()));
172            }
173        }
174
175        if let Some(callback) = &self.read().unwrap().callback {
176            callback(event)
177        }
178
179        Ok(())
180    }
181}
182
183impl TSession for Arc<RwLock<LocalSession>> {
184    fn load_module(&self, path: PathBuf) -> Result<MRef, SessionError> {
185        let module = RawModule::new_module(&path);
186
187        match module {
188            Ok(module) => Ok(self.add_module(module)?),
189            Err(err) => Err(SessionError::RawModule(err)),
190        }
191    }
192
193    fn remove_module(&self, info: ModuleId) -> Result<MRow, SessionError> {
194        let _ = self.notify_all(SessionEvent::DestroyedModule(info));
195
196        let index = info.0;
197        {
198            let module = self.read().unwrap().modules[index as usize].clone();
199            let module = module.read().unwrap();
200            let info = module.info.clone();
201            self.write()
202                .unwrap()
203                .actions
204                .retain(|e| *e.read().unwrap().owner.read().unwrap() != *info.read().unwrap());
205        }
206        let module = self.write().unwrap().modules.remove(index as usize);
207
208        let mut notifications = Vec::new();
209
210        for (i, module) in self.write().unwrap().modules.iter().enumerate() {
211            let info = &module.write().unwrap().info;
212            let last = info.read().unwrap().uid;
213            let mut new = last;
214            new.0 = i as u64;
215            info.write().unwrap().uid = new;
216            notifications.push(SessionEvent::ModuleIdChanged(last, new));
217        }
218
219        for notification in notifications {
220            let _ = self.notify_all(notification);
221        }
222
223        Ok(module)
224    }
225
226    fn register_action(
227        &self,
228        module: &ModuleId,
229        name: String,
230        values: Vec<(String, Value)>,
231        callback: fn(MRef, values: Vec<Type>),
232    ) -> Result<(), SessionError> {
233        self.write()
234            .unwrap()
235            .actions
236            .push(Arc::new(RwLock::new(Action {
237                name,
238                owner: Arc::new(RwLock::new(RefModule {
239                    session: Some(self.c()),
240                    uid: *module,
241                })),
242                input: values,
243                callback,
244            })));
245        Ok(())
246    }
247
248    fn remove_action(&self, owner: &ModuleId, name: String) -> Result<(), SessionError> {
249        let mut finded = None;
250        for (i, action) in self.read().unwrap().actions.iter().enumerate() {
251            let action = action.read().unwrap();
252            if action.owner.read().unwrap().uid == *owner && action.name == name {
253                finded = Some(i);
254                break;
255            }
256        }
257        if let Some(finded) = finded {
258            self.write().unwrap().actions.remove(finded);
259        }
260        Ok(())
261    }
262
263    fn get_actions(
264        &self,
265        range: Range<usize>,
266    ) -> Result<Vec<(String, MRef, Vec<(String, Value)>)>, SessionError> {
267        let mut res = Vec::new();
268        for action in self.read().unwrap().actions[range].iter() {
269            let action = action.read().unwrap();
270            res.push((
271                action.name.clone(),
272                action.owner.clone(),
273                action.input.clone(),
274            ));
275        }
276
277        Ok(res)
278    }
279
280    fn get_actions_len(&self) -> Result<usize, SessionError> {
281        Ok(self.read().unwrap().actions.len())
282    }
283
284    fn run_action(
285        &self,
286        owner: &ModuleId,
287        name: String,
288        data: Vec<Type>,
289    ) -> Result<(), SessionError> {
290        let mut finded = None;
291        for (i, action) in self.read().unwrap().actions.iter().enumerate() {
292            let action = action.read().unwrap();
293            if action.owner.read().unwrap().uid == *owner && action.name == name {
294                finded = Some(i);
295                break;
296            }
297        }
298
299        let info = self.get_module(owner)?.read().unwrap().info.clone();
300
301        if let Some(finded) = finded {
302            let action = self.read().unwrap().actions[finded].clone();
303            (action.read().unwrap().callback)(info, data);
304        }
305        Ok(())
306    }
307
308    fn get_modules_len(&self) -> Result<usize, SessionError> {
309        Ok(self.read().unwrap().modules.len())
310    }
311
312    fn get_modules(&self, range: Range<usize>) -> Result<Vec<MRef>, SessionError> {
313        let mut modules = Vec::new();
314
315        for module in self.read().unwrap().modules[range].iter() {
316            let info = &module.write().unwrap().info;
317            modules.push(info.clone())
318        }
319
320        Ok(modules)
321    }
322
323    fn module_get_name(&self, module_id: &ModuleId) -> Result<String, SessionError> {
324        Ok(self.get_module(module_id)?.read().unwrap().name.clone())
325    }
326
327    fn module_set_name(&self, module_id: &ModuleId, name: String) -> Result<(), SessionError> {
328        self.get_module(module_id)?.write().unwrap().name = name;
329        Ok(())
330    }
331
332    fn module_get_default_name(&self, module_id: &ModuleId) -> Result<String, SessionError> {
333        let module = self.get_module(module_id)?;
334        let name = module.read().unwrap().module.get_name();
335        Ok(name)
336    }
337
338    fn module_get_desc(&self, module_id: &ModuleId) -> Result<String, SessionError> {
339        Ok(self.get_module(module_id)?.read().unwrap().desc.clone())
340    }
341
342    fn module_set_desc(&self, module_id: &ModuleId, desc: String) -> Result<(), SessionError> {
343        self.get_module(module_id)?.write().unwrap().desc = desc;
344        Ok(())
345    }
346
347    fn module_get_default_desc(&self, module_id: &ModuleId) -> Result<String, SessionError> {
348        let module = self.get_module(module_id)?;
349        let desc = module.read().unwrap().module.get_desc();
350        Ok(desc)
351    }
352
353    fn module_get_proxy(&self, module_id: &ModuleId) -> Result<usize, SessionError> {
354        Ok(self.get_module(module_id)?.read().unwrap().proxy)
355    }
356
357    fn module_set_proxy(&self, module_id: &ModuleId, proxy: usize) -> Result<(), SessionError> {
358        self.get_module(module_id)?.write().unwrap().proxy = proxy;
359        Err(SessionError::InvalidModule)
360    }
361
362    fn module_get_settings(&self, module_info: &ModuleId) -> Result<Data, SessionError> {
363        Ok(self
364            .get_module(module_info)?
365            .read()
366            .unwrap()
367            .settings
368            .clone())
369    }
370
371    fn module_set_settings(&self, module_info: &ModuleId, data: Data) -> Result<(), SessionError> {
372        self.get_module(module_info)?.write().unwrap().settings = data;
373        Ok(())
374    }
375
376    fn module_get_element_settings(&self, module_info: &ModuleId) -> Result<Data, SessionError> {
377        Ok(self
378            .get_module(module_info)?
379            .read()
380            .unwrap()
381            .element_data
382            .clone())
383    }
384
385    fn module_set_element_settings(
386        &self,
387        module_info: &ModuleId,
388        data: Data,
389    ) -> Result<(), SessionError> {
390        self.get_module(module_info)?.write().unwrap().element_data = data;
391        Ok(())
392    }
393
394    fn module_init_location(
395        &self,
396        module_info: &ModuleId,
397        location_info: &LocationId,
398        data: crate::data::FileOrData,
399    ) -> Result<(), SessionError> {
400        let location_info = self
401            .get_location(location_info)?
402            .read()
403            .unwrap()
404            .info
405            .clone();
406        self.get_module(module_info)?
407            .read()
408            .unwrap()
409            .module
410            .init_location(location_info, data);
411        Ok(())
412    }
413
414    fn module_init_element(
415        &self,
416        module_info: &ModuleId,
417        element_info: &ElementId,
418    ) -> Result<(), SessionError> {
419        let module = self.get_module(module_info)?;
420        let module = module.read().unwrap();
421        let element = self.get_element(element_info)?;
422
423        {
424            let mut element = element.write().unwrap();
425            element.element_data = module.element_data.clone();
426            element.module_data = module.settings.clone();
427        }
428        module.module.init_element(element);
429
430        Ok(())
431    }
432
433    fn module_accept_url(&self, module_info: &ModuleId, url: String) -> Result<bool, SessionError> {
434        Ok(self
435            .get_module(module_info)?
436            .read()
437            .unwrap()
438            .module
439            .accept_url(url))
440    }
441
442    fn module_accept_extension(
443        &self,
444        module_info: &ModuleId,
445        filename: &str,
446    ) -> Result<bool, SessionError> {
447        Ok(self
448            .get_module(module_info)?
449            .read()
450            .unwrap()
451            .module
452            .accept_extension(filename))
453    }
454
455    fn module_accepted_protocols(&self, module_id: &ModuleId) -> Result<Vec<String>, SessionError> {
456        Ok(self
457            .get_module(module_id)?
458            .read()
459            .unwrap()
460            .module
461            .accepted_protocols())
462    }
463
464    fn module_step_element(
465        &self,
466        module_info: &ModuleId,
467        element_info: &ElementId,
468        control_flow: ControlFlow,
469        storage: Storage,
470    ) -> Result<(ControlFlow, Storage), SessionError> {
471        let module;
472        {
473            let m = self.get_module(module_info)?;
474            module = m.read().unwrap().module.c();
475        }
476
477        let element = self.get_element(element_info)?;
478
479        let mut control_flow = control_flow;
480        let mut storage = storage;
481
482        module.step_element(element, &mut control_flow, &mut storage);
483        Ok((control_flow, storage))
484    }
485
486    fn module_step_location(
487        &self,
488        module_info: &ModuleId,
489        location_info: &LocationId,
490        control_flow: ControlFlow,
491        storage: Storage,
492    ) -> Result<(ControlFlow, Storage), SessionError> {
493        let module;
494        {
495            let m = self.get_module(module_info)?;
496            module = m.read().unwrap().module.c();
497        }
498
499        let location = self.get_location(location_info)?;
500
501        let mut control_flow = control_flow;
502        let mut storage = storage;
503
504        module.step_location(location, &mut control_flow, &mut storage);
505        Ok((control_flow, storage))
506    }
507
508    fn create_element(&self, name: &str, location: &LocationId) -> Result<ERef, SessionError> {
509        let element_uid = self.get_location(location)?.read().unwrap().elements.len();
510        let element_info = Arc::new(RwLock::new(RefElement {
511            session: Some(self.c()),
512            id: ElementId {
513                location_id: location.clone(),
514                uid: element_uid as u64,
515            },
516        }));
517
518        let path = self.get_location(location)?.read().unwrap().path.join(name);
519
520        let element = Arc::new(RwLock::new(Element {
521            name: name.to_owned(),
522            desc: String::new(),
523            meta: String::new(),
524            url: None,
525            element_data: Data::new(),
526            module_data: Data::new(),
527            module: None,
528            statuses: Vec::new(),
529            status: usize::MAX,
530            data: FileOrData::File(path, None),
531            progress: 0.0,
532            should_save: false,
533            enabled: false,
534            thread: None,
535            info: element_info.clone(),
536            events: Arc::new(RwLock::new(Events::default())),
537        }));
538
539        self.get_location(location)?
540            .write()
541            .unwrap()
542            .elements
543            .push(element);
544
545        let _ = self.notify_all(SessionEvent::NewElement(
546            element_info.read().unwrap().id.clone(),
547        ));
548
549        Ok(element_info)
550    }
551
552    fn move_element(&self, element: &ElementId, location: &LocationId) -> Result<(), SessionError> {
553        let elem = self.destroy_element(element.clone())?;
554        let info = elem.read().unwrap().info.clone();
555        let new_uid = self.get_location(location)?.read().unwrap().elements.len();
556        let last = info.read().unwrap().id.clone();
557        let new = ElementId {
558            uid: new_uid as u64,
559            location_id: location.clone(),
560        };
561
562        elem.read().unwrap().info.write().unwrap().id = new.clone();
563        self.get_location(location)?
564            .write()
565            .unwrap()
566            .elements
567            .push(elem);
568
569        let _ = self.notify_all(SessionEvent::ElementIdChanged(last, new));
570        Ok(())
571    }
572
573    fn destroy_element(&self, element: ElementId) -> Result<ERow, SessionError> {
574        let _ = self.get_element_ref(&element)?;
575
576        let _ = self.notify_all(SessionEvent::DestroyedElement(element.clone()));
577
578        let element = self
579            .get_location(&element.location_id)?
580            .write()
581            .unwrap()
582            .elements
583            .remove(element.uid as usize);
584
585        let mut notifications = Vec::new();
586        for (i, element) in self
587            .get_location(&element.read().unwrap().info.read().unwrap().id.location_id)?
588            .read()
589            .unwrap()
590            .elements
591            .iter()
592            .enumerate()
593        {
594            let info = element.read().unwrap().info.clone();
595            let last = info.read().unwrap().id.clone();
596            info.write().unwrap().id.uid = i as u64;
597
598            notifications.push(SessionEvent::ElementIdChanged(
599                last,
600                ElementId {
601                    uid: i as u64,
602                    location_id: info.read().unwrap().id.location_id.clone(),
603                },
604            ));
605        }
606        for notification in notifications {
607            let _ = self.notify_all(notification);
608        }
609        Ok(element)
610    }
611
612    fn element_get_name(&self, element: &ElementId) -> Result<String, SessionError> {
613        Ok(self.get_element(element)?.read().unwrap().name.clone())
614    }
615
616    fn element_set_name(&self, element: &ElementId, name: &str) -> Result<(), SessionError> {
617        self.get_element(element)?.write().unwrap().name = name.to_owned();
618        Ok(())
619    }
620
621    fn element_get_desc(&self, element: &ElementId) -> Result<String, SessionError> {
622        Ok(self.get_element(element)?.read().unwrap().desc.clone())
623    }
624
625    fn element_set_desc(&self, element: &ElementId, desc: &str) -> Result<(), SessionError> {
626        self.get_element(element)?.write().unwrap().desc = desc.to_owned();
627        Ok(())
628    }
629
630    fn element_get_meta(&self, element: &ElementId) -> Result<String, SessionError> {
631        Ok(self.get_element(element)?.read().unwrap().meta.clone())
632    }
633
634    fn element_set_meta(&self, element: &ElementId, meta: &str) -> Result<(), SessionError> {
635        self.get_element(element)?.write().unwrap().meta = meta.to_owned();
636        Ok(())
637    }
638
639    fn element_get_url(&self, element_id: &ElementId) -> Result<Option<String>, SessionError> {
640        Ok(self.get_element(element_id)?.read().unwrap().url.clone())
641    }
642
643    fn element_set_url(
644        &self,
645        element_id: &ElementId,
646        url: Option<String>,
647    ) -> Result<(), SessionError> {
648        self.get_element(element_id)?.write().unwrap().url = url;
649        Ok(())
650    }
651
652    fn element_get_element_data(&self, element: &ElementId) -> Result<Data, SessionError> {
653        Ok(self
654            .get_element(element)?
655            .read()
656            .unwrap()
657            .element_data
658            .clone())
659    }
660
661    fn element_set_element_data(
662        &self,
663        element: &ElementId,
664        data: Data,
665    ) -> Result<(), SessionError> {
666        self.get_element(element)?.write().unwrap().element_data = data;
667        Ok(())
668    }
669
670    fn element_get_module_data(&self, element: &ElementId) -> Result<Data, SessionError> {
671        Ok(self
672            .get_element(element)?
673            .read()
674            .unwrap()
675            .module_data
676            .clone())
677    }
678
679    fn element_set_module_data(&self, element: &ElementId, data: Data) -> Result<(), SessionError> {
680        self.get_element(element)?.write().unwrap().module_data = data;
681        Ok(())
682    }
683
684    fn element_get_module(&self, element: &ElementId) -> Result<Option<MRef>, SessionError> {
685        if let Some(module) = &self.get_element(element)?.read().unwrap().module {
686            Ok(Some(module.clone()))
687        } else {
688            Ok(None)
689        }
690    }
691
692    fn element_set_module(
693        &self,
694        element_id: &ElementId,
695        module: Option<ModuleId>,
696    ) -> Result<(), SessionError> {
697        self.get_element(element_id)?.write().unwrap().module = match &module {
698            Some(module_id) => Some(self.get_module_ref(module_id)?),
699            None => None,
700        };
701        Ok(())
702    }
703
704    fn element_get_statuses(&self, element: &ElementId) -> Result<Vec<String>, SessionError> {
705        Ok(self.get_element(element)?.read().unwrap().statuses.clone())
706    }
707
708    fn element_set_statuses(
709        &self,
710        element: &ElementId,
711        statuses: Vec<String>,
712    ) -> Result<(), SessionError> {
713        self.get_element(element)?.write().unwrap().statuses = statuses;
714        Ok(())
715    }
716
717    fn element_get_status(&self, element: &ElementId) -> Result<usize, SessionError> {
718        Ok(self.get_element(element)?.read().unwrap().status)
719    }
720
721    fn element_set_status(&self, element: &ElementId, status: usize) -> Result<(), SessionError> {
722        let statuses = self.get_element(element)?.read().unwrap().statuses.len();
723        if status < statuses {
724            self.get_element(element)?.write().unwrap().status = status;
725            Ok(())
726        } else {
727            Err(SessionError::InvalidElementStatus)
728        }
729    }
730
731    fn element_get_data(&self, element: &ElementId) -> Result<FileOrData, SessionError> {
732        Ok(self.get_element(element)?.read().unwrap().data.clone())
733    }
734
735    fn element_set_data(&self, element: &ElementId, data: FileOrData) -> Result<(), SessionError> {
736        self.get_element(element)?.write().unwrap().data = data;
737        Ok(())
738    }
739
740    fn element_get_progress(&self, element: &ElementId) -> Result<f32, SessionError> {
741        Ok(self.get_element(element)?.read().unwrap().progress)
742    }
743
744    fn element_set_progress(&self, element: &ElementId, progress: f32) -> Result<(), SessionError> {
745        self.get_element(element)?.write().unwrap().progress = progress;
746        Ok(())
747    }
748
749    fn element_get_should_save(&self, element: &ElementId) -> Result<bool, SessionError> {
750        Ok(self.get_element(element)?.read().unwrap().should_save)
751    }
752
753    fn element_set_should_save(
754        &self,
755        element: &ElementId,
756        should_save: bool,
757    ) -> Result<(), SessionError> {
758        self.get_element(element)?.write().unwrap().should_save = should_save;
759        Ok(())
760    }
761
762    fn element_get_enabled(&self, element: &ElementId) -> Result<bool, SessionError> {
763        Ok(self.get_element(element)?.read().unwrap().enabled)
764    }
765
766    fn element_set_enabled(
767        &self,
768        element: &ElementId,
769        enabled: bool,
770        storage: Option<Storage>,
771    ) -> Result<(), SessionError> {
772        let element = self.get_element(element)?;
773        element.write().unwrap().enabled = enabled;
774        if !enabled {
775            return Ok(());
776        }
777
778        let tmp_element = element.clone();
779        element.write().unwrap().thread = Some(std::thread::spawn(move || {
780            let element = tmp_element.clone();
781            let element_info = element.read().unwrap().info.clone();
782            let mut control_flow = ControlFlow::Run;
783            let mut storage = if let Some(storage) = storage {
784                storage
785            } else {
786                Storage::default()
787            };
788
789            loop {
790                if let ControlFlow::Break = control_flow {
791                    break;
792                }
793                let enabled = element.read().unwrap().enabled;
794                if enabled {
795                    let module;
796                    let has_module = element.read().unwrap().module.is_some();
797                    if has_module {
798                        if let Some(m) = &element.read().unwrap().module {
799                            module = Some(m.clone());
800                        } else {
801                            panic!("Is inposibile!")
802                        }
803                    } else {
804                        std::thread::sleep(std::time::Duration::from_secs(1));
805                        continue;
806                    }
807                    if let Some(module) = module {
808                        (control_flow, storage) = module
809                            .step_element(
810                                &element_info.read().unwrap().id.clone(),
811                                control_flow,
812                                storage,
813                            )
814                            .unwrap();
815                    }
816                } else {
817                    break;
818                }
819            }
820
821            element.write().unwrap().enabled = false;
822        }));
823
824        Ok(())
825    }
826
827    fn element_resolv_module(&self, element_info: &ElementId) -> Result<bool, SessionError> {
828        let len = self.get_modules_len()?;
829
830        let mut module = None;
831
832        if let Some(url) = self.get_element(element_info)?.read().unwrap().url.clone() {
833            for tmp_module in self.get_modules(0..len)? {
834                if self
835                    .get_module(&tmp_module.read().unwrap().uid)?
836                    .read()
837                    .unwrap()
838                    .module
839                    .accept_url(url.clone())
840                {
841                    module = Some(tmp_module);
842                    break;
843                }
844            }
845        }
846
847        if let Some(module) = module {
848            self.element_set_module(element_info, Some(module.id()))?;
849            return Ok(true);
850        }
851
852        Ok(false)
853    }
854
855    fn element_wait(&self, element: &ElementId) -> Result<(), SessionError> {
856        let thread = self.get_element(element)?.write().unwrap().thread.take();
857        if let Some(thread) = thread {
858            thread.join().unwrap();
859        }
860        Ok(())
861    }
862
863    fn element_get_element_info(&self, element: &ElementId) -> Result<ElementInfo, SessionError> {
864        let element = self.get_element(element)?;
865        let mut module = None;
866        {
867            let __module;
868            {
869                __module = element.read().unwrap().module.clone();
870            }
871
872            if let Some(__module) = __module {
873                let __module = self.get_module(&__module.read().unwrap().uid)?;
874                let __module = __module.read().unwrap();
875
876                let mut hasher = DefaultHasher::new();
877                let hasher = &mut hasher;
878                __module.name.hash(hasher);
879                __module.desc.hash(hasher);
880                let id = hasher.finish();
881
882                module = Some(ModuleInfo {
883                    name: __module.name.clone(),
884                    desc: __module.desc.clone(),
885                    module: id,
886                    proxy: __module.proxy,
887                    settings: __module.settings.clone(),
888                    element_data: __module.element_data.clone(),
889                    id: __module.info.id(),
890                });
891            }
892        }
893        let element = element.read().unwrap();
894        Ok(ElementInfo {
895            name: element.name.clone(),
896            desc: element.desc.clone(),
897            meta: element.meta.clone(),
898            element_data: element.element_data.clone(),
899            module_data: element.module_data.clone(),
900            module,
901            statuses: element.statuses.clone(),
902            status: element.status,
903            data: element.data.clone(),
904            progress: element.progress,
905            should_save: element.should_save,
906            enabled: element.enabled,
907            id: element.info.id(),
908        })
909    }
910
911    fn element_notify(&self, element_info: &ElementId, event: Event) -> Result<(), SessionError> {
912        let element = self.get_element(element_info)?;
913        let module;
914        {
915            let Some(__module) = &element.read().unwrap().module else{
916            return Err(SessionError::InvalidModule)
917        };
918
919            module = __module.clone();
920        }
921
922        let raw_module;
923        {
924            let __module = self.get_module(&module.read().unwrap().uid)?;
925            raw_module = __module.read().unwrap().module.c();
926        }
927
928        let element_ref = self.get_element_ref(element_info)?;
929        raw_module.notify(Ref::Element(element_ref), event);
930
931        Ok(())
932    }
933
934    fn element_emit(&self, element_info: &ElementId, event: Event) -> Result<(), SessionError> {
935        let element = self.get_element(element_info)?;
936        let events;
937        {
938            events = element.read().unwrap().events.clone()
939        }
940
941        let mut event = event;
942        match &mut event {
943            Event::Element(info, _) => *info = element_info.clone(),
944            Event::Location(_, _) => return Err(SessionError::IsNotLocation),
945            Event::Log(r, _) => *r = ID::Element(element_info.clone()),
946            Event::SessionEvent(_) => return Ok(()),
947        }
948
949        events.write().unwrap().new_event(event, self.c());
950
951        Ok(())
952    }
953
954    fn element_subscribe(&self, element_info: &ElementId, _ref: ID) -> Result<(), SessionError> {
955        // validate if element is valid
956        {
957            let _ = self.get_element(element_info)?;
958        }
959
960        let events = match _ref {
961            ID::Element(e_info) => {
962                let e = self.get_element(&e_info)?;
963                let d = e.read().unwrap().events.clone();
964                d
965            }
966            ID::Location(l_info) => {
967                let l = self.get_location(&l_info)?;
968                let d = l.read().unwrap().events.clone();
969                d
970            }
971        };
972
973        if !events
974            .write()
975            .unwrap()
976            .subscribe(ID::Element(element_info.clone()))
977        {
978            return Err(SessionError::AlreadySubscribed);
979        }
980
981        Ok(())
982    }
983
984    fn element_unsubscribe(&self, element_info: &ElementId, _ref: ID) -> Result<(), SessionError> {
985        // validate if element is valid
986        {
987            let _ = self.get_element(element_info)?;
988        }
989
990        let events = match _ref {
991            ID::Element(e_info) => {
992                let e = self.get_element(&e_info)?;
993                let d = e.read().unwrap().events.clone();
994                d
995            }
996            ID::Location(l_info) => {
997                let l = self.get_location(&l_info)?;
998                let d = l.read().unwrap().events.clone();
999                d
1000            }
1001        };
1002
1003        if !events
1004            .write()
1005            .unwrap()
1006            .unsubscribe(ID::Element(element_info.clone()))
1007        {
1008            return Err(SessionError::AlreadyUnsubscribed);
1009        }
1010
1011        Ok(())
1012    }
1013
1014    fn create_location(&self, name: &str, location: &LocationId) -> Result<LRef, SessionError> {
1015        let mut location_uid = location.clone();
1016        location_uid.push(self.get_locations_len(location)? as u64);
1017        let location_info = Arc::new(RwLock::new(RefLocation {
1018            session: Some(self.c()),
1019            id: location_uid,
1020        }));
1021
1022        let path = self.get_location(location)?.read().unwrap().path.join(name);
1023
1024        let loc = Location {
1025            name: name.to_owned(),
1026            desc: String::new(),
1027            where_is: WhereIsLocation::Local(LocalLocation {
1028                path: PathBuf::from("."),
1029            }),
1030            shoud_save: false,
1031            elements: Vec::new(),
1032            locations: Vec::new(),
1033            info: location_info.clone(),
1034            module: None,
1035            path,
1036            thread: None,
1037            events: Arc::new(RwLock::new(Events::default())),
1038        };
1039
1040        let dest = self.get_location(location)?;
1041        dest.write()
1042            .unwrap()
1043            .locations
1044            .push(Arc::new(RwLock::new(loc)));
1045
1046        let _ = self.notify_all(SessionEvent::NewLocation(
1047            location_info.read().unwrap().id.clone(),
1048        ));
1049
1050        Ok(location_info)
1051    }
1052
1053    fn get_locations_len(&self, location: &LocationId) -> Result<usize, SessionError> {
1054        Ok(self.get_location(location)?.read().unwrap().locations.len())
1055    }
1056
1057    fn get_locations(
1058        &self,
1059        location: &LocationId,
1060        range: Range<usize>,
1061    ) -> Result<Vec<LRef>, SessionError> {
1062        let mut location_infos = Vec::new();
1063        let location = self.get_location(location)?;
1064        for loc in location.read().unwrap().locations[range].iter() {
1065            location_infos.push(loc.read().unwrap().info.clone());
1066        }
1067        Ok(location_infos)
1068    }
1069
1070    fn destroy_location(&self, location: LocationId) -> Result<LRow, SessionError> {
1071        let _ = self.get_location_ref(&location)?;
1072        let _ = self.notify_all(SessionEvent::DestroyedLocation(location.clone()));
1073
1074        let mut location_uid = location;
1075        if let Some(location_index) = location_uid.pop() {
1076            let parent_location = self.get_location(&location_uid)?;
1077
1078            let removed_location = parent_location
1079                .write()
1080                .unwrap()
1081                .locations
1082                .remove(location_index as usize);
1083
1084            let mut notifications = Vec::new();
1085            for (i, location) in parent_location.read().unwrap().locations.iter().enumerate() {
1086                let info = location.read().unwrap().info.clone();
1087                let last = info.id();
1088                let mut new = last.clone();
1089                *new.last_mut().unwrap() = i as u64;
1090
1091                info.write().unwrap().id = new.clone();
1092
1093                notifications.push(SessionEvent::LocationIdChanged(last, new));
1094            }
1095
1096            for notification in notifications {
1097                let _ = self.notify_all(notification);
1098            }
1099
1100            return Ok(removed_location);
1101        }
1102        Err(SessionError::InvalidLocation)
1103    }
1104
1105    fn get_default_location(&self) -> Result<LRef, SessionError> {
1106        if let Some(location) = &self.read().unwrap().location {
1107            return Ok(location.read().unwrap().info.clone());
1108        }
1109        Err(SessionError::InvalidLocation)
1110    }
1111
1112    fn move_location(&self, location: &LocationId, to: &LocationId) -> Result<(), SessionError> {
1113        let location = self.destroy_location(location.clone())?;
1114        let mut new = to.clone();
1115        new.push(self.get_locations_len(to)? as u64);
1116        let info = location.read().unwrap().info.clone();
1117        let last = info.read().unwrap().id.clone();
1118        location.write().unwrap().info.write().unwrap().id = new.clone();
1119        self.get_location(to)?
1120            .write()
1121            .unwrap()
1122            .locations
1123            .push(location);
1124
1125        let _ = self.notify_all(SessionEvent::LocationIdChanged(last, new));
1126
1127        Ok(())
1128    }
1129
1130    fn location_get_name(&self, location: &LocationId) -> Result<String, SessionError> {
1131        Ok(self.get_location(location)?.read().unwrap().name.clone())
1132    }
1133
1134    fn location_set_name(&self, location: &LocationId, name: &str) -> Result<(), SessionError> {
1135        self.get_location(location)?.write().unwrap().name = name.to_owned();
1136        Ok(())
1137    }
1138
1139    fn location_get_desc(&self, location: &LocationId) -> Result<String, SessionError> {
1140        Ok(self.get_location(location)?.read().unwrap().desc.clone())
1141    }
1142
1143    fn location_set_desc(&self, location: &LocationId, desc: &str) -> Result<(), SessionError> {
1144        self.get_location(location)?.write().unwrap().desc = desc.to_owned();
1145        Ok(())
1146    }
1147
1148    fn location_get_path(&self, location: &LocationId) -> Result<PathBuf, SessionError> {
1149        Ok(self.get_location(location)?.read().unwrap().path.clone())
1150    }
1151
1152    fn location_set_path(&self, location: &LocationId, path: PathBuf) -> Result<(), SessionError> {
1153        self.get_location(location)?.write().unwrap().path = path;
1154        Ok(())
1155    }
1156
1157    fn location_get_where_is(
1158        &self,
1159        location: &LocationId,
1160    ) -> Result<WhereIsLocation, SessionError> {
1161        Ok(self
1162            .get_location(location)?
1163            .read()
1164            .unwrap()
1165            .where_is
1166            .clone())
1167    }
1168
1169    fn location_set_where_is(
1170        &self,
1171        location: &LocationId,
1172        where_is: WhereIsLocation,
1173    ) -> Result<(), SessionError> {
1174        self.get_location(location)?.write().unwrap().where_is = where_is;
1175        Ok(())
1176    }
1177
1178    fn location_get_should_save(&self, location: &LocationId) -> Result<bool, SessionError> {
1179        Ok(self.get_location(location)?.read().unwrap().shoud_save)
1180    }
1181
1182    fn location_set_should_save(
1183        &self,
1184        location: &LocationId,
1185        should_save: bool,
1186    ) -> Result<(), SessionError> {
1187        self.get_location(location)?.write().unwrap().shoud_save = should_save;
1188        Ok(())
1189    }
1190
1191    fn location_get_elements_len(&self, location: &LocationId) -> Result<usize, SessionError> {
1192        Ok(self.get_location(location)?.read().unwrap().elements.len())
1193    }
1194
1195    fn location_get_elements(
1196        &self,
1197        location: &LocationId,
1198        range: Range<usize>,
1199    ) -> Result<Vec<ERef>, SessionError> {
1200        let mut element_infos = Vec::new();
1201        for element in self.get_location(location)?.read().unwrap().elements[range].iter() {
1202            element_infos.push(element.read().unwrap().info.clone())
1203        }
1204        Ok(element_infos)
1205    }
1206
1207    fn location_get_location_info(
1208        &self,
1209        location: &LocationId,
1210    ) -> Result<LocationInfo, SessionError> {
1211        let mut module = None;
1212        {
1213            let __module;
1214            {
1215                let location = self.get_location(location)?;
1216                __module = location.read().unwrap().module.clone();
1217            }
1218
1219            if let Some(__module) = __module {
1220                let __module = self.get_module(&__module.read().unwrap().uid)?;
1221                let __module = __module.read().unwrap();
1222
1223                let mut hasher = DefaultHasher::new();
1224                let hasher = &mut hasher;
1225                __module.name.hash(hasher);
1226                __module.desc.hash(hasher);
1227                let id = hasher.finish();
1228
1229                module = Some(ModuleInfo {
1230                    name: __module.name.clone(),
1231                    desc: __module.desc.clone(),
1232                    module: id,
1233                    proxy: __module.proxy,
1234                    settings: __module.settings.clone(),
1235                    element_data: __module.element_data.clone(),
1236                    id: __module.info.id(),
1237                });
1238            }
1239        }
1240
1241        let mut elements = Vec::new();
1242        {
1243            let len = self.location_get_elements_len(location)?;
1244            let __elements = self.location_get_elements(location, 0..len)?;
1245            for element in __elements {
1246                let info = element.get_element_info()?;
1247                elements.push(info)
1248            }
1249        }
1250
1251        let mut locations = Vec::new();
1252        {
1253            let len = self.get_locations_len(location)?;
1254            let __locations = self.get_locations(location, 0..len)?;
1255            for location in __locations {
1256                let info = location.get_location_info()?;
1257                locations.push(info)
1258            }
1259        }
1260
1261        let location = self.get_location(location)?;
1262        let location = location.read().unwrap();
1263
1264        Ok(LocationInfo {
1265            name: location.name.clone(),
1266            desc: location.desc.clone(),
1267            id: location.info.id(),
1268            where_is: location.where_is.clone(),
1269            shoud_save: location.shoud_save,
1270            elements,
1271            locations,
1272            path: location.path.clone(),
1273            module,
1274        })
1275    }
1276
1277    fn location_notify(
1278        &self,
1279        location_info: &LocationId,
1280        event: Event,
1281    ) -> Result<(), SessionError> {
1282        let location = self.get_location(location_info)?;
1283        let module;
1284        {
1285            let Some(__module) = &location.read().unwrap().module else{
1286            return Err(SessionError::InvalidModule)
1287        };
1288
1289            module = __module.clone();
1290        }
1291
1292        let raw_module;
1293        {
1294            let __module = self.get_module(&module.read().unwrap().uid)?;
1295            raw_module = __module.read().unwrap().module.c();
1296        }
1297
1298        let location_ref = self.get_location_ref(location_info)?;
1299        raw_module.notify(Ref::Location(location_ref), event);
1300
1301        Ok(())
1302    }
1303
1304    fn location_emit(&self, location_info: &LocationId, event: Event) -> Result<(), SessionError> {
1305        let location = self.get_location(location_info)?;
1306        let events;
1307        {
1308            events = location.read().unwrap().events.clone()
1309        }
1310
1311        let mut event = event;
1312        match &mut event {
1313            Event::Element(_, _) => return Err(SessionError::IsNotElement),
1314            Event::Location(info, _) => *info = location_info.clone(),
1315            Event::Log(r, _) => *r = ID::Location(location_info.clone()),
1316            Event::SessionEvent(_) => return Ok(()),
1317        }
1318
1319        events.write().unwrap().new_event(event, self.c());
1320
1321        Ok(())
1322    }
1323
1324    fn location_subscribe(&self, location_info: &LocationId, _ref: ID) -> Result<(), SessionError> {
1325        // validate if element is valid
1326        {
1327            let _ = self.get_location(location_info)?;
1328        }
1329
1330        let events = match _ref {
1331            ID::Element(e_info) => {
1332                let e = self.get_element(&e_info)?;
1333                let d = e.read().unwrap().events.clone();
1334                d
1335            }
1336            ID::Location(l_info) => {
1337                let l = self.get_location(&l_info)?;
1338                let d = l.read().unwrap().events.clone();
1339                d
1340            }
1341        };
1342
1343        if !events
1344            .write()
1345            .unwrap()
1346            .subscribe(ID::Location(location_info.clone()))
1347        {
1348            return Err(SessionError::AlreadySubscribed);
1349        }
1350
1351        Ok(())
1352    }
1353
1354    fn location_unsubscribe(
1355        &self,
1356        location_info: &LocationId,
1357        _ref: ID,
1358    ) -> Result<(), SessionError> {
1359        // validate if element is valid
1360        {
1361            let _ = self.get_location(location_info)?;
1362        }
1363
1364        let events = match _ref {
1365            ID::Element(e_info) => {
1366                let e = self.get_element(&e_info)?;
1367                let d = e.read().unwrap().events.clone();
1368                d
1369            }
1370            ID::Location(l_info) => {
1371                let l = self.get_location(&l_info)?;
1372                let d = l.read().unwrap().events.clone();
1373                d
1374            }
1375        };
1376
1377        if !events
1378            .write()
1379            .unwrap()
1380            .unsubscribe(ID::Location(location_info.clone()))
1381        {
1382            return Err(SessionError::AlreadyUnsubscribed);
1383        }
1384
1385        Ok(())
1386    }
1387
1388    fn get_module_ref(&self, id: &ModuleId) -> Result<MRef, SessionError> {
1389        Ok(self.get_module(id)?.read().unwrap().info.clone())
1390    }
1391
1392    fn get_element_ref(&self, id: &ElementId) -> Result<ERef, SessionError> {
1393        Ok(self.get_element(id)?.read().unwrap().info.clone())
1394    }
1395
1396    fn get_location_ref(&self, id: &LocationId) -> Result<LRef, SessionError> {
1397        Ok(self.get_location(id)?.read().unwrap().info.clone())
1398    }
1399
1400    fn c(&self) -> Box<dyn TSession> {
1401        Box::new(self.clone())
1402    }
1403}