rust_widgets 2.8.4

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Native AppKit FFI wrappers for the macOS objc2 backend (BLUE11 R1.5/R2.3 100%).
//!
//! This module is gated behind `#[cfg(target_os = "macos")]` and the
//! `objc2-macos` feature flag.
//!
//! # The presentation path
//!
//! `macos_objc2` is a self-drawn backend: every `WidgetKind` is painted by
//! `src/widget/`, so the only native object it needs is a **surface** that pulls
//! one RGBA frame out of [`crate::widget::runtime`] and blits it. That surface is
//! [`RustWidgetsObjc2CanvasView`], an `NSView` subclass whose `drawRect:` mirrors
//! `macos/canvas.rs::draw_rect` for the sibling cocoa backend.
//!
//! Without it `MacOSObjc2Platform::supports_surfaces()` promised a presentation
//! path that did not exist: `mount_surface` recorded bookkeeping and no pixels
//! ever reached the screen.

#![cfg(target_os = "macos")]
#![cfg(feature = "macos")]
// objc2 init methods may require unsafe blocks depending on platform
#![allow(unused_unsafe)]

use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::sel;
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
use objc2_app_kit::{
    NSApplication, NSApplicationActivationPolicy, NSBackingStoreType, NSEvent, NSEventMask,
    NSGraphicsContext, NSView, NSWindow, NSWindowStyleMask,
};
use objc2_core_graphics::CGContext;
use objc2_foundation::{NSDate, NSDefaultRunLoopMode, NSNotification, NSRect, NSSize, NSString};

use crate::core::{ObjectId, Point};
use crate::event::Event;
use crate::platform::types::MousePhase;

use std::collections::HashMap;
use std::sync::LazyLock;
use std::sync::Mutex;

/// Wrapper around `*mut c_void` that implements `Send`.
///
/// `Send` is required because the pointer is stored in a process-global
/// `Mutex<HashMap<..>>` (the registry lives in a `LazyLock` static).
///
/// `Sync` is deliberately NOT implemented: AppKit objects are owned by the
/// main thread, and an `unsafe impl Sync` would additionally permit `&NativePtr`
/// to be shared across threads, removing the compiler's last guard against
/// off-main AppKit access. Every native entry point still re-checks the thread
/// before messaging AppKit (see `check_apple_thread_safety.sh`), and keeping the
/// bound narrow means a future helper that forgets that check has a smaller
/// unsafe surface to slip through.
#[derive(Clone, Copy)]
struct NativePtr(*mut std::ffi::c_void);
unsafe impl Send for NativePtr {}

/// Thread-local storage for native widget handles.
static NATIVE_VIEWS: LazyLock<Mutex<HashMap<u64, NativePtr>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

static PENDING_NATIVE_RELEASES: LazyLock<Mutex<Vec<NativePtr>>> =
    LazyLock::new(|| Mutex::new(Vec::new()));

/// Side table from a mounted surface id to its canvas view pointer.
///
/// Distinct from [`NATIVE_VIEWS`], which holds the window (or control) a widget id
/// was created as. A *surface* is the drawing view mounted **onto** that window, so
/// `resize_surface` / `invalidate_surface` / `unmount_surface` need to find it by
/// the id passed to [`mount_surface_native`] independently of the window registry.
static SURFACE_VIEWS: LazyLock<Mutex<HashMap<u64, NativePtr>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// Returns whether the calling thread is the AppKit main thread.
///
/// Every native entry point in this module re-checks this before messaging
/// AppKit. It is exported so `platform_impl` can choose the documented state-only
/// fallback off the main thread rather than mistaking "AppKit is unreachable" for
/// "the surface failed to mount".
pub(crate) fn on_main_thread() -> bool {
    MainThreadMarker::new().is_some()
}

pub(crate) fn store_native_view(widget_id: u64, view: *mut std::ffi::c_void) {
    if view.is_null() {
        return;
    }
    remove_native_view(widget_id);
    unsafe {
        let object = view as *mut AnyObject;
        let _: *mut AnyObject = msg_send![object, retain];
    }
    NATIVE_VIEWS.lock().unwrap().insert(widget_id, NativePtr(view));
}

pub(crate) fn remove_native_view(widget_id: u64) {
    let removed = NATIVE_VIEWS.lock().unwrap().remove(&widget_id);
    if let Some(ptr) = removed {
        unsafe {
            let object = ptr.0 as *mut AnyObject;
            // Detach from the superview first. A parent view retains whatever was
            // added as its subview, and that reference is NOT balanced by the
            // registry's `retain`/`release` pair — so releasing only the registry
            // reference left the object alive and owned by the parent forever
            // (a create/destroy UI churn grew RSS by ~6 KB per widget, without
            // bound). `removeFromSuperview` drops the parent's reference, which
            // is what actually lets the object deallocate.
            let has_superview: bool =
                msg_send![object, respondsToSelector: sel!(removeFromSuperview)];
            if has_superview {
                let _: () = msg_send![object, removeFromSuperview];
            }
            let _: () = msg_send![object, release];
        }
    }
}

/// Returns whether `object` is (or descends from) `NSWindow`.
///
/// Used by [`destroy_native_handle`] to decide between closing a window and
/// detaching a plain view: `removeFromSuperview` on an `NSWindow` does nothing
/// useful and never takes it off screen, so a logically destroyed window could
/// stay visible.
unsafe fn object_is_window(object: *mut AnyObject) -> bool {
    let window_class = <NSWindow as objc2::ClassType>::class();
    let is_window: bool = msg_send![object, isKindOfClass: window_class];
    is_window
}

/// What [`destroy_native_handle`] did (or could not do).
///
/// The caller must be able to tell "there was no native object" (its bookkeeping
/// is the only thing to drop) from "there was one but AppKit is main-thread-only
/// and we are not on it" (the bookkeeping must be **kept** so a later main-thread
/// call can finish). A plain `bool` collapsed the two and let an off-main destroy
/// report success while the window stayed on screen (D08-P-02).
pub(crate) enum NativeDestroyOutcome {
    /// A native object was found and torn down.
    Destroyed,
    /// No native object was ever created for this id (a state-only widget).
    NoNativeObject,
    /// AppKit refused: not the main thread. The registry entry is **kept** so the
    /// teardown can be retried on the main thread.
    RefusedOffMainThread,
}

/// Destroys a native handle created by this backend.
///
/// A **window** is closed with `close` (which hides and releases the window's
/// AppKit resources); any other view is detached with `removeFromSuperview`.
/// Both run only on the main thread — off it, AppKit must not be messaged, so the
/// call logs and reports [`NativeDestroyOutcome::RefusedOffMainThread`] and the
/// caller keeps the bookkeeping it had.
pub(crate) fn destroy_native_handle(widget_id: u64) -> NativeDestroyOutcome {
    if MainThreadMarker::new().is_none() {
        log::error!(
            "[macos-objc2] destroy_handle: refused off the AppKit main thread (id={widget_id})"
        );
        return NativeDestroyOutcome::RefusedOffMainThread;
    }
    let removed = NATIVE_VIEWS.lock().unwrap().remove(&widget_id);
    let Some(ptr) = removed else {
        // No native object was ever created for this id (a state-only widget), so
        // there is nothing to tear down and the caller's bookkeeping stands.
        return NativeDestroyOutcome::NoNativeObject;
    };
    unsafe {
        let object = ptr.0 as *mut AnyObject;
        if object_is_window(object) {
            // `close`, not `orderOut:`: `close` is the symmetric counterpart of
            // `makeKeyAndOrderFront:`, releasing the window and its views. An
            // `orderOut:` alone would hide it but leave the object retained.
            let _: () = msg_send![object, close];
        } else {
            let _: () = msg_send![object, removeFromSuperview];
        }
        let _: () = msg_send![object, release];
    }
    NativeDestroyOutcome::Destroyed
}

fn release_closed_window(host_id: u64) {
    if MainThreadMarker::new().is_none() {
        log::error!(
            "[macos-objc2] close_window: refused off the AppKit main thread (id={host_id})"
        );
        return;
    }
    let removed = NATIVE_VIEWS.lock().unwrap().remove(&host_id);
    if let Some(ptr) = removed {
        PENDING_NATIVE_RELEASES.lock().unwrap().push(ptr);
    }
}

fn drain_pending_native_releases() {
    let pending = std::mem::take(&mut *PENDING_NATIVE_RELEASES.lock().unwrap());
    for ptr in pending {
        unsafe {
            let object = ptr.0 as *mut AnyObject;
            let _: () = msg_send![object, release];
        }
    }
}

fn make_rect(x: i32, y: i32, width: u32, height: u32) -> NSRect {
    NSRect::new(
        objc2_foundation::NSPoint::new(x as f64, y as f64),
        NSSize::new(width.max(1) as f64, height.max(1) as f64),
    )
}

// ---------------------------------------------------------------------------
// Canvas view: the presentation path
// ---------------------------------------------------------------------------

/// Instance variables of [`RustWidgetsObjc2CanvasView`].
///
/// The widget id is stored in an ivar rather than an associated object because
/// `define_class!` finalises the ivar layout at class-registration time, which is
/// exactly the point of the macro — the id travels with the view for the view's
/// whole lifetime, including the `drawRect:` calls AppKit makes from its own
/// display machinery.
pub(crate) struct CanvasIvars {
    /// Registry id of the widget this view presents.
    widget_id: std::cell::Cell<u64>,
    /// `true` when this canvas is a window's content view, so `drawRect:` paints
    /// the window **and its descendants** rather than one mounted box.
    is_window: std::cell::Cell<bool>,
}

define_class!(
    // SAFETY:
    // - `NSView` has no subclassing requirements beyond using the designated
    //   initializer, which `init_with_frame` performs.
    // - `RustWidgetsObjc2CanvasView` does not implement `Drop`; the ivar is a
    //   `Cell<u64>`, which needs no release.
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "RustWidgetsObjc2CanvasView"]
    #[ivars = CanvasIvars]
    pub(crate) struct RustWidgetsObjc2CanvasView;

    impl RustWidgetsObjc2CanvasView {
        /// `drawRect:` — pull one RGBA frame from the widget runtime and blit it.
        ///
        /// Mirrors `macos/canvas.rs::draw_rect`: the size comes from `bounds`, not
        /// from the dirty rectangle AppKit passes, because a partial invalidation
        /// hands a rect smaller than the view and sizing the frame from it would
        /// stretch the image into the wrong place.
        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, _dirty_rect: NSRect) {
            // A panic must not unwind through AppKit: a foreign exception cannot
            // cross the Objective-C frame, so it is caught and logged here.
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.blit_frame();
            }));
            if outcome.is_err() {
                log::error!("[macos-objc2] canvas: panic while drawing a self-drawn widget");
            }
        }

        /// The view uses AppKit's native coordinate system, so a frame buffer's
        /// top-left origin lands at the view's top-left after the blit flips rows.
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            false
        }

        /// The canvas owns the keyboard while it hosts the focused widget, so it must
        /// accept first-responder status — otherwise AppKit never delivers `keyDown:`.
        #[unsafe(method(acceptsFirstResponder))]
        fn accepts_first_responder(&self) -> bool {
            true
        }

        #[unsafe(method(mouseDown:))]
        fn mouse_down(&self, event: &NSEvent) {
            self.forward_mouse(event, MousePhase::Press);
        }

        #[unsafe(method(mouseUp:))]
        fn mouse_up(&self, event: &NSEvent) {
            self.forward_mouse(event, MousePhase::Release);
        }

        #[unsafe(method(mouseDragged:))]
        fn mouse_dragged(&self, event: &NSEvent) {
            self.forward_mouse(event, MousePhase::Drag);
        }

        #[unsafe(method(rightMouseDown:))]
        fn right_mouse_down(&self, event: &NSEvent) {
            self.forward_mouse(event, MousePhase::SecondaryPress);
        }

        #[unsafe(method(rightMouseUp:))]
        fn right_mouse_up(&self, event: &NSEvent) {
            self.forward_mouse(event, MousePhase::SecondaryRelease);
        }

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

        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &NSEvent) {
            self.forward_key(event, false);
        }

        #[unsafe(method(keyUp:))]
        fn key_up(&self, event: &NSEvent) {
            self.forward_key(event, true);
        }

        /// AppKit calls this on the window's content view when the window is resized.
        ///
        /// The superclass call performs the resize; the library is then told the new
        /// client size so layout re-runs — otherwise a user drag of the window edge
        /// changed the pixels but never the widget geometry.
        #[unsafe(method(setFrameSize:))]
        fn set_frame_size(&self, new_size: NSSize) {
            // SAFETY: `super` is the documented objc2 spelling for messaging the
            // superclass implementation; `setFrameSize:` is the NSView setter.
            let _: () = unsafe { msg_send![super(self), setFrameSize: new_size] };
            #[cfg(widgets_unstripped)]
            if let Some(widget_id) = self.widget_target() {
                crate::queue_resize_trigger(
                    widget_id,
                    new_size.width.round().max(1.0) as u32,
                    new_size.height.round().max(1.0) as u32,
                );
            }
        }

        /// The window delegate hook for the close button: emit the widget's `closed`
        /// signal (so `on_close` handlers run), then allow AppKit to close the window.
        #[unsafe(method(windowShouldClose:))]
        fn window_should_close(&self, _window: &NSWindow) -> bool {
            #[cfg(widgets_unstripped)]
            if let Some(widget_id) = self.widget_target() {
                let _ = crate::close_widget(widget_id);
            }
            true
        }

        #[unsafe(method(windowWillClose:))]
        fn window_will_close(&self, _notification: &NSNotification) {
            let host_id = self.ivars().widget_id.get();
            if host_id != 0 {
                release_closed_window(host_id);
            }
        }
    }
);

impl RustWidgetsObjc2CanvasView {
    /// Renders one frame for the carried widget id and draws it into the view's
    /// current CoreGraphics context.
    fn blit_frame(&self) {
        let widget_id = self.ivars().widget_id.get();
        if widget_id == 0 {
            log::error!("[macos-objc2] canvas: drawRect: on a view with no widget id");
            return;
        }
        // The size comes from `bounds`, not the dirty rect (see `draw_rect`).
        let bounds = self.bounds();
        let width = bounds.size.width.round().max(1.0) as u32;
        let height = bounds.size.height.round().max(1.0) as u32;
        let clear = crate::core::Color::WHITE;
        let size = crate::core::Size::new(width, height);

        #[cfg(widgets_unstripped)]
        let frame = if self.ivars().is_window.get() {
            // The window canvas stores the **host** id `create_window` returned (the
            // `BackendState` counter starts at 1), while `render_frame_tree` looks the
            // widget up by its **widget-registry** id (allocated from a far higher
            // base). Translate at this boundary so the frame targets the correct
            // widget instead of missing it and painting nothing.
            let Some(widget) = crate::widget::runtime::widget_id_for_host_window(widget_id) else {
                log::error!(
                    "[macos-objc2] canvas: drawRect: host id={widget_id} has no owning widget; \
                     nothing to paint"
                );
                return;
            };
            // A window's content view paints the window's own chrome and every child
            // that implements `Draw`; a plain `render_frame_cached` would show the
            // window over an empty client area.
            crate::widget::runtime::render_frame_tree(widget, size, clear)
        } else {
            // A mounted surface is one self-drawn widget in its own box, which is
            // what the cocoa backend's `draw_rect` blits.
            crate::widget::runtime::render_frame_cached(widget_id, size, clear)
        };
        #[cfg(widgets_unstripped)]
        let Some(frame) = frame
        else {
            // Not mounted (dropped while the view survived) or it refused to paint.
            log::error!(
                "[macos-objc2] canvas: drawRect: widget id={widget_id} produced no frame \
                 (unmounted, or it does not implement Draw)"
            );
            return;
        };
        #[cfg(not(widgets_unstripped))]
        {
            // A stripped profile has no `widget::runtime`, so there is no frame to
            // pull. Log the reason rather than shipping a silent blank view.
            log::error!(
                "[macos-objc2] canvas: drawRect: widget id={widget_id} cannot render in a \
                 profile without an unstripped widget set"
            );
            return;
        }

        let Some(context) = NSGraphicsContext::currentContext() else {
            log::error!(
                "[macos-objc2] canvas: drawRect: +[NSGraphicsContext currentContext] was nil"
            );
            return;
        };
        let cg_context = context.CGContext();
        if !blit_rgba(&cg_context, width, height, &frame) {
            log::error!("[macos-objc2] canvas: drawRect: blit failed for {width}x{height}");
        }
    }

    /// Allocates a canvas view for `widget_id` sized to `frame`, on the main thread.
    ///
    /// `is_window` selects tree rendering (a window paints its children) over the
    /// single-box rendering a mounted surface uses.
    ///
    /// The ivars are installed before `initWithFrame:`, which is the two-phase
    /// initialisation `define_class!` expects.
    pub(crate) fn new(
        mtm: MainThreadMarker,
        widget_id: u64,
        is_window: bool,
        frame: NSRect,
    ) -> Retained<Self> {
        let this = mtm.alloc::<Self>().set_ivars(CanvasIvars {
            widget_id: std::cell::Cell::new(widget_id),
            is_window: std::cell::Cell::new(is_window),
        });
        // SAFETY: `this` is an allocated instance with its ivars initialised, and
        // `initWithFrame:` is the designated initializer of `NSView`.
        unsafe { msg_send![super(this), initWithFrame: frame] }
    }

    /// The widget-registry id this canvas presents.
    ///
    /// A window canvas stores the **host** id `create_window` returned; a mounted
    /// surface stores the widget id directly. The event router and the frame lookup
    /// both speak the widget-registry id, so the window case translates here.
    #[cfg(widgets_unstripped)]
    fn widget_target(&self) -> Option<ObjectId> {
        let id = self.ivars().widget_id.get();
        if id == 0 {
            return None;
        }
        if self.ivars().is_window.get() {
            crate::widget::runtime::widget_id_for_host_window(id)
        } else {
            Some(id)
        }
    }

    /// Translates an AppKit mouse event into a widget event and routes it.
    #[cfg(widgets_unstripped)]
    fn forward_mouse(&self, event: &NSEvent, phase: MousePhase) {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let Some(widget_id) = self.widget_target() else {
                return;
            };
            let local = self.convertPoint_fromView(event.locationInWindow(), None);
            let origin = self.frame().origin;
            let position = Point::new(
                (origin.x + local.x).round() as i32,
                (origin.y + local.y).round() as i32,
            );
            let modifiers =
                crate::platform::macos::types::map_modifiers(event.modifierFlags().bits() as u64);
            let translated = match phase {
                MousePhase::Press => Event::mouse_press_with(
                    position.x,
                    position.y,
                    crate::event::mouse_button::PRIMARY,
                    modifiers,
                ),
                MousePhase::Release => Event::MouseRelease {
                    pos: position,
                    button: crate::event::mouse_button::PRIMARY,
                },
                MousePhase::Drag => Event::MouseMove { pos: position },
                MousePhase::SecondaryPress => Event::mouse_press_with(
                    position.x,
                    position.y,
                    crate::event::mouse_button::SECONDARY,
                    modifiers,
                ),
                MousePhase::SecondaryRelease => Event::MouseRelease {
                    pos: position,
                    button: crate::event::mouse_button::SECONDARY,
                },
                MousePhase::DoubleClick => Event::mouse_double_click(
                    position.x,
                    position.y,
                    crate::event::mouse_button::PRIMARY,
                ),
            };
            let delivered = crate::platform::platform_facts().route_pointer_event(
                widget_id,
                &translated,
                position,
            );
            if !delivered {
                return;
            }
            if matches!(
                phase,
                MousePhase::Press | MousePhase::SecondaryPress | MousePhase::DoubleClick
            ) {
                // A click can move focus to a nested control; take the keyboard so
                // subsequent keys are delivered to this view.
                if let Some(window) = self.window() {
                    window.makeFirstResponder(Some(self));
                }
            }
            self.setNeedsDisplay(true);
        }));
        if outcome.is_err() {
            log::error!("[macos-objc2] canvas: panic while forwarding a mouse event");
        }
    }

    /// Translates an AppKit scroll-wheel event into a widget wheel event.
    #[cfg(widgets_unstripped)]
    fn forward_wheel(&self, event: &NSEvent) {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let Some(widget_id) = self.widget_target() else {
                return;
            };
            let local = self.convertPoint_fromView(event.locationInWindow(), None);
            let origin = self.frame().origin;
            let position = Point::new(
                (origin.x + local.x).round() as i32,
                (origin.y + local.y).round() as i32,
            );
            let modifiers =
                crate::platform::macos::types::map_modifiers(event.modifierFlags().bits() as u64);
            // AppKit reports a positive `scrollingDeltaY` for scrolling up; the widget
            // layer's wheel `delta.y` is positive for scrolling down, so the sign is
            // inverted (matching `macos::canvas` and `windows::canvas`).
            let translated = Event::wheel(
                event.scrollingDeltaX().round() as i32,
                -(event.scrollingDeltaY().round() as i32),
                modifiers,
            );
            if crate::platform::platform_facts().route_pointer_event(
                widget_id,
                &translated,
                position,
            ) {
                self.setNeedsDisplay(true);
            }
        }));
        if outcome.is_err() {
            log::error!("[macos-objc2] canvas: panic while forwarding a wheel event");
        }
    }

    /// Translates an AppKit key event into a widget key/text event and routes it.
    #[cfg(widgets_unstripped)]
    fn forward_key(&self, event: &NSEvent, release: bool) {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let Some(widget_id) = self.widget_target() else {
                return;
            };
            let key = event.keyCode() as u32;
            let modifiers =
                crate::platform::macos::types::map_modifiers(event.modifierFlags().bits() as u64);
            if release {
                // A release produces no text, so `KeyRelease` is the only event it can be.
                let target = crate::widget::runtime::focused_widget().unwrap_or(widget_id);
                if crate::widget::runtime::dispatch_event(
                    target,
                    &Event::KeyRelease { key, modifiers },
                ) {
                    self.setNeedsDisplay(true);
                }
                return;
            }
            // Printable characters travel as `TextInput` so the widget's text path runs;
            // non-printing keys travel as `KeyPress` with their hardware key code.
            let translated = if let Some(text) = printable_characters(event) {
                Event::TextInput { text }
            } else {
                Event::KeyPress { key, modifiers }
            };
            // Keys follow focus; with nothing focused, the surface owner keeps them.
            let target = crate::widget::runtime::focused_widget().unwrap_or(widget_id);
            if crate::widget::runtime::dispatch_event(target, &translated) {
                self.setNeedsDisplay(true);
            }
        }));
        if outcome.is_err() {
            log::error!("[macos-objc2] canvas: panic while forwarding a key event");
        }
    }
}

/// Reads the printable characters of a key event, or `None` when it has none.
#[cfg(widgets_unstripped)]
fn printable_characters(event: &NSEvent) -> Option<crate::compat::String> {
    let characters = event.characters()?;
    let text = characters.to_string();
    let printable: crate::compat::String = text.chars().filter(|ch| !ch.is_control()).collect();
    if printable.is_empty() {
        None
    } else {
        Some(printable)
    }
}

/// Blits a top-down, straight-alpha RGBA frame into a CoreGraphics context.
///
/// The two details the caller should not have to think about:
///
/// 1. **Premultiplication** — the frame is straight alpha; `PremultipliedLast` is
///    not, so RGB is scaled by alpha.
/// 2. **Ownership** — the colour space, bitmap context and image are all released
///    here, including on the early-return paths.
///
/// The image is drawn at its own pixel size (a 1:1 blit). Like
/// `macos/cg.rs::blit_rgba`, no CTM flip is applied: the canvas reports
/// `isFlipped == NO`, so the frame's row order matches the context's.
///
/// Uses `objc2-core-graphics` (already a dependency of the `macos` feature)
/// rather than re-declaring the FFI the cocoa backend keeps in `macos/cg.rs`.
///
/// Returns `false` when a CoreGraphics object cannot be created or the frame is
/// too small for the requested size.
fn blit_rgba(context: &CGContext, width: u32, height: u32, frame: &[u8]) -> bool {
    use objc2_core_graphics::{
        CGBitmapContextCreate, CGBitmapContextCreateImage, CGBitmapContextGetBytesPerRow,
        CGBitmapContextGetData, CGColorSpace, CGContext, CGImage, CGImageAlphaInfo,
        CGImageByteOrderInfo, CGInterpolationQuality,
    };

    if width == 0 || height == 0 {
        return false;
    }
    let expected = width as usize * height as usize * 4;
    if frame.len() < expected {
        log::error!(
            "[macos-objc2] canvas: frame is {} bytes, need {} for {width}x{height}",
            frame.len(),
            expected
        );
        return false;
    }

    let Some(color_space) = CGColorSpace::new_device_rgb() else {
        log::error!("[macos-objc2] canvas: CGColorSpaceCreateDeviceRGB returned null");
        return false;
    };

    // `kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast` gives an
    // in-memory R, G, B, A byte order — the order the software renderer produces.
    let bitmap_info = CGImageAlphaInfo::PremultipliedLast.0 | CGImageByteOrderInfo::Order32Little.0;
    // SAFETY: every pointer argument is either null (let CG allocate) or a value
    // derived from the borrowed `frame` and the live colour space.
    let Some(bitmap) = (unsafe {
        CGBitmapContextCreate(
            std::ptr::null_mut(),
            width as usize,
            height as usize,
            8,
            width as usize * 4,
            Some(&color_space),
            bitmap_info,
        )
    }) else {
        log::error!(
            "[macos-objc2] canvas: CGBitmapContextCreate returned null for {width}x{height}"
        );
        return false;
    };

    // Copy in with premultiplied alpha, row by row using the bitmap's **actual**
    // stride: CoreGraphics may pad rows once the width crosses an alignment
    // boundary, and assuming `width * 4` shifts every row after the first.
    let destination = unsafe { CGBitmapContextGetData(Some(&bitmap)) } as *mut u8;
    if !destination.is_null() {
        let stride = unsafe { CGBitmapContextGetBytesPerRow(Some(&bitmap)) };
        for y in 0..height as usize {
            for x in 0..width as usize {
                let source = (y * width as usize + x) * 4;
                let target = y * stride + x * 4;
                let alpha = frame[source + 3] as u32;
                // SAFETY: `target + 3 < height * stride` because the bitmap was
                // created at `height` rows; each row of `destination` is `stride`
                // bytes wide.
                unsafe {
                    *destination.add(target) = (frame[source] as u32 * alpha / 255) as u8;
                    *destination.add(target + 1) = (frame[source + 1] as u32 * alpha / 255) as u8;
                    *destination.add(target + 2) = (frame[source + 2] as u32 * alpha / 255) as u8;
                    *destination.add(target + 3) = alpha as u8;
                }
            }
        }
    }

    let Some(image) = (unsafe { CGBitmapContextCreateImage(Some(&bitmap)) }) else {
        log::error!("[macos-objc2] canvas: CGBitmapContextCreateImage returned null");
        return false;
    };

    // SAFETY: `context` is valid for the duration of the draw (AppKit owns it for
    // the current `drawRect:`), and `image` is live. `NSRect` is an alias of
    // `CGRect`, so the rect built from the image's own pixel size can be passed
    // straight to `CGContextDrawImage`.
    unsafe {
        CGContext::set_interpolation_quality(Some(context), CGInterpolationQuality::None);
        let image_width = CGImage::width(Some(&image)) as f64;
        let image_height = CGImage::height(Some(&image)) as f64;
        let rect = NSRect::new(
            objc2_foundation::NSPoint::new(0.0, 0.0),
            NSSize::new(image_width, image_height),
        );
        CGContext::draw_image(Some(context), rect, Some(&image));
    }
    true
}

// ---------------------------------------------------------------------------
// Window creation
// ---------------------------------------------------------------------------

pub(crate) fn create_ns_window(
    mtm: MainThreadMarker,
    widget_id: u64,
    title: &str,
    x: i32,
    y: i32,
    width: u32,
    height: u32,
) -> Retained<NSWindow> {
    let style_mask = NSWindowStyleMask::Titled
        | NSWindowStyleMask::Closable
        | NSWindowStyleMask::Miniaturizable
        | NSWindowStyleMask::Resizable;
    let rect = make_rect(x, y, width, height);
    // SAFETY: NSWindow::initWithContentRect_styleMask_backing_defer is called with
    // a valid MainThreadMarker, ensuring this runs on the main thread. The alloc
    // is obtained from mtm which guarantees the correct memory allocation context.
    // The returned Retained<NSWindow> is always non-null (objc2 init methods return
    // a valid retained object on success, or panic on allocation failure).
    let window = unsafe {
        NSWindow::initWithContentRect_styleMask_backing_defer(
            mtm.alloc(),
            rect,
            style_mask,
            NSBackingStoreType::Buffered,
            false,
        )
    };
    window.setTitle(&NSString::from_str(title));

    // Install a canvas as the window's content view **before** the window is put
    // on screen, so the very first frame the compositor shows is already the
    // library-painted one. Making the window key/ordered front with a plain
    // content view would flash an empty white client area first.
    //
    // The canvas carries `widget_id` and the window flag, so `invalidate_surface`
    // for this window id can mark the content view and `drawRect:` paints the
    // window's own chrome plus every child that implements `Draw`.
    let canvas =
        RustWidgetsObjc2CanvasView::new(mtm, widget_id, true, make_rect(0, 0, width, height));
    window.setContentView(Some(&canvas));
    // The canvas doubles as the window's delegate so `windowShouldClose:` forwards the
    // close to the widget layer. NSWindow holds its delegate as a weak (assign)
    // reference, but the canvas is retained as the content view for the window's whole
    // lifetime, so the pointer stays valid. `msg_send!` is used rather than the typed
    // `setDelegate` because that one needs a `ProtocolObject<dyn NSWindowDelegate>`.
    let delegate_ptr = Retained::as_ptr(&canvas) as *mut AnyObject;
    let _: () = unsafe { msg_send![&*window, setDelegate: delegate_ptr] };
    window.makeKeyAndOrderFront(None);
    window
}

// ---------------------------------------------------------------------------
// Surface lifecycle
// ---------------------------------------------------------------------------

/// Mounts a canvas view for `id` on the window registered under `parent`.
///
/// Creates [`RustWidgetsObjc2CanvasView`] sized to `rect`, adds it to the parent
/// window's `contentView`, records it in [`SURFACE_VIEWS`] so later
/// resize/invalidate/unmount calls can reach it, and marks it for display.
///
/// # Return value
///
/// `false` when there is no parent window under `parent`, it has no content view,
/// the view cannot be allocated, or the call runs off the main thread.
pub(crate) fn mount_surface_native(
    parent: u64,
    id: u64,
    x: i32,
    y: i32,
    width: u32,
    height: u32,
) -> bool {
    let Some(mtm) = MainThreadMarker::new() else {
        log::error!(
            "[macos-objc2] mount_surface: refused off the AppKit main thread (parent={parent}, id={id})"
        );
        return false;
    };
    // Resolve the parent window through the registry `create_ns_window` populated.
    //
    // The registry is typed as an opaque `*mut c_void`, and it also holds non-window views (surfaces
    // store their canvas there too). The runtime class check keeps a parent id that names a plain
    // view — rather than a window — from being reinterpreted as an `NSWindow`, which would be a type
    // confusion the compiler cannot catch on an erased pointer.
    let parent_ptr = match NATIVE_VIEWS.lock().unwrap().get(&parent).copied() {
        Some(ptr) if unsafe { object_is_window(ptr.0 as *mut AnyObject) } => ptr.0 as *mut NSWindow,
        Some(_) => {
            log::error!(
                "[macos-objc2] mount_surface: parent {parent} is not a window; a surface is mounted on\
                 a window's content view"
            );
            return false;
        }
        None => {
            log::error!("[macos-objc2] mount_surface: unknown parent window {parent}");
            return false;
        }
    };
    // SAFETY: the registry only ever stores objects `create_ns_window` made, and
    // the main-thread guard above satisfies AppKit's threading requirement.
    let parent_window: &NSWindow = unsafe { &*parent_ptr };
    let Some(content_view) = parent_window.contentView() else {
        log::error!("[macos-objc2] mount_surface: window {parent} has no content view");
        return false;
    };

    let frame = make_rect(x, y, width, height);
    let canvas = RustWidgetsObjc2CanvasView::new(mtm, id, false, frame);
    content_view.addSubview(&canvas);
    canvas.setNeedsDisplay(true);
    // The view is being revealed, which is the platform repainting a surface the
    // library just mounted; announce it like every other platform redraw.
    crate::notify_native_redraw(id, None);

    SURFACE_VIEWS
        .lock()
        .unwrap()
        .insert(id, NativePtr(Retained::as_ptr(&canvas) as *mut std::ffi::c_void));
    // The content view retains the canvas as a subview, so dropping the local
    // `Retained` here leaves the AppKit-owned reference intact.
    drop(canvas);
    log::debug!("[macos-objc2] mount_surface: id={id} mounted at ({x}, {y}, {width}, {height})");
    true
}

/// Resizes the mounted surface `id` and asks AppKit to redraw it.
///
/// Returns `false` when `id` has no mounted surface or the call is off-main.
pub(crate) fn resize_surface_native(id: u64, x: i32, y: i32, width: u32, height: u32) -> bool {
    if MainThreadMarker::new().is_none() {
        log::error!("[macos-objc2] resize_surface: refused off the AppKit main thread");
        return false;
    }
    let Some(ptr) = surface_view(id) else {
        log::error!("[macos-objc2] resize_surface: id={id} is not mounted");
        return false;
    };
    // SAFETY: `ptr` was produced by `mount_surface_native` and is only removed by
    // `unmount_surface_native`; `setFrame:` and `setNeedsDisplay:` are NSView API.
    unsafe {
        let view: &NSView = &*(ptr as *const NSView);
        // `setNeedsDisplay:` after `setFrame:`: AppKit does not schedule a display
        // pass for a frame change on its own, so a bare `setFrame:` leaves the old
        // pixels on screen until an unrelated invalidation arrives.
        view.setFrame(make_rect(x, y, width, height));
        view.setNeedsDisplay(true);
    }
    true
}

/// Marks the mounted surface `id` as needing display.
///
/// Returns `false` when `id` has no mounted surface or the call is off-main.
pub(crate) fn invalidate_surface_native(id: u64) -> bool {
    if MainThreadMarker::new().is_none() {
        log::error!("[macos-objc2] invalidate_surface: refused off the AppKit main thread");
        return false;
    }
    let Some(ptr) = surface_view(id) else {
        return false;
    };
    // SAFETY: `ptr` came from the side table populated by `mount_surface_native`;
    // `setNeedsDisplay:` is a valid NSView selector.
    unsafe {
        let view: &NSView = &*(ptr as *const NSView);
        view.setNeedsDisplay(true);
    }
    true
}

/// Marks a window's content view as needing display.
///
/// A repaint request for a **window** id reaches the content view, which is what
/// draws that window's children. Returns `false` for an id with no native window.
pub(crate) fn invalidate_window_native(id: u64) -> bool {
    if MainThreadMarker::new().is_none() {
        log::error!("[macos-objc2] invalidate_window: refused off the AppKit main thread");
        return false;
    }
    // The library asks for a repaint by **widget** id, but `NATIVE_VIEWS` is keyed by
    // the **host** id `create_window` returned (the two id spaces never coincide).
    // Translate at the boundary; an id with no host association is tried as-is, the
    // same fallback `windows::window_hwnd_for_widget_id` uses for its own registry.
    #[cfg(widgets_unstripped)]
    let host_id = crate::widget::runtime::host_window_for(id).unwrap_or(id);
    #[cfg(not(widgets_unstripped))]
    let host_id = id;
    let window_ptr = match NATIVE_VIEWS.lock().unwrap().get(&host_id).copied() {
        Some(ptr) => ptr.0 as *mut NSWindow,
        None => return false,
    };
    // SAFETY: the registry only stores objects `create_ns_window` made; the
    // main-thread guard above satisfies AppKit's threading requirement.
    unsafe {
        let window: &NSWindow = &*window_ptr;
        if let Some(content_view) = window.contentView() {
            content_view.setNeedsDisplay(true);
        }
    }
    true
}

/// Removes the mounted surface `id` from its window.
///
/// Returns `false` when `id` has no mounted surface or the call is off-main.
pub(crate) fn unmount_surface_native(id: u64) -> bool {
    if MainThreadMarker::new().is_none() {
        log::error!("[macos-objc2] unmount_surface: refused off the AppKit main thread");
        return false;
    }
    let removed = SURFACE_VIEWS.lock().unwrap().remove(&id);
    let Some(ptr) = removed else {
        log::error!("[macos-objc2] unmount_surface: id={id} is not mounted");
        return false;
    };
    // SAFETY: the side-table entry was removed just above, so the view has no
    // other owner in this module and detaching it from its superview is the
    // correct teardown.
    unsafe {
        let view: &NSView = &*(ptr.0 as *const NSView);
        view.removeFromSuperview();
    }
    true
}

/// Looks up the canvas view pointer for a mounted surface.
fn surface_view(id: u64) -> Option<*mut NSView> {
    SURFACE_VIEWS.lock().unwrap().get(&id).map(|ptr| ptr.0 as *mut NSView)
}

/// Bootstrap the shared `NSApplication` (create + `finishLaunching`).
///
/// Mirrors the cocoa-legacy backend's `init()` so the objc2 backend is a real
/// AppKit application rather than only a state machine. Returns `false` when
/// called off the main thread (nothing is touched in that case).
pub(crate) fn bootstrap_ns_application() -> bool {
    let Some(mtm) = MainThreadMarker::new() else {
        return false;
    };
    let app = NSApplication::sharedApplication(mtm);
    // A GUI host must be a regular app (Dock icon + activation) so its windows can
    // become key and receive input; without this the app is a background accessory.
    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
    app.finishLaunching();
    app.activate();
    true
}

/// Pumps one AppKit event without blocking, and reports whether one was dispatched.
///
/// `-[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]` with
/// `NSDate distantPast` returns immediately when the queue is empty, so this is the
/// non-blocking step the backend's `run` interleaves with library frames. Without it
/// the native window never drew, received no mouse/key events, and could not close.
pub(crate) fn pump_native_event() -> bool {
    let Some(mtm) = MainThreadMarker::new() else {
        return false;
    };
    let app = NSApplication::sharedApplication(mtm);
    // SAFETY: `NSDefaultRunLoopMode` is a well-known, immutable AppKit mode constant.
    let mode = unsafe { NSDefaultRunLoopMode };
    let event = app.nextEventMatchingMask_untilDate_inMode_dequeue(
        NSEventMask::Any,
        Some(&NSDate::distantPast()),
        mode,
        true,
    );
    let dispatched = if let Some(event) = event {
        app.sendEvent(&event);
        true
    } else {
        false
    };
    // A window-close delegate queues its registry retain for release after AppKit's
    // close callback has unwound; releasing the last retain inside that callback
    // could deallocate the NSWindow before `close` returns.
    drain_pending_native_releases();
    dispatched
}