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
//! Build [`Rectangle`], [`Ellipse`], and [`Line`] shapes from Rust and set
//! their drawing properties without authoring XAML.
//!
//! Each handle owns a freshly-created Noesis shape holding a single `+1`
//! reference released on [`Drop`], the same ownership idiom as
//! [`crate::brushes`] / [`crate::transforms`]. A shape *is* a
//! [`FrameworkElement`](crate::view::FrameworkElement), so once built you can
//! hand its [`raw`](Rectangle::raw) pointer to the element tree (e.g. as a
//! `Panel` child) and let Noesis take its own reference, after which the Rust
//! handle may be dropped.
//!
//! `Fill` and `Stroke` accept any [`Brush`] handle from [`crate::brushes`];
//! Noesis takes its own reference to the brush, so the handle may be dropped
//! afterwards.
//!
//! Every setter has a matching getter that re-reads from the live Noesis object
//! rather than echoing a Rust-side cache.
//!
//! # SDK scope
//!
//! Noesis ships only `Rectangle`, `Ellipse`, `Line`, and `Path` as shape
//! elements; there is **no** `Polygon`/`Polyline`. Build a polygon or polyline
//! as a `PathGeometry`/`StreamGeometry` hosted in a `Path`.

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

use crate::brushes::Brush;
use crate::ffi::{
    noesis_base_component_add_reference, noesis_base_component_release, noesis_ellipse_create,
    noesis_line_create, noesis_line_get, noesis_line_set, noesis_rectangle_create,
    noesis_rectangle_get_radius_x, noesis_rectangle_get_radius_y, noesis_rectangle_set_radius_x,
    noesis_rectangle_set_radius_y, noesis_shape_get_fill, noesis_shape_get_height,
    noesis_shape_get_stretch, noesis_shape_get_stroke, noesis_shape_get_stroke_dash_array,
    noesis_shape_get_stroke_dash_cap, noesis_shape_get_stroke_dash_offset,
    noesis_shape_get_stroke_end_line_cap, noesis_shape_get_stroke_line_join,
    noesis_shape_get_stroke_miter_limit, noesis_shape_get_stroke_start_line_cap,
    noesis_shape_get_stroke_thickness, noesis_shape_get_trim_end, noesis_shape_get_trim_offset,
    noesis_shape_get_trim_start, noesis_shape_get_width, noesis_shape_set_fill,
    noesis_shape_set_height, noesis_shape_set_stretch, noesis_shape_set_stroke,
    noesis_shape_set_stroke_dash_array, noesis_shape_set_stroke_dash_cap,
    noesis_shape_set_stroke_dash_offset, noesis_shape_set_stroke_end_line_cap,
    noesis_shape_set_stroke_line_join, noesis_shape_set_stroke_miter_limit,
    noesis_shape_set_stroke_start_line_cap, noesis_shape_set_stroke_thickness,
    noesis_shape_set_trim_end, noesis_shape_set_trim_offset, noesis_shape_set_trim_start,
    noesis_shape_set_width,
};

/// How the ends of a dash (or a line) are drawn. Ordinals mirror
/// `Noesis::PenLineCap`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum PenLineCap {
    /// A cap that does not extend past the last point of the line.
    Flat = 0,
    /// A rectangle half the line thickness long.
    Square = 1,
    /// A semicircle with diameter equal to the line thickness.
    Round = 2,
    /// An isosceles right triangle.
    Triangle = 3,
}

/// How the vertices of a shape are joined. Ordinals mirror
/// `Noesis::PenLineJoin`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum PenLineJoin {
    /// Regular angular (mitered) vertices.
    Miter = 0,
    /// Beveled vertices.
    Bevel = 1,
    /// Rounded vertices.
    Round = 2,
}

/// How a shape fills its allocated space. Re-exported from [`crate::brushes`]
/// so the crate has a single `Stretch` type (ordinals mirror `Noesis::Stretch`).
pub use crate::brushes::Stretch;

impl PenLineCap {
    fn from_ordinal(v: i32) -> Option<Self> {
        match v {
            0 => Some(Self::Flat),
            1 => Some(Self::Square),
            2 => Some(Self::Round),
            3 => Some(Self::Triangle),
            _ => None,
        }
    }
}

impl PenLineJoin {
    fn from_ordinal(v: i32) -> Option<Self> {
        match v {
            0 => Some(Self::Miter),
            1 => Some(Self::Bevel),
            2 => Some(Self::Round),
            _ => None,
        }
    }
}

/// A handle to a Noesis `Shape` (the base class of [`Rectangle`], [`Ellipse`],
/// and [`Line`]). The trait carries every property defined on `Shape` plus the
/// inherited `FrameworkElement` `Width`/`Height`, so all three concrete shapes
/// share one implementation.
///
/// Getters re-read from the live Noesis object.
pub trait Shape {
    /// Borrowed `Noesis::Shape*` (also a `FrameworkElement*` / `BaseComponent*`),
    /// valid for `self`'s lifetime. Used by the shared property methods and by
    /// callers handing the shape to other Noesis APIs (e.g. tree insertion).
    fn shape_raw(&self) -> *mut c_void;

    /// View this shape as an owning [`FrameworkElement`](crate::view::FrameworkElement)
    /// handle (a fresh `+1`) so it can be handed to element-tree APIs that take a
    /// `&FrameworkElement` — e.g.
    /// [`FrameworkElement::set_content`](crate::view::FrameworkElement::set_content)
    /// (a `ContentControl`'s `Content`) or
    /// [`FrameworkElement::set_decorator_child`](crate::view::FrameworkElement::set_decorator_child)
    /// (a `Border`/`Decorator`'s `Child`). Dropping the returned handle releases
    /// only its own reference and does not affect `self`.
    #[must_use]
    fn as_element(&self) -> crate::view::FrameworkElement {
        // SAFETY: shape_raw() is a live FrameworkElement*/BaseComponent*; AddRef
        // hands back an independent +1 the returned handle owns and releases on
        // drop.
        let p = unsafe { noesis_base_component_add_reference(self.shape_raw()) };
        let ptr = NonNull::new(p).expect("add_reference returned null on a live shape");
        // SAFETY: `ptr` carries the +1 we just took ownership of.
        unsafe { crate::view::FrameworkElement::from_owned(ptr) }
    }

    /// Set the element's explicit `Width` (a `FrameworkElement` DP; `NaN` ==
    /// "auto").
    fn set_width(&mut self, width: f32) {
        // SAFETY: shape_raw() is a live Shape*/FrameworkElement*.
        unsafe { noesis_shape_set_width(self.shape_raw(), width) };
    }

    /// Read the element's explicit `Width` back from the live object.
    #[must_use]
    fn width(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is a valid f32 slot.
        unsafe { noesis_shape_get_width(self.shape_raw(), &mut out) };
        out
    }

    /// Set the element's explicit `Height` (`NaN` == "auto").
    fn set_height(&mut self, height: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_height(self.shape_raw(), height) };
    }

    /// Read the element's explicit `Height` back from the live object.
    #[must_use]
    fn height(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is a valid f32 slot.
        unsafe { noesis_shape_get_height(self.shape_raw(), &mut out) };
        out
    }

    /// Paint the shape's interior with `brush` (any [`Brush`] handle). Noesis
    /// takes its own reference, so the brush handle may be dropped afterwards.
    fn set_fill<B: Brush>(&mut self, brush: &B) {
        // SAFETY: shape_raw() is live; brush_raw() is a live Brush* borrowed for
        // the call; Noesis stores its own reference.
        unsafe { noesis_shape_set_fill(self.shape_raw(), brush.brush_raw()) };
    }

    /// Clear the shape's `Fill`.
    fn clear_fill(&mut self) {
        // SAFETY: shape_raw() is live; a null brush clears the property.
        unsafe { noesis_shape_set_fill(self.shape_raw(), core::ptr::null_mut()) };
    }

    /// Borrowed `Brush*` currently set as `Fill`, or null if unset. Returned
    /// without a `+1`; use it only for identity checks against a brush handle's
    /// [`raw`](crate::brushes::SolidColorBrush::raw).
    #[must_use]
    fn fill_raw(&self) -> *mut c_void {
        // SAFETY: shape_raw() is live; the returned pointer is borrowed.
        unsafe { noesis_shape_get_fill(self.shape_raw()) }
    }

    /// Paint the shape's outline with `brush`.
    fn set_stroke<B: Brush>(&mut self, brush: &B) {
        // SAFETY: shape_raw() is live; brush_raw() is a live Brush* for the call.
        unsafe { noesis_shape_set_stroke(self.shape_raw(), brush.brush_raw()) };
    }

    /// Clear the shape's `Stroke`.
    fn clear_stroke(&mut self) {
        // SAFETY: shape_raw() is live; a null brush clears the property.
        unsafe { noesis_shape_set_stroke(self.shape_raw(), core::ptr::null_mut()) };
    }

    /// Borrowed `Brush*` currently set as `Stroke`, or null if unset.
    #[must_use]
    fn stroke_raw(&self) -> *mut c_void {
        // SAFETY: shape_raw() is live; the returned pointer is borrowed.
        unsafe { noesis_shape_get_stroke(self.shape_raw()) }
    }

    /// Set the outline width.
    fn set_stroke_thickness(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_thickness(self.shape_raw(), value) };
    }

    /// Read the outline width back from the live object.
    #[must_use]
    fn stroke_thickness(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_stroke_thickness(self.shape_raw(), &mut out) };
        out
    }

    /// Set the miter-length limit (ratio to half the `StrokeThickness`).
    fn set_stroke_miter_limit(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_miter_limit(self.shape_raw(), value) };
    }

    /// Read the miter limit back from the live object.
    #[must_use]
    fn stroke_miter_limit(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_stroke_miter_limit(self.shape_raw(), &mut out) };
        out
    }

    /// Set the distance into the dash pattern at which a dash begins.
    fn set_stroke_dash_offset(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_dash_offset(self.shape_raw(), value) };
    }

    /// Read the dash offset back from the live object.
    #[must_use]
    fn stroke_dash_offset(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_stroke_dash_offset(self.shape_raw(), &mut out) };
        out
    }

    /// Set the amount to trim from the start of the geometry path (`0..=1`).
    fn set_trim_start(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_trim_start(self.shape_raw(), value) };
    }

    /// Read the trim-start back from the live object.
    #[must_use]
    fn trim_start(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_trim_start(self.shape_raw(), &mut out) };
        out
    }

    /// Set the amount to trim from the end of the geometry path (`0..=1`).
    fn set_trim_end(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_trim_end(self.shape_raw(), value) };
    }

    /// Read the trim-end back from the live object.
    #[must_use]
    fn trim_end(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_trim_end(self.shape_raw(), &mut out) };
        out
    }

    /// Set the amount to offset trimming the geometry path.
    fn set_trim_offset(&mut self, value: f32) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_trim_offset(self.shape_raw(), value) };
    }

    /// Read the trim-offset back from the live object.
    #[must_use]
    fn trim_offset(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: shape_raw() is live; `out` is valid.
        unsafe { noesis_shape_get_trim_offset(self.shape_raw(), &mut out) };
        out
    }

    /// Set the cap drawn at the ends of each dash.
    fn set_stroke_dash_cap(&mut self, cap: PenLineCap) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_dash_cap(self.shape_raw(), cap as i32) };
    }

    /// Read the dash cap back from the live object.
    #[must_use]
    fn stroke_dash_cap(&self) -> Option<PenLineCap> {
        // SAFETY: shape_raw() is live.
        PenLineCap::from_ordinal(unsafe { noesis_shape_get_stroke_dash_cap(self.shape_raw()) })
    }

    /// Set the cap drawn at the start of the stroke.
    fn set_stroke_start_line_cap(&mut self, cap: PenLineCap) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_start_line_cap(self.shape_raw(), cap as i32) };
    }

    /// Read the start line cap back from the live object.
    #[must_use]
    fn stroke_start_line_cap(&self) -> Option<PenLineCap> {
        // SAFETY: shape_raw() is live.
        PenLineCap::from_ordinal(unsafe {
            noesis_shape_get_stroke_start_line_cap(self.shape_raw())
        })
    }

    /// Set the cap drawn at the end of the stroke.
    fn set_stroke_end_line_cap(&mut self, cap: PenLineCap) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_end_line_cap(self.shape_raw(), cap as i32) };
    }

    /// Read the end line cap back from the live object.
    #[must_use]
    fn stroke_end_line_cap(&self) -> Option<PenLineCap> {
        // SAFETY: shape_raw() is live.
        PenLineCap::from_ordinal(unsafe { noesis_shape_get_stroke_end_line_cap(self.shape_raw()) })
    }

    /// Set the join used at the vertices of the stroke.
    fn set_stroke_line_join(&mut self, join: PenLineJoin) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stroke_line_join(self.shape_raw(), join as i32) };
    }

    /// Read the line join back from the live object.
    #[must_use]
    fn stroke_line_join(&self) -> Option<PenLineJoin> {
        // SAFETY: shape_raw() is live.
        PenLineJoin::from_ordinal(unsafe { noesis_shape_get_stroke_line_join(self.shape_raw()) })
    }

    /// Set how the shape stretches to fill its allocated space.
    fn set_stretch(&mut self, stretch: Stretch) {
        // SAFETY: shape_raw() is live.
        unsafe { noesis_shape_set_stretch(self.shape_raw(), stretch as i32) };
    }

    /// Read the stretch mode back from the live object.
    #[must_use]
    fn stretch(&self) -> Option<Stretch> {
        // SAFETY: shape_raw() is live.
        Stretch::from_ordinal(unsafe { noesis_shape_get_stretch(self.shape_raw()) })
    }

    /// Set the dash pattern. Noesis exposes this as a space-separated string of
    /// dash/gap lengths (e.g. `"2 1 3"`).
    ///
    /// # Panics
    ///
    /// Panics if `dashes` contains an interior NUL byte.
    fn set_stroke_dash_array(&mut self, dashes: &str) {
        let c = CString::new(dashes).expect("dash array contained NUL");
        // SAFETY: shape_raw() is live; `c` outlives the call and the C side
        // copies it into the Noesis object.
        unsafe { noesis_shape_set_stroke_dash_array(self.shape_raw(), c.as_ptr()) };
    }

    /// Read the dash pattern back from the live object as an owned `String`
    /// (empty if unset).
    #[must_use]
    fn stroke_dash_array(&self) -> String {
        // SAFETY: shape_raw() is live; the returned pointer is owned by the
        // Noesis object and valid until the next mutation, so we copy immediately.
        let p = unsafe { noesis_shape_get_stroke_dash_array(self.shape_raw()) };
        if p.is_null() {
            String::new()
        } else {
            // SAFETY: `p` is a NUL-terminated C string from Noesis.
            unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
        }
    }
}

macro_rules! shape_handle {
    ($name:ident, $create:ident, $doc:literal) => {
        #[doc = $doc]
        pub struct $name {
            ptr: NonNull<c_void>,
        }

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

        impl $name {
            /// Create the shape with default property values.
            ///
            /// # Panics
            ///
            /// Panics if Noesis fails to allocate the shape (not expected after
            /// [`crate::init`]).
            #[must_use]
            pub fn new() -> Self {
                // SAFETY: a plain component-create call; returns a +1 ref we own.
                let ptr = unsafe { $create() };
                Self {
                    ptr: NonNull::new(ptr).expect(concat!(stringify!($create), " returned null")),
                }
            }

            /// Raw `Noesis::Shape*` (also a `FrameworkElement*` /
            /// `BaseComponent*`). Borrowed for the lifetime of `self`; hand it to
            /// other Noesis APIs (e.g. inserting the shape into an element tree).
            #[must_use]
            pub fn raw(&self) -> *mut c_void {
                self.ptr.as_ptr()
            }
        }

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

        impl Shape for $name {
            fn shape_raw(&self) -> *mut c_void {
                self.ptr.as_ptr()
            }
        }

        impl Drop for $name {
            fn drop(&mut self) {
                // SAFETY: produced by a `*_create` entrypoint with a +1 ref we
                // own; released exactly once here.
                unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
            }
        }
    };
}

shape_handle!(
    Rectangle,
    noesis_rectangle_create,
    "A `Rectangle` shape. Adds rounded-corner radii on top of the shared\n\
     [`Shape`] surface; its size comes from the inherited\n\
     [`Shape::set_width`]/[`Shape::set_height`]."
);
shape_handle!(
    Ellipse,
    noesis_ellipse_create,
    "An `Ellipse` shape. Carries only the shared [`Shape`] surface; its size\n\
     comes from the inherited [`Shape::set_width`]/[`Shape::set_height`]."
);
shape_handle!(
    Line,
    noesis_line_create,
    "A `Line` shape defined by its two endpoints `(X1, Y1)`-`(X2, Y2)` in\n\
     addition to the shared [`Shape`] surface."
);

impl Rectangle {
    /// Set the x-axis corner radius.
    pub fn set_radius_x(&mut self, value: f32) {
        // SAFETY: self.ptr is a live Rectangle*.
        unsafe { noesis_rectangle_set_radius_x(self.ptr.as_ptr(), value) };
    }

    /// Read the x-axis corner radius back from the live object.
    #[must_use]
    pub fn radius_x(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: self.ptr is live; `out` is valid.
        unsafe { noesis_rectangle_get_radius_x(self.ptr.as_ptr(), &mut out) };
        out
    }

    /// Set the y-axis corner radius.
    pub fn set_radius_y(&mut self, value: f32) {
        // SAFETY: self.ptr is a live Rectangle*.
        unsafe { noesis_rectangle_set_radius_y(self.ptr.as_ptr(), value) };
    }

    /// Read the y-axis corner radius back from the live object.
    #[must_use]
    pub fn radius_y(&self) -> f32 {
        let mut out = 0.0f32;
        // SAFETY: self.ptr is live; `out` is valid.
        unsafe { noesis_rectangle_get_radius_y(self.ptr.as_ptr(), &mut out) };
        out
    }
}

impl Line {
    /// Set both endpoints at once: `(x1, y1)` start and `(x2, y2)` end.
    pub fn set_points(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
        // SAFETY: self.ptr is a live Line*.
        unsafe { noesis_line_set(self.ptr.as_ptr(), x1, y1, x2, y2) };
    }

    /// Read both endpoints back from the live object as `[x1, y1, x2, y2]`.
    #[must_use]
    pub fn points(&self) -> [f32; 4] {
        let mut out = [0.0f32; 4];
        // SAFETY: self.ptr is live; `out` is a 4-float buffer.
        unsafe { noesis_line_get(self.ptr.as_ptr(), out.as_mut_ptr()) };
        out
    }
}