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;
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  /// The style in effect, with a button's hover and pressed styles laid
124  /// over its own. Inherited fields aren't filled in;
125  /// [`TextView::color`] has the color text is drawn in.
126  pub fn style(&self) -> Style {
127    self.node.shown_style()
128  }
129
130  /// The region the node and everything inside it show within, in its
131  /// own logical pixels from its rectangle's top-left corner, from
132  /// `mask_region`. Draw nothing outside it or outside the rectangle.
133  pub fn mask_region(&self) -> Option<&'a Region> {
134    self.node.mask_region.as_ref()
135  }
136
137  /// The children, in drawing order: by their style's `z`, lowest
138  /// first, and in child order where it is equal.
139  pub fn children(&self) -> impl Iterator<Item = NodeView<'a>> + 'a {
140    let tree = self.tree;
141    tree
142      .drawn_children(self.id)
143      .into_iter()
144      .filter_map(move |id| NodeView::new(tree, id))
145  }
146
147  /// Whether the node cuts its children to the inside of its border: a
148  /// clipping style or a scroll view.
149  pub fn clips(&self) -> bool {
150    self.node.clips()
151  }
152
153  /// A scroll view's first scroll bar handle and the style to draw it
154  /// with, over its children, while it shows one. See
155  /// [`scroll_bars`](Self::scroll_bars) for a view that scrolls both ways.
156  pub fn scroll_bar(&self) -> Option<(Rect, Style)> {
157    self.scroll_bars().next()
158  }
159
160  /// A scroll view's scroll bar handles, one an axis it shows a bar
161  /// along, and the style to draw them with, over its children.
162  pub fn scroll_bars(&self) -> impl Iterator<Item = (Rect, Style)> + 'a {
163    let scroll = match &self.node.kind {
164      NodeKind::Scroll(scroll) => Some(&**scroll),
165      _ => None,
166    };
167    scroll.into_iter().flat_map(|scroll| {
168      scroll
169        .axes
170        .iter()
171        .filter_map(|axis| Some((axis.handle?.1, scroll.bar?)))
172    })
173  }
174
175  /// What the node draws besides its background and border.
176  pub fn content(&self) -> Content<'a> {
177    match &self.node.kind {
178      NodeKind::Text(text) => Content::Text(TextView {
179        text,
180        color: self.inherited_color(),
181        underline: self.inherited(|style| style.underline) == Some(true),
182        strikethrough: self.inherited(|style| style.strikethrough) == Some(true),
183        selected: None,
184      }),
185      NodeKind::Icon(icon) => match &icon.source {
186        Some(source) => Content::Icon(IconView {
187          source,
188          fallback: icon.fallback.as_ref(),
189          rect: icon_rect(self.node.content, icon.size),
190          tint: icon.tint,
191        }),
192        None => Content::None,
193      },
194      NodeKind::Input(input) => {
195        let color = self.inherited_color();
196        let color = if input.showing_placeholder() {
197          Color::rgba(color.r, color.g, color.b, color.a / 2)
198        } else {
199          color
200        };
201        // The selected glyphs, between two cursors of the buffer.
202        let selected = match (input.focused, input.selected_text_color) {
203          (true, Some(selected)) => input.shown_selection().map(|range| {
204            let at = |index| {
205              let cursor = cursor_at(&input.text.buffer, index);
206              (cursor.line, cursor.index)
207            };
208            (at(range.start), at(range.end), selected)
209          }),
210          _ => None,
211        };
212        Content::Input(InputView {
213          text: TextView {
214            text: &input.text,
215            color,
216            underline: self.inherited(|style| style.underline) == Some(true),
217            strikethrough: self.inherited(|style| style.strikethrough) == Some(true),
218            selected,
219          },
220          selection_color: input.selection_color.unwrap_or(Color::rgba(
221            color.r,
222            color.g,
223            color.b,
224            color.a / 3,
225          )),
226          // An input method may ask for no caret while it composes.
227          caret: (input.focused
228            && !matches!(&input.preedit, Some(preedit) if preedit.cursor.is_none()))
229          .then_some(input.caret),
230          selection: if input.focused { &input.selection } else { &[] },
231          area: input.area,
232          underline: &input.underline,
233        })
234      }
235      NodeKind::Image(image) => match &image.source {
236        Some(source) => Content::Image(ImageView {
237          id: image.id,
238          source,
239          rect: centered(self.node.content, image.width, image.height),
240          fit: image.fit,
241          filters: image.filters,
242          playing: image.playing,
243          transition: image.transition,
244          leaving: image
245            .leaving
246            .as_ref()
247            .map(|leaving| (&leaving.source, leaving.t)),
248        }),
249        None => Content::None,
250      },
251      NodeKind::Capture(capture) => match &capture.frame {
252        Some(frame) => Content::Capture(CaptureView {
253          id: capture.id,
254          frame,
255          rect: self.node.content,
256          fit: capture.fit,
257          crop: capture.crop,
258        }),
259        None => Content::None,
260      },
261      NodeKind::Canvas(canvas) => Content::Canvas(CanvasView {
262        ops: &canvas.ops,
263        rect: self.node.rect.unwrap_or_default(),
264      }),
265      _ => Content::None,
266    }
267  }
268
269  /// The color of the nearest node, starting with this one, whose style
270  /// sets one.
271  fn inherited_color(&self) -> Color {
272    self
273      .inherited(|style| style.color)
274      .unwrap_or(DEFAULT_TEXT_COLOR)
275  }
276
277  /// `field` of the nearest node, starting with this one, whose style
278  /// sets it.
279  fn inherited<T>(&self, field: impl Fn(&Style) -> Option<T>) -> Option<T> {
280    let mut id = Some(self.id);
281    while let Some(current) = id {
282      if let Some(value) = self
283        .tree
284        .node(current)
285        .and_then(|node| field(&node.shown_style()))
286      {
287        return Some(value);
288      }
289      id = self.tree.taffy.parent(current);
290    }
291    None
292  }
293}
294
295/// What a node draws besides its background and border.
296pub enum Content<'a> {
297  /// Nothing.
298  None,
299  /// Text.
300  Text(TextView<'a>),
301  /// An icon.
302  Icon(IconView<'a>),
303  /// An image.
304  Image(ImageView<'a>),
305  /// A screencopy view's frame.
306  Capture(CaptureView<'a>),
307  /// A text field.
308  Input(InputView<'a>),
309  /// A canvas's drawing.
310  Canvas(CanvasView<'a>),
311}
312
313/// A canvas's drawing, ready to draw: each op in order, in logical pixels
314/// from the corner of `rect`, cut to it and its style's rounded corners.
315pub struct CanvasView<'a> {
316  /// What the paint closure drew at its last run that didn't panic.
317  pub ops: &'a [CanvasOp],
318  /// Where: the canvas's rectangle.
319  pub rect: Rect,
320}
321
322/// A text field, ready to draw: the selection behind the text, then the
323/// text, then the caret.
324pub struct InputView<'a> {
325  /// What the field shows; a placeholder comes in half its color.
326  pub text: TextView<'a>,
327  /// The caret, while the field has the keyboard.
328  pub caret: Option<Rect>,
329  /// The selection, while the field has the keyboard: one span, or more
330  /// where right-to-left and left-to-right text mix.
331  pub selection: &'a [Rect],
332  /// The color to draw the selection in: the field's own, or a third of
333  /// the text's alpha.
334  pub selection_color: Color,
335  /// The content box everything is cut to.
336  pub area: Rect,
337  /// The line under text an input method is composing.
338  pub underline: &'a [Rect],
339}
340
341/// Laid-out text, ready to draw. Lines can stick out of the node's
342/// rectangle when it is too small for them; draw them unclipped, as CSS
343/// does. The window's damage covers them.
344pub struct TextView<'a> {
345  text: &'a TextNode,
346  color: Color,
347  underline: bool,
348  strikethrough: bool,
349  /// From which line and byte to which the glyphs take a field's
350  /// selected text color, and the color.
351  selected: Option<(Place, Place, Color)>,
352}
353
354/// A buffer line and a byte in it.
355type Place = (usize, usize);
356
357impl<'a> TextView<'a> {
358  /// The text itself.
359  pub fn content(&self) -> &'a str {
360    &self.text.content
361  }
362
363  /// The cosmic-text buffer layout measured, for drawing glyphs from.
364  pub fn buffer(&self) -> &'a Buffer {
365    &self.text.buffer
366  }
367
368  /// The lines to draw: the buffer's lines, at most `max_lines`. Glyph
369  /// positions are relative to [`origin`](Self::origin).
370  pub fn runs(&self) -> impl Iterator<Item = TextRun<'a>> + 'a {
371    self.text.runs()
372  }
373
374  /// The top-left corner of the first line, in window coordinates.
375  pub fn origin(&self) -> Point {
376    self.text.origin
377  }
378
379  /// The color to draw in, inherited if the text's own style doesn't set
380  /// one.
381  pub fn color(&self) -> Color {
382    self.color
383  }
384
385  /// The span of a rich text that `glyph`, on the run of buffer line
386  /// `line`, belongs to, if any. The ellipsis belongs to none, though
387  /// cosmic-text gives it the first span's color.
388  pub fn span(&self, line: usize, glyph: &LayoutGlyph) -> Option<&'a Span> {
389    let index = self.text.glyph_span(line, glyph)?;
390    self.text.spans.get(index)
391  }
392
393  /// Whether `glyph`, on the run of buffer line `line`, belongs to a
394  /// link drawn lit, because the pointer is over it or the keyboard focus
395  /// is on it: underlined, and in
396  /// [`link_hover_color`](Self::link_hover_color) if the text has one.
397  pub fn glyph_lit(&self, line: usize, glyph: &LayoutGlyph) -> bool {
398    let text = self.text;
399    (text.hovered_link.is_some() || text.focused_link.is_some())
400      && text
401        .glyph_span(line, glyph)
402        .is_some_and(|index| text.lit(index))
403  }
404
405  /// The color a lit link is drawn in; without one it keeps its own.
406  pub fn link_hover_color(&self) -> Option<Color> {
407    self.text.link_hover_color
408  }
409
410  /// The color `glyph`, on the run of buffer line `line`, is drawn in
411  /// because it is selected in a field with a selected text color, over
412  /// any span or link color.
413  pub fn selected_color(&self, line: usize, glyph: &LayoutGlyph) -> Option<Color> {
414    let (start, end, color) = self.selected?;
415    let at = (line, glyph.start);
416    (start <= at && at < end).then_some(color)
417  }
418
419  /// Whether to draw a line under the glyphs, in the text's color.
420  pub fn underline(&self) -> bool {
421    self.underline
422  }
423
424  /// Whether to draw a line through the glyphs, in the text's color.
425  pub fn strikethrough(&self) -> bool {
426    self.strikethrough
427  }
428
429  /// Where a selectable text's selection shows, in window coordinates,
430  /// to be drawn behind it: a rectangle for each line it covers, or more
431  /// where right-to-left and left-to-right text mix.
432  pub fn selection(&self) -> Vec<Rect> {
433    text_selection(self.text).map_or_else(Vec::new, |range| highlights(self.text, range))
434  }
435}
436
437/// An icon, ready to draw.
438pub struct IconView<'a> {
439  /// What to show.
440  pub source: &'a IconSource,
441  /// What to show when `source` can't be loaded.
442  pub fallback: Option<&'a IconSource>,
443  /// Where: a square of the icon's size, centered in the node.
444  pub rect: Rect,
445  /// The color its pixels are painted in, keeping their alpha.
446  pub tint: Option<Color>,
447}
448
449/// An image, ready to draw.
450pub struct ImageView<'a> {
451  /// Names the image, so a renderer can keep a GIF's playback and the
452  /// platform repaint it with [`Window::repaint_image`](crate::Window::repaint_image).
453  pub id: u64,
454  /// What to show: a file, an icon name looked up in the theme at the
455  /// box's larger side, or raw pixels.
456  pub source: &'a IconSource,
457  /// Where: a box of the image's size, centered in the node.
458  pub rect: Rect,
459  /// How the picture fills the box.
460  pub fit: Fit,
461  /// What the picture is drawn through.
462  pub filters: ImageFilters,
463  /// Whether a GIF plays; paused, it stays on its frame.
464  pub playing: bool,
465  /// How a new source comes in. With one other than none, a source that
466  /// can't be loaded shows the last one that could.
467  pub transition: ImageTransition,
468  /// While a transition runs: the source it leaves and how far along it is,
469  /// eased, from 0 (all old) to 1 (all new); an easing that overshoots
470  /// may stray past either end.
471  pub leaving: Option<(&'a IconSource, f32)>,
472}
473
474/// A screencopy view's frame, ready to draw.
475pub struct CaptureView<'a> {
476  /// Names the view, so a cache can keep its frame scaled to its box.
477  pub id: u64,
478  /// The frame last captured.
479  pub frame: &'a CaptureFrame,
480  /// Where: the view's content box.
481  pub rect: Rect,
482  /// How the frame fills the box.
483  pub fit: Fit,
484  /// The part of the frame shown, in the source's logical pixels; `None`
485  /// for all of it.
486  pub crop: Option<Rect>,
487}