xengui 0.2.7

a retained-mode gui library in rust
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
// SPDX-License-Identifier: Apache-2.0
use smol_str::SmolStr;

use crate::{
    AnimationManager,
    Background,
    Border,
    BoxShadow,
    BoxShadowCommand,
    Color,
    Constraints,
    EventCtx,
    EventStatus,
    InputEvent,
    Interaction,
    LayoutBox,
    Length,
    MeasureContext,
    MeasureResult,
    Outline,
    PaintContext,
    RectCommand,
    Style,
    WidgetId,
    properties::StyleValue,
};
use std::any::Any;

/// Snapshot of a widget's text-input state, used to mirror it onto a real
/// DOM `<input>` on web targets so mobile browsers open the keyboard.
#[derive(Clone, Debug)]
pub struct NativeTextInputSnapshot {
    pub value: String,
    pub placeholder: String,
    pub max_length: Option<usize>,
    pub read_only: bool,
}

pub trait Widget: Any {
    fn as_any(&self) -> &dyn Any;

    fn as_any_mut(&mut self) -> &mut dyn Any;

    fn debug_name(&self) -> &'static str {
        "Widget"
    }

    fn get_key(&self) -> Option<&SmolStr> {
        None
    }

    fn is_dirty(&self) -> bool;

    fn set_dirty(&mut self, dirty: bool);

    fn style(&self) -> &Style;

    fn style_mut(&mut self) -> &mut Style;

    fn computed_style(&self) -> &Style {
        self.style()
    }

    /// Called once, right after this widget is inserted into the tree.
    fn on_mount(&mut self) {}

    /// Called once, right before this widget is permanently removed from the tree.
    fn on_unmount(&mut self) {}

    fn children(&self) -> &[Box<dyn Widget>] {
        &[]
    }

    fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
        None
    }

    /// Additional scroll translation applied to this widget's children
    /// during layout, in logical pixels.
    fn scroll_offset(&self) -> (f32, f32) {
        (0.0, 0.0)
    }

    /// Reports this widget's total content size after layout, which may
    /// exceed `layout_box()` when children overflow it.
    fn set_content_size(&mut self, _size: (f32, f32)) {}

    /// The rectangle this widget clips its children's painted output to,
    /// in absolute screen coordinates. `None` means no clipping.
    fn clip_children(&self) -> Option<(f32, f32, f32, f32)> {
        None
    }

    fn measure(&self, ctx: &mut MeasureContext, constraints: Constraints) -> MeasureResult;

    /// Runs once per full layout pass for every widget, leaf or not,
    /// purely so a widget can cache intrinsic measurements it needs later
    /// for painting (e.g. a popup's natural width) without affecting its
    /// own flex/grid size, which `measure` alone controls.
    fn on_layout_pass(&self, _ctx: &mut MeasureContext) {}

    fn layout(&mut self, rect: LayoutBox);

    fn layout_box(&self) -> &LayoutBox;

    fn paint(&self, ctx: &mut PaintContext);

    /// Painted after every descendant, on top of them, and never cached -
    /// used for overlays like a scrollbar thumb that depend on live state.
    fn paint_overlay(&self, _ctx: &mut PaintContext) {}

    fn paint_box(&self, ctx: &mut PaintContext) {
        let style = self.computed_style();
        let sf = ctx.scale_factor;
        let layout = *self.layout_box();
        let radius = style.border
            .as_ref()
            .and_then(|b| b.radius)
            .map(|r| r.to_physical(sf))
            .unwrap_or(0.0);

        if let Some(shadows) = &style.box_shadow {
            for shadow in shadows
                .iter()
                .rev()
                .filter(|s| !s.inset) {
                self.paint_shadow_layer(ctx, layout, radius, shadow, sf);
            }
        }

        if style.background.is_some() || style.border.is_some() {
            let border = style.border.as_ref();

            if border.is_some_and(|b| !b.is_uniform()) {
                if style.background.is_some() {
                    ctx.draw_rect(RectCommand {
                        position: (layout.x, layout.y),
                        size: (layout.width, layout.height),
                        background: style.background.clone(),
                        border_radius: None,
                        border_color: None,
                        border_width: None,
                        clip_rect: None,
                    });
                }
                self.paint_edge_borders(ctx, layout, border.unwrap(), sf);
            } else {
                ctx.draw_rect(RectCommand {
                    position: (layout.x, layout.y),
                    size: (layout.width, layout.height),
                    background: style.background.clone(),
                    border_radius: border
                        .and_then(|b| b.radius)
                        .map(|r| Length::px(r.to_physical(sf))),
                    border_color: border.map(|b| b.color),
                    border_width: border.map(|b| Length::px(b.top.to_physical(sf))),
                    clip_rect: None,
                });
            }
        }

        if let Some(shadows) = &style.box_shadow {
            for shadow in shadows
                .iter()
                .rev()
                .filter(|s| s.inset) {
                self.paint_shadow_layer(ctx, layout, radius, shadow, sf);
            }
        }
    }

    fn paint_edge_borders(&self, ctx: &mut PaintContext, layout: LayoutBox, b: &Border, sf: f32) {
        let top = b.top.to_physical(sf);
        let right = b.right.to_physical(sf);
        let bottom = b.bottom.to_physical(sf);
        let left = b.left.to_physical(sf);

        let mut edge = |x: f32, y: f32, w: f32, h: f32| {
            ctx.draw_rect(RectCommand {
                position: (x, y),
                size: (w, h),
                background: Some(Background::Color(b.color)),
                border_radius: None,
                border_width: None,
                border_color: None,
                clip_rect: None,
            });
        };

        if top > 0.0 {
            edge(layout.x, layout.y, layout.width, top);
        }
        if bottom > 0.0 {
            edge(layout.x, layout.y + layout.height - bottom, layout.width, bottom);
        }
        if left > 0.0 {
            edge(layout.x, layout.y, left, layout.height);
        }
        if right > 0.0 {
            edge(layout.x + layout.width - right, layout.y, right, layout.height);
        }
    }

    fn paint_shadow_layer(
        &self,
        ctx: &mut PaintContext,
        layout: LayoutBox,
        radius: f32,
        shadow: &BoxShadow,
        sf: f32
    ) {
        let ox = shadow.offset_x.to_physical(sf);
        let oy = shadow.offset_y.to_physical(sf);
        let blur = shadow.blur_radius.to_physical(sf).max(0.0);
        let spread = shadow.spread_radius.to_physical(sf);

        let cx = layout.x + layout.width * 0.5;
        let cy = layout.y + layout.height * 0.5;

        let (shadow_position, shadow_size, shadow_radius) = if shadow.inset {
            let half_w = (layout.width * 0.5 - spread).max(0.0);
            let half_h = (layout.height * 0.5 - spread).max(0.0);
            (
                (cx + ox - half_w, cy + oy - half_h),
                (half_w * 2.0, half_h * 2.0),
                (radius - spread).max(0.0),
            )
        } else {
            let half_w = layout.width * 0.5 + spread;
            let half_h = layout.height * 0.5 + spread;
            (
                (cx + ox - half_w, cy + oy - half_h),
                (half_w * 2.0, half_h * 2.0),
                (radius + spread).max(0.0),
            )
        };

        ctx.draw_box_shadow(BoxShadowCommand {
            shadow_position,
            shadow_size,
            shadow_radius,
            blur,
            color: shadow.color,
            inset: shadow.inset,
            box_position: (layout.x, layout.y),
            box_size: (layout.width, layout.height),
            box_radius: radius,
            clip_rect: None,
        });
    }

    fn paint_outline(&self, ctx: &mut PaintContext) {
        // Skipped while the focus ring is visible - paint_focus draws the
        // same outline field on top, in its own always-last render pass.
        if self.interaction().is_some_and(|i| i.focused && i.focus_visible) {
            return;
        }

        let style = self.computed_style();

        let outline = match &style.outline {
            StyleValue::None => {
                return;
            }
            StyleValue::Value(outline) => outline,
            StyleValue::Default => {
                return;
            }
        };

        let sf = ctx.scale_factor;
        let layout = self.layout_box();
        let offset = outline.offset.to_physical(sf);
        let radius = outline.radius
            .or_else(|| style.border.as_ref().and_then(|b| b.radius))
            .map(|r| Length::px(r.to_physical(sf)));

        ctx.draw_rect(RectCommand {
            position: (layout.x - offset, layout.y - offset),
            size: (layout.width + offset * 2.0, layout.height + offset * 2.0),
            background: None,
            border_radius: radius,
            border_color: Some(outline.color),
            border_width: Some(Length::px(outline.width.to_physical(sf))),
            clip_rect: None,
        });
    }

    fn paint_focus(&self, ctx: &mut PaintContext) {
        let Some(interaction) = self.interaction() else {
            return;
        };

        if !interaction.focused || !interaction.focus_visible {
            return;
        }

        let style = self.computed_style();
        let layout = self.layout_box();

        let outline = match &style.outline {
            StyleValue::None => {
                return;
            }
            StyleValue::Value(outline) => *outline,
            StyleValue::Default =>
                Outline {
                    width: Length::px(2.5),
                    color: Color::BLUE_500,
                    radius: style.border
                        .as_ref()
                        .and_then(|b| b.radius)
                        .map(|r| r.add_px(4.0)),
                    offset: Length::px(4.0),
                },
        };

        let sf = ctx.scale_factor;
        let offset = outline.offset.to_physical(sf);
        let radius = outline.radius
            .or_else(|| style.border.as_ref().and_then(|b| b.radius))
            .map(|r| Length::px(r.to_physical(sf)));

        ctx.draw_rect(RectCommand {
            position: (layout.x - offset, layout.y - offset),
            size: (layout.width + offset * 2.0, layout.height + offset * 2.0),
            background: None,
            border_radius: radius,
            border_width: Some(Length::px(outline.width.to_physical(sf))),
            border_color: Some(outline.color),
            clip_rect: None,
        });
    }

    /// Painted after every other widget's own content and after all
    /// deferred text has been flushed - use this instead of
    /// `paint_overlay` for a popup that must render above everything
    /// else, including other widgets' text (which is otherwise batched
    /// and flushed in its own pass after every widget's rects).
    fn paint_top(&self, _ctx: &mut PaintContext) {}

    fn hit_test(&self, point: (f32, f32)) -> bool {
        let b = self.layout_box();

        if point.0 < b.x || point.0 > b.x + b.width || point.1 < b.y || point.1 > b.y + b.height {
            return false;
        }

        let Some(border) = &self.style().border else {
            return true;
        };

        let radius: f32 = border.radius.unwrap_or(Length::Px(0.0)).value();

        if radius <= 0.0 {
            return true;
        }

        let r = radius.min(b.width * 0.5).min(b.height * 0.5);

        let local_x = point.0 - b.x;
        let local_y = point.1 - b.y;

        if local_x >= r && local_x <= b.width - r {
            return true;
        }

        if local_y >= r && local_y <= b.height - r {
            return true;
        }

        let cx = if local_x < r { r } else { b.width - r };

        let cy = if local_y < r { r } else { b.height - r };

        let dx = local_x - cx;
        let dy = local_y - cy;

        dx * dx + dy * dy <= r * r
    }

    /// When true at `point`, hit-testing stops at this widget instead of
    /// descending into its children.
    fn blocks_children_hit_test(&self, _point: (f32, f32)) -> bool {
        false
    }

    fn interaction(&self) -> Option<&Interaction> {
        None
    }

    fn interaction_mut(&mut self) -> Option<&mut Interaction> {
        None
    }

    fn transfer_interaction_state(&mut self, old: &dyn Widget) {
        if let (Some(new), Some(old)) = (self.interaction_mut(), old.interaction()) {
            new.transfer_from(old);
        }
    }

    fn event(&mut self, event: &InputEvent, ctx: &mut EventCtx) -> EventStatus {
        let status = match self.interaction_mut() {
            Some(interaction) if interaction.is_active() => interaction.handle(event, ctx),
            _ => EventStatus::Ignored,
        };

        if matches!(status, EventStatus::Handled) {
            self.set_dirty(true);
        }

        status
    }

    fn content_eq(&self, _other: &dyn Widget) -> bool {
        false
    }

    fn cascade_style(&mut self, parent: &Style, anim: &mut AnimationManager) {
        if let Some(children) = self.children_mut() {
            for child in children.iter_mut() {
                child.cascade_style(parent, anim);
            }
        }
    }

    fn after_interaction_transfer(&mut self) {}

    fn transfer_measured_state(&mut self, _old: &dyn Widget) {}

    fn blink_interval(&self) -> Option<web_time::Duration> {
        None
    }

    /// Whether this widget needs a continuous per-frame animation callback
    /// (`InputEvent::AnimationTick`) right now, independent of focus.
    fn wants_animation_frame(&self) -> bool {
        false
    }

    /// HTML-style selectable text content for mouse selection / Ctrl+C.
    /// `None` opts the widget out entirely (e.g. Button, TextBox).
    fn selectable_text(&self) -> Option<&str> {
        None
    }

    fn text_selection(&self) -> Option<(usize, usize)> {
        None
    }

    fn set_text_selection(&mut self, _range: Option<(usize, usize)>) {}

    // Called by the global Escape handler; clears the selection and also
    // stops any drag-in-progress so a still-held mouse button can't
    // immediately re-create the selection on the next move.
    fn cancel_text_selection(&mut self) {
        self.set_text_selection(None);
    }

    /// Nearest character index to an absolute screen point, used by
    /// cross-widget drag selection to know where a widget's own
    /// selection should start or end.
    fn text_index_at(&self, _point: (f32, f32)) -> usize {
        0
    }

    fn select_all_text(&mut self) {}

    /// Stable per-instance animation key namespace. Assign once in the
    /// constructor via `WidgetId::new_unique()` and preserve it across
    /// reconciliation so in-flight transitions aren't reset.
    fn anim_id(&self) -> WidgetId {
        WidgetId::default()
    }

    /// `Some(...)` marks this widget as backed by a real DOM `<input>` on
    /// web targets. `None` (the default) means it has no native counterpart.
    fn native_text_input(&self) -> Option<NativeTextInputSnapshot> {
        None
    }

    /// Applies a value typed into the native DOM `<input>` back onto this
    /// widget's own state.
    fn set_native_text_value(&mut self, _value: &str, _ctx: &mut EventCtx) {}

    /// Syncs this widget's native DOM input (web only). Widgets exposing
    /// `native_text_input()` should override this to keep the hidden
    /// `<input>`'s value/placeholder/read-only state in sync, so mobile
    /// keyboards get correct context.
    #[cfg(target_arch = "wasm32")]
    fn sync_native_input(&self, _input: &web_sys::HtmlInputElement) {}
}

/// Shrinks or grows `rect` around its own center by `scale`, so an
/// animated scale transform can be painted without touching layout.
pub fn scaled_layout_box(rect: LayoutBox, scale: f32) -> LayoutBox {
    let cx = rect.x + rect.width * 0.5;
    let cy = rect.y + rect.height * 0.5;
    let w = rect.width * scale;
    let h = rect.height * scale;
    LayoutBox {
        x: cx - w * 0.5,
        y: cy - h * 0.5,
        width: w,
        height: h,
    }
}