fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
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
//! Unstable retained-widget bridge for policy-heavy UI (e.g. docking migration).
//!
//! This module is intentionally feature-gated (`unstable-retained-bridge`) and is **not** part of
//! the stable `fret-ui` runtime contract surface (ADR 0066).

use crate::{UiHost, UiTree};
use fret_core::NodeId;
use std::any::Any;
use std::sync::Arc;

pub use crate::resizable_panel_group::{ResizablePanelGroupLayout, ResizablePanelGroupStyle};
pub use crate::resize_handle::ResizeHandle;
pub use crate::text_input::{BoundTextInput, TextInput};
pub use crate::widget::{
    CommandAvailability, CommandAvailabilityCx, CommandCx, EventCx, Invalidation, LayoutCx,
    MeasureCx, PaintCx, PrepaintCx, SemanticsCx, Widget,
};

type RetainedSubtreeBuildFn<H> = dyn Fn(&mut UiTree<H>) -> NodeId;

/// Extension trait that exposes a feature-gated node creation API for retained widgets.
pub trait UiTreeRetainedExt<H: UiHost> {
    fn create_node_retained(&mut self, widget: impl Widget<H> + 'static) -> NodeId;
}

impl<H: UiHost> UiTreeRetainedExt<H> for UiTree<H> {
    fn create_node_retained(&mut self, widget: impl Widget<H> + 'static) -> NodeId {
        self.create_node(widget)
    }
}

/// Unstable declarative bridge for hosting retained subtrees inside the element runtime.
///
/// This is intended as a migration aid for policy-heavy ecosystems (docking, node graphs, charts)
/// while the primary authoring direction remains declarative (ADR 0028 / ADR 0039).
#[derive(Clone)]
pub struct RetainedSubtreeFactory {
    inner: Arc<dyn Any>,
}

impl std::fmt::Debug for RetainedSubtreeFactory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RetainedSubtreeFactory")
            .finish_non_exhaustive()
    }
}

impl RetainedSubtreeFactory {
    pub fn new<H: UiHost + 'static>(f: impl Fn(&mut UiTree<H>) -> NodeId + 'static) -> Self {
        let f: Arc<RetainedSubtreeBuildFn<H>> = Arc::new(f);
        Self { inner: Arc::new(f) }
    }

    pub(crate) fn build<H: UiHost + 'static>(&self, ui: &mut UiTree<H>) -> NodeId {
        let Some(f) = self.inner.downcast_ref::<Arc<RetainedSubtreeBuildFn<H>>>() else {
            if crate::strict_runtime::strict_runtime_enabled() {
                panic!("retained subtree factory type mismatch (host type changed?)");
            }

            tracing::error!(
                "retained subtree factory type mismatch (host type changed?); returning fallback empty widget node"
            );

            struct FallbackWidget;
            impl<H2: UiHost> Widget<H2> for FallbackWidget {}

            return ui.create_node(FallbackWidget);
        };

        (f)(ui)
    }
}

#[derive(Debug, Clone)]
pub struct RetainedSubtreeProps {
    pub layout: crate::element::LayoutStyle,
    pub factory: RetainedSubtreeFactory,
}

impl RetainedSubtreeProps {
    pub fn new<H: UiHost + 'static>(f: impl Fn(&mut UiTree<H>) -> NodeId + 'static) -> Self {
        let mut layout = crate::element::LayoutStyle::default();
        layout.size.width = crate::element::Length::Fill;
        layout.size.height = crate::element::Length::Fill;
        Self {
            layout,
            factory: RetainedSubtreeFactory::new(f),
        }
    }

    pub fn with_layout(mut self, layout: crate::element::LayoutStyle) -> Self {
        self.layout = layout;
        self
    }
}

/// Unstable mechanism helpers for splitter / panel-group sizing.
pub mod resizable_panel_group {
    use fret_core::{Axis, Point, Px, Rect};

    use crate::resizable_panel_group::{
        ResizablePanelGroupLayout, apply_handle_delta, compute_resizable_panel_group_layout,
        fractions_from_sizes,
    };

    pub fn compute_layout(
        axis: Axis,
        bounds: Rect,
        children_len: usize,
        fractions: &[f32],
        gap: Px,
        hit_thickness: Px,
        min_px: &[Px],
    ) -> ResizablePanelGroupLayout {
        compute_resizable_panel_group_layout(
            axis,
            bounds,
            children_len,
            fractions.to_vec(),
            gap,
            hit_thickness,
            min_px,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn drag_update_fractions(
        axis: Axis,
        bounds: Rect,
        children_len: usize,
        fractions: &[f32],
        handle_ix: usize,
        gap: Px,
        hit_thickness: Px,
        min_px: &[Px],
        grab_offset: f32,
        position: Point,
    ) -> Option<Vec<f32>> {
        if children_len < 2 || handle_ix + 1 >= children_len {
            return None;
        }

        let layout = compute_layout(
            axis,
            bounds,
            children_len,
            fractions,
            gap,
            hit_thickness,
            min_px,
        );
        let old_center = *layout.handle_centers.get(handle_ix)?;

        let axis_pos = match axis {
            Axis::Horizontal => position.x.0,
            Axis::Vertical => position.y.0,
        };

        let desired_center = axis_pos - grab_offset;
        let desired_delta = desired_center - old_center;
        if !desired_delta.is_finite() {
            return None;
        }

        let mut sizes = layout.sizes.clone();
        let actual = apply_handle_delta(handle_ix, desired_delta, &mut sizes, &layout.mins);
        if actual.abs() <= 1.0e-6 {
            return None;
        }
        Some(fractions_from_sizes(&sizes, layout.avail))
    }

    /// Updates fractions by resizing only the two panels adjacent to the dragged handle.
    ///
    /// This matches the "adjacent-only" semantics expected by docking N-ary split sizing:
    /// moving handle `i` adjusts only panels `i` and `i + 1` (subject to min sizes).
    #[allow(clippy::too_many_arguments)]
    pub fn drag_update_adjacent_fractions(
        axis: Axis,
        bounds: Rect,
        children_len: usize,
        fractions: &[f32],
        handle_ix: usize,
        gap: Px,
        hit_thickness: Px,
        min_px: &[Px],
        grab_offset: f32,
        position: Point,
    ) -> Option<Vec<f32>> {
        if children_len < 2 || handle_ix + 1 >= children_len {
            return None;
        }

        let layout = compute_layout(
            axis,
            bounds,
            children_len,
            fractions,
            gap,
            hit_thickness,
            min_px,
        );
        let old_center = *layout.handle_centers.get(handle_ix)?;

        let axis_pos = match axis {
            Axis::Horizontal => position.x.0,
            Axis::Vertical => position.y.0,
        };

        let desired_center = axis_pos - grab_offset;
        let desired_delta = desired_center - old_center;
        if !desired_delta.is_finite() {
            return None;
        }

        let i = handle_ix;
        let j = handle_ix + 1;
        if layout.sizes.len() != children_len || layout.mins.len() != children_len {
            return None;
        }

        let pair_sum = layout.sizes[i] + layout.sizes[j];
        if !pair_sum.is_finite() || pair_sum <= 0.0 {
            return None;
        }

        let min_i = layout.mins[i].max(0.0);
        let min_j = layout.mins[j].max(0.0);
        let max_i = (pair_sum - min_j).clamp(0.0, pair_sum);
        let min_i = min_i.clamp(0.0, max_i);

        let mut next_i = (layout.sizes[i] + desired_delta).clamp(min_i, max_i);
        if !next_i.is_finite() {
            return None;
        }
        let mut next_j = (pair_sum - next_i).max(0.0);
        if next_j < min_j {
            next_j = min_j.clamp(0.0, pair_sum);
            next_i = (pair_sum - next_j).clamp(min_i, max_i);
        }

        let actual = next_i - layout.sizes[i];
        if actual.abs() <= 1.0e-6 {
            return None;
        }

        let mut sizes = layout.sizes.clone();
        sizes[i] = next_i;
        sizes[j] = next_j;
        Some(fractions_from_sizes(&sizes, layout.avail))
    }
}

/// Unstable retained helpers for viewport surfaces (Tier A embedding).
pub mod viewport_surface {
    use fret_core::{
        AppWindowId, Event, MouseButton, PointerEvent, RenderTargetId, ViewportInputEvent,
        ViewportInputKind, ViewportMapping, WindowMetricsService,
    };
    use fret_runtime::Effect;

    use crate::widget::EventCx;
    use crate::{UiHost, widget::Invalidation};

    #[derive(Debug, Clone, Copy, PartialEq)]
    pub struct ViewportInputCapture {
        pub window: AppWindowId,
        pub target: RenderTargetId,
        pub mapping: ViewportMapping,
        pub button: MouseButton,
        pub last_cursor_px: fret_core::Point,
    }

    /// Forwards pointer + wheel events into a viewport surface using `ViewportMapping`.
    ///
    /// This helper mirrors the "capture on pointer down, then clamp moves/up while captured"
    /// pattern used by viewport panels (game views, editor canvases).
    pub fn handle_viewport_surface_input<H: UiHost>(
        cx: &mut EventCx<'_, H>,
        event: &Event,
        target: RenderTargetId,
        mapping: ViewportMapping,
        capture: &mut Option<ViewportInputCapture>,
        focus_on_down: bool,
    ) -> bool {
        let Some(window) = cx.window else {
            return false;
        };
        let pixels_per_point = cx
            .app
            .global::<WindowMetricsService>()
            .and_then(|svc| svc.scale_factor(window))
            .unwrap_or(1.0);

        match event {
            Event::Pointer(PointerEvent::Down {
                position,
                button,
                modifiers,
                click_count,
                pointer_id,
                pointer_type,
                ..
            }) => {
                let kind = ViewportInputKind::PointerDown {
                    button: *button,
                    modifiers: *modifiers,
                    click_count: *click_count,
                };
                let Some(evt) = ViewportInputEvent::from_mapping_window_point(
                    window,
                    target,
                    &mapping,
                    pixels_per_point,
                    *pointer_id,
                    *pointer_type,
                    *position,
                    kind,
                ) else {
                    return false;
                };

                cx.app.push_effect(Effect::ViewportInput(evt));
                if focus_on_down {
                    cx.request_focus(cx.node);
                }
                *capture = Some(ViewportInputCapture {
                    window,
                    target,
                    mapping,
                    button: *button,
                    last_cursor_px: *position,
                });
                cx.capture_pointer(cx.node);
                cx.invalidate_self(Invalidation::Paint);
                cx.request_redraw();
                cx.stop_propagation();
                true
            }
            Event::Pointer(PointerEvent::Move {
                position,
                buttons,
                modifiers,
                pointer_id,
                pointer_type,
                ..
            }) => {
                if let Some(c) = capture
                    && c.window == window
                    && cx.captured == Some(cx.node)
                {
                    c.last_cursor_px = *position;
                    let pixels_per_point = cx
                        .app
                        .global::<WindowMetricsService>()
                        .and_then(|svc| svc.scale_factor(c.window))
                        .unwrap_or(1.0);
                    let evt = ViewportInputEvent::from_mapping_window_point_clamped(
                        c.window,
                        c.target,
                        &c.mapping,
                        pixels_per_point,
                        *pointer_id,
                        *pointer_type,
                        *position,
                        ViewportInputKind::PointerMove {
                            buttons: *buttons,
                            modifiers: *modifiers,
                        },
                    );
                    cx.app.push_effect(Effect::ViewportInput(evt));
                    cx.stop_propagation();
                    return true;
                }

                let Some(evt) = ViewportInputEvent::from_mapping_window_point(
                    window,
                    target,
                    &mapping,
                    pixels_per_point,
                    *pointer_id,
                    *pointer_type,
                    *position,
                    ViewportInputKind::PointerMove {
                        buttons: *buttons,
                        modifiers: *modifiers,
                    },
                ) else {
                    return false;
                };
                if let Some(c) = capture {
                    c.last_cursor_px = *position;
                }
                cx.app.push_effect(Effect::ViewportInput(evt));
                cx.stop_propagation();
                true
            }
            Event::Pointer(PointerEvent::Up {
                position,
                button,
                modifiers,
                is_click,
                click_count,
                pointer_id,
                pointer_type,
                ..
            }) => {
                let Some(c) = *capture else {
                    return false;
                };
                if c.window != window || c.button != *button {
                    return false;
                }

                let pixels_per_point = cx
                    .app
                    .global::<WindowMetricsService>()
                    .and_then(|svc| svc.scale_factor(c.window))
                    .unwrap_or(1.0);
                let evt = ViewportInputEvent::from_mapping_window_point_clamped(
                    c.window,
                    c.target,
                    &c.mapping,
                    pixels_per_point,
                    *pointer_id,
                    *pointer_type,
                    *position,
                    ViewportInputKind::PointerUp {
                        button: *button,
                        modifiers: *modifiers,
                        is_click: *is_click,
                        click_count: *click_count,
                    },
                );
                cx.app.push_effect(Effect::ViewportInput(evt));

                *capture = None;
                if cx.captured == Some(cx.node) {
                    cx.release_pointer_capture();
                }
                cx.invalidate_self(Invalidation::Paint);
                cx.request_redraw();
                cx.stop_propagation();
                true
            }
            Event::Pointer(PointerEvent::Wheel {
                position,
                delta,
                modifiers,
                pointer_id,
                pointer_type,
                ..
            }) => {
                let Some(evt) = ViewportInputEvent::from_mapping_window_point(
                    window,
                    target,
                    &mapping,
                    pixels_per_point,
                    *pointer_id,
                    *pointer_type,
                    *position,
                    ViewportInputKind::Wheel {
                        delta: *delta,
                        modifiers: *modifiers,
                    },
                ) else {
                    return false;
                };
                if let Some(c) = capture {
                    c.last_cursor_px = *position;
                }
                cx.app.push_effect(Effect::ViewportInput(evt));
                cx.stop_propagation();
                true
            }
            Event::PointerCancel(e) => {
                let position = e
                    .position
                    .or_else(|| capture.as_ref().map(|c| c.last_cursor_px))
                    .unwrap_or_else(|| mapping.map().draw_rect.origin);
                let evt = ViewportInputEvent::from_mapping_window_point_clamped(
                    window,
                    target,
                    &mapping,
                    pixels_per_point,
                    e.pointer_id,
                    e.pointer_type,
                    position,
                    ViewportInputKind::PointerCancel {
                        buttons: e.buttons,
                        modifiers: e.modifiers,
                        reason: e.reason,
                    },
                );
                cx.app.push_effect(Effect::ViewportInput(evt));

                *capture = None;
                if cx.captured == Some(cx.node) {
                    cx.release_pointer_capture();
                }
                cx.invalidate_self(Invalidation::Paint);
                cx.request_redraw();
                cx.stop_propagation();
                true
            }
            _ => false,
        }
    }
}