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
//! The application: the single entry point that runs a frame from reactive
//! effects to damage.
//!
//! An [`App`] owns the reactive runtime, the widget tree, the update queue and
//! the damage for one window. [`App::frame`] runs the whole pipeline in order,
//! so a window, a headless test and a benchmark all drive the same code.
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use web_time::Instant;
use crate::damage::DamageAccumulator;
use crate::element::{IntoElement, UpdateQueue, mount};
use crate::geometry::{Color, PixelRect, Point, Rect, Size};
use crate::input::{InputEvent, Modifiers};
use crate::paint::DisplayList;
use crate::reactive::runtime::Scope;
use crate::reactive::{self, Owner, RenderEffect};
use crate::semantics::{A11yChanges, SemanticsNode};
use crate::theme::Theme;
use crate::timer::{self, Clock, TimerBook};
use crate::tree::{WidgetId, WidgetTree};
/// How many flush and apply rounds a frame runs before it reports a cycle.
const MAX_FLUSH_ROUNDS: u32 = 16;
/// How much of the surface a frame repaints.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum RepaintMode {
/// Repaint only the pixels that changed since the previous frame.
#[default]
Damage,
/// Repaint the whole surface on every frame.
Full,
}
/// The settings an [`App`] starts with.
#[derive(Clone, Debug)]
pub struct AppConfig {
/// The size of the window in logical pixels.
pub viewport: Size,
/// The number of physical pixels per logical pixel.
pub scale: f32,
/// The color a renderer fills the surface with before it replays the
/// display list.
pub clear_color: Color,
/// How much of the surface each frame repaints.
pub repaint: RepaintMode,
}
/// What a renderer draws for one frame.
#[derive(Debug)]
pub struct FrameOutput<'a> {
/// The operations to replay, in paint order.
pub list: &'a DisplayList,
/// The physical rectangles that changed since the previous frame.
pub damage: &'a [PixelRect],
/// Whether the frame repaints the whole surface.
pub full: bool,
/// The color the surface starts from, before `list` is replayed.
pub clear_color: Color,
/// The number of physical pixels per logical pixel.
pub scale: f32,
}
/// How long each step of the last frame took and how much work it did.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FrameStats {
/// Time spent running reactive effects and applying their updates.
pub flush: Duration,
/// Time spent in the layout pass.
pub layout: Duration,
/// Time spent in the paint pass.
pub paint: Duration,
/// Time spent rebuilding the display list.
pub list: Duration,
/// Time spent converting and merging the damage.
pub damage: Duration,
/// Whether the layout pass ran the layout engine.
pub layout_ran: bool,
/// How many nodes the paint pass regenerated.
pub nodes_painted: u32,
/// How many physical rectangles the damage holds.
pub damage_rects: u32,
/// How many physical pixels the damage covers, counting an overlap once per
/// rectangle.
pub damage_pixels: u64,
/// How many physical pixels the damage covered before the merge step
/// collapsed the rectangles, counting an overlap once per rectangle.
///
/// Together with [`FrameStats::damage_pixels`] this shows what the merge
/// step traded: rectangles for area.
pub damage_pixels_before_merge: u64,
/// How many flush and apply rounds the frame ran.
pub flush_rounds: u32,
}
/// One window's widget tree, reactive runtime and frame pipeline.
///
/// The app owns everything the frame touches. [`App::frame`] is the only method
/// that mutates the tree, and it does so in one fixed order, so an effect never
/// observes a half-applied frame.
///
/// # Examples
///
/// ```
/// use smudge_core::app::{App, AppConfig, RepaintMode};
/// use smudge_core::geometry::{Color, Size};
/// use smudge_core::style::px;
/// use smudge_core::widget::panel;
///
/// let mut app = App::new(
/// AppConfig {
/// viewport: Size {
/// width: 320.0,
/// height: 200.0,
/// },
/// scale: 1.0,
/// clear_color: Color::WHITE,
/// repaint: RepaintMode::Damage,
/// },
/// || panel().width(px(120.0)).height(px(40.0)).background(Color::BLACK),
/// );
///
/// let full = app.frame().full;
/// assert!(full, "the first frame repaints the whole surface");
/// assert_eq!(app.stats().damage_rects, 1);
///
/// let empty = app.frame().damage.is_empty();
/// assert!(empty, "a frame with no changes damages nothing");
/// ```
pub struct App {
/// The widget tree the frame lays out and paints.
tree: WidgetTree,
/// The updates that reactive effects have queued.
queue: UpdateQueue,
/// The damage collected for the frame that is running.
damage: DamageAccumulator,
/// The display list of the last frame that built one.
list: DisplayList,
/// The settings the frame uses.
config: AppConfig,
/// The pointer position the last pointer event reported, in logical
/// pixels.
pointer: Point,
/// The keyboard modifiers the last key event reported.
modifiers: Modifiers,
/// The timings and counts of the last frame.
stats: FrameStats,
/// The callback that runs at the start of every frame.
tick: Option<Box<dyn FnMut(Instant)>>,
/// The timers of the app and the clock they read.
timers: Rc<RefCell<TimerBook>>,
/// The channels other threads send values through, and the book the
/// frame drains them from.
channels: Rc<RefCell<crate::channel::ChannelBook>>,
/// The window commands handlers queue and the state the window reports,
/// shared with every owner of the tree.
window: Rc<RefCell<crate::window::WindowBook>>,
/// Whether the next frame repaints the whole surface.
force_full: bool,
/// The owner that the build closure, the signals it created, every
/// node's owner and the theme bindings live under.
///
/// Held so those stay alive for as long as the app does, and so the
/// cleanup at the end stops the theme bindings.
_root: Owner,
/// The clipboard the app's handlers copy and paste through, when one is
/// installed.
clipboard: Option<crate::clipboard::Slot>,
}
impl App {
/// Creates an app and mounts the element that `build` returns.
///
/// Installs the reactive runtime on the calling thread, then runs `build`
/// and mounts its element inside an owner that lives as long as the app, so
/// every binding sees the context that `build` provides. The mounted tree
/// is laid out and painted by the first call to [`App::frame`], which
/// repaints the whole surface.
///
/// Timers read the operating system's clock. Use [`App::with_clock`] to
/// run them on another one.
pub fn new<E: IntoElement>(config: AppConfig, build: impl FnOnce() -> E) -> App {
App::with_clock(config, Clock::system(), build)
}
/// Creates an app like [`App::new`] whose timers and tick callback read
/// `clock`.
///
/// The clock is in place before `build` runs, so a timer that `build`
/// creates is scheduled on it too. A test passes a
/// [`VirtualClock`](crate::timer::VirtualClock) and advances it by hand.
pub fn with_clock<E: IntoElement>(
config: AppConfig,
clock: Clock,
build: impl FnOnce() -> E,
) -> App {
reactive::init();
let root = Owner::new();
let timers = Rc::new(RefCell::new(TimerBook::new(clock)));
root.data().timer_book.replace(Some(Rc::downgrade(&timers)));
let channels = Rc::new(RefCell::new(crate::channel::ChannelBook::default()));
root.data()
.channel_book
.replace(Some(Rc::downgrade(&channels)));
let window = crate::window::new_book(&root);
root.data()
.window_book
.replace(Some(Rc::downgrade(&window)));
let mut tree = WidgetTree::new();
tree.set_scale(config.scale);
let queue = UpdateQueue::default();
root.with(|| mount(build().into_any(), &mut tree, &queue, None));
App {
tree,
queue,
damage: DamageAccumulator::new(),
list: DisplayList::new(),
config,
pointer: Point::default(),
modifiers: Modifiers::default(),
stats: FrameStats::default(),
tick: None,
timers,
channels,
window,
force_full: true,
_root: root,
clipboard: None,
}
}
/// Changes the viewport and the scale, and makes the next frame repaint the
/// whole surface.
///
/// The viewport is in logical pixels and the scale is the number of
/// physical pixels per logical pixel. A viewport that differs from the last
/// one also runs the layout pass again.
pub fn set_viewport(&mut self, viewport: Size, scale: f32) {
self.config.viewport = viewport;
self.config.scale = scale;
self.tree.set_scale(scale);
self.force_full = true;
}
/// Changes how much of the surface each frame repaints, and makes the next
/// frame repaint the whole surface.
pub fn set_repaint_mode(&mut self, mode: RepaintMode) {
self.config.repaint = mode;
self.force_full = true;
}
/// Replaces the theme that style values which name a token resolve
/// against, and marks for repainting every node whose last paint looked
/// up a token, whether through its style or inside its widget's own
/// `paint`.
///
/// The tree starts on [`Theme::light`]. Nodes whose paint resolves no
/// value from the theme paint the same pixels under any theme and are not
/// repainted, so a switch damages only what the switch can change. An
/// equal theme marks nothing.
///
/// ```
/// use smudge_core::app::{App, AppConfig, RepaintMode};
/// use smudge_core::geometry::{Color, Size};
/// use smudge_core::style::px;
/// use smudge_core::theme::{ColorToken, Theme};
/// use smudge_core::widget::panel;
///
/// let mut app = App::new(
/// AppConfig {
/// viewport: Size {
/// width: 120.0,
/// height: 80.0,
/// },
/// scale: 1.0,
/// clear_color: Color::WHITE,
/// repaint: RepaintMode::Damage,
/// },
/// || panel().width(px(40.0)).height(px(20.0)).background(ColorToken::SURFACE),
/// );
/// app.frame();
///
/// app.set_theme(Theme::dark());
/// app.frame();
/// assert_eq!(app.stats().nodes_painted, 1);
/// ```
pub fn set_theme(&mut self, theme: Theme) {
self.tree.set_theme(theme);
}
/// Installs one effect that keeps the theme current.
///
/// The closure is read when it is installed and again whenever a signal it
/// reads changes; each run hands the theme it returns to
/// [`App::set_theme`] through the update queue, so the change lands inside
/// a frame like any other reactive update. Pass a closure that builds the
/// theme from a signal to switch the theme reactively:
///
/// ```
/// use smudge_core::app::{App, AppConfig, RepaintMode};
/// use smudge_core::geometry::{Color, Size};
/// use smudge_core::reactive::{prelude::*, signal_local};
/// use smudge_core::style::px;
/// use smudge_core::theme::{ColorToken, Theme};
/// use smudge_core::widget::panel;
///
/// let (dark, set_dark) = signal_local(false);
/// let mut app = App::new(
/// AppConfig {
/// viewport: Size {
/// width: 120.0,
/// height: 80.0,
/// },
/// scale: 1.0,
/// clear_color: Color::WHITE,
/// repaint: RepaintMode::Damage,
/// },
/// || panel().width(px(40.0)).height(px(20.0)).background(ColorToken::SURFACE),
/// );
/// app.bind_theme(move || if dark.get() { Theme::dark() } else { Theme::light() });
/// app.frame();
///
/// set_dark.set(true);
/// app.frame();
/// assert_eq!(app.stats().nodes_painted, 1);
/// ```
///
/// The binding runs under the app's root owner, so it reports its wakes
/// to the callback set with [`App::set_wake_callback`] and stops when the
/// app is dropped.
pub fn bind_theme(&mut self, get: impl Fn() -> Theme + 'static) {
let queue = self.queue.clone();
self._root.with(|| {
RenderEffect::new(move || {
let theme = get();
let queue = queue.clone();
queue.push(Box::new(move |tree| tree.set_theme(theme)));
});
});
}
/// Installs the clipboard the app's widgets copy and paste through.
///
/// Until one is installed, a clipboard read or write finds nothing, so
/// cut, copy and paste keys do nothing. The windowing layer installs one
/// that reaches the system clipboard; a test installs a
/// [`MemoryClipboard`](crate::clipboard::MemoryClipboard) and keeps a
/// clone to seed or read the text. Installing again replaces the
/// previous clipboard.
pub fn set_clipboard(&mut self, clipboard: Box<dyn crate::clipboard::Clipboard>) {
self.clipboard = Some(crate::clipboard::install(self._root.data(), clipboard));
}
/// Sets the callback that a wake in this app's tree runs to request a
/// redraw.
///
/// A write that queues this app's first effect since the last flush runs
/// the callback once, so the platform learns that the next frame has work
/// to do. Every binding of this app reports its wake here, and an app on
/// another part of the thread neither sees this app's wakes nor hides
/// them. A write made while [`App::frame`] runs its timers, its tick and
/// its updates runs no callback, because the frame runs the effects it
/// wakes before it lays out; a write made later in the frame, while a
/// widget paints, does. See
/// [`set_wake_callback`](crate::reactive::set_wake_callback) for the
/// exact rules.
pub fn set_wake_callback(&self, callback: impl Fn() + 'static) {
self._root.set_wake_callback(callback);
}
/// Sets the callback that a message from another thread runs to ask for
/// the frame that applies it.
///
/// The platform installs one that posts a wake event to the event loop,
/// so a thread that sends does not have to poll and the window does not
/// wake for anything else. A headless app needs none: its next
/// [`App::frame`] call finds the values on its own. Channels created
/// before this call get the waker too, and later ones start with it.
pub fn set_remote_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
crate::channel::install_waker(&self.channels, std::sync::Arc::new(waker));
}
/// Ends the held press as if it had been cancelled, without running the
/// pressed node's `on_press`.
///
/// The windowing layer calls this when the window system takes over the
/// press, as it does for an interactive move or resize: the release of
/// that press never reaches the app, so without this the press would stay
/// captured and hover would stop following the pointer. The pressed node
/// loses its pressed state and hears `on_pointer_up`, so a drag it started
/// ends. A window system may still refuse the gesture after the call that
/// starts it succeeded, and then the release arrives after all: a primary
/// release that comes with no press held, before the next primary press,
/// reaches no handler. With no press held this does nothing.
pub fn release_press(&mut self) {
self.tree.release_press();
}
/// Takes every window command queued so far, in the order the handlers
/// queued them.
///
/// The windowing layer calls this after it hands an input event over, so
/// a command starts its move or resize while the press that queued it is
/// still being handled. A headless application has no windowing layer and
/// no need to take the commands, so they stay queued for a test to
/// inspect. Taking them empties the queue.
pub fn take_window_commands(&mut self) -> Vec<crate::window::WindowCommand> {
crate::window::take_commands(&self.window)
}
/// Replaces the window state the application's
/// [`maximized`](crate::window::maximized) reads.
///
/// The windowing layer calls this when the window's maximized state may
/// have changed. An equal report changes nothing, so a binding that reads
/// the state reruns only on a real change.
pub fn set_window_state(&mut self, state: crate::window::WindowState) {
crate::window::set_state(&self.window, state);
}
/// Returns the cursor the pointer should show.
///
/// This is the cursor of the deepest enabled node under the pointer that
/// set one with the [`cursor`](crate::element::Element::cursor) builder,
/// or [`Cursor::Default`](crate::window::Cursor::Default) when no node
/// under the pointer sets one or the pointer left the window. While a
/// press is held, the walk starts at the pressed node instead. The
/// windowing layer reads it after every input event and every frame and
/// shows it on the window.
pub fn cursor(&self) -> crate::window::Cursor {
self.tree.cursor()
}
/// Sets a callback that runs once at the start of every frame with the
/// current time.
///
/// The time comes from the app's [`Clock`], the same one its timers
/// read, so a test that runs the app on a virtual clock drives both.
pub fn set_tick(&mut self, tick: impl FnMut(Instant) + 'static) {
self.tick = Some(Box::new(tick));
}
/// Returns the current time of the app's clock.
pub fn now(&self) -> Instant {
self.timers.borrow().clock.now()
}
/// Returns the earliest time a timer fires at, or `None` when none is
/// scheduled.
///
/// A platform that has no tick callback waits until this deadline, so a
/// pending timer wakes the window when it comes due instead of the
/// window polling.
pub fn next_deadline(&self) -> Option<Instant> {
self.timers.borrow().next_deadline()
}
/// Runs the timers that are due on the app's clock, outside a frame.
///
/// A timer that writes a signal wakes the app through the callback set
/// with [`App::set_wake_callback`], like any write between frames, and a
/// timer that changes nothing asks for nothing. A platform calls this
/// when [`App::next_deadline`] passes, so a due timer costs a frame only
/// when it has something to show. [`App::frame`] runs due timers itself
/// as well, so a caller that draws every frame needs no call.
pub fn run_due_timers(&mut self) {
timer::fire_due(&self.timers);
}
/// Returns whether a frame tick callback is set.
pub fn has_tick(&self) -> bool {
self.tick.is_some()
}
/// Returns whether an event left work that only a frame can finish.
///
/// An input event can change how the tree looks without writing a signal,
/// for example by hovering a node with a hover style, so the reactive wake
/// callback never hears of it. A message from another thread also leaves
/// such work: the values its channel queues are the frame's to deliver.
/// A platform calls this after handing events over and asks for a frame
/// when it is `true`. Most pointer moves change
/// nothing, and asking for a frame every time would present the window
/// for nothing.
pub fn needs_frame(&self) -> bool {
self.tree.has_pending_work() || crate::channel::has_pending(&self.channels)
}
/// Handles one input event between frames.
///
/// The pointer events are routed to the tree: a move moves the hovered
/// chain, a primary press captures the node under the pointer and focuses
/// it when it can take the focus, and a release runs the captured node's
/// `on_press` when it happens over it. A press elsewhere clears the focus,
/// except while a focus trap is mounted and the press lands outside it,
/// and any press turns the keyboard navigation mode off. A wheel scroll
/// goes to the deepest node in the hovered chain that has a wheel handler.
/// Key events are routed to the focused node and bubble to its ancestors
/// until a handler takes them, starting at the root when nothing anchors
/// the key and at the active focus trap when the key would otherwise
/// start outside it, and an unhandled Tab or Shift+Tab moves the focus, staying
/// inside the active focus trap when one is mounted. Handlers run at
/// once, inside their node's owner, and a handler that writes a signal
/// makes the change visible with the next call to [`App::frame`]. The app
/// also records the pointer position from pointer events and the keyboard
/// modifiers from key and modifiers events.
pub fn handle_event(&mut self, event: InputEvent) {
match event {
InputEvent::PointerMoved { position } => {
self.pointer = position;
self.tree.pointer_move(position);
}
InputEvent::PointerDown { position, button } => {
self.pointer = position;
self.tree.pointer_down(position, button);
}
InputEvent::PointerUp { position, button } => {
self.pointer = position;
self.tree.pointer_up(position, button);
}
InputEvent::PointerLeft => self.tree.pointer_left(),
InputEvent::Wheel { delta } => self.tree.wheel(delta),
InputEvent::Key(key) => {
self.tree.key(&key);
self.modifiers = key.modifiers;
}
InputEvent::ModifiersChanged(modifiers) => self.modifiers = modifiers,
InputEvent::ImeCommit { text } => self.tree.ime_commit(&text),
InputEvent::ImePreedit { text, cursor } => self.tree.ime_preedit(&text, cursor),
InputEvent::WindowFocus(focused) => {
// A window that loses the input focus drops its input method
// context, so a composition must not outlive the focus. The
// empty preedit is the clear.
if !focused {
self.tree.ime_preedit("", None);
}
}
}
}
/// Returns the pointer position the last pointer event reported, in
/// logical pixels.
///
/// The position starts at the origin and moves only when a pointer event
/// carries a position, so it lags the real pointer until the first event
/// arrives.
pub fn pointer_position(&self) -> Point {
self.pointer
}
/// Returns the keyboard modifiers the last key or modifiers event
/// reported.
///
/// They start at none and change only when one of those events arrives.
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
/// Returns the root owner, for the crate's own tests.
#[cfg(test)]
pub(crate) fn root(&self) -> &Owner {
&self._root
}
/// Returns the node that holds the keyboard focus, when one does.
///
/// A press on a focusable node focuses it, a press elsewhere clears the
/// focus, and Tab moves it. While a focus trap is mounted, a press
/// outside the trap leaves the focus where it is, and Tab moves it within
/// the trap only. Removing the focused node clears the focus, and
/// removing or hiding a trap returns the focus to the node that held it
/// when the trap mounted or last showed.
pub fn focused(&self) -> Option<WidgetId> {
self.tree.focused()
}
/// Returns whether the keyboard navigation mode is on.
///
/// A Tab or an arrow key turns the mode on and a pointer press turns it
/// off, so a focus ring can draw for keyboard users alone. A node carries
/// the keyboard focus bit only while it holds the focus and this mode is
/// on.
pub fn keyboard_navigation(&self) -> bool {
self.tree.keyboard_nav()
}
/// Returns the area the focused widget reports to the input method, in
/// window coordinates, when it reports one.
///
/// This is [`None`] while no widget reports an area, which is the default,
/// while nothing is focused, and while the focused node sits outside an
/// active focus trap. A window presents the area to the
/// operating system so the input method can anchor its candidate window to
/// it.
pub fn ime_area(&self) -> Option<Rect> {
self.tree.ime_area()
}
/// Returns the surface size in physical pixels.
///
/// This is the viewport multiplied by the scale and rounded to the nearest
/// pixel. A viewport or scale that gives a negative or NaN size gives zero
/// on that axis.
pub fn surface_size(&self) -> (u32, u32) {
let width = (self.config.viewport.width * self.config.scale).round();
let height = (self.config.viewport.height * self.config.scale).round();
(width.max(0.0) as u32, height.max(0.0) as u32)
}
/// Runs one frame and returns what the renderer has to draw.
///
/// The frame runs these steps in order:
///
/// 1. The values other threads sent through the app's channels: each
/// handler runs inside the owner that created its channel, delivering
/// at most what the queue held when the drain reached it.
/// 2. The timers that are due on the app's clock, then the tick callback,
/// when one is set.
/// 3. Reactive effects and the updates they queue, until neither has work
/// left. A signal write therefore lands before layout, including one a
/// channel handler or a timer made at the start of the frame.
/// 4. The layout pass, which runs the layout engine only when a node needs
/// it.
/// 5. The paint pass, which regenerates the operations of the nodes that
/// changed and reports their old and new bounds as damage.
/// 6. The display list, rebuilt only when something may have changed.
/// 7. Damage conversion and merging, then the output.
///
/// The output borrows the app until it is dropped, so read [`App::stats`]
/// either before the output is kept or after it is let go.
///
/// # Panics
///
/// Panics in debug builds when the update queue does not settle within a
/// fixed number of rounds, which means applying updates keeps waking a
/// binding: a mounted child or a widget's bind function writes a signal
/// that leads back to the same update. Release builds carry on with the
/// state they reached.
///
/// Also panics in debug builds when one binding runs too many times in one
/// flush, which means it writes a signal that wakes it again, directly or
/// through another binding. A release build never returns from that frame.
pub fn frame(&mut self) -> FrameOutput<'_> {
// The frame runs every effect its channels, its timers, its tick and
// its updates wake before it lays out, so reporting those wakes would
// only ask the platform for a second frame with nothing to do.
let quiet = QuietWakes::enter(&self._root);
crate::channel::drain_all(&self.channels);
timer::fire_due(&self.timers);
let now = self.now();
if let Some(tick) = &mut self.tick {
tick(now);
}
let flush_start = Instant::now();
let mut rounds = 0u32;
let mut settled = false;
loop {
rounds += 1;
let flushed = reactive::flush();
let applied = self.queue.apply(&mut self.tree);
if !flushed && !applied {
settled = true;
break;
}
debug_assert!(
rounds < MAX_FLUSH_ROUNDS,
"the update queue did not settle in {MAX_FLUSH_ROUNDS} rounds, \
so applying updates keeps waking a binding in a cycle, for \
example through a mounted child or a widget's bind function"
);
if rounds >= MAX_FLUSH_ROUNDS {
break;
}
}
self.stats.flush = flush_start.elapsed();
self.stats.flush_rounds = rounds;
drop(quiet);
if !settled {
// The capped loop left work queued that no frame has run yet.
self._root.wake();
}
let layout_start = Instant::now();
self.stats.layout_ran = self.tree.layout(self.config.viewport);
self.stats.layout = layout_start.elapsed();
self.damage.clear();
let paint_start = Instant::now();
self.stats.nodes_painted = self.tree.paint(&mut self.damage);
self.stats.paint = paint_start.elapsed();
let full = self.force_full || self.config.repaint == RepaintMode::Full;
self.force_full = false;
let list_start = Instant::now();
if full || self.stats.nodes_painted > 0 || !self.damage.is_empty() {
self.tree.build_display_list(&mut self.list);
}
self.stats.list = list_start.elapsed();
if full {
self.damage.add_full();
}
let (width, height) = self.surface_size();
let damage_start = Instant::now();
let (damage, damage_pixels_before_merge) =
self.damage
.finish_measured(self.config.scale, width, height);
self.stats.damage = damage_start.elapsed();
self.stats.damage_rects = damage.len() as u32;
self.stats.damage_pixels = damage.iter().map(|rect| rect.area()).sum();
self.stats.damage_pixels_before_merge = damage_pixels_before_merge;
FrameOutput {
list: &self.list,
damage,
full,
clear_color: self.config.clear_color,
scale: self.config.scale,
}
}
/// Returns the timings and counts of the last frame.
pub fn stats(&self) -> &FrameStats {
&self.stats
}
/// Visits every visible node of the tree in paint order, for diagnostics.
///
/// `visit` receives the node's depth, with the root at zero, the full name
/// of the widget's concrete type, and the node's absolute rectangle in
/// logical pixels as the last layout pass left it. A hidden node and its
/// subtree are skipped, because they are laid out as empty and paint
/// nothing. The tree itself stays private, so this is the only way code
/// outside this crate can describe the structure of a frame.
///
/// # Examples
///
/// ```
/// use smudge_core::app::{App, AppConfig, RepaintMode};
/// use smudge_core::geometry::{Color, Size};
/// use smudge_core::style::px;
/// use smudge_core::widget::panel;
///
/// let mut app = App::new(
/// AppConfig {
/// viewport: Size {
/// width: 100.0,
/// height: 50.0,
/// },
/// scale: 1.0,
/// clear_color: Color::WHITE,
/// repaint: RepaintMode::Damage,
/// },
/// || panel().child(panel().width(px(10.0)).height(px(10.0))),
/// );
/// app.frame();
///
/// let mut depths = Vec::new();
/// app.visit_nodes(|depth, _type_name, _rect| depths.push(depth));
/// assert_eq!(depths, [0, 1]);
/// ```
pub fn visit_nodes(&self, mut visit: impl FnMut(usize, &'static str, Rect)) {
self.tree.visit_nodes(&mut visit);
}
/// Projects every visible node that reports a role, in paint order.
///
/// This is the tree an accessibility backend reads. A node is projected
/// when its element set a role or its widget reports one; the children
/// of a node without a role attach to the nearest projected ancestor.
/// A hidden node and its subtree are skipped, because they paint
/// nothing. The bounds are in logical pixels, as the last layout pass
/// left them.
pub fn semantics_nodes(&self) -> Vec<SemanticsNode> {
self.tree.semantics_nodes()
}
/// Returns the projected nodes that no projected ancestor holds, in paint
/// order.
///
/// These are the nodes an accessibility backend attaches to the root it
/// adds for the window.
pub fn semantics_roots(&self) -> Vec<WidgetId> {
self.tree.semantics_roots()
}
/// Projects one node with the children the projection gives it.
///
/// Returns [`None`] when the id is stale, when the node or an ancestor
/// is hidden, or when neither the element nor the widget reports a role
/// for it.
pub fn semantics_node(&self, id: WidgetId) -> Option<SemanticsNode> {
self.tree.semantics_node(id)
}
/// Returns whether the projection has unread changes.
///
/// A backend that only rebuilds when this returns true skips frames that
/// changed nothing projected.
pub fn has_a11y_changes(&self) -> bool {
self.tree.has_a11y_changes()
}
/// Takes the projected nodes that changed since the last call.
///
/// A change to a node the projection leaves out is reported as its
/// nearest projected ancestor, whose child list it changed, or as
/// [`A11yChanges::roots_changed`] when no ancestor projects. A repaint
/// of such a node, such as a caret's blink, changes nothing projected
/// and is not reported. Stale and
/// hidden ids drop out, and a frame that changed too much sets
/// [`A11yChanges::reset`] instead of listing every node, so a backend can
/// rebuild from scratch. Take these only when no frame is pending: a
/// node that changes again while it waits for a frame is not queued
/// twice, so changes taken before that frame miss what it does.
pub fn take_a11y_changes(&mut self) -> A11yChanges {
self.tree.take_a11y_changes()
}
/// Runs the press handler of `id`, as an accessibility action would.
///
/// This is the same path a press of Enter or Space takes, so a disabled
/// or hidden node runs nothing and `false` is returned. `true` means a
/// handler ran.
pub fn press(&mut self, id: WidgetId) -> bool {
self.tree.run_press(id)
}
/// Moves the keyboard focus to `id`, as an accessibility action would.
///
/// A node that is not focusable, or that cannot hold the focus because
/// it is disabled or hidden, is left alone and `false` is returned. A
/// node that already holds the focus keeps it and `true` is returned.
/// Unlike the autofocus request, an active focus trap does not confine
/// this one: the trap binds Tab movement and pointer presses, not an
/// explicit request that names its node.
pub fn request_focus(&mut self, id: WidgetId) -> bool {
self.tree.request_focus(id)
}
}
/// Keeps the wakes of one app's owner tree unreported while its frame runs
/// them itself, and reports them again when dropped, even when the frame
/// unwinds.
struct QuietWakes(Rc<Scope>);
impl QuietWakes {
/// Silences the wakes of the tree `root` belongs to.
fn enter(root: &Owner) -> QuietWakes {
let scope = Rc::clone(&root.data().scope);
scope.quiet.set(true);
QuietWakes(scope)
}
}
impl Drop for QuietWakes {
fn drop(&mut self) {
self.0.quiet.set(false);
}
}