noesis_runtime 0.12.1

Rust bindings for the Noesis GUI Native SDK: load XAML UI, drive the view and renderer, and write custom controls in Rust. Renderer-agnostic; Bevy integration lives in noesis_bevy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! `ICommand` from Rust: let XAML `Command="{Binding ...}"` invoke Rust logic.
//!
//! A [`Command`] wraps a `Noesis::BaseCommand` subclass whose `CanExecute` /
//! `Execute` forward into a Rust [`CommandHandler`]. The command is a
//! `BaseComponent`, so it crosses the FFI the same way every other Rust-owned
//! Noesis value does, as an opaque pointer ([`Command::raw`]). To make it
//! reachable from XAML:
//!
//! 1. Register a Rust-backed view model with a `BaseComponent` dependency
//!    property (see [`ClassBuilder`](crate::classes::ClassBuilder)).
//! 2. Set that DP to the command (safe, no `unsafe`):
//!    `instance.handle().set_command(idx, &command)` (see
//!    [`Instance::set_command`](crate::classes::Instance::set_command)). The
//!    raw [`Instance::set_component`](crate::classes::Instance::set_component)
//!    path remains available for arbitrary `BaseComponent*` values.
//! 3. Expose the instance as a `DataContext`
//!    ([`FrameworkElement::set_data_context`](crate::view::FrameworkElement::set_data_context)).
//! 4. Author `<Button Command="{Binding ThatProperty}"/>` in XAML.
//!
//! When the button is clicked, Noesis calls the command's `Execute`, which
//! runs [`CommandHandler::execute`]. Noesis also queries `CanExecute` to drive
//! the button's `IsEnabled`; call [`Command::raise_can_execute_changed`] after
//! your enabled-state changes so bound controls re-query.
//!
//! # Lifetime
//!
//! [`Command`] holds the caller's `+1` reference, released on drop. If a
//! binding still references the command (the common case while a `Button` is
//! bound to it), the underlying object (and the boxed handler) stay alive
//! until that reference also drops. The handler is freed exactly once, by the
//! C++ destructor, after the last reference goes away. So a `Command` may be
//! dropped while still bound and live; `CanExecute` / `Execute` keep working.
//!
//! # Threading
//!
//! `CanExecute` / `Execute` fire from inside Noesis's input pump on whatever
//! thread drives the view. The handler is stored behind `Send`; keep the work
//! small and route to a queue if you need anything heavy.

#![allow(unsafe_op_in_unsafe_fn)] // thin FFI surface; explicit blocks add noise

use core::ptr::NonNull;
use std::ffi::{CStr, CString, c_void};
use std::os::raw::c_char;

use crate::ffi::{
    CommandVTable, noesis_application_command, noesis_base_component_release,
    noesis_command_binding_attach, noesis_command_binding_create, noesis_command_binding_destroy,
    noesis_command_create, noesis_command_destroy, noesis_command_raise_can_execute_changed,
    noesis_component_command, noesis_routed_command_can_execute, noesis_routed_command_create,
    noesis_routed_command_execute, noesis_routed_command_get_name, noesis_routed_ui_command_create,
    noesis_routed_ui_command_get_text, noesis_routed_ui_command_set_text, noesis_unbox_bool,
    noesis_unbox_double, noesis_unbox_int32, noesis_unbox_string,
};
use crate::view::FrameworkElement;

/// A borrowed C string (`*const c_char`) → owned `String`, or `None` if null.
unsafe fn cstr_opt(p: *const c_char) -> Option<String> {
    if p.is_null() {
        None
    } else {
        Some(std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned())
    }
}

/// A borrowed command parameter: Noesis's `CommandParameter` as an opaque,
/// boxed `Noesis::BaseComponent*`. [`is_none`](Self::is_none) reports the
/// no-parameter case (the bound control supplied none); the typed accessors
/// decode the boxed value, each returning `None` when its runtime type doesn't
/// match. The pointer is borrowed for the duration of the callback; copy /
/// re-root (via Noesis accessors) if you need it past the call.
pub struct CommandParameterValue(Option<NonNull<c_void>>);

impl CommandParameterValue {
    /// Wrap a raw `CommandParameter` pointer, mapping null to the no-parameter
    /// case. Use this to supply a parameter when invoking a command yourself
    /// (e.g. [`RoutedCommand::execute`]).
    #[must_use]
    pub fn new(raw: *mut c_void) -> Self {
        Self(NonNull::new(raw))
    }

    /// Whether the bound control supplied no parameter (a null pointer).
    #[must_use]
    pub fn is_none(&self) -> bool {
        self.0.is_none()
    }

    /// Raw borrowed `Noesis::BaseComponent*` (the boxed value), or `None` when
    /// no parameter was supplied.
    #[must_use]
    pub fn raw(&self) -> Option<NonNull<c_void>> {
        self.0
    }

    /// Unbox a `bool` (a `BoxedValue<bool>`), or `None` on type mismatch / no
    /// parameter.
    #[must_use]
    pub fn as_bool(&self) -> Option<bool> {
        let p = self.0?;
        let mut out = false;
        // SAFETY: p is a live boxed BaseComponent* for the callback; out is valid.
        let ok = unsafe { noesis_unbox_bool(p.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Unbox an `i32` (a `BoxedValue<int>`), or `None` on type mismatch / no
    /// parameter.
    #[must_use]
    pub fn as_i32(&self) -> Option<i32> {
        let p = self.0?;
        let mut out = 0i32;
        // SAFETY: as in `as_bool`.
        let ok = unsafe { noesis_unbox_int32(p.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Unbox an `f64` (a `BoxedValue<double>`), or `None` on type mismatch / no
    /// parameter.
    #[must_use]
    pub fn as_f64(&self) -> Option<f64> {
        let p = self.0?;
        let mut out = 0.0f64;
        // SAFETY: as in `as_bool`.
        let ok = unsafe { noesis_unbox_double(p.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Borrowed view of a boxed string (a `BoxedValue<String>`), valid for the
    /// callback. `None` on type mismatch / no parameter / non-UTF-8. Noesis
    /// boxes a XAML `CommandParameter="..."` literal as a string, so this is the
    /// usual decoder for a constant parameter.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        let p = self.0?;
        // SAFETY: p is a live boxed BaseComponent* for the callback.
        let s = unsafe { noesis_unbox_string(p.as_ptr()) };
        if s.is_null() {
            return None;
        }
        // SAFETY: s is a borrowed NUL-terminated string valid for the callback.
        unsafe { CStr::from_ptr(s) }.to_str().ok()
    }
}

/// Rust-side command logic. `execute` runs the action; `can_execute` gates it
/// (and drives the bound control's `IsEnabled`).
///
/// The `Send + 'static` bounds let the handler live inside a Bevy `Resource`
/// or be moved onto the render thread.
pub trait CommandHandler: Send + 'static {
    /// Whether the command can run now. Default: always `true`. Noesis calls
    /// this to decide a bound `Button`'s enabled state, and again before each
    /// `Execute`. After the answer changes, call
    /// [`Command::raise_can_execute_changed`] so bound controls re-query.
    fn can_execute(&self, _param: CommandParameterValue) -> bool {
        true
    }

    /// Invoke the command. Called when the bound control is activated (e.g. a
    /// `Button` click), but only if [`Self::can_execute`] returned `true`.
    ///
    /// Takes `&self`: a single handler box backs the command, and `execute` may
    /// re-enter the same box (it can trigger a synchronous `can_execute` requery,
    /// or activate another control bound to the same command). Use interior
    /// mutability for handler state.
    fn execute(&self, param: CommandParameterValue);
}

/// Adapter so a bare `Fn` closure is a fire-always [`CommandHandler`]
/// (`can_execute` is always `true`). Use [`Command::new`] with a struct
/// implementing [`CommandHandler`] when you need a controllable
/// `can_execute`.
impl<F: Fn(CommandParameterValue) + Send + 'static> CommandHandler for F {
    fn execute(&self, param: CommandParameterValue) {
        self(param);
    }
}

/// A single, shared vtable suffices for every command: the trampolines are
/// generic-free (they recover the `Box<dyn CommandHandler>` from `userdata`).
static COMMAND_VTABLE: CommandVTable = CommandVTable {
    can_execute: command_can_execute_trampoline,
    execute: command_execute_trampoline,
};

/// SAFETY: `userdata` is the `Box<Box<dyn CommandHandler>>` leaked in
/// [`Command::new`], alive until the free trampoline runs.
unsafe extern "C" fn command_can_execute_trampoline(
    userdata: *mut c_void,
    param: *mut c_void,
) -> bool {
    crate::panic_guard::guard(|| {
        let handler = &*userdata.cast::<Box<dyn CommandHandler>>();
        handler.can_execute(CommandParameterValue::new(param))
    })
}

/// SAFETY: see [`command_can_execute_trampoline`].
unsafe extern "C" fn command_execute_trampoline(userdata: *mut c_void, param: *mut c_void) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `CommandHandler::execute`).
        let handler = &*userdata.cast::<Box<dyn CommandHandler>>();
        handler.execute(CommandParameterValue::new(param));
    })
}

/// SAFETY: `userdata` was produced by [`Command::new`] and C++ owns it; this
/// is the matching `Box::from_raw` that ends that ownership, run exactly once.
unsafe extern "C" fn command_free_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        if userdata.is_null() {
            return;
        }
        drop(Box::from_raw(userdata.cast::<Box<dyn CommandHandler>>()));
    })
}

/// A Rust-backed `ICommand`. Owns a `+1` reference released on drop. Hand
/// [`Command::raw`] to XAML via a view-model `BaseComponent` property (see the
/// module docs).
pub struct Command {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for Command {}

impl Command {
    /// Build a command from a [`CommandHandler`]. A bare
    /// `Fn(CommandParameterValue)` closure also works (fire-always: its
    /// `can_execute` is always `true`).
    ///
    /// # Panics
    ///
    /// Panics only on an impossible internal invariant (`Box::into_raw`
    /// returning null / the C side returning null for a valid vtable, which it
    /// never does).
    #[must_use]
    pub fn new<H: CommandHandler>(handler: H) -> Self {
        // Double-Box for a stable thin pointer across the C ABI.
        let boxed: Box<Box<dyn CommandHandler>> = Box::new(Box::new(handler));
        let userdata = Box::into_raw(boxed);

        // SAFETY: vtable is a 'static valid pointer; userdata is freshly
        // leaked and ownership transfers to C++; free trampoline is extern "C".
        let ptr = unsafe {
            noesis_command_create(&COMMAND_VTABLE, userdata.cast(), command_free_trampoline)
        };

        match NonNull::new(ptr) {
            Some(ptr) => Command { ptr },
            None => {
                // Reclaim the leaked box defensively rather than leak it.
                // SAFETY: userdata came from Box::into_raw above; C++ never
                // stored it (null return = nothing took ownership).
                unsafe { drop(Box::from_raw(userdata)) };
                unreachable!("noesis_command_create returned null for a non-null vtable");
            }
        }
    }

    /// Raw `Noesis::BaseComponent*` (an `ICommand`), for handing to a
    /// view-model `BaseComponent` property
    /// ([`Instance::set_component`](crate::classes::Instance::set_component))
    /// or any API that takes a borrowed component. Borrowed for the lifetime of
    /// `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Fire `CanExecuteChanged` so any control bound to this command re-queries
    /// [`CommandHandler::can_execute`], e.g. a bound `Button` re-evaluates its
    /// `IsEnabled` on the next `View::update`. Call after your enabled-state
    /// logic changes.
    pub fn raise_can_execute_changed(&self) {
        // SAFETY: self.ptr is a live RustCommand* for the lifetime of self.
        unsafe { noesis_command_raise_can_execute_changed(self.ptr.as_ptr()) }
    }
}

impl Drop for Command {
    fn drop(&mut self) {
        // SAFETY: produced by noesis_command_create with +1 ref; this
        // releases exactly that ref. The handler box is freed by the C++
        // destructor once the last reference (possibly a binding) drops.
        unsafe { noesis_command_destroy(self.ptr.as_ptr()) }
    }
}

/// Anything that can be referenced as a `Noesis::ICommand*`: a [`Command`],
/// [`RoutedCommand`], [`RoutedUICommand`], or a built-in [`BorrowedCommand`].
/// Lets a [`CommandBinding`] (and any `Command` DP) accept any of them.
pub trait AsCommand {
    /// Borrowed `Noesis::ICommand*` (`BaseComponent*`), valid for `self`.
    fn command_ptr(&self) -> *mut c_void;
}

impl AsCommand for Command {
    fn command_ptr(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

/// A `Noesis::RoutedCommand` built in code. Unlike [`Command`] (a Rust-backed
/// `ICommand` whose logic lives in the handler), a routed command carries no
/// logic itself. Invoking it routes `Execute` / `CanExecute` through the
/// element tree to the first matching [`CommandBinding`]. Owns a `+1` reference
/// released on drop.
pub struct RoutedCommand {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for RoutedCommand {}

impl RoutedCommand {
    /// Create a routed command named `name`, owned by the type `owner_type`
    /// (resolved through the reflection registry, a built-in like `"UIElement"`
    /// or a [`ClassBuilder`](crate::classes)-registered custom class). Returns
    /// `None` if `owner_type` can't be resolved to a class.
    ///
    /// # Panics
    ///
    /// Panics if `name` / `owner_type` contain an interior NUL byte.
    #[must_use]
    pub fn new(name: &str, owner_type: &str) -> Option<Self> {
        let cn = CString::new(name).expect("name contained interior NUL");
        let co = CString::new(owner_type).expect("owner_type contained interior NUL");
        // SAFETY: both C strings live for the call; C returns +1 or NULL.
        let ptr = unsafe { noesis_routed_command_create(cn.as_ptr(), co.as_ptr()) };
        NonNull::new(ptr).map(|ptr| Self { ptr })
    }

    /// Execute the command against `target` (a `UIElement`), routing to its
    /// `CommandBinding`s. `param` is an optional borrowed command parameter.
    pub fn execute(&self, param: CommandParameterValue, target: &FrameworkElement) {
        // SAFETY: self.ptr is a live RoutedCommand*; target.raw() a live element.
        unsafe {
            noesis_routed_command_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw());
        }
    }

    /// Whether the command can currently execute against `target` (queries its
    /// `CommandBinding`s' `CanExecute`). `false` if nothing handles it.
    #[must_use]
    pub fn can_execute(&self, param: CommandParameterValue, target: &FrameworkElement) -> bool {
        // SAFETY: as above.
        unsafe {
            noesis_routed_command_can_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw())
        }
    }

    /// The command's registered name (`RoutedCommand::GetName`).
    #[must_use]
    pub fn name(&self) -> Option<String> {
        // SAFETY: self.ptr is a live RoutedCommand*; returns a borrowed interned
        // string we copy immediately.
        unsafe { cstr_opt(noesis_routed_command_get_name(self.ptr.as_ptr())) }
    }

    /// Raw `Noesis::ICommand*`, borrowed for the lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

impl AsCommand for RoutedCommand {
    fn command_ptr(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

impl Drop for RoutedCommand {
    fn drop(&mut self) {
        // SAFETY: +1 from create, released exactly once here.
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

/// A `Noesis::RoutedUICommand`: a [`RoutedCommand`] plus localizable display
/// `Text` (e.g. for menu items). Owns a `+1` reference released on drop.
pub struct RoutedUICommand {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for RoutedUICommand {}

impl RoutedUICommand {
    /// Create a routed UI command. `text` is the display label; see
    /// [`RoutedCommand::new`] for `name` / `owner_type`. Returns `None` if the
    /// owner type can't be resolved.
    ///
    /// # Panics
    ///
    /// Panics if any argument contains an interior NUL byte.
    #[must_use]
    pub fn new(name: &str, text: &str, owner_type: &str) -> Option<Self> {
        let cn = CString::new(name).expect("name contained interior NUL");
        let ct = CString::new(text).expect("text contained interior NUL");
        let co = CString::new(owner_type).expect("owner_type contained interior NUL");
        // SAFETY: all C strings live for the call; C returns +1 or NULL.
        let ptr = unsafe { noesis_routed_ui_command_create(cn.as_ptr(), ct.as_ptr(), co.as_ptr()) };
        NonNull::new(ptr).map(|ptr| Self { ptr })
    }

    /// See [`RoutedCommand::execute`].
    pub fn execute(&self, param: CommandParameterValue, target: &FrameworkElement) {
        // SAFETY: self.ptr is a live RoutedUICommand* (a RoutedCommand).
        unsafe {
            noesis_routed_command_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw());
        }
    }

    /// See [`RoutedCommand::can_execute`].
    #[must_use]
    pub fn can_execute(&self, param: CommandParameterValue, target: &FrameworkElement) -> bool {
        // SAFETY: as above.
        unsafe {
            noesis_routed_command_can_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw())
        }
    }

    /// The display text (`RoutedUICommand::GetText`).
    #[must_use]
    pub fn text(&self) -> Option<String> {
        // SAFETY: self.ptr is a live RoutedUICommand*; borrowed string copied.
        unsafe { cstr_opt(noesis_routed_ui_command_get_text(self.ptr.as_ptr())) }
    }

    /// Set the display text.
    ///
    /// # Panics
    ///
    /// Panics if `text` contains an interior NUL byte.
    pub fn set_text(&mut self, text: &str) {
        let c = CString::new(text).expect("text contained interior NUL");
        // SAFETY: self.ptr is a live RoutedUICommand*; c lives for the call.
        unsafe { noesis_routed_ui_command_set_text(self.ptr.as_ptr(), c.as_ptr()) };
    }

    /// The command's registered name (`RoutedCommand::GetName`).
    #[must_use]
    pub fn name(&self) -> Option<String> {
        // SAFETY: self.ptr is a live RoutedCommand*; borrowed string copied.
        unsafe { cstr_opt(noesis_routed_command_get_name(self.ptr.as_ptr())) }
    }

    /// Raw `Noesis::ICommand*`, borrowed for the lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

impl AsCommand for RoutedUICommand {
    fn command_ptr(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

impl Drop for RoutedUICommand {
    fn drop(&mut self) {
        // SAFETY: +1 from create, released exactly once here.
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

/// [`CommandParameterValue`] → raw pointer for the C ABI (NULL when no
/// parameter). Used on the outbound path when we invoke a command ourselves.
fn param_ptr(param: &CommandParameterValue) -> *mut c_void {
    param.raw().map_or(core::ptr::null_mut(), NonNull::as_ptr)
}

/// A borrowed reference to a framework-owned `RoutedUICommand` singleton (the
/// built-in [`ApplicationCommand`] / [`ComponentCommand`] libraries). It holds
/// no reference and runs no `Drop` (the framework owns these for the process
/// lifetime), so it is `Copy`. Use it as a [`CommandBinding`] command or assign
/// it to a control's `Command` property.
#[derive(Copy, Clone)]
pub struct BorrowedCommand {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for BorrowedCommand {}

impl BorrowedCommand {
    /// Raw `Noesis::ICommand*`, valid for the process lifetime.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// The command's display text (these built-ins are `RoutedUICommand`s).
    #[must_use]
    pub fn text(&self) -> Option<String> {
        // SAFETY: self.ptr is a live RoutedUICommand*; borrowed string copied.
        unsafe { cstr_opt(noesis_routed_ui_command_get_text(self.ptr.as_ptr())) }
    }

    /// The command's registered name.
    #[must_use]
    pub fn name(&self) -> Option<String> {
        // SAFETY: self.ptr is a live RoutedCommand*; borrowed string copied.
        unsafe { cstr_opt(noesis_routed_command_get_name(self.ptr.as_ptr())) }
    }

    /// Execute this command against `target` (a `UIElement`), routing to its
    /// `CommandBinding`s. The built-ins are `RoutedCommand`s. See
    /// [`RoutedCommand::execute`].
    pub fn execute(&self, param: CommandParameterValue, target: &FrameworkElement) {
        // SAFETY: self.ptr is a live RoutedCommand*; target.raw() a live element.
        unsafe {
            noesis_routed_command_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw());
        }
    }

    /// Whether this command can currently execute against `target`. See
    /// [`RoutedCommand::can_execute`].
    #[must_use]
    pub fn can_execute(&self, param: CommandParameterValue, target: &FrameworkElement) -> bool {
        // SAFETY: as above.
        unsafe {
            noesis_routed_command_can_execute(self.ptr.as_ptr(), param_ptr(&param), target.raw())
        }
    }
}

impl AsCommand for BorrowedCommand {
    fn command_ptr(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

/// The `ApplicationCommands` library: common application-level commands
/// (clipboard, document, edit). [`Self::command`] returns the framework
/// singleton.
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApplicationCommand {
    CancelPrint = 0,
    Close = 1,
    ContextMenu = 2,
    Copy = 3,
    CorrectionList = 4,
    Cut = 5,
    Delete = 6,
    Find = 7,
    Help = 8,
    New = 9,
    Open = 10,
    Paste = 11,
    Print = 12,
    PrintPreview = 13,
    Properties = 14,
    Redo = 15,
    Replace = 16,
    Save = 17,
    SaveAs = 18,
    SelectAll = 19,
    Stop = 20,
    Undo = 21,
}

impl ApplicationCommand {
    /// The framework's `RoutedUICommand` singleton for this command.
    ///
    /// # Panics
    ///
    /// Panics if the Noesis runtime is not initialized (the singletons are set
    /// up during [`crate::init`]).
    #[must_use]
    pub fn command(self) -> BorrowedCommand {
        // SAFETY: returns a borrowed framework singleton (valid after init()).
        let ptr = unsafe { noesis_application_command(self as u32) };
        BorrowedCommand {
            ptr: NonNull::new(ptr.cast_mut())
                .expect("ApplicationCommands singleton was null (runtime not initialized?)"),
        }
    }
}

/// The `ComponentCommands` library: control-internal navigation / selection /
/// scrolling commands. [`Self::command`] returns the framework singleton.
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ComponentCommand {
    ExtendSelectionDown = 0,
    ExtendSelectionLeft = 1,
    ExtendSelectionRight = 2,
    ExtendSelectionUp = 3,
    MoveDown = 4,
    MoveFocusBack = 5,
    MoveFocusDown = 6,
    MoveFocusForward = 7,
    MoveFocusPageDown = 8,
    MoveFocusPageUp = 9,
    MoveFocusUp = 10,
    MoveLeft = 11,
    MoveRight = 12,
    MoveToEnd = 13,
    MoveToHome = 14,
    MoveToPageDown = 15,
    MoveToPageUp = 16,
    MoveUp = 17,
    ScrollByLine = 18,
    ScrollPageDown = 19,
    ScrollPageLeft = 20,
    ScrollPageRight = 21,
    ScrollPageUp = 22,
    SelectToEnd = 23,
    SelectToHome = 24,
    SelectToPageDown = 25,
    SelectToPageUp = 26,
}

impl ComponentCommand {
    /// The framework's `RoutedUICommand` singleton for this command.
    ///
    /// # Panics
    ///
    /// Panics if the Noesis runtime is not initialized.
    #[must_use]
    pub fn command(self) -> BorrowedCommand {
        // SAFETY: returns a borrowed framework singleton (valid after init()).
        let ptr = unsafe { noesis_component_command(self as u32) };
        BorrowedCommand {
            ptr: NonNull::new(ptr.cast_mut())
                .expect("ComponentCommands singleton was null (runtime not initialized?)"),
        }
    }
}

/// Rust handlers for a [`CommandBinding`]: `execute` runs the action when a
/// bound command is invoked through the attached element; `can_execute` gates
/// it (default always-`true`). A bare `Fn(CommandParameterValue)` closure works
/// as a fire-always handler.
pub trait CommandBindingHandler: Send + 'static {
    /// Whether the command may run now. Default `true`.
    fn can_execute(&self, _param: CommandParameterValue) -> bool {
        true
    }

    /// Run the command's action.
    ///
    /// Takes `&self` (re-entrant per the same reasoning as
    /// [`CommandHandler::execute`]; use interior mutability for handler state).
    fn execute(&self, param: CommandParameterValue);
}

impl<F: Fn(CommandParameterValue) + Send + 'static> CommandBindingHandler for F {
    fn execute(&self, param: CommandParameterValue) {
        self(param);
    }
}

/// SAFETY: `userdata` is the double-boxed handler leaked in
/// [`CommandBinding::new`], alive until the free trampoline runs.
unsafe extern "C" fn cb_executed_trampoline(userdata: *mut c_void, param: *mut c_void) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `CommandBindingHandler`).
        let handler = &*userdata.cast::<Box<dyn CommandBindingHandler>>();
        handler.execute(CommandParameterValue::new(param));
    })
}

/// SAFETY: see [`cb_executed_trampoline`].
unsafe extern "C" fn cb_can_execute_trampoline(userdata: *mut c_void, param: *mut c_void) -> bool {
    crate::panic_guard::guard(|| {
        let handler = &*userdata.cast::<Box<dyn CommandBindingHandler>>();
        handler.can_execute(CommandParameterValue::new(param))
    })
}

/// SAFETY: matching `Box::from_raw` for the leak in [`CommandBinding::new`],
/// run exactly once by the C++ destructor.
unsafe extern "C" fn cb_free_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        if userdata.is_null() {
            return;
        }
        drop(Box::from_raw(
            userdata.cast::<Box<dyn CommandBindingHandler>>(),
        ));
    })
}

/// Binds a command to Rust handlers and (once [`attached`](Self::attach)) makes
/// an element respond to that command when it's invoked and routes through the
/// element. RAII: drop it to detach the handlers, remove the binding from the
/// element it was attached to, and free them. Dropping it from inside its own
/// `Executed` / `CanExecute` handler is safe (the C++ bridge owns the handler
/// box and defers its own destruction until the callback frame unwinds).
pub struct CommandBinding {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for CommandBinding {}

impl CommandBinding {
    /// Build a binding for `command` (any [`AsCommand`]: a [`RoutedCommand`],
    /// [`RoutedUICommand`], built-in [`BorrowedCommand`], or [`Command`]) with
    /// the given [`CommandBindingHandler`]. Attach it to an element with
    /// [`Self::attach`]. Returns `None` only if the C entrypoint fails (e.g. a
    /// non-command pointer).
    #[must_use]
    pub fn new<C: AsCommand, H: CommandBindingHandler>(command: &C, handler: H) -> Option<Self> {
        let boxed: Box<Box<dyn CommandBindingHandler>> = Box::new(Box::new(handler));
        let userdata = Box::into_raw(boxed);

        // SAFETY: trampolines are extern "C"; userdata is freshly leaked and
        // donated to the C++ bridge (freed via cb_free on destroy); the command
        // pointer is borrowed for the call only.
        let token = unsafe {
            noesis_command_binding_create(
                command.command_ptr(),
                cb_executed_trampoline,
                Some(cb_can_execute_trampoline),
                userdata.cast(),
                cb_free_trampoline,
            )
        };

        match NonNull::new(token) {
            Some(token) => Some(Self { token }),
            None => {
                // SAFETY: userdata came from Box::into_raw above; nothing took it.
                unsafe { drop(Box::from_raw(userdata)) };
                None
            }
        }
    }

    /// Attach this binding to `element`'s `CommandBindings` so commands invoked
    /// on (or routing through) the element reach these handlers. Returns `false`
    /// if `element` is not a `UIElement`. Dropping the binding removes it from
    /// the element's `CommandBindings` again, so it does not accumulate there.
    /// The binding remembers the element it was attached to (holding a `+1`
    /// ref); calling `attach` on more than one element only auto-detaches from
    /// the most recent.
    pub fn attach(&self, element: &FrameworkElement) -> bool {
        // SAFETY: token is a live bridge; element.raw() a live element.
        unsafe { noesis_command_binding_attach(self.token.as_ptr(), element.raw()) }
    }
}

impl Drop for CommandBinding {
    fn drop(&mut self) {
        // SAFETY: token from new(); destroy detaches the delegates, removes the
        // binding from the attached element, and frees the donated handler box
        // exactly once (deferred if dropping from inside the callback).
        unsafe { noesis_command_binding_destroy(self.token.as_ptr()) }
    }
}