devpage_design/design/mod.rs
1//! A design as it is held while it is shown: its scene, how many nodes use
2//! each of its files, and its drawing in each theme a caller asks for —
3//! every one brought along by each change to the scene, the damage it does
4//! to their tiles kept until it is taken. It answers what a canvas or a PNG
5//! asks of a drawing: its size, the interaction at a point, the tiles a
6//! view needs, and an area to paint — rounded first where an update left a
7//! run's children a fraction of a pixel off, so what is painted there is a
8//! fresh drawing's.
9//!
10//! **One rule for a scene that can't be drawn** — its images too many for
11//! the GPU's atlas. The design keeps showing its last good drawing in that
12//! theme: the drawing of the last scene that could be drawn, made afresh the
13//! moment the scene stopped being drawable, which every tile, size and
14//! click is answered from meanwhile — a tile no one painted before, after a
15//! pan or a zoom, too — and which no damage reaches; why is
16//! [`Design::problem`]. The drawing that follows the scene is kept beside
17//! it, so the next change updates it at the change's cost, and the change
18//! that makes the scene drawable again damages every tile of that theme.
19//!
20//! It holds no renderer — a server shares one between its designs, a canvas
21//! has its own — and has no mode: the browser draws the theme it shows when
22//! it is shown, the server every theme the design has, at once.
23
24use kurbo::Rect as KRect;
25use peniko::ImageData;
26
27use crate::display::{Frame, List};
28use crate::proto;
29use crate::render::{Damage, Drawing, Renderer, Undrawable};
30use crate::scene::{self, Applied, Edits, Scene, Theme, Uses};
31use crate::tiles::{self, Level, View};
32
33/// A design's scene — its one copy — the files it uses, and its drawing in
34/// each theme it was asked to draw in.
35pub struct Design {
36 /// The scene, the design's one copy of it.
37 scene: Scene,
38 /// How many nodes use each image and font file, kept in step with `scene`
39 /// by every edit.
40 uses: Uses,
41 /// Light, then dark.
42 themes: [Shown; 2],
43 /// What changed since it was last taken, per theme.
44 damage: Vec<(Theme, Damage)>,
45}
46
47/// One theme of a design.
48#[derive(Default)]
49struct Shown {
50 /// The scene laid out and made into its display list in the theme;
51 /// `None` before it is first asked for, or when it was let go.
52 drawing: Option<Drawing>,
53 /// A whole scene arrived since `drawing` was made: it is made afresh
54 /// when next asked for, sharing its images' blobs where it paints the
55 /// same ones.
56 stale: bool,
57 /// Why the scene can't be drawn in the theme. Nothing is painted from
58 /// `drawing` meanwhile.
59 broken: Option<Undrawable>,
60 /// While the scene can't be drawn: the drawing of the last scene that
61 /// could be, in the theme — what is shown meanwhile. `None` otherwise,
62 /// or when no scene could be drawn in the theme yet.
63 good: Option<Drawing>,
64}
65
66/// Every theme, in the order `themes` holds them.
67const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
68
69/// Where `theme` sits in [`THEMES`] and in a design's `themes`.
70fn index(theme: Theme) -> usize {
71 match theme {
72 Theme::Light => 0,
73 Theme::Dark => 1,
74 }
75}
76
77impl Design {
78 /// `scene`, drawn in no theme yet: every tile of both is stale.
79 pub fn new(scene: Scene) -> Design {
80 Design {
81 uses: Uses::of(&scene.root),
82 scene,
83 themes: Default::default(),
84 damage: THEMES.iter().map(|&t| (t, Damage::All)).collect(),
85 }
86 }
87
88 /// The scene.
89 pub fn scene(&self) -> &Scene {
90 &self.scene
91 }
92
93 /// The scene replaced whole — a watch stream sent all of it again. Every
94 /// tile of both themes is stale, and each drawing is made afresh when
95 /// next asked for; until one can be, the last good drawing in its theme
96 /// is what is shown — rounded first where updates left it unrounded,
97 /// while the scene it shows is still at hand.
98 pub fn replace(&mut self, renderer: &mut Renderer, scene: Scene) {
99 for shown in &mut self.themes {
100 if shown.broken.is_some() {
101 // The last good drawing stays; the one that followed the
102 // scene before goes with it.
103 shown.drawing = None;
104 } else if let Some(drawing) = shown.drawing.as_mut().filter(|_| !shown.stale) {
105 drawing.prepare(renderer, &self.scene, everywhere());
106 }
107 shown.stale = true;
108 shown.broken = None;
109 }
110 self.uses = Uses::of(&scene.root);
111 self.scene = scene;
112 self.damage.extend(THEMES.iter().map(|&t| (t, Damage::All)));
113 }
114
115 /// Applies `edits` to the scene and brings every drawing along by what
116 /// they did — at the cost of the edits, never the scene's — or says why
117 /// they don't apply, leaving everything as it was. A theme whose scene
118 /// they leave undrawable has its last good drawing made, from the scene
119 /// before them: what it shows until a change makes the scene drawable
120 /// again.
121 pub fn apply(&mut self, renderer: &mut Renderer, edits: &Edits) -> Result<Applied, String> {
122 let (applied, undo) = scene::applied(&mut self.scene, &mut self.uses, edits)?;
123 let mut breaking = Vec::new();
124 for theme in THEMES {
125 let shown = &mut self.themes[index(theme)];
126 let Some(drawing) = shown.drawing.as_mut().filter(|_| !shown.stale) else {
127 // Made afresh, from this scene, when next asked for.
128 shown.broken = None;
129 continue;
130 };
131 match drawing.update(renderer, &self.scene, &applied) {
132 Ok(damage) => {
133 // Back from a scene that couldn't be drawn: its tiles
134 // show the last one that could.
135 let damage = if shown.broken.take().is_some() {
136 shown.good = None;
137 Damage::All
138 } else {
139 damage
140 };
141 self.damage.push((theme, damage));
142 }
143 Err(undrawable) => {
144 if shown.broken.replace(undrawable).is_none() {
145 breaking.push(theme);
146 }
147 }
148 }
149 }
150 if !breaking.is_empty() {
151 // The scene before the edits, which could be drawn, drawn afresh
152 // in each theme they broke — the tiles painted already show it,
153 // so none is damaged — and the edits applied to it again.
154 undo.undo(&mut self.scene, &mut self.uses);
155 for theme in breaking {
156 self.themes[index(theme)].good = renderer.drawing(&self.scene, theme, None).ok();
157 }
158 scene::apply(&mut self.scene, &mut self.uses, edits)
159 .expect("edits apply again to the scene they were just undone from");
160 }
161 Ok(applied)
162 }
163
164 /// Applies a watch stream's patch: [`Design::apply`] with the edits it
165 /// carries, each image and font file the scene holds already taken from
166 /// it.
167 pub fn patch(&mut self, renderer: &mut Renderer, patch: &proto::Patch) -> Result<(), String> {
168 let edits = crate::wire::edits(patch, &self.scene)?;
169 self.apply(renderer, &edits).map(|_| ())
170 }
171
172 /// Draws the scene in `theme`, if it isn't: made afresh the first time,
173 /// or after a whole scene — painting the last drawing's images, in
174 /// either theme, when it paints the same ones, so the GPU keeps its
175 /// atlas — or why it can't be drawn. A scene that couldn't be drawn
176 /// isn't tried again until it changes.
177 pub fn draw(&mut self, renderer: &mut Renderer, theme: Theme) -> Result<(), &Undrawable> {
178 let i = index(theme);
179 let shown = &self.themes[i];
180 if shown.drawing.is_some() && !shown.stale || shown.broken.is_some() {
181 return match &self.themes[i].broken {
182 Some(undrawable) => Err(undrawable),
183 None => Ok(()),
184 };
185 }
186 let last = self.themes[i]
187 .drawing
188 .take()
189 .or_else(|| self.themes[1 - i].drawing.take());
190 let made = {
191 let after = last.as_ref().or(self.themes[i].good.as_ref());
192 renderer.drawing(&self.scene, theme, after)
193 };
194 // The other theme's drawing, taken to share its images' blobs, goes
195 // back.
196 let last = match last {
197 Some(other) if other.theme() != theme => {
198 self.themes[1 - i].drawing = Some(other);
199 None
200 }
201 last => last,
202 };
203 let shown = &mut self.themes[i];
204 match made {
205 // Its tiles went stale when its scene arrived; any painted since
206 // were the last good drawing's.
207 Ok(drawing) => {
208 shown.drawing = Some(drawing);
209 shown.stale = false;
210 if shown.good.take().is_some() {
211 self.damage.push((theme, Damage::All));
212 }
213 Ok(())
214 }
215 // The last drawing in the theme, of the scene before this one —
216 // which could be drawn, or the last good one would be kept
217 // already — is what is shown until a scene can be drawn again.
218 Err(undrawable) => {
219 if shown.good.is_none() {
220 shown.good = last;
221 }
222 Err(shown.broken.insert(undrawable))
223 }
224 }
225 }
226
227 /// Lets the drawing in `theme` go: the design isn't shown in it.
228 pub fn forget(&mut self, theme: Theme) {
229 self.themes[index(theme)] = Shown::default();
230 self.damage.retain(|(t, _)| *t != theme);
231 }
232
233 /// Why the scene can't be drawn in `theme`, when it can't.
234 pub fn problem(&self, theme: Theme) -> Option<&Undrawable> {
235 self.themes[index(theme)].broken.as_ref()
236 }
237
238 /// The damage since it was last taken, per theme, in the order it was
239 /// done.
240 pub fn take_damage(&mut self) -> Vec<(Theme, Damage)> {
241 std::mem::take(&mut self.damage)
242 }
243
244 /// The drawing shown in `theme`, drawn if it isn't — the last good one
245 /// while the scene can't be drawn — or `None` when there is none to
246 /// show: no scene could be drawn in it yet.
247 pub fn drawing(&mut self, renderer: &mut Renderer, theme: Theme) -> Option<&Drawing> {
248 let drawn = self.draw(renderer, theme).is_ok();
249 let shown = &self.themes[index(theme)];
250 if drawn {
251 shown.drawing.as_ref()
252 } else {
253 shown.good.as_ref()
254 }
255 }
256
257 /// The shown drawing's area in `theme`: its top-left and size, in the
258 /// design's coordinates.
259 pub fn area(&mut self, renderer: &mut Renderer, theme: Theme) -> Option<Frame> {
260 self.drawing(renderer, theme).map(Drawing::area)
261 }
262
263 /// The interaction of the topmost node at `(x, y)` — in the design's
264 /// coordinates — that has one, where its clipping frames show it.
265 pub fn action_at(
266 &mut self,
267 renderer: &mut Renderer,
268 theme: Theme,
269 x: f64,
270 y: f64,
271 ) -> Option<&str> {
272 let drawing = self.prepared(renderer, theme, KRect::new(x, y, x, y))?;
273 drawing.action_at(x as f32, y as f32)
274 }
275
276 /// The tiles `view` needs at its own zoom's level, nearest its middle
277 /// first — of the last good drawing while the scene can't be drawn.
278 pub fn view_tiles(
279 &mut self,
280 renderer: &mut Renderer,
281 theme: Theme,
282 view: &View,
283 ) -> Vec<(u32, u32)> {
284 let Some(a) = self.area(renderer, theme) else {
285 return Vec::new();
286 };
287 let area = KRect::new(
288 a.x as f64,
289 a.y as f64,
290 (a.x + a.width) as f64,
291 (a.y + a.height) as f64,
292 );
293 view.tiles(area, Level::of(view.zoom))
294 }
295
296 /// The images the shown drawing in `theme` paints, in the order it first
297 /// paints them: what the GPU's atlas holds for it.
298 pub fn images(&mut self, renderer: &mut Renderer, theme: Theme) -> Option<&[ImageData]> {
299 self.drawing(renderer, theme).map(|d| d.images.as_slice())
300 }
301
302 /// The display list to paint tile `(col, row)` at `scale` from, in
303 /// `theme` — the last good drawing's while the scene can't be drawn.
304 pub fn tile(
305 &mut self,
306 renderer: &mut Renderer,
307 theme: Theme,
308 scale: f64,
309 col: u32,
310 row: u32,
311 ) -> Option<&List> {
312 self.painted(renderer, theme, |list| {
313 tiles::tile_rect(list, scale, col, row)
314 })
315 }
316
317 /// The display list to paint a strip of the drawing at 1× from, in
318 /// `theme`: [`tiles::TILE`] pixels wide at tile column `col`, `rows`
319 /// tall from pixel row `y` — a piece of a PNG band too wide for whole
320 /// tiles.
321 pub fn strip(
322 &mut self,
323 renderer: &mut Renderer,
324 theme: Theme,
325 col: u32,
326 y: u32,
327 rows: u32,
328 ) -> Option<&List> {
329 self.painted(renderer, theme, |list| {
330 let (x0, y0) = (list.area.x as f64, list.area.y as f64);
331 KRect::new(
332 x0 + (col * tiles::TILE) as f64,
333 y0 + y as f64,
334 x0 + ((col + 1) * tiles::TILE) as f64,
335 y0 + (y + rows) as f64,
336 )
337 })
338 }
339
340 /// The display list to paint the whole drawing from, in `theme`.
341 pub fn whole(&mut self, renderer: &mut Renderer, theme: Theme) -> Option<&List> {
342 self.painted(renderer, theme, |_| everywhere())
343 }
344
345 /// The shown drawing's display list in `theme`, rounded where `area` —
346 /// in the design's coordinates, from the list — is painted.
347 fn painted(
348 &mut self,
349 renderer: &mut Renderer,
350 theme: Theme,
351 area: impl FnOnce(&List) -> KRect,
352 ) -> Option<&List> {
353 let rect = area(&self.drawing(renderer, theme)?.list);
354 self.prepared(renderer, theme, rect).map(|d| &d.list)
355 }
356
357 /// The shown drawing in `theme` with every run child in `rect` — in the
358 /// design's coordinates — rounded where the runs now place it: what is
359 /// read there is a fresh drawing's. A last good drawing needs none: it
360 /// was made afresh, or rounded whole when its scene was replaced.
361 fn prepared(&mut self, renderer: &mut Renderer, theme: Theme, rect: KRect) -> Option<&Drawing> {
362 if self.draw(renderer, theme).is_err() {
363 return self.themes[index(theme)].good.as_ref();
364 }
365 let drawing = self.themes[index(theme)].drawing.as_mut()?;
366 drawing.prepare(renderer, &self.scene, rect);
367 Some(drawing)
368 }
369}
370
371/// An area holding all of any drawing.
372fn everywhere() -> KRect {
373 KRect::new(-1e12, -1e12, 1e12, 1e12)
374}
375
376#[cfg(test)]
377impl Design {
378 /// The drawing in `theme` as it is held — none made, nothing rounded —
379 /// for a test to look inside.
380 pub(crate) fn held(&mut self, theme: Theme) -> &mut Drawing {
381 self.themes[index(theme)].drawing.as_mut().expect("drawn")
382 }
383}
384
385#[cfg(test)]
386mod tests;