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, LayoutRun};
7
8use crate::canvas::CanvasOp;
9use crate::geometry::{Affine, Point, Rect, Size};
10use crate::image::ImageTransition;
11use crate::screencopy::CaptureFrame;
12use crate::style::{Color, Style};
13use crate::text::TextNode;
14use crate::tree::{Node, NodeId, NodeKind, Tree, centered, icon_rect};
15use crate::widgets::{Fit, IconSource, ImageFilters};
16
17/// The color text uses when no ancestor sets one.
18const DEFAULT_TEXT_COLOR: Color = Color::rgb(0, 0, 0);
19
20/// A window's laid-out tree, borrowed for reading. Get one from
21/// [`Window::view`](crate::Window::view).
22pub struct WindowView<'w> {
23 tree: Ref<'w, Tree>,
24}
25
26impl<'w> WindowView<'w> {
27 pub(crate) fn new(tree: Ref<'w, Tree>) -> WindowView<'w> {
28 WindowView { tree }
29 }
30
31 /// The window's size in logical pixels.
32 pub fn size(&self) -> Size {
33 self.tree.size
34 }
35
36 /// The window's root node, which has the window's style and its child.
37 pub fn root(&self) -> NodeView<'_> {
38 NodeView::new(&self.tree, self.tree.root)
39 .expect("invariant: the root node exists while the tree does")
40 }
41}
42
43/// One node of a laid-out window: a widget, or the window itself at the
44/// root. Draw it, then its [`children`](Self::children) in order, so later
45/// ones are on top.
46#[derive(Clone, Copy)]
47pub struct NodeView<'a> {
48 tree: &'a Tree,
49 id: NodeId,
50 node: &'a Node,
51}
52
53impl<'a> NodeView<'a> {
54 fn new(tree: &'a Tree, id: NodeId) -> Option<NodeView<'a>> {
55 let node = tree.node(id)?;
56 Some(NodeView { tree, id, node })
57 }
58
59 /// The widget type, such as `"Row"`, or `"PanelWindow"` at the root.
60 pub fn name(&self) -> &'static str {
61 self.node.name
62 }
63
64 /// The widget path, such as `PanelWindow[DP-1]/Row/Button[2]`.
65 pub fn path(&self) -> &'a str {
66 &self.node.path
67 }
68
69 /// The rectangle from the last layout, in window coordinates. Empty
70 /// before the first layout.
71 pub fn rect(&self) -> Rect {
72 self.node.rect.unwrap_or_default()
73 }
74
75 /// The area the node and everything inside it painted at the last
76 /// layout: its rectangle, text and icons that overflow it, and its
77 /// descendants' bounds, moved by its [`transform`](Self::transform) into
78 /// its parent's coordinates. Nothing outside it needs drawing for this
79 /// node.
80 pub fn bounds(&self) -> Rect {
81 self.node.bounds
82 }
83
84 /// [`bounds`](Self::bounds) before the node's own transform, in its own
85 /// coordinates: what a layer drawn for the transform must hold. The
86 /// same as `bounds` when it has none.
87 pub fn inner_bounds(&self) -> Rect {
88 self.node.inner_bounds
89 }
90
91 /// How the node's style moves it and everything inside it where it is
92 /// drawn, from its own coordinates, which its rectangle and its
93 /// children's are in, into its parent's. `None` when it doesn't. The
94 /// whole subtree is drawn as one layer through it.
95 pub fn transform(&self) -> Option<Affine> {
96 self.node.transform
97 }
98
99 /// The style in effect, with a button's hover and pressed styles laid
100 /// over its own. Inherited fields aren't filled in;
101 /// [`TextView::color`] has the color text is drawn in.
102 pub fn style(&self) -> Style {
103 self.node.shown_style()
104 }
105
106 /// The children, in drawing order: by their style's `z`, lowest
107 /// first, and in child order where it is equal.
108 pub fn children(&self) -> impl Iterator<Item = NodeView<'a>> + 'a {
109 let tree = self.tree;
110 tree
111 .drawn_children(self.id)
112 .into_iter()
113 .filter_map(move |id| NodeView::new(tree, id))
114 }
115
116 /// Whether the node cuts its children to the inside of its border: a
117 /// clipping style or a scroll view.
118 pub fn clips(&self) -> bool {
119 self.node.clips()
120 }
121
122 /// A scroll view's scroll bar handle and the style to draw it with,
123 /// over its children, while it shows one.
124 pub fn scroll_bar(&self) -> Option<(Rect, Style)> {
125 match &self.node.kind {
126 NodeKind::Scroll(scroll) => Some((scroll.handle?.1, scroll.bar?)),
127 _ => None,
128 }
129 }
130
131 /// What the node draws besides its background and border.
132 pub fn content(&self) -> Content<'a> {
133 match &self.node.kind {
134 NodeKind::Text(text) => Content::Text(TextView {
135 text,
136 color: self.inherited_color(),
137 }),
138 NodeKind::Icon(icon) => match &icon.source {
139 Some(source) => Content::Icon(IconView {
140 source,
141 rect: icon_rect(self.node.content, icon.size),
142 tint: icon.tint,
143 }),
144 None => Content::None,
145 },
146 NodeKind::Input(input) => {
147 let color = self.inherited_color();
148 let color = if input.showing_placeholder() {
149 Color::rgba(color.r, color.g, color.b, color.a / 2)
150 } else {
151 color
152 };
153 Content::Input(InputView {
154 text: TextView {
155 text: &input.text,
156 color,
157 },
158 // An input method may ask for no caret while it composes.
159 caret: (input.focused
160 && !matches!(&input.preedit, Some(preedit) if preedit.cursor.is_none()))
161 .then_some(input.caret),
162 selection: if input.focused { &input.selection } else { &[] },
163 area: input.area,
164 underline: &input.underline,
165 })
166 }
167 NodeKind::Image(image) => match &image.source {
168 Some(path) => Content::Image(ImageView {
169 id: image.id,
170 path,
171 rect: centered(self.node.content, image.width, image.height),
172 fit: image.fit,
173 filters: image.filters,
174 playing: image.playing,
175 transition: image.transition,
176 leaving: image
177 .leaving
178 .as_ref()
179 .map(|leaving| (leaving.source.as_path(), leaving.t)),
180 }),
181 None => Content::None,
182 },
183 NodeKind::Capture(capture) => match &capture.frame {
184 Some(frame) => Content::Capture(CaptureView {
185 id: capture.id,
186 frame,
187 rect: self.node.content,
188 fit: capture.fit,
189 }),
190 None => Content::None,
191 },
192 NodeKind::Canvas(canvas) => Content::Canvas(CanvasView {
193 ops: &canvas.ops,
194 rect: self.node.rect.unwrap_or_default(),
195 }),
196 _ => Content::None,
197 }
198 }
199
200 /// The color of the nearest node, starting with this one, whose style
201 /// sets one.
202 fn inherited_color(&self) -> Color {
203 let mut id = Some(self.id);
204 while let Some(current) = id {
205 if let Some(color) = self
206 .tree
207 .node(current)
208 .and_then(|node| node.shown_style().color)
209 {
210 return color;
211 }
212 id = self.tree.taffy.parent(current);
213 }
214 DEFAULT_TEXT_COLOR
215 }
216}
217
218/// What a node draws besides its background and border.
219pub enum Content<'a> {
220 /// Nothing.
221 None,
222 /// Text.
223 Text(TextView<'a>),
224 /// An icon.
225 Icon(IconView<'a>),
226 /// An image.
227 Image(ImageView<'a>),
228 /// A screencopy view's frame.
229 Capture(CaptureView<'a>),
230 /// A text field.
231 Input(InputView<'a>),
232 /// A canvas's drawing.
233 Canvas(CanvasView<'a>),
234}
235
236/// A canvas's drawing, ready to draw: each op in order, in logical pixels
237/// from the corner of `rect`, cut to it and its style's rounded corners.
238pub struct CanvasView<'a> {
239 /// What the paint closure drew at its last run that didn't panic.
240 pub ops: &'a [CanvasOp],
241 /// Where: the canvas's rectangle.
242 pub rect: Rect,
243}
244
245/// A text field, ready to draw: the selection behind the text, then the
246/// text, then the caret.
247pub struct InputView<'a> {
248 /// What the field shows; a placeholder comes in half its color.
249 pub text: TextView<'a>,
250 /// The caret, while the field has the keyboard.
251 pub caret: Option<Rect>,
252 /// The selection, while the field has the keyboard: one span, or more
253 /// where right-to-left and left-to-right text mix.
254 pub selection: &'a [Rect],
255 /// The content box everything is cut to.
256 pub area: Rect,
257 /// The line under text an input method is composing.
258 pub underline: &'a [Rect],
259}
260
261/// Laid-out text, ready to draw. Lines can stick out of the node's
262/// rectangle when it is too small for them; draw them unclipped, as CSS
263/// does. The window's damage covers them.
264pub struct TextView<'a> {
265 text: &'a TextNode,
266 color: Color,
267}
268
269impl<'a> TextView<'a> {
270 /// The text itself.
271 pub fn content(&self) -> &'a str {
272 &self.text.content
273 }
274
275 /// The cosmic-text buffer layout measured, for drawing glyphs from.
276 pub fn buffer(&self) -> &'a Buffer {
277 &self.text.buffer
278 }
279
280 /// The lines to draw: the buffer's lines, at most `max_lines`. Glyph
281 /// positions are relative to [`origin`](Self::origin).
282 pub fn runs(&self) -> impl Iterator<Item = LayoutRun<'a>> + 'a {
283 self.text.runs()
284 }
285
286 /// The top-left corner of the first line, in window coordinates.
287 pub fn origin(&self) -> Point {
288 self.text.origin
289 }
290
291 /// The color to draw in, inherited if the text's own style doesn't set
292 /// one.
293 pub fn color(&self) -> Color {
294 self.color
295 }
296}
297
298/// An icon, ready to draw.
299pub struct IconView<'a> {
300 /// What to show.
301 pub source: &'a IconSource,
302 /// Where: a square of the icon's size, centered in the node.
303 pub rect: Rect,
304 /// The color its pixels are painted in, keeping their alpha.
305 pub tint: Option<Color>,
306}
307
308/// An image, ready to draw.
309pub struct ImageView<'a> {
310 /// Names the image, so a renderer can keep a GIF's playback and the
311 /// platform repaint it with [`Window::repaint_image`](crate::Window::repaint_image).
312 pub id: u64,
313 /// The file to show.
314 pub path: &'a Path,
315 /// Where: a box of the image's size, centered in the node.
316 pub rect: Rect,
317 /// How the picture fills the box.
318 pub fit: Fit,
319 /// What the picture is drawn through.
320 pub filters: ImageFilters,
321 /// Whether a GIF plays; paused, it stays on its frame.
322 pub playing: bool,
323 /// How a new source comes in. With one other than none, a source that
324 /// can't be loaded shows the last one that could.
325 pub transition: ImageTransition,
326 /// While a transition runs: the file it leaves and how far along it is,
327 /// eased, from 0 (all old) to 1 (all new); an easing that overshoots
328 /// may stray past either end.
329 pub leaving: Option<(&'a Path, f32)>,
330}
331
332/// A screencopy view's frame, ready to draw.
333pub struct CaptureView<'a> {
334 /// Names the view, so a cache can keep its frame scaled to its box.
335 pub id: u64,
336 /// The frame last captured.
337 pub frame: &'a CaptureFrame,
338 /// Where: the view's content box.
339 pub rect: Rect,
340 /// How the frame fills the box.
341 pub fit: Fit,
342}