crabshell_ui/view.rs
1//! A read-only view of a laid-out window, for drawing it.
2
3use std::cell::Ref;
4
5use cosmic_text::{Buffer, LayoutGlyph};
6
7use crate::canvas::CanvasOp;
8use crate::geometry::{Affine, Point, Rect, Size};
9use crate::image::ImageTransition;
10use crate::region::Region;
11use crate::rich::Span;
12use crate::screencopy::CaptureFrame;
13use crate::select::{cursor_at, highlights, text_selection};
14use crate::style::{Color, Style};
15use crate::text::{TextNode, TextRun};
16use crate::tree::{Node, NodeId, NodeKind, Tree, centered, icon_rect};
17use crate::widgets::{Fit, IconSource, ImageFilters};
18
19/// The color text uses when no ancestor sets one.
20const DEFAULT_TEXT_COLOR: Color = Color::rgb(0, 0, 0);
21
22/// A window's laid-out tree, borrowed for reading. Get one from
23/// [`Window::view`](crate::Window::view).
24pub struct WindowView<'w> {
25 tree: Ref<'w, Tree>,
26}
27
28impl<'w> WindowView<'w> {
29 pub(crate) fn new(tree: Ref<'w, Tree>) -> WindowView<'w> {
30 WindowView { tree }
31 }
32
33 /// The window's size in logical pixels.
34 pub fn size(&self) -> Size {
35 self.tree.size
36 }
37
38 /// The window's root node, which has the window's style and its child.
39 pub fn root(&self) -> NodeView<'_> {
40 NodeView::new(&self.tree, self.tree.root)
41 .expect("invariant: the root node exists while the tree does")
42 }
43
44 /// Whether the window has any [`Image`](crate::Image), shown or not.
45 pub fn has_images(&self) -> bool {
46 !self.tree.images.is_empty()
47 }
48
49 /// The window's images whose `status` signal still says Loading, hidden
50 /// ones too, at the box they were last laid out in. The platform has the
51 /// renderer load them when
52 /// [`image_sources_changed`](crate::image_sources_changed) says so,
53 /// drawn or not, since one may be shown only once it is Ready.
54 pub fn loading_images(&self) -> Vec<ImageView<'_>> {
55 self
56 .tree
57 .images
58 .iter()
59 .filter_map(|&id| match NodeView::new(&self.tree, id)?.content() {
60 Content::Image(image) if crate::image::awaits_status(image.id) => Some(image),
61 _ => None,
62 })
63 .collect()
64 }
65}
66
67/// One node of a laid-out window: a widget, or the window itself at the
68/// root. Draw it, then its [`children`](Self::children) in order, so later
69/// ones are on top.
70#[derive(Clone, Copy)]
71pub struct NodeView<'a> {
72 tree: &'a Tree,
73 id: NodeId,
74 node: &'a Node,
75}
76
77impl<'a> NodeView<'a> {
78 fn new(tree: &'a Tree, id: NodeId) -> Option<NodeView<'a>> {
79 let node = tree.node(id)?;
80 Some(NodeView { tree, id, node })
81 }
82
83 /// The widget type, such as `"Row"`, or `"PanelWindow"` at the root.
84 pub fn name(&self) -> &'static str {
85 self.node.name
86 }
87
88 /// The widget path, such as `PanelWindow[DP-1]/Row/Button[2]`.
89 pub fn path(&self) -> &'a str {
90 &self.node.path
91 }
92
93 /// The rectangle from the last layout, in window coordinates. Empty
94 /// before the first layout.
95 pub fn rect(&self) -> Rect {
96 self.node.rect.unwrap_or_default()
97 }
98
99 /// The area the node and everything inside it painted at the last
100 /// layout: its rectangle, text and icons that overflow it, and its
101 /// descendants' bounds, moved by its [`transform`](Self::transform) into
102 /// its parent's coordinates. Nothing outside it needs drawing for this
103 /// node.
104 pub fn bounds(&self) -> Rect {
105 self.node.bounds
106 }
107
108 /// [`bounds`](Self::bounds) before the node's own transform, in its own
109 /// coordinates: what a layer drawn for the transform must hold. The
110 /// same as `bounds` when it has none.
111 pub fn inner_bounds(&self) -> Rect {
112 self.node.inner_bounds
113 }
114
115 /// How the node's style moves it and everything inside it where it is
116 /// drawn, from its own coordinates, which its rectangle and its
117 /// children's are in, into its parent's. `None` when it doesn't. The
118 /// whole subtree is drawn as one layer through it.
119 pub fn transform(&self) -> Option<Affine> {
120 self.node.transform
121 }
122
123 /// A number that changes whenever anything the node and everything
124 /// inside it draw changes, but for the node's own opacity and
125 /// transform: a style, its own or one its text inherits, text shaped
126 /// again, a picture or frame coming in, a child added, removed or
127 /// moved, a scroll, a hover. A renderer that kept the node's layer may
128 /// blend it in again while this stays the same. What only the renderer
129 /// knows, such as its icon theme, it tracks itself.
130 pub fn revision(&self) -> u64 {
131 self.node.revision
132 }
133
134 /// The style in effect, with a button's hover and pressed styles laid
135 /// over its own. Inherited fields aren't filled in;
136 /// [`TextView::color`] has the color text is drawn in.
137 pub fn style(&self) -> Style {
138 self.node.shown_style()
139 }
140
141 /// The region the node and everything inside it show within, in its
142 /// own logical pixels from its rectangle's top-left corner, from
143 /// `mask_region`. Draw nothing outside it or outside the rectangle.
144 pub fn mask_region(&self) -> Option<&'a Region> {
145 self.node.mask_region.as_ref()
146 }
147
148 /// The children, in drawing order: by their style's `z`, lowest
149 /// first, and in child order where it is equal.
150 pub fn children(&self) -> impl Iterator<Item = NodeView<'a>> + 'a {
151 let tree = self.tree;
152 tree
153 .drawn_children(self.id)
154 .into_iter()
155 .filter_map(move |id| NodeView::new(tree, id))
156 }
157
158 /// Whether the node cuts its children to the inside of its border: a
159 /// clipping style or a scroll view.
160 pub fn clips(&self) -> bool {
161 self.node.clips()
162 }
163
164 /// A scroll view's first scroll bar handle and the style to draw it
165 /// with, over its children, while it shows one. See
166 /// [`scroll_bars`](Self::scroll_bars) for a view that scrolls both ways.
167 pub fn scroll_bar(&self) -> Option<(Rect, Style)> {
168 self.scroll_bars().next()
169 }
170
171 /// A scroll view's scroll bar handles, one an axis it shows a bar
172 /// along, and the style to draw them with, over its children.
173 pub fn scroll_bars(&self) -> impl Iterator<Item = (Rect, Style)> + 'a {
174 let scroll = match &self.node.kind {
175 NodeKind::Scroll(scroll) => Some(&**scroll),
176 _ => None,
177 };
178 scroll.into_iter().flat_map(|scroll| {
179 scroll
180 .axes
181 .iter()
182 .filter_map(|axis| Some((axis.handle?.1, scroll.bar?)))
183 })
184 }
185
186 /// What the node draws besides its background and border.
187 pub fn content(&self) -> Content<'a> {
188 match &self.node.kind {
189 NodeKind::Text(text) => Content::Text(TextView {
190 text,
191 color: self.inherited_color(),
192 underline: self.inherited(|style| style.underline) == Some(true),
193 strikethrough: self.inherited(|style| style.strikethrough) == Some(true),
194 selected: None,
195 }),
196 NodeKind::Icon(icon) => match &icon.source {
197 Some(source) => Content::Icon(IconView {
198 source,
199 fallback: icon.fallback.as_ref(),
200 rect: icon_rect(self.node.content, icon.size),
201 tint: icon.tint,
202 }),
203 None => Content::None,
204 },
205 NodeKind::Input(input) => {
206 let color = self.inherited_color();
207 let color = if input.showing_placeholder() {
208 Color::rgba(color.r, color.g, color.b, color.a / 2)
209 } else {
210 color
211 };
212 // The selected glyphs, between two cursors of the buffer.
213 let selected = match (input.focused, input.selected_text_color) {
214 (true, Some(selected)) => input.shown_selection().map(|range| {
215 let at = |index| {
216 let cursor = cursor_at(&input.text.buffer, index);
217 (cursor.line, cursor.index)
218 };
219 (at(range.start), at(range.end), selected)
220 }),
221 _ => None,
222 };
223 Content::Input(InputView {
224 text: TextView {
225 text: &input.text,
226 color,
227 underline: self.inherited(|style| style.underline) == Some(true),
228 strikethrough: self.inherited(|style| style.strikethrough) == Some(true),
229 selected,
230 },
231 selection_color: input.selection_color.unwrap_or(Color::rgba(
232 color.r,
233 color.g,
234 color.b,
235 color.a / 3,
236 )),
237 // An input method may ask for no caret while it composes.
238 caret: (input.focused
239 && !matches!(&input.preedit, Some(preedit) if preedit.cursor.is_none()))
240 .then_some(input.caret),
241 selection: if input.focused { &input.selection } else { &[] },
242 area: input.area,
243 underline: &input.underline,
244 })
245 }
246 NodeKind::Image(image) => match &image.source {
247 Some(source) => Content::Image(ImageView {
248 id: image.id,
249 source,
250 rect: centered(self.node.content, image.width, image.height),
251 fit: image.fit,
252 filters: image.filters,
253 playing: image.playing,
254 transition: image.transition,
255 leaving: image
256 .leaving
257 .as_ref()
258 .map(|leaving| (&leaving.source, leaving.t)),
259 }),
260 None => Content::None,
261 },
262 NodeKind::Capture(capture) => match &capture.frame {
263 Some(frame) => Content::Capture(CaptureView {
264 id: capture.id,
265 frame,
266 rect: self.node.content,
267 fit: capture.fit,
268 crop: capture.crop,
269 }),
270 None => Content::None,
271 },
272 NodeKind::Canvas(canvas) => Content::Canvas(CanvasView {
273 ops: &canvas.ops,
274 rect: self.node.rect.unwrap_or_default(),
275 }),
276 _ => Content::None,
277 }
278 }
279
280 /// The color of the nearest node, starting with this one, whose style
281 /// sets one.
282 fn inherited_color(&self) -> Color {
283 self
284 .inherited(|style| style.color)
285 .unwrap_or(DEFAULT_TEXT_COLOR)
286 }
287
288 /// `field` of the nearest node, starting with this one, whose style
289 /// sets it.
290 fn inherited<T>(&self, field: impl Fn(&Style) -> Option<T>) -> Option<T> {
291 let mut id = Some(self.id);
292 while let Some(current) = id {
293 if let Some(value) = self
294 .tree
295 .node(current)
296 .and_then(|node| field(&node.shown_style()))
297 {
298 return Some(value);
299 }
300 id = self.tree.taffy.parent(current);
301 }
302 None
303 }
304}
305
306/// What a node draws besides its background and border.
307pub enum Content<'a> {
308 /// Nothing.
309 None,
310 /// Text.
311 Text(TextView<'a>),
312 /// An icon.
313 Icon(IconView<'a>),
314 /// An image.
315 Image(ImageView<'a>),
316 /// A screencopy view's frame.
317 Capture(CaptureView<'a>),
318 /// A text field.
319 Input(InputView<'a>),
320 /// A canvas's drawing.
321 Canvas(CanvasView<'a>),
322}
323
324/// A canvas's drawing, ready to draw: each op in order, in logical pixels
325/// from the corner of `rect`, cut to it and its style's rounded corners.
326pub struct CanvasView<'a> {
327 /// What the paint closure drew at its last run that didn't panic.
328 pub ops: &'a [CanvasOp],
329 /// Where: the canvas's rectangle.
330 pub rect: Rect,
331}
332
333/// A text field, ready to draw: the selection behind the text, then the
334/// text, then the caret.
335pub struct InputView<'a> {
336 /// What the field shows; a placeholder comes in half its color.
337 pub text: TextView<'a>,
338 /// The caret, while the field has the keyboard.
339 pub caret: Option<Rect>,
340 /// The selection, while the field has the keyboard: one span, or more
341 /// where right-to-left and left-to-right text mix.
342 pub selection: &'a [Rect],
343 /// The color to draw the selection in: the field's own, or a third of
344 /// the text's alpha.
345 pub selection_color: Color,
346 /// The content box everything is cut to.
347 pub area: Rect,
348 /// The line under text an input method is composing.
349 pub underline: &'a [Rect],
350}
351
352/// Laid-out text, ready to draw. Lines can stick out of the node's
353/// rectangle when it is too small for them; draw them unclipped, as CSS
354/// does. The window's damage covers them.
355pub struct TextView<'a> {
356 text: &'a TextNode,
357 color: Color,
358 underline: bool,
359 strikethrough: bool,
360 /// From which line and byte to which the glyphs take a field's
361 /// selected text color, and the color.
362 selected: Option<(Place, Place, Color)>,
363}
364
365/// A buffer line and a byte in it.
366type Place = (usize, usize);
367
368impl<'a> TextView<'a> {
369 /// The text itself.
370 pub fn content(&self) -> &'a str {
371 &self.text.content
372 }
373
374 /// The cosmic-text buffer layout measured, for drawing glyphs from.
375 pub fn buffer(&self) -> &'a Buffer {
376 &self.text.buffer
377 }
378
379 /// The lines to draw: the buffer's lines, at most `max_lines`. Glyph
380 /// positions are relative to [`origin`](Self::origin).
381 pub fn runs(&self) -> impl Iterator<Item = TextRun<'a>> + 'a {
382 self.text.runs()
383 }
384
385 /// The top-left corner of the first line, in window coordinates.
386 pub fn origin(&self) -> Point {
387 self.text.origin
388 }
389
390 /// The color to draw in, inherited if the text's own style doesn't set
391 /// one.
392 pub fn color(&self) -> Color {
393 self.color
394 }
395
396 /// The span of a rich text that `glyph`, on the run of buffer line
397 /// `line`, belongs to, if any. The ellipsis belongs to none, though
398 /// cosmic-text gives it the first span's color.
399 pub fn span(&self, line: usize, glyph: &LayoutGlyph) -> Option<&'a Span> {
400 let index = self.text.glyph_span(line, glyph)?;
401 self.text.spans.get(index)
402 }
403
404 /// Whether `glyph`, on the run of buffer line `line`, belongs to a
405 /// link drawn lit, because the pointer is over it or the keyboard focus
406 /// is on it: underlined, and in
407 /// [`link_hover_color`](Self::link_hover_color) if the text has one.
408 pub fn glyph_lit(&self, line: usize, glyph: &LayoutGlyph) -> bool {
409 let text = self.text;
410 (text.hovered_link.is_some() || text.focused_link.is_some())
411 && text
412 .glyph_span(line, glyph)
413 .is_some_and(|index| text.lit(index))
414 }
415
416 /// The color a lit link is drawn in; without one it keeps its own.
417 pub fn link_hover_color(&self) -> Option<Color> {
418 self.text.link_hover_color
419 }
420
421 /// The color `glyph`, on the run of buffer line `line`, is drawn in
422 /// because it is selected in a field with a selected text color, over
423 /// any span or link color.
424 pub fn selected_color(&self, line: usize, glyph: &LayoutGlyph) -> Option<Color> {
425 let (start, end, color) = self.selected?;
426 let at = (line, glyph.start);
427 (start <= at && at < end).then_some(color)
428 }
429
430 /// Whether to draw a line under the glyphs, in the text's color.
431 pub fn underline(&self) -> bool {
432 self.underline
433 }
434
435 /// Whether to draw a line through the glyphs, in the text's color.
436 pub fn strikethrough(&self) -> bool {
437 self.strikethrough
438 }
439
440 /// Where a selectable text's selection shows, in window coordinates,
441 /// to be drawn behind it: a rectangle for each line it covers, or more
442 /// where right-to-left and left-to-right text mix.
443 pub fn selection(&self) -> Vec<Rect> {
444 text_selection(self.text).map_or_else(Vec::new, |range| highlights(self.text, range))
445 }
446}
447
448/// An icon, ready to draw.
449pub struct IconView<'a> {
450 /// What to show.
451 pub source: &'a IconSource,
452 /// What to show when `source` can't be loaded.
453 pub fallback: Option<&'a IconSource>,
454 /// Where: a square of the icon's size, centered in the node.
455 pub rect: Rect,
456 /// The color its pixels are painted in, keeping their alpha.
457 pub tint: Option<Color>,
458}
459
460/// An image, ready to draw.
461pub struct ImageView<'a> {
462 /// Names the image, so a renderer can keep a GIF's playback and the
463 /// platform repaint it with [`Window::repaint_image`](crate::Window::repaint_image).
464 pub id: u64,
465 /// What to show: a file, an icon name looked up in the theme at the
466 /// box's larger side, or raw pixels.
467 pub source: &'a IconSource,
468 /// Where: a box of the image's size, centered in the node.
469 pub rect: Rect,
470 /// How the picture fills the box.
471 pub fit: Fit,
472 /// What the picture is drawn through.
473 pub filters: ImageFilters,
474 /// Whether a GIF plays; paused, it stays on its frame.
475 pub playing: bool,
476 /// How a new source comes in. With one other than none, a source that
477 /// can't be loaded shows the last one that could.
478 pub transition: ImageTransition,
479 /// While a transition runs: the source it leaves and how far along it is,
480 /// eased, from 0 (all old) to 1 (all new); an easing that overshoots
481 /// may stray past either end.
482 pub leaving: Option<(&'a IconSource, f32)>,
483}
484
485/// A screencopy view's frame, ready to draw.
486pub struct CaptureView<'a> {
487 /// Names the view, so a cache can keep its frame scaled to its box.
488 pub id: u64,
489 /// The frame last captured.
490 pub frame: &'a CaptureFrame,
491 /// Where: the view's content box.
492 pub rect: Rect,
493 /// How the frame fills the box.
494 pub fit: Fit,
495 /// The part of the frame shown, in the source's logical pixels; `None`
496 /// for all of it.
497 pub crop: Option<Rect>,
498}