muri 0.9.0

Menu Utilities for Rust Interfaces — a cross-platform, fully-styleable tray-icon and popup-menu system (a custom-drawn muda/tray-icon replacement).
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//! macOS backend: `NSStatusItem` tray anchor plus a native, non-activating
//! `NSPanel` popup driven directly by `NSApplication` (no winit / softbuffer).
//!
//! The status item's button is both the click target and the anchor rect. On
//! click the popup opens as a borderless `NSPanel` (see the `window` submodule)
//! whose content view hosts an `NSVisualEffectView` vibrancy backdrop under a
//! `CALayer` that the shared raster [`Framebuffer`](crate::render::Framebuffer)
//! is blitted to (see the
//! `present` submodule). Submenu rows open a second such panel (a flyout).
//!
//! ## Event model
//!
//! The app runs a native `NSApplication` run loop. Every AppKit callback (tray
//! click, mouse, keyboard, key-window changes, AccessKit actions) is tiny: it
//! translates the event and *enqueues* a `UiEvent`, then asks for a main-thread
//! drain via GCD. A single drain is the only place that mutates state, so
//! windows are never created or destroyed re-entrantly inside an AppKit event
//! dispatch. A [`TrayHandle`](crate::TrayHandle) posts its commands through the
//! same drain from any thread.
//!
//! ## Device-verified behaviors
//!
//! Focus-driven dismissal, keyboard nav on the key panel, VoiceOver traversal,
//! and vibrancy appearance require a real display + assistive tech; those spots
//! are marked `DEVICE-VERIFY(0.9.0)`. The architecture (native non-activating
//! panel, CALayer present, per-window a11y adapter) is complete and compiles.

#![allow(unsafe_code)]

mod input;
mod present;
mod window;

#[cfg(feature = "a11y")]
mod a11y;

use std::cell::RefCell;
use std::collections::HashSet;
use std::ffi::c_void;
use std::rc::Rc;

use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject};
use objc2::{define_class, msg_send, sel, AllocAnyThread, MainThreadMarker, MainThreadOnly};
use objc2_app_kit::{
    NSApplication, NSApplicationActivationPolicy, NSColor, NSColorSpace, NSEventMask, NSImage,
    NSScreen, NSStatusBar, NSStatusItem, NSVariableStatusItemLength,
};
use objc2_foundation::{NSData, NSPoint, NSRect, NSSize, NSString};

use crate::anchor::place_popup;
use crate::error::{Error, Result};
use crate::flyout::{next_flyout, place_flyout, HoverTarget};
use crate::geometry::{Edge, LogicalPoint, LogicalRect, LogicalSize};
use crate::keynav::{handle_key, FlyoutFocus, MenuFocus, NavAction, NavKey};
use crate::menu::{Icon, Item, Menu, MenuId};
use crate::platform::{Appearance, Platform};
use crate::render::paint::{render_menu, LaidMenu};
use crate::render::RasterDrawer;
use crate::style::Color;
use crate::theme::{MenuOptions, Theme, ThemeSource};
use crate::{Tray, TrayCommand};

use window::{make_panel, MuriView, MuriWindowDelegate};

// =============================================================================
// GCD main-queue dispatch (replaces the winit event-loop proxy)
// =============================================================================

extern "C" {
    /// The libdispatch main queue (`dispatch_get_main_queue()` is a macro over
    /// the address of this global).
    static _dispatch_main_q: c_void;
    fn dispatch_async_f(
        queue: *const c_void,
        context: *mut c_void,
        work: extern "C" fn(*mut c_void),
    );
}

/// The GCD callback: drain the queued UI events + tray commands on the main
/// thread. Never re-entrant (GCD serializes main-queue blocks), and it skips if
/// a drain is somehow already in flight — the queued work is picked up next.
extern "C" fn drain_trampoline(_ctx: *mut c_void) {
    let app = MAIN_APP.with(|slot| slot.borrow().clone());
    if let Some(app) = app {
        if let Ok(mut state) = app.try_borrow_mut() {
            state.drain();
        }
    }
}

/// Schedule a main-thread drain. Thread-safe: GCD accepts a main-queue dispatch
/// from any thread, which is exactly how a [`TrayHandle`](crate::TrayHandle) on
/// a worker thread pokes the run loop.
pub(super) fn defer_drain() {
    unsafe {
        dispatch_async_f(
            (&_dispatch_main_q as *const c_void).cast(),
            std::ptr::null_mut(),
            drain_trampoline,
        );
    }
}

// =============================================================================
// Thread-local run-loop state + event inbox
// =============================================================================

thread_local! {
    /// The single running [`AppState`], reachable from every main-thread AppKit
    /// callback and the GCD drain. Set once in [`run_tray`].
    static MAIN_APP: RefCell<Option<Rc<RefCell<AppState>>>> = const { RefCell::new(None) };

    /// Pending high-level UI events, pushed by AppKit callbacks and applied by
    /// the drain. Kept separate from [`AppState`] so callbacks never take an
    /// `AppState` borrow (which could alias the drain's).
    static EVENTS: RefCell<Vec<UiEvent>> = const { RefCell::new(Vec::new()) };
}

/// Enqueue a UI event and request a drain. Safe to call from any AppKit
/// callback; performs no [`AppState`] borrow.
pub(super) fn push_event(event: UiEvent) {
    EVENTS.with(|e| e.borrow_mut().push(event));
    defer_drain();
}

/// Which muri panel an event came from. Flyouts carry their **depth** on the open
/// stack (`0` = the first flyout, opened from the popup; `1` = its child; …) so a
/// callback can tag its events with the exact level without consulting shared
/// state (decision #8, N-level submenus).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum WindowKind {
    /// The top-level popup (anchored to the tray icon, a point, or a rect).
    Popup,
    /// An open submenu flyout at the given stack depth (`0` = first flyout).
    Flyout(usize),
}

impl WindowKind {
    /// The menu level this panel renders: `0` is the top-level menu, `k` the
    /// submenu reached by descending `k` open flyouts.
    fn menu_level(self) -> usize {
        match self {
            WindowKind::Popup => 0,
            WindowKind::Flyout(depth) => depth + 1,
        }
    }
}

/// A translated, backend-neutral UI event awaiting application on the drain.
pub(super) enum UiEvent {
    /// The tray icon button was clicked — toggle the popup.
    TrayClicked,
    /// The pointer moved over a panel (view-local top-left points).
    MouseMoved {
        /// Which panel.
        kind: WindowKind,
        /// X in the panel's logical points.
        x: f64,
        /// Y in the panel's logical points.
        y: f64,
    },
    /// A left mouse-down landed on a panel.
    MouseDown {
        /// Which panel.
        kind: WindowKind,
        /// X in the panel's logical points.
        x: f64,
        /// Y in the panel's logical points.
        y: f64,
    },
    /// A navigation key was pressed on the key panel.
    Key(NavKey),
    /// A panel gained or lost key-window status.
    FocusChanged {
        /// Which panel.
        kind: WindowKind,
        /// `true` on become-key, `false` on resign-key.
        key: bool,
    },
    /// An AccessKit action request (VoiceOver focus/activate) for a panel.
    #[cfg(feature = "a11y")]
    A11yAction {
        /// Which panel's adapter raised it.
        kind: WindowKind,
        /// The requested action.
        request: accesskit::ActionRequest,
    },
}

// =============================================================================
// Tray click target
// =============================================================================

define_class!(
    #[unsafe(super(NSObject))]
    #[name = "MuriTrayTarget"]
    #[thread_kind = MainThreadOnly]
    struct TrayTarget;

    impl TrayTarget {
        #[unsafe(method(trayClicked:))]
        fn tray_clicked(&self, _sender: Option<&AnyObject>) {
            push_event(UiEvent::TrayClicked);
        }
    }
);

impl TrayTarget {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        unsafe { msg_send![super(mtm.alloc::<Self>().set_ivars(())), init] }
    }
}

// =============================================================================
// NSStatusItem anchor
// =============================================================================

/// The macOS `NSStatusItem`-based anchor. Owns the status item and its click
/// target once installed, and removes the status item explicitly on drop.
pub struct MacosAnchor {
    mtm: MainThreadMarker,
    status_item: Option<Retained<NSStatusItem>>,
    // Kept alive so the button's (non-retaining) target isn't deallocated.
    _target: Option<Retained<TrayTarget>>,
}

impl std::fmt::Debug for MacosAnchor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MacosAnchor")
            .field("installed", &self.status_item.is_some())
            .finish()
    }
}

/// The status item's on-screen geometry, resolved against the *button's own*
/// screen so multi-monitor / notch-overflow placement is correct (spec 20 §2).
/// All the derived rectangles live in that screen's local, top-left logical
/// space; [`AnchorGeometry::to_screen`] converts back to AppKit's global,
/// bottom-left screen coordinates for window placement.
#[derive(Clone, Copy)]
struct AnchorGeometry {
    button_frame: NSRect,
    screen_frame: NSRect,
    visible_frame: NSRect,
    scale: f32,
}

impl AnchorGeometry {
    /// The status-item rect in the screen's local top-left space.
    fn anchor_rect_local(&self) -> LogicalRect {
        let sf = self.screen_frame;
        let bf = self.button_frame;
        let x = (bf.origin.x - sf.origin.x) as f32;
        let top = (sf.origin.y + sf.size.height - (bf.origin.y + bf.size.height)) as f32;
        LogicalRect::new(
            LogicalPoint::new(x, top),
            LogicalSize::new(bf.size.width as f32, bf.size.height as f32),
        )
    }

    /// The usable work area (excludes menu bar + Dock) in the same local space.
    fn work_area_local(&self) -> LogicalRect {
        let sf = self.screen_frame;
        let vf = self.visible_frame;
        let x = (vf.origin.x - sf.origin.x) as f32;
        let top = (sf.origin.y + sf.size.height - (vf.origin.y + vf.size.height)) as f32;
        LogicalRect::new(
            LogicalPoint::new(x, top),
            LogicalSize::new(vf.size.width as f32, vf.size.height as f32),
        )
    }

    /// Convert a local top-left origin (+ panel size) back to an AppKit global
    /// bottom-left screen point for `initWithContentRect:`.
    fn to_screen(self, origin: LogicalPoint, size: LogicalSize) -> NSPoint {
        let sf = self.screen_frame;
        let x = sf.origin.x + origin.x as f64;
        let y = sf.origin.y + sf.size.height - (origin.y as f64 + size.height as f64);
        NSPoint::new(x, y)
    }

    /// A fixed anchor `rect` (top-left logical, e.g. a zero-size rect at a
    /// pointer, or a toolbar-button rect), resolved against the main screen — the
    /// anchor geometry for a pointer/rect-anchored
    /// [`ContextMenu`](crate::ContextMenu) / [`Popup`](crate::Popup) that has no
    /// tray icon (spec 20 §3).
    ///
    // DEVICE-VERIFY(0.9.0): multi-monitor point resolution — this resolves the
    // rect against the *main* screen; a rect on a secondary display needs the
    // screen that actually contains it (same flip fragility as the tray anchor).
    fn for_rect(mtm: MainThreadMarker, rect: LogicalRect) -> Option<Self> {
        let screen = NSScreen::screens(mtm).firstObject()?;
        let sf = screen.frame();
        // Invert `anchor_rect_local`: a local top-left rect maps to a bottom-left
        // button frame on the main screen.
        let bf = NSRect::new(
            NSPoint::new(
                sf.origin.x + rect.origin.x as f64,
                sf.origin.y + sf.size.height - (rect.origin.y + rect.size.height) as f64,
            ),
            NSSize::new(rect.size.width as f64, rect.size.height as f64),
        );
        Some(AnchorGeometry {
            button_frame: bf,
            screen_frame: sf,
            visible_frame: screen.visibleFrame(),
            scale: screen.backingScaleFactor() as f32,
        })
    }
}

impl MacosAnchor {
    /// Create the (not-yet-installed) macOS anchor. Must be called on the main
    /// thread.
    pub fn new(mtm: MainThreadMarker) -> Self {
        MacosAnchor {
            mtm,
            status_item: None,
            _target: None,
        }
    }

    /// Set the status-item button's image from a muri [`Icon`]. PNG/SVG icons
    /// are decoded by AppKit; other kinds fall back to a text title.
    fn set_icon(&self, icon: &Icon, tooltip: Option<&str>) {
        let Some(item) = &self.status_item else {
            return;
        };
        let Some(button) = item.button(self.mtm) else {
            return;
        };
        match icon {
            Icon::Png(bytes) | Icon::Svg(bytes) => {
                let data = NSData::with_bytes(bytes);
                if let Some(image) =
                    NSImage::initWithData(NSImage::alloc(), &data).filter(|i| i.isValid())
                {
                    image.setSize(NSSize::new(18.0, 18.0));
                    button.setImage(Some(&image));
                } else {
                    button.setTitle(&NSString::from_str(""));
                }
            }
            _ => button.setTitle(&NSString::from_str("")),
        }
        if let Some(tip) = tooltip {
            button.setToolTip(Some(&NSString::from_str(tip)));
        }
    }

    /// Update the tooltip / accessible name of the status-item button.
    fn set_tooltip(&self, tooltip: Option<&str>) {
        if let Some(item) = &self.status_item {
            if let Some(button) = item.button(self.mtm) {
                button.setToolTip(tooltip.map(NSString::from_str).as_deref());
            }
        }
    }

    /// Show or hide the status item.
    fn set_visible(&self, visible: bool) {
        if let Some(item) = &self.status_item {
            item.setVisible(visible);
        }
    }

    /// Resolve the status item's geometry against the button's own screen.
    fn geometry(&self) -> Option<AnchorGeometry> {
        let item = self.status_item.as_ref()?;
        let button = item.button(self.mtm)?;
        let window = button.window()?;
        let screen = window
            .screen()
            .or_else(|| NSScreen::screens(self.mtm).firstObject())?;
        Some(AnchorGeometry {
            button_frame: window.frame(),
            screen_frame: screen.frame(),
            visible_frame: screen.visibleFrame(),
            scale: screen.backingScaleFactor() as f32,
        })
    }
}

impl MacosAnchor {
    fn install(&mut self, tooltip: Option<&str>) -> Result<()> {
        let status_bar = NSStatusBar::systemStatusBar();
        let item = status_bar.statusItemWithLength(NSVariableStatusItemLength);
        let target = TrayTarget::new(self.mtm);
        if let Some(button) = item.button(self.mtm) {
            unsafe {
                button.setTarget(Some(&target));
                button.setAction(Some(sel!(trayClicked:)));
            }
            if let Some(tip) = tooltip {
                button.setToolTip(Some(&NSString::from_str(tip)));
            }
        }
        self.status_item = Some(item);
        self._target = Some(target);
        Ok(())
    }

    fn anchor_rect(&self) -> Result<LogicalRect> {
        self.geometry()
            .map(|g| g.anchor_rect_local())
            .ok_or_else(|| Error::Platform("status item not installed".into()))
    }

    /// The logical work area of the monitor the tray anchor lives on.
    fn work_area(&self) -> Result<LogicalRect> {
        self.geometry()
            .map(|g| g.work_area_local())
            .ok_or_else(|| Error::Platform("status item not installed".into()))
    }
}

impl Drop for MacosAnchor {
    fn drop(&mut self) {
        // Explicit teardown (spec 20 §1): don't rely on ARC release alone.
        if let Some(item) = self.status_item.take() {
            NSStatusBar::systemStatusBar().removeStatusItem(&item);
        }
    }
}

// =============================================================================
// Panels + app state
// =============================================================================

/// A live popup or flyout panel: the native objects, the raster drawer that
/// paints it, and its current layout / hover / selection state.
struct Panel {
    panel: Retained<objc2_app_kit::NSPanel>,
    view: Retained<MuriView>,
    /// The window delegate is *not* retained by the panel, so we must keep it.
    #[allow(dead_code)]
    delegate: Retained<MuriWindowDelegate>,
    drawer: RasterDrawer,
    laid: Option<LaidMenu>,
    cursor: LogicalPoint,
    hovered: Option<usize>,
    /// Top-left origin in the anchor screen's local logical space.
    origin: LogicalPoint,
    scale: f32,
    #[cfg(feature = "a11y")]
    adapter: accesskit_macos::SubclassingAdapter,
    #[cfg(feature = "a11y")]
    snapshot: Rc<RefCell<a11y::A11ySnapshot>>,
}

impl Panel {
    fn order_out(&self) {
        self.panel.orderOut(None);
    }
}

/// One open flyout level: the row (within its parent level's menu) it opened
/// from, and its native panel. Level `k` of [`PopupSession::flyouts`] is panel
/// depth `k + 1` ([`WindowKind::Flyout`]) and its menu is
/// [`PopupSession::menu_at_level`]`(k + 1)`.
struct Flyout {
    /// Item index (within the parent level's menu) this flyout opened from.
    parent: usize,
    /// The flyout's native panel.
    panel: Panel,
}

/// Where a session's popup anchors: the live tray icon (which also owns icon /
/// tooltip / visibility) or a fixed rectangle for a pointer-anchored
/// [`ContextMenu`](crate::ContextMenu) / [`Popup`](crate::Popup) (spec 20 §3).
enum Anchor {
    /// The `NSStatusItem` tray anchor (its geometry follows the icon).
    Tray(MacosAnchor),
    /// A fixed anchor rectangle, resolved once against the main screen.
    Fixed(AnchorGeometry),
}

impl Anchor {
    /// The current anchor geometry (screen frames + scale + anchor rect).
    fn geometry(&self) -> Option<AnchorGeometry> {
        match self {
            Anchor::Tray(a) => a.geometry(),
            Anchor::Fixed(g) => Some(*g),
        }
    }
}

/// The shared popup machinery: the top-level popup, the **stack** of open flyout
/// panels (decision #8), the focus set that drives dismissal, and everything
/// needed to render/anchor them. [`Tray`], [`ContextMenu`](crate::ContextMenu),
/// and [`Popup`](crate::Popup) all drive one of these; they differ only in how the
/// anchor rectangle is obtained ([`Anchor`]) — spec 20 §3.
///
/// The click handler is stored as a `Box<dyn Fn + 'a>`: the tray uses a `'static`
/// handler owned for the whole run loop; a context menu borrows the caller's
/// handler for the duration of its blocking `open_at`/`anchored_to` call.
struct PopupSession<'a> {
    mtm: MainThreadMarker,
    /// The top-level menu; source of truth for rendering + a11y.
    menu: Menu,
    options: MenuOptions,
    /// Row-activation sink; dispatches the activated [`MenuId`].
    dispatch: Box<dyn Fn(&MenuId) + 'a>,
    /// How the popup anchors (tray icon or a fixed rect).
    anchor: Anchor,
    /// Which edge the popup grows from relative to its anchor.
    edge: Edge,
    popup: Option<Panel>,
    /// The open flyout window stack, shallowest first (decision #8).
    flyouts: Vec<Flyout>,
    /// Which muri panels currently hold key-window focus. The whole stack is
    /// dismissed only when this empties (and a resign armed it) — so opening a
    /// flyout, or focus transferring between our own panels, never self-closes.
    focused: HashSet<WindowKind>,
    /// Set when a resign-key left [`PopupSession::focused`] empty; checked after
    /// the drain so a paired become-key (a within-stack transfer) cancels it.
    dismiss_armed: bool,
}

impl PopupSession<'_> {
    /// The resolved theme for the current appearance, with the live OS accent
    /// injected (spec 20 §4c) so `Color::Accent` follows the system.
    fn theme(&self) -> Theme {
        let dark = self.options.theme.wants_dark(system_is_dark);
        let mut theme = self.options.theme.resolve_theme(dark);
        if matches!(self.options.theme, ThemeSource::FollowSystem) {
            if let Some((r, g, b, a)) = system_accent(self.mtm) {
                theme.accent = Color::Rgba(r, g, b, a);
            }
        }
        theme
    }

    /// The menu shown at the given level: `0` is the top-level menu, `k` the
    /// submenu reached by descending the first `k` open flyouts' parents. Returns
    /// `None` if a parent along the way is no longer a submenu.
    fn menu_at_level(&self, level: usize) -> Option<&Menu> {
        crate::menu::descend(
            &self.menu,
            self.flyouts.iter().take(level).map(|f| f.parent),
        )
    }

    fn panel(&self, kind: WindowKind) -> Option<&Panel> {
        match kind {
            WindowKind::Popup => self.popup.as_ref(),
            WindowKind::Flyout(d) => self.flyouts.get(d).map(|f| &f.panel),
        }
    }

    fn panel_mut(&mut self, kind: WindowKind) -> Option<&mut Panel> {
        match kind {
            WindowKind::Popup => self.popup.as_mut(),
            WindowKind::Flyout(d) => self.flyouts.get_mut(d).map(|f| &mut f.panel),
        }
    }

    /// The open-flyout parent stack ([`next_flyout`]'s representation).
    fn flyout_stack(&self) -> Vec<usize> {
        self.flyouts.iter().map(|f| f.parent).collect()
    }

    /// Rebuild the current keyboard/mouse selection from the panels' hovered rows.
    fn current_focus(&self) -> MenuFocus {
        MenuFocus {
            top: self.popup.as_ref().and_then(|p| p.hovered),
            flyout: self
                .flyouts
                .iter()
                .map(|f| FlyoutFocus {
                    parent: f.parent,
                    child: f.panel.hovered,
                })
                .collect(),
        }
    }

    // -- open / close --------------------------------------------------------

    fn open_popup(&mut self) {
        if self.popup.is_some() {
            return;
        }
        let theme = self.theme();
        let Some(geom) = self.anchor.geometry() else {
            return;
        };
        let scale = geom.scale.max(1.0);

        // Measure offscreen to size the panel before it exists (no resize flash).
        let mut probe = RasterDrawer::new(scale);
        let laid = render_menu(&mut probe, &self.menu, &theme, &self.options, None);

        let origin = place_popup(
            geom.anchor_rect_local(),
            laid.size,
            geom.work_area_local(),
            self.edge,
            2.0,
        );
        let screen_origin = geom.to_screen(origin, laid.size);
        let content_rect = NSRect::new(
            screen_origin,
            NSSize::new(laid.size.width as f64, laid.size.height as f64),
        );

        let native = make_panel(
            self.mtm,
            content_rect,
            theme.corner_radius,
            WindowKind::Popup,
        );

        #[cfg(feature = "a11y")]
        let snapshot = Rc::new(RefCell::new(a11y::A11ySnapshot {
            menu: self.menu.clone(),
            focus: MenuFocus {
                top: None,
                flyout: Vec::new(),
            },
        }));
        #[cfg(feature = "a11y")]
        let adapter = a11y::make_adapter(&native.view, Rc::clone(&snapshot), WindowKind::Popup);

        self.popup = Some(Panel {
            panel: native.panel,
            view: native.view,
            delegate: native.delegate,
            drawer: RasterDrawer::new(scale),
            laid: Some(laid),
            cursor: LogicalPoint::default(),
            hovered: None,
            origin,
            scale,
            #[cfg(feature = "a11y")]
            adapter,
            #[cfg(feature = "a11y")]
            snapshot,
        });

        // Paint the first frame, then reveal + take key. A NonactivatingPanel
        // becoming key does not deactivate the user's foreground app.
        self.redraw(WindowKind::Popup);
        if let Some(popup) = self.popup.as_ref() {
            popup.panel.makeKeyAndOrderFront(None);
        }
        self.sync_a11y();
    }

    /// Push a flyout for row `parent_index` of the currently deepest open level
    /// (the popup when no flyout is open), placed beside its parent panel by
    /// [`place_flyout`] (right by default, flipped left on spill — doc 10 §12).
    fn push_flyout(&mut self, parent_index: usize) {
        let depth = self.flyouts.len();
        // The level whose row we're opening from == the current deepest level.
        let Some(parent_menu) = self.menu_at_level(depth) else {
            return;
        };
        let Some(child) = (match parent_menu.items.get(parent_index) {
            Some(Item::Submenu { menu, .. }) => Some(menu.clone()),
            _ => None,
        }) else {
            return;
        };

        let (parent_origin, parent_size, scale, row_rect) = {
            let parent_panel = if depth == 0 {
                self.popup.as_ref()
            } else {
                self.flyouts.get(depth - 1).map(|f| &f.panel)
            };
            let Some(pp) = parent_panel else {
                return;
            };
            let Some(rect) = pp
                .laid
                .as_ref()
                .and_then(|l| l.rows.iter().find(|r| r.index == parent_index))
                .map(|r| r.rect)
            else {
                return;
            };
            (
                pp.origin,
                pp.laid.as_ref().map(|l| l.size).unwrap_or_default(),
                pp.scale,
                rect,
            )
        };

        let theme = self.theme();
        let Some(geom) = self.anchor.geometry() else {
            return;
        };
        let mut probe = RasterDrawer::new(scale);
        let child_laid = render_menu(&mut probe, &child, &theme, &self.options, None);

        let parent_rect = LogicalRect::new(parent_origin, parent_size);
        let placement = place_flyout(
            parent_rect,
            row_rect,
            child_laid.size,
            geom.work_area_local(),
        );
        let screen_origin = geom.to_screen(placement.origin, child_laid.size);
        let content_rect = NSRect::new(
            screen_origin,
            NSSize::new(child_laid.size.width as f64, child_laid.size.height as f64),
        );

        let kind = WindowKind::Flyout(depth);
        let native = make_panel(self.mtm, content_rect, theme.corner_radius, kind);

        #[cfg(feature = "a11y")]
        let snapshot = Rc::new(RefCell::new(a11y::A11ySnapshot {
            menu: child.clone(),
            focus: MenuFocus {
                top: None,
                flyout: Vec::new(),
            },
        }));
        #[cfg(feature = "a11y")]
        let adapter = a11y::make_adapter(&native.view, Rc::clone(&snapshot), kind);

        self.flyouts.push(Flyout {
            parent: parent_index,
            panel: Panel {
                panel: native.panel,
                view: native.view,
                delegate: native.delegate,
                drawer: RasterDrawer::new(scale),
                laid: None,
                cursor: LogicalPoint::default(),
                hovered: None,
                origin: placement.origin,
                scale,
                #[cfg(feature = "a11y")]
                adapter,
                #[cfg(feature = "a11y")]
                snapshot,
            },
        });
        // DEVICE-VERIFY(0.9.0): pre-insert the new flyout's focus id so opening a
        // deeper panel never momentarily empties the focus set and self-dismisses
        // (spec 20 §2, 40 §5). A real become-key would insert it too.
        self.focused.insert(kind);

        self.redraw(kind);
        // Order in front but do NOT take key from the popup: keyboard nav keeps
        // running through the key panel and the stack does not self-dismiss.
        if let Some(f) = self.flyouts.last() {
            f.panel.panel.orderFrontRegardless();
        }
        self.sync_a11y();
    }

    /// Close every flyout deeper than `len`, ordering their panels out.
    fn truncate_flyouts(&mut self, len: usize) {
        while self.flyouts.len() > len {
            let depth = self.flyouts.len() - 1;
            if let Some(f) = self.flyouts.pop() {
                f.panel.order_out();
            }
            self.focused.remove(&WindowKind::Flyout(depth));
        }
    }

    fn close_popup(&mut self) {
        self.truncate_flyouts(0);
        if let Some(popup) = self.popup.take() {
            popup.order_out();
        }
        self.focused.clear();
        self.dismiss_armed = false;
    }

    /// Reconcile the open flyout window stack to `target` (per-level parent
    /// indices, as produced by [`next_flyout`]): keep the common prefix, close
    /// anything deeper, then push the remaining levels.
    fn apply_flyout_stack(&mut self, target: &[usize]) {
        let mut common = 0;
        while common < target.len()
            && common < self.flyouts.len()
            && self.flyouts[common].parent == target[common]
        {
            common += 1;
        }
        self.truncate_flyouts(common);
        for &parent in &target[common..] {
            self.push_flyout(parent);
        }
    }

    // -- present -------------------------------------------------------------

    /// Re-render one panel from its level's menu + hovered row.
    fn redraw(&mut self, kind: WindowKind) {
        let theme = self.theme();
        let options = self.options.clone();
        // Borrow the level's menu from `self.menu`; the panel below is taken from
        // the disjoint `self.popup`/`self.flyouts` fields (not via `panel_mut`,
        // which would borrow all of `self`), so no clone is needed on redraw.
        let Some(menu) = crate::menu::descend(
            &self.menu,
            self.flyouts
                .iter()
                .take(kind.menu_level())
                .map(|f| f.parent),
        ) else {
            return;
        };
        let panel = match kind {
            WindowKind::Popup => self.popup.as_mut(),
            WindowKind::Flyout(d) => self.flyouts.get_mut(d).map(|f| &mut f.panel),
        };
        let Some(panel) = panel else {
            return;
        };
        let laid = render_menu(&mut panel.drawer, menu, &theme, &options, panel.hovered);
        if let Some(image) = present::framebuffer_to_cgimage(panel.drawer.framebuffer()) {
            present::set_layer_contents(&panel.view, &image, panel.scale);
        }
        panel.laid = Some(laid);
    }

    fn redraw_all(&mut self) {
        self.redraw(WindowKind::Popup);
        for d in 0..self.flyouts.len() {
            self.redraw(WindowKind::Flyout(d));
        }
    }

    // -- pointer -------------------------------------------------------------

    /// Handle a cursor move over `kind`: update its hovered row (repaint on
    /// change), then drive the flyout stack from the pure hover-stack rule.
    fn on_cursor(&mut self, kind: WindowKind, pt: LogicalPoint) {
        let (hovered, changed) = {
            let Some(p) = self.panel_mut(kind) else {
                return;
            };
            p.cursor = pt;
            let h = p.laid.as_ref().and_then(|l| l.hit(pt));
            let changed = h != p.hovered;
            if changed {
                p.hovered = h;
            }
            (h, changed)
        };
        if changed {
            self.redraw(kind);
        }
        let panel_depth = kind.menu_level();
        let level_menu = self.menu_at_level(panel_depth);
        let target = match hovered {
            Some(i)
                if level_menu
                    .is_some_and(|m| matches!(m.items.get(i), Some(Item::Submenu { .. }))) =>
            {
                HoverTarget::ParentRow {
                    panel: panel_depth,
                    index: i,
                }
            }
            Some(_) => HoverTarget::OtherRow { panel: panel_depth },
            None => HoverTarget::Outside,
        };
        let next = next_flyout(&self.flyout_stack(), target);
        self.apply_flyout_stack(&next);
        self.sync_a11y();
    }

    fn on_click(&mut self, kind: WindowKind) {
        let level = kind.menu_level();
        let Some(menu) = self.menu_at_level(level) else {
            return;
        };
        let (hit, id) = {
            let Some(p) = self.panel(kind) else {
                return;
            };
            (
                p.laid.as_ref().and_then(|l| l.hit(p.cursor)),
                p.laid.as_ref().and_then(|l| l.id_at(p.cursor)),
            )
        };
        if let Some(i) = hit {
            if matches!(menu.items.get(i), Some(Item::Submenu { .. })) {
                // Open (or switch to) this row's flyout, closing anything deeper.
                self.truncate_flyouts(level);
                self.push_flyout(i);
                return;
            }
        }
        if let Some(id) = id {
            if !id.is_none() {
                (self.dispatch)(&id);
            }
            self.close_popup();
        }
    }

    // -- keyboard ------------------------------------------------------------

    fn on_key_nav(&mut self, key: NavKey) {
        let mut focus = self.current_focus();
        let action = handle_key(&self.menu, &mut focus, key);
        if let Some(popup) = self.popup.as_mut() {
            popup.hovered = focus.top;
        }
        match action {
            NavAction::None => return,
            NavAction::Redraw => {}
            NavAction::OpenFlyout(i) => self.push_flyout(i),
            NavAction::CloseFlyout => {
                let keep = self.flyouts.len().saturating_sub(1);
                self.truncate_flyouts(keep);
            }
            NavAction::Activate(id) => {
                if !id.is_none() {
                    (self.dispatch)(&id);
                }
                self.close_popup();
                return;
            }
            NavAction::CloseAll => {
                self.close_popup();
                return;
            }
        }
        // Write the (possibly new) per-level child selections back into the
        // panels that still exist.
        for (k, f) in self.flyouts.iter_mut().enumerate() {
            if let Some(ff) = focus.flyout.get(k) {
                f.panel.hovered = ff.child;
            }
        }
        self.redraw_all();
        self.sync_a11y();
    }

    // -- accessibility -------------------------------------------------------

    #[cfg(feature = "a11y")]
    fn is_submenu_at_path(&self, path: &[usize]) -> bool {
        let mut menu = &self.menu;
        for (k, &idx) in path.iter().enumerate() {
            match menu.items.get(idx) {
                Some(Item::Submenu { menu: child, .. }) => {
                    if k + 1 == path.len() {
                        return true;
                    }
                    menu = child;
                }
                _ => return false,
            }
        }
        false
    }

    #[cfg(feature = "a11y")]
    fn menu_id_at_path(&self, path: &[usize]) -> Option<MenuId> {
        let mut menu = &self.menu;
        for (k, &idx) in path.iter().enumerate() {
            match menu.items.get(idx)? {
                Item::Row(row) if k + 1 == path.len() => return Some(row.id.clone()),
                Item::Submenu { menu: child, .. } => menu = child,
                _ => return None,
            }
        }
        None
    }

    /// Push a fresh `TreeUpdate` to every open panel's adapter (Option B: one
    /// per-window adapter per stack level — spec 30 §3). Each window's tree is
    /// its own level's menu; its focus is that window's selection, and any deeper
    /// open levels are carried as its expanded sub-stack.
    #[cfg(feature = "a11y")]
    fn sync_a11y(&mut self) {
        let full = self.current_focus();
        // `menu` closures below are only invoked when the panel's adapter is
        // active (an AT is listening), so the `Menu` clone is skipped entirely on
        // the hot hover/keynav path when nothing is attached (spec 30 §3).
        let root = &self.menu;
        if let Some(popup) = self.popup.as_mut() {
            a11y::sync(
                &mut popup.adapter,
                &popup.snapshot,
                || root.clone(),
                MenuFocus {
                    top: full.top,
                    flyout: full.flyout.clone(),
                },
            );
        }
        // Pre-collect the open flyouts' parent indices so each level's menu can be
        // borrowed from `self.menu` (via `descend`) while the matching panel in the
        // disjoint `self.flyouts` is mutably borrowed for its adapter.
        let parents: Vec<usize> = self.flyouts.iter().map(|f| f.parent).collect();
        for d in 0..self.flyouts.len() {
            let Some(menu) = crate::menu::descend(&self.menu, parents[..=d].iter().copied()) else {
                continue;
            };
            let top = full.flyout.get(d).and_then(|f| f.child);
            let sub: Vec<FlyoutFocus> = full.flyout.iter().skip(d + 1).copied().collect();
            if let Some(f) = self.flyouts.get_mut(d) {
                a11y::sync(
                    &mut f.panel.adapter,
                    &f.panel.snapshot,
                    || menu.clone(),
                    MenuFocus { top, flyout: sub },
                );
            }
        }
    }

    #[cfg(not(feature = "a11y"))]
    #[inline]
    fn sync_a11y(&mut self) {}

    #[cfg(feature = "a11y")]
    fn on_a11y_action(&mut self, kind: WindowKind, request: accesskit::ActionRequest) {
        let target = crate::a11y::AxId(request.target.0);
        let level = kind.menu_level();
        let Some(menu) = self.menu_at_level(level) else {
            return;
        };
        let tree = crate::a11y::build_tree(menu);
        let Some(rel_path) = crate::a11y::locate_path(&tree, target) else {
            return;
        };
        // Absolute path from the top-level menu = the parents that lead to this
        // window (levels 1..=level) followed by the in-window path.
        let mut abs: Vec<usize> = self.flyouts.iter().take(level).map(|f| f.parent).collect();
        abs.extend_from_slice(&rel_path);
        self.apply_a11y(&abs, request.action);
    }

    #[cfg(feature = "a11y")]
    fn apply_a11y(&mut self, abs: &[usize], action: accesskit::Action) {
        use accesskit::Action;
        if abs.is_empty() {
            return;
        }
        match action {
            Action::Focus => {
                // Open flyouts for every submenu ancestor along the path (all but
                // the final element), then select the final row in its window.
                let target = &abs[..abs.len() - 1];
                self.apply_flyout_stack(target);
                let final_kind = if target.is_empty() {
                    WindowKind::Popup
                } else {
                    WindowKind::Flyout(target.len() - 1)
                };
                if let (Some(&last), Some(p)) = (abs.last(), self.panel_mut(final_kind)) {
                    p.hovered = Some(last);
                }
                if let (Some(&first), Some(p)) = (abs.first(), self.popup.as_mut()) {
                    p.hovered = Some(first);
                }
                self.redraw_all();
                self.sync_a11y();
            }
            Action::Click => {
                if self.is_submenu_at_path(abs) {
                    self.apply_flyout_stack(abs);
                    if let (Some(&first), Some(p)) = (abs.first(), self.popup.as_mut()) {
                        p.hovered = Some(first);
                    }
                    self.sync_a11y();
                    return;
                }
                if let Some(id) = self.menu_id_at_path(abs) {
                    if !id.is_none() {
                        (self.dispatch)(&id);
                    }
                }
                self.close_popup();
            }
            _ => {}
        }
    }

    // -- drain ---------------------------------------------------------------

    fn apply_event(&mut self, event: UiEvent) {
        match event {
            UiEvent::TrayClicked => {
                if self.popup.is_some() {
                    self.close_popup();
                } else {
                    self.open_popup();
                }
            }
            UiEvent::MouseMoved { kind, x, y } => {
                self.on_cursor(kind, LogicalPoint::new(x as f32, y as f32));
            }
            UiEvent::MouseDown { kind, x, y } => {
                if let Some(p) = self.panel_mut(kind) {
                    p.cursor = LogicalPoint::new(x as f32, y as f32);
                }
                self.on_click(kind);
            }
            UiEvent::Key(key) => self.on_key_nav(key),
            UiEvent::FocusChanged { kind, key } => {
                if key {
                    self.focused.insert(kind);
                    self.dismiss_armed = false;
                } else {
                    self.focused.remove(&kind);
                    if self.focused.is_empty() {
                        self.dismiss_armed = true;
                    }
                }
            }
            #[cfg(feature = "a11y")]
            UiEvent::A11yAction { kind, request } => self.on_a11y_action(kind, request),
        }
    }

    /// After a drain, dismiss the whole stack iff a resign-key armed it and no
    /// muri panel regained focus. Returns whether it dismissed.
    fn finalize_dismiss(&mut self) -> bool {
        // DEVICE-VERIFY(0.9.0): focus-loss dismissal on a real display —
        // requires the non-activating panel's key transitions to fire as
        // expected across outside clicks and within-stack transfers.
        let dismissed = self.dismiss_armed && self.focused.is_empty() && self.popup.is_some();
        if dismissed {
            self.close_popup();
        }
        self.dismiss_armed = false;
        dismissed
    }
}

/// The tray's run-loop state: the shared [`PopupSession`] plus the tray icon /
/// tooltip / command bits specific to the persistent tray surface.
struct AppState {
    session: PopupSession<'static>,
    tray: Tray,
}

impl AppState {
    fn apply_command(&mut self, command: TrayCommand) {
        match command {
            TrayCommand::SetMenu(menu) => {
                self.tray.menu = menu.clone();
                self.session.menu = menu;
                if self.session.popup.is_some() {
                    // The structure may have changed under an open flyout; drop
                    // it, then repaint + refresh the a11y tree live.
                    self.session.truncate_flyouts(0);
                    self.session.redraw(WindowKind::Popup);
                    self.session.sync_a11y();
                }
            }
            TrayCommand::SetIcon(icon) => {
                self.tray.icon = icon;
                let icon = self.tray.icon.clone();
                let tooltip = self.tray.tooltip.clone();
                if let Anchor::Tray(a) = &self.session.anchor {
                    a.set_icon(&icon, tooltip.as_deref());
                }
            }
            TrayCommand::SetTooltip(tooltip) => {
                self.tray.tooltip = tooltip;
                if let Anchor::Tray(a) = &self.session.anchor {
                    a.set_tooltip(self.tray.tooltip.as_deref());
                }
            }
            TrayCommand::SetVisible(visible) => {
                if let Anchor::Tray(a) = &self.session.anchor {
                    a.set_visible(visible);
                }
            }
            TrayCommand::Open => {
                if self.session.popup.is_none() {
                    self.session.open_popup();
                }
            }
            TrayCommand::Close => self.session.close_popup(),
        }
    }

    /// Apply all pending commands and UI events, looping until both inboxes are
    /// empty (applying an event can enqueue more, e.g. a become-key). Then run the
    /// armed focus-loss dismissal check.
    fn drain(&mut self) {
        loop {
            let events = EVENTS.with(|e| std::mem::take(&mut *e.borrow_mut()));
            let commands: Vec<TrayCommand> = self
                .tray
                .commands
                .lock()
                .map(|mut q| std::mem::take(&mut *q))
                .unwrap_or_default();
            if events.is_empty() && commands.is_empty() {
                break;
            }
            for command in commands {
                self.apply_command(command);
            }
            for event in events {
                self.session.apply_event(event);
            }
        }
        self.session.finalize_dismiss();
    }
}

// =============================================================================
// Platform seam (ADR-0002)
// =============================================================================

/// The macOS [`Platform`] implementation: an `NSStatusItem` tray anchor plus the
/// native non-activating `NSPanel` popup + flyout event loop, the CALayer
/// present path, the per-window AccessKit adapter (behind `a11y`), and the
/// appearance/work-area queries. Every macOS-specific dependency (objc2,
/// objc2-quartz-core, objc2-core-graphics, accesskit_macos) lives in this module
/// behind the [`Platform`] trait — no AppKit type crosses the seam.
pub struct MacPlatform {
    mtm: Option<MainThreadMarker>,
    anchor: Option<MacosAnchor>,
}

impl Default for MacPlatform {
    fn default() -> Self {
        Self::new()
    }
}

impl MacPlatform {
    /// Create the macOS platform handle. Captures a [`MainThreadMarker`] if
    /// called on the main thread; the tray methods and [`Platform::run_tray`]
    /// error out otherwise.
    pub fn new() -> Self {
        MacPlatform {
            mtm: MainThreadMarker::new(),
            anchor: None,
        }
    }

    fn require_mtm(&self) -> Result<MainThreadMarker> {
        self.mtm
            .ok_or_else(|| Error::Platform("must be called on the main thread".into()))
    }
}

impl Platform for MacPlatform {
    fn install_tray(&mut self, icon: &Icon, tooltip: Option<&str>) -> Result<()> {
        let mtm = self.require_mtm()?;
        let mut anchor = MacosAnchor::new(mtm);
        anchor.install(tooltip)?;
        anchor.set_icon(icon, tooltip);
        self.anchor = Some(anchor);
        Ok(())
    }

    fn tray_anchor_rect(&self) -> Result<LogicalRect> {
        self.anchor
            .as_ref()
            .ok_or_else(|| Error::Platform("tray not installed".into()))?
            .anchor_rect()
    }

    fn supports_tray_anchor(&self) -> bool {
        true
    }

    fn appearance(&self) -> Appearance {
        Appearance::from_is_dark(system_is_dark())
    }

    fn work_area(&self) -> LogicalRect {
        self.anchor
            .as_ref()
            .and_then(|a| a.work_area().ok())
            .unwrap_or_else(|| {
                LogicalRect::new(LogicalPoint::new(0.0, 0.0), LogicalSize::new(1440.0, 900.0))
            })
    }

    fn run_tray(self, tray: Tray) -> Result<()> {
        run_event_loop(tray)
    }

    fn open_popup_session(
        &mut self,
        menu: Menu,
        options: MenuOptions,
        on_click: &(dyn Fn(&MenuId) + '_),
        anchor: LogicalRect,
        edge: Edge,
    ) -> Result<()> {
        let mtm = self.require_mtm()?;
        run_popup_session(mtm, menu, options, on_click, anchor, edge)
    }
}

/// Install the tray icon and run the native `NSApplication` loop, opening the
/// styled popup on click and dispatching row clicks to the tray's handler.
/// Consumes the [`Tray`]; returns when the loop exits.
fn run_event_loop(mut tray: Tray) -> Result<()> {
    let mtm = MainThreadMarker::new()
        .ok_or_else(|| Error::Platform("Tray::run must be called on the main thread".into()))?;

    // A tray-only native app is an Accessory: no Dock icon, no app menu bar
    // (spec 20 §5). The muda-compat menu-bar path chooses Regular elsewhere.
    let app = NSApplication::sharedApplication(mtm);
    app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);

    let mut anchor = MacosAnchor::new(mtm);
    anchor.install(tray.tooltip.as_deref())?;
    anchor.set_icon(&tray.icon, tray.tooltip.as_deref());

    // Install the TrayHandle waker so posts from any thread schedule a drain.
    if let Ok(mut waker) = tray.waker.lock() {
        *waker = Some(Box::new(defer_drain));
    }

    // Move the click handler into the session's dispatch sink (owned for the
    // whole run loop, hence `'static`).
    let dispatch: Box<dyn Fn(&MenuId) + 'static> = match tray.on_click.take() {
        Some(handler) => Box::new(move |id| handler(id)),
        None => Box::new(|_| {}),
    };
    let session = PopupSession {
        mtm,
        menu: tray.menu.clone(),
        options: tray.options.clone(),
        dispatch,
        anchor: Anchor::Tray(anchor),
        edge: Edge::Bottom,
        popup: None,
        flyouts: Vec::new(),
        focused: HashSet::new(),
        dismiss_armed: false,
    };

    let state = Rc::new(RefCell::new(AppState { session, tray }));
    MAIN_APP.with(|slot| *slot.borrow_mut() = Some(Rc::clone(&state)));

    // Apply any commands a handle posted before the loop came up.
    defer_drain();

    app.run();
    Ok(())
}

/// Run a pointer/rect-anchored [`ContextMenu`](crate::ContextMenu) /
/// [`Popup`](crate::Popup) session to completion (spec 20 §3): open the styled
/// popup at `anchor`, then pump AppKit events — draining muri UI events after each
/// — until the whole stack dismisses. Reuses the shared [`PopupSession`]; the only
/// difference from the tray is that the anchor is a fixed rect and the handler is
/// borrowed for the call rather than owned for a run loop.
///
/// Leaves the app's activation policy untouched (a context menu runs inside the
/// host's existing app — spec 20 §5, "neither surface installed").
fn run_popup_session(
    mtm: MainThreadMarker,
    menu: Menu,
    options: MenuOptions,
    on_click: &(dyn Fn(&MenuId) + '_),
    anchor: LogicalRect,
    edge: Edge,
) -> Result<()> {
    let app = NSApplication::sharedApplication(mtm);
    let geom = AnchorGeometry::for_rect(mtm, anchor)
        .ok_or_else(|| Error::Platform("no screen available for the popup".into()))?;

    let mut session = PopupSession {
        mtm,
        menu,
        options,
        dispatch: Box::new(move |id| on_click(id)),
        anchor: Anchor::Fixed(geom),
        edge,
        popup: None,
        flyouts: Vec::new(),
        focused: HashSet::new(),
        dismiss_armed: false,
    };
    session.open_popup();
    if session.popup.is_none() {
        return Err(Error::Platform("failed to open the popup window".into()));
    }

    // DEVICE-VERIFY(0.9.0): scoped modal event pump. Unlike the tray, this drives
    // the popup with a bounded `nextEventMatchingMask:` loop (no persistent run
    // loop, no GCD drain) so `open_at`/`anchored_to` can block on the caller's
    // stack and return when the menu dismisses. AppKit callbacks still enqueue
    // into the shared `EVENTS` inbox, which we drain here after each native event.
    loop {
        let event = app.nextEventMatchingMask_untilDate_inMode_dequeue(
            NSEventMask::Any,
            Some(&objc2_foundation::NSDate::distantFuture()),
            &objc2_foundation::NSString::from_str("kCFRunLoopDefaultMode"),
            true,
        );
        if let Some(event) = event {
            app.sendEvent(&event);
        }
        let events = EVENTS.with(|e| std::mem::take(&mut *e.borrow_mut()));
        for e in events {
            session.apply_event(e);
        }
        session.finalize_dismiss();
        if session.popup.is_none() {
            break;
        }
    }
    Ok(())
}

// =============================================================================
// System appearance
// =============================================================================

/// Query whether the system (menu-bar) appearance is currently dark.
fn system_is_dark() -> bool {
    let Some(mtm) = MainThreadMarker::new() else {
        return false;
    };
    let app = NSApplication::sharedApplication(mtm);
    let name = app.effectiveAppearance().name();
    name.to_string().to_lowercase().contains("dark")
}

/// Query the live OS accent color as straight-alpha RGBA, or `None` if it can't
/// be resolved. Fed into the theme's `accent` so `Color::Accent` follows the
/// system (spec 20 §4c).
fn system_accent(_mtm: MainThreadMarker) -> Option<(u8, u8, u8, u8)> {
    let accent = NSColor::controlAccentColor();
    let srgb = accent.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace())?;
    let to_u8 = |c: f64| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
    Some((
        to_u8(srgb.redComponent()),
        to_u8(srgb.greenComponent()),
        to_u8(srgb.blueComponent()),
        to_u8(srgb.alphaComponent()),
    ))
}

#[cfg(test)]
mod descend_tests {
    use crate::menu::{Item, Menu, Row};

    fn first_row_id(menu: &Menu) -> &str {
        match &menu.items[0] {
            Item::Row(row) => row.id.as_str(),
            other => panic!("expected a row, got {other:?}"),
        }
    }

    /// `menu_at_level`/`descend` must borrow nested submenus straight out of the
    /// source `Menu` (it runs on every redraw) rather than cloning the tree.
    #[test]
    fn descend_borrows_nested_submenus_without_cloning() {
        let grandchild = Menu::new().row(Row::new("c").label("C"));
        let child = Menu::new()
            .row(Row::new("b").label("B"))
            .submenu(Row::new("sub2").label("Sub2"), grandchild);
        let top = Menu::new()
            .row(Row::new("a").label("A"))
            .submenu(Row::new("sub1").label("Sub1"), child);

        // Level 0 is the top menu itself.
        assert_eq!(
            first_row_id(crate::menu::descend(&top, [0usize; 0]).unwrap()),
            "a"
        );
        // Descending the submenu at index 1 yields the child menu.
        assert_eq!(first_row_id(crate::menu::descend(&top, [1]).unwrap()), "b");
        // Two levels deep reaches the grandchild.
        assert_eq!(
            first_row_id(crate::menu::descend(&top, [1, 1]).unwrap()),
            "c"
        );
        // A non-submenu row on the path -> None.
        assert!(crate::menu::descend(&top, [0]).is_none());
        // An out-of-range index -> None.
        assert!(crate::menu::descend(&top, [9]).is_none());

        // The returned reference points *into* `top` (no clone).
        let borrowed = crate::menu::descend(&top, [1]).unwrap();
        let Item::Submenu { menu, .. } = &top.items[1] else {
            panic!("index 1 should be a submenu");
        };
        assert!(std::ptr::eq(borrowed, menu));
    }
}