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