teksilo-core 0.9.1

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Backend event subscription infrastructure (architecture §9.4).
//!
//! Widgets subscribe to external event sources (database change notifiers,
//! file watchers, message buses, network response channels) directly from
//! their `build()` method via [`crate::BuildContext::subscribe_event`]. The
//! framework bridges events from the publisher's thread to the UI thread via
//! the application's event-loop proxy and routes them to the widget's
//! UI-side callback, with automatic per-widget lifetime cleanup.
//!
//! This module defines the public [`EventSource`] trait, the opaque
//! [`SubscriptionHandle`] returned by sources, and the internal
//! [`TreeAppContext`] / [`EventSourceAdapter`] / [`AppEventPoster`] types that
//! plug a registered source into the tree.

use std::any::{Any, TypeId};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;

use crate::widget::EventContext;
use crate::window::TeksiloWindowId;

/// An external source of events that widgets can subscribe to.
///
/// Implementations include backend message buses, database change notifiers,
/// file watchers, network response channels — any source that publishes
/// events asynchronously and that widgets need to react to.
pub trait EventSource: 'static {
    /// The key by which subscribers identify which events they care about.
    /// Typically an enum (a Qleany `Origin`) or a topic string.
    type Origin: Clone + 'static;

    /// The event payload delivered to subscriber callbacks. Must be `Send`
    /// because events cross from the publisher's thread to the UI thread via
    /// the framework's proxy bridge.
    type Event: Send + 'static;

    /// Subscribe a callback to events of a given origin. The callback is
    /// invoked on whatever thread the source publishes from (typically a
    /// background thread). The returned handle, when dropped, removes the
    /// subscription from the source's internal registry.
    fn subscribe(
        &self,
        origin: Self::Origin,
        callback: Arc<dyn Fn(Self::Event) + Send + Sync + 'static>,
    ) -> SubscriptionHandle;
}

/// An opaque handle returned by [`EventSource::subscribe`].
///
/// The source defines what the handle contains; the framework treats it as a
/// token whose `Drop` impl performs the unsubscription. Returning an empty
/// handle (via [`SubscriptionHandle::empty`]) is acceptable for sources that
/// outlive the application or do not support removal.
pub struct SubscriptionHandle {
    _inner: Box<dyn Any>,
}

impl SubscriptionHandle {
    /// Wrap an arbitrary value as a subscription handle. The value is dropped
    /// when the handle is dropped — typically that drop performs removal from
    /// the source's internal subscriber registry.
    pub fn new<T: 'static>(token: T) -> Self {
        Self {
            _inner: Box::new(token),
        }
    }

    /// A handle that performs no cleanup on drop. Use this for sources that
    /// outlive the application or whose subscribers cannot be individually
    /// removed.
    pub fn empty() -> Self {
        Self::new(())
    }
}

/// A unique identifier for a subscription installed via
/// [`crate::BuildContext::subscribe_event`].
///
/// Used internally to look up the UI-side callback when a posted event
/// arrives back on the UI thread, and to key the per-widget cleanup scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubscriptionId(pub(crate) u64);

/// Posts events from background threads back to the UI thread.
///
/// teksilo-core cannot depend on winit or teksilo-app, so this trait acts as the
/// boundary: teksilo-app provides an implementation that wraps the
/// `EventLoopProxy<AppEvent>` and converts the calls into the
/// matching `AppEvent::*` user-event variants.
///
/// Two posting paths share this trait:
///
/// - `post_subscription_event` — backend events for widgets that
///   subscribed via [`BuildContext::subscribe_event`](crate::build_context::BuildContext).
/// - `post_external` — arbitrary typed payloads delivered as
///   [`AppEvent::External`](crate::app_event::AppEvent::External). Used
///   by async OS-driven integrations (file dialogs, future background
///   tasks) that resolve off the UI thread and need to deliver typed
///   results back to the main loop.
pub trait AppEventPoster: Send + Sync + 'static {
    fn post_subscription_event(&self, sub_id: SubscriptionId, event: Box<dyn Any + Send>);

    /// Post an arbitrary typed payload as `AppEvent::External(_)`.
    /// Default body is a no-op so existing implementations stay
    /// source-compatible; the real implementation in teksilo-app
    /// forwards to `EventLoopProxy::send_event`.
    fn post_external(&self, _payload: Box<dyn Any + Send>) {}
}

/// Type-erased wrapper around a registered [`EventSource`].
///
/// The generic source `S` is consumed when the adapter is constructed via
/// [`EventSourceAdapter::new`]; only erased closures and `TypeId`s remain.
/// This lets `WidgetTree` / `BuildContext` reach the source without becoming
/// generic over `S`.
pub struct EventSourceAdapter {
    pub(crate) origin_type: TypeId,
    pub(crate) origin_type_name: &'static str,
    pub(crate) event_type: TypeId,
    pub(crate) event_type_name: &'static str,
    #[allow(clippy::type_complexity)]
    pub(crate) subscribe_fn: Box<
        dyn Fn(
            Box<dyn Any>,
            Arc<dyn Fn(Box<dyn Any + Send>) + Send + Sync + 'static>,
        ) -> SubscriptionHandle,
    >,
}

impl EventSourceAdapter {
    /// Build an adapter from a concrete event source. Called by
    /// `TeksiloAppBuilder::event_source`.
    pub fn new<S: EventSource>(source: S) -> Self {
        let source = Arc::new(source);
        let origin_type = TypeId::of::<S::Origin>();
        let origin_type_name = std::any::type_name::<S::Origin>();
        let event_type = TypeId::of::<S::Event>();
        let event_type_name = std::any::type_name::<S::Event>();

        let subscribe_fn: Box<
            dyn Fn(
                Box<dyn Any>,
                Arc<dyn Fn(Box<dyn Any + Send>) + Send + Sync + 'static>,
            ) -> SubscriptionHandle,
        > = Box::new(move |erased_origin, framework_wrapper| {
            let origin: Box<S::Origin> = erased_origin
                .downcast::<S::Origin>()
                .expect("origin type mismatch — framework bug");

            // Wrap the framework's `Fn(Box<dyn Any + Send>)` into the
            // `Fn(S::Event)` shape the source expects. The wrapper boxes
            // the typed event and forwards to the framework's poster.
            let typed_callback: Arc<dyn Fn(S::Event) + Send + Sync + 'static> =
                Arc::new(move |event: S::Event| {
                    let erased: Box<dyn Any + Send> = Box::new(event);
                    framework_wrapper(erased);
                });

            source.subscribe(*origin, typed_callback)
        });

        Self {
            origin_type,
            origin_type_name,
            event_type,
            event_type_name,
            subscribe_fn,
        }
    }
}

/// UI-side callback for a *context-bearing* subscription
/// ([`BuildContext::subscribe_event_with_ctx`](crate::build_context::BuildContext::subscribe_event_with_ctx)):
/// it receives the downcast event **and** a fresh [`EventContext`], so it can
/// imperatively drive toasts, modals, intents and navigation in reaction to a
/// backend event — the things a plain, context-free `subscribe_event` callback
/// cannot. teksilo-app invokes it from inside
/// [`WidgetTree::run_with_event_context`](crate::WidgetTree::run_with_event_context),
/// keyed by the originating window so the context binds to the right tree.
///
/// Stored behind `Rc` (not `Box`) so dispatch can **clone the handle and release
/// the map borrow before invoking** — the callback runs arbitrary UI code (it
/// may `open_window`, which synchronously builds a new tree whose widgets can
/// register *their own* context-bearing subscriptions, i.e. re-enter this very
/// map). Holding the borrow across the call would `BorrowMutError`-panic there.
type CtxSubscriptionCallback = Rc<dyn Fn(&dyn Any, &mut EventContext)>;

/// Per-tree app-level subscription state.
///
/// Held by `WidgetTree` as `Rc<TreeAppContext>` so that `BuildContext` can
/// reach the event source adapter, allocate subscription ids, and post the
/// UI-side callback into the lookup map. Fields are `RefCell`/`Cell`
/// because the tree borrows itself mutably during `build()` and we need
/// shared interior access.
pub struct TreeAppContext {
    pub(crate) poster: Option<Arc<dyn AppEventPoster>>,
    pub(crate) event_source: Option<EventSourceAdapter>,
    /// Plain (context-free) subscription callbacks and the window each was registered
    /// from. Populated by
    /// [`BuildContext::subscribe_event`](crate::build_context::BuildContext::subscribe_event).
    ///
    /// The window is recorded for the same reason `subscription_ctx_callbacks` below
    /// records one: this map is shared by every window's tree (one `TreeAppContext`, one
    /// `Rc` handed to each tree), while a closing window's tree is dropped wholesale with
    /// no per-widget destroy pass. Without a window key the entries a closed window
    /// installed could not be purged even in principle, and each would hold whatever its
    /// closure captured for the rest of the process. See
    /// [`purge_subscriptions_for_window`](Self::purge_subscriptions_for_window).
    ///
    /// `None` for a registration from a windowless tree (headless / tests). No window
    /// purge ever touches those; only the per-widget teardown in `WidgetTree` does.
    #[allow(clippy::type_complexity)]
    pub(crate) subscription_callbacks:
        RefCell<HashMap<SubscriptionId, (Option<TeksiloWindowId>, Rc<dyn Fn(&dyn Any)>)>>,
    /// Context-bearing subscription callbacks + the window they target.
    /// Populated by [`BuildContext::subscribe_event_with_ctx`](crate::build_context::BuildContext::subscribe_event_with_ctx);
    /// dispatched by teksilo-app with a freshly-minted [`EventContext`]. A given
    /// `SubscriptionId` lives in exactly one of the two callback maps.
    ///
    /// The window is `Option` because a subscription registered from a windowless
    /// tree (headless / tests) has no tree to mint an `EventContext` from — the
    /// app-side router then can't deliver it (real app widgets always have a
    /// window). Direct [`dispatch_subscription_event_with_ctx`](Self::dispatch_subscription_event_with_ctx)
    /// is window-agnostic, which is what unit tests drive.
    #[allow(clippy::type_complexity)]
    pub(crate) subscription_ctx_callbacks:
        RefCell<HashMap<SubscriptionId, (Option<TeksiloWindowId>, CtxSubscriptionCallback)>>,
    pub(crate) next_subscription_id: Cell<u64>,
    /// Application-scoped values keyed by `TypeId`.
    /// Populated at builder time, read-only after the tree starts running.
    pub(crate) app_state: HashMap<TypeId, Box<dyn Any>>,
}

impl TreeAppContext {
    /// Empty context — no event source, no proxy poster. Used by tests
    /// and by `WidgetTree::new()`.
    pub fn empty() -> Self {
        Self {
            poster: None,
            event_source: None,
            subscription_callbacks: RefCell::new(HashMap::new()),
            subscription_ctx_callbacks: RefCell::new(HashMap::new()),
            next_subscription_id: Cell::new(1),
            app_state: HashMap::new(),
        }
    }

    /// Build a context with both a registered event source and a proxy
    /// poster. Called by `teksilo-app` when constructing a window for an
    /// application that registered an event source on the builder.
    pub fn with_source_and_poster(
        event_source: EventSourceAdapter,
        poster: Arc<dyn AppEventPoster>,
    ) -> Self {
        Self {
            poster: Some(poster),
            event_source: Some(event_source),
            subscription_callbacks: RefCell::new(HashMap::new()),
            subscription_ctx_callbacks: RefCell::new(HashMap::new()),
            next_subscription_id: Cell::new(1),
            app_state: HashMap::new(),
        }
    }

    /// Install an app-state registry. Consumes `self`
    /// and returns a new context with the registry attached; the builder
    /// calls this after constructing the context and before wrapping it
    /// in `Rc`.
    pub fn with_app_state(mut self, registry: HashMap<TypeId, Box<dyn Any>>) -> Self {
        self.app_state = registry;
        self
    }

    /// Install an [`AppEventPoster`] so background work (file dialogs,
    /// future async-result features) can post typed payloads back to
    /// the UI loop via `AppEvent::External`. The builder calls this
    /// unconditionally during `TeksiloAppBuilder::run` — the poster is
    /// cheap (a thin wrapper around the event-loop proxy) and being
    /// reachable means widgets do not have to depend on the event-source
    /// feature for unrelated async-result delivery.
    pub fn with_poster(mut self, poster: Arc<dyn AppEventPoster>) -> Self {
        self.poster = Some(poster);
        self
    }

    /// Borrow the registered [`AppEventPoster`] if one was installed.
    /// Used by integrations that need to post typed payloads back to
    /// the UI loop from an external thread (e.g. file-dialog backends).
    pub fn poster(&self) -> Option<&Arc<dyn AppEventPoster>> {
        self.poster.as_ref()
    }

    /// Look up an app-state value of type `T` previously registered via
    /// `TeksiloAppBuilder::app_state`.
    pub fn app_state<T: 'static>(&self) -> Option<&T> {
        self.app_state
            .get(&TypeId::of::<T>())
            .and_then(|boxed| boxed.downcast_ref::<T>())
    }

    pub(crate) fn allocate_subscription_id(&self) -> SubscriptionId {
        let id = self.next_subscription_id.get();
        self.next_subscription_id.set(id + 1);
        SubscriptionId(id)
    }

    /// Look up and invoke the UI-side callback for a posted subscription
    /// event. Returns `true` if a callback was found and invoked.
    /// The `Rc` handle is **cloned and the map borrow released before the call**, for
    /// the same reason [`dispatch_subscription_event_with_ctx`](Self::dispatch_subscription_event_with_ctx)
    /// does it: the callback may re-enter this map. It re-enters on two paths that both
    /// exist today — a widget built from inside a handler registers its own
    /// subscription (`borrow_mut` to insert), and a window closed from inside one is
    /// purged by [`purge_subscriptions_for_window`](Self::purge_subscriptions_for_window)
    /// (`borrow_mut` to retain). Holding the borrow across the call turns either into a
    /// `BorrowMutError` panic; hence `Rc`, not `Box`.
    pub fn dispatch_subscription_event(&self, sub_id: SubscriptionId, event: &dyn Any) -> bool {
        let callback = self
            .subscription_callbacks
            .borrow()
            .get(&sub_id)
            .map(|(_window_id, callback)| Rc::clone(callback));
        match callback {
            Some(callback) => {
                callback(event);
                true
            }
            None => false,
        }
    }

    /// The window a *context-bearing* subscription targets, if `sub_id` names one
    /// **and** it was registered from a window (always true in a real app).
    /// teksilo-app peeks this to know which window's tree to mint the
    /// [`EventContext`] from before dispatching.
    pub fn ctx_subscription_window(&self, sub_id: SubscriptionId) -> Option<TeksiloWindowId> {
        self.subscription_ctx_callbacks
            .borrow()
            .get(&sub_id)
            .and_then(|(window_id, _)| *window_id)
    }

    /// Invoke the *context-bearing* UI-side callback for a posted subscription
    /// event, passing the freshly-minted [`EventContext`]. Returns `true` if a
    /// callback was found and invoked. Called by teksilo-app from inside
    /// [`WidgetTree::run_with_event_context`](crate::WidgetTree::run_with_event_context).
    ///
    /// The `Rc` handle is **cloned and the map borrow released before the call**,
    /// so the callback may freely re-enter this map — e.g. `ctx.open_window(...)`
    /// synchronously builds a new tree whose widgets register their own
    /// context-bearing subscriptions. (Holding the borrow across the call would
    /// panic there; hence `Rc`, not `Box`.)
    pub fn dispatch_subscription_event_with_ctx(
        &self,
        sub_id: SubscriptionId,
        event: &dyn Any,
        ctx: &mut EventContext,
    ) -> bool {
        let callback = self
            .subscription_ctx_callbacks
            .borrow()
            .get(&sub_id)
            .map(|(_window_id, callback)| Rc::clone(callback));
        match callback {
            Some(callback) => {
                callback(event, ctx);
                true
            }
            None => false,
        }
    }

    /// Number of context-bearing subscription callbacks currently installed.
    /// Companion to [`subscription_count`](Self::subscription_count); used by
    /// lifecycle tests to assert the ctx-map teardown ran.
    pub fn ctx_subscription_count(&self) -> usize {
        self.subscription_ctx_callbacks.borrow().len()
    }

    /// Drop every context-bearing subscription targeting `window_id`. Called by
    /// teksilo-app when a window closes, so the shared, longer-lived
    /// `TreeAppContext` map doesn't retain inert callbacks for a torn-down tree
    /// (a window's tree is dropped without a per-widget `destroy_subtree` pass).
    /// Mirrors [`AsyncCompletionHandle::purge_window`](crate::AsyncCompletionHandle::purge_window).
    pub fn purge_ctx_subscriptions_for_window(&self, window_id: TeksiloWindowId) {
        self.subscription_ctx_callbacks
            .borrow_mut()
            .retain(|_, (win, _)| *win != Some(window_id));
    }

    /// Drop every *plain* (context-free) subscription callback registered from
    /// `window_id`. Called by teksilo-app when a window closes, beside
    /// [`purge_ctx_subscriptions_for_window`](Self::purge_ctx_subscriptions_for_window).
    ///
    /// The two maps need two purges for the same reason they need two dispatch
    /// functions: a given `SubscriptionId` lives in exactly one of them. Without this
    /// one, every callback the closed window's widgets installed stays in the shared map
    /// for the life of the process, holding strong references to whatever it captured
    /// (view-models, document stores, context handles), because a closing window's tree
    /// is dropped wholesale and nothing runs the per-widget removal in
    /// `WidgetTree::destroy_subtree_inner`.
    ///
    /// A registration made from a windowless tree records `None` and is never purged
    /// here; only the per-widget teardown reaches it, which an application drives
    /// through [`BuildContext::destroy_subtree`](crate::BuildContext::destroy_subtree).
    pub fn purge_subscriptions_for_window(&self, window_id: TeksiloWindowId) {
        self.subscription_callbacks
            .borrow_mut()
            .retain(|_, (win, _)| *win != Some(window_id));
    }

    /// Number of UI-side subscription callbacks currently installed.
    /// Used by lifecycle tests to assert cleanup ran correctly.
    pub fn subscription_count(&self) -> usize {
        self.subscription_callbacks.borrow().len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signal::Signal;
    use crate::widget::{LayoutContext, Widget};
    use crate::widget_id::WidgetId;
    use crate::widget_tree::WidgetTree;
    use std::sync::Mutex;
    use teksilo_canvas::SizeProposal;

    // --- Test event source ---

    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
    enum TestOrigin {
        Created,
        Updated,
    }

    #[derive(Clone, Debug, PartialEq)]
    struct TestEvent {
        id: u64,
        message: String,
    }

    /// A trivial in-process event source. Holds a list of (id, origin, callback)
    /// entries; `publish` walks them and invokes matching callbacks
    /// synchronously on the calling thread.
    ///
    /// ⚠ **Its handle really unsubscribes**, which is not decoration. A source that
    /// returns [`SubscriptionHandle::empty`] keeps every subscriber it was ever given,
    /// so one publish reaches the wrappers of *all* of a widget's past builds. That used
    /// to be invisible, because each of those wrappers posted a by-then-dead id and the
    /// dispatch dropped it; now that an id outlives a rebuild it would deliver the same
    /// event once per past build. A mock that never removes anything would model a
    /// source no real one resembles and would make this suite assert the wrong thing.
    #[derive(Default)]
    struct MockEventSource {
        #[allow(clippy::type_complexity)]
        subscribers: Arc<
            Mutex<
                Vec<(
                    u64,
                    TestOrigin,
                    Arc<dyn Fn(TestEvent) + Send + Sync + 'static>,
                )>,
            >,
        >,
        next_id: std::sync::atomic::AtomicU64,
    }

    /// Removes its entry from [`MockEventSource`] on drop, the way a real source's
    /// token does.
    struct MockToken {
        #[allow(clippy::type_complexity)]
        subscribers: Arc<
            Mutex<
                Vec<(
                    u64,
                    TestOrigin,
                    Arc<dyn Fn(TestEvent) + Send + Sync + 'static>,
                )>,
            >,
        >,
        id: u64,
    }

    impl Drop for MockToken {
        fn drop(&mut self) {
            if let Ok(mut subs) = self.subscribers.lock() {
                subs.retain(|(id, _, _)| *id != self.id);
            }
        }
    }

    impl EventSource for MockEventSource {
        type Origin = TestOrigin;
        type Event = TestEvent;

        fn subscribe(
            &self,
            origin: Self::Origin,
            callback: Arc<dyn Fn(Self::Event) + Send + Sync + 'static>,
        ) -> SubscriptionHandle {
            let id = self
                .next_id
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            self.subscribers
                .lock()
                .unwrap()
                .push((id, origin, callback));
            SubscriptionHandle::new(MockToken {
                subscribers: self.subscribers.clone(),
                id,
            })
        }
    }

    impl MockEventSource {
        fn publish(&self, origin: TestOrigin, event: TestEvent) {
            let subs = self.subscribers.lock().unwrap();
            for (_id, sub_origin, cb) in subs.iter() {
                if *sub_origin == origin {
                    cb(event.clone());
                }
            }
        }

        fn subscriber_count(&self) -> usize {
            self.subscribers.lock().unwrap().len()
        }
    }

    /// A poster that buffers posted events into a thread-safe queue. Tests
    /// drain it after `publish` and dispatch them through the tree's
    /// app_context, mirroring the real proxy → user_event flow.
    #[derive(Default)]
    struct TestPoster {
        #[allow(clippy::type_complexity)]
        queue: Mutex<Vec<(SubscriptionId, Box<dyn Any + Send>)>>,
    }

    impl AppEventPoster for TestPoster {
        fn post_subscription_event(&self, sub_id: SubscriptionId, event: Box<dyn Any + Send>) {
            self.queue.lock().unwrap().push((sub_id, event));
        }
    }

    impl TestPoster {
        fn drain(&self) -> Vec<(SubscriptionId, Box<dyn Any + Send>)> {
            std::mem::take(&mut *self.queue.lock().unwrap())
        }
    }

    // --- Test widget that subscribes in build() ---

    #[derive(Debug)]
    struct SubscribingWidget {
        origin: TestOrigin,
        last_message: Signal<String>,
    }

    impl Widget for SubscribingWidget {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let last_message = self.last_message.clone();
            ctx.subscribe_event(self.origin.clone(), move |event: &TestEvent| {
                last_message.set(event.message.clone());
            });
            Vec::new()
        }

        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }
    }

    /// Subscribes via the *context-bearing* API in `build()` — headless, so the
    /// registration records `None` for the window but still lands in the ctx map
    /// and is torn down on destroy.
    #[derive(Debug)]
    struct CtxSubscribingWidget {
        origin: TestOrigin,
        last_message: Signal<String>,
    }

    impl Widget for CtxSubscribingWidget {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let last_message = self.last_message.clone();
            ctx.subscribe_event_with_ctx(
                self.origin.clone(),
                move |event: &TestEvent, _ctx: &mut crate::widget::EventContext| {
                    last_message.set(event.message.clone());
                },
            );
            Vec::new()
        }

        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }
    }

    // --- Helpers ---

    fn install_source(
        tree: &mut WidgetTree,
        source: MockEventSource,
    ) -> (Arc<MockEventSource>, Arc<TestPoster>) {
        let source = Arc::new(source);
        // We need to share the source between the test and the adapter,
        // so wrap a thin proxy that delegates to the Arc.
        struct SharedSource {
            inner: Arc<MockEventSource>,
        }
        impl EventSource for SharedSource {
            type Origin = TestOrigin;
            type Event = TestEvent;
            fn subscribe(
                &self,
                origin: Self::Origin,
                callback: Arc<dyn Fn(Self::Event) + Send + Sync + 'static>,
            ) -> SubscriptionHandle {
                self.inner.subscribe(origin, callback)
            }
        }

        let adapter = EventSourceAdapter::new(SharedSource {
            inner: source.clone(),
        });
        let poster: Arc<TestPoster> = Arc::new(TestPoster::default());
        let poster_dyn: Arc<dyn AppEventPoster> = poster.clone();
        let app_context =
            std::rc::Rc::new(TreeAppContext::with_source_and_poster(adapter, poster_dyn));
        tree.set_app_context(app_context);
        (source, poster)
    }

    fn drain_and_dispatch(tree: &WidgetTree, poster: &TestPoster) {
        let events = poster.drain();
        for (sub_id, event) in events {
            tree.app_context()
                .dispatch_subscription_event(sub_id, &*event);
        }
    }

    // --- Tests ---

    #[test]
    fn subscribe_event_delivers_to_widget_signal() {
        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let _id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        assert_eq!(source.subscriber_count(), 1);
        assert_eq!(tree.app_context().subscription_count(), 1);

        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "hello".to_string(),
            },
        );
        drain_and_dispatch(&tree, &poster);

        assert_eq!(signal.get(), "hello");
    }

    #[test]
    fn subscribe_event_with_ctx_dispatches_inside_fresh_context() {
        use crate::window::{NoopWindowOps, TeksiloWindowId};

        let mut tree = WidgetTree::new();
        // Register a context-bearing callback the way
        // `BuildContext::subscribe_event_with_ctx` does — but directly, so the
        // test needs no real window (that routing is covered end-to-end by the
        // `toast_demo` example and the Skribisto importer).
        let app_ctx = tree.app_context().clone();
        let sub_id = app_ctx.allocate_subscription_id();
        let win = TeksiloWindowId::new(1);
        let seen = Signal::new(String::new());
        let seen_cb = seen.clone();
        let stored: std::rc::Rc<dyn Fn(&dyn Any, &mut crate::widget::EventContext)> =
            std::rc::Rc::new(move |event_any, _ctx: &mut crate::widget::EventContext| {
                let ev = event_any
                    .downcast_ref::<TestEvent>()
                    .expect("subscription event downcast failed");
                seen_cb.set(ev.message.clone());
            });
        app_ctx
            .subscription_ctx_callbacks
            .borrow_mut()
            .insert(sub_id, (Some(win), stored));

        // The target window is peekable (teksilo-app reads it to pick the tree
        // whose `EventContext` it mints).
        assert_eq!(app_ctx.ctx_subscription_window(sub_id), Some(win));
        assert_eq!(app_ctx.ctx_subscription_window(SubscriptionId(9999)), None);

        // Dispatch inside a fresh `EventContext`, exactly like teksilo-app's
        // `try_dispatch_subscription_with_ctx`.
        let event = TestEvent {
            id: 9,
            message: "progress-42".to_string(),
        };
        let handled = std::cell::Cell::new(false);
        tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
            handled.set(app_ctx.dispatch_subscription_event_with_ctx(sub_id, &event, ctx));
        });
        assert!(
            handled.get(),
            "context-bearing dispatch must find the callback"
        );
        assert_eq!(seen.get(), "progress-42");

        // An unknown sub_id is not consumed (so the caller falls back to the
        // plain, context-free path).
        tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
            assert!(!app_ctx.dispatch_subscription_event_with_ctx(
                SubscriptionId(9999),
                &event,
                ctx
            ));
        });
    }

    /// Regression for the re-entrancy panic: dispatch must clone the `Rc` and
    /// **release the map borrow before invoking** the callback, so a callback
    /// that re-enters the same map — as `ctx.open_window(...)` does via a nested
    /// `build()` calling `subscribe_event_with_ctx` — does not `BorrowMutError`.
    #[test]
    fn ctx_dispatch_releases_borrow_before_invoking_callback() {
        use crate::window::{NoopWindowOps, TeksiloWindowId};

        let mut tree = WidgetTree::new();
        let app_ctx = tree.app_context().clone();
        let sub_id = app_ctx.allocate_subscription_id();

        let reenter_ctx = app_ctx.clone();
        let reentered = std::rc::Rc::new(std::cell::Cell::new(false));
        let flag = reentered.clone();
        let cb: std::rc::Rc<dyn Fn(&dyn Any, &mut crate::widget::EventContext)> =
            std::rc::Rc::new(move |_ev, _ctx| {
                // Simulate open_window → build() → subscribe_event_with_ctx: a
                // fresh registration into the SAME map while this callback runs.
                reenter_ctx.subscription_ctx_callbacks.borrow_mut().insert(
                    SubscriptionId(4242),
                    (
                        Some(TeksiloWindowId::new(2)),
                        std::rc::Rc::new(|_e: &dyn Any, _c: &mut crate::widget::EventContext| {}),
                    ),
                );
                flag.set(true);
            });
        app_ctx
            .subscription_ctx_callbacks
            .borrow_mut()
            .insert(sub_id, (Some(TeksiloWindowId::new(1)), cb));

        let event = TestEvent {
            id: 1,
            message: String::new(),
        };
        tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
            assert!(app_ctx.dispatch_subscription_event_with_ctx(sub_id, &event, ctx));
        });

        assert!(
            reentered.get(),
            "callback ran and its re-entrant map insert did not panic"
        );
        assert_eq!(
            app_ctx.ctx_subscription_count(),
            2,
            "original + the re-entrant insert both present"
        );
    }

    /// Exercises the real `BuildContext::subscribe_event_with_ctx` (headless →
    /// window `None`) end-to-end: registration lands in the ctx map, and
    /// destroying the widget tears it back down (covers the widget-destroy path's
    /// removal from the ctx map).
    #[test]
    fn subscribe_event_with_ctx_registers_and_tears_down() {
        let mut tree = WidgetTree::new();
        let (_source, _poster) = install_source(&mut tree, MockEventSource::default());

        let id = tree.add(CtxSubscribingWidget {
            origin: TestOrigin::Created,
            last_message: Signal::new(String::new()),
        });
        // The ctx path uses the OTHER map — the plain count stays 0.
        assert_eq!(tree.app_context().ctx_subscription_count(), 1);
        assert_eq!(tree.app_context().subscription_count(), 0);

        tree.destroy_subtree(id);
        assert_eq!(
            tree.app_context().ctx_subscription_count(),
            0,
            "destroying the widget must remove its context-bearing subscription"
        );
    }

    #[test]
    fn unrelated_origin_does_not_fire_callback() {
        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let _id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        source.publish(
            TestOrigin::Updated,
            TestEvent {
                id: 1,
                message: "ignored".to_string(),
            },
        );
        drain_and_dispatch(&tree, &poster);

        assert_eq!(signal.get(), "");
    }

    #[test]
    fn destroying_widget_removes_ui_callback() {
        let mut tree = WidgetTree::new();
        let (_source, _poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        assert_eq!(tree.app_context().subscription_count(), 1);
        tree.destroy_subtree(id);
        assert_eq!(tree.app_context().subscription_count(), 0);
    }

    /// The window-closing twin of [`destroying_widget_removes_ui_callback`].
    ///
    /// Closing a window drops its whole tree at once: nothing calls `destroy_subtree`,
    /// so the per-widget removal the test above pins never runs for a single one of the
    /// widgets that window built. The callback map is shared by every window in the
    /// process (one `TreeAppContext`, one `Rc` per tree), so without a window key those
    /// closures stay live for the rest of the session holding everything they captured.
    /// `purge_subscriptions_for_window` is what the app-side close path calls instead,
    /// and this test is the only place that says so about the plain map.
    ///
    /// Three trees stand in for the three cases that must be told apart: the window
    /// being closed, a window that stays open, and a windowless (headless) registration
    /// that no window purge may ever touch.
    #[test]
    fn closing_a_window_removes_its_ui_callbacks() {
        use crate::WindowStateInit;
        use crate::window::{TeksiloWindowId, WindowPlacement, WindowState};

        fn window_state(id: u64) -> WindowState {
            WindowState::new(WindowStateInit {
                id: TeksiloWindowId::new(id),
                string_id: None,
                placement: WindowPlacement::Floating,
                title: String::new(),
                size: (800, 600),
                position: (0, 0),
                focused: true,
                resizable: true,
                always_on_top: false,
            })
        }

        // Window 1 installs the shared context; window 2 and the headless tree get a
        // clone of the same `Rc`, exactly as `WindowManager` hands out its
        // `app_context_template`.
        let mut tree_one = WidgetTree::new();
        tree_one.set_window_state(window_state(1));
        let (source, poster) = install_source(&mut tree_one, MockEventSource::default());

        let mut tree_two = WidgetTree::new();
        tree_two.set_window_state(window_state(2));
        tree_two.set_app_context(tree_one.app_context().clone());

        let mut tree_headless = WidgetTree::new();
        tree_headless.set_app_context(tree_one.app_context().clone());

        let one = Signal::new(String::new());
        let two = Signal::new(String::new());
        let headless = Signal::new(String::new());
        tree_one.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: one.clone(),
        });
        tree_two.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: two.clone(),
        });
        tree_headless.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: headless.clone(),
        });

        let app_ctx = tree_one.app_context().clone();
        assert_eq!(app_ctx.subscription_count(), 3);
        assert_eq!(source.subscriber_count(), 3);

        // Close window 1 the way `WindowManager::close_window` does: purge first, then
        // drop the tree (which drops the arena's subscription handles and so
        // unregisters that window from the source).
        app_ctx.purge_subscriptions_for_window(TeksiloWindowId::new(1));
        drop(tree_one);

        assert_eq!(
            app_ctx.subscription_count(),
            2,
            "the closed window's callback must be gone, and neither the other window's \
             nor the windowless one may go with it"
        );
        assert_eq!(
            source.subscriber_count(),
            2,
            "dropping the tree unregisters the closed window from the source"
        );

        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "after the close".to_string(),
            },
        );
        drain_and_dispatch(&tree_two, &poster);

        assert_eq!(one.get(), "", "a closed window's callback must not run");
        assert_eq!(
            two.get(),
            "after the close",
            "a window that stayed open keeps receiving"
        );
        assert_eq!(
            headless.get(),
            "after the close",
            "a windowless registration is not purged by any window id"
        );

        // And the surviving window purges on its own close, leaving only the
        // windowless entry, which nothing but a widget destroy can reach.
        app_ctx.purge_subscriptions_for_window(TeksiloWindowId::new(2));
        assert_eq!(app_ctx.subscription_count(), 1);
    }

    #[test]
    fn in_flight_event_after_destroy_is_dropped_not_delivered() {
        // An event that was buffered in the proxy queue before the widget
        // was destroyed is silently dropped once cleanup completes. The
        // destroy path removes the UI-side callback synchronously, so by
        // the time the drain happens the callback lookup misses. This
        // preserves the invariant that a destroyed widget never sees
        // another event.
        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        // Publish — the wrapper fires and enqueues into the test poster.
        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 7,
                message: "buffered".to_string(),
            },
        );

        tree.destroy_subtree(id);
        drain_and_dispatch(&tree, &poster);

        assert_eq!(signal.get(), "");
        assert_eq!(tree.app_context().subscription_count(), 0);
    }

    #[test]
    #[should_panic(expected = "no event source was registered")]
    fn subscribe_without_event_source_panics() {
        let mut tree = WidgetTree::new();
        let signal = Signal::new(String::new());
        // No install_source — tree has the empty default app context.
        tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal,
        });
    }

    // --- app_state tests (architecture §9.5) ---

    use std::rc::Rc;

    struct TestGlobals {
        greeting: Signal<String>,
    }

    /// Widget that reads `Rc<TestGlobals>` from app_state in `build()` and
    /// records what it observed into an out-of-band signal.
    #[derive(Debug)]
    struct AppStateReader {
        observed: Signal<String>,
        saw_none: Signal<bool>,
    }

    impl Widget for AppStateReader {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            match ctx.app_state::<Rc<TestGlobals>>() {
                Some(globals) => self.observed.set(globals.greeting.get()),
                None => self.saw_none.set(true),
            }
            Vec::new()
        }

        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }
    }

    #[test]
    fn app_state_roundtrip_in_build_context() {
        let globals = Rc::new(TestGlobals {
            greeting: Signal::new("hello from registry".to_string()),
        });

        let mut registry: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        registry.insert(TypeId::of::<Rc<TestGlobals>>(), Box::new(globals.clone()));

        let mut tree = WidgetTree::new();
        tree.set_app_context(Rc::new(TreeAppContext::empty().with_app_state(registry)));

        let observed = Signal::new(String::new());
        let saw_none = Signal::new(false);
        tree.add(AppStateReader {
            observed: observed.clone(),
            saw_none: saw_none.clone(),
        });

        assert_eq!(observed.get(), "hello from registry");
        assert!(!saw_none.get());
    }

    #[test]
    fn app_state_missing_returns_none() {
        let mut tree = WidgetTree::new();
        // No app_state installed — tree has the empty default app context.

        let observed = Signal::new(String::new());
        let saw_none = Signal::new(false);
        tree.add(AppStateReader {
            observed: observed.clone(),
            saw_none: saw_none.clone(),
        });

        assert_eq!(observed.get(), "");
        assert!(saw_none.get());
    }

    #[test]
    fn app_state_distinct_types_coexist() {
        struct Alpha(u32);
        struct Beta(String);

        let mut registry: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        registry.insert(TypeId::of::<Rc<Alpha>>(), Box::new(Rc::new(Alpha(42))));
        registry.insert(
            TypeId::of::<Rc<Beta>>(),
            Box::new(Rc::new(Beta("beta!".to_string()))),
        );

        let ctx = TreeAppContext::empty().with_app_state(registry);
        assert_eq!(ctx.app_state::<Rc<Alpha>>().unwrap().0, 42);
        assert_eq!(ctx.app_state::<Rc<Beta>>().unwrap().0, "beta!");
        assert!(ctx.app_state::<Rc<u64>>().is_none());
    }

    /// **An event posted before a rebuild must still reach the widget after it.**
    ///
    /// A backend event crosses two thread boundaries and a queue: the source publishes
    /// on its own thread, the wrapper posts an `AppEvent::SubscriptionEvent` carrying
    /// the `SubscriptionId` it captured at *publish* time, and the UI thread dispatches
    /// it some frames later. A rebuild in that gap used to be fatal — `build()` runs
    /// again, allocates fresh ids, and the teardown in `rebuild_single_widget` removes
    /// the previous build's callbacks, so the queued event named a dead id and
    /// `dispatch_subscription_event` dropped it on the floor and returned `false`.
    ///
    /// ⚠ The window is **not** the microsecond between dropping the source handle and
    /// removing the callback, which is what that function's `§9.4.5` comment reasons
    /// about. It is the whole span from publish to dispatch, and a widget opens it on
    /// itself simply by binding a signal at `BindingLevel::Rebuild` and then setting
    /// that signal — the ordinary documented pattern. Skribisto's Analysis pane starts
    /// a long operation in `build()` and sets its own state signal to `Running`, so
    /// whenever the operation finished inside that gap the completion was lost and the
    /// pane sat on "Reading the manuscript…" for the rest of the session.
    #[test]
    fn an_event_posted_before_a_rebuild_still_reaches_the_widget() {
        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        // Posted now: the queued event carries the id minted by the first build.
        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "landed".to_string(),
            },
        );

        // …and the widget rebuilds before the UI thread gets to it. This is exactly
        // what a `BindingLevel::Rebuild` binding does when its signal changes.
        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(SizeProposal::exact(100.0, 100.0));

        drain_and_dispatch(&tree, &poster);

        assert_eq!(
            signal.get(),
            "landed",
            "the rebuild must not swallow an event that was already in flight"
        );
    }

    /// The same guarantee for the **context-bearing** API.
    ///
    /// `subscribe_event_with_ctx` keeps its callbacks in a second map and is dispatched
    /// by a different function, so it fails and has to be fixed separately from the
    /// plain path. It is also the API the framework documents as *the* bridge for
    /// long-operation progress, which is precisely the traffic this race eats.
    #[test]
    fn an_event_posted_before_a_rebuild_still_reaches_a_context_bearing_subscription() {
        use crate::window::NoopWindowOps;

        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let id = tree.add(CtxSubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "landed".to_string(),
            },
        );

        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // Dispatched the way teksilo-app's `try_dispatch_subscription_with_ctx` does,
        // from the queue the wrapper actually posted into.
        let app_ctx = tree.app_context().clone();
        let events = poster.drain();
        assert!(!events.is_empty(), "the source must have posted something");
        for (sub_id, event) in events {
            tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
                app_ctx.dispatch_subscription_event_with_ctx(sub_id, &*event, ctx);
            });
        }

        assert_eq!(
            signal.get(),
            "landed",
            "the ctx-bearing path must survive a rebuild too"
        );
    }

    /// A widget that is genuinely **destroyed** must not have its callback fired by a
    /// late event, and must not leave one behind. The fix above makes a subscription's
    /// identity outlive a rebuild; it must not make it outlive the widget.
    #[test]
    fn an_event_posted_before_a_destroy_fires_nothing_and_leaks_nothing() {
        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let signal = Signal::new(String::new());
        let id = tree.add(SubscribingWidget {
            origin: TestOrigin::Created,
            last_message: signal.clone(),
        });

        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "too late".to_string(),
            },
        );
        tree.destroy_subtree(id);
        drain_and_dispatch(&tree, &poster);

        assert_eq!(
            signal.get(),
            "",
            "a destroyed widget's callback must not run"
        );
        assert_eq!(
            tree.app_context().subscription_count(),
            0,
            "and nothing may be left behind in the callback map"
        );
    }

    /// The mirror of the case below: a rebuild that subscribes **more** times than the one
    /// before it re-uses what it can and allocates the rest.
    ///
    /// Worth its own test because the re-use is matched by position against a list that can
    /// simply run out. Reading one past its end has to mean "allocate", not panic and not
    /// silently re-use somebody else's id, and the extra subscription has to be a real live
    /// one rather than a slot that quietly went nowhere.
    #[test]
    fn a_rebuild_that_subscribes_more_reuses_what_it_can_and_allocates_the_rest() {
        /// Subscribes once on the first build and twice on every build after it.
        #[derive(Debug)]
        struct GrowingWidget {
            built: std::rc::Rc<std::cell::Cell<u32>>,
            first_message: Signal<String>,
            second_message: Signal<String>,
        }

        impl Widget for GrowingWidget {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                let first = self.built.get() == 0;
                self.built.set(self.built.get() + 1);
                let one = self.first_message.clone();
                ctx.subscribe_event(TestOrigin::Created, move |event: &TestEvent| {
                    one.set(event.message.clone());
                });
                if !first {
                    let two = self.second_message.clone();
                    ctx.subscribe_event(TestOrigin::Updated, move |event: &TestEvent| {
                        two.set(event.message.clone());
                    });
                }
                Vec::new()
            }

            fn layout_response(
                &self,
                proposal: SizeProposal,
                _ctx: &LayoutContext,
            ) -> crate::widget::LayoutResponse {
                proposal.resolve(0.0, 0.0).into()
            }
        }

        let mut tree = WidgetTree::new();
        let (source, poster) = install_source(&mut tree, MockEventSource::default());

        let built = std::rc::Rc::new(std::cell::Cell::new(0));
        let one = Signal::new(String::new());
        let two = Signal::new(String::new());
        let id = tree.add(GrowingWidget {
            built: built.clone(),
            first_message: one.clone(),
            second_message: two.clone(),
        });
        assert_eq!(tree.app_context().subscription_count(), 1);

        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(SizeProposal::exact(100.0, 100.0));
        assert_eq!(
            tree.app_context().subscription_count(),
            2,
            "the re-used slot plus a freshly allocated one"
        );
        assert_eq!(
            source.subscriber_count(),
            2,
            "and both are registered with the source, not just the re-used one"
        );

        // Both deliver, and neither is delivering the other's traffic.
        source.publish(
            TestOrigin::Created,
            TestEvent {
                id: 1,
                message: "to the first".to_string(),
            },
        );
        source.publish(
            TestOrigin::Updated,
            TestEvent {
                id: 2,
                message: "to the second".to_string(),
            },
        );
        drain_and_dispatch(&tree, &poster);

        assert_eq!(one.get(), "to the first");
        assert_eq!(
            two.get(),
            "to the second",
            "the newly allocated id must be live"
        );
    }

    /// A rebuild that subscribes **fewer** times than the one before it must not leave
    /// the surplus subscription live. Reusing a slot across a rebuild is only safe if a
    /// slot the new build did not claim is dropped.
    #[test]
    fn a_rebuild_that_subscribes_less_drops_the_surplus_subscription() {
        /// Subscribes twice on the first build and once on every build after it.
        #[derive(Debug)]
        struct ShrinkingWidget {
            built: std::rc::Rc<std::cell::Cell<u32>>,
        }

        impl Widget for ShrinkingWidget {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                let first = self.built.get() == 0;
                self.built.set(self.built.get() + 1);
                ctx.subscribe_event(TestOrigin::Created, |_event: &TestEvent| {});
                if first {
                    ctx.subscribe_event(TestOrigin::Updated, |_event: &TestEvent| {});
                }
                Vec::new()
            }

            fn layout_response(
                &self,
                proposal: SizeProposal,
                _ctx: &LayoutContext,
            ) -> crate::widget::LayoutResponse {
                proposal.resolve(0.0, 0.0).into()
            }
        }

        let mut tree = WidgetTree::new();
        let (source, _poster) = install_source(&mut tree, MockEventSource::default());

        let built = std::rc::Rc::new(std::cell::Cell::new(0));
        let id = tree.add(ShrinkingWidget {
            built: built.clone(),
        });
        assert_eq!(tree.app_context().subscription_count(), 2);
        assert_eq!(source.subscriber_count(), 2);

        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(SizeProposal::exact(100.0, 100.0));

        assert_eq!(
            tree.app_context().subscription_count(),
            1,
            "the second slot was not re-registered, so it must be gone"
        );
        assert_eq!(
            source.subscriber_count(),
            1,
            "and the source must not still be holding it"
        );
    }
}