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.dirty = true;
180        }
181    }
182
183    /// Whether something changed since the last [`frame`](Self::frame).
184    pub fn needs_frame(&self) -> bool {
185        let t = self.shared.tree.borrow();
186        t.dirty || self.frame_sources_changed(&t)
187    }
188
189    fn frame_sources_changed(&self, t: &Tree) -> bool {
190        let mut changed = false;
191        t.walk(t.root, &mut |_, n| {
192            changed |= n.viewport.as_ref().is_some_and(|v| v.dirty());
193            if let Some(c) = &n.canvas
194                && serge_core::paint::sources_changed(&c.sources)
195            {
196                changed = true;
197            }
198        });
199        changed
200    }
201
202    /// Whether a canvas reads a frame source (the host then keeps
203    /// producing frames).
204    pub fn animating(&self) -> bool {
205        let t = self.shared.tree.borrow();
206        let mut any = false;
207        t.walk(t.root, &mut |_, n| {
208            if n.viewport.is_some() || n.canvas.as_ref().is_some_and(|c| !c.sources.is_empty()) {
209                any = true;
210            }
211        });
212        any
213    }
214
215    /// Lays out and collects the scene.
216    pub fn frame(&self) -> Vec<ScenePrimitive> {
217        self.frame_at(1.0)
218    }
219
220    /// Collects a frame for a specific physical pixel scale.
221    pub fn frame_at(&self, scale: f32) -> Vec<ScenePrimitive> {
222        self.shared.tree.borrow_mut().scale = scale;
223        // Canvases whose frame sources changed repaint first.
224        let stale: Vec<_> = {
225            let t = self.shared.tree.borrow();
226            let mut v = Vec::new();
227            t.walk(t.root, &mut |_, n| {
228                if let Some(c) = &n.canvas
229                    && serge_core::paint::sources_changed(&c.sources)
230                {
231                    v.push(c.tick);
232                }
233            });
234            v
235        };
236        for tick in stale {
237            tick.update(|t| *t += 1);
238        }
239        // Layout may resize canvases, whose paint then runs; one more pass
240        // picks up anything that changed size again.
241        for _ in 0..3 {
242            let resized = {
243                let mut t = self.shared.tree.borrow_mut();
244                let mut text = self.text.borrow_mut();
245                scene::layout(&mut t, &mut text)
246            };
247            if resized.is_empty() {
248                break;
249            }
250            let mut t = self.shared.tree.borrow_mut();
251            let signals: Vec<_> = resized
252                .into_iter()
253                .filter_map(|(id, r)| {
254                    t.node_mut(id)
255                        .and_then(|n| n.canvas.as_ref())
256                        .map(|c| (c.bounds, r))
257                })
258                .collect();
259            drop(t);
260            for (s, r) in signals {
261                s.set(r);
262            }
263        }
264        let mut t = self.shared.tree.borrow_mut();
265        t.dirty = false;
266        let mut text = self.text.borrow_mut();
267        scene::collect(&t, &mut text, &self.shared.theme)
268    }
269
270    fn handler(&self, id: usize, pick: impl Fn(&Handler) -> bool) -> Option<(Handler, View)> {
271        let t = self.shared.tree.borrow();
272        let n = t.node(id)?;
273        n.handlers
274            .iter()
275            .find(|h| pick(h))
276            .map(|h| (h.clone(), n.view.clone()))
277    }
278
279    /// Invalidates viewport resources after the native surface has been released.
280    pub fn invalidate_surfaces(&self) {
281        let mut tree = self.shared.tree.borrow_mut();
282        tree.walk(tree.root, &mut |_, n| {
283            if let Some(slot) = &n.viewport {
284                slot.invalidate()
285            }
286        });
287        tree.dirty = true;
288    }
289
290    fn viewport_pointer(
291        &self,
292        x: f32,
293        y: f32,
294        event: impl FnOnce(Point) -> serge_core::viewport::Pointer,
295        captured: bool,
296    ) {
297        let hit = {
298            let tree = self.shared.tree.borrow();
299            let id = if captured { tree.pressed } else { None }.or_else(|| scene::hit(&tree, x, y));
300            id.and_then(|id| tree.node(id)).and_then(|n| {
301                Some((
302                    n.viewport.clone()?,
303                    Point::new(
304                        (x - n.rect.x) * tree.scale,
305                        (y + tree.scroll_y - n.rect.y) * tree.scale,
306                    ),
307                ))
308            })
309        };
310        if let Some((slot, point)) = hit {
311            slot.pointer(event(point))
312        }
313    }
314
315    /// The pointer moved; returns whether a frame is needed.
316    pub fn pointer_move(&self, x: f32, y: f32) -> bool {
317        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Move, true);
318        let drag = self.shared.tree.borrow().drag;
319        if let Some(id) = drag {
320            self.slide(id, x);
321            return true;
322        }
323        let mut t = self.shared.tree.borrow_mut();
324        let h = scene::hit(&t, x, y);
325        if h != t.hover {
326            t.hover = h;
327            t.dirty = true;
328            return true;
329        }
330        false
331    }
332
333    /// The primary button went down.
334    pub fn pointer_down(&self, x: f32, y: f32) {
335        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Down, false);
336        let target = {
337            let mut t = self.shared.tree.borrow_mut();
338            let h = scene::hit(&t, x, y);
339            t.hover = h;
340            t.pressed = h;
341            t.focus = h;
342            t.dirty = true;
343            h
344        };
345        if let Some(id) = target
346            && self.kind(id) == Some(Kind::Slider)
347        {
348            self.shared.tree.borrow_mut().drag = Some(id);
349            self.slide(id, x);
350        }
351    }
352
353    /// Stops an interrupted pointer gesture without activating the pressed control.
354    pub fn pointer_cancel(&self) {
355        let slot = {
356            let tree = self.shared.tree.borrow();
357            tree.pressed
358                .and_then(|id| tree.node(id))
359                .and_then(|n| n.viewport.clone())
360        };
361        if let Some(slot) = slot {
362            slot.pointer(serge_core::viewport::Pointer::Cancel);
363        }
364
365        let mut tree = self.shared.tree.borrow_mut();
366        tree.pressed = None;
367        tree.drag = None;
368        tree.hover = None;
369        tree.dirty = true;
370    }
371
372    /// Whether the focused control accepts input from a platform keyboard.
373    pub fn wants_text_input(&self) -> bool {
374        let tree = self.shared.tree.borrow();
375        tree.focus.and_then(|id| tree.node(id)).is_some_and(|node| {
376            node.kind == NKind::Widget(Kind::Input) && !node.flag(Attr::Disabled)
377        })
378    }
379
380    /// The primary button went up: clicks, toggles.
381    pub fn pointer_up(&self, x: f32, y: f32) {
382        self.viewport_pointer(x, y, serge_core::viewport::Pointer::Up, true);
383        let (pressed, over) = {
384            let mut t = self.shared.tree.borrow_mut();
385            let p = t.pressed.take();
386            t.drag = None;
387            t.dirty = true;
388            (p, scene::hit(&t, x, y))
389        };
390        let Some(id) = pressed.filter(|p| Some(*p) == over) else {
391            return;
392        };
393        self.activate(id);
394    }
395
396    fn activate(&self, id: usize) {
397        let (kind, disabled, checked, href) = {
398            let t = self.shared.tree.borrow();
399            let Some(n) = t.node(id) else { return };
400            (
401                self.kind(id),
402                n.flag(Attr::Disabled),
403                n.flag(Attr::Checked),
404                n.attr(Attr::Href).map(|v| v.as_str().to_owned()),
405            )
406        };
407        match kind {
408            Some(Kind::Button) if !disabled => {
409                if let Some((Handler::Clicked(f), v)) =
410                    self.handler(id, |h| matches!(h, Handler::Clicked(_)))
411                {
412                    v.run(|| f());
413                }
414            }
415            Some(Kind::Checkbox) if !disabled => {
416                if let Some((Handler::ChangedBool(f), v)) =
417                    self.handler(id, |h| matches!(h, Handler::ChangedBool(_)))
418                {
419                    v.run(|| f(!checked));
420                }
421            }
422            Some(Kind::Link) if !disabled => {
423                if let Some(to) = href {
424                    let v = self.shared.tree.borrow().node(id).map(|n| n.view.clone());
425                    if let Some(v) = v {
426                        v.run(|| serge_core::navigate(&to));
427                    }
428                }
429            }
430            _ => {}
431        }
432        self.shared.changed();
433    }
434
435    /// Scrolls the window content by `dy` logical pixels.
436    pub fn scroll(&self, dy: f32) {
437        let mut t = self.shared.tree.borrow_mut();
438        let max = (t.content_height - t.size.1).max(0.0);
439        t.scroll_y = (t.scroll_y + dy).clamp(0.0, max);
440        t.dirty = true;
441    }
442
443    /// Text typed (or committed by an input method) into the focused input.
444    pub fn text_input(&self, s: &str) {
445        let s: String = s.chars().filter(|c| !c.is_control()).collect();
446        if s.is_empty() {
447            return;
448        }
449        self.edit(|text| text.push_str(&s));
450    }
451
452    /// A non-text key.
453    pub fn key(&self, key: Key) {
454        match key {
455            Key::Backspace => self.edit(|t| {
456                t.pop();
457            }),
458            Key::Enter | Key::Space | Key::Step(_) => {
459                let Some(id) = self.shared.tree.borrow().focus else {
460                    return;
461                };
462                match (self.kind(id), key) {
463                    (Some(Kind::Input), Key::Enter) => {
464                        if let Some((Handler::Submitted(f), v)) =
465                            self.handler(id, |h| matches!(h, Handler::Submitted(_)))
466                        {
467                            v.run(|| f());
468                        }
469                    }
470                    (Some(Kind::Input), Key::Space) => self.text_input(" "),
471                    (Some(Kind::Button | Kind::Checkbox), Key::Space | Key::Enter)
472                    | (Some(Kind::Link), Key::Enter) => self.activate(id),
473                    (Some(Kind::Slider), Key::Step(up)) => self.set_slider(id, |n, step| {
474                        n.num(Attr::Value, n.num(Attr::Min, 0.0)) + if up { step } else { -step }
475                    }),
476                    _ => {}
477                }
478            }
479            Key::Escape => {
480                self.shared.tree.borrow_mut().focus = None;
481            }
482            Key::Tab | Key::BackTab => {
483                let mut t = self.shared.tree.borrow_mut();
484                let mut controls = Vec::new();
485                t.walk(t.root, &mut |id, n| {
486                    if n.focusable() {
487                        controls.push(id);
488                    }
489                });
490                if key == Key::BackTab {
491                    controls.reverse();
492                }
493                let position = controls.iter().position(|id| Some(*id) == t.focus);
494                t.focus = position
495                    .and_then(|p| controls.get(p + 1))
496                    .or(controls.first())
497                    .copied();
498            }
499        }
500        self.shared.changed();
501    }
502
503    fn edit(&self, f: impl FnOnce(&mut String)) {
504        let (id, text) = {
505            let mut t = self.shared.tree.borrow_mut();
506            let Some(id) = t.focus else { return };
507            let Some(n) = t.node_mut(id) else { return };
508            if n.kind != NKind::Widget(Kind::Input) || n.flag(Attr::Disabled) {
509                return;
510            }
511            f(&mut n.input);
512            (id, n.input.clone())
513        };
514        if let Some((Handler::ChangedText(f), v)) =
515            self.handler(id, |h| matches!(h, Handler::ChangedText(_)))
516        {
517            v.run(|| f(text));
518        }
519        self.shared.changed();
520    }
521
522    fn kind(&self, id: usize) -> Option<Kind> {
523        match self.shared.tree.borrow().node(id)?.kind {
524            NKind::Widget(k) => Some(k),
525            _ => None,
526        }
527    }
528
529    fn slide(&self, id: usize, x: f32) {
530        self.set_slider(id, |n, _| {
531            let track = scene::slider_track(n, 0.0);
532            let (lo, hi) = (n.num(Attr::Min, 0.0), n.num(Attr::Max, 1.0));
533            lo + ((x - track.x) / track.width).clamp(0.0, 1.0) * (hi - lo)
534        });
535    }
536
537    fn set_slider(&self, id: usize, change: impl FnOnce(&tree::NNode, f32) -> f32) {
538        let value = {
539            let t = self.shared.tree.borrow();
540            let Some(n) = t.node(id) else { return };
541            let (lo, hi) = (n.num(Attr::Min, 0.0), n.num(Attr::Max, 1.0));
542            if !n.focusable() || !lo.is_finite() || !hi.is_finite() || lo >= hi {
543                return;
544            }
545            let step = n.num(Attr::Step, 0.0);
546            let mut v = change(n, if step > 0.0 { step } else { (hi - lo) / 100.0 });
547            if !v.is_finite() {
548                return;
549            }
550            if step > 0.0 {
551                v = lo + ((v - lo) / step).round() * step;
552            }
553            v.clamp(lo, hi)
554        };
555        if let Some((Handler::ChangedNum(f), v)) =
556            self.handler(id, |h| matches!(h, Handler::ChangedNum(_)))
557        {
558            v.run(|| f(value));
559        }
560        self.shared.changed();
561    }
562
563    /// The cursor to show at `(x, y)`.
564    pub fn cursor_at(&self, x: f32, y: f32) -> Cursor {
565        let t = self.shared.tree.borrow();
566        match scene::hit(&t, x, y).and_then(|id| t.node(id)) {
567            Some(n) => n.cursor.unwrap_or(match n.kind {
568                NKind::Widget(Kind::Input) => Cursor::Text,
569                _ => Cursor::Pointer,
570            }),
571            None => Cursor::Default,
572        }
573    }
574
575    /// Visible widgets with text, in paint order: `(kind, text, rect in
576    /// window coordinates)`. For tests and accessibility.
577    pub fn texts(&self) -> Vec<(Kind, String, Rect)> {
578        let t = self.shared.tree.borrow();
579        let mut out = Vec::new();
580        let dy = -t.scroll_y;
581        t.walk(t.root, &mut |_, n| {
582            if let NKind::Widget(k) = n.kind {
583                let text = match k {
584                    Kind::Input => n.input.clone(),
585                    _ => n.text().to_owned(),
586                };
587                if !text.is_empty() || matches!(k, Kind::Input) {
588                    out.push((k, text, n.rect.offset(0.0, dy)));
589                }
590            }
591        });
592        out
593    }
594
595    /// Widgets of `kind` in paint order with their rects and attributes.
596    pub fn widgets(&self, kind: Kind) -> Vec<(Rect, Vec<(Attr, AttrValue)>)> {
597        let t = self.shared.tree.borrow();
598        let mut out = Vec::new();
599        let dy = -t.scroll_y;
600        t.walk(t.root, &mut |_, n| {
601            if n.kind == NKind::Widget(kind) {
602                out.push((n.rect.offset(0.0, dy), n.attrs.clone()));
603            }
604        });
605        out
606    }
607}
608
609/// The UI without a window: the native runtime, the CPU-side scene and
610/// simulated input, for tests (`docs/01-dx-and-dsl.md` §2, 헤드리스 통합
611/// 테스트).
612pub struct Headless {
613    ui: Ui,
614    exec: LocalExecutor,
615}
616
617impl std::fmt::Debug for Headless {
618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619        f.debug_struct("Headless").finish_non_exhaustive()
620    }
621}
622
623impl Headless {
624    /// Mounts `root()` in a `width` × `height` window under a new root scope.
625    pub fn new(width: f32, height: f32, root: impl FnOnce() -> Element) -> Headless {
626        Headless::with_scope(Scope::root(), width, height, root)
627    }
628
629    /// Like [`new`](Self::new) under `scope` (with values provided).
630    pub fn with_scope(
631        scope: Scope,
632        width: f32,
633        height: f32,
634        root: impl FnOnce() -> Element,
635    ) -> Headless {
636        let exec = LocalExecutor::new(|| {});
637        serge_core::install_executor(Rc::new(exec.clone()));
638        let ui = Ui::mount(scope, Theme::LIGHT, Rc::new(|| {}), root);
639        ui.resize(width, height);
640        let h = Headless { ui, exec };
641        h.settle();
642        h
643    }
644
645    /// The runtime.
646    pub fn ui(&self) -> &Ui {
647        &self.ui
648    }
649
650    /// Polls ready tasks and produces a frame (layout and paint).
651    pub fn settle(&self) -> Vec<ScenePrimitive> {
652        self.exec.run_ready();
653        self.ui.frame()
654    }
655
656    /// Settles until `cond` holds or `timeout` passes (tasks waiting on I/O
657    /// on other threads); returns whether it held.
658    pub fn wait_until(&self, timeout: Duration, cond: impl Fn(&Headless) -> bool) -> bool {
659        let end = Instant::now() + timeout;
660        loop {
661            self.settle();
662            if cond(self) {
663                return true;
664            }
665            if Instant::now() > end {
666                return false;
667            }
668            std::thread::sleep(Duration::from_millis(5));
669        }
670    }
671
672    /// The visible texts in paint order.
673    pub fn texts(&self) -> Vec<String> {
674        self.ui.texts().into_iter().map(|(_, t, _)| t).collect()
675    }
676
677    /// Whether some widget shows exactly `text`.
678    pub fn shows(&self, text: &str) -> bool {
679        self.texts().iter().any(|t| t == text)
680    }
681
682    /// The rect of the first widget showing `text`.
683    pub fn rect_of(&self, text: &str) -> Option<Rect> {
684        self.ui
685            .texts()
686            .into_iter()
687            .find(|(_, t, _)| t == text)
688            .map(|(_, _, r)| r)
689    }
690
691    /// Clicks at `(x, y)` and settles.
692    pub fn click(&self, x: f32, y: f32) {
693        self.ui.pointer_move(x, y);
694        self.ui.pointer_down(x, y);
695        self.ui.pointer_up(x, y);
696        self.settle();
697    }
698
699    /// Clicks the center of the first widget showing `text`.
700    ///
701    /// # Panics
702    ///
703    /// Panics if no widget shows `text`.
704    pub fn click_text(&self, text: &str) {
705        let r = self
706            .rect_of(text)
707            .unwrap_or_else(|| panic!("no widget shows {text:?}; visible: {:?}", self.texts()));
708        let c = r.center();
709        self.click(c.x, c.y);
710    }
711
712    /// Drags the `nth` slider to `fraction` of its track.
713    pub fn slide(&self, nth: usize, fraction: f32) {
714        let (r, _) = self
715            .ui
716            .widgets(Kind::Slider)
717            .into_iter()
718            .nth(nth)
719            .expect("slider");
720        let track = Rect::new(
721            r.x + scene::THUMB,
722            r.y,
723            r.width - 2.0 * scene::THUMB,
724            r.height,
725        );
726        let y = r.center().y;
727        self.ui.pointer_down(r.center().x, y);
728        self.ui.pointer_move(track.x + track.width * fraction, y);
729        self.ui.pointer_up(track.x + track.width * fraction, y);
730        self.settle();
731    }
732
733    /// Focuses the `nth` input and types `text`.
734    pub fn type_into(&self, nth: usize, text: &str) {
735        let (r, _) = self
736            .ui
737            .widgets(Kind::Input)
738            .into_iter()
739            .nth(nth)
740            .expect("input");
741        let c = r.center();
742        self.ui.pointer_down(c.x, c.y);
743        self.ui.pointer_up(c.x, c.y);
744        self.ui.text_input(text);
745        self.settle();
746    }
747
748    /// Presses a key and settles.
749    pub fn press(&self, key: Key) {
750        self.ui.key(key);
751        self.settle();
752    }
753
754    /// How many UI tasks are alive.
755    pub fn tasks(&self) -> usize {
756        self.exec.len()
757    }
758}
759
760impl Drop for Headless {
761    fn drop(&mut self) {
762        self.ui.unmount();
763    }
764}