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