dfui 0.2.0

Declarative UI framework that draws shapes, text and icons analytically in one wgpu shader
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;

use web_time::Instant;
use winit::event::TouchPhase;
use winit::keyboard::{Key as WKey, ModifiersState, NamedKey};

use crate::App;
use crate::layout::{Insets, Layout, Measured, Placed, flatten, order, place, walk, walk_to};
use crate::render::{Color, Outcome, Rect, Renderer, Scene, Spans, damage};
use crate::text::Text;
use crate::widget::{Element, Event, EventCx, Key, Keyboard, PaintCx, State};
use task::{LoopWaker, Tasks};

#[cfg(target_os = "android")]
pub(crate) mod activity;
#[cfg(target_os = "android")]
pub mod android;
mod bench;
mod clipboard;
#[cfg(target_os = "android")]
mod editor;
mod focus;
// TIMERS is already const; clippy misfires on Android's thread_local expansion.
#[allow(clippy::missing_const_for_thread_local)]
pub(crate) mod task;
// Already const; clippy misfires on Android's thread_local expansion.
#[allow(clippy::missing_const_for_thread_local)]
mod insets_cell {
    use super::Insets;
    thread_local! {
        pub(super) static INSETS: std::cell::Cell<Insets> = const { std::cell::Cell::new([0.0; 4]) };
    }
}
use insets_cell::INSETS;

/// The system bars' insets over the window, logical px: top, right, bottom,
/// left. For content in a [`Layer::Screen`](crate::Layer::Screen) layer to
/// pad itself clear of them; views rebuild when they change.
pub fn insets() -> [f32; 4] {
    INSETS.get()
}

/// Tells the user why there's no UI, in the page on the web; elsewhere exits.
#[cfg(target_arch = "wasm32")]
pub(crate) fn startup_failed(reason: &str) -> ! {
    if let Some(body) = web_sys::window()
        .and_then(|w| w.document())
        .and_then(|d| d.body())
    {
        body.set_text_content(Some(&format!("This page needs WebGPU. {reason}")));
    }
    wasm_bindgen::throw_str(reason)
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn startup_failed(reason: &str) -> ! {
    log::error!("{reason}");
    eprintln!("dfui: {reason}");
    std::process::exit(1)
}

#[cfg(test)]
mod tests;
mod winit_app;

pub use bench::{Bench, GpuBench, snapshot};
use clipboard::Clipboard;

type PendingRenderer = Pin<Box<dyn Future<Output = Result<Renderer, String>>>>;

pub(crate) struct Runtime<A: App> {
    app: A,
    root: Element,
    /// Pre-order ids of `root`, so frames that keep the tree skip [`flatten`].
    ids: Vec<u64>,
    /// Paint order of `ids`' indices; layers last.
    order: Vec<usize>,
    /// Per index: one past its last descendant, and its place in `order`.
    ends: Vec<usize>,
    rank: Vec<usize>,
    /// Indices of layer widgets.
    layers: Vec<usize>,
    states: HashMap<u64, State>,
    tasks: Tasks,
    /// Wakes the event loop when a task can progress; a no-op without one.
    waker: Waker,
    loop_waker: Option<Arc<LoopWaker>>,
    text: Text,
    layout: Layout,
    /// Taffy's last result; reused until the tree or viewport changes.
    measured: Vec<Measured>,
    placed: Vec<Placed>,
    captured: Option<u64>,
    /// Nodes (index, id) under the last pointer event and under the press
    /// in progress: they get the next pointer events too, so they see the
    /// pointer leave and keep tracking a drag.
    hovered: Vec<(usize, u64)>,
    pressed: Vec<(usize, u64)>,
    /// Last painted frame, diffed against the next one for damage.
    prev: Option<(Scene, Spans)>,
    /// Animation frame due after an idle one; idle frames don't block on
    /// vsync, so they're paced by this timer instead.
    next_frame: Option<Instant>,
    /// Earliest `request_frame_at` from the last paint.
    wake: Option<Instant>,
    /// A widget asked for placement to rerun before the next paint.
    place: bool,
    /// A widget asked for a rebuild after the last paint.
    rebuild_due: bool,
    /// Hidden windows don't animate; presents would be throttled anyway.
    occluded: bool,
    /// [`App::zoom`] as last applied.
    zoom: f32,
    focused: Option<u64>,
    /// The focused widget takes typing, so character keys arrive as text.
    typing: bool,
    /// Focus came from the keyboard, so the ring shows.
    focus_visible: bool,
    ring: focus::Ring,
    mods: ModifiersState,
    instance: Option<wgpu::Instance>,
    renderer: Option<Renderer>,
    /// GPU setup started in `resumed`; polled like a task until it resolves.
    pending_renderer: Option<PendingRenderer>,
    viewport: (f32, f32),
    cursor: (f32, f32),
    /// Fingers down, by id, at most two.
    fingers: Vec<(u64, (f32, f32))>,
    /// Added to the fingers' midpoint so the pointer doesn't jump when one
    /// lands or lifts.
    finger_shift: (f32, f32),
    clipboard: Clipboard,
    stats: Stats,
    insets: Insets,
    #[cfg(target_os = "android")]
    pub(crate) android: Option<crate::AndroidApp>,
    /// Keyboard requests, since tests have no window to send them to.
    #[cfg(test)]
    ime_requests: Vec<Option<Keyboard>>,
}

/// Rolling frame timings, logged every couple of seconds. The maxima show
/// hitches that the averages hide.
struct Stats {
    since: Instant,
    frames: u32,
    cpu: Duration,
    cpu_max: Duration,
    gpu_max: Option<f32>,
}

impl Default for Stats {
    fn default() -> Self {
        Stats {
            since: Instant::now(),
            frames: 0,
            cpu: Duration::ZERO,
            cpu_max: Duration::ZERO,
            gpu_max: None,
        }
    }
}

impl Stats {
    fn frame(&mut self, cpu: Duration, gpu_ms: Option<f32>, instances: usize) {
        self.frames += 1;
        self.cpu += cpu;
        self.cpu_max = self.cpu_max.max(cpu);
        if let Some(g) = gpu_ms {
            self.gpu_max = Some(self.gpu_max.map_or(g, |m| m.max(g)));
        }
        let window = self.since.elapsed();
        if window >= Duration::from_secs(2) {
            log::info!(
                "fps {:.1}  cpu {:.2}ms (max {:.2}ms)  gpu {} (max {})  instances {instances}",
                self.frames as f32 / window.as_secs_f32(),
                self.cpu.as_secs_f32() * 1e3 / self.frames as f32,
                self.cpu_max.as_secs_f32() * 1e3,
                gpu_ms.map_or("n/a".into(), |g| format!("{g:.2}ms")),
                self.gpu_max.map_or("n/a".into(), |g| format!("{g:.2}ms")),
            );
            *self = Stats::default();
        }
    }
}

impl<A: App> Runtime<A> {
    pub fn new(app: A) -> Self {
        let root = app.view();
        let mut states = HashMap::new();
        let mut tasks = Tasks::new();
        let f = flat_ids(&root, &mut states, &mut tasks);
        Runtime {
            app,
            root,
            ids: f.ids,
            order: f.order,
            ends: f.ends,
            rank: f.rank,
            layers: f.layers,
            states,
            tasks,
            waker: Waker::noop().clone(),
            loop_waker: None,
            text: Text::default(),
            layout: Layout::default(),
            measured: Vec::new(),
            placed: Vec::new(),
            captured: None,
            hovered: Vec::new(),
            pressed: Vec::new(),
            prev: None,
            next_frame: None,
            wake: None,
            place: false,
            rebuild_due: false,
            occluded: false,
            zoom: 1.0,
            focused: None,
            typing: false,
            focus_visible: false,
            ring: focus::Ring::default(),
            #[cfg(test)]
            ime_requests: Vec::new(),
            mods: ModifiersState::empty(),
            instance: None,
            renderer: None,
            pending_renderer: None,
            viewport: (0.0, 0.0),
            cursor: (0.0, 0.0),
            fingers: Vec::new(),
            finger_shift: (0.0, 0.0),
            clipboard: Clipboard::default(),
            stats: Stats::default(),
            insets: [0.0; 4],
            #[cfg(target_os = "android")]
            android: None,
        }
    }

    fn now(&self) -> Instant {
        task::now()
    }

    fn scale(&self) -> f32 {
        self.renderer
            .as_ref()
            .map_or(1.0, |r| r.window().scale() * self.zoom)
    }

    /// The only way `root` changes, so `ids` always matches it.
    fn set_root(&mut self, root: Element) {
        self.root = root;
        let f = flat_ids(&self.root, &mut self.states, &mut self.tasks);
        (self.ids, self.order, self.ends, self.rank, self.layers) =
            (f.ids, f.order, f.ends, f.rank, f.layers);
    }

    /// Rebuilds the tree from `view`, dropping state and tasks of removed nodes.
    // ponytail: any change rebuilds the whole tree; rebuild only dirty subtrees if views get expensive.
    fn rebuild(&mut self) {
        self.set_root(self.app.view());
        let live: std::collections::HashSet<u64> = self.ids.iter().copied().collect();
        self.states.retain(|id, _| live.contains(id));
        self.tasks.retain(|id, _| live.contains(id));
        if self.focused.is_some_and(|id| !live.contains(&id)) {
            self.set_focus(None);
        }
    }

    /// Runs a rebuild a widget asked for while painting.
    fn rebuild_if_due(&mut self) {
        if std::mem::take(&mut self.rebuild_due) {
            self.rebuild();
            self.drive();
            self.relayout();
        }
    }

    /// A task or the renderer setup can progress.
    fn woken(&mut self) {
        if let Some(w) = &self.loop_waker {
            w.clear();
        }
        self.poll_renderer();
        if self.drive() {
            self.redraw();
        }
    }

    fn poll_renderer(&mut self) {
        let Some(f) = &mut self.pending_renderer else {
            return;
        };
        if let Poll::Ready(r) = f.as_mut().poll(&mut Context::from_waker(&self.waker)) {
            self.pending_renderer = None;
            let r = match r {
                Ok(r) => r,
                Err(e) => startup_failed(&e),
            };
            // Resizes during setup were scaled without the window's factor.
            let ((w, h), s) = (r.window().size(), r.window().scale() * self.zoom);
            self.viewport = (w as f32 / s, h as f32 / s);
            self.renderer = Some(r);
            self.update_insets();
            self.redraw();
        }
    }

    /// Polls tasks and rebuilds if they changed state, then does the same for
    /// tasks those rebuilds started. Running tasks wait for their next wake,
    /// so a source faster than a rebuild can't hold off painting. Returns
    /// whether anything changed.
    fn drive(&mut self) -> bool {
        let (mut changed, mut only_new) = (false, false);
        while task::poll(&mut self.tasks, &mut self.states, &self.waker, only_new) {
            self.rebuild();
            (changed, only_new) = (true, true);
        }
        changed
    }

    fn relayout(&mut self) {
        let nodes = walk(&self.root, &self.ids);
        self.measured = self
            .layout
            .measure(&nodes, &self.text, self.viewport, self.insets);
        let now = self.now();
        self.placed = place(&nodes, &self.measured, &mut self.states, now);
    }

    /// System bars cover part of an edge-to-edge window; the content rect is what's left.
    #[cfg(target_os = "android")]
    fn update_insets(&mut self) {
        let (Some(a), Some(r)) = (&self.android, &self.renderer) else {
            return;
        };
        let s = r.window().scale() * self.zoom;
        let insets = android::insets(a).map(|v| v as f32 / s);
        if insets != self.insets {
            self.insets = insets;
            INSETS.set(insets);
            // Views may pad by them.
            self.rebuild_due = true;
            log::info!("insets {:?}", self.insets);
        }
    }

    #[cfg(not(target_os = "android"))]
    fn update_insets(&mut self) {}

    /// The window's new size, physical px.
    fn resized(&mut self, w: u32, h: u32) {
        let scale = self.scale();
        if let Some(r) = &mut self.renderer {
            r.resize(w, h);
        }
        self.viewport = (w as f32 / scale, h as f32 / scale);
        self.update_insets();
        self.redraw();
    }

    fn redraw(&mut self) {
        self.relayout();
        self.request_redraw();
    }

    /// Redraw for changes that keep every size (hover, press, scroll, caret):
    /// only placement reruns.
    fn reposition(&mut self) {
        let nodes = walk(&self.root, &self.ids);
        if nodes.len() != self.measured.len() {
            return self.redraw();
        }
        let now = self.now();
        self.placed = place(&nodes, &self.measured, &mut self.states, now);
        self.request_redraw();
    }

    fn request_redraw(&self) {
        if let Some(r) = &self.renderer {
            r.window().request_redraw();
        }
    }

    /// Whether a widget stopped the event.
    fn dispatch(&mut self, ev: Event) -> bool {
        if self.ids.len() != self.placed.len() {
            return false;
        }
        let mut updates = Vec::new();
        let mut copied = None;
        let mut redraw = false;
        let now = self.now();
        let mut focus = None;
        let keyboard = matches!(ev, Event::Text(_) | Event::Key(_));
        let captured = self.captured.filter(|_| !matches!(ev, Event::Back));
        let find = |id: u64| self.ids.iter().position(|&n| n == id);
        let targets: Vec<usize> = match (keyboard, captured) {
            // Keys go to the focused widget, then to everyone topmost first until one stops them.
            (true, _) if matches!(ev, Event::Key(_)) => {
                let focused = self.focused.and_then(find);
                let rest = self
                    .order
                    .iter()
                    .rev()
                    .copied()
                    .filter(|&i| Some(i) != focused);
                focused.into_iter().chain(rest).collect()
            }
            (true, _) => self.focused.and_then(find).into_iter().collect(),
            (false, Some(id)) => find(id).into_iter().collect(),
            (false, None) if matches!(ev, Event::Cancel | Event::Back) => {
                self.order.iter().rev().copied().collect()
            }
            // Pointer events go to the nodes under them, the tracked ones and
            // layers (overlays watch for taps anywhere); no other node acts
            // on a pointer that isn't over it.
            (false, None) => {
                let ids = &self.ids;
                // A rebuild can move a node; find it again by id.
                let at = |&(i, id): &(usize, u64)| match ids.get(i) == Some(&id) {
                    true => Some(i),
                    false => ids.iter().position(|&n| n == id),
                };
                let mut t: Vec<usize> = self
                    .hovered
                    .iter()
                    .chain(&self.pressed)
                    .filter_map(at)
                    .collect();
                if let Some((x, y)) = pointer_at(&ev) {
                    // ponytail: scans every placed box; a spatial index if this shows up again.
                    let hits: Vec<(usize, u64)> = (0..ids.len())
                        .filter(|&i| {
                            let p = &self.placed[i];
                            p.rect.contains(x, y) && p.clip.contains(x, y)
                        })
                        .map(|i| (i, ids[i]))
                        .collect();
                    t.extend(hits.iter().map(|h| h.0));
                    if let Event::PointerDown { .. } = ev {
                        self.pressed = hits.clone();
                    }
                    self.hovered = hits;
                }
                t.extend(&self.layers);
                t.retain(|&i| !self.placed[i].inert);
                // Topmost first: layers, then descendants and later siblings.
                t.sort_unstable_by_key(|&i| std::cmp::Reverse(self.rank[i]));
                t.dedup();
                t
            }
        };
        let mut sorted = targets.clone();
        sorted.sort_unstable();
        let widgets = walk_to(&self.root, &self.ends, &sorted);
        let widget = |i: usize| widgets[sorted.binary_search(&i).unwrap()];
        let mut send = |i: usize, ev: &Event, states: &mut HashMap<u64, State>| {
            let (id, p) = (self.ids[i], self.placed[i]);
            let mut cx = EventCx {
                now,
                rect: p.rect,
                clip: p.clip,
                content: p.content,
                focused: self.focused == Some(id),
                shift: self.mods.shift_key(),
                state: states.entry(id).or_default(),
                text: &self.text,
                updates: &mut updates,
                copied: &mut copied,
                capture: false,
                focus: None,
                stop: false,
                redraw: false,
            };
            widget(i).event(ev, &mut cx);
            redraw |= cx.redraw;
            if let Some(k) = cx.focus {
                focus = Some((id, k));
            }
            // A press taken by a capture never reached what it would have focused.
            if cx.capture {
                focus = None;
            }
            (cx.capture, cx.stop)
        };
        let mut stopped = false;
        for &i in &targets {
            let (capture, stop) = send(i, &ev, &mut self.states);
            stopped = stop;
            if capture && self.captured.is_none() {
                self.captured = Some(self.ids[i]);
                // Only nodes that got pointer events can have a gesture to drop.
                for &j in targets.iter().filter(|&&j| j != i) {
                    send(j, &Event::Cancel, &mut self.states);
                }
                break;
            }
            if stop {
                break;
            }
        }
        if matches!(ev, Event::PointerUp { .. }) {
            self.captured = None;
            self.pressed.clear();
        }
        if matches!(ev, Event::Leave | Event::Cancel) {
            self.hovered.clear();
            self.pressed.clear();
        }
        if let Some(t) = copied {
            self.clipboard.set(t);
        }
        // A tap that no widget claims for focus blurs the focused one.
        if matches!(ev, Event::PointerDown { .. }) {
            self.focus_visible = false;
            redraw |= self.set_focus(focus.map(|(id, k)| (id, Some(k))));
        }

        let rebuild = !updates.is_empty();
        if rebuild {
            for (id, f) in updates {
                f(self.states.entry(id).or_default());
            }
            self.rebuild();
            self.drive();
        }
        if rebuild {
            self.redraw();
        } else if redraw {
            self.reposition();
        }
        stopped
    }

    fn key_pressed(&mut self, key: &WKey, text: Option<&str>) {
        let command = if cfg!(target_os = "macos") {
            self.mods.super_key()
        } else {
            self.mods.control_key()
        };
        let shortcut =
            |k: &str| command && matches!(key, WKey::Character(c) if c.eq_ignore_ascii_case(k));
        if let WKey::Named(NamedKey::Tab) = key {
            return self.tab(!self.mods.shift_key());
        }
        let k = match key {
            WKey::Named(NamedKey::Backspace) => Some(Key::Backspace),
            WKey::Named(NamedKey::Delete) => Some(Key::Delete),
            WKey::Named(NamedKey::ArrowLeft) => Some(Key::Left),
            WKey::Named(NamedKey::ArrowRight) => Some(Key::Right),
            WKey::Named(NamedKey::ArrowUp) => Some(Key::Up),
            WKey::Named(NamedKey::ArrowDown) => Some(Key::Down),
            WKey::Named(NamedKey::Enter) => Some(Key::Enter),
            WKey::Named(NamedKey::PageUp) => Some(Key::PageUp),
            WKey::Named(NamedKey::PageDown) => Some(Key::PageDown),
            WKey::Named(NamedKey::Home) => Some(Key::Home),
            WKey::Named(NamedKey::End) => Some(Key::End),
            WKey::Named(NamedKey::Escape) => {
                self.dispatch(Event::Back);
                return;
            }
            _ if shortcut("a") => Some(Key::SelectAll),
            _ if shortcut("c") => Some(Key::Copy),
            _ if shortcut("x") => Some(Key::Cut),
            _ => None,
        };
        let char_key = || {
            let mut cs = text?.chars();
            cs.next()
                .filter(|c| !c.is_control() && cs.next().is_none() && !self.typing)
        };
        if let Some(k) = k {
            self.dispatch(Event::Key(k));
        } else if let Some(c) = char_key() {
            self.dispatch(Event::Key(Key::Char(c)));
        } else if shortcut("v") {
            // Pasting is typing the clipboard's text.
            if self.focused.is_some()
                && let Some(t) = self.clipboard.get().map(|t| printable(&t))
                && !t.is_empty()
            {
                self.dispatch(Event::Text(t));
            }
        } else if !(self.mods.control_key() && !self.mods.alt_key() || self.mods.super_key())
            && let Some(t) = text
        {
            let t = printable(t);
            if !t.is_empty() {
                self.dispatch(Event::Text(t));
            }
        }
    }

    /// Moves keyboard focus to the next (or previous) visible focusable widget, in tree order.
    // ponytail: every visible widget, also under an open dialog; trap focus in the top layer if that matters.
    fn tab(&mut self, forward: bool) {
        if self.ids.len() != self.placed.len() {
            return;
        }
        let nodes = walk(&self.root, &self.ids);
        let stops: Vec<(u64, Option<Keyboard>)> = nodes
            .iter()
            .zip(&self.placed)
            .filter_map(|(n, p)| {
                let f = n.w.focus()?;
                let seen = p.rect.intersect(&p.clip);
                (seen.w > 0.0 && seen.h > 0.0).then_some((n.id, f.keyboard))
            })
            .collect();
        let n = stops.len();
        if n == 0 {
            return;
        }
        let at = self
            .focused
            .and_then(|id| stops.iter().position(|s| s.0 == id));
        let next = match (at, forward) {
            (Some(i), true) => (i + 1) % n,
            (Some(i), false) => (i + n - 1) % n,
            (None, true) => 0,
            (None, false) => n - 1,
        };
        self.focus_visible = true;
        self.set_focus(Some(stops[next]));
        self.reposition();
    }

    /// A finger's touch, logical px. Two fingers move one pointer with their
    /// midpoint and send [`Event::Pinch`]; a third is ignored.
    fn touch(&mut self, id: u64, phase: TouchPhase, x: f32, y: f32) {
        let i = self.fingers.iter().position(|f| f.0 == id);
        match (phase, i) {
            (TouchPhase::Started, None) if self.fingers.is_empty() => {
                self.fingers.push((id, (x, y)));
                self.finger_shift = (0.0, 0.0);
                self.dispatch(Event::PointerDown { x, y });
            }
            (TouchPhase::Started, None) if self.fingers.len() == 1 => {
                let p = self.finger_pointer();
                self.fingers.push((id, (x, y)));
                self.keep_pointer(p);
            }
            (TouchPhase::Moved, Some(i)) => {
                let before = self.spread();
                self.fingers[i].1 = (x, y);
                let (px, py) = self.finger_pointer();
                self.dispatch(Event::PointerMove { x: px, y: py });
                if let (Some(a), Some(b)) = (before, self.spread())
                    && a > 0.0
                {
                    let (mx, my) = self.midpoint();
                    let scale = b / a;
                    self.dispatch(Event::Pinch {
                        x: mx,
                        y: my,
                        scale,
                    });
                }
            }
            (TouchPhase::Ended, Some(i)) if self.fingers.len() == 2 => {
                let p = self.finger_pointer();
                self.fingers.remove(i);
                self.keep_pointer(p);
            }
            (TouchPhase::Ended, Some(_)) => {
                let (x, y) = self.finger_pointer();
                self.fingers.clear();
                self.dispatch(Event::PointerUp { x, y });
                self.dispatch(Event::Leave);
            }
            (TouchPhase::Cancelled, Some(_)) => {
                self.fingers.clear();
                self.captured = None;
                self.dispatch(Event::Cancel);
                self.dispatch(Event::Leave);
            }
            _ => {}
        }
    }

    fn midpoint(&self) -> (f32, f32) {
        let n = self.fingers.len().max(1) as f32;
        let (x, y) = self
            .fingers
            .iter()
            .fold((0.0, 0.0), |a, f| (a.0 + f.1.0, a.1 + f.1.1));
        (x / n, y / n)
    }

    fn finger_pointer(&self) -> (f32, f32) {
        let (x, y) = self.midpoint();
        (x + self.finger_shift.0, y + self.finger_shift.1)
    }

    fn keep_pointer(&mut self, p: (f32, f32)) {
        let (x, y) = self.midpoint();
        self.finger_shift = (p.0 - x, p.1 - y);
    }

    /// Distance between two fingers down.
    fn spread(&self) -> Option<f32> {
        let [(_, a), (_, b)] = self.fingers[..] else {
            return None;
        };
        Some((a.0 - b.0).hypot(a.1 - b.1))
    }

    /// Returns whether focus changed.
    fn set_focus(&mut self, to: Option<(u64, Option<Keyboard>)>) -> bool {
        let id = to.map(|(id, _)| id);
        let keyboard = to.and_then(|(_, k)| k);
        let changed = self.focused != id;
        self.focused = id;
        self.typing = keyboard.is_some();
        // ponytail: IME only drives the Android soft keyboard; desktop composition (CJK) needs Ime::Preedit handling.
        // Tapping the focused input again brings back a keyboard the user dismissed.
        if changed || id.is_some() {
            #[cfg(test)]
            self.ime_requests.push(keyboard);
            if let Some(r) = &self.renderer {
                r.window().set_ime(keyboard);
            }
        }
        changed
    }

    fn paint(&mut self) {
        if let Some(r) = &mut self.renderer {
            r.set_hdr(self.app.hdr());
        }
        let zoom = self.app.zoom();
        if zoom != self.zoom
            && let Some(r) = &mut self.renderer
        {
            self.zoom = zoom;
            r.set_zoom(zoom);
            let (w, h) = r.window().size();
            self.resized(w, h);
        }
        let start = Instant::now();
        let mut frame = false;
        let (scene, spans) = self.scene(&mut frame);
        self.rebuild_if_due();
        // Empty when nothing changed: the retained frame is reused as is.
        let damage = self
            .prev
            .as_ref()
            .map(|(ps, pn)| damage(ps, pn, &scene, &spans).unwrap_or_default());
        self.next_frame = None;
        if let Some(r) = &mut self.renderer {
            match r.render(&scene, &mut self.text, damage) {
                // Canvas untouched: keep diffing against what it actually holds.
                Outcome::Failed => return,
                Outcome::Idle if frame && !self.occluded => {
                    let mhz = r.window().refresh_mhz();
                    let interval = Duration::from_secs_f64(1000.0 / mhz.unwrap_or(60_000) as f64);
                    self.next_frame = Some(Instant::now() + interval);
                }
                Outcome::Idle => {}
                Outcome::Presented(waited) => {
                    self.stats.frame(
                        start.elapsed().saturating_sub(waited),
                        r.gpu_ms(),
                        scene.len(),
                    );
                    if frame {
                        r.window().request_redraw();
                    }
                }
            }
        }
        if !frame
            && !self.occluded
            && let Some(t) = self.wake
        {
            self.next_frame = Some(t);
        }
        self.prev = Some((scene, spans));
    }

    fn scene(&mut self, frame: &mut bool) -> (Scene, Spans) {
        let nodes = walk(&self.root, &self.ids);
        let now = self.now();
        if std::mem::take(&mut self.place) && nodes.len() == self.measured.len() {
            self.placed = place(&nodes, &self.measured, &mut self.states, now);
        }
        self.wake = None;
        let mut scene = Scene::default();
        // Partial redraws load the previous frame, so damage needs its own background.
        let (w, h) = self.viewport;
        let all = Rect::new(0.0, 0.0, w, h);
        scene.shape(
            all,
            0.0,
            self.app.background(),
            0.0,
            Color::TRANSPARENT,
            all,
        );
        self.text.begin_frame();
        let mut spans = Vec::with_capacity(nodes.len());
        let app_theme = self.app.theme();
        let mut themes: Vec<&crate::Theme> = Vec::with_capacity(nodes.len());
        for n in &nodes {
            let inherited = n.parent.map_or(&app_theme, |p| themes[p]);
            let provided = n.w.provide().and_then(|v| v.downcast_ref());
            themes.push(provided.unwrap_or(inherited));
        }
        for &i in &self.order {
            let (n, p) = (&nodes[i], &self.placed[i]);
            let start = scene.len();
            if culled(p.rect, p.clip) {
                spans.push((n.id, start..start));
                continue;
            }
            n.w.paint(&mut PaintCx {
                now,
                rect: p.rect,
                clip: p.clip,
                focused: self.focused == Some(n.id),
                theme: themes[i],
                state: self.states.entry(n.id).or_default(),
                scene: &mut scene,
                text: &mut self.text,
                frame: &mut *frame,
                wake: &mut self.wake,
                place: &mut self.place,
                rebuild: &mut self.rebuild_due,
            });
            spans.push((n.id, start..scene.len()));
        }
        let to = self.focused.filter(|_| self.focus_visible).and_then(|id| {
            let i = self.ids.iter().position(|&n| n == id)?;
            let f = nodes[i].w.focus()?;
            let p = &self.placed[i];
            Some((
                focus::Outline {
                    rect: p.rect,
                    radius: f.radius,
                },
                p.clip,
            ))
        });
        let start = scene.len();
        let (outline, clip) = (to.map(|t| t.0), to.map_or(all, |t| t.1));
        let accent = app_theme.accent;
        *frame |= self
            .ring
            .paint(self.focused, outline, accent, clip, now, &mut scene);
        // Its own id, so damage covers where the ring was and where it is.
        spans.push((u64::MAX, start..scene.len()));
        self.text.end_frame();
        (scene, spans)
    }
}

/// How far past its box a widget may draw, e.g. a shadow's blur and offset.
const OVERDRAW: f32 = 48.0;

/// Whether nothing `rect` paints can show through `clip`, so its paint is skipped.
// ponytail: fixed overdraw margin; a per-widget paint bound if something draws farther out.
fn culled(rect: Rect, clip: Rect) -> bool {
    let m = OVERDRAW;
    let grown = Rect::new(rect.x - m, rect.y - m, rect.w + 2.0 * m, rect.h + 2.0 * m);
    let v = grown.intersect(&clip);
    v.w <= 0.0 || v.h <= 0.0
}

fn pointer_at(ev: &Event) -> Option<(f32, f32)> {
    match *ev {
        Event::PointerDown { x, y }
        | Event::PointerMove { x, y }
        | Event::PointerUp { x, y }
        | Event::Wheel { x, y, .. }
        | Event::Pinch { x, y, .. } => Some((x, y)),
        _ => None,
    }
}

fn printable(t: &str) -> String {
    t.chars().filter(|c| !c.is_control()).collect()
}

struct Flat {
    ids: Vec<u64>,
    order: Vec<usize>,
    ends: Vec<usize>,
    rank: Vec<usize>,
    layers: Vec<usize>,
}

fn flat_ids(root: &Element, states: &mut HashMap<u64, State>, tasks: &mut Tasks) -> Flat {
    let nodes = flatten(root, states, tasks);
    let order = order(&nodes);
    let mut rank = vec![0; nodes.len()];
    for (r, &i) in order.iter().enumerate() {
        rank[i] = r;
    }
    Flat {
        ids: nodes.iter().map(|n| n.id).collect(),
        ends: nodes.iter().map(|n| n.end).collect(),
        layers: (0..nodes.len())
            .filter(|&i| nodes[i].w.layer().is_some())
            .collect(),
        rank,
        order,
    }
}