Skip to main content

serge_native/
lib.rs

1//! `serge-native` — the native runtime shared by every native platform and
2//! by headless tests: it mounts `Element`s into a retained tree, keeps it in
3//! sync with signals, lays it out (`serge-native-layout`), shapes text
4//! (`serge-native-text`), collects [`ScenePrimitive`]s for the GPU/CPU
5//! renderers, routes input, and runs UI tasks ([`LocalExecutor`]).
6//!
7//! [`Headless`] drives the same runtime without a window (tests, CI).
8
9mod accessibility;
10mod exec;
11mod scene;
12mod tree;
13pub use accesskit;
14
15use std::cell::RefCell;
16use std::rc::Rc;
17use std::time::{Duration, Instant};
18
19use hyve::Scope;
20use hyve::state::untrack;
21use serge_core::{
22    Attr, AttrValue, Cursor, Element, Handler, Kind, Point, Rect, ScenePrimitive, View,
23};
24use serge_native_text::TextSystem;
25use serge_style::Theme;
26
27pub use exec::{LocalExecutor, yield_now};
28pub use serge_native_text::Font;
29
30use tree::{NKind, Shared, Tree};
31
32/// A key that is not text.
33#[derive(Clone, Copy, PartialEq, Eq, Debug)]
34pub enum Key {
35    /// Deletes the character before the caret.
36    Backspace,
37    /// Submits an input or activates a focused control.
38    Enter,
39    /// Inserts a space or activates a focused button or checkbox.
40    Space,
41    /// Moves focus to the next enabled control.
42    Tab,
43    /// Moves focus to the previous enabled control.
44    BackTab,
45    /// Increases or decreases a focused slider by one step.
46    Step(bool),
47    /// Drops focus.
48    Escape,
49}
50
51/// The renderer a window uses (`docs/03-adapters-and-pipeline.md` §1.2).
52#[derive(Clone, Copy, PartialEq, Eq, Debug)]
53pub enum Backend {
54    /// GPU (`wgpu`).
55    Gpu,
56    /// CPU (`vello_cpu`).
57    Cpu,
58}
59
60/// Why no renderer could be chosen.
61#[derive(Clone, PartialEq, Eq, Debug)]
62pub enum BackendError {
63    /// `HYPERISH_RENDER_BACKEND` names neither `cpu` nor `gpu`.
64    Unknown(String),
65    /// `gpu` was requested explicitly and the GPU path failed.
66    GpuUnavailable(String),
67}
68
69impl std::fmt::Display for BackendError {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            BackendError::Unknown(v) => write!(
73                f,
74                "HYPERISH_RENDER_BACKEND={v:?} is not a backend; use `cpu` or `gpu`"
75            ),
76            BackendError::GpuUnavailable(why) => write!(
77                f,
78                "HYPERISH_RENDER_BACKEND=gpu, but the GPU renderer is unavailable: {why}"
79            ),
80        }
81    }
82}
83
84impl std::error::Error for BackendError {}
85
86/// The backend `requested` (`HYPERISH_RENDER_BACKEND`) names: `None` when
87/// unset or empty, an error when it names neither `cpu` nor `gpu`.
88pub fn requested_backend(requested: Option<&str>) -> Result<Option<Backend>, BackendError> {
89    match requested.map(str::trim).filter(|v| !v.is_empty()) {
90        None => Ok(None),
91        Some(v) if v.eq_ignore_ascii_case("cpu") => Ok(Some(Backend::Cpu)),
92        Some(v) if v.eq_ignore_ascii_case("gpu") => Ok(Some(Backend::Gpu)),
93        Some(v) => Err(BackendError::Unknown(v.to_owned())),
94    }
95}
96
97/// The fallback policy as a pure function: an explicit `requested` value
98/// (`HYPERISH_RENDER_BACKEND`) always wins and an explicit `gpu` that fails
99/// is an error; without one, headless runs use the CPU and windows try the
100/// GPU, falling back to the CPU when `gpu()` fails.
101pub fn choose_backend(
102    requested: Option<&str>,
103    headless: bool,
104    gpu: impl FnOnce() -> Result<(), String>,
105) -> Result<Backend, BackendError> {
106    match requested_backend(requested)? {
107        Some(Backend::Cpu) => Ok(Backend::Cpu),
108        Some(Backend::Gpu) => gpu()
109            .map(|()| Backend::Gpu)
110            .map_err(BackendError::GpuUnavailable),
111        None if headless => Ok(Backend::Cpu),
112        None => Ok(gpu().map_or(Backend::Cpu, |()| Backend::Gpu)),
113    }
114}
115
116/// A mounted UI: its tree, text system and input state. One per window.
117pub struct Ui {
118    shared: Rc<Shared>,
119    text: RefCell<TextSystem>,
120    view: View,
121}
122
123impl std::fmt::Debug for Ui {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("Ui").finish_non_exhaustive()
126    }
127}
128
129impl Ui {
130    /// Mounts `root()` in a view under `scope`. `request_frame` is called
131    /// whenever something changed that needs a new frame.
132    pub fn mount(
133        scope: Scope,
134        theme: Theme,
135        request_frame: Rc<dyn Fn()>,
136        root: impl FnOnce() -> Element,
137    ) -> Ui {
138        let view = View::root(scope);
139        let shared = Rc::new(Shared {
140            tree: RefCell::new(Tree::new(view.clone())),
141            theme,
142            request_frame: RefCell::new(request_frame),
143        });
144        let root_id = shared.tree.borrow().root;
145        view.run(|| {
146            let el = untrack(root);
147            tree::mount(&shared, el.0, root_id, &view);
148        });
149        Ui {
150            shared,
151            text: RefCell::new(TextSystem::new()),
152            view,
153        }
154    }
155
156    /// The root view.
157    pub fn view(&self) -> &View {
158        &self.view
159    }
160
161    /// Unmounts everything (cancels tasks and in-flight calls).
162    pub fn unmount(&self) {
163        self.view.dispose();
164    }
165
166    /// Sets the window size in logical pixels.
167    pub fn resize(&self, width: f32, height: f32) {
168        self.set_viewport(Rect::new(0.0, 0.0, width, height));
169    }
170
171    /// Lays out controls within the platform's usable rectangle, in window coordinates.
172    pub fn set_viewport(&self, bounds: Rect) {
173        let mut tree = self.shared.tree.borrow_mut();
174        let origin = (bounds.x, bounds.y);
175        let size = (bounds.width.max(0.0), bounds.height.max(0.0));
176        if tree.origin != origin || tree.size != size {
177            tree.origin = origin;
178            tree.size = size;
179            tree.layout_dirty = true;
180            tree.dirty = true;
181        }
182    }
183
184    /// Whether something changed since the last [`frame`](Self::frame).
185    pub fn needs_frame(&self) -> bool {
186        let t = self.shared.tree.borrow();
187        t.dirty || t.layout_dirty || self.frame_sources_changed(&t)
188    }
189
190    fn frame_sources_changed(&self, t: &Tree) -> bool {
191        let mut changed = false;
192        t.walk(t.root, &mut |_, n| {
193            changed |= n.viewport.as_ref().is_some_and(|v| v.dirty());
194            if let Some(c) = &n.canvas
195                && serge_core::paint::sources_changed(&c.sources)
196            {
197                changed = true;
198            }
199        });
200        changed
201    }
202
203    /// Whether a canvas reads a frame source (the host then keeps
204    /// producing frames).
205    pub fn animating(&self) -> bool {
206        let t = self.shared.tree.borrow();
207        let mut any = false;
208        t.walk(t.root, &mut |_, n| {
209            if n.viewport.is_some() || n.canvas.as_ref().is_some_and(|c| !c.sources.is_empty()) {
210                any = true;
211            }
212        });
213        any
214    }
215
216    /// Lays out and collects the scene.
217    pub fn frame(&self) -> Vec<ScenePrimitive> {
218        self.frame_at(1.0)
219    }
220
221    /// Collects a frame for a specific physical pixel scale.
222    pub fn frame_at(&self, scale: f32) -> Vec<ScenePrimitive> {
223        self.shared.tree.borrow_mut().scale = scale;
224        // Canvases whose frame sources changed repaint first.
225        let stale: Vec<_> = {
226            let t = self.shared.tree.borrow();
227            let mut v = Vec::new();
228            t.walk(t.root, &mut |_, n| {
229                if let Some(c) = &n.canvas
230                    && serge_core::paint::sources_changed(&c.sources)
231                {
232                    v.push(c.tick);
233                }
234            });
235            v
236        };
237        for tick in stale {
238            tick.update(|t| *t += 1);
239        }
240        // Layout may resize canvases, whose paint then runs; one more pass
241        // picks up anything that changed size again.
242        for _ in 0..3 {
243            let resized = {
244                let mut t = self.shared.tree.borrow_mut();
245                if !std::mem::take(&mut t.layout_dirty) {
246                    break;
247                }
248                let mut text = self.text.borrow_mut();
249                scene::layout(&mut t, &mut text)
250            };
251            if resized.is_empty() {
252                break;
253            }
254            let mut t = self.shared.tree.borrow_mut();
255            let signals: Vec<_> = resized
256                .into_iter()
257                .filter_map(|(id, r)| {
258                    t.node_mut(id)
259                        .and_then(|n| n.canvas.as_ref())
260                        .map(|c| (c.bounds, r))
261                })
262                .collect();
263            drop(t);
264            for (s, r) in signals {
265                s.set(r);
266            }
267        }
268        let mut t = self.shared.tree.borrow_mut();
269        t.dirty = false;
270        let mut text = self.text.borrow_mut();
271        scene::collect(&t, &mut text, &self.shared.theme)
272    }
273
274    fn handler(&self, id: usize, pick: impl Fn(&Handler) -> bool) -> Option<(Handler, View)> {
275        let t = self.shared.tree.borrow();
276        let n = t.node(id)?;
277        n.handlers
278            .iter()
279            .find(|h| pick(h))
280            .map(|h| (h.clone(), n.view.clone()))
281    }
282
283    /// Invalidates viewport resources after the native surface has been released.
284    pub fn invalidate_surfaces(&self) {
285        let mut tree = self.shared.tree.borrow_mut();
286        tree.walk(tree.root, &mut |_, n| {
287            if let Some(slot) = &n.viewport {
288                slot.invalidate()
289            }
290        });
291        tree.dirty = true;
292    }
293
294    fn viewport_pointer(
295        &self,
296        x: f32,
297        y: f32,
298        event: impl FnOnce(Point) -> serge_core::viewport::Pointer,
299        captured: bool,
300    ) {
301        let hit = {
302            let tree = self.shared.tree.borrow();
303            let id = if captured { tree.pressed } else { None }.or_else(|| scene::hit(&tree, x, y));
304            id.and_then(|id| tree.node(id)).and_then(|n| {
305                Some((
306                    n.viewport.clone()?,
307                    Point::new(
308                        (x - n.rect.x) * tree.scale,
309                        (y + tree.scroll_y - n.rect.y) * tree.scale,
310                    ),
311                ))
312            })
313        };
314        if let Some((slot, point)) = hit {
315            slot.pointer(event(point))
316        }
317    }
318
319    /// The pointer moved; returns whether a frame is needed.
320    pub fn pointer_move(&self, x: f32, y: f32) -> bool {
321        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Move, true);
322        let drag = self.shared.tree.borrow().drag;
323        if let Some(id) = drag {
324            self.slide(id, x);
325            return true;
326        }
327        let mut t = self.shared.tree.borrow_mut();
328        let h = scene::hit(&t, x, y);
329        if h != t.hover {
330            t.hover = h;
331            t.dirty = true;
332            return true;
333        }
334        false
335    }
336
337    /// The primary button went down.
338    pub fn pointer_down(&self, x: f32, y: f32) {
339        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Down, false);
340        let target = {
341            let mut t = self.shared.tree.borrow_mut();
342            let h = scene::hit(&t, x, y);
343            t.hover = h;
344            t.pressed = h;
345            t.focus = h;
346            t.dirty = true;
347            h
348        };
349        if let Some(id) = target
350            && self.kind(id) == Some(Kind::Slider)
351        {
352            self.shared.tree.borrow_mut().drag = Some(id);
353            self.slide(id, x);
354        }
355    }
356
357    /// Stops an interrupted pointer gesture without activating the pressed control.
358    pub fn pointer_cancel(&self) {
359        let slot = {
360            let tree = self.shared.tree.borrow();
361            tree.pressed
362                .and_then(|id| tree.node(id))
363                .and_then(|n| n.viewport.clone())
364        };
365        if let Some(slot) = slot {
366            slot.pointer(serge_core::viewport::Pointer::Cancel);
367        }
368
369        let mut tree = self.shared.tree.borrow_mut();
370        tree.pressed = None;
371        tree.drag = None;
372        tree.hover = None;
373        tree.dirty = true;
374    }
375
376    /// Whether the focused control accepts input from a platform keyboard.
377    pub fn wants_text_input(&self) -> bool {
378        let tree = self.shared.tree.borrow();
379        tree.focus.and_then(|id| tree.node(id)).is_some_and(|node| {
380            node.kind == NKind::Widget(Kind::Input) && !node.flag(Attr::Disabled)
381        })
382    }
383
384    /// The primary button went up: clicks, toggles.
385    pub fn pointer_up(&self, x: f32, y: f32) {
386        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Up, true);
387        let (pressed, over) = {
388            let mut t = self.shared.tree.borrow_mut();
389            let p = t.pressed.take();
390            t.drag = None;
391            t.dirty = true;
392            (p, scene::hit(&t, x, y))
393        };
394        let Some(id) = pressed.filter(|p| Some(*p) == over) else {
395            return;
396        };
397        self.activate(id);
398    }
399
400    fn activate(&self, id: usize) {
401        let (kind, disabled, checked, href) = {
402            let t = self.shared.tree.borrow();
403            let Some(n) = t.node(id) else { return };
404            (
405                self.kind(id),
406                n.flag(Attr::Disabled),
407                n.flag(Attr::Checked),
408                n.attr(Attr::Href).map(|v| v.as_str().to_owned()),
409            )
410        };
411        match kind {
412            Some(Kind::Button) if !disabled => {
413                if let Some((Handler::Clicked(f), v)) =
414                    self.handler(id, |h| matches!(h, Handler::Clicked(_)))
415                {
416                    v.run(|| f());
417                }
418            }
419            Some(Kind::Checkbox) if !disabled => {
420                if let Some((Handler::ChangedBool(f), v)) =
421                    self.handler(id, |h| matches!(h, Handler::ChangedBool(_)))
422                {
423                    v.run(|| f(!checked));
424                }
425            }
426            Some(Kind::Link) if !disabled => {
427                if let Some(to) = href {
428                    let v = self.shared.tree.borrow().node(id).map(|n| n.view.clone());
429                    if let Some(v) = v {
430                        v.run(|| serge_core::navigate(&to));
431                    }
432                }
433            }
434            _ => {}
435        }
436        self.shared.changed();
437    }
438
439    /// Scrolls the window content by `dy` logical pixels.
440    pub fn scroll(&self, dy: f32) {
441        let mut t = self.shared.tree.borrow_mut();
442        let max = (t.content_height - t.size.1).max(0.0);
443        t.scroll_y = (t.scroll_y + dy).clamp(0.0, max);
444        t.dirty = true;
445    }
446
447    /// Text typed (or committed by an input method) into the focused input.
448    pub fn text_input(&self, s: &str) {
449        let s: String = s.chars().filter(|c| !c.is_control()).collect();
450        if s.is_empty() {
451            return;
452        }
453        self.edit(|text| text.push_str(&s));
454    }
455
456    /// A non-text key.
457    pub fn key(&self, key: Key) {
458        match key {
459            Key::Backspace => self.edit(|t| {
460                t.pop();
461            }),
462            Key::Enter | Key::Space | Key::Step(_) => {
463                let Some(id) = self.shared.tree.borrow().focus else {
464                    return;
465                };
466                match (self.kind(id), key) {
467                    (Some(Kind::Input), Key::Enter) => {
468                        if let Some((Handler::Submitted(f), v)) =
469                            self.handler(id, |h| matches!(h, Handler::Submitted(_)))
470                        {
471                            v.run(|| f());
472                        }
473                    }
474                    (Some(Kind::Input), Key::Space) => self.text_input(" "),
475                    (Some(Kind::Button | Kind::Checkbox), Key::Space | Key::Enter)
476                    | (Some(Kind::Link), Key::Enter) => self.activate(id),
477                    (Some(Kind::Slider), Key::Step(up)) => self.set_slider(id, |n, step| {
478                        n.num(Attr::Value, n.num(Attr::Min, 0.0)) + if up { step } else { -step }
479                    }),
480                    _ => {}
481                }
482            }
483            Key::Escape => {
484                self.shared.tree.borrow_mut().focus = None;
485            }
486            Key::Tab | Key::BackTab => {
487                let mut t = self.shared.tree.borrow_mut();
488                let mut controls = Vec::new();
489                t.walk(t.root, &mut |id, n| {
490                    if n.focusable() {
491                        controls.push(id);
492                    }
493                });
494                if key == Key::BackTab {
495                    controls.reverse();
496                }
497                let position = controls.iter().position(|id| Some(*id) == t.focus);
498                t.focus = position
499                    .and_then(|p| controls.get(p + 1))
500                    .or(controls.first())
501                    .copied();
502            }
503        }
504        self.shared.changed();
505    }
506
507    fn edit(&self, f: impl FnOnce(&mut String)) {
508        let (id, text) = {
509            let mut t = self.shared.tree.borrow_mut();
510            let Some(id) = t.focus else { return };
511            let Some(n) = t.node_mut(id) else { return };
512            if n.kind != NKind::Widget(Kind::Input) || n.flag(Attr::Disabled) {
513                return;
514            }
515            f(&mut n.input);
516            (id, n.input.clone())
517        };
518        if let Some((Handler::ChangedText(f), v)) =
519            self.handler(id, |h| matches!(h, Handler::ChangedText(_)))
520        {
521            v.run(|| f(text));
522        }
523        self.shared.changed();
524    }
525
526    fn kind(&self, id: usize) -> Option<Kind> {
527        match self.shared.tree.borrow().node(id)?.kind {
528            NKind::Widget(k) => Some(k),
529            _ => None,
530        }
531    }
532
533    fn slide(&self, id: usize, x: f32) {
534        self.set_slider(id, |n, _| {
535            let track = scene::slider_track(n, 0.0);
536            let (lo, hi) = (n.num(Attr::Min, 0.0), n.num(Attr::Max, 1.0));
537            lo + ((x - track.x) / track.width).clamp(0.0, 1.0) * (hi - lo)
538        });
539    }
540
541    fn set_slider(&self, id: usize, change: impl FnOnce(&tree::NNode, f32) -> f32) {
542        let value = {
543            let t = self.shared.tree.borrow();
544            let Some(n) = t.node(id) else { return };
545            let (lo, hi) = (n.num(Attr::Min, 0.0), n.num(Attr::Max, 1.0));
546            if !n.focusable() || !lo.is_finite() || !hi.is_finite() || lo >= hi {
547                return;
548            }
549            let step = n.num(Attr::Step, 0.0);
550            let mut v = change(n, if step > 0.0 { step } else { (hi - lo) / 100.0 });
551            if !v.is_finite() {
552                return;
553            }
554            if step > 0.0 {
555                v = lo + ((v - lo) / step).round() * step;
556            }
557            v.clamp(lo, hi)
558        };
559        if let Some((Handler::ChangedNum(f), v)) =
560            self.handler(id, |h| matches!(h, Handler::ChangedNum(_)))
561        {
562            v.run(|| f(value));
563        }
564        self.shared.changed();
565    }
566
567    /// The cursor to show at `(x, y)`.
568    pub fn cursor_at(&self, x: f32, y: f32) -> Cursor {
569        let t = self.shared.tree.borrow();
570        match scene::hit(&t, x, y).and_then(|id| t.node(id)) {
571            Some(n) => n.cursor.unwrap_or(match n.kind {
572                NKind::Widget(Kind::Input) => Cursor::Text,
573                _ => Cursor::Pointer,
574            }),
575            None => Cursor::Default,
576        }
577    }
578
579    /// Visible widgets with text, in paint order: `(kind, text, rect in
580    /// window coordinates)`. For tests and accessibility.
581    pub fn texts(&self) -> Vec<(Kind, String, Rect)> {
582        let t = self.shared.tree.borrow();
583        let mut out = Vec::new();
584        let dy = -t.scroll_y;
585        t.walk(t.root, &mut |_, n| {
586            if let NKind::Widget(k) = n.kind {
587                let text = match k {
588                    Kind::Input => n.input.clone(),
589                    _ => n.text().to_owned(),
590                };
591                if !text.is_empty() || matches!(k, Kind::Input) {
592                    out.push((k, text, n.rect.offset(0.0, dy)));
593                }
594            }
595        });
596        out
597    }
598
599    /// Widgets of `kind` in paint order with their rects and attributes.
600    pub fn widgets(&self, kind: Kind) -> Vec<(Rect, Vec<(Attr, AttrValue)>)> {
601        let t = self.shared.tree.borrow();
602        let mut out = Vec::new();
603        let dy = -t.scroll_y;
604        t.walk(t.root, &mut |_, n| {
605            if n.kind == NKind::Widget(kind) {
606                out.push((n.rect.offset(0.0, dy), n.attrs.clone()));
607            }
608        });
609        out
610    }
611}
612
613/// The UI without a window: the native runtime, the CPU-side scene and
614/// simulated input, for tests (`docs/01-dx-and-dsl.md` §2, 헤드리스 통합
615/// 테스트).
616pub struct Headless {
617    ui: Ui,
618    exec: LocalExecutor,
619}
620
621impl std::fmt::Debug for Headless {
622    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623        f.debug_struct("Headless").finish_non_exhaustive()
624    }
625}
626
627impl Headless {
628    /// Mounts `root()` in a `width` × `height` window under a new root scope.
629    pub fn new(width: f32, height: f32, root: impl FnOnce() -> Element) -> Headless {
630        Headless::with_scope(Scope::root(), width, height, root)
631    }
632
633    /// Like [`new`](Self::new) under `scope` (with values provided).
634    pub fn with_scope(
635        scope: Scope,
636        width: f32,
637        height: f32,
638        root: impl FnOnce() -> Element,
639    ) -> Headless {
640        let exec = LocalExecutor::new(|| {});
641        serge_core::install_executor(Rc::new(exec.clone()));
642        let ui = Ui::mount(scope, Theme::LIGHT, Rc::new(|| {}), root);
643        ui.resize(width, height);
644        let h = Headless { ui, exec };
645        h.settle();
646        h
647    }
648
649    /// The runtime.
650    pub fn ui(&self) -> &Ui {
651        &self.ui
652    }
653
654    /// Polls ready tasks and produces a frame (layout and paint).
655    pub fn settle(&self) -> Vec<ScenePrimitive> {
656        self.exec.run_ready();
657        self.ui.frame()
658    }
659
660    /// Settles until `cond` holds or `timeout` passes (tasks waiting on I/O
661    /// on other threads); returns whether it held.
662    pub fn wait_until(&self, timeout: Duration, cond: impl Fn(&Headless) -> bool) -> bool {
663        let end = Instant::now() + timeout;
664        loop {
665            self.settle();
666            if cond(self) {
667                return true;
668            }
669            if Instant::now() > end {
670                return false;
671            }
672            std::thread::sleep(Duration::from_millis(5));
673        }
674    }
675
676    /// The visible texts in paint order.
677    pub fn texts(&self) -> Vec<String> {
678        self.ui.texts().into_iter().map(|(_, t, _)| t).collect()
679    }
680
681    /// Whether some widget shows exactly `text`.
682    pub fn shows(&self, text: &str) -> bool {
683        self.texts().iter().any(|t| t == text)
684    }
685
686    /// The rect of the first widget showing `text`.
687    pub fn rect_of(&self, text: &str) -> Option<Rect> {
688        self.ui
689            .texts()
690            .into_iter()
691            .find(|(_, t, _)| t == text)
692            .map(|(_, _, r)| r)
693    }
694
695    /// Clicks at `(x, y)` and settles.
696    pub fn click(&self, x: f32, y: f32) {
697        self.ui.pointer_move(x, y);
698        self.ui.pointer_down(x, y);
699        self.ui.pointer_up(x, y);
700        self.settle();
701    }
702
703    /// Clicks the center of the first widget showing `text`.
704    ///
705    /// # Panics
706    ///
707    /// Panics if no widget shows `text`.
708    pub fn click_text(&self, text: &str) {
709        let r = self
710            .rect_of(text)
711            .unwrap_or_else(|| panic!("no widget shows {text:?}; visible: {:?}", self.texts()));
712        let c = r.center();
713        self.click(c.x, c.y);
714    }
715
716    /// Drags the `nth` slider to `fraction` of its track.
717    pub fn slide(&self, nth: usize, fraction: f32) {
718        let (r, _) = self
719            .ui
720            .widgets(Kind::Slider)
721            .into_iter()
722            .nth(nth)
723            .expect("slider");
724        let track = Rect::new(
725            r.x + scene::THUMB,
726            r.y,
727            r.width - 2.0 * scene::THUMB,
728            r.height,
729        );
730        let y = r.center().y;
731        self.ui.pointer_down(r.center().x, y);
732        self.ui.pointer_move(track.x + track.width * fraction, y);
733        self.ui.pointer_up(track.x + track.width * fraction, y);
734        self.settle();
735    }
736
737    /// Focuses the `nth` input and types `text`.
738    pub fn type_into(&self, nth: usize, text: &str) {
739        let (r, _) = self
740            .ui
741            .widgets(Kind::Input)
742            .into_iter()
743            .nth(nth)
744            .expect("input");
745        let c = r.center();
746        self.ui.pointer_down(c.x, c.y);
747        self.ui.pointer_up(c.x, c.y);
748        self.ui.text_input(text);
749        self.settle();
750    }
751
752    /// Presses a key and settles.
753    pub fn press(&self, key: Key) {
754        self.ui.key(key);
755        self.settle();
756    }
757
758    /// How many UI tasks are alive.
759    pub fn tasks(&self) -> usize {
760        self.exec.len()
761    }
762}
763
764impl Drop for Headless {
765    fn drop(&mut self) {
766        self.ui.unmount();
767    }
768}