mkgraphic 0.4.1

A Rust port of the cycfi/elements GUI framework
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
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
//! macOS platform implementation.
//!
//! This module provides the macOS-specific implementation using Cocoa/AppKit
//! through the objc2 crate.

#![cfg(target_os = "macos")]

use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::sync::Arc;

use block2::RcBlock;
use core::ptr::NonNull;
use core_graphics::color_space::CGColorSpace;
use core_graphics::context::CGContext;
use core_graphics::data_provider::CGDataProvider;
use core_graphics::image::CGImage;
use objc2::rc::Retained;
use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
use objc2_app_kit::{
    NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSAutoresizingMaskOptions,
    NSBackingStoreType, NSCursor, NSEvent, NSGraphicsContext, NSMenu, NSMenuItem,
    NSModalResponseOK, NSOpenPanel, NSPasteboard, NSSavePanel, NSView, NSWindow, NSWindowDelegate,
    NSWindowStyleMask,
};
use objc2_foundation::{
    MainThreadMarker, NSNotification, NSPoint, NSRect, NSSize, NSString, NSTimer,
};

use super::{CloseBehavior, Window};

use crate::element::context::Context;
use crate::element::ElementPtr;
use crate::support::canvas::Canvas;
use crate::support::color::Color;
use crate::support::point::{Extent, Point};
use crate::support::rect::Rect;
use crate::view::{modifiers, CursorType, KeyCode, MouseButton, MouseButtonKind, View};

/// Converts NSPoint to our Point type.
fn ns_point_to_point(p: NSPoint) -> Point {
    Point::new(p.x as f32, p.y as f32)
}

/// Converts our Point type to NSPoint.
fn point_to_ns_point(p: Point) -> NSPoint {
    NSPoint::new(p.x as f64, p.y as f64)
}

/// Converts NSSize to our Extent type.
fn ns_size_to_extent(s: NSSize) -> Extent {
    Extent::new(s.width as f32, s.height as f32)
}

/// Converts our Extent type to NSSize.
fn extent_to_ns_size(e: Extent) -> NSSize {
    NSSize::new(e.x as f64, e.y as f64)
}

/// Translates a macOS key code to our KeyCode enum.
pub fn translate_key(keycode: u16) -> KeyCode {
    match keycode {
        0x00 => KeyCode::A,
        0x01 => KeyCode::S,
        0x02 => KeyCode::D,
        0x03 => KeyCode::F,
        0x04 => KeyCode::H,
        0x05 => KeyCode::G,
        0x06 => KeyCode::Z,
        0x07 => KeyCode::X,
        0x08 => KeyCode::C,
        0x09 => KeyCode::V,
        0x0B => KeyCode::B,
        0x0C => KeyCode::Q,
        0x0D => KeyCode::W,
        0x0E => KeyCode::E,
        0x0F => KeyCode::R,
        0x10 => KeyCode::Y,
        0x11 => KeyCode::T,
        0x12 => KeyCode::Key1,
        0x13 => KeyCode::Key2,
        0x14 => KeyCode::Key3,
        0x15 => KeyCode::Key4,
        0x16 => KeyCode::Key6,
        0x17 => KeyCode::Key5,
        0x19 => KeyCode::Key9,
        0x1A => KeyCode::Key7,
        0x1C => KeyCode::Key8,
        0x1D => KeyCode::Key0,
        0x1F => KeyCode::O,
        0x20 => KeyCode::U,
        0x22 => KeyCode::I,
        0x23 => KeyCode::P,
        0x25 => KeyCode::L,
        0x26 => KeyCode::J,
        0x28 => KeyCode::K,
        0x2D => KeyCode::N,
        0x2E => KeyCode::M,
        0x24 => KeyCode::Enter,
        0x30 => KeyCode::Tab,
        0x31 => KeyCode::Space,
        0x33 => KeyCode::Backspace,
        0x35 => KeyCode::Escape,
        0x37 => KeyCode::LeftSuper,
        0x38 => KeyCode::LeftShift,
        0x39 => KeyCode::CapsLock,
        0x3A => KeyCode::LeftAlt,
        0x3B => KeyCode::LeftControl,
        0x3C => KeyCode::RightShift,
        0x3D => KeyCode::RightAlt,
        0x3E => KeyCode::RightControl,
        0x60 => KeyCode::F5,
        0x61 => KeyCode::F6,
        0x62 => KeyCode::F7,
        0x63 => KeyCode::F3,
        0x64 => KeyCode::F8,
        0x65 => KeyCode::F9,
        0x67 => KeyCode::F11,
        0x6D => KeyCode::F10,
        0x6F => KeyCode::F12,
        0x72 => KeyCode::Insert,
        0x73 => KeyCode::Home,
        0x74 => KeyCode::PageUp,
        0x75 => KeyCode::Delete,
        0x76 => KeyCode::F4,
        0x77 => KeyCode::End,
        0x78 => KeyCode::F2,
        0x79 => KeyCode::PageDown,
        0x7A => KeyCode::F1,
        0x7B => KeyCode::Left,
        0x7C => KeyCode::Right,
        0x7D => KeyCode::Down,
        0x7E => KeyCode::Up,
        _ => KeyCode::Unknown,
    }
}

/// Translates macOS modifier flags to our modifier bitmask.
pub fn translate_flags(flags: usize) -> i32 {
    let mut mods = 0i32;

    if flags & (1 << 17) != 0 {
        // NSEventModifierFlagShift
        mods |= modifiers::SHIFT;
    }
    if flags & (1 << 18) != 0 {
        // NSEventModifierFlagControl
        mods |= modifiers::CONTROL;
    }
    if flags & (1 << 19) != 0 {
        // NSEventModifierFlagOption (Alt)
        mods |= modifiers::ALT;
    }
    if flags & (1 << 20) != 0 {
        // NSEventModifierFlagCommand
        mods |= modifiers::SUPER;
    }
    if flags & (1 << 16) != 0 {
        // NSEventModifierFlagCapsLock
        mods |= modifiers::CAPS_LOCK;
    }

    mods
}

/// Sets the cursor type.
///
/// # Safety
/// This function calls Objective-C methods which require running on the main thread.
pub fn set_cursor(cursor: CursorType) {
    unsafe {
        match cursor {
            CursorType::Arrow => {
                let cursor = NSCursor::arrowCursor();
                cursor.set();
            }
            CursorType::IBeam => {
                let cursor = NSCursor::IBeamCursor();
                cursor.set();
            }
            CursorType::CrossHair => {
                let cursor = NSCursor::crosshairCursor();
                cursor.set();
            }
            CursorType::Hand => {
                let cursor = NSCursor::openHandCursor();
                cursor.set();
            }
            CursorType::HResize => {
                let cursor = NSCursor::resizeLeftRightCursor();
                cursor.set();
            }
            CursorType::VResize => {
                let cursor = NSCursor::resizeUpDownCursor();
                cursor.set();
            }
        }
    }
}

/// Gets the clipboard contents.
pub fn get_clipboard() -> String {
    unsafe {
        let _pasteboard = NSPasteboard::generalPasteboard();
        // Would need to read string from pasteboard
        String::new()
    }
}

/// Sets the clipboard contents.
pub fn set_clipboard(_text: &str) {
    unsafe {
        let _pasteboard = NSPasteboard::generalPasteboard();
        // Would need to write string to pasteboard
    }
}

/// Shows a native "choose a folder" panel (e.g. Open Project), optionally
/// starting in `initial_dir` (a sensible default the user can still
/// navigate away from, not a substitute for actually asking them). Blocks
/// the caller until the user picks a folder or cancels -- `runModal` pumps
/// its own modal run loop, which is the normal, expected way a native panel
/// works (every other Mac app blocks the same way), not a bug.
pub fn choose_folder(title: &str, initial_dir: Option<&std::path::Path>) -> Option<PathBuf> {
    let mtm = MainThreadMarker::new()?;
    unsafe {
        let panel = NSOpenPanel::openPanel(mtm);
        panel.setCanChooseDirectories(true);
        panel.setCanChooseFiles(false);
        panel.setAllowsMultipleSelection(false);
        panel.setTitle(Some(&NSString::from_str(title)));
        if let Some(dir) = initial_dir {
            let dir_str = NSString::from_str(&dir.display().to_string());
            panel.setDirectoryURL(Some(&objc2_foundation::NSURL::fileURLWithPath(&dir_str)));
        }
        if panel.runModal() != NSModalResponseOK {
            return None;
        }
        let urls = panel.URLs();
        url_to_path(urls.iter().next()?)
    }
}

/// Shows a native "open a file" panel, optionally restricted to the given
/// extensions (e.g. `&["rs"]`; empty allows any file).
pub fn choose_file_to_open(title: &str) -> Option<PathBuf> {
    let mtm = MainThreadMarker::new()?;
    unsafe {
        let panel = NSOpenPanel::openPanel(mtm);
        panel.setCanChooseDirectories(false);
        panel.setCanChooseFiles(true);
        panel.setAllowsMultipleSelection(false);
        panel.setTitle(Some(&NSString::from_str(title)));
        if panel.runModal() != NSModalResponseOK {
            return None;
        }
        let urls = panel.URLs();
        url_to_path(urls.iter().next()?)
    }
}

/// Shows a native "save as" panel, pre-filled with `default_name`.
pub fn choose_file_to_save(title: &str, default_name: &str) -> Option<PathBuf> {
    let mtm = MainThreadMarker::new()?;
    unsafe {
        let panel = NSSavePanel::savePanel(mtm);
        panel.setTitle(Some(&NSString::from_str(title)));
        panel.setNameFieldStringValue(&NSString::from_str(default_name));
        if panel.runModal() != NSModalResponseOK {
            return None;
        }
        let url = panel.URL()?;
        url_to_path(&url)
    }
}

unsafe fn url_to_path(url: &objc2_foundation::NSURL) -> Option<PathBuf> {
    Some(PathBuf::from(url.path()?.to_string()))
}

/// macOS application wrapper.
pub struct MacOSApp {
    app: Retained<NSApplication>,
    mtm: MainThreadMarker,
    // `NSApplication.delegate` is an unretained (`weak`-equivalent)
    // reference by convention, not a strong one, so nothing but us keeps
    // this instance alive once `setDelegate:` returns -- without holding it
    // here, it would be deallocated immediately and every subsequent
    // `applicationShouldTerminateAfterLastWindowClosed:`/
    // `applicationShouldHandleReopen:hasVisibleWindows:` call would land on
    // a dangling reference.
    delegate: RefCell<Option<Retained<MKAppDelegate>>>,
    // One `MenuActionTarget` per native menu item with an `on_select`
    // callback -- see that type's doc comment for why these must be kept
    // alive here rather than just handed to `setTarget` and forgotten.
    menu_action_targets: RefCell<Vec<Retained<MenuActionTarget>>>,
}

impl MacOSApp {
    /// Creates a new macOS application.
    pub fn new() -> Option<Self> {
        let mtm = MainThreadMarker::new()?;

        let app = NSApplication::sharedApplication(mtm);
        app.setActivationPolicy(NSApplicationActivationPolicy::Regular);

        let macos_app = Self {
            app,
            mtm,
            delegate: RefCell::new(None),
            menu_action_targets: RefCell::new(Vec::new()),
        };
        macos_app.setup_menu();

        Some(macos_app)
    }

    /// See [`super::CloseBehavior`] and [`super::App::set_close_behavior`].
    pub fn set_close_behavior(&self, behavior: CloseBehavior) {
        let (quit_on_last_window_closed, rebuild) = match behavior {
            CloseBehavior::QuitApp => (true, None),
            CloseBehavior::KeepRunning(rebuild) => (false, Some(rebuild)),
        };

        let delegate = MKAppDelegate::new(self.mtm, quit_on_last_window_closed, rebuild);
        self.app
            .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
        *self.delegate.borrow_mut() = Some(delegate);
    }

    /// Schedules `callback` on the main run loop: repeatedly, every
    /// `interval_secs` seconds, if `repeats` is true, or once after
    /// `interval_secs` otherwise. `NSApplication::run` (called from
    /// `MacOSApp::run`) pumps the main run loop in its default mode, which
    /// is exactly where `scheduledTimerWithTimeInterval:` attaches the
    /// timer, so no extra run-loop plumbing is needed here.
    ///
    /// The returned `Retained<NSTimer>` must be kept alive by the caller
    /// for exactly as long as the callback should keep firing: dropping it
    /// invalidates the timer (see `MacOSTimer`'s `Drop` impl in `mod.rs`).
    /// Simply dropping the `Retained<NSTimer>` on its own would NOT stop
    /// it, since the run loop keeps its own separate strong reference once
    /// scheduled -- that's exactly why the wrapper's `Drop` explicitly
    /// calls `invalidate()` rather than relying on refcounting.
    ///
    /// Every firing marks every open window's content view dirty
    /// afterward, regardless of whether the callback actually changed
    /// anything visible (see the redraw comment in this fn's body) --
    /// cheap for a small window, but a real, measured cost (confirmed via
    /// `ps` while building this) for a window with expensive content (a
    /// syntax-highlighting code editor, a large tree view, ...). Pick
    /// `interval_secs` with that in mind rather than defaulting to
    /// something very short "to be responsive": MKIDE settled on 0.5s for
    /// polling build output, which still feels live.
    pub fn schedule_timer(
        &self,
        interval_secs: f64,
        repeats: bool,
        callback: impl FnMut() + 'static,
    ) -> Retained<NSTimer> {
        let callback = RefCell::new(callback);
        let app = self.app.clone();
        let block = RcBlock::new(move |_timer: NonNull<NSTimer>| {
            (callback.borrow_mut())();

            // Timer-driven state changes (e.g. MKIDE polling a build task's
            // output into its log) don't go through any of the mouse/key/
            // scroll handlers that already call `setNeedsDisplay` after
            // handling an event -- without this, whatever the callback just
            // changed just sat there unrendered until some unrelated
            // interaction (a click, a scroll) incidentally repainted the
            // window. `NSApplication.windows` already enumerates every live
            // window, so no separate registry of views is needed here.
            for window in app.windows().iter() {
                if let Some(content_view) = window.contentView() {
                    unsafe { content_view.setNeedsDisplay(true) };
                }
            }
        });
        unsafe {
            NSTimer::scheduledTimerWithTimeInterval_repeats_block(interval_secs, repeats, &block)
        }
    }

    /// Sets up the application menu bar based on configuration or defaults.
    fn setup_menu(&self) {
        use crate::element::menu::get_native_menu_bar;

        // Check if there's a custom menu bar configuration
        let config = get_native_menu_bar().unwrap_or_default();

        // Dropped only after every old `NSMenuItem` referencing them is
        // itself replaced by `setMainMenu` below, so no menu item is ever
        // left pointing at a deallocated target.
        self.menu_action_targets.borrow_mut().clear();

        unsafe {
            let main_menu = NSMenu::new(self.mtm);

            // App menu (always included)
            if config.include_app_menu {
                self.add_app_menu(&main_menu);
            }

            // Custom menus (inserted before Edit)
            for custom_menu in &config.menus {
                self.add_custom_menu(&main_menu, custom_menu);
            }

            // Edit menu
            if config.include_edit_menu {
                self.add_edit_menu(&main_menu);
            }

            // Window menu
            if config.include_window_menu {
                self.add_window_menu(&main_menu);
            }

            self.app.setMainMenu(Some(&main_menu));
        }
    }

    /// Adds the standard app menu.
    unsafe fn add_app_menu(&self, main_menu: &NSMenu) {
        let app_menu_item = NSMenuItem::new(self.mtm);
        let app_menu = NSMenu::new(self.mtm);

        // About item
        let about_title = NSString::from_str("About");
        let about_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &about_title,
            Some(objc2::sel!(orderFrontStandardAboutPanel:)),
            &NSString::from_str(""),
        );
        app_menu.addItem(&about_item);

        app_menu.addItem(&NSMenuItem::separatorItem(self.mtm));

        // Services menu
        let services_title = NSString::from_str("Services");
        let services_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &services_title,
            None,
            &NSString::from_str(""),
        );
        let services_menu = NSMenu::initWithTitle(self.mtm.alloc(), &services_title);
        services_item.setSubmenu(Some(&services_menu));
        app_menu.addItem(&services_item);
        self.app.setServicesMenu(Some(&services_menu));

        app_menu.addItem(&NSMenuItem::separatorItem(self.mtm));

        // Hide item
        let hide_title = NSString::from_str("Hide");
        let hide_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &hide_title,
            Some(objc2::sel!(hide:)),
            &NSString::from_str("h"),
        );
        app_menu.addItem(&hide_item);

        // Hide Others item
        let hide_others_title = NSString::from_str("Hide Others");
        let hide_others_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &hide_others_title,
            Some(objc2::sel!(hideOtherApplications:)),
            &NSString::from_str("h"),
        );
        hide_others_item.setKeyEquivalentModifierMask(
            objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagCommand
                | objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagOption,
        );
        app_menu.addItem(&hide_others_item);

        // Show All item
        let show_all_title = NSString::from_str("Show All");
        let show_all_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &show_all_title,
            Some(objc2::sel!(unhideAllApplications:)),
            &NSString::from_str(""),
        );
        app_menu.addItem(&show_all_item);

        app_menu.addItem(&NSMenuItem::separatorItem(self.mtm));

        // Quit item
        let quit_title = NSString::from_str("Quit");
        let quit_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &quit_title,
            Some(objc2::sel!(terminate:)),
            &NSString::from_str("q"),
        );
        app_menu.addItem(&quit_item);

        app_menu_item.setSubmenu(Some(&app_menu));
        main_menu.addItem(&app_menu_item);
    }

    /// Adds the standard edit menu.
    unsafe fn add_edit_menu(&self, main_menu: &NSMenu) {
        let edit_menu_item = NSMenuItem::new(self.mtm);
        let edit_title = NSString::from_str("Edit");
        let edit_menu = NSMenu::initWithTitle(self.mtm.alloc(), &edit_title);

        // Undo
        let undo_title = NSString::from_str("Undo");
        let undo_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &undo_title,
            Some(objc2::sel!(undo:)),
            &NSString::from_str("z"),
        );
        edit_menu.addItem(&undo_item);

        // Redo
        let redo_title = NSString::from_str("Redo");
        let redo_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &redo_title,
            Some(objc2::sel!(redo:)),
            &NSString::from_str("Z"),
        );
        edit_menu.addItem(&redo_item);

        edit_menu.addItem(&NSMenuItem::separatorItem(self.mtm));

        // Cut
        let cut_title = NSString::from_str("Cut");
        let cut_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &cut_title,
            Some(objc2::sel!(cut:)),
            &NSString::from_str("x"),
        );
        edit_menu.addItem(&cut_item);

        // Copy
        let copy_title = NSString::from_str("Copy");
        let copy_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &copy_title,
            Some(objc2::sel!(copy:)),
            &NSString::from_str("c"),
        );
        edit_menu.addItem(&copy_item);

        // Paste
        let paste_title = NSString::from_str("Paste");
        let paste_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &paste_title,
            Some(objc2::sel!(paste:)),
            &NSString::from_str("v"),
        );
        edit_menu.addItem(&paste_item);

        // Select All
        let select_all_title = NSString::from_str("Select All");
        let select_all_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &select_all_title,
            Some(objc2::sel!(selectAll:)),
            &NSString::from_str("a"),
        );
        edit_menu.addItem(&select_all_item);

        edit_menu_item.setSubmenu(Some(&edit_menu));
        main_menu.addItem(&edit_menu_item);
    }

    /// Adds the standard window menu.
    unsafe fn add_window_menu(&self, main_menu: &NSMenu) {
        let window_menu_item = NSMenuItem::new(self.mtm);
        let window_title = NSString::from_str("Window");
        let window_menu = NSMenu::initWithTitle(self.mtm.alloc(), &window_title);

        // Minimize
        let minimize_title = NSString::from_str("Minimize");
        let minimize_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &minimize_title,
            Some(objc2::sel!(performMiniaturize:)),
            &NSString::from_str("m"),
        );
        window_menu.addItem(&minimize_item);

        // Zoom
        let zoom_title = NSString::from_str("Zoom");
        let zoom_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &zoom_title,
            Some(objc2::sel!(performZoom:)),
            &NSString::from_str(""),
        );
        window_menu.addItem(&zoom_item);

        window_menu.addItem(&NSMenuItem::separatorItem(self.mtm));

        // Bring All to Front
        let bring_all_title = NSString::from_str("Bring All to Front");
        let bring_all_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &bring_all_title,
            Some(objc2::sel!(arrangeInFront:)),
            &NSString::from_str(""),
        );
        window_menu.addItem(&bring_all_item);

        window_menu_item.setSubmenu(Some(&window_menu));
        main_menu.addItem(&window_menu_item);
        self.app.setWindowsMenu(Some(&window_menu));
    }

    /// Adds a custom menu from NativeMenu configuration.
    unsafe fn add_custom_menu(
        &self,
        main_menu: &NSMenu,
        custom_menu: &crate::element::menu::NativeMenu,
    ) {
        let menu_item = NSMenuItem::new(self.mtm);
        let title = NSString::from_str(&custom_menu.title);
        let ns_menu = NSMenu::initWithTitle(self.mtm.alloc(), &title);

        for item in &custom_menu.items {
            self.add_native_menu_item(&ns_menu, item);
        }

        menu_item.setSubmenu(Some(&ns_menu));
        main_menu.addItem(&menu_item);
    }

    /// Adds a native menu item to a menu.
    unsafe fn add_native_menu_item(
        &self,
        menu: &NSMenu,
        item: &crate::element::menu::NativeMenuItem,
    ) {
        if item.is_separator() {
            menu.addItem(&NSMenuItem::separatorItem(self.mtm));
            return;
        }

        let title = NSString::from_str(&item.label);
        let key_equiv = item
            .shortcut
            .as_ref()
            .map(|s| s.key.to_string())
            .unwrap_or_default();
        let key_str = NSString::from_str(&key_equiv);

        let ns_item = NSMenuItem::initWithTitle_action_keyEquivalent(
            self.mtm.alloc(),
            &title,
            None,
            &key_str,
        );

        // Wire the Rust `on_select` callback to a real AppKit target/action
        // -- a menu item with `action == nil` doesn't just silently do
        // nothing when clicked, `NSMenu`'s automatic item validation greys
        // it out entirely (an item AppKit can't validate/perform is
        // treated as unavailable), which is exactly what "buttons in the
        // Build menu are inactive" turned out to be. `target` is an
        // unretained reference by AppKit convention, hence keeping the
        // `MenuActionTarget` alive separately in `menu_action_targets`.
        if let Some(ref callback) = item.action {
            let target = MenuActionTarget::new(self.mtm, callback.clone());
            ns_item.setTarget(Some(&target));
            ns_item.setAction(Some(objc2::sel!(performMenuAction:)));
            self.menu_action_targets.borrow_mut().push(target);
        }

        // Set modifier mask if there's a shortcut
        if let Some(ref shortcut) = item.shortcut {
            let mut mask = objc2_app_kit::NSEventModifierFlags::empty();
            if shortcut.modifiers.command {
                mask |= objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagCommand;
            }
            if shortcut.modifiers.shift {
                mask |= objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagShift;
            }
            if shortcut.modifiers.option {
                mask |= objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagOption;
            }
            if shortcut.modifiers.control {
                mask |= objc2_app_kit::NSEventModifierFlags::NSEventModifierFlagControl;
            }
            ns_item.setKeyEquivalentModifierMask(mask);
        }

        // Set enabled state
        if !item.enabled {
            ns_item.setEnabled(false);
        }

        // Handle submenu
        if let Some(ref submenu_items) = item.submenu {
            let submenu_title = NSString::from_str(&item.label);
            let submenu = NSMenu::initWithTitle(self.mtm.alloc(), &submenu_title);
            for sub_item in submenu_items {
                self.add_native_menu_item(&submenu, sub_item);
            }
            ns_item.setSubmenu(Some(&submenu));
        }

        menu.addItem(&ns_item);
    }

    /// Runs the application event loop.
    pub fn run(&self) {
        unsafe {
            self.app.run();
        }
    }

    /// Stops the application.
    pub fn stop(&self) {
        self.app.stop(None);
    }
}

/// Ivars for [`MKAppDelegate`]. `RefCell`s rather than plain fields since
/// `declare_class!` methods only ever get `&self` (Objective-C has no
/// concept of Rust's exclusive borrows), matching every other stateful
/// `declare_class!` type in this file (e.g. `MKViewIvars`).
struct MKAppDelegateIvars {
    quit_on_last_window_closed: Cell<bool>,
    rebuild: RefCell<Option<Box<dyn Fn() -> Window>>>,
    // Holds whatever `rebuild` last produced, so it stays alive for as long
    // as the app keeps running instead of being dropped (and its native
    // window deallocated/closed) the instant `applicationShouldHandleReopen:
    // hasVisibleWindows:` returns.
    current_window: RefCell<Option<Window>>,
}

declare_class!(
    struct MKAppDelegate;

    unsafe impl ClassType for MKAppDelegate {
        type Super = NSObject;
        type Mutability = mutability::MainThreadOnly;
        const NAME: &'static str = "MKAppDelegate";
    }

    impl DeclaredClass for MKAppDelegate {
        type Ivars = MKAppDelegateIvars;
    }

    unsafe impl NSObjectProtocol for MKAppDelegate {}

    unsafe impl NSApplicationDelegate for MKAppDelegate {
        #[method(applicationShouldTerminateAfterLastWindowClosed:)]
        fn should_terminate_after_last_window_closed(&self, _sender: &NSApplication) -> bool {
            self.ivars().quit_on_last_window_closed.get()
        }

        #[method(applicationShouldHandleReopen:hasVisibleWindows:)]
        fn should_handle_reopen(&self, _sender: &NSApplication, has_visible_windows: bool) -> bool {
            if !has_visible_windows {
                let rebuilt = self.ivars().rebuild.borrow().as_ref().map(|rebuild| {
                    let mut window = rebuild();
                    window.show();
                    window
                });
                if let Some(window) = rebuilt {
                    *self.ivars().current_window.borrow_mut() = Some(window);
                }
            }
            true
        }
    }
);

impl MKAppDelegate {
    fn new(
        mtm: MainThreadMarker,
        quit_on_last_window_closed: bool,
        rebuild: Option<Box<dyn Fn() -> Window>>,
    ) -> Retained<Self> {
        let this = mtm.alloc::<Self>().set_ivars(MKAppDelegateIvars {
            quit_on_last_window_closed: Cell::new(quit_on_last_window_closed),
            rebuild: RefCell::new(rebuild),
            current_window: RefCell::new(None),
        });
        unsafe { msg_send_id![super(this), init] }
    }
}

/// `NSMenuItem.target` is an unretained (`weak`-equivalent) reference by
/// AppKit convention -- exactly the same reason `MacOSApp::delegate` above
/// holds `MKAppDelegate` itself. One of these exists per menu item that has
/// a Rust `on_select`/`action` callback; `MacOSApp::menu_action_targets`
/// keeps them alive for as long as the menu itself exists.
struct MenuActionTargetIvars {
    callback: Arc<dyn Fn() + Send + Sync>,
}

declare_class!(
    struct MenuActionTarget;

    unsafe impl ClassType for MenuActionTarget {
        type Super = NSObject;
        type Mutability = mutability::MainThreadOnly;
        const NAME: &'static str = "MKMenuActionTarget";
    }

    impl DeclaredClass for MenuActionTarget {
        type Ivars = MenuActionTargetIvars;
    }

    unsafe impl NSObjectProtocol for MenuActionTarget {}

    unsafe impl MenuActionTarget {
        #[method(performMenuAction:)]
        fn perform_menu_action(&self, _sender: &NSObject) {
            (self.ivars().callback)();
        }
    }
);

impl MenuActionTarget {
    fn new(mtm: MainThreadMarker, callback: Arc<dyn Fn() + Send + Sync>) -> Retained<Self> {
        let this = mtm
            .alloc::<Self>()
            .set_ivars(MenuActionTargetIvars { callback });
        unsafe { msg_send_id![super(this), init] }
    }
}

/// Backs [`MacOSWindow::on_focus`]. A plain `Box<dyn Fn()>` (not `Arc<dyn
/// Fn() + Send + Sync>` like `MenuActionTarget`'s callback) since a
/// window's focus callback is never shared across multiple native objects
/// the way one `on_select` callback can be reused for several menu items --
/// each window gets exactly one delegate.
struct WindowFocusDelegateIvars {
    callback: Box<dyn Fn()>,
}

declare_class!(
    struct WindowFocusDelegate;

    unsafe impl ClassType for WindowFocusDelegate {
        type Super = NSObject;
        type Mutability = mutability::MainThreadOnly;
        const NAME: &'static str = "MKWindowFocusDelegate";
    }

    impl DeclaredClass for WindowFocusDelegate {
        type Ivars = WindowFocusDelegateIvars;
    }

    unsafe impl NSObjectProtocol for WindowFocusDelegate {}

    unsafe impl NSWindowDelegate for WindowFocusDelegate {
        #[method(windowDidBecomeKey:)]
        fn window_did_become_key(&self, _notification: &NSNotification) {
            (self.ivars().callback)();
        }
    }
);

impl WindowFocusDelegate {
    fn new(mtm: MainThreadMarker, callback: Box<dyn Fn()>) -> Retained<Self> {
        let this = mtm
            .alloc::<Self>()
            .set_ivars(WindowFocusDelegateIvars { callback });
        unsafe { msg_send_id![super(this), init] }
    }
}

/// State for our custom view.
#[derive(Default)]
struct MKViewIvars {
    canvas: RefCell<Option<Canvas>>,
    content: RefCell<Option<ElementPtr>>,
    size: RefCell<Extent>,
}

declare_class!(
    struct MKView;

    unsafe impl ClassType for MKView {
        type Super = NSView;
        type Mutability = mutability::MainThreadOnly;
        const NAME: &'static str = "MKView";
    }

    impl DeclaredClass for MKView {
        type Ivars = MKViewIvars;
    }

    unsafe impl MKView {
        #[method(isFlipped)]
        fn is_flipped(&self) -> bool {
            true
        }

        #[method(acceptsFirstResponder)]
        fn accepts_first_responder(&self) -> bool {
            true
        }

        #[method(mouseDown:)]
        fn mouse_down(&self, event: &NSEvent) {
            self.handle_mouse_event(event, true);
        }

        #[method(mouseUp:)]
        fn mouse_up(&self, event: &NSEvent) {
            self.handle_mouse_event(event, false);
        }

        #[method(rightMouseDown:)]
        fn right_mouse_down(&self, event: &NSEvent) {
            self.handle_mouse_event(event, true);
        }

        #[method(rightMouseUp:)]
        fn right_mouse_up(&self, event: &NSEvent) {
            self.handle_mouse_event(event, false);
        }

        #[method(mouseDragged:)]
        fn mouse_dragged(&self, event: &NSEvent) {
            self.handle_mouse_drag(event);
        }

        #[method(rightMouseDragged:)]
        fn right_mouse_dragged(&self, event: &NSEvent) {
            self.handle_mouse_drag(event);
        }

        #[method(scrollWheel:)]
        fn scroll_wheel(&self, event: &NSEvent) {
            self.handle_scroll(event);
        }

        #[method(keyDown:)]
        fn key_down(&self, event: &NSEvent) {
            self.handle_key_event(event, true);
        }

        #[method(keyUp:)]
        fn key_up(&self, event: &NSEvent) {
            self.handle_key_event(event, false);
        }

        #[method(drawRect:)]
        fn draw_rect(&self, _dirty_rect: NSRect) {
            let ivars = self.ivars();

            // Get actual view frame size, in points
            let frame = self.frame();
            let size = Extent::new(frame.size.width as f32, frame.size.height as f32);
            *ivars.size.borrow_mut() = size;

            if size.x <= 0.0 || size.y <= 0.0 {
                return;
            }

            // Query the window's backing scale factor so we rasterize at
            // native resolution on HiDPI/Retina displays. Without this the
            // canvas is sized 1:1 with points and gets blurrily upscaled by
            // CoreGraphics when blitted onto a higher-density backing store.
            let scale: f32 = unsafe {
                let window_ptr: *mut objc2::runtime::AnyObject = objc2::msg_send![self, window];
                if window_ptr.is_null() {
                    1.0
                } else {
                    let factor: f64 = objc2::msg_send![window_ptr, backingScaleFactor];
                    factor as f32
                }
            };

            let pixel_width = (size.x * scale).round().max(1.0) as u32;
            let pixel_height = (size.y * scale).round().max(1.0) as u32;

            // Create or resize canvas at physical pixel resolution
            {
                let mut canvas_opt = ivars.canvas.borrow_mut();
                let needs_new = match &*canvas_opt {
                    Some(c) => c.width() != pixel_width || c.height() != pixel_height,
                    None => true,
                };
                if needs_new {
                    *canvas_opt = Canvas::new(pixel_width, pixel_height);
                }
            }

            // Draw content and blit to screen
            let mut canvas_opt = ivars.canvas.borrow_mut();
            if let Some(ref mut canvas) = *canvas_opt {
                // Clear with dark background
                canvas.clear(Color::new(0.2, 0.2, 0.2, 1.0));

                // Establish the HiDPI base scale so element drawing (which
                // operates entirely in logical points) rasterizes across the
                // full physical pixel resolution of the canvas.
                canvas.reset_transform();
                canvas.scale(scale, scale);

                // Draw elements if we have content
                let content_ref = ivars.content.borrow();
                if let Some(ref content) = *content_ref {
                    let bounds = Rect {
                        left: 0.0,
                        top: 0.0,
                        right: size.x,
                        bottom: size.y,
                    };

                    // Create a temporary view for the context
                    let mut temp_view = View::new(size);
                    temp_view.set_scale(scale);

                    // We need to temporarily move the canvas into a RefCell for the Context
                    // Take canvas out, wrap in RefCell, draw, then put back
                    let temp_canvas = std::mem::replace(canvas, Canvas::new(1, 1).unwrap());
                    let canvas_cell = RefCell::new(temp_canvas);

                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                    // Draw the content element
                    content.draw(&ctx);

                    // Get the canvas back
                    *canvas = canvas_cell.into_inner();
                }

                // Blit to screen. `size` (points) is the destination rect;
                // the canvas holds `pixel_width x pixel_height` physical
                // pixels, so CoreGraphics maps it 1:1 to device pixels.
                Self::blit_to_screen(canvas, size);
            }
        }
    }
);

impl MKView {
    fn new(mtm: MainThreadMarker, size: Extent) -> Retained<Self> {
        let frame = NSRect::new(
            NSPoint::new(0.0, 0.0),
            NSSize::new(size.x as f64, size.y as f64),
        );

        let this = mtm.alloc::<MKView>().set_ivars(MKViewIvars {
            canvas: RefCell::new(None),
            content: RefCell::new(None),
            size: RefCell::new(size),
        });

        unsafe { msg_send_id![super(this), initWithFrame: frame] }
    }

    fn set_content(&self, content: ElementPtr) {
        *self.ivars().content.borrow_mut() = Some(content);
        unsafe {
            self.setNeedsDisplay(true);
        }
    }

    fn set_size(&self, size: Extent) {
        *self.ivars().size.borrow_mut() = size;
    }

    fn handle_mouse_event(&self, event: &NSEvent, down: bool) {
        unsafe {
            // Get the mouse location in view coordinates
            let location_in_window = event.locationInWindow();
            let location = self.convertPoint_fromView(location_in_window, None);
            let pos = ns_point_to_point(location);

            // Determine which button
            let button_number = event.buttonNumber();
            let button_kind = match button_number {
                0 => MouseButtonKind::Left,
                1 => MouseButtonKind::Right,
                2 => MouseButtonKind::Middle,
                _ => MouseButtonKind::Left,
            };

            // Create MouseButton event
            let mouse_btn = MouseButton {
                down,
                click_count: event.clickCount() as i32,
                button: button_kind,
                modifiers: translate_flags(event.modifierFlags().bits()),
                pos,
            };

            // Forward to content element
            let ivars = self.ivars();
            let size = *ivars.size.borrow();
            let content_ref = ivars.content.borrow();

            if let Some(ref content) = *content_ref {
                let bounds = Rect {
                    left: 0.0,
                    top: 0.0,
                    right: size.x,
                    bottom: size.y,
                };

                // Create a dummy canvas for the context
                if let Some(dummy_canvas) = Canvas::new(1, 1) {
                    let canvas_cell = RefCell::new(dummy_canvas);
                    let temp_view = View::new(size);
                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                    // Clear focus from all elements on mouse down first. This
                    // ensures text boxes lose focus when clicking elsewhere -
                    // and, critically, runs *before* dispatching the click so
                    // that if the click lands on a focusable control (e.g. a
                    // TextBox), that control's own re-focus in handle_click
                    // below isn't immediately wiped out afterward.
                    if down {
                        content.clear_focus();
                    }

                    let handled = content.handle_click(&ctx, mouse_btn);

                    // Trigger redraw
                    self.setNeedsDisplay(true);
                }
            }
        }
    }

    fn handle_mouse_drag(&self, event: &NSEvent) {
        unsafe {
            let location_in_window = event.locationInWindow();
            let location = self.convertPoint_fromView(location_in_window, None);
            let pos = ns_point_to_point(location);

            let button_number = event.buttonNumber();
            let button_kind = match button_number {
                0 => MouseButtonKind::Left,
                1 => MouseButtonKind::Right,
                2 => MouseButtonKind::Middle,
                _ => MouseButtonKind::Left,
            };

            let mouse_btn = MouseButton {
                down: true,
                click_count: 1,
                button: button_kind,
                modifiers: translate_flags(event.modifierFlags().bits()),
                pos,
            };

            let ivars = self.ivars();
            let size = *ivars.size.borrow();

            // For drag, we need mutable access to the content
            // We use a RwLock pattern here through the ElementPtr (Arc<RwLock<dyn Element>>)
            let content_ref = ivars.content.borrow();
            if let Some(ref content) = *content_ref {
                let bounds = Rect {
                    left: 0.0,
                    top: 0.0,
                    right: size.x,
                    bottom: size.y,
                };

                if let Some(dummy_canvas) = Canvas::new(1, 1) {
                    let canvas_cell = RefCell::new(dummy_canvas);
                    let temp_view = View::new(size);
                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                    // Call handle_drag on the content (immutable version)
                    content.handle_drag(&ctx, mouse_btn);
                    self.setNeedsDisplay(true);
                }
            }
        }
    }

    fn handle_scroll(&self, event: &NSEvent) {
        unsafe {
            let location_in_window = event.locationInWindow();
            let location = self.convertPoint_fromView(location_in_window, None);
            let pos = ns_point_to_point(location);

            let delta_x = event.scrollingDeltaX() as f32;
            let delta_y = event.scrollingDeltaY() as f32;
            let dir = Point::new(delta_x, delta_y);

            let ivars = self.ivars();
            let size = *ivars.size.borrow();
            let content_ref = ivars.content.borrow();

            if let Some(ref content) = *content_ref {
                let bounds = Rect {
                    left: 0.0,
                    top: 0.0,
                    right: size.x,
                    bottom: size.y,
                };

                if let Some(dummy_canvas) = Canvas::new(1, 1) {
                    let canvas_cell = RefCell::new(dummy_canvas);
                    let temp_view = View::new(size);
                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                    if content.handle_scroll(&ctx, dir, pos) {
                        self.setNeedsDisplay(true);
                    }
                }
            }
        }
    }

    fn handle_key_event(&self, event: &NSEvent, down: bool) {
        unsafe {
            use crate::view::{KeyAction, KeyInfo};

            let keycode = event.keyCode();
            let key = translate_key(keycode);
            let modifiers = translate_flags(event.modifierFlags().bits());

            let action = if down {
                KeyAction::Press
            } else {
                KeyAction::Release
            };

            let key_info = KeyInfo {
                key,
                action,
                modifiers,
            };

            let ivars = self.ivars();
            let size = *ivars.size.borrow();
            let content_ref = ivars.content.borrow();

            if let Some(ref content) = *content_ref {
                let bounds = Rect {
                    left: 0.0,
                    top: 0.0,
                    right: size.x,
                    bottom: size.y,
                };

                if let Some(dummy_canvas) = Canvas::new(1, 1) {
                    let canvas_cell = RefCell::new(dummy_canvas);
                    let temp_view = View::new(size);
                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                    if content.handle_key(&ctx, key_info) {
                        self.setNeedsDisplay(true);
                    }
                }
            }

            // Also handle text input for keyDown events
            if down {
                if let Some(characters) = event.characters() {
                    let text: String = characters.to_string();
                    if !text.is_empty() {
                        for c in text.chars() {
                            // Skip control characters
                            if c.is_control() && c != '\n' && c != '\t' {
                                continue;
                            }

                            let text_info = crate::view::TextInfo {
                                codepoint: c,
                                modifiers,
                            };

                            let content_ref = ivars.content.borrow();
                            if let Some(ref content) = *content_ref {
                                let bounds = Rect {
                                    left: 0.0,
                                    top: 0.0,
                                    right: size.x,
                                    bottom: size.y,
                                };

                                if let Some(dummy_canvas) = Canvas::new(1, 1) {
                                    let canvas_cell = RefCell::new(dummy_canvas);
                                    let temp_view = View::new(size);
                                    let ctx = Context::new(&temp_view, &canvas_cell, bounds);

                                    if content.handle_text(&ctx, text_info) {
                                        self.setNeedsDisplay(true);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Blits `canvas` (rasterized at physical pixel resolution) into the
    /// current graphics context, scaled to fit `logical_size` (in points).
    /// On HiDPI displays the canvas holds more pixels than there are points,
    /// so this maps 1:1 to device pixels instead of upscaling a 1x bitmap.
    fn blit_to_screen(canvas: &Canvas, logical_size: Extent) {
        unsafe {
            // Get the current graphics context
            let Some(ns_ctx) = NSGraphicsContext::currentContext() else {
                return;
            };

            // Get the CGContextRef - use graphicsPort for compatibility
            // (CGContext property returns an objc2 type that doesn't match)
            let cg_ctx_ptr: *mut std::ffi::c_void = objc2::msg_send![&ns_ctx, graphicsPort];
            if cg_ctx_ptr.is_null() {
                return;
            }

            let pixel_width = canvas.width();
            let pixel_height = canvas.height();

            // Get pixmap data - tiny-skia stores premultiplied RGBA
            let pixmap = canvas.pixmap();
            let data = pixmap.data();

            // Create CGImage from our pixmap
            let color_space = CGColorSpace::create_device_rgb();
            let provider = CGDataProvider::from_slice(data);

            // tiny-skia uses premultiplied RGBA in native byte order
            // On macOS (little-endian), we need:
            // kCGImageAlphaPremultipliedLast (1) = RGBA with premultiplied alpha
            // kCGBitmapByteOrderDefault (0) = native byte order
            // Combined: just 1 for standard RGBA premultiplied
            let cg_image = CGImage::new(
                pixel_width as usize,
                pixel_height as usize,
                8,
                32,
                pixel_width as usize * 4,
                &color_space,
                1, // kCGImageAlphaPremultipliedLast (RGBA order)
                &provider,
                false,
                0, // kCGRenderingIntentDefault
            );

            // Destination rect is in points, not pixels - CoreGraphics scales
            // the (higher-resolution) image to fill it.
            let rect = core_graphics::geometry::CGRect::new(
                &core_graphics::geometry::CGPoint::new(0.0, 0.0),
                &core_graphics::geometry::CGSize::new(logical_size.x as f64, logical_size.y as f64),
            );

            let cg_ctx = CGContext::from_existing_context_ptr(cg_ctx_ptr as *mut _);

            // Flip the context to match our top-left origin coordinate system
            // Core Graphics has origin at bottom-left, we need top-left
            cg_ctx.save();
            cg_ctx.translate(0.0, logical_size.y as f64);
            cg_ctx.scale(1.0, -1.0);
            cg_ctx.draw_image(rect, &cg_image);
            cg_ctx.restore();
        }
    }
}

/// macOS window wrapper.
pub struct MacOSWindow {
    window: Retained<NSWindow>,
    mk_view: Retained<MKView>,
    view: Option<View>,
    // `NSWindow.delegate` is unretained by AppKit convention (same
    // reasoning as `MacOSApp::delegate`/`menu_action_targets`), so nothing
    // else keeps this alive once `on_focus` sets it.
    focus_delegate: RefCell<Option<Retained<WindowFocusDelegate>>>,
}

impl MacOSWindow {
    /// Creates a new macOS window with the default style (closable,
    /// miniaturizable, resizable).
    pub fn new(title: &str, size: Extent, mtm: MainThreadMarker) -> Self {
        Self::new_with_style(title, size, super::WindowStyle::default(), mtm)
    }

    /// Creates a new macOS window honoring `style`'s flags -- `Window::new`
    /// (via `MacOSWindow::new` above) always used a hardcoded style mask
    /// regardless of what a `WindowBuilder` was configured with, so e.g.
    /// `.style(WindowStyle { resizable: false, .. })` silently had no
    /// effect on macOS; this is what `Window::new_with_options` now calls
    /// instead so that configuration actually applies.
    pub fn new_with_style(
        title: &str,
        size: Extent,
        style: super::WindowStyle,
        mtm: MainThreadMarker,
    ) -> Self {
        let frame = NSRect::new(NSPoint::new(0.0, 0.0), extent_to_ns_size(size));

        let style = if style.borderless {
            NSWindowStyleMask::Borderless
        } else {
            let mut mask = NSWindowStyleMask::Titled;
            if style.closable {
                mask |= NSWindowStyleMask::Closable;
            }
            if style.miniaturizable {
                mask |= NSWindowStyleMask::Miniaturizable;
            }
            if style.resizable {
                mask |= NSWindowStyleMask::Resizable;
            }
            mask
        };

        let window = unsafe {
            NSWindow::initWithContentRect_styleMask_backing_defer(
                mtm.alloc(),
                frame,
                style,
                NSBackingStoreType::NSBackingStoreBuffered,
                false,
            )
        };

        let title_str = NSString::from_str(title);
        window.setTitle(&title_str);
        window.center();

        // Create our custom view
        let mk_view = MKView::new(mtm, size);
        // Without this, dragging the window's edge resizes the *window*
        // but leaves this content view pinned at its original construction
        // size in the bottom-left corner (NSView's default
        // autoresizingMask is `NotSizable`) -- so widgets never actually
        // re-laid-out on resize, since `drawRect:`'s `self.frame()` read
        // (which is otherwise correctly live -- see `MKView::draw_rect`)
        // never changed either. `WidthSizable | HeightSizable` makes
        // AppKit stretch this view's frame to track the window's content
        // rect on every resize, which is what actually makes the already-
        // correct per-frame `self.frame()` read (and this session's earlier
        // `VTile`/`HTile`/`ScrollView` resize-cache fixes) take effect.
        unsafe {
            mk_view.setAutoresizingMask(
                NSAutoresizingMaskOptions::NSViewWidthSizable
                    | NSAutoresizingMaskOptions::NSViewHeightSizable,
            );
        }
        window.setContentView(Some(&mk_view));

        Self {
            window,
            mk_view,
            view: Some(View::new(size)),
            focus_delegate: RefCell::new(None),
        }
    }

    /// Calls `callback` whenever this window becomes the key (frontmost,
    /// receiving-input) window -- e.g. MKIDE uses this so its native menu
    /// bar's Save/Build/Run/Test/Debug commands act on whichever open
    /// project's window is currently focused, the same way switching
    /// windows in any multi-window Mac app changes what the menu bar's
    /// commands apply to.
    pub fn on_focus(&self, callback: impl Fn() + 'static) {
        let Some(mtm) = MainThreadMarker::new() else {
            return;
        };
        let delegate = WindowFocusDelegate::new(mtm, Box::new(callback));
        self.window
            .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
        *self.focus_delegate.borrow_mut() = Some(delegate);
    }

    /// Shows the window.
    pub fn show(&self) {
        self.window.makeKeyAndOrderFront(None);
    }

    /// Hides the window.
    pub fn hide(&self) {
        self.window.orderOut(None);
    }

    /// Closes the window.
    pub fn close(&self) {
        self.window.close();
    }

    /// Sets the window title.
    pub fn set_title(&self, title: &str) {
        let title_str = NSString::from_str(title);
        self.window.setTitle(&title_str);
    }

    /// Returns the window size.
    pub fn size(&self) -> Extent {
        let frame = self.window.frame();
        ns_size_to_extent(frame.size)
    }

    /// Sets the window size.
    pub fn set_size(&self, size: Extent) {
        let mut frame = self.window.frame();
        frame.size = extent_to_ns_size(size);
        self.window.setFrame_display(frame, true);
        self.mk_view.set_size(size);
    }

    /// Sets the window content.
    pub fn set_content(&self, content: ElementPtr) {
        self.mk_view.set_content(content);
    }

    /// Returns a reference to the view.
    pub fn view(&self) -> Option<&View> {
        self.view.as_ref()
    }

    /// Returns a mutable reference to the view.
    pub fn view_mut(&mut self) -> Option<&mut View> {
        self.view.as_mut()
    }

    /// Triggers a redraw.
    pub fn refresh(&self) {
        unsafe {
            self.mk_view.setNeedsDisplay(true);
        }
    }

    /// Returns the raw `NSWindow*` pointer, for embedding externally-managed
    /// native content (e.g. a caller-owned content view rendered by another
    /// library) into this window instead of using mkgraphic's own element
    /// tree for it.
    ///
    /// The returned pointer is valid for as long as this `MacOSWindow` is
    /// alive; the caller does not gain ownership (mkgraphic still manages
    /// the window's lifetime).
    pub fn native_window_handle(&self) -> *mut std::ffi::c_void {
        Retained::as_ptr(&self.window) as *mut std::ffi::c_void
    }
}