1use std::any::{Any, TypeId};
4use std::cell::RefCell;
5use std::collections::{HashMap, HashSet};
6use std::fmt::{self, Debug};
7use std::hash::{DefaultHasher, Hash, Hasher};
8use std::rc::Rc;
9
10use waft_foundation::{App, Handle};
11
12use crate::framework::{
13 BuildContext, InheritedModel, InheritedModelKind, InheritedWidget, IntoWidget, KeyRef, State,
14 StateData, StatefulWidget, WidgetRef,
15};
16
17#[derive(Clone)]
19pub struct SharedAppDataKey {
20 key: Rc<dyn Any>,
21 hash: u64,
22 equals: fn(&dyn Any, &dyn Any) -> bool,
23 type_name: &'static str,
24}
25
26impl SharedAppDataKey {
27 pub fn new<K: Hash + Eq + 'static>(key: K) -> SharedAppDataKey {
29 let mut hasher = DefaultHasher::new();
30 TypeId::of::<K>().hash(&mut hasher);
31 key.hash(&mut hasher);
32 SharedAppDataKey {
33 key: Rc::new(key),
34 hash: hasher.finish(),
35 equals: |a, b| a.downcast_ref::<K>() == b.downcast_ref::<K>(),
36 type_name: std::any::type_name::<K>(),
37 }
38 }
39}
40
41impl PartialEq for SharedAppDataKey {
42 fn eq(&self, other: &SharedAppDataKey) -> bool {
43 self.hash == other.hash && (self.equals)(&*self.key, &*other.key)
44 }
45}
46
47impl Eq for SharedAppDataKey {}
48
49impl Hash for SharedAppDataKey {
50 fn hash<H: Hasher>(&self, state: &mut H) {
51 self.hash.hash(state);
52 }
53}
54
55impl Debug for SharedAppDataKey {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 write!(f, "SharedAppDataKey<{}>", self.type_name)
58 }
59}
60
61#[derive(Clone)]
63struct SharedAppDataValue {
64 value: Rc<dyn Any>,
65 equals: fn(&dyn Any, &dyn Any) -> bool,
66}
67
68impl SharedAppDataValue {
69 fn new<V: PartialEq + 'static>(value: V) -> SharedAppDataValue {
70 SharedAppDataValue {
71 value: Rc::new(value),
72 equals: |a, b| a.downcast_ref::<V>() == b.downcast_ref::<V>(),
73 }
74 }
75
76 fn equals(&self, other: &SharedAppDataValue) -> bool {
77 (self.equals)(&*self.value, &*other.value)
78 }
79}
80
81type SharedAppDataMap = HashMap<SharedAppDataKey, SharedAppDataValue>;
82
83#[derive(Debug)]
113pub struct SharedAppData {
114 key: Option<KeyRef>,
115 child: WidgetRef,
117}
118
119impl SharedAppData {
120 #[cfg_attr(debug_assertions, track_caller)]
123 pub fn new<K>(child: impl IntoWidget<K>) -> SharedAppData {
124 SharedAppData {
125 key: None,
126 child: child.into_widget(),
127 }
128 }
129
130 pub fn key(mut self, key: KeyRef) -> SharedAppData {
132 self.key = Some(key);
133 self
134 }
135
136 pub fn get_value<K: Hash + Eq + 'static, V: Clone + PartialEq + 'static>(
152 app: &mut App,
153 context: BuildContext,
154 key: K,
155 init: impl FnOnce() -> V,
156 ) -> V {
157 let key = SharedAppDataKey::new(key);
158 let state = SharedAppModel::inherit_from(app, context, Some(key.clone()))
159 .map(|model| model.shared_app_data_state)
160 .expect(NO_SHARED_APP_DATA);
161 state.get_value(app, key, init)
162 }
163
164 pub fn set_value<K: Hash + Eq + 'static, V: PartialEq + 'static>(
178 app: &mut App,
179 context: BuildContext,
180 key: K,
181 value: V,
182 ) {
183 let state = context
184 .get_inherited_widget_of_exact_type::<SharedAppModel>(app)
185 .map(|model| model.shared_app_data_state)
186 .expect(NO_SHARED_APP_DATA);
187 state.set_value(app, SharedAppDataKey::new(key), value);
188 }
189}
190
191const NO_SHARED_APP_DATA: &str = "No SharedAppData widget found.\n\
192 SharedAppData.getValue / setValue require an SharedAppData widget ancestor.\n\
193 Typically, the SharedAppData widget is introduced by the WidgetsApp widget at the top of \
194 your application widget tree. It provides a key/value map of data that is shared with \
195 the entire application.";
196
197impl StatefulWidget for SharedAppData {
198 type State = SharedAppDataState;
199
200 fn key(&self) -> Option<&KeyRef> {
201 self.key.as_ref()
202 }
203
204 fn create_state(&self) -> SharedAppDataState {
205 SharedAppDataState {
206 state: StateData::new(),
207 data: Rc::default(),
208 }
209 }
210}
211
212pub struct SharedAppDataState {
214 state: StateData<SharedAppData>,
215 data: Rc<RefCell<SharedAppDataMap>>,
218}
219
220impl SharedAppDataState {
221 fn get_value<V: Clone + PartialEq + 'static>(
222 self: Handle<Self>,
223 app: &App,
224 key: SharedAppDataKey,
225 init: impl FnOnce() -> V,
226 ) -> V {
227 let data = Rc::clone(&app.get(self).data);
228 let mut data = data.borrow_mut();
229 let entry = data
230 .entry(key)
231 .or_insert_with(|| SharedAppDataValue::new(init()));
232 entry
233 .value
234 .downcast_ref::<V>()
235 .expect("the value stored under this key has this type")
236 .clone()
237 }
238
239 fn set_value<V: PartialEq + 'static>(
240 self: Handle<Self>,
241 app: &mut App,
242 key: SharedAppDataKey,
243 value: V,
244 ) {
245 let value = SharedAppDataValue::new(value);
246 let unchanged = app
247 .get(self)
248 .data
249 .borrow()
250 .get(&key)
251 .is_some_and(|current| current.equals(&value));
252 if unchanged {
253 return;
254 }
255 self.set_state(app, |state| {
256 let mut data = state.data.borrow().clone();
257 data.insert(key, value);
258 state.data = Rc::new(RefCell::new(data));
259 });
260 }
261}
262
263impl State for SharedAppDataState {
264 type Widget = SharedAppData;
265 crate::state_accessors!();
266
267 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
268 SharedAppModel {
269 shared_app_data_state: self,
270 data: Rc::clone(&app.get(self).data),
271 child: self.widget(app).child.clone(),
272 }
273 .into_widget()
274 }
275}
276
277struct SharedAppModel {
279 shared_app_data_state: Handle<SharedAppDataState>,
280 data: Rc<RefCell<SharedAppDataMap>>,
281 child: WidgetRef,
282}
283
284impl SharedAppModel {
285 fn into_widget(self) -> WidgetRef {
286 IntoWidget::<InheritedModelKind>::into_widget(self)
287 }
288}
289
290impl Debug for SharedAppModel {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 f.debug_struct("SharedAppModel")
293 .field("keys", &self.data.borrow().keys().collect::<Vec<_>>())
294 .finish_non_exhaustive()
295 }
296}
297
298impl InheritedWidget for SharedAppModel {
299 fn child(&self) -> &WidgetRef {
300 &self.child
301 }
302
303 fn update_should_notify(&self, old: &SharedAppModel) -> bool {
304 !Rc::ptr_eq(&self.data, &old.data)
305 }
306}
307
308impl InheritedModel for SharedAppModel {
309 type Aspect = SharedAppDataKey;
310
311 fn update_should_notify_dependent(
312 &self,
313 old: &SharedAppModel,
314 keys: &HashSet<SharedAppDataKey>,
315 ) -> bool {
316 let data = self.data.borrow();
317 let old_data = old.data.borrow();
318 keys.iter()
319 .any(|key| match (data.get(key), old_data.get(key)) {
320 (Some(value), Some(old_value)) => !value.equals(old_value),
321 (None, None) => false,
322 _ => true,
323 })
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use std::cell::Cell;
330 use waft_foundation::AppCell;
331
332 use super::*;
333 use crate::test_harness::Harness;
334 use crate::widgets::basic::{Builder, SizedBox};
335
336 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
337 enum Slot {
338 Count,
339 Name,
340 }
341
342 fn reader<V: Clone + PartialEq + Debug + 'static>(
344 key: Slot,
345 init: V,
346 seen: &Rc<RefCell<Vec<V>>>,
347 context: &Rc<Cell<Option<BuildContext>>>,
348 ) -> Builder {
349 let seen = Rc::clone(seen);
350 let context_slot = Rc::clone(context);
351 Builder::new(move |app, context| {
352 context_slot.set(Some(context));
353 let value = SharedAppData::get_value(app, context, key, {
354 let init = init.clone();
355 move || init
356 });
357 seen.borrow_mut().push(value);
358 SizedBox::shrink().into_widget()
359 })
360 }
361
362 #[test]
363 fn set_value_rebuilds_only_the_dependents_of_that_key() {
364 let cell = AppCell::new();
365 let mut app = cell.borrow_mut();
366 let counts: Rc<RefCell<Vec<i32>>> = Rc::default();
367 let names: Rc<RefCell<Vec<String>>> = Rc::default();
368 let count_context = Rc::new(Cell::new(None));
369 let name_context = Rc::new(Cell::new(None));
370 let harness = Harness::mount(
371 &mut app,
372 SharedAppData::new(crate::widgets::basic::Column::new().children([
373 reader(Slot::Count, 0, &counts, &count_context).into_widget(),
374 reader(Slot::Name, String::from("a"), &names, &name_context).into_widget(),
375 ]))
376 .into_widget(),
377 );
378 harness.pump(&mut app);
379 assert_eq!(*counts.borrow(), [0]);
380 assert_eq!(*names.borrow(), ["a"]);
381
382 let context = count_context.get().expect("built");
383 SharedAppData::set_value(&mut app, context, Slot::Count, 0);
384 harness.pump(&mut app);
385 assert_eq!(*counts.borrow(), [0], "an equal value rebuilds nothing");
386
387 SharedAppData::set_value(&mut app, context, Slot::Count, 1);
388 harness.pump(&mut app);
389 assert_eq!(
390 *counts.borrow(),
391 [0, 1],
392 "the dependent of the key rebuilds"
393 );
394 assert_eq!(*names.borrow(), ["a"], "the other key's dependent does not");
395
396 SharedAppData::set_value(&mut app, context, Slot::Name, String::from("b"));
397 harness.pump(&mut app);
398 assert_eq!(*counts.borrow(), [0, 1]);
399 assert_eq!(*names.borrow(), ["a", "b"]);
400 }
401
402 #[test]
403 fn get_value_initializes_once_and_shares_the_value_with_later_readers() {
404 let cell = AppCell::new();
405 let mut app = cell.borrow_mut();
406 let inits = Rc::new(Cell::new(0));
407 let seen: Rc<RefCell<Vec<i32>>> = Rc::default();
408 let probe = |seen: &Rc<RefCell<Vec<i32>>>| {
409 let seen = Rc::clone(seen);
410 let inits = Rc::clone(&inits);
411 Builder::new(move |app, context| {
412 let value = SharedAppData::get_value(app, context, "count", {
413 let inits = Rc::clone(&inits);
414 move || {
415 inits.set(inits.get() + 1);
416 7
417 }
418 });
419 seen.borrow_mut().push(value);
420 SizedBox::shrink().into_widget()
421 })
422 };
423 let harness = Harness::mount(
424 &mut app,
425 SharedAppData::new(
426 crate::widgets::basic::Column::new()
427 .children([probe(&seen).into_widget(), probe(&seen).into_widget()]),
428 )
429 .into_widget(),
430 );
431 harness.pump(&mut app);
432 assert_eq!(*seen.borrow(), [7, 7]);
433 assert_eq!(inits.get(), 1, "the second reader finds the value");
434 }
435}