Skip to main content

crabshell_ui/
view.rs

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