Skip to main content

devpage_core/
designs.rs

1//! The design store: every design asked for kept resolved in memory and
2//! resolved again only when a save touched what it read, its problems and
3//! its PNG. The canvas page that shows a design is `page::canvas`; the watch
4//! stream that keeps it current is the binary's, in `http::watch_stream`.
5
6use std::cell::RefCell;
7use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9use std::sync::{Arc, Mutex, MutexGuard};
10
11use devpage_design::display::List;
12use devpage_design::fonts::FontFile;
13use devpage_design::ids::{Parses, Remembering};
14use devpage_design::png::{Piece, write_bands};
15use devpage_design::proto;
16use devpage_design::render::Undrawable;
17use devpage_design::resolve::{Outcome, Resolution};
18use devpage_design::scene::{Applied, Edits, Holder, ImageFile};
19use devpage_design::tiles::{Cache, Key, Level, TILE, Tiled};
20use devpage_design::{Damage, Design, Files, Problem, Renderer, Scene, Theme, wire};
21
22use crate::folder::ServedFolder;
23
24/// What the store knows of a design without locking it: which version of
25/// its scene it shows or its problems, every file resolving it asked for —
26/// missing ones included, so creating one counts — and whether its own file
27/// is missing.
28#[derive(Clone, PartialEq)]
29struct Resolved {
30    /// The version of the design's scene it shows.
31    version: u64,
32    /// The design's problems; `None` when it has none.
33    problems: Option<Vec<Problem>>,
34    /// Every file resolving it asked for, sorted, missing ones included.
35    asked: Vec<String>,
36    /// The design's own file doesn't exist.
37    missing: bool,
38}
39
40/// A file as last read: its bytes, or `None` when it doesn't exist or lies
41/// outside the served folder. A folder's listing is kept the same way, under
42/// its path and a `/`, as the names of its files, one per line.
43struct Source {
44    /// The file's bytes, or the folder's listing; `None` when it doesn't exist or
45    /// lies outside the served folder.
46    bytes: Option<Vec<u8>>,
47    /// Which read of the store's this was, counting from one: a result made
48    /// from it is current only while the file is still this read.
49    read: u64,
50    /// Its canonical path from the top of the served folder, which is what the
51    /// watcher reports.
52    canonical: Option<String>,
53    /// The file decoded as an image, once a design shows it: forgotten with
54    /// the file, so a save decodes only the image that changed.
55    image: Option<Result<Arc<ImageFile>, String>>,
56    /// The file checked as a font, once a design's text is set in it:
57    /// forgotten with the file, like `image`.
58    font: Option<Result<Arc<FontFile>, String>>,
59}
60
61/// A design as the store keeps it: kept resolved — where each node of its
62/// scene came from — and held as a [`Design`], its one scene drawn in each
63/// theme it shows in; with that scene's version, its problems now, and the
64/// patches that brought the scene to its version, for the watch streams.
65#[derive(Default)]
66struct Kept {
67    /// What tells this design's tiles apart in the store's cache.
68    id: u64,
69    /// The scene's version: one more for each patch that changed it.
70    version: u64,
71    /// `None` before the design first resolves, or after the engine
72    /// panicked on it.
73    held: Option<Held>,
74    /// The design's problems now — resolving it, or drawing its scene.
75    problems: Option<Vec<Problem>>,
76    /// The last patches, each from the version before it: what a stream that
77    /// sent that version sends next.
78    log: std::collections::VecDeque<(u64, Arc<proto::Patch>)>,
79    /// Every file resolving the design asked for, sorted, missing ones included:
80    /// a save to any of them resolves it again.
81    asked: Vec<String>,
82    /// Whether the design's own file doesn't exist.
83    missing: bool,
84}
85
86/// A design resolved and held: what resolving it again starts from, and
87/// the design holding its last valid scene — the one copy of it.
88struct Held {
89    /// Where each node of the scene came from: what resolving again starts from.
90    resolution: Resolution,
91    /// The design holding the last valid scene.
92    design: Design,
93}
94
95/// A kept design as the holder of its scene, which resolving it again
96/// reads and brings across: each edit applied once, to the design, its
97/// drawings brought along under the store's renderer — locked only then,
98/// never while files are read.
99struct Bringing<'a> {
100    /// The design whose scene the edits are applied to.
101    design: &'a mut Design,
102    /// The store's renderer, locked only while edits are applied.
103    renderer: &'a Mutex<Renderer>,
104    #[cfg(test)]
105    applies: &'a std::sync::atomic::AtomicUsize,
106}
107
108impl Holder for Bringing<'_> {
109    fn scene(&self) -> &Scene {
110        self.design.scene()
111    }
112
113    fn apply(&mut self, edits: &Edits) -> Result<Applied, String> {
114        #[cfg(test)]
115        self.applies
116            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
117        self.design.apply(&mut lock(self.renderer), edits)
118    }
119}
120
121/// How many patches a design keeps for streams behind: one further behind
122/// is sent the whole scene.
123const LOG: usize = 64;
124
125/// What a watch stream sends next for a design, after the version it sent.
126pub enum Next {
127    /// The design has these problems.
128    Problems(Vec<Problem>),
129    /// Its whole scene, at this version: the stream sent none, or is too far
130    /// behind for patches.
131    Scene(u64, Box<proto::Scene>),
132    /// The patches from the version sent to this one, as one.
133    Patch(u64, proto::Patch),
134    /// The stream is current; the scene is themed or not.
135    Current(bool),
136}
137
138/// A tile in the store's cache: which kept design it is of, and which tile.
139#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
140struct Tile {
141    /// The id of the kept design the tile is of.
142    design: u64,
143    /// Which tile of it: its theme, level, column and row.
144    key: Key,
145}
146
147impl Tiled for Tile {
148    fn key(&self) -> Key {
149        self.key
150    }
151}
152
153/// What the store's tiles may hold together: 64 MB of pixels.
154pub const TILES_CAP: usize = 64 << 20;
155
156/// What a tile's pixels cost in the cache.
157const TILE_BYTES: usize = (TILE * TILE * 4) as usize;
158
159/// What the store tells when a design's scene or problems change.
160type Listener = Box<dyn Fn(&str) + Send + Sync>;
161
162/// What every folder's designs in one store share: the renderer, whose
163/// fonts load once, the one capped tile cache, the numbering of kept designs
164/// — which tells their tiles apart in it — and of reads, what tells this
165/// store's versions from another run's, and the folders it holds by mount.
166struct Shared {
167    /// The one renderer of every folder's designs, whose fonts load once.
168    renderer: Mutex<Renderer>,
169    /// How many files the store has read from disk.
170    reads: std::sync::atomic::AtomicU64,
171    /// What tells this store's versions from another run's, in an ETag.
172    nonce: u64,
173    /// How many resolves the store has started, numbering each.
174    versions: std::sync::atomic::AtomicU64,
175    /// Every design's tiles at 1×, in each theme, of every folder: shared
176    /// and capped. Locked after a folder's own locks.
177    tiles: Mutex<Cache<Arc<[u8]>, Tile>>,
178    /// The folders whose designs are held, by mount, while anything holds
179    /// them.
180    mounts: Mutex<HashMap<String, std::sync::Weak<Folder>>>,
181}
182
183/// The designs of one folder, under its mount: what was read from it and
184/// each design kept from it. Its tiles are in the store's shared cache, and
185/// go with it.
186struct Folder {
187    /// What the folder shares with every other folder of the store.
188    shared: Arc<Shared>,
189    /// What the folder's designs are told apart by in the store: their
190    /// folder's mount, `""` for the one folder a local devpage serves.
191    mount: String,
192    /// The folder its designs are read from.
193    served: ServedFolder,
194    /// Each file as last read, by its path from the top of the folder; a folder's
195    /// listing under its path and a `/`.
196    sources: Mutex<HashMap<String, Source>>,
197    /// Locked before `sources` whenever both are.
198    resolved: Mutex<HashMap<String, Resolved>>,
199    /// Told the address of each design whose scene or problems changed.
200    listeners: Mutex<Vec<Listener>>,
201    /// Each design as it is kept, locked one design at a time — while it is
202    /// resolved again, and before `renderer`, `resolved` and `tiles`
203    /// whenever they are.
204    kept: Mutex<HashMap<String, Arc<Mutex<Kept>>>>,
205    /// Each design file's last parse, by path, kept across its saves: a new
206    /// parse is matched against it, so its elements keep their ids.
207    parses: Parses,
208    /// How many tiles the folder's designs were painted in, for the tests.
209    #[cfg(test)]
210    painted: std::sync::atomic::AtomicUsize,
211    /// How many times a design was resolved, for the tests.
212    #[cfg(test)]
213    resolutions: std::sync::atomic::AtomicUsize,
214    /// How many times edits were applied to a design's scene, for the
215    /// tests.
216    #[cfg(test)]
217    applies: std::sync::atomic::AtomicUsize,
218    /// Called after each file read from disk, for the tests: a save can land
219    /// there.
220    #[cfg(test)]
221    after_read: Mutex<Option<AfterRead>>,
222}
223
224/// A folder no one holds takes its tiles with it, and leaves the store.
225impl Drop for Folder {
226    fn drop(&mut self) {
227        let ids: Vec<u64> = lock(&self.kept).values().map(|k| lock(k).id).collect();
228        lock(&self.shared.tiles).forget(|t| ids.contains(&t.design));
229        let mut mounts = lock(&self.shared.mounts);
230        if mounts
231            .get(&self.mount)
232            .is_some_and(|held| held.strong_count() == 0)
233        {
234            mounts.remove(&self.mount);
235        }
236    }
237}
238
239#[cfg(test)]
240type AfterRead = Box<dyn Fn(&str) + Send + Sync>;
241
242/// `mutex`, locked — even after a panic poisoned it.
243fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
244    mutex
245        .lock()
246        .unwrap_or_else(|poisoned| poisoned.into_inner())
247}
248
249/// The store's files, recording every path a resolving asks for and which
250/// read of it the resolving saw.
251struct Reading<'a> {
252    /// The folder whose files are read.
253    store: &'a Folder,
254    /// Every path asked for, in order, missing ones included.
255    asked: RefCell<Vec<String>>,
256    /// Each path asked for with which read of it was seen, to tell whether a save
257    /// landed while resolving.
258    seen: RefCell<Vec<(String, u64)>>,
259}
260
261impl Reading<'_> {
262    /// What `key` holds — a file's bytes, or a folder's listing when it ends
263    /// in `/` — read once and kept until the watcher reports it changed.
264    fn source(&self, key: &str) -> Option<Vec<u8>> {
265        self.asked.borrow_mut().push(key.to_string());
266        let mut sources = lock(&self.store.sources);
267        if let Some(source) = sources.get(key) {
268            self.seen.borrow_mut().push((key.to_string(), source.read));
269            return source.bytes.clone();
270        }
271        let served = &self.store.served;
272        let source = match key.strip_suffix('/') {
273            Some(folder) => {
274                let found = served.folder(&served.path().join(folder));
275                Source {
276                    bytes: found
277                        .as_ref()
278                        .and_then(|f| names(f))
279                        .map(|names| names.join("\n").into_bytes()),
280                    canonical: found.as_ref().map(|f| format!("{}/", self.store.name(f))),
281                    read: self.store.next_read(),
282                    image: None,
283                    font: None,
284                }
285            }
286            None => {
287                let found = served.file(&served.path().join(key));
288                Source {
289                    bytes: found.as_ref().and_then(|f| std::fs::read(f).ok()),
290                    canonical: found.as_ref().map(|f| self.store.name(f)),
291                    read: self.store.next_read(),
292                    image: None,
293                    font: None,
294                }
295            }
296        };
297        self.seen.borrow_mut().push((key.to_string(), source.read));
298        let bytes = source.bytes.clone();
299        sources.insert(key.to_string(), source);
300        drop(sources);
301        #[cfg(test)]
302        if let Some(after) = lock(&self.store.after_read).as_ref() {
303            after(key);
304        }
305        bytes
306    }
307}
308
309/// The names of the files directly in `folder`, sorted.
310fn names(folder: &Path) -> Option<Vec<String>> {
311    let mut names: Vec<String> = std::fs::read_dir(folder)
312        .ok()?
313        .filter_map(|entry| entry.ok())
314        .filter(|entry| entry.path().is_file())
315        .filter_map(|entry| entry.file_name().into_string().ok())
316        .collect();
317    names.sort();
318    Some(names)
319}
320
321impl Files for Reading<'_> {
322    /// Any file's bytes — a design's text, an image's or a font's — read
323    /// once and kept until the watcher reports it changed.
324    fn bytes(&self, path: &str) -> Option<Vec<u8>> {
325        self.source(path)
326    }
327
328    /// A folder's files, listed once and kept until the watcher reports a
329    /// change to any file directly in it.
330    fn list(&self, path: &str) -> Option<Vec<String>> {
331        let listing = self.source(&format!("{path}/"))?;
332        let text = String::from_utf8(listing).ok()?;
333        Some(text.lines().map(str::to_string).collect())
334    }
335
336    /// A font file checked, once per read of it.
337    fn font(&self, path: &str) -> Option<Result<Arc<FontFile>, String>> {
338        if let Some(source) = lock(&self.store.sources).get(path)
339            && let Some(font) = &source.font
340        {
341            self.asked.borrow_mut().push(path.to_string());
342            self.seen.borrow_mut().push((path.to_string(), source.read));
343            return Some(font.clone());
344        }
345        let bytes = self.bytes(path)?;
346        let read = self.seen.borrow().last().map(|(_, read)| *read);
347        let font = FontFile::new(bytes).map(Arc::new);
348        if let Some(source) = lock(&self.store.sources).get_mut(path)
349            && Some(source.read) == read
350        {
351            source.font = Some(font.clone());
352        }
353        Some(font)
354    }
355
356    /// An image file decoded, once per read of it.
357    fn image(&self, path: &str) -> Option<Result<Arc<ImageFile>, String>> {
358        if let Some(source) = lock(&self.store.sources).get(path)
359            && let Some(image) = &source.image
360        {
361            self.asked.borrow_mut().push(path.to_string());
362            self.seen.borrow_mut().push((path.to_string(), source.read));
363            return Some(image.clone());
364        }
365        let bytes = self.bytes(path)?;
366        let read = self.seen.borrow().last().map(|(_, read)| *read);
367        let image = ImageFile::new(bytes).map(Arc::new);
368        if let Some(source) = lock(&self.store.sources).get_mut(path)
369            && Some(source.read) == read
370        {
371            source.image = Some(image.clone());
372        }
373        Some(image)
374    }
375}
376
377impl Folder {
378    /// The number of the next read from disk, counting from one.
379    fn next_read(&self) -> u64 {
380        1 + self
381            .shared
382            .reads
383            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
384    }
385
386    /// The name of a file the served folder resolved, which lies inside it
387    /// by construction.
388    fn name(&self, file: &Path) -> String {
389        self.served
390            .name(file)
391            .unwrap_or_else(|| panic!("{} is outside the served folder", file.display()))
392    }
393
394    /// The design at `path` brought up to the files as they are now: the
395    /// first time resolved whole, then resolved again only as far as the
396    /// files in `changed` reach — and kept. A file the resolving read may
397    /// change while it runs, after the read and before the result is kept,
398    /// and `changed` would then find nothing kept to resolve again; so every
399    /// file it read is checked to still be that read, and what isn't is
400    /// resolved again.
401    fn refresh(&self, path: &str, changed: &[String]) -> Resolved {
402        let kept = self.kept(path);
403        let mut k = lock(&kept);
404        let mut changed = changed.to_vec();
405        loop {
406            let seen = self.bring(path, &mut k, &changed);
407            let sources = lock(&self.sources);
408            changed = seen
409                .into_iter()
410                .filter(|(file, read)| sources.get(file).is_none_or(|s| s.read != *read))
411                .map(|(file, _)| file)
412                .collect();
413            drop(sources);
414            if changed.is_empty() {
415                break;
416            }
417        }
418        let resolved = Resolved {
419            version: k.version,
420            problems: k.problems.clone(),
421            asked: k.asked.clone(),
422            missing: k.missing,
423        };
424        lock(&self.resolved).insert(path.to_string(), resolved.clone());
425        resolved
426    }
427
428    /// Resolves the design at `path` — whole, or again as far as `changed`
429    /// reaches, its edits applied to the design that holds its scene — and
430    /// draws it; says which read of each file it saw.
431    fn bring(&self, path: &str, k: &mut Kept, changed: &[String]) -> Vec<(String, u64)> {
432        #[cfg(test)]
433        self.resolutions
434            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
435        let reading = Remembering::with(
436            Reading {
437                store: self,
438                asked: RefCell::new(Vec::new()),
439                seen: RefCell::new(Vec::new()),
440            },
441            &self.parses,
442        );
443        enum Done {
444            Fresh(Box<(Resolution, Scene)>),
445            Again(Outcome),
446        }
447        let done = guarded(
448            path,
449            || match k.held.as_mut() {
450                None => Resolution::new(&reading, path).map(|r| Done::Fresh(Box::new(r))),
451                Some(held) => {
452                    let mut holder = Bringing {
453                        design: &mut held.design,
454                        renderer: &self.shared.renderer,
455                        #[cfg(test)]
456                        applies: &self.applies,
457                    };
458                    Ok(Done::Again(held.resolution.update(
459                        &mut holder,
460                        &reading,
461                        changed,
462                    )))
463                }
464            },
465            |p| vec![p],
466        );
467        let asked = reading.files.asked.take();
468        k.missing = lock(&self.sources)
469            .get(path)
470            .is_none_or(|source| source.bytes.is_none());
471        match done {
472            Ok(Done::Fresh(fresh)) => {
473                let (resolution, scene) = *fresh;
474                if k.id == 0 {
475                    k.id = 1 + self
476                        .shared
477                        .versions
478                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
479                }
480                k.held = Some(Held {
481                    resolution,
482                    design: Design::new(scene),
483                });
484                k.version += 1;
485                // No stream holds this scene yet, or holds one it can't be
486                // patched into: each is sent it whole.
487                k.log.clear();
488                k.asked = asked;
489                k.problems = self.draw(path, k).err();
490            }
491            Ok(Done::Again(Outcome::Same)) => {
492                k.asked.extend(asked);
493                k.problems = self.draw(path, k).err();
494            }
495            Ok(Done::Again(Outcome::Changed(edits, _))) => {
496                k.asked.extend(asked);
497                k.log.push_back((k.version, Arc::new(wire::patch(&edits))));
498                if k.log.len() > LOG {
499                    k.log.pop_front();
500                }
501                k.version += 1;
502                k.problems = self.draw(path, k).err();
503            }
504            Ok(Done::Again(Outcome::Problems(problems))) => {
505                k.asked.extend(asked);
506                k.problems = Some(problems);
507            }
508            Err(problems) => {
509                // Resolving failed — or the engine did, and what it kept may
510                // be half done: the next change resolves the design afresh,
511                // and owes nothing to the tiles painted before.
512                k.asked.extend(asked);
513                if problems
514                    .iter()
515                    .any(|p| p.message.starts_with("the design engine failed"))
516                {
517                    self.let_go(k);
518                }
519                k.problems = Some(problems);
520            }
521        }
522        k.asked.sort();
523        k.asked.dedup();
524        reading.files.seen.into_inner()
525    }
526
527    /// The kept state of the design at `path`, made the first time.
528    fn kept(&self, path: &str) -> Arc<Mutex<Kept>> {
529        lock(&self.kept)
530            .entry(path.to_string())
531            .or_default()
532            .clone()
533    }
534
535    /// Lets the design `k` holds go, with its tiles: the engine panicked on
536    /// it, and it is resolved afresh next time.
537    fn let_go(&self, k: &mut Kept) {
538        k.held = None;
539        let id = k.id;
540        lock(&self.shared.tiles).forget(|t| t.design == id);
541    }
542
543    /// Draws the design in each theme its scene shows in — the edits that
544    /// brought it there applied already — the tiles its changes damaged gone
545    /// stale and those of a theme it no longer shows in dropped. Or why the
546    /// scene can't be drawn: the design keeps showing its last good drawing,
547    /// and no tile goes stale until the scene can be drawn again.
548    fn draw(&self, path: &str, k: &mut Kept) -> Result<(), Vec<Problem>> {
549        let id = k.id;
550        let Some(held) = k.held.as_mut() else {
551            return Ok(());
552        };
553        let themes = themes(held.design.scene());
554        let mut renderer = lock(&self.shared.renderer);
555        let drawn = guarded(
556            path,
557            || {
558                let design = &mut held.design;
559                for theme in [Theme::Light, Theme::Dark] {
560                    if !themes.contains(&theme) {
561                        design.forget(theme);
562                    }
563                }
564                let mut broke = None;
565                for &theme in themes {
566                    if let Err(undrawable) = design.draw(&mut renderer, theme) {
567                        broke.get_or_insert_with(|| undrawable.clone());
568                    }
569                }
570                Ok((design.take_damage(), broke))
571            },
572            |p| Undrawable {
573                message: p.message,
574                at: None,
575            },
576        );
577        drop(renderer);
578        let (damage, broke) = match drawn {
579            Ok(drawn) => drawn,
580            // A design the engine panicked on is resolved afresh next time.
581            Err(undrawable) => {
582                self.let_go(k);
583                (Vec::new(), Some(undrawable))
584            }
585        };
586        let mut tiles = lock(&self.shared.tiles);
587        for (theme, damage) in damage {
588            let mine = |t: &Tile| t.design == id && t.key.theme == theme;
589            match damage {
590                Damage::All => tiles.damage_all_where(mine),
591                Damage::Rects { origin, rects } => tiles.damage_where(mine, origin, &rects),
592            }
593        }
594        // The themes the design no longer shows in, and their tiles.
595        tiles.forget(|t| t.design == id && !themes.contains(&t.key.theme));
596        match broke {
597            None => Ok(()),
598            Some(u) => Err(problem(path, u)),
599        }
600    }
601
602    /// The design at `path`, from memory, resolving it the first time.
603    fn get(&self, path: &str) -> Resolved {
604        if let Some(resolved) = lock(&self.resolved).get(path) {
605            return resolved.clone();
606        }
607        self.refresh(path, &[])
608    }
609}
610
611/// The design store: every folder's designs it holds, one renderer — its
612/// fonts load once — and one tile cache of [`TILES_CAP`] for them all. A
613/// local devpage holds one folder; a devpage server one per version it
614/// serves, each under that version's own mount, for as long as its routers
615/// hold it.
616#[derive(Clone)]
617pub struct Store(Arc<Shared>);
618
619impl Store {
620    /// An empty store, its renderer's fonts loaded and its tile cache capped at
621    /// [`TILES_CAP`].
622    pub fn new() -> Store {
623        Store(Arc::new(Shared {
624            renderer: Mutex::new(Renderer::new()),
625            reads: Default::default(),
626            nonce: std::time::SystemTime::now()
627                .duration_since(std::time::UNIX_EPOCH)
628                .map_or(0, |d| d.as_nanos() as u64),
629            versions: Default::default(),
630            tiles: Mutex::new(Cache::<Arc<[u8]>, Tile>::new(TILES_CAP)),
631            mounts: Mutex::default(),
632        }))
633    }
634
635    /// The designs of `served`, told apart from every other folder's by
636    /// `mount`: the ones held already under it — the same folder's — or
637    /// held from now on. A mount names one folder's files and never other
638    /// files: what is kept under it is never read again.
639    pub fn designs(&self, mount: &str, served: &ServedFolder) -> Designs {
640        let mut mounts = lock(&self.0.mounts);
641        let held = mounts.get(mount).and_then(std::sync::Weak::upgrade);
642        if let Some(folder) = held.as_ref().filter(|f| f.served.path() == served.path()) {
643            return Designs(folder.clone());
644        }
645        let folder = Arc::new(Folder {
646            shared: self.0.clone(),
647            mount: mount.to_string(),
648            served: served.clone(),
649            sources: Mutex::default(),
650            resolved: Mutex::default(),
651            listeners: Mutex::default(),
652            kept: Mutex::default(),
653            parses: Parses::default(),
654            #[cfg(test)]
655            painted: Default::default(),
656            #[cfg(test)]
657            resolutions: Default::default(),
658            #[cfg(test)]
659            applies: Default::default(),
660            #[cfg(test)]
661            after_read: Mutex::default(),
662        });
663        mounts.insert(mount.to_string(), Arc::downgrade(&folder));
664        drop(mounts);
665        // The folder it replaces — the same files, unpacked elsewhere — goes
666        // when its last holder lets it, never under the lock it takes then.
667        drop(held);
668        Designs(folder)
669    }
670
671    /// How many folders the store holds designs of.
672    #[cfg(test)]
673    fn folders(&self) -> usize {
674        lock(&self.0.mounts).len()
675    }
676}
677
678impl Default for Store {
679    fn default() -> Self {
680        Store::new()
681    }
682}
683
684/// The designs of one folder, from a [`Store`]: every design asked for,
685/// kept resolved in memory.
686#[derive(Clone)]
687pub struct Designs(Arc<Folder>);
688
689/// A design's address as the engine names files: from the top of the served
690/// folder, without a leading slash.
691pub fn address(path: &str) -> &str {
692    path.trim_start_matches('/')
693}
694
695impl Designs {
696    /// The designs of the served folder, in a store of their own.
697    pub fn new(served: &ServedFolder) -> Designs {
698        Store::new().designs("", served)
699    }
700
701    /// The design at `path` resolved — its scene, copied — or its problems.
702    pub fn resolve(&self, path: &str) -> Result<Scene, Vec<Problem>> {
703        let path = address(path);
704        let resolved = self.0.get(path);
705        if let Some(problems) = resolved.problems {
706            return Err(problems);
707        }
708        let kept = self.0.kept(path);
709        let k = lock(&kept);
710        Ok(k.held
711            .as_ref()
712            .expect("a design with no problems is held")
713            .design
714            .scene()
715            .clone())
716    }
717
718    /// What a watch stream that last sent the design at `path` at version
719    /// `sent` — or nothing, `None` — sends next: the design's problems, its
720    /// whole scene, the patches since that version as one, or nothing new.
721    /// The patches were made once, when the design was resolved again, and
722    /// every stream sends the same.
723    pub fn next(&self, path: &str, sent: Option<u64>) -> Next {
724        let path = address(path);
725        let resolved = self.0.get(path);
726        if let Some(problems) = resolved.problems {
727            return Next::Problems(problems);
728        }
729        let kept = self.0.kept(path);
730        let k = lock(&kept);
731        let Some(held) = k.held.as_ref() else {
732            return Next::Problems(Vec::new());
733        };
734        let scene = held.design.scene();
735        let whole = || Next::Scene(k.version, Box::new(wire::scene(scene)));
736        match sent {
737            None => whole(),
738            Some(v) if v == k.version => Next::Current(scene.themed),
739            Some(v) => {
740                let Some(first) = k.log.iter().position(|(from, _)| *from == v) else {
741                    return whole();
742                };
743                let mut patch = proto::Patch {
744                    themed: scene.themed,
745                    ..Default::default()
746                };
747                for (_, p) in k.log.iter().skip(first) {
748                    patch.ops.extend(p.ops.iter().cloned());
749                    patch.images.extend(p.images.iter().cloned());
750                    patch.fonts.extend(p.fonts.iter().cloned());
751                }
752                Next::Patch(k.version, patch)
753            }
754        }
755    }
756
757    /// The design at `path`'s problems — resolving it, or drawing its scene
758    /// in each theme it shows in: what `devpage check` and a page's problems
759    /// bar report. None when it resolves and draws.
760    pub fn problems(&self, path: &str) -> Vec<Problem> {
761        self.0.get(address(path)).problems.unwrap_or_default()
762    }
763
764    /// Everything the design at `path` is made of, as the store read it:
765    /// the design itself, its imports, images, themes and fonts — every
766    /// file a resolve of it has read since it was last resolved whole,
767    /// whether or not it resolves — and every folder it listed, a font
768    /// folder, with the fonts it then read from it. A file or folder it
769    /// asked for that isn't there is among them, named as it would be. A
770    /// change to any of them — a file in a listed folder added or removed
771    /// among them — is a change to the design.
772    pub fn made_of(&self, path: &str) -> Vec<PathBuf> {
773        let served = &self.0.served;
774        self.0
775            .get(address(path))
776            .asked
777            .iter()
778            .filter_map(|key| match key.strip_suffix('/') {
779                Some(folder) => {
780                    let folder = served.path().join(folder);
781                    served.folder(&folder).or_else(|| served.named(&folder))
782                }
783                None => served.named(&served.path().join(key)),
784            })
785            .collect()
786    }
787
788    /// How many times the store resolved a design, for the tests.
789    #[cfg(test)]
790    pub(crate) fn resolutions(&self) -> usize {
791        self.0
792            .resolutions
793            .load(std::sync::atomic::Ordering::Relaxed)
794    }
795
796    /// Tells `listener` the address of each design whose scene or problems
797    /// change from now on, as the engine names it — what
798    /// [`Designs::resolve`] then answers anew. It is called on the thread
799    /// that reported the change, so it should only pass the address on.
800    pub fn on_change(&self, listener: impl Fn(&str) + Send + Sync + 'static) {
801        lock(&self.0.listeners).push(Box::new(listener));
802    }
803
804    /// A file in the served folder changed, was created or was deleted: forget
805    /// it and its folder's listing, resolve again every design that asked for
806    /// either, and announce the designs whose scene or problems changed.
807    pub fn changed(&self, file: &Path) {
808        let store = &self.0;
809        // A path outside the served folder is no source of any design.
810        let Some(relative) = store.served.name(file) else {
811            return;
812        };
813        let folder = match relative.rsplit_once('/') {
814            Some((folder, _)) => format!("{folder}/"),
815            None => "/".to_string(),
816        };
817        // Forgotten and looked up at once, so a design is either kept already
818        // and found here, or not yet kept and made again by `refresh`.
819        let (affected, forgotten): (Vec<(String, Resolved)>, Vec<String>) = {
820            let resolved = lock(&store.resolved);
821            let mut sources = lock(&store.sources);
822            let forgotten = sources
823                .iter()
824                .filter(|(key, source)| {
825                    [relative.as_str(), folder.as_str()].iter().any(|changed| {
826                        key == changed || source.canonical.as_deref() == Some(changed)
827                    })
828                })
829                .map(|(key, _)| key.clone())
830                .collect::<Vec<_>>();
831            if forgotten.is_empty() {
832                return;
833            }
834            for key in &forgotten {
835                sources.remove(key);
836            }
837            let affected = resolved
838                .iter()
839                .filter(|(_, resolved)| resolved.asked.iter().any(|a| forgotten.contains(a)))
840                .map(|(path, resolved)| (path.clone(), resolved.clone()))
841                .collect();
842            (affected, forgotten)
843        };
844        for (path, old) in affected {
845            let new = store.refresh(&path, &forgotten);
846            let differs = new.version != old.version
847                || new.problems != old.problems
848                || new.missing != old.missing;
849            if differs {
850                for listener in lock(&store.listeners).iter() {
851                    listener(&path);
852                }
853            }
854        }
855        // A design file no design reads any more takes its last parse with
856        // it.
857        let resolved = lock(&store.resolved);
858        for key in &forgotten {
859            if store.parses.holds(key) && !resolved.values().any(|r| r.asked.contains(key)) {
860                store.parses.forget(key);
861            }
862        }
863    }
864
865    /// The validator of the design at `path`'s PNG in `theme`, known before
866    /// painting: the version of its scene — one more for every change to it
867    /// — of this store, the theme, and devpage's build, which paints it.
868    /// `None` when it doesn't resolve. It may resolve the design, so it
869    /// blocks.
870    pub fn etag(&self, path: &str, theme: Theme) -> Option<String> {
871        let path = address(path);
872        let resolved = self.0.get(path);
873        if resolved.problems.is_some() {
874            return None;
875        }
876        let text = format!(
877            "{}\0{theme:?}\0{}\0{path}\0{}\0{}",
878            crate::addresses::BUILD,
879            self.0.mount,
880            self.0.shared.nonce,
881            resolved.version
882        );
883        Some(crate::addresses::hash(text.as_bytes()))
884    }
885
886    /// The design at `path` as a PNG in `theme`, written to `out` band by band
887    /// — each band at most 16 MB of pixels: one row of tiles at 1×, from the
888    /// store's cache, only the missing and stale ones painted, or for a drawing
889    /// too wide for that, shorter strips painted and not cached — or its
890    /// problems one per line, before anything is written. Painting blocks; a
891    /// writer that fails — a client gone — stops it.
892    ///
893    /// No lock of the store's is held while `out` is written to, so a client
894    /// that stops reading holds up nothing but its own PNG. A save that
895    /// changes the design while its PNG is written ends the PNG there, with
896    /// an error, rather than finish it from another scene.
897    pub fn png_to(&self, path: &str, theme: Theme, out: impl std::io::Write) -> Result<(), String> {
898        let path = address(path);
899        let store = &self.0;
900        let resolved = store.get(path);
901        if let Some(problems) = &resolved.problems {
902            return Err(lines(problems));
903        }
904        let kept = store.kept(path);
905        let (id, version, area, theme) = {
906            let mut k = lock(&kept);
907            if let Some(problems) = &k.problems {
908                return Err(lines(problems));
909            }
910            let themed = k.held.as_ref().is_some_and(|h| h.design.scene().themed);
911            let theme = if themed { theme } else { Theme::Light };
912            let area = k
913                .held
914                .as_mut()
915                .and_then(|h| h.design.area(&mut lock(&store.shared.renderer), theme))
916                .ok_or_else(|| format!("{path}: the design has no drawing in {theme:?}"))?;
917            (k.id, k.version, area, theme)
918        };
919        guarded(
920            path,
921            || {
922                write_bands(area.width as u32, area.height as u32, out, |piece| {
923                    let (col, row) = match piece {
924                        Piece::Tile { col, row } => (col, row),
925                        // A band of a drawing too wide for whole tiles is
926                        // painted in strips, never cached.
927                        Piece::Strip { col, y, rows } => {
928                            let mut kept = lock(&kept);
929                            let list =
930                                prepared(&mut kept, version, &store.shared.renderer, |d, r| {
931                                    d.strip(r, theme, col, y, rows)
932                                })?;
933                            return Ok::<_, &str>(
934                                devpage_design::cpu::strip(list, col, y, rows).into(),
935                            );
936                        }
937                    };
938                    let tile = Tile {
939                        design: id,
940                        key: Key {
941                            theme,
942                            level: Level::of(1.0),
943                            col,
944                            row,
945                        },
946                    };
947                    // The design's lock, for one tile at a time: never while
948                    // the band is written.
949                    let mut kept = lock(&kept);
950                    if Some(&*kept).filter(|k| k.version == version).is_none() {
951                        return Err("the design changed while its PNG was written");
952                    }
953                    if let Some((pixels, false)) = lock(&store.shared.tiles).get(&tile) {
954                        return Ok(pixels.clone());
955                    }
956                    let list = prepared(&mut kept, version, &store.shared.renderer, |d, r| {
957                        d.tile(r, theme, 1.0, col, row)
958                    })?;
959                    let pixels: Arc<[u8]> = devpage_design::cpu::tile(list, 1.0, col, row).into();
960                    #[cfg(test)]
961                    store
962                        .painted
963                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
964                    lock(&store.shared.tiles).insert(tile, pixels.clone(), TILE_BYTES);
965                    Ok(pixels)
966                })
967                .map_err(|e| format!("writing the PNG: {e}"))
968            },
969            |p| p.message,
970        )
971        .map_err(|e| format!("{path}: {e}"))
972    }
973
974    /// The design at `path` painted as a PNG in `theme`, or its problems one
975    /// per line: [`Designs::png_to`], whole. Painting blocks.
976    pub fn png(&self, path: &str, theme: Theme) -> Result<Vec<u8>, String> {
977        let mut png = Vec::new();
978        self.png_to(path, theme, &mut png)?;
979        Ok(png)
980    }
981}
982
983/// The display list `list` picks from `kept`'s design — if it is still
984/// `version`'s — rounded where it is painted, so what is painted there is a
985/// fresh drawing's. The renderer is locked only while it rounds, never
986/// while the list is painted.
987fn prepared<'a>(
988    kept: &'a mut Kept,
989    version: u64,
990    renderer: &Mutex<Renderer>,
991    list: impl FnOnce(&'a mut Design, &mut Renderer) -> Option<&'a List>,
992) -> Result<&'a List, &'static str> {
993    let gone = "the design changed while its PNG was written";
994    if kept.version != version {
995        return Err(gone);
996    }
997    let held = kept.held.as_mut().ok_or(gone)?;
998    list(&mut held.design, &mut lock(renderer)).ok_or(gone)
999}
1000
1001/// The themes a design shows in: both when it is themed, else the light one,
1002/// which is the same as the dark.
1003fn themes(scene: &Scene) -> &'static [Theme] {
1004    if scene.themed {
1005        &[Theme::Light, Theme::Dark]
1006    } else {
1007        &[Theme::Light]
1008    }
1009}
1010
1011/// Why a design can't be drawn, as its problem: at the attribute that broke
1012/// it, or else at the design's start.
1013fn problem(path: &str, undrawable: Undrawable) -> Vec<Problem> {
1014    let (file, pos) = match undrawable.at {
1015        Some(at) => (at.file, at.pos),
1016        None => (
1017            path.to_string(),
1018            devpage_design::parse::Pos { line: 1, col: 1 },
1019        ),
1020    };
1021    vec![Problem {
1022        file,
1023        pos,
1024        message: undrawable.message,
1025    }]
1026}
1027
1028/// What `f` gives, or — should the engine ever panic on a design — a problem
1029/// saying so, so that no design file can take the server or its watcher down.
1030pub fn guarded<T, E>(
1031    path: &str,
1032    f: impl FnOnce() -> Result<T, E>,
1033    failed: impl FnOnce(Problem) -> E,
1034) -> Result<T, E> {
1035    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
1036        let message = panic
1037            .downcast_ref::<&str>()
1038            .map(|s| s.to_string())
1039            .or_else(|| panic.downcast_ref::<String>().cloned())
1040            .unwrap_or_default();
1041        Err(failed(Problem {
1042            file: path.to_string(),
1043            pos: devpage_design::parse::Pos { line: 1, col: 1 },
1044            message: format!("the design engine failed on this design: {message}"),
1045        }))
1046    })
1047}
1048
1049/// `problems`, one per line.
1050fn lines(problems: &[Problem]) -> String {
1051    problems
1052        .iter()
1053        .map(Problem::to_string)
1054        .collect::<Vec<_>>()
1055        .join("\n")
1056}
1057
1058/// Designs to test with, and saving one as the watcher would.
1059#[cfg(any(test, feature = "testing"))]
1060pub mod testing {
1061    use std::path::{Path, PathBuf};
1062
1063    use super::Designs;
1064
1065    /// A button design with a `label` prop, at `app/button.design`.
1066    pub const BUTTON: &str = r##"<Frame props={{ label: "Button" }} layout="row" padding={[12, 20]} fill="#2563eb">
1067  <Text color="#ffffff">{label}</Text>
1068</Frame>
1069"##;
1070    /// A screen design that imports [`BUTTON`] and shows it, at
1071    /// `app/screen.design`.
1072    pub const SCREEN: &str = r##"import Button from "./button.design"
1073
1074<Frame width={200} height={120} layout="column" gap={8} padding={16} fill="#f8fafc">
1075  <Text>Cart</Text>
1076  <Button label="Pay" />
1077</Frame>
1078"##;
1079    /// A plain black square that imports nothing, at `app/other.design`.
1080    pub const OTHER: &str = r##"<Frame width={50} height={50} fill="#000000" />
1081"##;
1082
1083    /// A fresh folder in the temp dir, named after `name`, holding [`BUTTON`],
1084    /// [`SCREEN`] and [`OTHER`] under `app/`: its canonical path.
1085    pub fn served(name: &str) -> PathBuf {
1086        let dir =
1087            std::env::temp_dir().join(format!("devpage-designs-{name}-{}", std::process::id()));
1088        let _ = std::fs::remove_dir_all(&dir);
1089        std::fs::create_dir_all(dir.join("app")).unwrap();
1090        std::fs::write(dir.join("app/button.design"), BUTTON).unwrap();
1091        std::fs::write(dir.join("app/screen.design"), SCREEN).unwrap();
1092        std::fs::write(dir.join("app/other.design"), OTHER).unwrap();
1093        dir.canonicalize().unwrap()
1094    }
1095
1096    /// A themes file with a light and a dark theme, each defining `bg`.
1097    pub const THEMES: &str = "kind: themes\nlight:\n  bg: \"#ffffff\"\ndark:\n  bg: \"#000000\"\n";
1098
1099    /// Writes a file and tells the store, as the watcher does.
1100    pub fn save(designs: &Designs, file: &Path, text: &str) {
1101        std::fs::write(file, text).unwrap();
1102        designs.changed(file);
1103    }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108    use super::testing::*;
1109    use super::*;
1110
1111    /// What the store tells, as it tells it.
1112    fn announced(designs: &Designs) -> std::sync::mpsc::Receiver<String> {
1113        let (tx, rx) = std::sync::mpsc::channel();
1114        let tx = Mutex::new(tx);
1115        designs.on_change(move |path| {
1116            let _ = lock(&tx).send(path.to_string());
1117        });
1118        rx
1119    }
1120
1121    /// A design 100,000 pixels tall: a column of 1,000 rows, 400 by 100, the
1122    /// row `edited` set apart by its fill.
1123    fn tall(dir: &Path, edited: Option<usize>) {
1124        let rows: String = (0..1000)
1125            .map(|i| {
1126                let fill = if Some(i) == edited { 0xff0000 } else { i * 997 };
1127                format!("<Frame width={{400}} height={{100}} fill=\"#{fill:06x}\" />")
1128            })
1129            .collect();
1130        save_quietly(
1131            &dir.join("app/huge.design"),
1132            &format!("<Frame layout=\"column\">{rows}</Frame>"),
1133        );
1134    }
1135
1136    fn save_quietly(file: &Path, text: &str) {
1137        std::fs::write(file, text).unwrap();
1138    }
1139
1140    fn painted(designs: &Designs) -> usize {
1141        designs
1142            .0
1143            .painted
1144            .swap(0, std::sync::atomic::Ordering::Relaxed)
1145    }
1146
1147    /// Counts what is written.
1148    #[derive(Default)]
1149    struct Count(usize);
1150    impl std::io::Write for Count {
1151        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
1152            self.0 += b.len();
1153            Ok(b.len())
1154        }
1155        fn flush(&mut self) -> std::io::Result<()> {
1156            Ok(())
1157        }
1158    }
1159
1160    /// Two folders in one store — two versions of a document — share its
1161    /// one tile cache and nothing else: the same address in each is its own
1162    /// design, with its own validator; asked for again under the same mount
1163    /// it is the one already kept; and a folder no one holds leaves the
1164    /// store with its tiles.
1165    #[test]
1166    fn folders_in_one_store_share_its_tiles_and_never_each_others_designs() {
1167        let one = served("mount-one");
1168        let two = served("mount-two");
1169        std::fs::write(two.join("app/other.design"), BOX_RED).unwrap();
1170        let store = Store::new();
1171        let first = store.designs("/d/x/v/1", &ServedFolder::new(&one).unwrap());
1172        let second = store.designs("/d/x/v/2", &ServedFolder::new(&two).unwrap());
1173        let png_one = first.png("app/other.design", Theme::Light).unwrap();
1174        let png_two = second.png("app/other.design", Theme::Light).unwrap();
1175        assert_ne!(png_one, png_two, "each folder's own design");
1176        assert_ne!(
1177            first.etag("app/other.design", Theme::Light),
1178            second.etag("app/other.design", Theme::Light),
1179            "a validator names the mount"
1180        );
1181        let tiles = || lock(&store.0.tiles).cost();
1182        let both = tiles();
1183        assert_eq!(both, 2 * TILE_BYTES, "one cache holds both");
1184
1185        // The same mount and folder: the design already kept.
1186        let again = store.designs("/d/x/v/1", &ServedFolder::new(&one).unwrap());
1187        again.png("app/other.design", Theme::Light).unwrap();
1188        assert_eq!(painted(&first), 1, "painted once, for the first ask");
1189        assert_eq!(store.folders(), 2);
1190
1191        drop((first, again));
1192        assert_eq!(store.folders(), 1);
1193        assert_eq!(tiles(), TILE_BYTES, "its tiles went with it");
1194        drop(second);
1195        assert_eq!((store.folders(), tiles()), (0, 0));
1196    }
1197
1198    const BOX_RED: &str = r##"<Frame width={50} height={50} fill="#ff0000" />
1199"##;
1200
1201    /// The store knows everything a design is made of — itself, what it
1202    /// imports, its themes, the font folder it listed and the font files its
1203    /// text is set in — from the one resolve that keeps it, whether or not
1204    /// the design resolves: a file it asked for that isn't there too, named
1205    /// as it would be — a `themes.yml` above it, an image to come.
1206    #[test]
1207    fn the_store_knows_everything_a_design_is_made_of() {
1208        let dir = served("files");
1209        let regular = std::fs::read(
1210            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Regular.ttf"),
1211        )
1212        .unwrap();
1213        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1214        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &regular).unwrap();
1215        std::fs::write(
1216            dir.join("app/themes.yml"),
1217            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1218        )
1219        .unwrap();
1220        std::fs::write(
1221            dir.join("app/set.design"),
1222            "import Button from \"./button.design\"\n\n<Frame><Text font=\"body\">Hello</Text><Button label=\"Go\" /></Frame>\n",
1223        )
1224        .unwrap();
1225        std::fs::write(
1226            dir.join("app/gone.design"),
1227            "<Frame>\n  <Image src=\"./gone.png\" width={5} height={5} />\n</Frame>\n",
1228        )
1229        .unwrap();
1230        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1231        let names = |path: &str| -> Vec<String> {
1232            designs
1233                .made_of(path)
1234                .iter()
1235                .map(|f| crate::folder::slashed(f.strip_prefix(&dir).unwrap()))
1236                .collect()
1237        };
1238        assert_eq!(
1239            names("/app/set.design"),
1240            [
1241                "app/button.design",
1242                "app/fonts/Body",
1243                "app/fonts/Body/Body-Regular.ttf",
1244                "app/set.design",
1245                "app/themes.yml",
1246                "themes.yml",
1247            ]
1248        );
1249        assert!(designs.problems("app/set.design").is_empty());
1250        assert_eq!(
1251            names("app/gone.design"),
1252            ["app/gone.design", "app/gone.png"]
1253        );
1254        assert_eq!(designs.problems("app/gone.design").len(), 1);
1255        assert_eq!(names("app/nothing.design"), ["app/nothing.design"]);
1256        assert_eq!(designs.resolutions(), 3, "each resolved once");
1257    }
1258
1259    /// A design too wide for a row of tiles in one band is banded in strips,
1260    /// painted and never cached: its PNG is right and the cache stays empty.
1261    #[test]
1262    fn a_design_too_wide_for_tiles_is_banded_in_strips_never_cached() {
1263        let dir = served("wide");
1264        std::fs::write(
1265            dir.join("app/wide.design"),
1266            r##"<Frame width={40000} height={20} fill="#ffffff"><Rect x={39990} y={10} width={10} height={10} fill="#0000ff" /></Frame>"##,
1267        )
1268        .unwrap();
1269        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1270        let png = designs.png("app/wide.design", Theme::Light).unwrap();
1271        let (px, w, h) = devpage_design::compare::pixels(&png).unwrap();
1272        assert_eq!((w, h), (40_000, 20));
1273        let at = |x: usize, y: usize| px[(y * 40_000 + x) * 4..][..4].to_vec();
1274        assert_eq!(at(0, 0), vec![255, 255, 255, 255]);
1275        assert_eq!(at(39_999, 19), vec![0, 0, 255, 255]);
1276        assert_eq!(painted(&designs), 0);
1277        assert_eq!(lock(&designs.0.shared.tiles).cost(), 0);
1278    }
1279
1280    /// A design 100,000 pixels tall has a PNG, streamed band by band from the
1281    /// store's cache, which never holds more than its cap; asked for again,
1282    /// only the tiles the cap dropped are painted again.
1283    #[test]
1284    fn a_design_100000_pixels_tall_streams_its_png_from_a_capped_cache() {
1285        let dir = served("huge");
1286        tall(&dir, None);
1287        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1288        assert!(designs.problems("/app/huge.design").is_empty());
1289        let started = std::time::Instant::now();
1290        let png = designs.png("app/huge.design", Theme::Light).unwrap();
1291        let took = started.elapsed();
1292        let (px, w, h) = devpage_design::compare::pixels(&png).unwrap();
1293        assert_eq!((w, h), (400, 100_000));
1294        let c = 999 * 997;
1295        let at = (99_950 * 400 + 200) * 4;
1296        assert_eq!(&px[at..at + 3], &[(c >> 16) as u8, (c >> 8) as u8, c as u8]);
1297        // 391 rows of 2 tiles, all painted once; the cache holds 256 of them.
1298        assert_eq!(painted(&designs), 782);
1299        let held = lock(&designs.0.shared.tiles).cost();
1300        assert!(held <= TILES_CAP, "{held}");
1301        assert_eq!(held, TILES_CAP);
1302        eprintln!("100,000-px PNG: {took:?}, {} bytes", png.len());
1303        let mut count = Count::default();
1304        designs
1305            .png_to("app/huge.design", Theme::Light, &mut count)
1306            .unwrap();
1307        assert_eq!(count.0, png.len());
1308        // The last bands were cached; the first ones were dropped for them,
1309        // and dropping them again as the PNG goes on, all are painted again.
1310        assert_eq!(painted(&designs), 782);
1311        assert!(lock(&designs.0.shared.tiles).cost() <= TILES_CAP);
1312    }
1313
1314    /// A PNG asked for twice paints nothing the second time; after an edit to
1315    /// one node of a design 100,000 pixels tall, only the tiles over it.
1316    #[test]
1317    fn an_edit_repaints_only_the_tiles_over_it() {
1318        let dir = served("edit");
1319        std::fs::write(
1320            dir.join("app/small.design"),
1321            r##"<Frame width={600} height={300} fill="#336699" />"##,
1322        )
1323        .unwrap();
1324        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1325        let first = designs.png("app/small.design", Theme::Light).unwrap();
1326        assert_eq!(painted(&designs), 6);
1327        assert_eq!(
1328            designs.png("app/small.design", Theme::Light).unwrap(),
1329            first
1330        );
1331        assert_eq!(painted(&designs), 0);
1332
1333        tall(&dir, None);
1334        // Room for the whole design, to count only what the edit needs.
1335        *lock(&designs.0.shared.tiles) = Cache::new(usize::MAX);
1336        let before = designs.png("app/huge.design", Theme::Light).unwrap();
1337        assert_eq!(painted(&designs), 782);
1338        // Row 500 is y 50,000 to 50,100, inside tile row 195: its two tiles.
1339        tall(&dir, Some(500));
1340        designs.changed(&dir.join("app/huge.design"));
1341        let started = std::time::Instant::now();
1342        let after = designs.png("app/huge.design", Theme::Light).unwrap();
1343        let took = started.elapsed();
1344        assert_eq!(painted(&designs), 2);
1345        eprintln!("PNG after an edit: {took:?}, 2 tiles painted");
1346        let (a, _, _) = devpage_design::compare::pixels(&before).unwrap();
1347        let (b, _, _) = devpage_design::compare::pixels(&after).unwrap();
1348        let row = |px: &[u8], y: usize| px[(y * 400 + 10) * 4..(y * 400 + 10) * 4 + 4].to_vec();
1349        assert_eq!(row(&b, 50_050), vec![255, 0, 0, 255]);
1350        assert_eq!(row(&a, 49_950), row(&b, 49_950));
1351        assert_eq!(row(&a, 50_150), row(&b, 50_150));
1352        // The edit undone: those tiles again, and the PNG as before.
1353        tall(&dir, None);
1354        designs.changed(&dir.join("app/huge.design"));
1355        assert_eq!(
1356            designs.png("app/huge.design", Theme::Light).unwrap(),
1357            before
1358        );
1359        assert_eq!(painted(&designs), 2);
1360    }
1361
1362    /// A design's scene is held once, by its `Design`: a save that changes
1363    /// it applies its edits there once — never again to a copy beside it —
1364    /// and what the store serves, the scene and the PNG, is that one scene.
1365    #[test]
1366    fn a_save_applies_its_edits_to_the_designs_one_scene_once() {
1367        let dir = served("once");
1368        let file = dir.join("app/once.design");
1369        let design = |fill: &str| {
1370            format!(
1371                r##"<Frame width={{60}} height={{40}} fill="#ffffff"><Rect width={{20}} height={{20}} fill="{fill}" /></Frame>"##
1372            )
1373        };
1374        std::fs::write(&file, design("#ff0000")).unwrap();
1375        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1376        designs.png("app/once.design", Theme::Light).unwrap();
1377        let applies = || designs.0.applies.load(std::sync::atomic::Ordering::Relaxed);
1378        assert_eq!(applies(), 0);
1379
1380        save(&designs, &file, &design("#00ff00"));
1381        assert_eq!(applies(), 1);
1382        let scene = designs.resolve("app/once.design").unwrap();
1383        let fresh = devpage_design::resolve(
1384            &std::collections::HashMap::from([("a.design".to_string(), design("#00ff00"))]),
1385            "a.design",
1386        )
1387        .unwrap();
1388        assert_eq!(scene.root.children[0].fill, fresh.root.children[0].fill);
1389        let png = designs.png("app/once.design", Theme::Light).unwrap();
1390        let (px, _, _) = devpage_design::compare::pixels(&png).unwrap();
1391        assert_eq!(
1392            px[(10 * 60 + 10) * 4..(10 * 60 + 10) * 4 + 4],
1393            [0, 255, 0, 255]
1394        );
1395        // A save that changes nothing applies nothing.
1396        save(&designs, &file, &design("#00ff00"));
1397        assert_eq!(applies(), 1);
1398    }
1399
1400    /// A themed design keeps a drawing in each theme, and each theme its own
1401    /// tiles; a design that stops using its themes drops its dark ones.
1402    #[test]
1403    fn each_theme_keeps_its_own_tiles() {
1404        let dir = served("theme-tiles");
1405        std::fs::write(dir.join("app/themes.yml"), THEMES).unwrap();
1406        let file = dir.join("app/t.design");
1407        std::fs::write(&file, "<Frame width={300} height={100} fill={theme.bg} />").unwrap();
1408        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1409        let light = designs.png("app/t.design", Theme::Light).unwrap();
1410        let dark = designs.png("app/t.design", Theme::Dark).unwrap();
1411        assert_ne!(light, dark);
1412        assert_eq!(painted(&designs), 4);
1413        designs.png("app/t.design", Theme::Light).unwrap();
1414        designs.png("app/t.design", Theme::Dark).unwrap();
1415        assert_eq!(painted(&designs), 0);
1416        std::fs::write(
1417            &file,
1418            r##"<Frame width={300} height={100} fill="#00ff00" />"##,
1419        )
1420        .unwrap();
1421        designs.changed(&file);
1422        assert!(
1423            lock(&designs.0.shared.tiles)
1424                .iter()
1425                .all(|(t, _, _)| t.key.theme == Theme::Light)
1426        );
1427        // Not themed: the dark PNG is the light one.
1428        let green = designs.png("app/t.design", Theme::Light).unwrap();
1429        assert_eq!(designs.png("app/t.design", Theme::Dark).unwrap(), green);
1430    }
1431
1432    /// A PNG file `w` × `h` pixels of one `fill`, painted by the engine.
1433    fn png_file(w: u32, h: u32, fill: &str) -> Vec<u8> {
1434        let files: HashMap<String, String> = [(
1435            "p.design".to_string(),
1436            format!(r##"<Frame width={{{w}}} height={{{h}}} fill="{fill}" />"##),
1437        )]
1438        .into();
1439        let scene = devpage_design::resolve(&files, "p.design").unwrap();
1440        devpage_design::png::fresh(&mut Renderer::new(), &scene, Theme::Light).unwrap()
1441    }
1442
1443    /// An image that grows mid-session past what the GPU's atlas holds —
1444    /// three 4096-pixel squares and two small images, one of which turns
1445    /// into a fourth square — makes the design's problem, at its `src`, in
1446    /// place of a PNG; a save in the meantime is kept. Once the image is
1447    /// small again, the PNG is the one a fresh store paints: every tile the
1448    /// last good drawing left is painted again.
1449    #[test]
1450    fn an_image_that_breaks_mid_session_draws_as_fresh_once_mended() {
1451        let dir = served("image-breaks");
1452        for (name, fill) in [("a", "#dc0000"), ("b", "#00c800"), ("c", "#0000dc")] {
1453            std::fs::write(
1454                dir.join(format!("app/{name}.png")),
1455                png_file(4096, 4096, fill),
1456            )
1457            .unwrap();
1458        }
1459        let small = png_file(8, 8, "#c800c8");
1460        std::fs::write(dir.join("app/x.png"), &small).unwrap();
1461        std::fs::write(dir.join("app/y.png"), png_file(8, 8, "#00c8c8")).unwrap();
1462        let design = |fill: &str| {
1463            let images: String = "abcxy"
1464                .chars()
1465                .map(|c| format!("\n  <Image src=\"./{c}.png\" width={{40}} height={{40}} />"))
1466                .collect();
1467            format!(
1468                r##"<Frame layout="row" gap={{4}} padding={{8}} fill="#ffffff">{images}
1469  <Rect width={{40}} height={{40}} fill="{fill}" />
1470</Frame>
1471"##
1472            )
1473        };
1474        let file = dir.join("app/grows.design");
1475        std::fs::write(&file, design("#000000")).unwrap();
1476        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1477        designs.png("app/grows.design", Theme::Light).unwrap();
1478
1479        std::fs::write(dir.join("app/x.png"), png_file(4096, 4096, "#c800c8")).unwrap();
1480        designs.changed(&dir.join("app/x.png"));
1481        let broken = designs.png("app/grows.design", Theme::Light).unwrap_err();
1482        assert!(
1483            broken.starts_with("app/grows.design:") && broken.contains("doesn't fit"),
1484            "{broken}"
1485        );
1486        save(&designs, &file, &design("#ffaa00"));
1487        assert!(designs.png("app/grows.design", Theme::Light).is_err());
1488
1489        std::fs::write(dir.join("app/x.png"), &small).unwrap();
1490        designs.changed(&dir.join("app/x.png"));
1491        let mended = designs.png("app/grows.design", Theme::Light).unwrap();
1492        let fresh = Designs::new(&ServedFolder::new(&dir).unwrap())
1493            .png("app/grows.design", Theme::Light)
1494            .unwrap();
1495        assert!(mended == fresh, "the mended PNG isn't a fresh one");
1496    }
1497
1498    /// A PNG whose reader has stopped reading holds up no save: the store
1499    /// takes the save while the PNG waits, and the PNG, once read again,
1500    /// ends rather than finish from the next scene.
1501    #[test]
1502    fn a_save_lands_while_a_png_is_not_read() {
1503        let dir = served("unread");
1504        tall(&dir, None);
1505        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1506        designs.resolve("app/huge.design").unwrap();
1507        /// A reader that stops after the first write until it is let go.
1508        struct Stalled(std::sync::mpsc::Receiver<()>, bool);
1509        impl std::io::Write for Stalled {
1510            fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
1511                if self.1 {
1512                    self.1 = false;
1513                    let _ = self.0.recv();
1514                }
1515                Ok(b.len())
1516            }
1517            fn flush(&mut self) -> std::io::Result<()> {
1518                Ok(())
1519            }
1520        }
1521        let (go, wait) = std::sync::mpsc::channel();
1522        let reader = designs.clone();
1523        let png = std::thread::spawn(move || {
1524            reader.png_to("app/huge.design", Theme::Light, Stalled(wait, true))
1525        });
1526        // Let the PNG reach its first write.
1527        std::thread::sleep(std::time::Duration::from_millis(200));
1528        let (done, saved) = std::sync::mpsc::channel();
1529        let saver = designs.clone();
1530        let file = dir.join("app/huge.design");
1531        let save_dir = dir.clone();
1532        std::thread::spawn(move || {
1533            tall(&save_dir, Some(3));
1534            saver.changed(&file);
1535            let _ = done.send(());
1536        });
1537        assert!(
1538            saved
1539                .recv_timeout(std::time::Duration::from_secs(20))
1540                .is_ok(),
1541            "the save waited for the PNG's reader"
1542        );
1543        go.send(()).unwrap();
1544        let ended = png.join().unwrap().unwrap_err();
1545        assert!(
1546            ended.contains("changed while its PNG was written"),
1547            "{ended}"
1548        );
1549        // The next PNG is the new scene's.
1550        let next = designs.png("app/huge.design", Theme::Light).unwrap();
1551        let (px, _, _) = devpage_design::compare::pixels(&next).unwrap();
1552        let at = (350 * 400 + 10) * 4;
1553        assert_eq!(&px[at..at + 4], &[255, 0, 0, 255]);
1554    }
1555
1556    /// A writer that fails — a client gone — stops the painting there.
1557    #[test]
1558    fn a_writer_that_fails_stops_the_painting() {
1559        let dir = served("gone");
1560        tall(&dir, None);
1561        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1562        struct Gone;
1563        impl std::io::Write for Gone {
1564            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
1565                Err(std::io::Error::other("gone"))
1566            }
1567            fn flush(&mut self) -> std::io::Result<()> {
1568                Ok(())
1569            }
1570        }
1571        assert!(
1572            designs
1573                .png_to("app/huge.design", Theme::Light, Gone)
1574                .is_err()
1575        );
1576        assert!(painted(&designs) <= 2, "painted past the first band");
1577    }
1578
1579    /// Images that don't fit the GPU's atlas together are a problem at the
1580    /// `src` of the first that doesn't, wherever the design is looked at.
1581    #[test]
1582    fn images_too_many_for_the_gpu_are_a_problem_at_their_src() {
1583        /// `w`x`h`-name.png is an image file that size, never decoded.
1584        struct Sized(String);
1585        impl Files for Sized {
1586            fn bytes(&self, path: &str) -> Option<Vec<u8>> {
1587                (path == "app/a.design").then(|| self.0.clone().into_bytes())
1588            }
1589            fn list(&self, _: &str) -> Option<Vec<String>> {
1590                None
1591            }
1592            fn image(&self, path: &str) -> Option<Result<Arc<ImageFile>, String>> {
1593                let (size, _) = path.strip_prefix("app/")?.split_once('-')?;
1594                let (w, h) = size.split_once('x')?;
1595                let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
1596                Some(Ok(Arc::new(ImageFile {
1597                    id: devpage_design::scene::ImageId::of(path.as_bytes()),
1598                    bytes: Vec::new(),
1599                    width: w,
1600                    height: h,
1601                    pixels: Arc::new(vec![0; 4 * w as usize * h as usize]),
1602                    pixels_width: w,
1603                    pixels_height: h,
1604                })))
1605            }
1606        }
1607        let images: String = "abcde"
1608            .chars()
1609            .map(|c| format!("\n  <Image src=\"4096x4096-{c}.png\" width={{40}} height={{40}} />"))
1610            .collect();
1611        let design = Sized(format!(r#"<Frame layout="row">{images}</Frame>"#));
1612        let scene = devpage_design::resolve(&design, "app/a.design").unwrap();
1613        let mut held = Design::new(scene);
1614        let undrawable = held.draw(&mut Renderer::new(), Theme::Light).unwrap_err();
1615        let found = problem("app/a.design", undrawable.clone());
1616        assert_eq!(found.len(), 1);
1617        assert!(
1618            found[0]
1619                .to_string()
1620                .starts_with("app/a.design:6:10: this doesn't fit: "),
1621            "{found:?}"
1622        );
1623    }
1624
1625    /// An image file is decoded once per read of it: a save of the design
1626    /// showing it, or of another file, doesn't decode it again.
1627    #[test]
1628    fn a_save_decodes_only_the_image_that_changed() {
1629        let dir = served("decode-once");
1630        let shirt = std::fs::read(
1631            Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/designs/checkout/shirt.jpg"),
1632        )
1633        .unwrap();
1634        std::fs::write(dir.join("app/p.jpg"), &shirt).unwrap();
1635        let photo = "<Frame>\n  <Image src=\"./p.jpg\" />\n  <Image src=\"./p.jpg\" />\n</Frame>\n";
1636        std::fs::write(dir.join("app/photo.design"), photo).unwrap();
1637        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1638        let first = designs.resolve("app/photo.design").unwrap();
1639        assert_eq!(first.images.len(), 1, "one file shown twice");
1640        save(
1641            &designs,
1642            &dir.join("app/photo.design"),
1643            &photo.replace("<Frame>", "<Frame fill=\"#ffffff\">"),
1644        );
1645        let second = designs.resolve("app/photo.design").unwrap();
1646        assert_ne!(first.root, second.root);
1647        let file = |s: &Scene| s.images.values().next().unwrap().clone();
1648        assert!(Arc::ptr_eq(&file(&first), &file(&second)));
1649        // A saved image file is decoded anew; the scene keeps the decode it
1650        // has while the bytes are the same.
1651        std::fs::write(dir.join("app/p.jpg"), &shirt).unwrap();
1652        designs.changed(&dir.join("app/p.jpg"));
1653        let third = designs.resolve("app/photo.design").unwrap();
1654        let decoded = lock(&designs.0.sources)["app/p.jpg"]
1655            .image
1656            .clone()
1657            .unwrap()
1658            .unwrap();
1659        assert!(!Arc::ptr_eq(&file(&second), &decoded));
1660        assert_eq!(file(&third).id, decoded.id);
1661    }
1662
1663    #[test]
1664    fn an_image_that_does_not_decode_is_a_problem_everywhere() {
1665        let dir = served("broken-image");
1666        let mut broken = b"\x89PNG\r\n\x1a\n".to_vec();
1667        broken.extend(b"garbage");
1668        std::fs::write(dir.join("app/broken.png"), broken).unwrap();
1669        std::fs::write(
1670            dir.join("app/photo.design"),
1671            "<Frame>\n  <Image src=\"./broken.png\" width={50} height={50} />\n</Frame>\n",
1672        )
1673        .unwrap();
1674        let expected = "app/photo.design:2:10: src: ./broken.png is a PNG that doesn't decode";
1675        // What `devpage check` reports…
1676        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1677        let found = designs.problems("app/photo.design");
1678        assert_eq!(found.len(), 1, "{found:?}");
1679        assert!(found[0].to_string().starts_with(expected), "{found:?}");
1680        // …and the PNG, instead of a blank picture.
1681        let png = designs.png("app/photo.design", Theme::Light).unwrap_err();
1682        assert!(png.starts_with(expected), "{png}");
1683    }
1684
1685    #[test]
1686    fn only_the_designs_made_from_a_changed_file_are_announced() {
1687        let dir = served("store");
1688        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1689        let updates = announced(&designs);
1690        assert!(designs.resolve("app/screen.design").is_ok());
1691        assert!(designs.resolve("/app/other.design").is_ok());
1692        let resolutions = || {
1693            designs
1694                .0
1695                .resolutions
1696                .load(std::sync::atomic::Ordering::Relaxed)
1697        };
1698        assert_eq!(resolutions(), 2);
1699        assert!(designs.resolve("app/screen.design").is_ok());
1700        assert_eq!(resolutions(), 2, "kept in memory");
1701
1702        save(
1703            &designs,
1704            &dir.join("app/button.design"),
1705            &BUTTON.replace("#2563eb", "#16a34a"),
1706        );
1707        assert_eq!(updates.try_recv().unwrap(), "app/screen.design");
1708        assert!(
1709            updates.try_recv().is_err(),
1710            "other.design doesn't use the button"
1711        );
1712        assert_eq!(resolutions(), 3, "only screen.design was resolved again");
1713
1714        // Saving the same scene again announces nothing.
1715        save(
1716            &designs,
1717            &dir.join("app/button.design"),
1718            &BUTTON.replace("#2563eb", "#16a34a"),
1719        );
1720        assert!(updates.try_recv().is_err());
1721
1722        // A file nothing was made from is not even looked at.
1723        save(&designs, &dir.join("app/notes.txt"), "hi");
1724        assert!(updates.try_recv().is_err());
1725    }
1726
1727    /// A save that lands while a design is being resolved — after its file
1728    /// was read, before the result is kept — is not lost: the stale result
1729    /// is never kept, and the design is resolved from the new file.
1730    #[test]
1731    fn a_save_while_a_design_resolves_is_not_lost() {
1732        let dir = served("race");
1733        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1734        let other = dir.join("app/other.design");
1735        let saver = designs.clone();
1736        let saved = std::sync::atomic::AtomicBool::new(false);
1737        *lock(&designs.0.after_read) = Some(Box::new(move |path: &str| {
1738            if path == "app/other.design" && !saved.swap(true, std::sync::atomic::Ordering::SeqCst)
1739            {
1740                save(&saver, &other, &OTHER.replace("{50}", "{20}"));
1741            }
1742        }));
1743        let width =
1744            |designs: &Designs| match designs.resolve("app/other.design").unwrap().root.width {
1745                devpage_design::scene::Size::Px(w) => w,
1746                other => panic!("{other:?}"),
1747            };
1748        assert_eq!(width(&designs), 20.0, "resolved from the saved file");
1749        *lock(&designs.0.after_read) = None;
1750        assert_eq!(width(&designs), 20.0, "and kept so");
1751    }
1752
1753    #[test]
1754    fn no_design_file_stops_the_store() {
1755        let dir = served("hostile");
1756        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1757        let other = dir.join("app/other.design");
1758        assert!(designs.png("app/other.design", Theme::Light).is_ok());
1759        // A colour with a pasted zero-width space, saved over a design held
1760        // in memory: what once panicked the watcher's thread.
1761        save(&designs, &other, &OTHER.replace("#000000", "#000\u{200b}"));
1762        let problems = designs.png("app/other.design", Theme::Light).unwrap_err();
1763        assert!(
1764            problems.contains("fill: #000\u{200b} is not a color"),
1765            "{problems}"
1766        );
1767        // Deep nesting, a huge number, a truncated file: problems, all.
1768        for text in [
1769            "<Frame>".repeat(5000),
1770            "<Frame width={99999999999} />".to_string(),
1771            "<Frame fill=\"#ff".to_string(),
1772        ] {
1773            save(&designs, &other, &text);
1774            assert!(
1775                designs.png("app/other.design", Theme::Light).is_err(),
1776                "{text:.40}"
1777            );
1778        }
1779        // And the store still sees saves afterwards.
1780        save(&designs, &other, &OTHER.replace("{50}", "{20}"));
1781        let png = designs.png("app/other.design", Theme::Light).unwrap();
1782        let (_, w, h) = devpage_design::compare::pixels(&png).unwrap();
1783        assert_eq!((w, h), (20, 20));
1784    }
1785
1786    /// An image a design shows that isn't there yet is one of its files,
1787    /// named as it would be: once it is added, the design is announced,
1788    /// and draws with it.
1789    #[test]
1790    fn adding_a_missing_image_redraws_the_design_with_it() {
1791        let dir = served("missing-image");
1792        std::fs::write(
1793            dir.join("app/later.design"),
1794            "<Frame>\n  <Image src=\"./later.png\" width={8} height={8} />\n</Frame>\n",
1795        )
1796        .unwrap();
1797        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1798        let updates = announced(&designs);
1799        assert!(designs.png("app/later.design", Theme::Light).is_err());
1800        assert!(
1801            designs
1802                .made_of("app/later.design")
1803                .contains(&dir.join("app/later.png")),
1804            "{:?}",
1805            designs.made_of("app/later.design")
1806        );
1807        std::fs::write(dir.join("app/later.png"), png_file(8, 8, "#00c800")).unwrap();
1808        designs.changed(&dir.join("app/later.png"));
1809        assert_eq!(updates.try_recv().unwrap(), "app/later.design");
1810        let png = designs.png("app/later.design", Theme::Light).unwrap();
1811        let (pixels, w, h) = devpage_design::compare::pixels(&png).unwrap();
1812        assert_eq!((w, h), (8, 8));
1813        assert_eq!(&pixels[..3], &[0x00, 0xc8, 0x00]);
1814    }
1815
1816    /// A font folder a design's themes name is part of what the design is
1817    /// made of: a font added to it is a change to the design, which is
1818    /// announced and draws with it; one removed takes it away again.
1819    #[test]
1820    fn a_font_added_to_a_listed_folder_redraws_the_design_with_it() {
1821        let dir = served("listed-folder");
1822        let fonts = Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts");
1823        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1824        std::fs::copy(
1825            fonts.join("Inter-Regular.ttf"),
1826            dir.join("app/fonts/Body/Body-Regular.ttf"),
1827        )
1828        .unwrap();
1829        std::fs::write(
1830            dir.join("app/themes.yml"),
1831            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1832        )
1833        .unwrap();
1834        std::fs::write(
1835            dir.join("app/bold.design"),
1836            "<Frame><Text font=\"body\" weight={700}>Hello</Text></Frame>\n",
1837        )
1838        .unwrap();
1839        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1840        let updates = announced(&designs);
1841        let problems = designs.resolve("app/bold.design").unwrap_err();
1842        assert!(problems[0].message.contains("has no 700"), "{problems:?}");
1843        assert!(
1844            designs
1845                .made_of("app/bold.design")
1846                .contains(&dir.join("app/fonts/Body")),
1847            "{:?}",
1848            designs.made_of("app/bold.design")
1849        );
1850        let bold = dir.join("app/fonts/Body/Body-Bold.ttf");
1851        std::fs::copy(fonts.join("Inter-Bold.ttf"), &bold).unwrap();
1852        designs.changed(&bold);
1853        assert_eq!(updates.try_recv().unwrap(), "app/bold.design");
1854        assert!(designs.problems("app/bold.design").is_empty());
1855        assert!(designs.png("app/bold.design", Theme::Light).is_ok());
1856        assert!(designs.made_of("app/bold.design").contains(&bold));
1857        std::fs::remove_file(&bold).unwrap();
1858        designs.changed(&bold);
1859        assert_eq!(updates.try_recv().unwrap(), "app/bold.design");
1860        assert!(!designs.problems("app/bold.design").is_empty());
1861    }
1862
1863    #[test]
1864    fn creating_a_missing_import_resolves_the_design_again() {
1865        let dir = served("create");
1866        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1867        std::fs::remove_file(dir.join("app/button.design")).unwrap();
1868        let problems = designs.resolve("app/screen.design").unwrap_err();
1869        assert!(problems[0].message.contains("no such file"), "{problems:?}");
1870        save(&designs, &dir.join("app/button.design"), BUTTON);
1871        assert!(designs.resolve("app/screen.design").is_ok());
1872    }
1873
1874    /// Creating, editing and deleting a `themes.yml` resolves again exactly
1875    /// the designs that read it — a missing one included.
1876    #[test]
1877    fn a_themes_file_resolves_again_only_the_designs_that_read_it() {
1878        let dir = served("themes");
1879        std::fs::write(
1880            dir.join("app/themed.design"),
1881            "<Frame width={10} height={10} fill={theme.bg} />",
1882        )
1883        .unwrap();
1884        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1885        let updates = announced(&designs);
1886        let problems = designs.resolve("app/themed.design").unwrap_err();
1887        assert!(
1888            problems[0].message.contains("no themes.yml"),
1889            "{problems:?}"
1890        );
1891        assert!(designs.resolve("app/other.design").is_ok());
1892        let fill = |designs: &Designs| designs.resolve("app/themed.design").unwrap().root.fill;
1893        // Created at the top: two folders above the design.
1894        save(&designs, &dir.join("themes.yml"), THEMES);
1895        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1896        assert!(updates.try_recv().is_err(), "other.design reads no themes");
1897        let top = fill(&designs);
1898        // Created between them: it overrides the top one.
1899        save(
1900            &designs,
1901            &dir.join("app/themes.yml"),
1902            &THEMES.replace("#000000", "#111111"),
1903        );
1904        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1905        assert_ne!(fill(&designs), top);
1906        // Deleted: the top one again.
1907        std::fs::remove_file(dir.join("app/themes.yml")).unwrap();
1908        designs.changed(&dir.join("app/themes.yml"));
1909        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1910        assert_eq!(fill(&designs), top);
1911        assert!(updates.try_recv().is_err());
1912    }
1913
1914    /// A font is one of the files of the designs set in it: a change to a
1915    /// font file, or to any file in a font folder, resolves again exactly
1916    /// the designs whose text is set in it — `devpage check` reports the
1917    /// same — and the scene carries the face its text uses.
1918    #[test]
1919    fn a_font_change_resolves_again_only_the_designs_set_in_it() {
1920        let dir = served("fonts");
1921        let regular = std::fs::read(
1922            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Regular.ttf"),
1923        )
1924        .unwrap();
1925        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1926        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &regular).unwrap();
1927        std::fs::write(dir.join("app/fonts/Body/OFL.txt"), "licence").unwrap();
1928        std::fs::write(
1929            dir.join("app/themes.yml"),
1930            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1931        )
1932        .unwrap();
1933        std::fs::write(
1934            dir.join("app/set.design"),
1935            r#"<Frame><Text font="body">Hello</Text></Frame>"#,
1936        )
1937        .unwrap();
1938        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1939        let updates = announced(&designs);
1940        let scene = designs.resolve("app/set.design").unwrap();
1941        assert_eq!(scene.fonts.len(), 1);
1942        assert!(designs.resolve("app/other.design").is_ok());
1943        let resolutions = || {
1944            designs
1945                .0
1946                .resolutions
1947                .load(std::sync::atomic::Ordering::Relaxed)
1948        };
1949        let before = resolutions();
1950        // The licence changes: the folder's listing is the same, the design
1951        // is resolved again and unchanged.
1952        save(&designs, &dir.join("app/fonts/Body/OFL.txt"), "licence, v2");
1953        assert_eq!(resolutions(), before + 1, "only set.design");
1954        assert!(updates.try_recv().is_err());
1955        // A second regular face arrives: a problem at the themes' font.
1956        let mut copy = regular.clone();
1957        copy.push(0);
1958        std::fs::write(dir.join("app/fonts/Body/Copy.ttf"), &copy).unwrap();
1959        designs.changed(&dir.join("app/fonts/Body/Copy.ttf"));
1960        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1961        assert!(updates.try_recv().is_err());
1962        let expected = "app/themes.yml:3:3: fonts.body: ./fonts/Body holds two files of weight 400: Body-Regular.ttf and Copy.ttf";
1963        let problems = designs.resolve("app/set.design").unwrap_err();
1964        assert_eq!(problems[0].to_string(), expected);
1965        assert_eq!(
1966            Designs::new(&ServedFolder::new(&dir).unwrap()).problems("/app/set.design")[0]
1967                .to_string(),
1968            expected
1969        );
1970        // It goes again, and a font file itself is saved over as bold.
1971        std::fs::remove_file(dir.join("app/fonts/Body/Copy.ttf")).unwrap();
1972        designs.changed(&dir.join("app/fonts/Body/Copy.ttf"));
1973        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1974        let bold = std::fs::read(
1975            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Bold.ttf"),
1976        )
1977        .unwrap();
1978        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &bold).unwrap();
1979        designs.changed(&dir.join("app/fonts/Body/Body-Regular.ttf"));
1980        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1981        assert_eq!(
1982            designs.resolve("app/set.design").unwrap_err()[0].message,
1983            "weight: Inter has no 400; it has 700"
1984        );
1985        assert!(updates.try_recv().is_err());
1986    }
1987
1988    #[test]
1989    fn a_design_outside_the_served_folder_is_never_read() {
1990        let dir = served("outside");
1991        std::fs::write(dir.join("../outside.design"), OTHER).unwrap();
1992        let designs = Designs::new(&ServedFolder::new(&dir.join("app")).unwrap());
1993        assert!(designs.resolve("../outside.design").is_err());
1994    }
1995
1996    /// A path outside the served folder is named by nothing, so it changes
1997    /// nothing: not even a file `/x` at the top of the disk stands in for
1998    /// one at the top of the folder, whose listing stays kept.
1999    #[test]
2000    fn a_change_outside_the_served_folder_forgets_nothing() {
2001        let dir = served("changed-outside");
2002        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2003        let reading = Reading {
2004            store: &designs.0,
2005            asked: RefCell::new(Vec::new()),
2006            seen: RefCell::new(Vec::new()),
2007        };
2008        assert_eq!(
2009            reading.list(""),
2010            Some(Vec::new()),
2011            "the top holds only app/"
2012        );
2013        assert!(lock(&designs.0.sources).contains_key("/"));
2014        designs.changed(Path::new("/outside.design"));
2015        assert!(
2016            lock(&designs.0.sources).contains_key("/"),
2017            "the top's listing is still kept"
2018        );
2019    }
2020    /// Saves through the store — rows inserted at the front and the end,
2021    /// edited, removed, a component and a theme changed, a break and its fix
2022    /// — each sent to two streams, one joining late, as the store's one
2023    /// patch: the browser's copy is a fresh resolve of the files every time.
2024    #[test]
2025    fn a_save_is_sent_as_what_it_reached() {
2026        let dir = served("reached");
2027        std::fs::write(dir.join("app/themes.yml"), THEMES).unwrap();
2028        let screen = |rows: &[&str]| {
2029            let rows: String = rows
2030                .iter()
2031                .map(|r| format!("  <Frame fill={{theme.bg}}><Text>{r}</Text></Frame>\n"))
2032                .collect();
2033            format!(
2034                "import Button from \"./button.design\"\n<Frame layout=\"column\">\n{rows}  <Button label=\"Pay\" />\n</Frame>\n"
2035            )
2036        };
2037        let file = dir.join("app/list.design");
2038        let mut rows = vec!["a", "b", "c"];
2039        std::fs::write(&file, screen(&rows)).unwrap();
2040        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2041        let path = "app/list.design";
2042        let decode = |s: &proto::Scene| {
2043            devpage_design::wire::decode_scene(s, (&Default::default(), &Default::default()))
2044                .unwrap()
2045        };
2046        let Next::Scene(mut v, scene) = designs.next(path, None) else {
2047            panic!()
2048        };
2049        let mut browser = decode(&scene);
2050        let mut uses = devpage_design::scene::Uses::of(&browser.root);
2051        let mut late = None;
2052        type Edit = Box<dyn Fn(&mut Vec<&'static str>) -> (&'static str, String)>;
2053        let edits: Vec<Edit> = vec![
2054            Box::new(|r| {
2055                r.insert(0, "front");
2056                ("app/list.design", String::new())
2057            }),
2058            Box::new(|r| {
2059                r.push("end");
2060                ("app/list.design", String::new())
2061            }),
2062            Box::new(|r| {
2063                r[1] = "edited";
2064                ("app/list.design", String::new())
2065            }),
2066            Box::new(|r| {
2067                r.remove(2);
2068                ("app/list.design", String::new())
2069            }),
2070            Box::new(|_| ("app/button.design", BUTTON.replace("#2563eb", "#16a34a"))),
2071            Box::new(|_| ("app/themes.yml", THEMES.replace("#ffffff", "#eeeeee"))),
2072            Box::new(|_| {
2073                (
2074                    "app/button.design",
2075                    "<Frame fill={theme.nope} />".to_string(),
2076                )
2077            }),
2078            Box::new(|r| {
2079                r.insert(1, "while broken");
2080                ("app/list.design", String::new())
2081            }),
2082            Box::new(|_| ("app/button.design", BUTTON.to_string())),
2083        ];
2084        for (step, edit) in edits.iter().enumerate() {
2085            let (name, text) = edit(&mut rows);
2086            let text = if text.is_empty() { screen(&rows) } else { text };
2087            save(&designs, &dir.join(name), &text);
2088            match designs.next(path, Some(v)) {
2089                Next::Problems(_) => continue,
2090                Next::Patch(now, patch) => {
2091                    v = now;
2092                    devpage_design::wire::apply(&mut browser, &mut uses, &patch)
2093                        .unwrap_or_else(|e| panic!("step {step}: {e}"));
2094                }
2095                Next::Current(_) => {}
2096                Next::Scene(..) => panic!("step {step}: sent whole"),
2097            }
2098            // A store that sent the scene by patches holds a fresh resolve.
2099            let kept = designs.resolve(path).unwrap();
2100            assert_eq!(
2101                devpage_design::wire::encode(&browser.root),
2102                devpage_design::wire::encode(&kept.root),
2103                "step {step}"
2104            );
2105            let fresh = Designs::new(&ServedFolder::new(&dir).unwrap())
2106                .resolve(path)
2107                .unwrap();
2108            assert_eq!(
2109                kept.root.children.len(),
2110                fresh.root.children.len(),
2111                "step {step}"
2112            );
2113            if step == 3 {
2114                late = Some(designs.next(path, None));
2115            }
2116        }
2117        assert!(matches!(late, Some(Next::Scene(..))));
2118        // Nothing was resolved whole after the first.
2119        let kept = designs.0.kept(path);
2120        assert_eq!(lock(&kept).held.as_ref().unwrap().resolution.wholes(), 0);
2121    }
2122}
2123
2124#[cfg(test)]
2125mod bench {
2126    use super::testing::*;
2127    use super::*;
2128
2129    /// Save → patch for one row's text, at 1k/10k/100k rows: run with
2130    /// `cargo test --release -p devpage-core bench -- --ignored --nocapture`.
2131    #[test]
2132    #[ignore]
2133    fn save_to_patch() {
2134        for n in [1_000usize, 10_000, 100_000] {
2135            let dir = served(&format!("bench-{n}"));
2136            let file = dir.join("app/list.design");
2137            let rows = |edited: usize| -> String {
2138                let body: String = (0..n)
2139                    .map(|i| {
2140                        let t = if i == edited {
2141                            "Edited".to_string()
2142                        } else {
2143                            format!("Row {i}")
2144                        };
2145                        format!("<Frame width={{400}} height={{20}}><Text>{t}</Text></Frame>\n")
2146                    })
2147                    .collect();
2148                format!("<Frame layout=\"column\">\n{body}</Frame>\n")
2149            };
2150            std::fs::write(&file, rows(usize::MAX)).unwrap();
2151            let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2152            let v = match designs.next("app/list.design", None) {
2153                Next::Scene(v, _) => v,
2154                _ => panic!(),
2155            };
2156            std::fs::write(&file, rows(n / 2)).unwrap();
2157            // Save to patch: resolving again, the drawing brought across
2158            // (whose layout is the layout's own cost), and the patch read
2159            // for a stream.
2160            let t = std::time::Instant::now();
2161            designs.changed(&file);
2162            let store = t.elapsed();
2163            let t = std::time::Instant::now();
2164            let Next::Patch(_, patch) = designs.next("app/list.design", Some(v)) else {
2165                panic!()
2166            };
2167            let diff = t.elapsed();
2168            // Of the store's time, resolving again alone.
2169            let (mut saves, scene) = devpage_design::resolve::Resolution::new(
2170                &std::collections::HashMap::<String, String>::from([(
2171                    "a.design".to_string(),
2172                    rows(usize::MAX),
2173                )]),
2174                "a.design",
2175            )
2176            .unwrap();
2177            // Its scene held undrawn: the edits applied, nothing brought
2178            // along.
2179            let mut design = Design::new(scene);
2180            let (renderer, applies) = (Mutex::new(Renderer::new()), Default::default());
2181            let mut holder = Bringing {
2182                design: &mut design,
2183                renderer: &renderer,
2184                applies: &applies,
2185            };
2186            let files = std::collections::HashMap::<String, String>::from([(
2187                "a.design".to_string(),
2188                rows(n / 2),
2189            )]);
2190            let t = std::time::Instant::now();
2191            let _ = saves.update(&mut holder, &files, &["a.design".to_string()]);
2192            let again = t.elapsed();
2193            // Of the rest, matching the saved file's elements against its
2194            // last parse — what the store does and the line above doesn't.
2195            let last = devpage_design::parse::parse(&rows(usize::MAX)).unwrap();
2196            let t = std::time::Instant::now();
2197            let fresh = devpage_design::parse::parse(&rows(n / 2)).unwrap();
2198            let parsed = t.elapsed();
2199            let t = std::time::Instant::now();
2200            let _ = devpage_design::ids::matched(fresh, &last);
2201            let matched = t.elapsed();
2202            eprintln!(
2203                "{n}: resolve again {again:?}, of the store's: parse {parsed:?}, match {matched:?}"
2204            );
2205            eprintln!(
2206                "{n}: store {store:?}, stream's patch {diff:?}, {} ops",
2207                patch.ops.len()
2208            );
2209        }
2210    }
2211}