qframe/widget/context/paint.rs
1//! The painting context.
2
3use std::time::Duration;
4
5use ratatui_core::buffer::{Buffer, Cell};
6use ratatui_core::style::Color;
7use unicode_segmentation::UnicodeSegmentation;
8
9use super::MeasureCx;
10use super::frame::{FocusRequest, Frame, Interaction, LayerEntry};
11use crate::color::{ColorDepth, Rgb};
12use crate::env::Env;
13use crate::geometry::{Rect, Size, clamp_u16};
14use crate::icons::PILLAR;
15use crate::keymap::KeyChord;
16use crate::motion::{Easing, Tweens};
17use crate::style::{CellStyle, WidgetStyle, to_color};
18use crate::text;
19use crate::theme::State;
20use crate::widget::memory::Memory;
21use crate::widget::{Key, LayoutProps, Node, WidgetId};
22
23/// Painting context: draws into the frame, clipped to the widget's visible area.
24pub struct PaintCx<'a> {
25 pub(crate) buf: &'a mut Buffer,
26 pub(crate) env: &'a Env,
27 pub(crate) frame: &'a mut Frame,
28 pub(crate) memory: &'a mut Memory,
29 pub(crate) interaction: &'a Interaction,
30 pub(crate) now: Duration,
31 pub(crate) clip: Rect,
32 pub(crate) id: WidgetId,
33 pub(crate) layout: LayoutProps,
34 pub(crate) scope: Option<WidgetId>,
35 /// How long no input has arrived, for views a widget builds while it paints.
36 pub(crate) idle: Duration,
37}
38
39impl PaintCx<'_> {
40 /// The id of the widget being painted.
41 #[must_use]
42 pub fn id(&self) -> WidgetId {
43 self.id
44 }
45
46 /// The environment.
47 #[must_use]
48 pub fn env(&self) -> &Env {
49 self.env
50 }
51
52 /// Layout properties of the widget being painted.
53 #[must_use]
54 pub fn layout(&self) -> LayoutProps {
55 self.layout
56 }
57
58 /// Time since the runtime started; drives animations.
59 #[must_use]
60 pub fn now(&self) -> Duration {
61 self.now
62 }
63
64 /// Whether the pointer is over this widget.
65 #[must_use]
66 pub fn is_hovered(&self) -> bool {
67 self.interaction.hovered == Some(self.id)
68 }
69
70 /// The widget that has keyboard focus, if any.
71 #[must_use]
72 pub fn focused(&self) -> Option<WidgetId> {
73 self.interaction.focused
74 }
75
76 /// The pointer cell wherever it is on screen, unlike [`PaintCx::pointer`].
77 #[must_use]
78 pub fn pointer_anywhere(&self) -> Option<(i32, i32)> {
79 self.interaction.pointer
80 }
81
82 /// Once this frame is painted, moves keyboard focus to the first focusable widget inside
83 /// `ancestor`, unless focus is already inside. Used by layers that take focus when they open.
84 pub fn request_focus_within(&mut self, ancestor: WidgetId) {
85 self.frame.focus_request = Some(FocusRequest::Within(ancestor));
86 }
87
88 /// Once this frame is painted, moves keyboard focus to `id` if that widget is focusable.
89 /// Used by layers to give focus back when they close.
90 pub fn request_focus(&mut self, id: WidgetId) {
91 self.frame.focus_request = Some(FocusRequest::Exact(id));
92 }
93
94 /// Makes this widget a dismissable layer for this frame: a pointer press outside it and its
95 /// descendants sends it [`Event::PointerOutside`](crate::event::Event::PointerOutside) and
96 /// then still reaches what was pressed, unless that is the widget whose press opened the
97 /// layer (then the press only closes it); an Esc key no focused widget used is sent to it.
98 /// Layers registered later are on top and are asked first. Dismissable layers share the
99 /// layer stack with modal layers ([`PaintCx::open_layer`]): a press on a modal layer above a
100 /// dismissable one lands inside the modal layer, so the dismissable layer beneath stays.
101 pub fn register_dismissable(&mut self) {
102 self.frame.layers.push(LayerEntry { id: self.id, modal: false, surface: None });
103 }
104
105 /// Whether this widget has keyboard focus.
106 #[must_use]
107 pub fn is_focused(&self) -> bool {
108 self.interaction.focused == Some(self.id)
109 }
110
111 /// Whether this widget has focus that should be shown loudly: it was reached with the
112 /// keyboard rather than clicked. Buttons and cards breathe their pillar only then, so a
113 /// clicked button stays calm under the pointer.
114 #[must_use]
115 pub fn is_focus_visible(&self) -> bool {
116 self.is_focused() && !self.interaction.focus_by_pointer
117 }
118
119 /// The pointer cell, when the pointer is over this widget.
120 #[must_use]
121 pub fn pointer(&self) -> Option<(i32, i32)> {
122 self.interaction.pointer.filter(|_| self.is_hovered())
123 }
124
125 /// Whether this widget is flashing after being activated. Schedules the frame that ends
126 /// the flash.
127 pub fn is_pressed(&mut self) -> bool {
128 let Some((id, at)) = self.interaction.pressed else {
129 return false;
130 };
131 let end = at + self.env.theme().motion().flash;
132 if id != self.id || self.now >= end {
133 return false;
134 }
135 self.frame.schedule(end);
136 true
137 }
138
139 /// Hover, focus and pressed states of a pressable widget such as a button, card, tab or
140 /// toggle: like [`states`](Self::states), but focus counts only when it is
141 /// [visible](Self::is_focus_visible), so a clicked control stays calm under the pointer.
142 pub fn pressable_states(&mut self) -> Vec<State> {
143 let visible = self.is_focus_visible();
144 let mut states = self.states();
145 if !visible {
146 states.retain(|state| *state != State::Focus);
147 }
148 states
149 }
150
151 /// Hover, focus and pressed states of this widget.
152 pub fn states(&mut self) -> Vec<State> {
153 let mut states = Vec::new();
154 if self.is_hovered() {
155 states.push(State::Hover);
156 }
157 if self.is_focused() {
158 states.push(State::Focus);
159 }
160 if self.is_pressed() {
161 states.push(State::Pressed);
162 }
163 states
164 }
165
166 /// The theme style of `widget.variant` in `states`, evaluated for this frame. Animated
167 /// styles schedule the next frame.
168 pub fn style(&mut self, widget: &str, variant: Option<&str>, states: &[State]) -> WidgetStyle {
169 let props = self.env.theme().style(widget, variant, states);
170 let style = WidgetStyle::new(props, self.pulse_phase());
171 if style.is_animated() && !self.env.reduced_motion() {
172 self.request_frame_in(PULSE_FRAME);
173 }
174 style
175 }
176
177 /// A theme colour token such as `"accent"`; black when the token does not exist.
178 #[must_use]
179 pub fn color(&self, token: &str) -> Rgb {
180 self.env.theme().color(token).unwrap_or(Rgb::new(0, 0, 0))
181 }
182
183 /// Asks for another frame after `delay`.
184 pub fn request_frame_in(&mut self, delay: Duration) {
185 self.frame.schedule(self.now + delay);
186 }
187
188 /// Whether the user asked for reduced motion; animations should show their end state.
189 #[must_use]
190 pub fn reduced_motion(&self) -> bool {
191 self.env.reduced_motion()
192 }
193
194 /// A value of this widget that moves towards `target` over `duration`. The value named
195 /// `name` starts at its first target without animating; later target changes animate from
196 /// wherever the value is. Schedules frames while it moves; returns `target` at once when
197 /// motion is reduced.
198 pub fn animate(&mut self, name: &'static str, target: f32, duration: Duration, easing: Easing) -> f32 {
199 if self.env.reduced_motion() {
200 return target;
201 }
202 let now = self.now;
203 let persistent = self.scope.is_some();
204 let tween = self.memory.get::<Tweens>(self.id, persistent).drive(name, target, now, duration, easing);
205 if tween.is_running(now) {
206 self.request_frame_in(ANIMATION_FRAME);
207 }
208 tween.value(now)
209 }
210
211 /// Eased progress from 0 to 1 of something that started at `start` (a time from
212 /// [`PaintCx::now`] or [`EventCx::now`](super::EventCx::now)) and takes `duration`. Schedules frames until it
213 /// completes; is 1 at once when motion is reduced.
214 pub fn progress_since(&mut self, start: Duration, duration: Duration, easing: Easing) -> f32 {
215 if self.env.reduced_motion() || duration.is_zero() {
216 return 1.0;
217 }
218 let elapsed = self.now.saturating_sub(start);
219 if elapsed >= duration {
220 return 1.0;
221 }
222 self.request_frame_in(ANIMATION_FRAME);
223 easing.apply(elapsed.as_secs_f32() / duration.as_secs_f32())
224 }
225
226 /// Where a repeating animation of length `period` is, `0.0..1.0`. Schedules smooth frames;
227 /// always 0 when motion is reduced.
228 pub fn cycle(&mut self, period: Duration) -> f32 {
229 let period = period.as_millis().max(1);
230 if self.env.reduced_motion() {
231 return 0.0;
232 }
233 self.request_frame_in(ANIMATION_FRAME);
234 (self.now.as_millis() % period) as f32 / period as f32
235 }
236
237 /// How many whole `interval`s have passed, for animations that jump between frames such as
238 /// spinners. Schedules a frame exactly at the next step; always 0 when motion is reduced.
239 pub fn ticks(&mut self, interval: Duration) -> u128 {
240 let interval_ms = interval.as_millis().max(1);
241 if self.env.reduced_motion() {
242 return 0;
243 }
244 let elapsed = self.now.as_millis();
245 let into = u64::try_from(elapsed % interval_ms).unwrap_or(0);
246 self.request_frame_in(Duration::from_millis(u64::try_from(interval_ms).unwrap_or(u64::MAX) - into));
247 elapsed / interval_ms
248 }
249
250 /// Where the theme pulse is, `0.0..1.0`; always 0 when motion is reduced.
251 #[must_use]
252 pub fn pulse_phase(&self) -> f32 {
253 if self.env.reduced_motion() {
254 return 0.0;
255 }
256 let period = self.env.theme().motion().pulse_period.as_secs_f64();
257 let phase = self.now.as_secs_f64().rem_euclid(period) / period;
258 // `phase` is in 0..1, which f32 represents closely enough for colour blending.
259 phase as f32
260 }
261
262 /// The visible area of this widget.
263 #[must_use]
264 pub fn clip(&self) -> Rect {
265 self.clip
266 }
267
268 /// Whether pasting would insert text, as far as the runtime knows; see `probe_clipboard` on
269 /// [`EventCx`](super::EventCx).
270 pub(crate) fn can_paste(&self) -> bool {
271 self.interaction.can_paste
272 }
273
274 /// Makes `rect` clickable for this widget. Later registrations are on top.
275 pub fn register_hit(&mut self, rect: Rect) {
276 self.register_hit_as(rect, self.id);
277 }
278
279 /// Makes `rect` clickable for `id`, a target the runtime handles itself (such as a toast)
280 /// rather than a widget in the view.
281 pub(crate) fn register_hit_as(&mut self, rect: Rect, id: WidgetId) {
282 if let Some(visible) = self.visible_part(rect) {
283 self.frame.hits.push((visible, id));
284 }
285 }
286
287 /// Keeps mouse text selection from starting in `rect`, even inside a selectable area, e.g.
288 /// for a secret shown in a selectable log.
289 pub fn unselectable(&mut self, rect: Rect) {
290 if let Some(visible) = self.visible_part(rect) {
291 self.frame.unselectable.push(visible);
292 }
293 }
294
295 /// Makes the visible part of `rect` a text selection region of this widget: a mouse drag
296 /// that starts inside it, and that no widget uses, selects text, and the selection stays
297 /// within this widget. Nothing is selectable unless a widget or
298 /// [`NodeMut::selectable`](crate::widget::NodeMut::selectable) asks; widgets whose text is
299 /// content to copy (code, documents, terminal output) call this while painting. The
300 /// innermost region under a press wins.
301 pub fn selectable(&mut self, rect: Rect) {
302 if let Some(visible) = self.visible_part(rect) {
303 self.frame.selectable.push((visible, self.id));
304 }
305 }
306
307 /// Marks the cells of `rect` as decoration rather than content, such as a scrollbar a widget
308 /// draws itself: a clean copy of a text selection leaves them out, a raw copy keeps them.
309 /// [`PaintCx::pillar`] marks its cell by itself.
310 pub fn decoration(&mut self, rect: Rect) {
311 if let Some(visible) = self.visible_part(rect) {
312 self.frame.decorations.push(visible);
313 }
314 }
315
316 /// Asks for [`MouseKind::Moved`](crate::event::MouseKind::Moved) events in this frame: the
317 /// pointer moving with no button held over this widget's hit area, or over a child of it.
318 /// Other widgets never see plain moves. Widgets that follow the pointer without a button,
319 /// such as an embedded terminal whose program asked for every motion,
320 /// call this while painting, and only while they need it.
321 pub fn track_pointer_moves(&mut self) {
322 self.frame.pointer_moves.push(self.id);
323 }
324
325 /// Shows this widget a mouse press inside it before the widgets inside it, for this frame:
326 /// a window takes an alt-drag on its body even from a terminal whose program reads the
327 /// mouse. The press arrives with [`EventCx::is_preview`](super::EventCx::is_preview) set;
328 /// using it keeps it from everything else, otherwise it goes on as usual. Outer widgets
329 /// see it first.
330 pub(crate) fn preview_presses(&mut self) {
331 self.frame.press_previews.push(self.id);
332 }
333
334 /// Adds this widget to the keyboard focus order.
335 pub fn register_focusable(&mut self) {
336 self.frame.focusable.push(self.id);
337 }
338
339 /// Paints this widget's overlay after the rest of the view.
340 pub fn request_overlay(&mut self, anchor: Rect) {
341 self.frame.overlays.push((self.id, anchor));
342 }
343
344 /// Makes this widget a modal layer for this frame and returns the time the layer opened.
345 ///
346 /// Call it from [`Widget::paint_overlay`](crate::widget::Widget::paint_overlay) every frame
347 /// the layer is shown, before painting what is inside it. Modal and dismissable layers
348 /// ([`PaintCx::register_dismissable`]) share one stack in paint order; the rules of a modal
349 /// layer are:
350 ///
351 /// - **Focus stays inside.** Each frame the layer asks, like
352 /// [`PaintCx::request_focus_within`], for focus to be inside it; a request made later in
353 /// the frame by a widget inside the layer (a popover opening) wins. Tab and Shift+Tab
354 /// cycle only through the layer's widgets.
355 /// - **Input stops at the layer.** Keys and pointer events bubble from their target up to
356 /// the topmost modal layer and no further; a press outside it lands on the layer itself.
357 /// Paint a hit area over the whole screen and use presses on it, so nothing beneath
358 /// reacts and no text selection starts there.
359 /// - **Shortcuts pause.** Application keymap actions (and global ones the runtime passes to
360 /// the application) do not run; quit, focus moves, debug, copy and paste still do. Key
361 /// listeners outside the layer are not heard.
362 /// - **Above it:** dismissable layers opened inside it, later modal layers, and the
363 /// runtime's toasts, which stay clickable.
364 /// - **Focus comes back.** When the layer is no longer painted, the runtime requests focus
365 /// for the widget that had it when the layer opened.
366 ///
367 /// The opening time stays the same for as long as the layer is shown, which makes it the
368 /// start of an entrance animation, even for layers inside persistent pages.
369 pub fn open_layer(&mut self) -> Duration {
370 self.frame.layers.push(LayerEntry { id: self.id, modal: true, surface: None });
371 self.request_focus_within(self.id);
372 self.interaction.layers.iter().find(|layer| layer.id == self.id).map_or(self.now, |layer| layer.opened)
373 }
374
375 /// Tells the runtime where the surface of the modal layer this widget opened with
376 /// [`PaintCx::open_layer`] sits, so toasts can keep clear of it.
377 pub(crate) fn set_layer_surface(&mut self, surface: Rect) {
378 let id = self.id;
379 if let Some(layer) = self.frame.layers.iter_mut().rev().find(|layer| layer.id == id) {
380 layer.surface = Some(surface);
381 }
382 }
383
384 /// The areas of the modal layers open in this frame: each layer's surface, or all of
385 /// `screen` for a layer that did not say where its surface is.
386 pub(crate) fn modal_surfaces(&self, screen: Rect) -> Vec<Rect> {
387 self.frame.layers.iter().filter(|layer| layer.modal).map(|layer| layer.surface.unwrap_or(screen)).collect()
388 }
389
390 /// Delivers `chord` to this widget even when it is not focused, for as long as the widget
391 /// is painted: after the focused widgets had their chance and before the keymap. Repeats
392 /// and releases of the key (which keyboards report while it is held) are delivered too,
393 /// including repeats of Enter and Space that focused widgets never see. Inside a modal
394 /// layer only listeners within the topmost layer hear keys.
395 pub fn listen_key(&mut self, chord: KeyChord) {
396 self.frame.listeners.push((chord, self.id));
397 }
398
399 /// Asks the nearest [`ScrollView`](crate::widgets::ScrollView) around this widget to scroll
400 /// just enough to show `rect`, a part of this widget's area, e.g. a line a code view jumps
401 /// to. The view glides there, or jumps when motion is reduced. Ask once when what should
402 /// be shown changes, not every frame, or the user could not scroll away from it.
403 pub fn reveal(&mut self, rect: Rect) {
404 self.frame.reveals.push((self.id, rect));
405 }
406
407 /// Blends the text and background colours already drawn in `rect` towards `color` by
408 /// `amount` (0 keeps them, 1 replaces them), e.g. to dim the screen behind a dialog. Cells
409 /// drawn with reduced colour depth take `color` once `amount` passes one half.
410 pub fn tint(&mut self, rect: Rect, color: Rgb, amount: f32) {
411 let amount = amount.clamp(0.0, 1.0);
412 if amount <= 0.0 {
413 return;
414 }
415 let depth = self.env.depth();
416 let blend = |current: Color| match current {
417 Color::Rgb(r, g, b) => Some(to_color(Rgb::new(r, g, b).mix(color, amount), depth)),
418 _ if amount > 0.5 => Some(to_color(color, depth)),
419 _ => None,
420 };
421 self.each_cell(rect, |cell| {
422 if let Some(fg) = blend(cell.fg) {
423 cell.fg = fg;
424 }
425 if let Some(bg) = blend(cell.bg) {
426 cell.bg = bg;
427 }
428 });
429 }
430
431 /// Blends the background of `rect` towards `color` by `amount`, keeping every glyph and its
432 /// colour, e.g. the tone a [`Ghost`](crate::widgets::Ghost) lays over the ground. Cells drawn
433 /// with reduced colour depth cannot be blended, so they take the colour mixed into the theme's
434 /// canvas instead, and text that would no longer read on it is brightened.
435 pub(crate) fn tint_ground(&mut self, rect: Rect, color: Rgb, amount: f32) {
436 let amount = amount.clamp(0.0, 1.0);
437 if amount <= 0.0 {
438 return;
439 }
440 if self.env.depth() != ColorDepth::TrueColor {
441 let ground = self.color("canvas").mix(color, amount);
442 let readable = self.color("text");
443 self.fill_keeping_text_readable(rect, ground, readable);
444 return;
445 }
446 let depth = self.env.depth();
447 self.each_cell(rect, |cell| {
448 if let Color::Rgb(r, g, b) = cell.bg {
449 cell.bg = to_color(Rgb::new(r, g, b).mix(color, amount), depth);
450 }
451 });
452 }
453
454 /// This widget's state of type `T`.
455 pub fn memory<T: Default + 'static>(&mut self) -> &mut T {
456 self.memory.get::<T>(self.id, self.scope.is_some())
457 }
458
459 /// Fills `rect` with `color`, keeping text.
460 pub fn fill(&mut self, rect: Rect, color: Rgb) {
461 let bg = to_color(color, self.env.depth());
462 self.each_cell(rect, |cell| cell.bg = bg);
463 }
464
465 /// Puts `color` behind the cells of `rect`, keeping their glyphs. A cell whose text would no
466 /// longer read on it (contrast below 3:1) takes `readable` instead, so faint text stays legible
467 /// under a highlight such as a text selection.
468 pub(crate) fn fill_keeping_text_readable(&mut self, rect: Rect, color: Rgb, readable: Rgb) {
469 let depth = self.env.depth();
470 let (bg, text) = (to_color(color, depth), to_color(readable, depth));
471 self.each_cell(rect, |cell| {
472 cell.bg = bg;
473 if let Color::Rgb(r, g, b) = cell.fg
474 && cell.symbol().trim() != ""
475 && Rgb::new(r, g, b).contrast_ratio(color) < 3.0
476 {
477 cell.fg = text;
478 }
479 });
480 }
481
482 /// Clears `rect` to spaces on `color`.
483 pub fn clear(&mut self, rect: Rect, color: Rgb) {
484 // An empty cell reads as a space and equals a cell holding one; copying a prepared blank
485 // cell is cheaper than resetting, writing and styling every cell.
486 let mut blank = Cell::EMPTY;
487 blank.bg = to_color(color, self.env.depth());
488 // Cells inside the rectangle are all replaced; only a wide character crossing its left
489 // or right edge would be cut in half.
490 let area = rect.intersect(self.clip);
491 if !area.is_empty() {
492 for y in area.y..area.bottom() {
493 self.release(area.x, y);
494 self.release(area.right() - 1, y);
495 }
496 }
497 self.each_cell(rect, |cell| cell.clone_from(&blank));
498 }
499
500 /// Draws the theme's pillar (`[icons] pillar`, e.g. `▌`) at `(x, y)` in `color`, over whatever
501 /// surface is already there. A blank glyph, as in ASCII mode, becomes a cell of `color`. The
502 /// cell is [decoration](PaintCx::decoration): clean copies of a text selection skip it.
503 pub fn pillar(&mut self, x: i32, y: i32, color: Rgb) {
504 self.decoration(Rect::new(x, y, 1, 1));
505 let env = self.env;
506 let glyph = env.icons().glyph(PILLAR);
507 if glyph.trim().is_empty() {
508 self.fill(Rect::new(x, y, 1, 1), color);
509 } else {
510 self.text(x, y, &glyph, CellStyle::fg(color), 1);
511 }
512 }
513
514 /// Draws `text` starting at `(x, y)`, at most `max` cells wide, clipped to the visible area.
515 /// Returns the number of cells the text occupies (before clipping).
516 pub fn text(&mut self, x: i32, y: i32, text: &str, style: CellStyle, max: u16) -> u16 {
517 let paint = style.for_depth(self.env.depth());
518 let clip = self.clip;
519 let limit = x + i32::from(max);
520 let mut column = x;
521 // Printable ASCII is one cell per byte. The byte after the last one that fits is checked
522 // too: a combining mark there would join the last character drawn.
523 let drawn = text.len().min(usize::from(max));
524 if text.get(..text.len().min(drawn + 1)).is_some_and(text::is_printable_ascii) {
525 for index in 0..drawn {
526 if clip.contains(column, y) {
527 self.release(column, y);
528 }
529 if clip.contains(column, y)
530 && let Some(cell) = self.cell_mut(column, y)
531 {
532 cell.set_symbol(&text[index..=index]);
533 paint.apply(cell);
534 }
535 column += 1;
536 }
537 return clamp_u16(column - x);
538 }
539 for grapheme in text.graphemes(true) {
540 let width = i32::from(text::grapheme_width(grapheme));
541 if width == 0 {
542 continue;
543 }
544 if column + width > limit {
545 break;
546 }
547 // Every cell of the grapheme is released before any is written, so its own second
548 // half is not mistaken for part of a character it cut.
549 for offset in 0..width {
550 if clip.contains(column + offset, y) {
551 self.release(column + offset, y);
552 }
553 }
554 for offset in 0..width {
555 let cx = column + offset;
556 if !clip.contains(cx, y) {
557 continue;
558 }
559 let whole = clip.contains(column, y) && clip.contains(column + width - 1, y);
560 if let Some(cell) = self.cell_mut(cx, y) {
561 let symbol = match (offset, whole) {
562 (0, true) => grapheme,
563 (_, true) => "",
564 _ => " ",
565 };
566 cell.set_symbol(symbol);
567 paint.apply(cell);
568 }
569 }
570 column += width;
571 }
572 clamp_u16(column - x)
573 }
574
575 /// Paints a child node into `rect`, applying its padding.
576 pub fn paint_child<M: 'static>(&mut self, node: &Node<M>, rect: Rect) {
577 self.paint_child_spilling(node, rect, rect);
578 }
579
580 /// Paints a child node into `rect` like [`PaintCx::paint_child`], letting it draw anywhere in
581 /// `visible` (which holds `rect`), e.g. a placed window's shadow just past its edges.
582 pub(crate) fn paint_child_spilling<M: 'static>(&mut self, node: &Node<M>, rect: Rect, visible: Rect) {
583 let saved = (self.id, self.layout, self.clip, self.scope);
584 self.id = node.id;
585 self.layout = node.layout;
586 if node.persistent {
587 self.scope = Some(node.id);
588 }
589 self.clip = saved.2.intersect(visible);
590 self.frame.rects.insert(node.id, rect);
591 self.frame.parents.insert(node.id, saved.0);
592 if let Key::Named(name) = &node.key {
593 self.frame.names.insert(node.id, name.clone());
594 }
595 if let Some(scope) = self.scope {
596 self.frame.scopes.insert(node.id, scope);
597 }
598 self.memory.touch(node.id, self.scope.is_some());
599 match node.selectable {
600 Some(true) => self.selectable(rect),
601 Some(false) => self.unselectable(rect),
602 None => {}
603 }
604 if node.widget.focusable() {
605 self.register_focusable();
606 }
607 node.widget.paint(self, rect.inset(node.layout.padding));
608 (self.id, self.layout, self.clip, self.scope) = saved;
609 }
610
611 /// Paints a child node that does not take keyboard focus itself, not even when it is
612 /// normally focusable. For composite widgets that take focus as one control and pass keys on
613 /// to the child with [`EventCx::forward`](super::EventCx::forward), such as a settings row's switch.
614 pub fn paint_child_unfocusable<M: 'static>(&mut self, node: &Node<M>, rect: Rect) {
615 let registered = self.frame.focusable.len();
616 self.paint_child(node, rect);
617 self.frame.focusable.truncate(registered);
618 }
619
620 /// The pointer cell, when the pointer is over this widget or over a widget inside it, for
621 /// containers whose rows light up while the pointer is on a control within them.
622 #[must_use]
623 pub fn pointer_within(&self) -> Option<(i32, i32)> {
624 self.interaction.pointer.filter(|_| self.interaction.hovered_chain.contains(&self.id))
625 }
626
627 /// Whether keyboard focus is on this widget or on a widget painted inside it so far in this
628 /// frame. Paint children before asking, e.g. to brighten a field label while its control has
629 /// focus.
630 #[must_use]
631 pub fn has_focus_within(&self) -> bool {
632 self.interaction.focused.is_some_and(|focused| self.frame.is_within(focused, self.id))
633 }
634
635 /// Measures a child node with the same rules as layout.
636 pub fn measure_child<M: 'static>(&mut self, node: &Node<M>, available: Size) -> Size {
637 MeasureCx::for_frame(self.env, &mut self.frame.measures).measure_child(node, available)
638 }
639
640 /// Runs `paint` with drawing limited to `rect` (and the current visible area).
641 pub fn with_clip(&mut self, rect: Rect, paint: impl FnOnce(&mut Self)) {
642 let saved = self.clip;
643 self.clip = saved.intersect(rect);
644 paint(self);
645 self.clip = saved;
646 }
647
648 /// The part of `rect` inside the visible area, when there is one.
649 fn visible_part(&self, rect: Rect) -> Option<Rect> {
650 Some(rect.intersect(self.clip)).filter(|visible| !visible.is_empty())
651 }
652
653 /// Runs `change` on every cell of `rect` inside the visible area and the screen.
654 pub(super) fn each_cell(&mut self, rect: Rect, mut change: impl FnMut(&mut Cell)) {
655 let area = rect.intersect(self.clip);
656 for y in area.y..area.bottom() {
657 for x in area.x..area.right() {
658 if let Some(cell) = self.cell_mut(x, y) {
659 change(cell);
660 }
661 }
662 }
663 }
664
665 /// Keeps wide characters whole before a new symbol lands on `(x, y)`.
666 ///
667 /// A terminal draws a double-width character from its first cell across the next one, and the
668 /// buffer holds it as the glyph followed by an empty second half. Replacing only one half, as a
669 /// dialog's pillar or edge drawn over text does, leaves a pair the terminal cannot show: the
670 /// glyph spills over the new symbol, or the rest of the row shifts by a column. So when the
671 /// cell belongs to a wide character that reaches beyond it, every other cell of that
672 /// character becomes a blank in the colours it already had. The cell may lie outside the
673 /// visible area: a layer's edge decides what happens to the character it cuts.
674 fn release(&mut self, x: i32, y: i32) {
675 // The character this cell is the second half of: the nearest non-empty cell to the left.
676 let mut lead = None;
677 for back in 1..=MAX_GLYPH_CELLS {
678 let Some(cell) = self.cell_mut(x - back, y) else { break };
679 let symbol = cell.symbol();
680 if symbol.is_empty() {
681 continue;
682 }
683 let cells = i32::from(text::width(symbol));
684 if cells > back {
685 lead = Some((x - back, cells));
686 }
687 break;
688 }
689 if let Some((start, cells)) = lead {
690 self.blank_cells(start, start + cells, y);
691 }
692 let own = self.cell_mut(x, y).map_or(1, |cell| i32::from(text::width(cell.symbol())));
693 if own > 1 {
694 self.blank_cells(x + 1, x + own, y);
695 }
696 }
697
698 /// Turns the cells from `start` up to `end` on row `y` into spaces, keeping their colours.
699 fn blank_cells(&mut self, start: i32, end: i32, y: i32) {
700 for x in start..end {
701 if let Some(cell) = self.cell_mut(x, y) {
702 cell.set_symbol(" ");
703 }
704 }
705 }
706
707 /// The screen cell at `(x, y)`, when it is on screen.
708 fn cell_mut(&mut self, x: i32, y: i32) -> Option<&mut Cell> {
709 self.buf.cell_mut((u16::try_from(x).ok()?, u16::try_from(y).ok()?))
710 }
711}
712
713/// The most cells one grapheme covers on screen; how far to look left for the start of the
714/// character a cell belongs to.
715const MAX_GLYPH_CELLS: i32 = 4;
716
717/// Frame interval while something moves: about 60 frames a second.
718pub(crate) const ANIMATION_FRAME: Duration = Duration::from_millis(16);
719
720/// How often animated theme colours are redrawn.
721pub(crate) const PULSE_FRAME: Duration = Duration::from_millis(50);