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          rect: icon_rect(self.node.content, icon.size),
159          tint: icon.tint,
160        }),
161        None => Content::None,
162      },
163      NodeKind::Input(input) => {
164        let color = self.inherited_color();
165        let color = if input.showing_placeholder() {
166          Color::rgba(color.r, color.g, color.b, color.a / 2)
167        } else {
168          color
169        };
170        Content::Input(InputView {
171          text: TextView {
172            text: &input.text,
173            color,
174            underline: self.inherited(|style| style.underline) == Some(true),
175            strikethrough: self.inherited(|style| style.strikethrough) == Some(true),
176          },
177          // An input method may ask for no caret while it composes.
178          caret: (input.focused
179            && !matches!(&input.preedit, Some(preedit) if preedit.cursor.is_none()))
180          .then_some(input.caret),
181          selection: if input.focused { &input.selection } else { &[] },
182          area: input.area,
183          underline: &input.underline,
184        })
185      }
186      NodeKind::Image(image) => match &image.source {
187        Some(path) => Content::Image(ImageView {
188          id: image.id,
189          path,
190          rect: centered(self.node.content, image.width, image.height),
191          fit: image.fit,
192          filters: image.filters,
193          playing: image.playing,
194          transition: image.transition,
195          leaving: image
196            .leaving
197            .as_ref()
198            .map(|leaving| (leaving.source.as_path(), leaving.t)),
199        }),
200        None => Content::None,
201      },
202      NodeKind::Capture(capture) => match &capture.frame {
203        Some(frame) => Content::Capture(CaptureView {
204          id: capture.id,
205          frame,
206          rect: self.node.content,
207          fit: capture.fit,
208        }),
209        None => Content::None,
210      },
211      NodeKind::Canvas(canvas) => Content::Canvas(CanvasView {
212        ops: &canvas.ops,
213        rect: self.node.rect.unwrap_or_default(),
214      }),
215      _ => Content::None,
216    }
217  }
218
219  /// The color of the nearest node, starting with this one, whose style
220  /// sets one.
221  fn inherited_color(&self) -> Color {
222    self
223      .inherited(|style| style.color)
224      .unwrap_or(DEFAULT_TEXT_COLOR)
225  }
226
227  /// `field` of the nearest node, starting with this one, whose style
228  /// sets it.
229  fn inherited<T>(&self, field: impl Fn(&Style) -> Option<T>) -> Option<T> {
230    let mut id = Some(self.id);
231    while let Some(current) = id {
232      if let Some(value) = self
233        .tree
234        .node(current)
235        .and_then(|node| field(&node.shown_style()))
236      {
237        return Some(value);
238      }
239      id = self.tree.taffy.parent(current);
240    }
241    None
242  }
243}
244
245/// What a node draws besides its background and border.
246pub enum Content<'a> {
247  /// Nothing.
248  None,
249  /// Text.
250  Text(TextView<'a>),
251  /// An icon.
252  Icon(IconView<'a>),
253  /// An image.
254  Image(ImageView<'a>),
255  /// A screencopy view's frame.
256  Capture(CaptureView<'a>),
257  /// A text field.
258  Input(InputView<'a>),
259  /// A canvas's drawing.
260  Canvas(CanvasView<'a>),
261}
262
263/// A canvas's drawing, ready to draw: each op in order, in logical pixels
264/// from the corner of `rect`, cut to it and its style's rounded corners.
265pub struct CanvasView<'a> {
266  /// What the paint closure drew at its last run that didn't panic.
267  pub ops: &'a [CanvasOp],
268  /// Where: the canvas's rectangle.
269  pub rect: Rect,
270}
271
272/// A text field, ready to draw: the selection behind the text, then the
273/// text, then the caret.
274pub struct InputView<'a> {
275  /// What the field shows; a placeholder comes in half its color.
276  pub text: TextView<'a>,
277  /// The caret, while the field has the keyboard.
278  pub caret: Option<Rect>,
279  /// The selection, while the field has the keyboard: one span, or more
280  /// where right-to-left and left-to-right text mix.
281  pub selection: &'a [Rect],
282  /// The content box everything is cut to.
283  pub area: Rect,
284  /// The line under text an input method is composing.
285  pub underline: &'a [Rect],
286}
287
288/// Laid-out text, ready to draw. Lines can stick out of the node's
289/// rectangle when it is too small for them; draw them unclipped, as CSS
290/// does. The window's damage covers them.
291pub struct TextView<'a> {
292  text: &'a TextNode,
293  color: Color,
294  underline: bool,
295  strikethrough: bool,
296}
297
298impl<'a> TextView<'a> {
299  /// The text itself.
300  pub fn content(&self) -> &'a str {
301    &self.text.content
302  }
303
304  /// The cosmic-text buffer layout measured, for drawing glyphs from.
305  pub fn buffer(&self) -> &'a Buffer {
306    &self.text.buffer
307  }
308
309  /// The lines to draw: the buffer's lines, at most `max_lines`. Glyph
310  /// positions are relative to [`origin`](Self::origin).
311  pub fn runs(&self) -> impl Iterator<Item = TextRun<'a>> + 'a {
312    self.text.runs()
313  }
314
315  /// The top-left corner of the first line, in window coordinates.
316  pub fn origin(&self) -> Point {
317    self.text.origin
318  }
319
320  /// The color to draw in, inherited if the text's own style doesn't set
321  /// one.
322  pub fn color(&self) -> Color {
323    self.color
324  }
325
326  /// The span of a rich text that `glyph`, on the run of buffer line
327  /// `line`, belongs to, if any. The ellipsis belongs to none, though
328  /// cosmic-text gives it the first span's color.
329  pub fn span(&self, line: usize, glyph: &LayoutGlyph) -> Option<&'a Span> {
330    let index = self.text.glyph_span(line, glyph)?;
331    self.text.spans.get(index)
332  }
333
334  /// Whether `glyph`, on the run of buffer line `line`, belongs to a
335  /// link drawn lit, because the pointer is over it or the keyboard focus
336  /// is on it: underlined, and in
337  /// [`link_hover_color`](Self::link_hover_color) if the text has one.
338  pub fn glyph_lit(&self, line: usize, glyph: &LayoutGlyph) -> bool {
339    let text = self.text;
340    (text.hovered_link.is_some() || text.focused_link.is_some())
341      && text
342        .glyph_span(line, glyph)
343        .is_some_and(|index| text.lit(index))
344  }
345
346  /// The color a lit link is drawn in; without one it keeps its own.
347  pub fn link_hover_color(&self) -> Option<Color> {
348    self.text.link_hover_color
349  }
350
351  /// Whether to draw a line under the glyphs, in the text's color.
352  pub fn underline(&self) -> bool {
353    self.underline
354  }
355
356  /// Whether to draw a line through the glyphs, in the text's color.
357  pub fn strikethrough(&self) -> bool {
358    self.strikethrough
359  }
360
361  /// Where a selectable text's selection shows, in window coordinates,
362  /// to be drawn behind it: a rectangle for each line it covers, or more
363  /// where right-to-left and left-to-right text mix.
364  pub fn selection(&self) -> Vec<Rect> {
365    text_selection(self.text).map_or_else(Vec::new, |range| highlights(self.text, range))
366  }
367}
368
369/// An icon, ready to draw.
370pub struct IconView<'a> {
371  /// What to show.
372  pub source: &'a IconSource,
373  /// Where: a square of the icon's size, centered in the node.
374  pub rect: Rect,
375  /// The color its pixels are painted in, keeping their alpha.
376  pub tint: Option<Color>,
377}
378
379/// An image, ready to draw.
380pub struct ImageView<'a> {
381  /// Names the image, so a renderer can keep a GIF's playback and the
382  /// platform repaint it with [`Window::repaint_image`](crate::Window::repaint_image).
383  pub id: u64,
384  /// The file to show.
385  pub path: &'a Path,
386  /// Where: a box of the image's size, centered in the node.
387  pub rect: Rect,
388  /// How the picture fills the box.
389  pub fit: Fit,
390  /// What the picture is drawn through.
391  pub filters: ImageFilters,
392  /// Whether a GIF plays; paused, it stays on its frame.
393  pub playing: bool,
394  /// How a new source comes in. With one other than none, a source that
395  /// can't be loaded shows the last one that could.
396  pub transition: ImageTransition,
397  /// While a transition runs: the file it leaves and how far along it is,
398  /// eased, from 0 (all old) to 1 (all new); an easing that overshoots
399  /// may stray past either end.
400  pub leaving: Option<(&'a Path, f32)>,
401}
402
403/// A screencopy view's frame, ready to draw.
404pub struct CaptureView<'a> {
405  /// Names the view, so a cache can keep its frame scaled to its box.
406  pub id: u64,
407  /// The frame last captured.
408  pub frame: &'a CaptureFrame,
409  /// Where: the view's content box.
410  pub rect: Rect,
411  /// How the frame fills the box.
412  pub fit: Fit,
413}