Skip to main content

lgui_store/store/runtime/
engine.rs

1use std::{
2    borrow::Cow,
3    sync::{Arc, Mutex, RwLock},
4};
5
6use crate::{
7    core::UiWake,
8    resources::{Resources, WeakResources},
9};
10
11use super::super::{
12    definition::StoreDefinition,
13    subscription::{StoreNotification, StoreObserver, Subscription, SubscriptionToken},
14    StoreUnit,
15};
16use super::registry::StoreRegistry;
17
18pub struct StoreRuntime {
19    registry: Mutex<StoreRegistry>,
20    resources: StoreResources,
21    wake: RwLock<Option<UiWake>>,
22}
23
24enum StoreResources {
25    Owned(Resources),
26    Application(WeakResources),
27}
28
29impl StoreResources {
30    fn get(&self) -> Resources {
31        match self {
32            Self::Owned(resources) => resources.clone(),
33            Self::Application(resources) => resources
34                .upgrade()
35                .expect("application resources were dropped before the store runtime"),
36        }
37    }
38}
39
40impl StoreRuntime {
41    pub fn new(resources: Resources) -> Self {
42        Self {
43            registry: Mutex::new(StoreRegistry::new()),
44            resources: StoreResources::Owned(resources),
45            wake: RwLock::new(None),
46        }
47    }
48
49    pub fn for_application(resources: &Resources) -> Self {
50        Self {
51            registry: Mutex::new(StoreRegistry::new()),
52            resources: StoreResources::Application(resources.downgrade()),
53            wake: RwLock::new(None),
54        }
55    }
56
57    pub fn set_wake(&self, wake: UiWake) {
58        *self.wake.write().expect("store wake lock poisoned") = Some(wake);
59    }
60
61    pub fn clear_wake(&self) {
62        *self.wake.write().expect("store wake lock poisoned") = None;
63    }
64
65    pub fn read<T, R>(&self, read: impl FnOnce(&T) -> R) -> R
66    where
67        T: StoreUnit,
68    {
69        let mut registry = self.registry.lock().expect("store poisoned");
70        registry.ensure::<T>(&self.resources.get());
71        read(registry.get::<T>().expect("lazy store must exist"))
72    }
73
74    pub fn read_defined<T, R>(
75        &self,
76        definition: StoreDefinition<T>,
77        read: impl FnOnce(&T) -> R,
78    ) -> R
79    where
80        T: Send + Sync + 'static,
81    {
82        let mut registry = self.registry.lock().expect("store poisoned");
83        registry.ensure_defined(definition);
84        read(registry.get::<T>().expect("lazy defined store must exist"))
85    }
86
87    pub fn update<T, R>(
88        &self,
89        reason: impl Into<Cow<'static, str>>,
90        mutate: impl FnOnce(&mut T) -> R,
91    ) -> R
92    where
93        T: StoreUnit,
94    {
95        let (result, notification) = {
96            let mut registry = self.registry.lock().expect("store poisoned");
97            registry.ensure::<T>(&self.resources.get());
98            let result = mutate(registry.get_mut::<T>().expect("lazy store must exist"));
99            (
100                result,
101                StoreNotification {
102                    store_key: T::KEY,
103                    reason: reason.into(),
104                },
105            )
106        };
107        self.dispatch_notification(notification);
108        result
109    }
110
111    pub fn update_defined<T, R>(
112        &self,
113        definition: StoreDefinition<T>,
114        reason: impl Into<Cow<'static, str>>,
115        mutate: impl FnOnce(&mut T) -> R,
116    ) -> R
117    where
118        T: Send + Sync + 'static,
119    {
120        let (result, notification) = {
121            let mut registry = self.registry.lock().expect("store poisoned");
122            registry.ensure_defined(definition);
123            let result = mutate(
124                registry
125                    .get_mut::<T>()
126                    .expect("lazy defined store must exist"),
127            );
128            (
129                result,
130                StoreNotification {
131                    store_key: definition.key(),
132                    reason: reason.into(),
133                },
134            )
135        };
136        self.dispatch_notification(notification);
137        result
138    }
139
140    pub fn subscribe(
141        &self,
142        subscription: Subscription,
143        observer: Arc<dyn StoreObserver>,
144    ) -> SubscriptionToken {
145        self.registry
146            .lock()
147            .expect("store poisoned")
148            .subscribe(subscription, observer)
149    }
150
151    pub fn unsubscribe(&self, token: SubscriptionToken) -> bool {
152        self.registry
153            .lock()
154            .expect("store poisoned")
155            .unsubscribe(token)
156    }
157
158    fn dispatch_notification(&self, notification: StoreNotification) {
159        let observers = self
160            .registry
161            .lock()
162            .expect("store poisoned")
163            .observers_for(&notification);
164        for observer in observers {
165            observer.on_store_notification(&notification);
166        }
167        if let Some(wake) = self.wake.read().expect("store wake lock poisoned").as_ref() {
168            wake();
169        }
170    }
171}