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, TimerMode, 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 identity_hash(self) -> u64 {
114 slotmap::Key::data(&self).as_ffi() & 0xFFFF_FFFF
115 }
116
117 pub fn to_bits(self) -> u64 {
121 slotmap::Key::data(&self).as_ffi()
122 }
123
124 pub fn from_bits(bits: u64) -> HandleId {
127 slotmap::KeyData::from_ffi(bits).into()
128 }
129
130 pub fn upgrade(self, app: &App) -> Option<AnyRef> {
132 app.handles.upgrade_id(self)
133 }
134
135 #[track_caller]
137 pub fn keep(self, app: &App) -> AnyRef {
138 Retained::keep(app, self)
139 }
140}
141
142impl<T> Clone for Handle<T> {
143 fn clone(&self) -> Handle<T> {
144 *self
145 }
146}
147
148impl<T> Copy for Handle<T> {}
149
150impl<T> Receiver for Handle<T> {
153 type Target = T;
154}
155
156impl<T> PartialEq for Handle<T> {
157 fn eq(&self, other: &Handle<T>) -> bool {
158 self.id == other.id
159 }
160}
161
162impl<T> Eq for Handle<T> {}
163
164impl<T> std::hash::Hash for Handle<T> {
165 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
166 self.id.hash(state)
167 }
168}
169
170impl<T> Debug for Handle<T> {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(f, "Handle<{}>({:?})", type_name::<T>(), self.id)
173 }
174}
175
176impl<T> From<Handle<T>> for HandleId {
177 fn from(handle: Handle<T>) -> HandleId {
178 handle.id
179 }
180}
181
182#[non_exhaustive]
188pub struct App {
189 this: Weak<AppCell>,
191 handles: HandleMap,
192 pub(crate) entities: EntityMap,
193 singletons: HashMap<std::any::TypeId, AnyRef>,
195 #[cfg(debug_assertions)]
197 skipped_tear_off_receivers: std::collections::HashSet<HandleId>,
198 #[cfg(debug_assertions)]
199 skipped_tear_offs: Vec<String>,
200 microtasks: VecDeque<Listener>,
201 timers: Timers,
202 debug_flags: HashMap<std::any::TypeId, bool>,
205 executor: ForegroundExecutor,
206 platform: PlatformRef,
207 dispatcher: std::sync::Arc<dyn waft_embedder::Dispatcher>,
209 platform_callbacks: PlatformCallbacks,
210 open_requests: UntilHandled<OpenRequest>,
211 notification_activations: UntilHandled<NotificationActivation>,
212}
213
214pub trait DebugFlag: 'static {
218 const DEFAULT: bool = false;
220}
221
222struct UntilHandled<T> {
225 handler: Option<Handler<T>>,
226 waiting: Vec<T>,
227}
228
229impl<T> Default for UntilHandled<T> {
230 fn default() -> UntilHandled<T> {
231 UntilHandled {
232 handler: None,
233 waiting: Vec::new(),
234 }
235 }
236}
237
238type Handler<T> = Rc<dyn Fn(&mut App, T)>;
240
241pub type OpenRequestedCallback = Rc<dyn Fn(&mut App, OpenRequest)>;
243
244pub type NotificationActivatedCallback = Rc<dyn Fn(&mut App, NotificationActivation)>;
246
247#[derive(Default)]
252pub struct PlatformCallbacks {
253 pub on_platform_brightness_changed: Option<Listener>,
254 pub on_locale_changed: Option<Listener>,
255 pub on_view_focus_change: Option<ViewFocusChangeCallback>,
257 pub on_drag: Option<DragCallback>,
259 pub on_clipboard_event: Option<ClipboardEventCallback>,
262 pub on_edit_command: Option<EditCommandCallback>,
265 pub on_menu_selected: Option<MenuSelectedCallback>,
268 pub on_dock_menu_selected: Option<MenuSelectedCallback>,
271 pub on_tray_icon_event: Option<TrayIconEventCallback>,
274 pub on_pop_route: Option<PopRouteCallback>,
277 pub on_view_added: Option<ViewChangeCallback>,
280 pub on_view_removed: Option<ViewChangeCallback>,
282 pub on_view_close_requested: Option<ViewCloseRequestedCallback>,
284 pub on_window_changed: Option<WindowChangedCallback>,
287 pub on_view_request_failed: Option<ViewRequestFailedCallback>,
289}
290
291pub type ViewFocusChangeCallback = Rc<dyn Fn(&mut App, ViewFocusEvent)>;
293
294pub type DragCallback = Rc<dyn Fn(&mut App, DragReport)>;
296
297pub type ClipboardEventCallback = Rc<dyn Fn(&mut App, ViewId, ClipboardEvent)>;
299
300pub type EditCommandCallback = Rc<dyn Fn(&mut App, ViewId, EditCommand)>;
302
303pub type MenuSelectedCallback = Rc<dyn Fn(&mut App, MenuId)>;
305
306pub type TrayIconEventCallback = Rc<dyn Fn(&mut App, TrayIconId, TrayIconEvent)>;
308
309pub type PopRouteCallback = Rc<dyn Fn(&mut App, ViewId) -> bool>;
311
312pub type ViewChangeCallback = Rc<dyn Fn(&mut App, ViewId)>;
314
315pub type ViewCloseRequestedCallback = Rc<dyn Fn(&mut App, ViewId)>;
317
318pub type WindowChangedCallback = Rc<dyn Fn(&mut App, ViewId)>;
320
321pub type ViewRequestFailedCallback = Rc<dyn Fn(&mut App, RequestId, ViewError)>;
323
324impl App {
325 pub(crate) fn build(
326 this: Weak<AppCell>,
327 platform: PlatformRef,
328 executor: ForegroundExecutor,
329 ) -> App {
330 App {
331 this,
332 handles: HandleMap::new(),
333 entities: EntityMap::new(),
334 singletons: HashMap::new(),
335 #[cfg(debug_assertions)]
336 skipped_tear_off_receivers: std::collections::HashSet::new(),
337 #[cfg(debug_assertions)]
338 skipped_tear_offs: Vec::new(),
339 microtasks: VecDeque::new(),
340 timers: Timers::default(),
341 debug_flags: HashMap::new(),
342 executor,
343 dispatcher: platform.dispatcher(),
344 platform,
345 platform_callbacks: PlatformCallbacks::default(),
346 open_requests: UntilHandled::default(),
347 notification_activations: UntilHandled::default(),
348 }
349 }
350
351 pub(crate) fn executor_handle(&self) -> ExecutorHandle {
353 self.executor.handle()
354 }
355
356 pub fn to_async(&self) -> AsyncApp {
358 AsyncApp::new(self.this.clone(), self.executor.handle())
359 }
360
361 pub fn spawn<R: 'static>(&self, f: impl AsyncFnOnce(&mut AsyncApp) -> R + 'static) -> Task<R> {
371 let mut cx = self.to_async();
372 self.executor.spawn(async move { f(&mut cx).await })
373 }
374
375 pub fn run_in_background<T: Send + 'static>(
380 &self,
381 work: impl FnOnce() -> T + Send + 'static,
382 ) -> Task<T> {
383 self.executor.run_in_background(work)
384 }
385
386 pub fn platform(&self) -> PlatformRef {
387 Rc::clone(&self.platform)
388 }
389
390 pub fn platform_callbacks(&self) -> &PlatformCallbacks {
392 &self.platform_callbacks
393 }
394
395 pub fn platform_callbacks_mut(&mut self) -> &mut PlatformCallbacks {
396 &mut self.platform_callbacks
397 }
398
399 pub fn set_open_requested_handler(&mut self, handler: Option<OpenRequestedCallback>) {
404 self.set_handler(|app| &mut app.open_requests, handler);
405 }
406
407 pub fn open_requested(&mut self, request: OpenRequest) {
412 self.hand_to_handler(|app| &mut app.open_requests, request);
413 }
414
415 pub fn set_notification_activated_handler(
420 &mut self,
421 handler: Option<NotificationActivatedCallback>,
422 ) {
423 self.set_handler(|app| &mut app.notification_activations, handler);
424 }
425
426 pub fn notification_activated(&mut self, activation: NotificationActivation) {
428 self.hand_to_handler(|app| &mut app.notification_activations, activation);
429 }
430
431 fn set_handler<T>(
432 &mut self,
433 queue: fn(&mut App) -> &mut UntilHandled<T>,
434 handler: Option<Handler<T>>,
435 ) {
436 queue(self).handler = handler.clone();
437 let Some(handler) = handler else {
438 return;
439 };
440 for waiting in std::mem::take(&mut queue(self).waiting) {
441 handler(self, waiting);
442 }
443 }
444
445 fn hand_to_handler<T>(&mut self, queue: fn(&mut App) -> &mut UntilHandled<T>, asked: T) {
446 match queue(self).handler.clone() {
447 Some(handler) => handler(self, asked),
448 None => queue(self).waiting.push(asked),
449 }
450 }
451
452 #[track_caller]
455 pub fn singleton<T: 'static + Default>(&mut self) -> Handle<T> {
456 if let Some(existing) = self.existing_singleton() {
457 return existing;
458 }
459 let singleton = self.create(T::default());
460 let handle = singleton.handle();
461 self.singletons
462 .insert(std::any::TypeId::of::<T>(), singleton.to_any());
463 handle
464 }
465
466 pub fn existing_singleton<T: 'static>(&self) -> Option<Handle<T>> {
469 self.singletons
470 .get(&std::any::TypeId::of::<T>())
471 .map(|singleton| Handle::new(singleton.handle()))
472 }
473
474 pub fn schedule_microtask(&mut self, callback: Listener) {
482 self.microtasks.push_back(callback);
483 }
484
485 pub fn drain_microtasks(&mut self) {
495 let mut drained = 0usize;
496 while let Some(callback) = self.microtasks.pop_front() {
497 drained += 1;
498 assert!(
499 drained <= MICROTASK_BUDGET,
500 "microtasks did not converge after {MICROTASK_BUDGET} callbacks; \
501 are two callbacks scheduling each other in a cycle?"
502 );
503 callback.call(self);
504 }
505 }
506
507 pub fn has_pending_microtasks(&self) -> bool {
513 !self.microtasks.is_empty()
514 }
515
516 pub fn schedule_timer(&mut self, duration: Duration, callback: Listener) -> Timer {
519 let timer = self.timers.schedule(duration, callback);
520 self.update_timer_wakeup();
521 timer
522 }
523
524 pub fn schedule_periodic_timer(
527 &mut self,
528 duration: Duration,
529 callback: impl Fn(&mut App, Timer) + 'static,
530 ) -> Timer {
531 let timer = self.timers.schedule_periodic(duration, Rc::new(callback));
532 self.update_timer_wakeup();
533 timer
534 }
535
536 pub fn cancel_timer(&mut self, timer: Timer) {
538 self.timers.cancel(timer);
539 self.update_timer_wakeup();
541 }
542
543 pub fn timer_is_active(&self, timer: Timer) -> bool {
545 self.timers.is_active(timer)
546 }
547
548 pub fn timer_tick(&self, timer: Timer) -> u64 {
550 self.timers.tick(timer)
551 }
552
553 pub fn clock(&self) -> Duration {
556 self.timers.now()
557 }
558
559 pub fn has_pending_timers(&self) -> bool {
562 self.timers.has_pending()
563 }
564
565 pub fn debug_flag<F: DebugFlag>(&self) -> bool {
569 self.debug_flags
570 .get(&std::any::TypeId::of::<F>())
571 .copied()
572 .unwrap_or(F::DEFAULT)
573 }
574
575 pub fn set_debug_flag<F: DebugFlag>(&mut self, value: bool) {
577 self.debug_flags.insert(std::any::TypeId::of::<F>(), value);
578 }
579
580 pub(crate) fn fire_next_due(&mut self, target: Duration, mode: TimerMode) -> bool {
583 let Some((timer, callback)) = self.timers.pop_next_due(target, mode) else {
584 return false;
585 };
586 callback(self, timer);
587 true
588 }
589
590 pub(crate) fn begin_timer_turn(&mut self) {
592 self.timers.begin_turn();
593 }
594
595 pub(crate) fn advance_clock_to(&mut self, target: Duration) {
596 self.timers.advance_to(target);
597 }
598
599 pub(crate) fn update_timer_wakeup(&mut self) {
603 if let Some(delay) = self.timers.timer_wakeup_if_changed() {
604 let wakeup = delay.map(|delay| self.platform.now() + delay);
605 self.dispatcher.wake_at(wakeup);
606 }
607 }
608
609 #[track_caller]
630 pub fn create<T: 'static>(&mut self, state: T) -> Ref<T> {
631 self.handles.create(state)
632 }
633
634 pub(crate) fn adopt_tree_node(&mut self, id: HandleId, keep: Rc<crate::handle_map::Keep>) {
636 self.handles.adopt_tree_node(id, keep);
637 }
638
639 pub fn release_tree_node(&mut self, node: impl Into<HandleId>) {
648 self.handles.release_tree_node(node.into());
649 }
650
651 pub(crate) fn not_kept(&self, id: HandleId) -> String {
653 self.handles.not_kept(id)
654 }
655
656 pub fn contains(&self, handle: impl Into<HandleId>) -> bool {
658 self.handles.contains(handle.into())
659 }
660
661 pub fn mark_disposed(&mut self, handle: impl Into<HandleId>) {
666 self.handles.mark_disposed(handle.into());
667 }
668
669 pub fn tear_off_receiver_is_live(&mut self, receiver: impl Into<HandleId>) -> bool {
674 let receiver = receiver.into();
675 let live = self.handles.contains(receiver);
676 #[cfg(debug_assertions)]
677 if !live && self.skipped_tear_off_receivers.insert(receiver) {
678 let message = format!(
679 "waft: a listener whose receiver was freed without removing it was skipped: {}",
680 self.handles.debug_describe(receiver)
681 );
682 eprintln!("{message}");
683 self.skipped_tear_offs.push(message);
684 }
685 live
686 }
687
688 pub fn expect_dispose(&mut self, handle: impl Into<HandleId>) {
697 self.handles.expect_dispose(handle.into());
698 }
699
700 #[cfg(debug_assertions)]
704 pub fn debug_take_not_disposed(&mut self) -> Vec<String> {
705 self.handles.take_not_disposed()
706 }
707
708 #[cfg(debug_assertions)]
713 pub fn debug_take_not_collected(&mut self) -> Vec<String> {
714 self.handles.take_not_collected()
715 }
716
717 #[cfg(debug_assertions)]
720 pub fn debug_live_objects(&self) -> Vec<crate::DebugObject> {
721 self.handles.debug_live_objects()
722 }
723
724 #[cfg(debug_assertions)]
727 pub fn debug_take_skipped_tear_offs(&mut self) -> Vec<String> {
728 std::mem::take(&mut self.skipped_tear_offs)
729 }
730
731 pub(crate) fn begin_checkpoint(&mut self) {
733 self.handles.begin_checkpoint();
734 }
735
736 pub(crate) fn free_dropped_objects(&mut self) {
738 self.handles.free_dropped();
739 }
740
741 pub fn is_disposed(&self, handle: impl Into<HandleId>) -> bool {
747 self.handles.is_disposed(handle.into())
748 }
749
750 pub fn handle<T: 'static>(&self, handle: impl Into<HandleId>) -> Option<Handle<T>> {
752 self.handles.handle(handle.into())
753 }
754
755 pub fn get<T: 'static>(&self, handle: impl ToHandle<T>) -> &T {
760 self.handles.get(handle.to_handle())
761 }
762
763 pub fn get_mut<T: 'static>(&mut self, handle: impl ToHandle<T>) -> &mut T {
765 self.handles.get_mut(handle.to_handle())
766 }
767
768 pub fn get_disjoint_mut<A: 'static, B: 'static>(
775 &mut self,
776 a: impl ToHandle<A>,
777 b: impl ToHandle<B>,
778 ) -> (&mut A, &mut B) {
779 self.handles.get_disjoint_mut(a.to_handle(), b.to_handle())
780 }
781}
782
783pub trait ToHandle<T> {
786 fn to_handle(self) -> Handle<T>;
788}
789
790impl<T> ToHandle<T> for Handle<T> {
791 fn to_handle(self) -> Handle<T> {
792 self
793 }
794}
795
796impl<T> ToHandle<T> for &Handle<T> {
797 fn to_handle(self) -> Handle<T> {
798 *self
799 }
800}
801
802impl<T> ToHandle<T> for &Ref<T> {
803 fn to_handle(self) -> Handle<T> {
804 self.handle()
805 }
806}
807
808#[cfg(test)]
809mod tests {
810 use super::*;
811 use crate::Timer;
812
813 #[derive(Debug, Default, PartialEq)]
814 struct Counter(i32);
815
816 #[derive(Debug, PartialEq)]
817 struct Label(&'static str);
818
819 #[test]
820 fn state_survives_a_round_trip_through_a_handle() {
821 let cell = AppCell::new();
822 let mut app = cell.borrow_mut();
823 let counter_ref = app.create(Counter(1));
824 let counter = counter_ref.handle();
825
826 assert_eq!(app.get(counter), &Counter(1));
827 app.get_mut(counter).0 = 7;
828 assert_eq!(app.get(counter), &Counter(7));
829 }
830
831 #[test]
832 fn handles_of_different_types_share_one_arena() {
833 let cell = AppCell::new();
834 let mut app = cell.borrow_mut();
835 let counter_ref = app.create(Counter(1));
836 let counter = counter_ref.handle();
837 let label_ref = app.create(Label("hello"));
838 let label = label_ref.handle();
839
840 assert_eq!(app.get(counter), &Counter(1));
841 assert_eq!(app.get(label), &Label("hello"));
842 }
843
844 #[test]
845 fn a_freed_entry_is_reused_but_its_handle_is_not() {
846 let cell = AppCell::new();
847 let first_id = cell.borrow_mut().create(Counter(1)).id();
848 cell.checkpoint();
849
850 let mut app = cell.borrow_mut();
851 let second_ref = app.create(Counter(2));
852 let second = second_ref.handle();
853 let entry_index = |id: HandleId| slotmap::Key::data(&id).as_ffi() & 0xffff_ffff;
855 assert_eq!(
856 entry_index(second.id()),
857 entry_index(first_id),
858 "the freed entry is reused, so the version is what tells them apart"
859 );
860 assert_ne!(second.id(), first_id);
861 assert!(!app.contains(first_id));
862 assert!(app.contains(second));
863 }
864
865 #[test]
866 #[cfg(debug_assertions)]
867 fn a_dropped_ref_keeps_the_object_readable_until_the_checkpoint() {
868 let cell = AppCell::new();
869 let counter_ref = cell.borrow_mut().create(Counter(3));
870 let counter = counter_ref.handle();
871
872 drop(counter_ref);
873 {
874 let app = cell.borrow();
875 assert_eq!(app.get(counter), &Counter(3), "still readable");
876 assert!(app.contains(counter), "still in the arena");
877 }
878 cell.checkpoint();
879 assert!(!cell.borrow().contains(counter), "freed at the checkpoint");
880 }
881
882 #[test]
883 #[should_panic(expected = "stale handle")]
884 fn reading_through_a_stale_handle_panics() {
885 let cell = AppCell::new();
886 let counter = cell.borrow_mut().create(Counter(1)).handle();
887 cell.checkpoint();
888 cell.borrow().get(counter);
889 }
890
891 #[test]
892 fn the_checked_path_from_an_untyped_id_answers_none_rather_than_panicking() {
893 let cell = AppCell::new();
894 let counter_ref = cell.borrow_mut().create(Counter(1));
895 let counter = counter_ref.handle();
896 let id = counter.id();
897
898 assert_eq!(cell.borrow().handle::<Counter>(id), Some(counter));
899 assert_eq!(cell.borrow().handle::<Label>(id), None, "wrong type");
900
901 drop(counter_ref);
902 cell.checkpoint();
903 assert_eq!(cell.borrow().handle::<Counter>(id), None, "stale");
904 }
905
906 #[test]
907 fn a_singleton_is_one_handle_per_type_per_app() {
908 let cell = AppCell::new();
909 let mut app = cell.borrow_mut();
910
911 let first: Handle<Counter> = app.singleton();
912 let second: Handle<Counter> = app.singleton();
913 assert_eq!(first, second);
914
915 app.get_mut(first).0 = 9;
916 assert_eq!(app.get(second).0, 9, "one entry behind both handles");
917
918 let other_cell = AppCell::new();
919 let mut other_app = other_cell.borrow_mut();
920 let elsewhere: Handle<Counter> = other_app.singleton();
921 assert_eq!(elsewhere.id(), first.id(), "ids may collide across Apps");
922 assert_eq!(other_app.get(elsewhere).0, 0, "but the state is per App");
923 }
924
925 #[test]
926 fn a_handle_is_copy_so_an_edge_can_be_a_plain_field() {
927 let cell = AppCell::new();
928 let mut app = cell.borrow_mut();
929 let counter_ref = app.create(Counter(1));
930 let counter = counter_ref.handle();
931
932 struct Edge {
933 target: Handle<Counter>,
934 }
935 let edge = Edge { target: counter };
936 let copied = edge.target;
937
938 assert_eq!(copied, counter);
939 assert_eq!(app.get(edge.target).0, 1);
940 }
941
942 #[test]
943 fn a_microtask_runs_on_drain_not_inline() {
944 let cell = AppCell::new();
945 let mut app = cell.borrow_mut();
946 let counter_ref = app.create(Counter(0));
947 let counter = counter_ref.handle();
948 app.schedule_microtask(crate::Listener::new(move |app| {
949 app.get_mut(counter).0 = 1;
950 }));
951 assert_eq!(app.get(counter).0, 0);
952 assert!(app.has_pending_microtasks());
953 app.drain_microtasks();
954 assert_eq!(app.get(counter).0, 1);
955 assert!(!app.has_pending_microtasks());
956 }
957
958 #[test]
959 fn a_microtask_scheduled_during_drain_runs_in_the_same_drain() {
960 let cell = AppCell::new();
961 let mut app = cell.borrow_mut();
962 let counter_ref = app.create(Counter(0));
963 let counter = counter_ref.handle();
964 app.schedule_microtask(crate::Listener::new(move |app| {
965 app.get_mut(counter).0 = 1;
966 app.schedule_microtask(crate::Listener::new(move |app| {
967 app.get_mut(counter).0 = 2;
968 }));
969 }));
970 app.drain_microtasks();
971 assert_eq!(app.get(counter).0, 2);
972 }
973
974 #[test]
975 fn timers_fire_in_due_order_after_microtasks() {
976 let cell = AppCell::new();
977 let mut app = cell.borrow_mut();
978 let log_ref = app.create(Vec::<&'static str>::new());
979 let log = log_ref.handle();
980 app.schedule_microtask(crate::Listener::new(move |app| {
981 app.get_mut(log).push("micro");
982 }));
983 Timer::new(
984 &mut app,
985 Duration::from_millis(200),
986 crate::Listener::new(move |app| {
987 app.get_mut(log).push("late");
988 }),
989 );
990 Timer::new(
991 &mut app,
992 Duration::from_millis(100),
993 crate::Listener::new(move |app| {
994 app.get_mut(log).push("early");
995 }),
996 );
997 Timer::new(
998 &mut app,
999 Duration::from_millis(100),
1000 crate::Listener::new(move |app| {
1001 app.get_mut(log).push("early-second");
1002 }),
1003 );
1004 assert!(app.get(log).is_empty());
1005 drop(app);
1006 cell.elapse(Duration::from_millis(200));
1007 let app = cell.borrow();
1008 assert_eq!(
1009 app.get(log).as_slice(),
1010 ["micro", "early", "early-second", "late"]
1011 );
1012 }
1013
1014 #[test]
1015 fn cancel_prevents_a_timer_from_firing() {
1016 let cell = AppCell::new();
1017 let mut app = cell.borrow_mut();
1018 let counter_ref = app.create(Counter(0));
1019 let counter = counter_ref.handle();
1020 let timer = Timer::new(
1021 &mut app,
1022 Duration::from_millis(10),
1023 crate::Listener::new(move |app| {
1024 app.get_mut(counter).0 = 1;
1025 }),
1026 );
1027 assert!(timer.is_active(&app));
1028 timer.cancel(&mut app);
1029 assert!(!timer.is_active(&app));
1030 drop(app);
1031 cell.elapse(Duration::from_millis(10));
1032 let app = cell.borrow();
1033 assert_eq!(app.get(counter).0, 0);
1034 }
1035 #[test]
1036 fn get_disjoint_mut_borrows_two_entries_at_once() {
1037 let cell = AppCell::new();
1038 let mut app = cell.borrow_mut();
1039 let a_ref = app.create(1u32);
1040 let a = a_ref.handle();
1041 let b_ref = app.create(String::from("x"));
1042 let b = b_ref.handle();
1043 let (a_value, b_value) = app.get_disjoint_mut(a, b);
1044 *a_value += 1;
1045 b_value.push('y');
1046 assert_eq!(*app.get(a), 2);
1047 assert_eq!(app.get(b), "xy");
1048 }
1049
1050 #[test]
1051 #[should_panic(expected = "not two live entries")]
1052 fn get_disjoint_mut_rejects_the_same_entry_twice() {
1053 let cell = AppCell::new();
1054 let mut app = cell.borrow_mut();
1055 let a_ref = app.create(1u32);
1056 let a = a_ref.handle();
1057 let _ = app.get_disjoint_mut(a, a);
1058 }
1059
1060 #[test]
1061 fn from_id_reads_like_the_minted_handle() {
1062 let cell = AppCell::new();
1063 let mut app = cell.borrow_mut();
1064 let minted_ref = app.create(Counter(7));
1065 let minted = minted_ref.handle();
1066 let rebuilt = Handle::<Counter>::from_id(minted.id());
1067 assert_eq!(rebuilt, minted);
1068 assert_eq!(app.get(rebuilt).0, 7);
1069 }
1070
1071 #[test]
1072 #[should_panic(expected = "stale handle")]
1073 fn from_id_defers_the_stale_check_to_get() {
1074 let cell = AppCell::new();
1075 let id = cell.borrow_mut().create(Counter(0)).id();
1076 cell.checkpoint();
1077 let rebuilt = Handle::<Counter>::from_id(id);
1078 cell.borrow().get(rebuilt);
1079 }
1080}