rust_widgets 2.8.7

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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! `impl Platform for MacOSPlatform` — the main trait implementation.

#![allow(deprecated)] // Cocoa 0.24 fallback; remove when objc2 backend fully replaces cocoa

use crate::compat::String;
use crate::compat::Vec;
use crate::core::{ObjectId, PlatformFamily};
use crate::platform::accessibility::AccessibilityBridge;
use crate::platform::clipboard::RichClipboardBackend;
use crate::platform::ime::ImeBridge;
use crate::platform::macos::types::*;
use crate::platform::types::{Display, DisplayId};
use crate::platform::Platform;
use crate::platform::PlatformCapabilities;
use cocoa::appkit::{
    NSApp, NSApplication, NSApplicationActivationOptions, NSApplicationActivationPolicyRegular,
    NSBackingStoreBuffered, NSRunningApplication, NSWindow,
};
// A plain content view is the `mini`/`embedded` fallback only; the canvas profile installs its own
// drawing view, so the import is compiled out where it would otherwise be unused.
#[cfg(not(widgets_unstripped))]
use cocoa::appkit::NSView;
use cocoa::base::{id, nil, BOOL, NO, YES};
use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSRect, NSString};
use objc::{class, msg_send, sel, sel_impl};
use std::ffi::CStr;
use std::os::raw::c_char;

/// An autoreleased `NSString` for a Rust `&str`.
///
/// `NSString::init_str` returns a +1-retained object, so an unmanaged result leaks on every call —
/// the clipboard reads/writes and the window-title setter each leaked one per invocation.
/// `autorelease` hands ownership to the enclosing pool, which is the correct lifetime for a string
/// that is only read during the following Objective-C call.
///
/// # SAFETY
/// Must be called on a thread with an active autorelease pool (AppKit's main thread has one).
unsafe fn autoreleased_nsstring(s: &str) -> id {
    NSString::alloc(nil).init_str(s).autorelease()
}

/// `NSEventTypeApplicationDefined` (`15`).
///
/// The type of event `MacOSPlatform::quit` posts to wake `-[NSApplication run]` after `stop:`
/// raises its flag. It is a literal rather than a `cocoa` constant because the crate exposes the
/// obsolete `NSApplicationDefined` spelling, while the ABI value is what the message needs.
const NS_EVENT_TYPE_APPLICATION_DEFINED: u64 = 15;

/// Resolves a window id a host holds to the platform window id this backend's registry is keyed by.
///
/// A window has two ids: the **widget-registry** id the host gets back from `create_window` (the
/// window *as a widget*), and the **platform** id `MacOSPlatform::create_window` returned and
/// registered. `host_window_for` is the association recorded at creation — the same translation
/// `set_widget_visible` and the paint path use — so an id that names a widget window resolves to the
/// handle this backend knows. A profile with no widget runtime (alloc-frugal, i.e. `mini`) has
/// neither a registry id nor that helper, and resolves the platform id alone; the caller tries the
/// registry directly first, so a platform id still resolves there.
#[cfg(not(alloc_frugal))]
fn translate_widget_id(window_id: ObjectId) -> Option<ObjectId> {
    crate::widget::runtime::host_window_for(window_id)
}

/// The `alloc_frugal` arm: there is no widget runtime, so only platform ids exist.
#[cfg(alloc_frugal)]
fn translate_widget_id(_window_id: ObjectId) -> Option<ObjectId> {
    None
}

impl Platform for MacOSPlatform {
    fn as_any(&self) -> &dyn crate::compat::Any {
        self
    }
    fn backend_name(&self) -> &'static str {
        "cocoa"
    }

    /// A library-painted widget gets an `NSView` subclass whose `drawRect:` blits a
    /// frame out of `widget::runtime`. See `macos/canvas.rs`.
    ///
    /// Gated on the same profile conditions as `canvas.rs`: `widget::runtime` is
    /// absent from `mini`/`embedded`, so the fallback defaults below apply there
    /// and `supports_surfaces()` honestly reports `false`.
    #[cfg(widgets_unstripped)]
    fn mount_surface(&self, parent: ObjectId, id: ObjectId, rect: crate::core::Rect) -> bool {
        self.mount_surface_impl(parent, id, rect)
    }

    #[cfg(widgets_unstripped)]
    fn resize_surface(&self, id: ObjectId, rect: crate::core::Rect) -> bool {
        self.resize_surface_impl(id, rect)
    }

    #[cfg(widgets_unstripped)]
    fn unmount_surface(&self, id: ObjectId) -> bool {
        self.unmount_surface_impl(id)
    }

    /// `true` only when the surface actually exists for this profile.
    ///
    /// Reporting `true` in a build where `canvas.rs` is compiled out would be a
    /// lie: a host would mount a widget and get an empty window with no error.
    #[cfg(widgets_unstripped)]
    fn supports_surfaces(&self) -> bool {
        true
    }

    /// Mark the canvas view as needing display, which schedules `drawRect:`.
    #[cfg(widgets_unstripped)]
    fn invalidate_surface(&self, id: ObjectId) -> bool {
        self.invalidate_surface_impl(id)
    }

    /// Mark one rectangle of the canvas view as needing display.
    ///
    /// Gated with `invalidate_surface` above: both are `canvas.rs` facilities, and
    /// `canvas.rs` is compiled out on the stripped profiles. Without the gate this
    /// method referenced a type that does not exist there, so `mini,cocoa-legacy`
    /// did not compile — the same drift the sibling gate above already prevents.
    #[cfg(widgets_unstripped)]
    fn invalidate_surface_rect(&self, id: ObjectId, rect: crate::core::Rect) -> bool {
        self.invalidate_surface_rect_impl(id, rect)
    }
    fn family(&self) -> PlatformFamily {
        PlatformFamily::Desktop
    }

    /// The host integrations this backend actually provides.
    ///
    /// # Why `native_menu` and `dpi_scaling` are `false`
    ///
    /// The comment above used to claim "AppKit supplies the screen scale, the
    /// input-method client, the accessibility tree and the application menu, so all
    /// four are `true`". The premise is true about AppKit and false about this type:
    /// `grep` over `src/platform/macos/` finds **no** `create_menu_bar`,
    /// `menu_add_item` or `attach_menu_bar_to_window`, and no `dpi_scale_factor`
    /// override — so both flags promised methods that are not there.
    ///
    /// The distinction matters because a flag is a promise the negotiation acts on: a
    /// host that reads `native_menu: true` asks the backend for a menu bar and gets id
    /// `0`, and a host that reads `dpi_scaling: true` lays out for a scale factor the
    /// backend cannot report and silently gets `1.0`.
    ///
    /// `ime` and `accessibility` stay `true`: both have real implementations reachable
    /// from this backend (`ime_bridge()` → `ImeMacosBridge`, `accessibility_bridge()` →
    /// the AppKit bridge), and `shortcut_style()` really is `Mac`. What is fixed here is
    /// only the pair with no implementation behind it (principle #37 — an honest
    /// absence, not a fabricated value).
    ///
    /// The two host-service flags follow the same rule: both are `true` because both
    /// methods have real bodies (`NSPasteboard`, and the `open` handler spawned by
    /// [`Self::open_external`]).
    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities {
            dpi_scaling: false,
            ime: true,
            accessibility: true,
            native_menu: false,
            typed_widget_trigger: true,
            // `set/get_clipboard_text` talk to `NSPasteboard`, so a copy is visible outside
            // this process.
            clipboard: true,
            // `open_external` spawns `open`.
            open_external: true,
            // `choose_path` presents `NSOpenPanel`/`NSSavePanel`, so the flag and the method are
            // one implementation.
            file_dialog: true,
        }
    }

    /// Presents AppKit's own file picker — see [`super::file_picker`] for the panel choice, the
    /// main-thread rule and what the answer does and does not claim.
    fn choose_path(
        &self,
        purpose: crate::platform::PathPurpose,
        title: &str,
    ) -> Result<Option<std::path::PathBuf>, crate::platform::PathPickerError> {
        super::file_picker::choose_path(purpose, title)
    }

    /// Hands a URL or path to the system's default handler by spawning `open`.
    ///
    /// See [`Platform::open_external`] for why this returns on hand-off rather than on the
    /// handler finishing, and [`crate::platform::external`] for the shared validation and
    /// spawn.
    fn open_external(&self, target: &str) -> Result<(), crate::platform::types::OpenError> {
        crate::platform::external::spawn_handler("open", &[], target)
    }

    /// Whether `open` is on this host's `PATH`.
    ///
    /// The companion of [`Self::open_external`]: that method hands a target to `open`, so "is the
    /// handler installed" is exactly "is `open` findable on `PATH`". See
    /// [`Platform::has_external_handler`] for why this is a separate, side-effect-free query rather
    /// than the capability flag (which reports only that the backend has the method).
    fn has_external_handler(&self) -> bool {
        crate::platform::external::program_is_on_path("open")
    }

    /// The displays AppKit reports; see [`super::displays`].
    fn displays(&self) -> Vec<Display> {
        super::displays::displays()
    }

    /// The screen the window is on, asked of AppKit's `-[NSWindow screen]`.
    ///
    /// # Both id spaces
    ///
    /// The id a host holds for a window is the widget-registry id, while this backend's handle
    /// table is keyed by the platform id `create_window` returned; the association recorded at
    /// creation (`translate_widget_id`, the same translation the paint path uses) bridges them. A
    /// caller that passes the platform id directly is honoured too, because the registry lookup
    /// accepts it. An id that names no window, or a `Canvas` handle rather than a `Window`, answers
    /// `None` instead of messaging an object that is not an `NSWindow`.
    fn display_of_window(&self, window_id: ObjectId) -> Option<DisplayId> {
        if !super::types::is_main_thread() {
            // AppKit is main-thread-only; messaging it from anywhere else would raise.
            return None;
        }
        // Looked up directly rather than through `get_handle`, which logs an error for a miss:
        // "which screen is *this* id on" is a question a host may ask of an id that is not a
        // window, and that is a `None`, not a defect worth a log line.
        let host = {
            let handles = crate::compat::lock(&self.handles);
            if handles.contains_key(&window_id) {
                Some(window_id)
            } else {
                translate_widget_id(window_id)
            }
        }?;
        let handle = crate::compat::lock(&self.handles).get(&host).copied()?;
        if handle.kind != HandleKind::Window || handle.ptr == 0 {
            return None;
        }
        // SAFETY: the registry only holds pointers this backend created, a `Window` handle is an
        // `NSWindow`, and the main thread is established above.
        unsafe { super::displays::window_display(handle.ptr as id) }
    }

    /// A revision of AppKit's current display set; see [`super::displays::generation`].
    fn display_generation(&self) -> u64 {
        super::displays::generation()
    }

    /// Reads installed physical memory via `sysconf` (`_SC_PHYS_PAGES` x `_SC_PAGESIZE`).
    ///
    /// BSD spells this `sysctl hw.memsize`; `sysconf` answers the same question on the
    /// same kernel and needs no FFI dependency the crate does not already link.
    fn total_memory_mb(&self) -> Option<u64> {
        crate::platform::darwin_probes::total_memory_mb()
    }

    /// macOS ships `pmset`; `-g batt` prints a `'AC Power'`/`'Battery Power'` line.
    fn is_on_battery(&self) -> bool {
        crate::platform::darwin_probes::is_on_battery()
    }

    /// Samples RSS over virtual size via `ps -o rss=,vsz=`.
    fn process_memory_utilization(&self) -> Option<f32> {
        crate::platform::darwin_probes::process_memory_utilization()
    }

    /// CPU tick accounting has no lock-free macOS source here, so this reports
    /// `None` rather than a fabricated figure.
    fn process_cpu_utilization(&self) -> Option<f32> {
        None
    }

    /// Submits the job to the unix print spooler via [`crate::platform::os_probes`].
    fn spawn_print_job(&self, job_file: &std::path::Path) -> Result<(), String> {
        crate::platform::os_probes::spawn_print_job(job_file)
    }

    /// macOS ships CUPS, so `lp`/`lpr` are present on every normal install.
    fn has_print_support(&self) -> bool {
        crate::platform::types::unix_print_clients_available()
    }

    /// Renders menu accelerators with AppKit symbols (`⌘⇧Z`).
    fn shortcut_style(&self) -> crate::shortcut::PlatformShortcutStyle {
        crate::shortcut::PlatformShortcutStyle::Mac
    }
    fn init(&self) {
        // AppKit's `NSApplication` singleton may only be created/activated on the
        // main thread. Off-main we skip the native bootstrap entirely and leave
        // the backend in state mode (mirrors the `macos_objc2` preview backend).
        if !super::types::is_main_thread() {
            log::debug!("[macos] init skipped: not on the AppKit main thread (state-only mode)");
            return;
        }
        // SAFETY: NSAutoreleasePool::new(nil) is safe per Apple's documentation
        // (nil argument is allowed). NSApplication sharedApplication and messaging
        // are called on the main thread, which is required by Cocoa. All Objective-C
        // message sends use valid selectors from the cocoa/objc crates.
        unsafe {
            let pool = NSAutoreleasePool::new(nil);
            let app = NSApplication::sharedApplication(nil);
            app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
            let _: () = msg_send![app, finishLaunching];
            let current_app = NSRunningApplication::currentApplication(nil);
            current_app.activateWithOptions_(
                NSApplicationActivationOptions::NSApplicationActivateIgnoringOtherApps,
            );
            pool.drain();
        }
    }
    fn run(&self) {
        // `-[NSApplication run]` must only be entered from the main thread; from
        // any other thread it would raise a foreign exception. Off-main callers
        // get a deterministic state-mode polling loop instead.
        if !super::types::is_main_thread() {
            log::debug!("[macos] run skipped: not on the AppKit main thread (state-only loop)");
            return;
        }
        // The frame heartbeat is installed here, once, **before** entering the run loop, so a session
        // ticks whether or not any window is created. It used to be a per-window `NSTimer` installed
        // by `create_window`, which meant a session with no window never ticked: a stop request or
        // any queued main-thread work had no reader, and the session could not end itself (designer
        // feedback `docs/issues/feedback-20261015.md` §十.2). The tick has to be scheduled on the
        // run loop before it runs; `-[NSApplication run]` does not return until the app stops, so
        // there is no point *after* it to install anything.
        #[cfg(widgets_unstripped)]
        // SAFETY: the main thread is established above, and the timer is scheduled on its run loop.
        unsafe {
            super::canvas::install_frame_heartbeat();
        }
        // The `-[NSApplication run]` call that follows must be on the main thread too.
        //
        // SAFETY: `NSApp()` returns the shared application instance initialized in
        // `init()`. `run()` must be called on the main thread, which the guard above
        // has established.
        unsafe {
            NSApp().run();
        }
    }
    /// Requests that the AppKit run loop stop.
    ///
    /// # Why the off-main case returns `false` instead of a quiet success
    ///
    /// `-[NSApplication stop:]` is main-thread-only, so this backend cannot honour a request
    /// that arrives on any other thread — and there is no safe way for it to hand the request
    /// to the main thread from here: the obvious selector (`performSelectorOnMainThread:…`) is
    /// banned by the `check_apple_thread_safety.sh` gate, and this crate links no dispatch
    /// queue to use instead. The refusal is therefore **reported** rather than logged, which is
    /// what lets a host that is not driving the loop itself (a smoke test, CI, a script)
    /// learn that its stop request will not take effect and arrange its own ending. It used to
    /// log and return `()`, so the same caller could not tell "asked" from "will stop".
    fn quit(&self) -> bool {
        if !super::types::is_main_thread() {
            log::debug!("[macos] quit refused: NSApplication stop is main-thread-only");
            return false;
        }
        // SAFETY: NSApp().stop_(nil) is safe to call on the main thread after the
        // application has been initialized. The nil argument tells the app to stop
        // without a specific sender.
        unsafe {
            NSApp().stop_(nil);
            // `stop:` only raises a flag; `-[NSApplication run]` observes it when it next returns
            // from `nextEventMatchingMask:`. When the loop is servicing timers rather than waiting
            // for events — which is exactly what this backend's frame heartbeat makes it do — that
            // return can be indefinitely delayed, so an application-defined event is posted to wake
            // the loop. This is the documented companion to `stop:` for that case, and it is what
            // makes a bounded session end promptly instead of "still running after 20 s"
            // (`docs/issues/feedback-20261015.md` §十.2).
            let event: id = msg_send![
                class!(NSEvent),
                otherEventWithType: NS_EVENT_TYPE_APPLICATION_DEFINED
                location: NSPoint::new(0.0, 0.0)
                modifierFlags: 0u64
                timestamp: 0.0f64
                windowNumber: 0i64
                context: nil
                subtype: 0i16
                data1: 0i64
                data2: 0i64
            ];
            if event != nil {
                let _: () = msg_send![NSApp(), postEvent: event atStart: YES];
            }
        }
        true
    }
    /// Pops the next typed widget-trigger event from this backend's queue.
    ///
    /// # Why this backend must delegate
    ///
    /// [`PlatformCapabilities::typed_widget_trigger`] claims this backend produces and delivers
    /// typed triggers, and it holds a `BackendState` (the shared queue) exactly like `harmony`,
    /// `android`, `ios`, `wayland`, `windows` and `mobile` — every one of which writes these two
    /// lines. This backend did not, so both methods fell through to the trait defaults (`None` /
    /// `false`) while the flag said `true`.
    ///
    /// The gap is reachable rather than theoretical: `NativeControlBackend` forwards both straight
    /// to `get_platform()`, so an injected trigger was accepted and then dropped on the floor.
    fn poll_widget_trigger_event(&self) -> Option<crate::platform::WidgetTriggerEvent> {
        self.state.pop_widget_trigger_event()
    }

    /// Pushes a typed widget-trigger event, refusing ids this backend never made.
    fn inject_widget_trigger_event(
        &self,
        widget_id: ObjectId,
        kind: crate::platform::WidgetTriggerKind,
    ) -> bool {
        self.state.inject_widget_trigger_event(widget_id, kind)
    }

    /// Pops the next pending trigger as a bare id, over the same queue as the typed view.
    fn poll_widget_triggered(&self) -> Option<ObjectId> {
        self.poll_widget_trigger_event().map(|event| event.widget_id)
    }

    fn destroy_widget(&self, widget_id: ObjectId) -> bool {
        // Take the native handle out under its own lock, then release the guard
        // before messaging AppKit (the two mutexes are never held together).
        let handle = crate::compat::lock(&self.handles).remove(&widget_id);
        // Drop the per-widget accessibility registration that `register_handle` added.
        self.a11y_bridge.unregister_handle(widget_id);
        // Native teardown for a window this backend really created: close it (so it
        // leaves the screen) and release the `alloc`-owned reference `create_window`
        // took. Without this, `destroy_widget` only deleted a `Copy` `usize` bookkeeping
        // entry and the OS window stayed visible with its reference never balanced
        // (D08-P-01). The close/release are main-thread-only, so they are skipped
        // off-main, where `create_window` also never constructed a native object.
        if let Some(handle) = handle {
            if handle.ptr != 0
                && matches!(handle.kind, HandleKind::Window)
                && super::types::is_main_thread()
            {
                // SAFETY: `handle.ptr` is the `NSWindow*` this backend obtained from
                // `NSWindow::alloc(..).initWithContentRect_..(..)` in `create_window`, so
                // it is a valid owned AppKit object. `close`/`release` are the balanced
                // teardown for that `alloc`, and both are main-thread-only (checked above).
                unsafe {
                    let window = handle.ptr as id;
                    let _: () = msg_send![window, close];
                    let _: () = msg_send![window, release];
                }
            }
        }
        // The state record is the authority for whether the widget existed.
        self.state.destroy_widget(widget_id)
    }
    fn create_window(&self, title: &str, x: i32, y: i32, width: u32, height: u32) -> u64 {
        // Off-main (e.g. the C ABI called from a worker thread or unit tests),
        // never construct `NSWindow`: AppKit raises a foreign exception that
        // aborts the process. Register a state-only handle instead so every
        // caller still receives a valid, text/geometry-consistent widget id.
        if !super::types::is_main_thread() {
            let id =
                self.register_state_only_handle(HandleKind::Window, title, x, y, width, height);
            // `window_style()` is titled + closable + resizable + miniaturizable,
            // so a fresh macOS window starts resizable and decorated.
            self.state
                .init_window_state(id, crate::platform::state::WindowStateRecord::new_window());
            return id;
        }
        // SAFETY: Cocoa APIs require the main thread, guaranteed by the platform contract.
        // NSAutoreleasePool::new(nil) is safe with nil argument. All Objective-C messages
        // use valid selectors from the cocoa crate. Self::register_handle() stores the
        // raw pointer cast as usize without aliasing issues. Nil returns from alloc are
        // checked and logged before proceeding.
        unsafe {
            let pool = NSAutoreleasePool::new(nil);

            // Check for nil after NSWindow::alloc — Cocoa returns nil on allocation failure.
            let raw_window = NSWindow::alloc(nil);
            if raw_window == nil {
                log::error!("[macos] create_window: NSWindow::alloc returned nil (out of memory?)");
                pool.drain();
                return 0;
            }
            let window = raw_window.initWithContentRect_styleMask_backing_defer_(
                Self::make_rect(x, y, width, height),
                Self::window_style(),
                NSBackingStoreBuffered,
                NO,
            );

            // Check for nil after NSView::alloc
            //
            // A profile without the library canvas (`mini`/`embedded`) gets a plain `NSView` as its
            // content area. The canvas profile installs its own drawing view below, so this is
            // compiled out there rather than allocated and thrown away.
            #[cfg(not(widgets_unstripped))]
            {
                let raw_content = NSView::alloc(nil);
                let content_view = if raw_content == nil {
                    log::error!(
                        "[macos] create_window: NSView::alloc returned nil (out of memory?)"
                    );
                    pool.drain();
                    return 0;
                } else {
                    NSView::initWithFrame_(raw_content, Self::make_rect(0, 0, width, height))
                };
                let _: () = msg_send![window, setContentView: content_view];
            }

            // Check for nil after NSString::alloc for the title
            let raw_title = NSString::alloc(nil);
            if raw_title == nil {
                log::error!("[macos] create_window: NSString::alloc returned nil (out of memory?)");
                pool.drain();
                return 0;
            }

            window.cascadeTopLeftFromPoint_(NSPoint::new(20.0, 20.0));
            NSWindow::setTitle_(window, raw_title.init_str(title));
            // The id has to exist before the canvas can be tagged with it, so `register_handle`
            // runs before the content view is installed. The canvas stores the **host** id and
            // paints the window's whole widget tree (`render_frame_tree`); a plain `NSView` here is
            // why the client area of every cocoa window used to stay blank — nothing ever drew the
            // children, which are not mounted surfaces.
            let id = self.register_handle(
                HandleKind::Window,
                title,
                x,
                y,
                width,
                height,
                window as usize,
            );
            #[cfg(widgets_unstripped)]
            if let Some(canvas) = super::canvas::make_window_canvas(id, width, height) {
                let _: () = msg_send![window, setContentView: canvas];
            }
            window.makeKeyAndOrderFront_(nil);
            let _: () = msg_send![window, display];
            // A window resized by the user then re-runs the host's layout instead of keeping stale
            // child geometry.
            //
            // Gated on `widgets_unstripped` because `macos::canvas` is: a
            // `macos-legacy + mini|embedded` build has no `NSView` canvas to install a
            // resize delegate on, and referencing the module ungated failed to compile
            // with `cannot find canvas in super`. The state-only handle above is the
            // whole window contract for those profiles, so there is nothing to
            // delegate a resize to.
            #[cfg(widgets_unstripped)]
            super::canvas::install_resize_delegate(window as id, id);
            self.state
                .init_window_state(id, crate::platform::state::WindowStateRecord::new_window());
            pool.drain();
            id
        }
    }

    /// The window's current client size, asked of AppKit.
    ///
    /// `contentView.bounds` is the authority once the user has dragged the window edge;
    /// the recorded size is only a fallback for an id with no live `NSWindow`.
    #[cfg(target_os = "macos")]
    fn window_client_size(&self, window_id: ObjectId) -> Option<(u32, u32)> {
        // SAFETY: `view_for`/`get_native_handle` return pointers this backend created,
        // and the messages sent are read-only AppKit accessors. Off-main is excluded by
        // the thread check, because AppKit must only be driven from the main thread.
        unsafe {
            if super::types::is_main_thread() {
                if let Some(handle) = self.get_native_handle(window_id) {
                    let window = handle as id;
                    let content: id = msg_send![window, contentView];
                    if content != nil {
                        let bounds: NSRect = msg_send![content, bounds];
                        let width = bounds.size.width.max(0.0) as u32;
                        let height = bounds.size.height.max(0.0) as u32;
                        if width > 0 && height > 0 {
                            return Some((width, height));
                        }
                    }
                }
            }
        }
        // Ask the control backend, which owns the window and is therefore the only
        // store that knows the size a resize reported.
        crate::window_client_size(window_id).or_else(|| self.state.window_size(window_id))
    }

    /// Reports a container's new client size and queues a `Resized` trigger.
    fn queue_resize_trigger(&self, window_id: ObjectId, width: u32, height: u32) -> bool {
        // Forward to the control backend, which owns the window and the queue the app
        // polls. Writing to the platform's own state would land in a store the host
        // never reads, because `create_window` goes through the control backend.
        crate::queue_resize_trigger(window_id, width, height)
    }

    fn menu_item_shortcut(&self, menu_item: ObjectId) -> Option<String> {
        let shortcuts = crate::compat::try_lock(&self.menu_item_shortcuts)?;
        shortcuts.get(&menu_item).cloned().filter(|text| !text.is_empty())
    }
    fn get_native_handle(&self, widget: ObjectId) -> Option<usize> {
        // A handle with a null pointer means the widget exists only as logical
        // state, so there is no native object to hand out.
        let handle = self.get_handle(widget)?;
        if handle.ptr == 0 {
            return None;
        }
        Some(handle.ptr)
    }
    fn poll_menu_triggered(&self) -> Option<u64> {
        let mut events = crate::compat::lock(menu_events());
        if events.is_empty() {
            None
        } else {
            Some(events.remove(0))
        }
    }

    /// Drives a menu item through AppKit's own action dispatch.
    ///
    /// `NSMenuItem -performActionForItemAtIndex:` is the single path AppKit takes for
    /// both a mouse click and a matched key equivalent, so a probe that reaches it is
    /// exercising the real menu route rather than a synthetic event.
    ///
    /// Off the main thread, or with no live `NSMenuItem`, this returns `false`: AppKit
    /// may only be driven from the main thread, and a state-only item has no action to
    /// send.
    fn activate_menu_item(&self, menu_item: ObjectId) -> bool {
        let Some(handle) = self.get_native_handle(menu_item) else {
            return false;
        };
        if !super::types::is_main_thread() {
            return false;
        }
        // SAFETY: `get_native_handle` returns a pointer this backend created for a live
        // `NSMenuItem`; the messages sent are the read-only `action`/`target` accessors
        // and the item's own action dispatch. Main-thread-only is enforced above.
        unsafe {
            let item = handle as id;
            if item == nil {
                return false;
            }
            let action: objc::runtime::Sel = msg_send![item, action];
            // A menu item with no action carries a null selector; comparing against
            // `Sel::from_ptr(null)` is how objc 0.2 exposes that check.
            if action == objc::runtime::Sel::from_ptr(std::ptr::null()) {
                return false;
            }
            let target: id = msg_send![item, target];
            if target == nil {
                return false;
            }
            // Route through `NSApplication -sendAction:to:from:`, the documented
            // dispatch entry point, rather than `performSelector:withObject:`.
            //
            // Two reasons. First, `performSelector:` is the API the project's
            // `check_apple_thread_safety.sh` gate bans in Apple native code (rule C),
            // because it bypasses the action machinery and its selector is unchecked at
            // runtime. Second, `sendAction:to:from:` is what a real menu click goes
            // through: the sender is passed as the `from:` argument, so a handler that
            // reads its sender (a common `validateMenuItem:`/action pattern) sees the
            // item rather than `nil`. `performSelector:withObject:` passes the item as a
            // plain argument, which an `NSMenuItem` action target does not expect.
            let app: id = msg_send![objc::class!(NSApplication), sharedApplication];
            if app == nil {
                return false;
            }
            let _: bool = msg_send![app, sendAction: action to: target from: item];
        }
        true
    }
    fn set_clipboard_text(&self, text: &str) -> bool {
        // `NSPasteboard` is a window-server singleton and may only be touched on
        // the AppKit main thread; off-main we go straight to state.
        if !super::types::is_main_thread() {
            return self.state.set_clipboard_text(text);
        }
        // Try real NSPasteboard integration first
        let result = std::panic::catch_unwind(|| unsafe {
            let pb: id = msg_send![class!(NSPasteboard), generalPasteboard];
            if pb == nil {
                return false;
            }
            let _: () = msg_send![pb, clearContents];
            let ns_str = autoreleased_nsstring(text);
            let type_str = autoreleased_nsstring("public.utf8-plain-text");
            let success: BOOL = msg_send![pb, setString:ns_str forType:type_str];
            success != NO
        });
        // Fall back to state on ObjC failure (including panics)
        result.unwrap_or_else(|_| self.state.set_clipboard_text(text))
    }
    fn get_clipboard_text(&self) -> String {
        // `NSPasteboard` is main-thread-only; state is the off-main source.
        if !super::types::is_main_thread() {
            return self.state.clipboard_text();
        }
        // Try real NSPasteboard integration first
        let result = std::panic::catch_unwind(|| unsafe {
            let pb: id = msg_send![class!(NSPasteboard), generalPasteboard];
            if pb == nil {
                return None;
            }
            let type_str = autoreleased_nsstring("public.utf8-plain-text");
            let text_obj: id = msg_send![pb, stringForType:type_str];
            if text_obj == nil {
                return None;
            }
            let c_str: *const c_char = msg_send![text_obj, UTF8String];
            if c_str.is_null() {
                return None;
            }
            Some(CStr::from_ptr(c_str).to_string_lossy().into_owned())
        });
        // Fall back to state on ObjC failure
        result.unwrap_or(None).unwrap_or_else(|| self.state.clipboard_text())
    }
    fn ime_bridge(&self) -> Option<&dyn ImeBridge> {
        Some(&self.ime_bridge)
    }

    /// Reads the record the backend keeps for every id it allocated.
    ///
    /// Both allocation paths — a real `NSWindow` on the main thread and a
    /// state-only handle off it — insert a [`crate::platform::state::WidgetRecord`],
    /// so text/geometry/enabled/visible are answered from that one record. Without
    /// these overrides the trait defaults would report empty text for a window the
    /// backend demonstrably created.
    fn get_widget_text(&self, widget_id: ObjectId) -> String {
        self.state.text(widget_id)
    }

    fn set_widget_text(&self, widget_id: ObjectId, text: &str) {
        self.state.set_text(widget_id, text);
        // Keep the live AppKit title in step when there is a native window. A
        // state-only handle has `ptr == 0`, so the message is skipped entirely.
        if let Some(handle) = self.get_handle(widget_id) {
            if handle.ptr != 0 && handle.kind == HandleKind::Window {
                // SAFETY: the handle was created in this process for an NSWindow
                // and `setTitle:` is declared by NSWindow.
                unsafe {
                    let window = Self::as_id(handle);
                    let title = autoreleased_nsstring(text);
                    NSWindow::setTitle_(window, title);
                }
            }
        }
    }

    fn set_widget_enabled(&self, widget_id: ObjectId, enabled: bool) {
        self.state.set_enabled(widget_id, enabled);
    }

    fn is_widget_enabled(&self, widget_id: ObjectId) -> bool {
        self.state.enabled(widget_id)
    }

    fn set_widget_visible(&self, widget_id: ObjectId, visible: bool) {
        self.state.set_visible(widget_id, visible);
    }

    fn is_widget_visible(&self, widget_id: ObjectId) -> bool {
        self.state.visible(widget_id)
    }

    fn set_widget_geometry(&self, widget_id: ObjectId, x: i32, y: i32, width: u32, height: u32) {
        self.state.set_geometry(widget_id, x, y, width, height);
    }

    /// Window state (maximised/minimised/fullscreen/resizable) round-trips
    /// through the record, so it works for the off-main state-only path too.
    fn set_window_state(
        &self,
        widget_id: ObjectId,
        flag: crate::platform::WindowStateFlag,
        on: bool,
    ) -> bool {
        self.state.set_window_state(widget_id, flag, on)
    }

    fn is_window_in_state(
        &self,
        widget_id: ObjectId,
        flag: crate::platform::WindowStateFlag,
    ) -> Option<bool> {
        self.state.window_state(widget_id, flag)
    }

    fn set_window_min_size(&self, widget_id: ObjectId, width: u32, height: u32) -> bool {
        self.state.set_window_min_size(widget_id, width, height)
    }

    fn window_min_size(&self, widget_id: ObjectId) -> Option<(u32, u32)> {
        self.state.window_min_size(widget_id)
    }

    fn set_widget_ime_enabled(&self, widget_id: ObjectId, enabled: bool) -> bool {
        self.state.set_ime_enabled(widget_id, enabled)
    }

    fn is_widget_ime_enabled(&self, widget_id: ObjectId) -> bool {
        self.state.ime_enabled(widget_id)
    }

    fn set_widget_accessibility_name(&self, widget_id: ObjectId, name: &str) -> bool {
        self.state.set_accessibility_name(widget_id, name)
    }

    fn get_widget_accessibility_name(&self, widget_id: ObjectId) -> String {
        self.state.accessibility_name(widget_id)
    }

    fn clipboard_backend(&self) -> Option<&dyn RichClipboardBackend> {
        Some(&self.clipboard)
    }

    // ── Drag and drop ───────────────────────────────────────────────────────
    //
    // # The gap this closes
    //
    // This backend implemented none of the three drag-and-drop methods, so it inherited the
    // trait defaults (`false`/`None`) and a drag started here did nothing at all — while the
    // same call worked on Windows, on every mobile backend and on the portable host. There was
    // no error to notice: `begin_drag` returns `bool` and the callers that ignore it, ignore it.
    //
    // # What is implemented, and what is not
    //
    // These are the **state-backed** drag and drop the Windows backend also uses: a payload and
    // a MIME type are recorded against the source widget, and a drop event is queued for the
    // host to poll. That is a complete, usable in-process contract — a host that owns its own
    // drag session (an `NSDraggingSession`, an ArkUI drag, a browser `dragstart`) reports the
    // result through `inject_drop_event`, and a library-internal drag works end to end without
    // any AppKit involvement.
    //
    // What is deliberately **not** here is a native `NSDraggingSession`: starting and driving
    // one requires an `NSPasteboard`, an `IDraggingSource` implementation and a live event loop,
    // none of which can be verified on a Linux host. Claiming it by writing the code and never
    // running it is the failure mode the project's own standards forbid; the state contract
    // above is what can be delivered honestly today, and the Windows backend records the same
    // choice in the same words.

    /// Records a drag originating at `source_widget_id`, with its payload.
    ///
    /// Returns `false` for an id this backend did not create, so a drag cannot be started from
    /// a widget that is not there.
    fn begin_drag(&self, source_widget_id: ObjectId, mime: &str, payload: &[u8]) -> bool {
        self.state.begin_drag(source_widget_id, mime, payload)
    }

    /// Pops the next drop event, if one is queued.
    fn poll_drop_event(&self) -> Option<crate::platform::DropEvent> {
        self.state.pop_drop_event()
    }

    /// Queues a drop event, as a host-reported drop would.
    ///
    /// # Why the refusal is checked here and not left to the queue
    ///
    /// A drop naming a widget that does not exist could only be dispatched against a recycled
    /// id, so an unknown target is refused rather than queued.
    fn inject_drop_event(&self, event: crate::platform::DropEvent) -> bool {
        if !self.state.contains_widget(event.target_widget_id) {
            return false;
        }
        self.state.inject_drop_event(event)
    }

    fn accessibility_bridge(&self) -> Option<&dyn AccessibilityBridge> {
        Some(&self.a11y_bridge)
    }
}