1use std::any::type_name;
4use std::collections::{HashMap, VecDeque};
5use std::fmt::{self, Debug};
6use std::marker::PhantomData;
7use std::ops::Receiver;
8use std::rc::{Rc, Weak};
9use std::time::Duration;
10
11use slotmap::new_key_type;
12use waft_embedder::{
13 ClipboardEvent, DragReport, EditCommand, MenuId, NotificationActivation, OpenRequest,
14 PlatformRef, RequestId, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent, ViewId,
15};
16
17use crate::app_cell::{AppCell, AsyncApp};
18use crate::change_notifier::Listener;
19use crate::entity::EntityMap;
20use crate::executor::{ExecutorHandle, ForegroundExecutor, Task};
21use crate::handle_map::HandleMap;
22pub use crate::handle_map::{AnyRef, OptionRetained, Ref, Retained};
23use crate::timers::{Timer, Timers};
24
25const MICROTASK_BUDGET: usize = 100_000;
29
30new_key_type! {
31 pub struct HandleId;
36}
37
38pub struct Handle<T> {
60 id: HandleId,
61 state: PhantomData<fn() -> T>,
62}
63
64impl<T> Handle<T> {
65 pub(crate) fn new(id: HandleId) -> Handle<T> {
68 Handle {
69 id,
70 state: PhantomData,
71 }
72 }
73
74 pub fn from_id(id: HandleId) -> Handle<T> {
78 Handle::new(id)
79 }
80
81 pub fn id(self) -> HandleId {
82 self.id
83 }
84}
85
86impl<T: 'static> Handle<T> {
87 pub fn upgrade(self, app: &App) -> Option<Ref<T>> {
94 app.handles.upgrade(self)
95 }
96
97 #[track_caller]
105 pub fn keep(self, app: &App) -> Ref<T> {
106 Retained::keep(app, self)
107 }
108}
109
110impl HandleId {
111 pub fn upgrade(self, app: &App) -> Option<AnyRef> {
113 app.handles.upgrade_id(self)
114 }
115
116 #[track_caller]
118 pub fn keep(self, app: &App) -> AnyRef {
119 Retained::keep(app, self)
120 }
121}
122
123impl<T> Clone for Handle<T> {
124 fn clone(&self) -> Handle<T> {
125 *self
126 }
127}
128
129impl<T> Copy for Handle<T> {}
130
131impl<T> Receiver for Handle<T> {
134 type Target = T;
135}
136
137impl<T> PartialEq for Handle<T> {
138 fn eq(&self, other: &Handle<T>) -> bool {
139 self.id == other.id
140 }
141}
142
143impl<T> Eq for Handle<T> {}
144
145impl<T> std::hash::Hash for Handle<T> {
146 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
147 self.id.hash(state)
148 }
149}
150
151impl<T> Debug for Handle<T> {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 write!(f, "Handle<{}>({:?})", type_name::<T>(), self.id)
154 }
155}
156
157impl<T> From<Handle<T>> for HandleId {
158 fn from(handle: Handle<T>) -> HandleId {
159 handle.id
160 }
161}
162
163#[non_exhaustive]
169pub struct App {
170 this: Weak<AppCell>,
172 handles: HandleMap,
173 pub(crate) entities: EntityMap,
174 singletons: HashMap<std::any::TypeId, AnyRef>,
176 #[cfg(debug_assertions)]
178 skipped_tear_off_receivers: std::collections::HashSet<HandleId>,
179 #[cfg(debug_assertions)]
180 skipped_tear_offs: Vec<String>,
181 microtasks: VecDeque<Listener>,
182 timers: Timers,
183 debug_flags: HashMap<std::any::TypeId, bool>,
186 executor: ForegroundExecutor,
187 platform: PlatformRef,
188 dispatcher: std::sync::Arc<dyn waft_embedder::Dispatcher>,
190 platform_callbacks: PlatformCallbacks,
191 open_requests: UntilHandled<OpenRequest>,
192 notification_activations: UntilHandled<NotificationActivation>,
193}
194
195pub trait DebugFlag: 'static {
199 const DEFAULT: bool = false;
201}
202
203struct UntilHandled<T> {
206 handler: Option<Handler<T>>,
207 waiting: Vec<T>,
208}
209
210impl<T> Default for UntilHandled<T> {
211 fn default() -> UntilHandled<T> {
212 UntilHandled {
213 handler: None,
214 waiting: Vec::new(),
215 }
216 }
217}
218
219type Handler<T> = Rc<dyn Fn(&mut App, T)>;
221
222pub type OpenRequestedCallback = Rc<dyn Fn(&mut App, OpenRequest)>;
224
225pub type NotificationActivatedCallback = Rc<dyn Fn(&mut App, NotificationActivation)>;
227
228#[derive(Default)]
233pub struct PlatformCallbacks {
234 pub on_platform_brightness_changed: Option<Listener>,
235 pub on_locale_changed: Option<Listener>,
236 pub on_view_focus_change: Option<ViewFocusChangeCallback>,
238 pub on_drag: Option<DragCallback>,
240 pub on_clipboard_event: Option<ClipboardEventCallback>,
243 pub on_edit_command: Option<EditCommandCallback>,
246 pub on_menu_selected: Option<MenuSelectedCallback>,
249 pub on_dock_menu_selected: Option<MenuSelectedCallback>,
252 pub on_tray_icon_event: Option<TrayIconEventCallback>,
255 pub on_pop_route: Option<PopRouteCallback>,
258 pub on_view_added: Option<ViewChangeCallback>,
261 pub on_view_removed: Option<ViewChangeCallback>,
263 pub on_view_close_requested: Option<ViewCloseRequestedCallback>,
265 pub on_window_changed: Option<WindowChangedCallback>,
268 pub on_view_request_failed: Option<ViewRequestFailedCallback>,
270}
271
272pub type ViewFocusChangeCallback = Rc<dyn Fn(&mut App, ViewFocusEvent)>;
274
275pub type DragCallback = Rc<dyn Fn(&mut App, DragReport)>;
277
278pub type ClipboardEventCallback = Rc<dyn Fn(&mut App, ViewId, ClipboardEvent)>;
280
281pub type EditCommandCallback = Rc<dyn Fn(&mut App, ViewId, EditCommand)>;
283
284pub type MenuSelectedCallback = Rc<dyn Fn(&mut App, MenuId)>;
286
287pub type TrayIconEventCallback = Rc<dyn Fn(&mut App, TrayIconId, TrayIconEvent)>;
289
290pub type PopRouteCallback = Rc<dyn Fn(&mut App, ViewId) -> bool>;
292
293pub type ViewChangeCallback = Rc<dyn Fn(&mut App, ViewId)>;
295
296pub type ViewCloseRequestedCallback = Rc<dyn Fn(&mut App, ViewId)>;
298
299pub type WindowChangedCallback = Rc<dyn Fn(&mut App, ViewId)>;
301
302pub type ViewRequestFailedCallback = Rc<dyn Fn(&mut App, RequestId, ViewError)>;
304
305impl App {
306 pub(crate) fn build(
307 this: Weak<AppCell>,
308 platform: PlatformRef,
309 executor: ForegroundExecutor,
310 ) -> App {
311 App {
312 this,
313 handles: HandleMap::new(),
314 entities: EntityMap::new(),
315 singletons: HashMap::new(),
316 #[cfg(debug_assertions)]
317 skipped_tear_off_receivers: std::collections::HashSet::new(),
318 #[cfg(debug_assertions)]
319 skipped_tear_offs: Vec::new(),
320 microtasks: VecDeque::new(),
321 timers: Timers::default(),
322 debug_flags: HashMap::new(),
323 executor,
324 dispatcher: platform.dispatcher(),
325 platform,
326 platform_callbacks: PlatformCallbacks::default(),
327 open_requests: UntilHandled::default(),
328 notification_activations: UntilHandled::default(),
329 }
330 }
331
332 pub(crate) fn executor_handle(&self) -> ExecutorHandle {
334 self.executor.handle()
335 }
336
337 pub fn to_async(&self) -> AsyncApp {
339 AsyncApp::new(self.this.clone(), self.executor.handle())
340 }
341
342 pub fn spawn<R: 'static>(&self, f: impl AsyncFnOnce(&mut AsyncApp) -> R + 'static) -> Task<R> {
352 let mut cx = self.to_async();
353 self.executor.spawn(async move { f(&mut cx).await })
354 }
355
356 pub fn run_in_background<T: Send + 'static>(
361 &self,
362 work: impl FnOnce() -> T + Send + 'static,
363 ) -> Task<T> {
364 self.executor.run_in_background(work)
365 }
366
367 pub fn platform(&self) -> PlatformRef {
368 Rc::clone(&self.platform)
369 }
370
371 pub fn platform_callbacks(&self) -> &PlatformCallbacks {
373 &self.platform_callbacks
374 }
375
376 pub fn platform_callbacks_mut(&mut self) -> &mut PlatformCallbacks {
377 &mut self.platform_callbacks
378 }
379
380 pub fn set_open_requested_handler(&mut self, handler: Option<OpenRequestedCallback>) {
385 self.set_handler(|app| &mut app.open_requests, handler);
386 }
387
388 pub fn open_requested(&mut self, request: OpenRequest) {
393 self.hand_to_handler(|app| &mut app.open_requests, request);
394 }
395
396 pub fn set_notification_activated_handler(
401 &mut self,
402 handler: Option<NotificationActivatedCallback>,
403 ) {
404 self.set_handler(|app| &mut app.notification_activations, handler);
405 }
406
407 pub fn notification_activated(&mut self, activation: NotificationActivation) {
409 self.hand_to_handler(|app| &mut app.notification_activations, activation);
410 }
411
412 fn set_handler<T>(
413 &mut self,
414 queue: fn(&mut App) -> &mut UntilHandled<T>,
415 handler: Option<Handler<T>>,
416 ) {
417 queue(self).handler = handler.clone();
418 let Some(handler) = handler else {
419 return;
420 };
421 for waiting in std::mem::take(&mut queue(self).waiting) {
422 handler(self, waiting);
423 }
424 }
425
426 fn hand_to_handler<T>(&mut self, queue: fn(&mut App) -> &mut UntilHandled<T>, asked: T) {
427 match queue(self).handler.clone() {
428 Some(handler) => handler(self, asked),
429 None => queue(self).waiting.push(asked),
430 }
431 }
432
433 #[track_caller]
436 pub fn singleton<T: 'static + Default>(&mut self) -> Handle<T> {
437 if let Some(existing) = self.existing_singleton() {
438 return existing;
439 }
440 let singleton = self.create(T::default());
441 let handle = singleton.handle();
442 self.singletons
443 .insert(std::any::TypeId::of::<T>(), singleton.to_any());
444 handle
445 }
446
447 pub fn existing_singleton<T: 'static>(&self) -> Option<Handle<T>> {
450 self.singletons
451 .get(&std::any::TypeId::of::<T>())
452 .map(|singleton| Handle::new(singleton.handle()))
453 }
454
455 pub fn schedule_microtask(&mut self, callback: Listener) {
463 self.microtasks.push_back(callback);
464 }
465
466 pub fn drain_microtasks(&mut self) {
476 let mut drained = 0usize;
477 while let Some(callback) = self.microtasks.pop_front() {
478 drained += 1;
479 assert!(
480 drained <= MICROTASK_BUDGET,
481 "microtasks did not converge after {MICROTASK_BUDGET} callbacks; \
482 are two callbacks scheduling each other in a cycle?"
483 );
484 callback.call(self);
485 }
486 }
487
488 pub fn has_pending_microtasks(&self) -> bool {
494 !self.microtasks.is_empty()
495 }
496
497 pub fn schedule_timer(&mut self, duration: Duration, callback: Listener) -> Timer {
500 let timer = self.timers.schedule(duration, callback);
501 self.update_timer_wakeup();
502 timer
503 }
504
505 pub fn cancel_timer(&mut self, timer: Timer) {
507 self.timers.cancel(timer);
508 self.update_timer_wakeup();
510 }
511
512 pub fn timer_is_active(&self, timer: Timer) -> bool {
514 self.timers.is_active(timer)
515 }
516
517 pub fn clock(&self) -> Duration {
520 self.timers.now()
521 }
522
523 pub fn has_pending_timers(&self) -> bool {
526 self.timers.has_pending()
527 }
528
529 pub fn debug_flag<F: DebugFlag>(&self) -> bool {
533 self.debug_flags
534 .get(&std::any::TypeId::of::<F>())
535 .copied()
536 .unwrap_or(F::DEFAULT)
537 }
538
539 pub fn set_debug_flag<F: DebugFlag>(&mut self, value: bool) {
541 self.debug_flags.insert(std::any::TypeId::of::<F>(), value);
542 }
543
544 pub(crate) fn fire_next_due(&mut self, target: Duration) -> bool {
546 let Some(callback) = self.timers.pop_next_due(target) else {
547 return false;
548 };
549 callback.call(self);
550 true
551 }
552
553 pub(crate) fn advance_clock_to(&mut self, target: Duration) {
554 self.timers.advance_to(target);
555 }
556
557 pub(crate) fn update_timer_wakeup(&mut self) {
561 if let Some(delay) = self.timers.timer_wakeup_if_changed() {
562 let wakeup = delay.map(|delay| self.platform.now() + delay);
563 self.dispatcher.wake_at(wakeup);
564 }
565 }
566
567 #[track_caller]
573 pub fn create<T: 'static>(&mut self, state: T) -> Ref<T> {
574 self.handles.create(state)
575 }
576
577 pub(crate) fn adopt_tree_node(&mut self, id: HandleId, keep: Rc<crate::handle_map::Keep>) {
579 self.handles.adopt_tree_node(id, keep);
580 }
581
582 pub fn release_tree_node(&mut self, node: impl Into<HandleId>) {
591 self.handles.release_tree_node(node.into());
592 }
593
594 pub(crate) fn not_kept(&self, id: HandleId) -> String {
596 self.handles.not_kept(id)
597 }
598
599 pub fn contains(&self, handle: impl Into<HandleId>) -> bool {
601 self.handles.contains(handle.into())
602 }
603
604 pub fn mark_disposed(&mut self, handle: impl Into<HandleId>) {
609 self.handles.mark_disposed(handle.into());
610 }
611
612 pub fn tear_off_receiver_is_live(&mut self, receiver: impl Into<HandleId>) -> bool {
617 let receiver = receiver.into();
618 let live = self.handles.contains(receiver);
619 #[cfg(debug_assertions)]
620 if !live && self.skipped_tear_off_receivers.insert(receiver) {
621 let message = format!(
622 "waft: a listener whose receiver was freed without removing it was skipped: {}",
623 self.handles.debug_describe(receiver)
624 );
625 eprintln!("{message}");
626 self.skipped_tear_offs.push(message);
627 }
628 live
629 }
630
631 pub fn expect_dispose(&mut self, handle: impl Into<HandleId>) {
640 self.handles.expect_dispose(handle.into());
641 }
642
643 #[cfg(debug_assertions)]
647 pub fn debug_take_not_disposed(&mut self) -> Vec<String> {
648 self.handles.take_not_disposed()
649 }
650
651 #[cfg(debug_assertions)]
656 pub fn debug_take_not_collected(&mut self) -> Vec<String> {
657 self.handles.take_not_collected()
658 }
659
660 #[cfg(debug_assertions)]
663 pub fn debug_live_objects(&self) -> Vec<crate::DebugObject> {
664 self.handles.debug_live_objects()
665 }
666
667 #[cfg(debug_assertions)]
670 pub fn debug_take_skipped_tear_offs(&mut self) -> Vec<String> {
671 std::mem::take(&mut self.skipped_tear_offs)
672 }
673
674 pub(crate) fn begin_checkpoint(&mut self) {
676 self.handles.begin_checkpoint();
677 }
678
679 pub(crate) fn free_dropped_objects(&mut self) {
681 self.handles.free_dropped();
682 }
683
684 pub fn is_disposed(&self, handle: impl Into<HandleId>) -> bool {
690 self.handles.is_disposed(handle.into())
691 }
692
693 pub fn handle<T: 'static>(&self, handle: impl Into<HandleId>) -> Option<Handle<T>> {
695 self.handles.handle(handle.into())
696 }
697
698 pub fn get<T: 'static>(&self, handle: impl ToHandle<T>) -> &T {
703 self.handles.get(handle.to_handle())
704 }
705
706 pub fn get_mut<T: 'static>(&mut self, handle: impl ToHandle<T>) -> &mut T {
708 self.handles.get_mut(handle.to_handle())
709 }
710
711 pub fn get_disjoint_mut<A: 'static, B: 'static>(
718 &mut self,
719 a: impl ToHandle<A>,
720 b: impl ToHandle<B>,
721 ) -> (&mut A, &mut B) {
722 self.handles.get_disjoint_mut(a.to_handle(), b.to_handle())
723 }
724}
725
726pub trait ToHandle<T> {
729 fn to_handle(self) -> Handle<T>;
731}
732
733impl<T> ToHandle<T> for Handle<T> {
734 fn to_handle(self) -> Handle<T> {
735 self
736 }
737}
738
739impl<T> ToHandle<T> for &Handle<T> {
740 fn to_handle(self) -> Handle<T> {
741 *self
742 }
743}
744
745impl<T> ToHandle<T> for &Ref<T> {
746 fn to_handle(self) -> Handle<T> {
747 self.handle()
748 }
749}
750
751#[cfg(test)]
752mod tests {
753 use super::*;
754 use crate::Timer;
755
756 #[derive(Debug, Default, PartialEq)]
757 struct Counter(i32);
758
759 #[derive(Debug, PartialEq)]
760 struct Label(&'static str);
761
762 #[test]
763 fn state_survives_a_round_trip_through_a_handle() {
764 let cell = AppCell::new();
765 let mut app = cell.borrow_mut();
766 let counter_ref = app.create(Counter(1));
767 let counter = counter_ref.handle();
768
769 assert_eq!(app.get(counter), &Counter(1));
770 app.get_mut(counter).0 = 7;
771 assert_eq!(app.get(counter), &Counter(7));
772 }
773
774 #[test]
775 fn handles_of_different_types_share_one_arena() {
776 let cell = AppCell::new();
777 let mut app = cell.borrow_mut();
778 let counter_ref = app.create(Counter(1));
779 let counter = counter_ref.handle();
780 let label_ref = app.create(Label("hello"));
781 let label = label_ref.handle();
782
783 assert_eq!(app.get(counter), &Counter(1));
784 assert_eq!(app.get(label), &Label("hello"));
785 }
786
787 #[test]
788 fn a_freed_entry_is_reused_but_its_handle_is_not() {
789 let cell = AppCell::new();
790 let first_id = cell.borrow_mut().create(Counter(1)).id();
791 cell.checkpoint();
792
793 let mut app = cell.borrow_mut();
794 let second_ref = app.create(Counter(2));
795 let second = second_ref.handle();
796 let entry_index = |id: HandleId| slotmap::Key::data(&id).as_ffi() & 0xffff_ffff;
798 assert_eq!(
799 entry_index(second.id()),
800 entry_index(first_id),
801 "the freed entry is reused, so the version is what tells them apart"
802 );
803 assert_ne!(second.id(), first_id);
804 assert!(!app.contains(first_id));
805 assert!(app.contains(second));
806 }
807
808 #[test]
809 #[cfg(debug_assertions)]
810 fn a_dropped_ref_keeps_the_object_readable_until_the_checkpoint() {
811 let cell = AppCell::new();
812 let counter_ref = cell.borrow_mut().create(Counter(3));
813 let counter = counter_ref.handle();
814
815 drop(counter_ref);
816 {
817 let app = cell.borrow();
818 assert_eq!(app.get(counter), &Counter(3), "still readable");
819 assert!(app.contains(counter), "still in the arena");
820 }
821 cell.checkpoint();
822 assert!(!cell.borrow().contains(counter), "freed at the checkpoint");
823 }
824
825 #[test]
826 #[should_panic(expected = "stale handle")]
827 fn reading_through_a_stale_handle_panics() {
828 let cell = AppCell::new();
829 let counter = cell.borrow_mut().create(Counter(1)).handle();
830 cell.checkpoint();
831 cell.borrow().get(counter);
832 }
833
834 #[test]
835 fn the_checked_path_from_an_untyped_id_answers_none_rather_than_panicking() {
836 let cell = AppCell::new();
837 let counter_ref = cell.borrow_mut().create(Counter(1));
838 let counter = counter_ref.handle();
839 let id = counter.id();
840
841 assert_eq!(cell.borrow().handle::<Counter>(id), Some(counter));
842 assert_eq!(cell.borrow().handle::<Label>(id), None, "wrong type");
843
844 drop(counter_ref);
845 cell.checkpoint();
846 assert_eq!(cell.borrow().handle::<Counter>(id), None, "stale");
847 }
848
849 #[test]
850 fn a_singleton_is_one_handle_per_type_per_app() {
851 let cell = AppCell::new();
852 let mut app = cell.borrow_mut();
853
854 let first: Handle<Counter> = app.singleton();
855 let second: Handle<Counter> = app.singleton();
856 assert_eq!(first, second);
857
858 app.get_mut(first).0 = 9;
859 assert_eq!(app.get(second).0, 9, "one entry behind both handles");
860
861 let other_cell = AppCell::new();
862 let mut other_app = other_cell.borrow_mut();
863 let elsewhere: Handle<Counter> = other_app.singleton();
864 assert_eq!(elsewhere.id(), first.id(), "ids may collide across Apps");
865 assert_eq!(other_app.get(elsewhere).0, 0, "but the state is per App");
866 }
867
868 #[test]
869 fn a_handle_is_copy_so_an_edge_can_be_a_plain_field() {
870 let cell = AppCell::new();
871 let mut app = cell.borrow_mut();
872 let counter_ref = app.create(Counter(1));
873 let counter = counter_ref.handle();
874
875 struct Edge {
876 target: Handle<Counter>,
877 }
878 let edge = Edge { target: counter };
879 let copied = edge.target;
880
881 assert_eq!(copied, counter);
882 assert_eq!(app.get(edge.target).0, 1);
883 }
884
885 #[test]
886 fn a_microtask_runs_on_drain_not_inline() {
887 let cell = AppCell::new();
888 let mut app = cell.borrow_mut();
889 let counter_ref = app.create(Counter(0));
890 let counter = counter_ref.handle();
891 app.schedule_microtask(crate::Listener::new(move |app| {
892 app.get_mut(counter).0 = 1;
893 }));
894 assert_eq!(app.get(counter).0, 0);
895 assert!(app.has_pending_microtasks());
896 app.drain_microtasks();
897 assert_eq!(app.get(counter).0, 1);
898 assert!(!app.has_pending_microtasks());
899 }
900
901 #[test]
902 fn a_microtask_scheduled_during_drain_runs_in_the_same_drain() {
903 let cell = AppCell::new();
904 let mut app = cell.borrow_mut();
905 let counter_ref = app.create(Counter(0));
906 let counter = counter_ref.handle();
907 app.schedule_microtask(crate::Listener::new(move |app| {
908 app.get_mut(counter).0 = 1;
909 app.schedule_microtask(crate::Listener::new(move |app| {
910 app.get_mut(counter).0 = 2;
911 }));
912 }));
913 app.drain_microtasks();
914 assert_eq!(app.get(counter).0, 2);
915 }
916
917 #[test]
918 fn timers_fire_in_due_order_after_microtasks() {
919 let cell = AppCell::new();
920 let mut app = cell.borrow_mut();
921 let log_ref = app.create(Vec::<&'static str>::new());
922 let log = log_ref.handle();
923 app.schedule_microtask(crate::Listener::new(move |app| {
924 app.get_mut(log).push("micro");
925 }));
926 Timer::new(
927 &mut app,
928 Duration::from_millis(200),
929 crate::Listener::new(move |app| {
930 app.get_mut(log).push("late");
931 }),
932 );
933 Timer::new(
934 &mut app,
935 Duration::from_millis(100),
936 crate::Listener::new(move |app| {
937 app.get_mut(log).push("early");
938 }),
939 );
940 Timer::new(
941 &mut app,
942 Duration::from_millis(100),
943 crate::Listener::new(move |app| {
944 app.get_mut(log).push("early-second");
945 }),
946 );
947 assert!(app.get(log).is_empty());
948 drop(app);
949 cell.elapse(Duration::from_millis(200));
950 let app = cell.borrow();
951 assert_eq!(
952 app.get(log).as_slice(),
953 ["micro", "early", "early-second", "late"]
954 );
955 }
956
957 #[test]
958 fn cancel_prevents_a_timer_from_firing() {
959 let cell = AppCell::new();
960 let mut app = cell.borrow_mut();
961 let counter_ref = app.create(Counter(0));
962 let counter = counter_ref.handle();
963 let timer = Timer::new(
964 &mut app,
965 Duration::from_millis(10),
966 crate::Listener::new(move |app| {
967 app.get_mut(counter).0 = 1;
968 }),
969 );
970 assert!(timer.is_active(&app));
971 timer.cancel(&mut app);
972 assert!(!timer.is_active(&app));
973 drop(app);
974 cell.elapse(Duration::from_millis(10));
975 let app = cell.borrow();
976 assert_eq!(app.get(counter).0, 0);
977 }
978 #[test]
979 fn get_disjoint_mut_borrows_two_entries_at_once() {
980 let cell = AppCell::new();
981 let mut app = cell.borrow_mut();
982 let a_ref = app.create(1u32);
983 let a = a_ref.handle();
984 let b_ref = app.create(String::from("x"));
985 let b = b_ref.handle();
986 let (a_value, b_value) = app.get_disjoint_mut(a, b);
987 *a_value += 1;
988 b_value.push('y');
989 assert_eq!(*app.get(a), 2);
990 assert_eq!(app.get(b), "xy");
991 }
992
993 #[test]
994 #[should_panic(expected = "not two live entries")]
995 fn get_disjoint_mut_rejects_the_same_entry_twice() {
996 let cell = AppCell::new();
997 let mut app = cell.borrow_mut();
998 let a_ref = app.create(1u32);
999 let a = a_ref.handle();
1000 let _ = app.get_disjoint_mut(a, a);
1001 }
1002
1003 #[test]
1004 fn from_id_reads_like_the_minted_handle() {
1005 let cell = AppCell::new();
1006 let mut app = cell.borrow_mut();
1007 let minted_ref = app.create(Counter(7));
1008 let minted = minted_ref.handle();
1009 let rebuilt = Handle::<Counter>::from_id(minted.id());
1010 assert_eq!(rebuilt, minted);
1011 assert_eq!(app.get(rebuilt).0, 7);
1012 }
1013
1014 #[test]
1015 #[should_panic(expected = "stale handle")]
1016 fn from_id_defers_the_stale_check_to_get() {
1017 let cell = AppCell::new();
1018 let id = cell.borrow_mut().create(Counter(0)).id();
1019 cell.checkpoint();
1020 let rebuilt = Handle::<Counter>::from_id(id);
1021 cell.borrow().get(rebuilt);
1022 }
1023}