gioser

tawasuyu/llimphi

Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.

Rust 660Markdown 302TOML 157RON 312382 Definiciones

⎇ e2102d6057046fade7d44f45092cc01cfd05b5e7 llimphi-ui/src/eventloop/helpers.rs Rust · 305 líneas · 11.3 KB Historia Quién tocó qué crudo

refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel ccab39f14 · Sergio ·

1// helpers.rs — Funciones puras auxiliares del bucle Elm.
2// Todas sin efecto observable sobre el runtime; se testean fácil de forma aislada.
3
4use super::super::*;
5
6/// Mapea el [`Cursor`](llimphi_compositor::Cursor) llimphi-native (resuelto por
7/// el hit-test de hover) a `winit::window::CursorIcon`. `None` → flecha default.
8/// Mantiene al compositor winit-free: la traducción vive sólo en el runtime.
9pub(super) fn to_winit_cursor(c: Option<llimphi_compositor::Cursor>) -> llimphi_hal::winit::window::CursorIcon {
10    use llimphi_compositor::Cursor as C;
11    use llimphi_hal::winit::window::CursorIcon as I;
12    match c {
13        None | Some(C::Default) => I::Default,
14        Some(C::Pointer) => I::Pointer,
15        Some(C::Text) => I::Text,
16        Some(C::Crosshair) => I::Crosshair,
17        Some(C::Move) => I::Move,
18        Some(C::Grab) => I::Grab,
19        Some(C::Grabbing) => I::Grabbing,
20        Some(C::NotAllowed) => I::NotAllowed,
21        Some(C::Wait) => I::Wait,
22        Some(C::Progress) => I::Progress,
23        Some(C::Help) => I::Help,
24        Some(C::ColResize) => I::ColResize,
25        Some(C::RowResize) => I::RowResize,
26        Some(C::EwResize) => I::EwResize,
27        Some(C::NsResize) => I::NsResize,
28        Some(C::NeswResize) => I::NeswResize,
29        Some(C::NwseResize) => I::NwseResize,
30        Some(C::ZoomIn) => I::ZoomIn,
31        Some(C::ZoomOut) => I::ZoomOut,
32    }
33}
34
35/// Resuelve el handler de **escala** (pinch-to-zoom) bajo el punto `(x, y)`
36/// contra el cache del último frame (overlay con prioridad, igual que clicks).
37/// Devuelve `(handler, focal_x, focal_y)` con el punto focal ya en coordenadas
38/// **locales** al rect del nodo. `None` si no hay nodo `on_scale` bajo el
39/// cursor. Compartido por el camino Ctrl+rueda y el de `PinchGesture`.
40pub(super) fn scale_hit_from_cache<Msg: Clone>(
41    cache: &RenderCache<Msg>,
42    x: f32,
43    y: f32,
44) -> Option<(ScaleFn<Msg>, f32, f32)> {
45    let (m, c) = match cache.overlay.as_ref() {
46        Some(ov) => (&ov.mounted, &ov.computed),
47        None => (&cache.mounted, &cache.computed),
48    };
49    hit_test_scale(m, c, x, y).and_then(|i| {
50        let node = &m.nodes[i];
51        node.on_scale.clone().map(|h| {
52            let (fx, fy) = c
53                .get(node.id)
54                .map(|r| (x - r.x, y - r.y))
55                .unwrap_or((0.0, 0.0));
56            (h, fx, fy)
57        })
58    })
59}
60
61/// Resuelve el handler de **rotación** (trackpad) bajo `(x, y)` contra el
62/// cache del último frame (overlay con prioridad). Espejo de
63/// [`scale_hit_from_cache`]. Devuelve `(handler, focal_x, focal_y)` con el
64/// punto focal local al rect del nodo. `None` si no hay nodo `on_rotate`.
65pub(super) fn rotate_hit_from_cache<Msg: Clone>(
66    cache: &RenderCache<Msg>,
67    x: f32,
68    y: f32,
69) -> Option<(RotateFn<Msg>, f32, f32)> {
70    let (m, c) = match cache.overlay.as_ref() {
71        Some(ov) => (&ov.mounted, &ov.computed),
72        None => (&cache.mounted, &cache.computed),
73    };
74    hit_test_rotate(m, c, x, y).and_then(|i| {
75        let node = &m.nodes[i];
76        node.on_rotate.clone().map(|h| {
77            let (fx, fy) = c
78                .get(node.id)
79                .map(|r| (x - r.x, y - r.y))
80                .unwrap_or((0.0, 0.0));
81            (h, fx, fy)
82        })
83    })
84}
85
86/// Resuelve el handler de **doble-tap** bajo `(x, y)` contra el cache del
87/// último frame (overlay con prioridad). Elige la variante `_at` (con focal
88/// local) si está, o el `Msg` directo. `None` si no hay nodo con doble-tap.
89pub(super) fn double_tap_hit_from_cache<Msg: Clone>(
90    cache: &RenderCache<Msg>,
91    x: f32,
92    y: f32,
93) -> Option<GestureResolved<Msg>> {
94    let (m, c) = match cache.overlay.as_ref() {
95        Some(ov) => (&ov.mounted, &ov.computed),
96        None => (&cache.mounted, &cache.computed),
97    };
98    hit_test_double_tap(m, c, x, y).and_then(|i| {
99        let node = &m.nodes[i];
100        let (rx, ry, rw, rh) = c.get(node.id).map(|r| (r.x, r.y, r.w, r.h)).unwrap_or_default();
101        if let Some(h) = node.on_double_tap_at.clone() {
102            Some(GestureResolved::At(h, x - rx, y - ry, rw, rh))
103        } else {
104            node.on_double_tap.clone().map(GestureResolved::Direct)
105        }
106    })
107}
108
109/// Como [`double_tap_hit_from_cache`] pero para **long-press**.
110pub(super) fn long_press_hit_from_cache<Msg: Clone>(
111    cache: &RenderCache<Msg>,
112    x: f32,
113    y: f32,
114) -> Option<GestureResolved<Msg>> {
115    let (m, c) = match cache.overlay.as_ref() {
116        Some(ov) => (&ov.mounted, &ov.computed),
117        None => (&cache.mounted, &cache.computed),
118    };
119    hit_test_long_press(m, c, x, y).and_then(|i| {
120        let node = &m.nodes[i];
121        let (rx, ry, rw, rh) = c.get(node.id).map(|r| (r.x, r.y, r.w, r.h)).unwrap_or_default();
122        if let Some(h) = node.on_long_press_at.clone() {
123            Some(GestureResolved::At(h, x - rx, y - ry, rw, rh))
124        } else {
125            node.on_long_press.clone().map(GestureResolved::Direct)
126        }
127    })
128}
129
130/// Resuelve el **ripple** bajo `(x, y)` contra el cache del último frame
131/// (overlay con prioridad). Devuelve `(Ripple, lx, ly)`: la config de la onda
132/// + el punto del tap relativo al rect del nodo. `None` si no hay nodo ripple.
133pub(super) fn ripple_hit_from_cache<Msg: Clone>(
134    cache: &RenderCache<Msg>,
135    x: f32,
136    y: f32,
137) -> Option<(llimphi_compositor::Ripple, f32, f32)> {
138    let (m, c) = match cache.overlay.as_ref() {
139        Some(ov) => (&ov.mounted, &ov.computed),
140        None => (&cache.mounted, &cache.computed),
141    };
142    hit_test_ripple(m, c, x, y).and_then(|i| {
143        let node = &m.nodes[i];
144        node.ripple.map(|rp| {
145            let (rx, ry) = c.get(node.id).map(|r| (r.x, r.y)).unwrap_or_default();
146            (rp, x - rx, y - ry)
147        })
148    })
149}
150
151// ── Selección de texto fuera del editor (ver `View::selectable`) ──
152
153/// Rect absoluto de un nodo: `(x, y, w, h)`.
154pub(super) type AbsRect = (f32, f32, f32, f32);
155
156/// `true` si el `TextSpec` es de texto **uniforme** (sin `runs`/`spans`): los
157/// únicos que la selección fuera-del-editor soporta. Los multicolor/RichText
158/// son del editor y se ignoran.
159pub(super) fn spec_is_uniform(spec: &llimphi_compositor::TextSpec) -> bool {
160    spec.runs.is_none() && spec.spans.is_none()
161}
162
163/// Bajo `(x, y)`, el nodo de texto seleccionable más al frente: su key, su
164/// `TextSpec` clonado y su rect absoluto. `None` si no hay texto seleccionable
165/// uniforme ahí.
166pub(super) fn selectable_hit_from_cache<Msg: Clone>(
167    cache: &RenderCache<Msg>,
168    x: f32,
169    y: f32,
170) -> Option<(u64, llimphi_compositor::TextSpec, AbsRect)> {
171    let (m, c) = match cache.overlay.as_ref() {
172        Some(ov) => (&ov.mounted, &ov.computed),
173        None => (&cache.mounted, &cache.computed),
174    };
175    let i = hit_test_selectable(m, c, x, y)?;
176    let node = &m.nodes[i];
177    let key = node.text_select_key?;
178    let spec = node.text.as_ref()?;
179    if !spec_is_uniform(spec) {
180        return None;
181    }
182    let r = c.get(node.id)?;
183    Some((key, spec.clone(), (r.x, r.y, r.w, r.h)))
184}
185
186/// Busca el nodo seleccionable por su `key` estable (para extender el drag o
187/// pintar el resaltado en frames posteriores, cuando el `NodeId` ya cambió).
188/// Recorre el overlay y el árbol principal. `None` si la key ya no está.
189pub(super) fn selectable_by_key<Msg>(
190    cache: &RenderCache<Msg>,
191    key: u64,
192) -> Option<(llimphi_compositor::TextSpec, AbsRect)> {
193    let trees = [
194        cache.overlay.as_ref().map(|ov| (&ov.mounted, &ov.computed)),
195        Some((&cache.mounted, &cache.computed)),
196    ];
197    trees
198        .into_iter()
199        .flatten()
200        .find_map(|(m, c)| selectable_node_in(m, c, key))
201}
202
203/// Busca en un árbol montado concreto el nodo de texto seleccionable con esa
204/// `key` y devuelve su `TextSpec` clonado + rect. Lo usa tanto la búsqueda por
205/// cache como el pintado del resaltado en el redraw (que tiene el `Mounted`
206/// del frame a mano, no un `RenderCache`).
207pub(super) fn selectable_node_in<Msg>(
208    m: &Mounted<Msg>,
209    c: &ComputedLayout,
210    key: u64,
211) -> Option<(llimphi_compositor::TextSpec, AbsRect)> {
212    for node in &m.nodes {
213        if node.text_select_key == Some(key) {
214            let spec = node.text.as_ref()?;
215            if !spec_is_uniform(spec) {
216                return None;
217            }
218            let r = c.get(node.id)?;
219            return Some((spec.clone(), (r.x, r.y, r.w, r.h)));
220        }
221    }
222    None
223}
224
225/// Reconstruye el `parley::Layout` de un nodo de texto, idéntico al que pinta
226/// el render (misma ruta cacheada `Typesetter::layout`), para hit-testear y
227/// medir la selección. El ancho de wrap es el del rect del nodo.
228pub(super) fn build_selectable_layout(
229    ts: &mut llimphi_text::Typesetter,
230    spec: &llimphi_compositor::TextSpec,
231    width: f32,
232) -> llimphi_text::parley::Layout<()> {
233    ts.layout(
234        &spec.content,
235        spec.size_px,
236        Some(width),
237        spec.alignment,
238        spec.line_height,
239        spec.italic,
240        spec.font_family.as_deref(),
241        spec.weight,
242        spec.underline,
243        spec.strikethrough,
244        spec.letter_spacing,
245        spec.word_spacing,
246    )
247}
248
249/// `true` si la tecla lógica es el carácter `c` (case-insensitive). Para
250/// atajos como Ctrl+C sin acoplarse a mayúsculas/minúsculas ni layout.
251pub(super) fn key_is_char(key: &Key, c: char) -> bool {
252    matches!(
253        key,
254        Key::Character(s) if s.chars().next().map(|k| k.eq_ignore_ascii_case(&c)).unwrap_or(false)
255    )
256}
257
258/// Copia texto al portapapeles del sistema (best-effort). Con la feature
259/// `clipboard` usa `arboard`; sin backend (headless) o sin la feature es no-op
260/// silencioso — nunca panica.
261#[cfg(feature = "clipboard")]
262pub(super) fn copy_to_clipboard(text: &str) {
263    if let Ok(mut cb) = arboard::Clipboard::new() {
264        let _ = cb.set_text(text.to_string());
265    }
266}
267
268#[cfg(not(feature = "clipboard"))]
269pub(super) fn copy_to_clipboard(_text: &str) {}
270
271/// Resuelve los [`View::layout_builder`] del árbol de la app en dos pasadas
272/// (ver [`llimphi_compositor::expand_layout_builders`]). **Coste cero** cuando
273/// ningún nodo usa el builder: devuelve el `view()` sin tocar tras un walk
274/// barato. Cuando hay builders: monta el árbol (builders como hojas), computa
275/// para conocer sus slots, y reconstruye un `view()` fresco expandiendo cada
276/// builder con sus constraints reales. `viewport` en px físicos; `ts` para medir
277/// texto igual que el compute principal. Lo llaman el redraw (vía cache) y el
278/// fallback de press.
279pub(super) fn resolve_layout_builders<A: App>(
280    model: &A::Model,
281    viewport: (f32, f32),
282    ts: &mut llimphi_text::Typesetter,
283) -> View<A::Msg> {
284    let view = A::view(model);
285    if !has_layout_builder(&view) {
286        return view;
287    }
288    // Pasada 1: montar (builders = hojas con su Style) y computar el layout.
289    let mut l1 = LayoutTree::new();
290    let m1: Mounted<A::Msg> = mount(&mut l1, view);
291    let c1 = {
292        let tmap = &m1.text_measures;
293        l1.compute_with_measure(m1.root, viewport, |nid, known, avail| {
294            match tmap.get(&nid) {
295                Some(tm) => measure_text_node(ts, tm, known, avail),
296                None => llimphi_layout::taffy::Size::ZERO,
297            }
298        })
299        .expect("layout layout_builder pasada 1")
300    };
301    let cons = collect_builder_constraints(&m1, &c1);
302    // Pasada 2: árbol fresco (mismo Model → misma estructura, mismo pre-orden de
303    // builders) + expand con las constraints resueltas.
304    expand_layout_builders(A::view(model), &cons)
305}