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    use codespec_rust_macro::spec;
1111
1112    /// What the store tells, as it tells it.
1113    fn announced(designs: &Designs) -> std::sync::mpsc::Receiver<String> {
1114        let (tx, rx) = std::sync::mpsc::channel();
1115        let tx = Mutex::new(tx);
1116        designs.on_change(move |path| {
1117            let _ = lock(&tx).send(path.to_string());
1118        });
1119        rx
1120    }
1121
1122    /// A design 100,000 pixels tall: a column of 1,000 rows, 400 by 100, the
1123    /// row `edited` set apart by its fill.
1124    fn tall(dir: &Path, edited: Option<usize>) {
1125        let rows: String = (0..1000)
1126            .map(|i| {
1127                let fill = if Some(i) == edited { 0xff0000 } else { i * 997 };
1128                format!("<Frame width={{400}} height={{100}} fill=\"#{fill:06x}\" />")
1129            })
1130            .collect();
1131        save_quietly(
1132            &dir.join("app/huge.design"),
1133            &format!("<Frame layout=\"column\">{rows}</Frame>"),
1134        );
1135    }
1136
1137    fn save_quietly(file: &Path, text: &str) {
1138        std::fs::write(file, text).unwrap();
1139    }
1140
1141    fn painted(designs: &Designs) -> usize {
1142        designs
1143            .0
1144            .painted
1145            .swap(0, std::sync::atomic::Ordering::Relaxed)
1146    }
1147
1148    /// Counts what is written.
1149    #[derive(Default)]
1150    struct Count(usize);
1151    impl std::io::Write for Count {
1152        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
1153            self.0 += b.len();
1154            Ok(b.len())
1155        }
1156        fn flush(&mut self) -> std::io::Result<()> {
1157            Ok(())
1158        }
1159    }
1160
1161    /// Two folders in one store — two versions of a document — share its
1162    /// one tile cache and nothing else: the same address in each is its own
1163    /// design, with its own validator; asked for again under the same mount
1164    /// it is the one already kept; and a folder no one holds leaves the
1165    /// store with its tiles.
1166    #[test]
1167    fn folders_in_one_store_share_its_tiles_and_never_each_others_designs() {
1168        let one = served("mount-one");
1169        let two = served("mount-two");
1170        std::fs::write(two.join("app/other.design"), BOX_RED).unwrap();
1171        let store = Store::new();
1172        let first = store.designs("/d/x/v/1", &ServedFolder::new(&one).unwrap());
1173        let second = store.designs("/d/x/v/2", &ServedFolder::new(&two).unwrap());
1174        let png_one = first.png("app/other.design", Theme::Light).unwrap();
1175        let png_two = second.png("app/other.design", Theme::Light).unwrap();
1176        assert_ne!(png_one, png_two, "each folder's own design");
1177        assert_ne!(
1178            first.etag("app/other.design", Theme::Light),
1179            second.etag("app/other.design", Theme::Light),
1180            "a validator names the mount"
1181        );
1182        let tiles = || lock(&store.0.tiles).cost();
1183        let both = tiles();
1184        assert_eq!(both, 2 * TILE_BYTES, "one cache holds both");
1185
1186        // The same mount and folder: the design already kept.
1187        let again = store.designs("/d/x/v/1", &ServedFolder::new(&one).unwrap());
1188        again.png("app/other.design", Theme::Light).unwrap();
1189        assert_eq!(painted(&first), 1, "painted once, for the first ask");
1190        assert_eq!(store.folders(), 2);
1191
1192        drop((first, again));
1193        assert_eq!(store.folders(), 1);
1194        assert_eq!(tiles(), TILE_BYTES, "its tiles went with it");
1195        drop(second);
1196        assert_eq!((store.folders(), tiles()), (0, 0));
1197    }
1198
1199    const BOX_RED: &str = r##"<Frame width={50} height={50} fill="#ff0000" />
1200"##;
1201
1202    /// The store knows everything a design is made of — itself, what it
1203    /// imports, its themes, the font folder it listed and the font files its
1204    /// text is set in — from the one resolve that keeps it, whether or not
1205    /// the design resolves: a file it asked for that isn't there too, named
1206    /// as it would be — a `themes.yml` above it, an image to come.
1207    #[test]
1208    fn the_store_knows_everything_a_design_is_made_of() {
1209        let dir = served("files");
1210        let regular = std::fs::read(
1211            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Regular.ttf"),
1212        )
1213        .unwrap();
1214        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1215        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &regular).unwrap();
1216        std::fs::write(
1217            dir.join("app/themes.yml"),
1218            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1219        )
1220        .unwrap();
1221        std::fs::write(
1222            dir.join("app/set.design"),
1223            "import Button from \"./button.design\"\n\n<Frame><Text font=\"body\">Hello</Text><Button label=\"Go\" /></Frame>\n",
1224        )
1225        .unwrap();
1226        std::fs::write(
1227            dir.join("app/gone.design"),
1228            "<Frame>\n  <Image src=\"./gone.png\" width={5} height={5} />\n</Frame>\n",
1229        )
1230        .unwrap();
1231        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1232        let names = |path: &str| -> Vec<String> {
1233            designs
1234                .made_of(path)
1235                .iter()
1236                .map(|f| crate::folder::slashed(f.strip_prefix(&dir).unwrap()))
1237                .collect()
1238        };
1239        assert_eq!(
1240            names("/app/set.design"),
1241            [
1242                "app/button.design",
1243                "app/fonts/Body",
1244                "app/fonts/Body/Body-Regular.ttf",
1245                "app/set.design",
1246                "app/themes.yml",
1247                "themes.yml",
1248            ]
1249        );
1250        assert!(designs.problems("app/set.design").is_empty());
1251        assert_eq!(
1252            names("app/gone.design"),
1253            ["app/gone.design", "app/gone.png"]
1254        );
1255        assert_eq!(designs.problems("app/gone.design").len(), 1);
1256        assert_eq!(names("app/nothing.design"), ["app/nothing.design"]);
1257        assert_eq!(designs.resolutions(), 3, "each resolved once");
1258    }
1259
1260    /// A design too wide for a row of tiles in one band is banded in strips,
1261    /// painted and never cached: its PNG is right and the cache stays empty.
1262    #[test]
1263    fn a_design_too_wide_for_tiles_is_banded_in_strips_never_cached() {
1264        let dir = served("wide");
1265        std::fs::write(
1266            dir.join("app/wide.design"),
1267            r##"<Frame width={40000} height={20} fill="#ffffff"><Rect x={39990} y={10} width={10} height={10} fill="#0000ff" /></Frame>"##,
1268        )
1269        .unwrap();
1270        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1271        let png = designs.png("app/wide.design", Theme::Light).unwrap();
1272        let (px, w, h) = devpage_design::compare::pixels(&png).unwrap();
1273        assert_eq!((w, h), (40_000, 20));
1274        let at = |x: usize, y: usize| px[(y * 40_000 + x) * 4..][..4].to_vec();
1275        assert_eq!(at(0, 0), vec![255, 255, 255, 255]);
1276        assert_eq!(at(39_999, 19), vec![0, 0, 255, 255]);
1277        assert_eq!(painted(&designs), 0);
1278        assert_eq!(lock(&designs.0.shared.tiles).cost(), 0);
1279    }
1280
1281    /// A design 100,000 pixels tall has a PNG, streamed band by band from the
1282    /// store's cache, which never holds more than its cap; asked for again,
1283    /// only the tiles the cap dropped are painted again.
1284    #[test]
1285    #[spec("drawing-time-depends-on-the-screen")]
1286    fn a_design_100000_pixels_tall_streams_its_png_from_a_capped_cache() {
1287        let dir = served("huge");
1288        tall(&dir, None);
1289        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1290        assert!(designs.problems("/app/huge.design").is_empty());
1291        let started = std::time::Instant::now();
1292        let png = designs.png("app/huge.design", Theme::Light).unwrap();
1293        let took = started.elapsed();
1294        let (px, w, h) = devpage_design::compare::pixels(&png).unwrap();
1295        assert_eq!((w, h), (400, 100_000));
1296        let c = 999 * 997;
1297        let at = (99_950 * 400 + 200) * 4;
1298        assert_eq!(&px[at..at + 3], &[(c >> 16) as u8, (c >> 8) as u8, c as u8]);
1299        // 391 rows of 2 tiles, all painted once; the cache holds 256 of them.
1300        assert_eq!(painted(&designs), 782);
1301        let held = lock(&designs.0.shared.tiles).cost();
1302        assert!(held <= TILES_CAP, "{held}");
1303        assert_eq!(held, TILES_CAP);
1304        eprintln!("100,000-px PNG: {took:?}, {} bytes", png.len());
1305        let mut count = Count::default();
1306        designs
1307            .png_to("app/huge.design", Theme::Light, &mut count)
1308            .unwrap();
1309        assert_eq!(count.0, png.len());
1310        // The last bands were cached; the first ones were dropped for them,
1311        // and dropping them again as the PNG goes on, all are painted again.
1312        assert_eq!(painted(&designs), 782);
1313        assert!(lock(&designs.0.shared.tiles).cost() <= TILES_CAP);
1314    }
1315
1316    /// A PNG asked for twice paints nothing the second time; after an edit to
1317    /// one node of a design 100,000 pixels tall, only the tiles over it.
1318    #[test]
1319    #[spec("drawing-time-depends-on-the-screen")]
1320    fn an_edit_repaints_only_the_tiles_over_it() {
1321        let dir = served("edit");
1322        std::fs::write(
1323            dir.join("app/small.design"),
1324            r##"<Frame width={600} height={300} fill="#336699" />"##,
1325        )
1326        .unwrap();
1327        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1328        let first = designs.png("app/small.design", Theme::Light).unwrap();
1329        assert_eq!(painted(&designs), 6);
1330        assert_eq!(
1331            designs.png("app/small.design", Theme::Light).unwrap(),
1332            first
1333        );
1334        assert_eq!(painted(&designs), 0);
1335
1336        tall(&dir, None);
1337        // Room for the whole design, to count only what the edit needs.
1338        *lock(&designs.0.shared.tiles) = Cache::new(usize::MAX);
1339        let before = designs.png("app/huge.design", Theme::Light).unwrap();
1340        assert_eq!(painted(&designs), 782);
1341        // Row 500 is y 50,000 to 50,100, inside tile row 195: its two tiles.
1342        tall(&dir, Some(500));
1343        designs.changed(&dir.join("app/huge.design"));
1344        let started = std::time::Instant::now();
1345        let after = designs.png("app/huge.design", Theme::Light).unwrap();
1346        let took = started.elapsed();
1347        assert_eq!(painted(&designs), 2);
1348        eprintln!("PNG after an edit: {took:?}, 2 tiles painted");
1349        let (a, _, _) = devpage_design::compare::pixels(&before).unwrap();
1350        let (b, _, _) = devpage_design::compare::pixels(&after).unwrap();
1351        let row = |px: &[u8], y: usize| px[(y * 400 + 10) * 4..(y * 400 + 10) * 4 + 4].to_vec();
1352        assert_eq!(row(&b, 50_050), vec![255, 0, 0, 255]);
1353        assert_eq!(row(&a, 49_950), row(&b, 49_950));
1354        assert_eq!(row(&a, 50_150), row(&b, 50_150));
1355        // The edit undone: those tiles again, and the PNG as before.
1356        tall(&dir, None);
1357        designs.changed(&dir.join("app/huge.design"));
1358        assert_eq!(
1359            designs.png("app/huge.design", Theme::Light).unwrap(),
1360            before
1361        );
1362        assert_eq!(painted(&designs), 2);
1363    }
1364
1365    /// A design's scene is held once, by its `Design`: a save that changes
1366    /// it applies its edits there once — never again to a copy beside it —
1367    /// and what the store serves, the scene and the PNG, is that one scene.
1368    #[test]
1369    fn a_save_applies_its_edits_to_the_designs_one_scene_once() {
1370        let dir = served("once");
1371        let file = dir.join("app/once.design");
1372        let design = |fill: &str| {
1373            format!(
1374                r##"<Frame width={{60}} height={{40}} fill="#ffffff"><Rect width={{20}} height={{20}} fill="{fill}" /></Frame>"##
1375            )
1376        };
1377        std::fs::write(&file, design("#ff0000")).unwrap();
1378        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1379        designs.png("app/once.design", Theme::Light).unwrap();
1380        let applies = || designs.0.applies.load(std::sync::atomic::Ordering::Relaxed);
1381        assert_eq!(applies(), 0);
1382
1383        save(&designs, &file, &design("#00ff00"));
1384        assert_eq!(applies(), 1);
1385        let scene = designs.resolve("app/once.design").unwrap();
1386        let fresh = devpage_design::resolve(
1387            &std::collections::HashMap::from([("a.design".to_string(), design("#00ff00"))]),
1388            "a.design",
1389        )
1390        .unwrap();
1391        assert_eq!(scene.root.children[0].fill, fresh.root.children[0].fill);
1392        let png = designs.png("app/once.design", Theme::Light).unwrap();
1393        let (px, _, _) = devpage_design::compare::pixels(&png).unwrap();
1394        assert_eq!(
1395            px[(10 * 60 + 10) * 4..(10 * 60 + 10) * 4 + 4],
1396            [0, 255, 0, 255]
1397        );
1398        // A save that changes nothing applies nothing.
1399        save(&designs, &file, &design("#00ff00"));
1400        assert_eq!(applies(), 1);
1401    }
1402
1403    /// A themed design keeps a drawing in each theme, and each theme its own
1404    /// tiles; a design that stops using its themes drops its dark ones.
1405    #[test]
1406    fn each_theme_keeps_its_own_tiles() {
1407        let dir = served("theme-tiles");
1408        std::fs::write(dir.join("app/themes.yml"), THEMES).unwrap();
1409        let file = dir.join("app/t.design");
1410        std::fs::write(&file, "<Frame width={300} height={100} fill={theme.bg} />").unwrap();
1411        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1412        let light = designs.png("app/t.design", Theme::Light).unwrap();
1413        let dark = designs.png("app/t.design", Theme::Dark).unwrap();
1414        assert_ne!(light, dark);
1415        assert_eq!(painted(&designs), 4);
1416        designs.png("app/t.design", Theme::Light).unwrap();
1417        designs.png("app/t.design", Theme::Dark).unwrap();
1418        assert_eq!(painted(&designs), 0);
1419        std::fs::write(
1420            &file,
1421            r##"<Frame width={300} height={100} fill="#00ff00" />"##,
1422        )
1423        .unwrap();
1424        designs.changed(&file);
1425        assert!(
1426            lock(&designs.0.shared.tiles)
1427                .iter()
1428                .all(|(t, _, _)| t.key.theme == Theme::Light)
1429        );
1430        // Not themed: the dark PNG is the light one.
1431        let green = designs.png("app/t.design", Theme::Light).unwrap();
1432        assert_eq!(designs.png("app/t.design", Theme::Dark).unwrap(), green);
1433    }
1434
1435    /// A PNG file `w` × `h` pixels of one `fill`, painted by the engine.
1436    fn png_file(w: u32, h: u32, fill: &str) -> Vec<u8> {
1437        let files: HashMap<String, String> = [(
1438            "p.design".to_string(),
1439            format!(r##"<Frame width={{{w}}} height={{{h}}} fill="{fill}" />"##),
1440        )]
1441        .into();
1442        let scene = devpage_design::resolve(&files, "p.design").unwrap();
1443        devpage_design::png::fresh(&mut Renderer::new(), &scene, Theme::Light).unwrap()
1444    }
1445
1446    /// An image that grows mid-session past what the GPU's atlas holds —
1447    /// three 4096-pixel squares and two small images, one of which turns
1448    /// into a fourth square — makes the design's problem, at its `src`, in
1449    /// place of a PNG; a save in the meantime is kept. Once the image is
1450    /// small again, the PNG is the one a fresh store paints: every tile the
1451    /// last good drawing left is painted again.
1452    #[test]
1453    fn an_image_that_breaks_mid_session_draws_as_fresh_once_mended() {
1454        let dir = served("image-breaks");
1455        for (name, fill) in [("a", "#dc0000"), ("b", "#00c800"), ("c", "#0000dc")] {
1456            std::fs::write(
1457                dir.join(format!("app/{name}.png")),
1458                png_file(4096, 4096, fill),
1459            )
1460            .unwrap();
1461        }
1462        let small = png_file(8, 8, "#c800c8");
1463        std::fs::write(dir.join("app/x.png"), &small).unwrap();
1464        std::fs::write(dir.join("app/y.png"), png_file(8, 8, "#00c8c8")).unwrap();
1465        let design = |fill: &str| {
1466            let images: String = "abcxy"
1467                .chars()
1468                .map(|c| format!("\n  <Image src=\"./{c}.png\" width={{40}} height={{40}} />"))
1469                .collect();
1470            format!(
1471                r##"<Frame layout="row" gap={{4}} padding={{8}} fill="#ffffff">{images}
1472  <Rect width={{40}} height={{40}} fill="{fill}" />
1473</Frame>
1474"##
1475            )
1476        };
1477        let file = dir.join("app/grows.design");
1478        std::fs::write(&file, design("#000000")).unwrap();
1479        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1480        designs.png("app/grows.design", Theme::Light).unwrap();
1481
1482        std::fs::write(dir.join("app/x.png"), png_file(4096, 4096, "#c800c8")).unwrap();
1483        designs.changed(&dir.join("app/x.png"));
1484        let broken = designs.png("app/grows.design", Theme::Light).unwrap_err();
1485        assert!(
1486            broken.starts_with("app/grows.design:") && broken.contains("doesn't fit"),
1487            "{broken}"
1488        );
1489        save(&designs, &file, &design("#ffaa00"));
1490        assert!(designs.png("app/grows.design", Theme::Light).is_err());
1491
1492        std::fs::write(dir.join("app/x.png"), &small).unwrap();
1493        designs.changed(&dir.join("app/x.png"));
1494        let mended = designs.png("app/grows.design", Theme::Light).unwrap();
1495        let fresh = Designs::new(&ServedFolder::new(&dir).unwrap())
1496            .png("app/grows.design", Theme::Light)
1497            .unwrap();
1498        assert!(mended == fresh, "the mended PNG isn't a fresh one");
1499    }
1500
1501    /// A PNG whose reader has stopped reading holds up no save: the store
1502    /// takes the save while the PNG waits, and the PNG, once read again,
1503    /// ends rather than finish from the next scene.
1504    #[test]
1505    fn a_save_lands_while_a_png_is_not_read() {
1506        let dir = served("unread");
1507        tall(&dir, None);
1508        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1509        designs.resolve("app/huge.design").unwrap();
1510        /// A reader that stops after the first write until it is let go.
1511        struct Stalled(std::sync::mpsc::Receiver<()>, bool);
1512        impl std::io::Write for Stalled {
1513            fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
1514                if self.1 {
1515                    self.1 = false;
1516                    let _ = self.0.recv();
1517                }
1518                Ok(b.len())
1519            }
1520            fn flush(&mut self) -> std::io::Result<()> {
1521                Ok(())
1522            }
1523        }
1524        let (go, wait) = std::sync::mpsc::channel();
1525        let reader = designs.clone();
1526        let png = std::thread::spawn(move || {
1527            reader.png_to("app/huge.design", Theme::Light, Stalled(wait, true))
1528        });
1529        // Let the PNG reach its first write.
1530        std::thread::sleep(std::time::Duration::from_millis(200));
1531        let (done, saved) = std::sync::mpsc::channel();
1532        let saver = designs.clone();
1533        let file = dir.join("app/huge.design");
1534        let save_dir = dir.clone();
1535        std::thread::spawn(move || {
1536            tall(&save_dir, Some(3));
1537            saver.changed(&file);
1538            let _ = done.send(());
1539        });
1540        assert!(
1541            saved
1542                .recv_timeout(std::time::Duration::from_secs(20))
1543                .is_ok(),
1544            "the save waited for the PNG's reader"
1545        );
1546        go.send(()).unwrap();
1547        let ended = png.join().unwrap().unwrap_err();
1548        assert!(
1549            ended.contains("changed while its PNG was written"),
1550            "{ended}"
1551        );
1552        // The next PNG is the new scene's.
1553        let next = designs.png("app/huge.design", Theme::Light).unwrap();
1554        let (px, _, _) = devpage_design::compare::pixels(&next).unwrap();
1555        let at = (350 * 400 + 10) * 4;
1556        assert_eq!(&px[at..at + 4], &[255, 0, 0, 255]);
1557    }
1558
1559    /// A writer that fails — a client gone — stops the painting there.
1560    #[test]
1561    fn a_writer_that_fails_stops_the_painting() {
1562        let dir = served("gone");
1563        tall(&dir, None);
1564        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1565        struct Gone;
1566        impl std::io::Write for Gone {
1567            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
1568                Err(std::io::Error::other("gone"))
1569            }
1570            fn flush(&mut self) -> std::io::Result<()> {
1571                Ok(())
1572            }
1573        }
1574        assert!(
1575            designs
1576                .png_to("app/huge.design", Theme::Light, Gone)
1577                .is_err()
1578        );
1579        assert!(painted(&designs) <= 2, "painted past the first band");
1580    }
1581
1582    /// Images that don't fit the GPU's atlas together are a problem at the
1583    /// `src` of the first that doesn't, wherever the design is looked at.
1584    #[test]
1585    fn images_too_many_for_the_gpu_are_a_problem_at_their_src() {
1586        /// `w`x`h`-name.png is an image file that size, never decoded.
1587        struct Sized(String);
1588        impl Files for Sized {
1589            fn bytes(&self, path: &str) -> Option<Vec<u8>> {
1590                (path == "app/a.design").then(|| self.0.clone().into_bytes())
1591            }
1592            fn list(&self, _: &str) -> Option<Vec<String>> {
1593                None
1594            }
1595            fn image(&self, path: &str) -> Option<Result<Arc<ImageFile>, String>> {
1596                let (size, _) = path.strip_prefix("app/")?.split_once('-')?;
1597                let (w, h) = size.split_once('x')?;
1598                let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
1599                Some(Ok(Arc::new(ImageFile {
1600                    id: devpage_design::scene::ImageId::of(path.as_bytes()),
1601                    bytes: Vec::new(),
1602                    width: w,
1603                    height: h,
1604                    pixels: Arc::new(vec![0; 4 * w as usize * h as usize]),
1605                    pixels_width: w,
1606                    pixels_height: h,
1607                })))
1608            }
1609        }
1610        let images: String = "abcde"
1611            .chars()
1612            .map(|c| format!("\n  <Image src=\"4096x4096-{c}.png\" width={{40}} height={{40}} />"))
1613            .collect();
1614        let design = Sized(format!(r#"<Frame layout="row">{images}</Frame>"#));
1615        let scene = devpage_design::resolve(&design, "app/a.design").unwrap();
1616        let mut held = Design::new(scene);
1617        let undrawable = held.draw(&mut Renderer::new(), Theme::Light).unwrap_err();
1618        let found = problem("app/a.design", undrawable.clone());
1619        assert_eq!(found.len(), 1);
1620        assert!(
1621            found[0]
1622                .to_string()
1623                .starts_with("app/a.design:6:10: this doesn't fit: "),
1624            "{found:?}"
1625        );
1626    }
1627
1628    /// An image file is decoded once per read of it: a save of the design
1629    /// showing it, or of another file, doesn't decode it again.
1630    #[test]
1631    fn a_save_decodes_only_the_image_that_changed() {
1632        let dir = served("decode-once");
1633        let shirt = std::fs::read(
1634            Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/designs/checkout/shirt.jpg"),
1635        )
1636        .unwrap();
1637        std::fs::write(dir.join("app/p.jpg"), &shirt).unwrap();
1638        let photo = "<Frame>\n  <Image src=\"./p.jpg\" />\n  <Image src=\"./p.jpg\" />\n</Frame>\n";
1639        std::fs::write(dir.join("app/photo.design"), photo).unwrap();
1640        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1641        let first = designs.resolve("app/photo.design").unwrap();
1642        assert_eq!(first.images.len(), 1, "one file shown twice");
1643        save(
1644            &designs,
1645            &dir.join("app/photo.design"),
1646            &photo.replace("<Frame>", "<Frame fill=\"#ffffff\">"),
1647        );
1648        let second = designs.resolve("app/photo.design").unwrap();
1649        assert_ne!(first.root, second.root);
1650        let file = |s: &Scene| s.images.values().next().unwrap().clone();
1651        assert!(Arc::ptr_eq(&file(&first), &file(&second)));
1652        // A saved image file is decoded anew; the scene keeps the decode it
1653        // has while the bytes are the same.
1654        std::fs::write(dir.join("app/p.jpg"), &shirt).unwrap();
1655        designs.changed(&dir.join("app/p.jpg"));
1656        let third = designs.resolve("app/photo.design").unwrap();
1657        let decoded = lock(&designs.0.sources)["app/p.jpg"]
1658            .image
1659            .clone()
1660            .unwrap()
1661            .unwrap();
1662        assert!(!Arc::ptr_eq(&file(&second), &decoded));
1663        assert_eq!(file(&third).id, decoded.id);
1664    }
1665
1666    #[test]
1667    fn an_image_that_does_not_decode_is_a_problem_everywhere() {
1668        let dir = served("broken-image");
1669        let mut broken = b"\x89PNG\r\n\x1a\n".to_vec();
1670        broken.extend(b"garbage");
1671        std::fs::write(dir.join("app/broken.png"), broken).unwrap();
1672        std::fs::write(
1673            dir.join("app/photo.design"),
1674            "<Frame>\n  <Image src=\"./broken.png\" width={50} height={50} />\n</Frame>\n",
1675        )
1676        .unwrap();
1677        let expected = "app/photo.design:2:10: src: ./broken.png is a PNG that doesn't decode";
1678        // What `devpage check` reports…
1679        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1680        let found = designs.problems("app/photo.design");
1681        assert_eq!(found.len(), 1, "{found:?}");
1682        assert!(found[0].to_string().starts_with(expected), "{found:?}");
1683        // …and the PNG, instead of a blank picture.
1684        let png = designs.png("app/photo.design", Theme::Light).unwrap_err();
1685        assert!(png.starts_with(expected), "{png}");
1686    }
1687
1688    #[test]
1689    fn only_the_designs_made_from_a_changed_file_are_announced() {
1690        let dir = served("store");
1691        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1692        let updates = announced(&designs);
1693        assert!(designs.resolve("app/screen.design").is_ok());
1694        assert!(designs.resolve("/app/other.design").is_ok());
1695        let resolutions = || {
1696            designs
1697                .0
1698                .resolutions
1699                .load(std::sync::atomic::Ordering::Relaxed)
1700        };
1701        assert_eq!(resolutions(), 2);
1702        assert!(designs.resolve("app/screen.design").is_ok());
1703        assert_eq!(resolutions(), 2, "kept in memory");
1704
1705        save(
1706            &designs,
1707            &dir.join("app/button.design"),
1708            &BUTTON.replace("#2563eb", "#16a34a"),
1709        );
1710        assert_eq!(updates.try_recv().unwrap(), "app/screen.design");
1711        assert!(
1712            updates.try_recv().is_err(),
1713            "other.design doesn't use the button"
1714        );
1715        assert_eq!(resolutions(), 3, "only screen.design was resolved again");
1716
1717        // Saving the same scene again announces nothing.
1718        save(
1719            &designs,
1720            &dir.join("app/button.design"),
1721            &BUTTON.replace("#2563eb", "#16a34a"),
1722        );
1723        assert!(updates.try_recv().is_err());
1724
1725        // A file nothing was made from is not even looked at.
1726        save(&designs, &dir.join("app/notes.txt"), "hi");
1727        assert!(updates.try_recv().is_err());
1728    }
1729
1730    /// A save that lands while a design is being resolved — after its file
1731    /// was read, before the result is kept — is not lost: the stale result
1732    /// is never kept, and the design is resolved from the new file.
1733    #[test]
1734    fn a_save_while_a_design_resolves_is_not_lost() {
1735        let dir = served("race");
1736        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1737        let other = dir.join("app/other.design");
1738        let saver = designs.clone();
1739        let saved = std::sync::atomic::AtomicBool::new(false);
1740        *lock(&designs.0.after_read) = Some(Box::new(move |path: &str| {
1741            if path == "app/other.design" && !saved.swap(true, std::sync::atomic::Ordering::SeqCst)
1742            {
1743                save(&saver, &other, &OTHER.replace("{50}", "{20}"));
1744            }
1745        }));
1746        let width =
1747            |designs: &Designs| match designs.resolve("app/other.design").unwrap().root.width {
1748                devpage_design::scene::Size::Px(w) => w,
1749                other => panic!("{other:?}"),
1750            };
1751        assert_eq!(width(&designs), 20.0, "resolved from the saved file");
1752        *lock(&designs.0.after_read) = None;
1753        assert_eq!(width(&designs), 20.0, "and kept so");
1754    }
1755
1756    #[test]
1757    fn no_design_file_stops_the_store() {
1758        let dir = served("hostile");
1759        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1760        let other = dir.join("app/other.design");
1761        assert!(designs.png("app/other.design", Theme::Light).is_ok());
1762        // A colour with a pasted zero-width space, saved over a design held
1763        // in memory: what once panicked the watcher's thread.
1764        save(&designs, &other, &OTHER.replace("#000000", "#000\u{200b}"));
1765        let problems = designs.png("app/other.design", Theme::Light).unwrap_err();
1766        assert!(
1767            problems.contains("fill: #000\u{200b} is not a color"),
1768            "{problems}"
1769        );
1770        // Deep nesting, a huge number, a truncated file: problems, all.
1771        for text in [
1772            "<Frame>".repeat(5000),
1773            "<Frame width={99999999999} />".to_string(),
1774            "<Frame fill=\"#ff".to_string(),
1775        ] {
1776            save(&designs, &other, &text);
1777            assert!(
1778                designs.png("app/other.design", Theme::Light).is_err(),
1779                "{text:.40}"
1780            );
1781        }
1782        // And the store still sees saves afterwards.
1783        save(&designs, &other, &OTHER.replace("{50}", "{20}"));
1784        let png = designs.png("app/other.design", Theme::Light).unwrap();
1785        let (_, w, h) = devpage_design::compare::pixels(&png).unwrap();
1786        assert_eq!((w, h), (20, 20));
1787    }
1788
1789    /// An image a design shows that isn't there yet is one of its files,
1790    /// named as it would be: once it is added, the design is announced,
1791    /// and draws with it.
1792    #[test]
1793    fn adding_a_missing_image_redraws_the_design_with_it() {
1794        let dir = served("missing-image");
1795        std::fs::write(
1796            dir.join("app/later.design"),
1797            "<Frame>\n  <Image src=\"./later.png\" width={8} height={8} />\n</Frame>\n",
1798        )
1799        .unwrap();
1800        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1801        let updates = announced(&designs);
1802        assert!(designs.png("app/later.design", Theme::Light).is_err());
1803        assert!(
1804            designs
1805                .made_of("app/later.design")
1806                .contains(&dir.join("app/later.png")),
1807            "{:?}",
1808            designs.made_of("app/later.design")
1809        );
1810        std::fs::write(dir.join("app/later.png"), png_file(8, 8, "#00c800")).unwrap();
1811        designs.changed(&dir.join("app/later.png"));
1812        assert_eq!(updates.try_recv().unwrap(), "app/later.design");
1813        let png = designs.png("app/later.design", Theme::Light).unwrap();
1814        let (pixels, w, h) = devpage_design::compare::pixels(&png).unwrap();
1815        assert_eq!((w, h), (8, 8));
1816        assert_eq!(&pixels[..3], &[0x00, 0xc8, 0x00]);
1817    }
1818
1819    /// A font folder a design's themes name is part of what the design is
1820    /// made of: a font added to it is a change to the design, which is
1821    /// announced and draws with it; one removed takes it away again.
1822    #[test]
1823    fn a_font_added_to_a_listed_folder_redraws_the_design_with_it() {
1824        let dir = served("listed-folder");
1825        let fonts = Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts");
1826        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1827        std::fs::copy(
1828            fonts.join("Inter-Regular.ttf"),
1829            dir.join("app/fonts/Body/Body-Regular.ttf"),
1830        )
1831        .unwrap();
1832        std::fs::write(
1833            dir.join("app/themes.yml"),
1834            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1835        )
1836        .unwrap();
1837        std::fs::write(
1838            dir.join("app/bold.design"),
1839            "<Frame><Text font=\"body\" weight={700}>Hello</Text></Frame>\n",
1840        )
1841        .unwrap();
1842        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1843        let updates = announced(&designs);
1844        let problems = designs.resolve("app/bold.design").unwrap_err();
1845        assert!(problems[0].message.contains("has no 700"), "{problems:?}");
1846        assert!(
1847            designs
1848                .made_of("app/bold.design")
1849                .contains(&dir.join("app/fonts/Body")),
1850            "{:?}",
1851            designs.made_of("app/bold.design")
1852        );
1853        let bold = dir.join("app/fonts/Body/Body-Bold.ttf");
1854        std::fs::copy(fonts.join("Inter-Bold.ttf"), &bold).unwrap();
1855        designs.changed(&bold);
1856        assert_eq!(updates.try_recv().unwrap(), "app/bold.design");
1857        assert!(designs.problems("app/bold.design").is_empty());
1858        assert!(designs.png("app/bold.design", Theme::Light).is_ok());
1859        assert!(designs.made_of("app/bold.design").contains(&bold));
1860        std::fs::remove_file(&bold).unwrap();
1861        designs.changed(&bold);
1862        assert_eq!(updates.try_recv().unwrap(), "app/bold.design");
1863        assert!(!designs.problems("app/bold.design").is_empty());
1864    }
1865
1866    #[test]
1867    fn creating_a_missing_import_resolves_the_design_again() {
1868        let dir = served("create");
1869        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1870        std::fs::remove_file(dir.join("app/button.design")).unwrap();
1871        let problems = designs.resolve("app/screen.design").unwrap_err();
1872        assert!(problems[0].message.contains("no such file"), "{problems:?}");
1873        save(&designs, &dir.join("app/button.design"), BUTTON);
1874        assert!(designs.resolve("app/screen.design").is_ok());
1875    }
1876
1877    /// Creating, editing and deleting a `themes.yml` resolves again exactly
1878    /// the designs that read it — a missing one included.
1879    #[test]
1880    fn a_themes_file_resolves_again_only_the_designs_that_read_it() {
1881        let dir = served("themes");
1882        std::fs::write(
1883            dir.join("app/themed.design"),
1884            "<Frame width={10} height={10} fill={theme.bg} />",
1885        )
1886        .unwrap();
1887        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1888        let updates = announced(&designs);
1889        let problems = designs.resolve("app/themed.design").unwrap_err();
1890        assert!(
1891            problems[0].message.contains("no themes.yml"),
1892            "{problems:?}"
1893        );
1894        assert!(designs.resolve("app/other.design").is_ok());
1895        let fill = |designs: &Designs| designs.resolve("app/themed.design").unwrap().root.fill;
1896        // Created at the top: two folders above the design.
1897        save(&designs, &dir.join("themes.yml"), THEMES);
1898        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1899        assert!(updates.try_recv().is_err(), "other.design reads no themes");
1900        let top = fill(&designs);
1901        // Created between them: it overrides the top one.
1902        save(
1903            &designs,
1904            &dir.join("app/themes.yml"),
1905            &THEMES.replace("#000000", "#111111"),
1906        );
1907        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1908        assert_ne!(fill(&designs), top);
1909        // Deleted: the top one again.
1910        std::fs::remove_file(dir.join("app/themes.yml")).unwrap();
1911        designs.changed(&dir.join("app/themes.yml"));
1912        assert_eq!(updates.try_recv().unwrap(), "app/themed.design");
1913        assert_eq!(fill(&designs), top);
1914        assert!(updates.try_recv().is_err());
1915    }
1916
1917    /// A font is one of the files of the designs set in it: a change to a
1918    /// font file, or to any file in a font folder, resolves again exactly
1919    /// the designs whose text is set in it — `devpage check` reports the
1920    /// same — and the scene carries the face its text uses.
1921    #[test]
1922    fn a_font_change_resolves_again_only_the_designs_set_in_it() {
1923        let dir = served("fonts");
1924        let regular = std::fs::read(
1925            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Regular.ttf"),
1926        )
1927        .unwrap();
1928        std::fs::create_dir_all(dir.join("app/fonts/Body")).unwrap();
1929        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &regular).unwrap();
1930        std::fs::write(dir.join("app/fonts/Body/OFL.txt"), "licence").unwrap();
1931        std::fs::write(
1932            dir.join("app/themes.yml"),
1933            "kind: themes\nfonts:\n  body: ./fonts/Body\nlight: {}\ndark: {}\n",
1934        )
1935        .unwrap();
1936        std::fs::write(
1937            dir.join("app/set.design"),
1938            r#"<Frame><Text font="body">Hello</Text></Frame>"#,
1939        )
1940        .unwrap();
1941        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
1942        let updates = announced(&designs);
1943        let scene = designs.resolve("app/set.design").unwrap();
1944        assert_eq!(scene.fonts.len(), 1);
1945        assert!(designs.resolve("app/other.design").is_ok());
1946        let resolutions = || {
1947            designs
1948                .0
1949                .resolutions
1950                .load(std::sync::atomic::Ordering::Relaxed)
1951        };
1952        let before = resolutions();
1953        // The licence changes: the folder's listing is the same, the design
1954        // is resolved again and unchanged.
1955        save(&designs, &dir.join("app/fonts/Body/OFL.txt"), "licence, v2");
1956        assert_eq!(resolutions(), before + 1, "only set.design");
1957        assert!(updates.try_recv().is_err());
1958        // A second regular face arrives: a problem at the themes' font.
1959        let mut copy = regular.clone();
1960        copy.push(0);
1961        std::fs::write(dir.join("app/fonts/Body/Copy.ttf"), &copy).unwrap();
1962        designs.changed(&dir.join("app/fonts/Body/Copy.ttf"));
1963        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1964        assert!(updates.try_recv().is_err());
1965        let expected = "app/themes.yml:3:3: fonts.body: ./fonts/Body holds two files of weight 400: Body-Regular.ttf and Copy.ttf";
1966        let problems = designs.resolve("app/set.design").unwrap_err();
1967        assert_eq!(problems[0].to_string(), expected);
1968        assert_eq!(
1969            Designs::new(&ServedFolder::new(&dir).unwrap()).problems("/app/set.design")[0]
1970                .to_string(),
1971            expected
1972        );
1973        // It goes again, and a font file itself is saved over as bold.
1974        std::fs::remove_file(dir.join("app/fonts/Body/Copy.ttf")).unwrap();
1975        designs.changed(&dir.join("app/fonts/Body/Copy.ttf"));
1976        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1977        let bold = std::fs::read(
1978            Path::new(env!("CARGO_MANIFEST_DIR")).join("../design/fonts/Inter-Bold.ttf"),
1979        )
1980        .unwrap();
1981        std::fs::write(dir.join("app/fonts/Body/Body-Regular.ttf"), &bold).unwrap();
1982        designs.changed(&dir.join("app/fonts/Body/Body-Regular.ttf"));
1983        assert_eq!(updates.try_recv().unwrap(), "app/set.design");
1984        assert_eq!(
1985            designs.resolve("app/set.design").unwrap_err()[0].message,
1986            "weight: Inter has no 400; it has 700"
1987        );
1988        assert!(updates.try_recv().is_err());
1989    }
1990
1991    #[test]
1992    fn a_design_outside_the_served_folder_is_never_read() {
1993        let dir = served("outside");
1994        std::fs::write(dir.join("../outside.design"), OTHER).unwrap();
1995        let designs = Designs::new(&ServedFolder::new(&dir.join("app")).unwrap());
1996        assert!(designs.resolve("../outside.design").is_err());
1997    }
1998
1999    /// A path outside the served folder is named by nothing, so it changes
2000    /// nothing: not even a file `/x` at the top of the disk stands in for
2001    /// one at the top of the folder, whose listing stays kept.
2002    #[test]
2003    fn a_change_outside_the_served_folder_forgets_nothing() {
2004        let dir = served("changed-outside");
2005        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2006        let reading = Reading {
2007            store: &designs.0,
2008            asked: RefCell::new(Vec::new()),
2009            seen: RefCell::new(Vec::new()),
2010        };
2011        assert_eq!(
2012            reading.list(""),
2013            Some(Vec::new()),
2014            "the top holds only app/"
2015        );
2016        assert!(lock(&designs.0.sources).contains_key("/"));
2017        designs.changed(Path::new("/outside.design"));
2018        assert!(
2019            lock(&designs.0.sources).contains_key("/"),
2020            "the top's listing is still kept"
2021        );
2022    }
2023    /// Saves through the store — rows inserted at the front and the end,
2024    /// edited, removed, a component and a theme changed, a break and its fix
2025    /// — each sent to two streams, one joining late, as the store's one
2026    /// patch: the browser's copy is a fresh resolve of the files every time.
2027    #[test]
2028    fn a_save_is_sent_as_what_it_reached() {
2029        let dir = served("reached");
2030        std::fs::write(dir.join("app/themes.yml"), THEMES).unwrap();
2031        let screen = |rows: &[&str]| {
2032            let rows: String = rows
2033                .iter()
2034                .map(|r| format!("  <Frame fill={{theme.bg}}><Text>{r}</Text></Frame>\n"))
2035                .collect();
2036            format!(
2037                "import Button from \"./button.design\"\n<Frame layout=\"column\">\n{rows}  <Button label=\"Pay\" />\n</Frame>\n"
2038            )
2039        };
2040        let file = dir.join("app/list.design");
2041        let mut rows = vec!["a", "b", "c"];
2042        std::fs::write(&file, screen(&rows)).unwrap();
2043        let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2044        let path = "app/list.design";
2045        let decode = |s: &proto::Scene| {
2046            devpage_design::wire::decode_scene(s, (&Default::default(), &Default::default()))
2047                .unwrap()
2048        };
2049        let Next::Scene(mut v, scene) = designs.next(path, None) else {
2050            panic!()
2051        };
2052        let mut browser = decode(&scene);
2053        let mut uses = devpage_design::scene::Uses::of(&browser.root);
2054        let mut late = None;
2055        type Edit = Box<dyn Fn(&mut Vec<&'static str>) -> (&'static str, String)>;
2056        let edits: Vec<Edit> = vec![
2057            Box::new(|r| {
2058                r.insert(0, "front");
2059                ("app/list.design", String::new())
2060            }),
2061            Box::new(|r| {
2062                r.push("end");
2063                ("app/list.design", String::new())
2064            }),
2065            Box::new(|r| {
2066                r[1] = "edited";
2067                ("app/list.design", String::new())
2068            }),
2069            Box::new(|r| {
2070                r.remove(2);
2071                ("app/list.design", String::new())
2072            }),
2073            Box::new(|_| ("app/button.design", BUTTON.replace("#2563eb", "#16a34a"))),
2074            Box::new(|_| ("app/themes.yml", THEMES.replace("#ffffff", "#eeeeee"))),
2075            Box::new(|_| {
2076                (
2077                    "app/button.design",
2078                    "<Frame fill={theme.nope} />".to_string(),
2079                )
2080            }),
2081            Box::new(|r| {
2082                r.insert(1, "while broken");
2083                ("app/list.design", String::new())
2084            }),
2085            Box::new(|_| ("app/button.design", BUTTON.to_string())),
2086        ];
2087        for (step, edit) in edits.iter().enumerate() {
2088            let (name, text) = edit(&mut rows);
2089            let text = if text.is_empty() { screen(&rows) } else { text };
2090            save(&designs, &dir.join(name), &text);
2091            match designs.next(path, Some(v)) {
2092                Next::Problems(_) => continue,
2093                Next::Patch(now, patch) => {
2094                    v = now;
2095                    devpage_design::wire::apply(&mut browser, &mut uses, &patch)
2096                        .unwrap_or_else(|e| panic!("step {step}: {e}"));
2097                }
2098                Next::Current(_) => {}
2099                Next::Scene(..) => panic!("step {step}: sent whole"),
2100            }
2101            // A store that sent the scene by patches holds a fresh resolve.
2102            let kept = designs.resolve(path).unwrap();
2103            assert_eq!(
2104                devpage_design::wire::encode(&browser.root),
2105                devpage_design::wire::encode(&kept.root),
2106                "step {step}"
2107            );
2108            let fresh = Designs::new(&ServedFolder::new(&dir).unwrap())
2109                .resolve(path)
2110                .unwrap();
2111            assert_eq!(
2112                kept.root.children.len(),
2113                fresh.root.children.len(),
2114                "step {step}"
2115            );
2116            if step == 3 {
2117                late = Some(designs.next(path, None));
2118            }
2119        }
2120        assert!(matches!(late, Some(Next::Scene(..))));
2121        // Nothing was resolved whole after the first.
2122        let kept = designs.0.kept(path);
2123        assert_eq!(lock(&kept).held.as_ref().unwrap().resolution.wholes(), 0);
2124    }
2125}
2126
2127#[cfg(test)]
2128mod bench {
2129    use super::testing::*;
2130    use super::*;
2131
2132    /// Save → patch for one row's text, at 1k/10k/100k rows: run with
2133    /// `cargo test --release -p devpage-core bench -- --ignored --nocapture`.
2134    #[test]
2135    #[ignore]
2136    fn save_to_patch() {
2137        for n in [1_000usize, 10_000, 100_000] {
2138            let dir = served(&format!("bench-{n}"));
2139            let file = dir.join("app/list.design");
2140            let rows = |edited: usize| -> String {
2141                let body: String = (0..n)
2142                    .map(|i| {
2143                        let t = if i == edited {
2144                            "Edited".to_string()
2145                        } else {
2146                            format!("Row {i}")
2147                        };
2148                        format!("<Frame width={{400}} height={{20}}><Text>{t}</Text></Frame>\n")
2149                    })
2150                    .collect();
2151                format!("<Frame layout=\"column\">\n{body}</Frame>\n")
2152            };
2153            std::fs::write(&file, rows(usize::MAX)).unwrap();
2154            let designs = Designs::new(&ServedFolder::new(&dir).unwrap());
2155            let v = match designs.next("app/list.design", None) {
2156                Next::Scene(v, _) => v,
2157                _ => panic!(),
2158            };
2159            std::fs::write(&file, rows(n / 2)).unwrap();
2160            // Save to patch: resolving again, the drawing brought across
2161            // (whose layout is the layout's own cost), and the patch read
2162            // for a stream.
2163            let t = std::time::Instant::now();
2164            designs.changed(&file);
2165            let store = t.elapsed();
2166            let t = std::time::Instant::now();
2167            let Next::Patch(_, patch) = designs.next("app/list.design", Some(v)) else {
2168                panic!()
2169            };
2170            let diff = t.elapsed();
2171            // Of the store's time, resolving again alone.
2172            let (mut saves, scene) = devpage_design::resolve::Resolution::new(
2173                &std::collections::HashMap::<String, String>::from([(
2174                    "a.design".to_string(),
2175                    rows(usize::MAX),
2176                )]),
2177                "a.design",
2178            )
2179            .unwrap();
2180            // Its scene held undrawn: the edits applied, nothing brought
2181            // along.
2182            let mut design = Design::new(scene);
2183            let (renderer, applies) = (Mutex::new(Renderer::new()), Default::default());
2184            let mut holder = Bringing {
2185                design: &mut design,
2186                renderer: &renderer,
2187                applies: &applies,
2188            };
2189            let files = std::collections::HashMap::<String, String>::from([(
2190                "a.design".to_string(),
2191                rows(n / 2),
2192            )]);
2193            let t = std::time::Instant::now();
2194            let _ = saves.update(&mut holder, &files, &["a.design".to_string()]);
2195            let again = t.elapsed();
2196            // Of the rest, matching the saved file's elements against its
2197            // last parse — what the store does and the line above doesn't.
2198            let last = devpage_design::parse::parse(&rows(usize::MAX)).unwrap();
2199            let t = std::time::Instant::now();
2200            let fresh = devpage_design::parse::parse(&rows(n / 2)).unwrap();
2201            let parsed = t.elapsed();
2202            let t = std::time::Instant::now();
2203            let _ = devpage_design::ids::matched(fresh, &last);
2204            let matched = t.elapsed();
2205            eprintln!(
2206                "{n}: resolve again {again:?}, of the store's: parse {parsed:?}, match {matched:?}"
2207            );
2208            eprintln!(
2209                "{n}: store {store:?}, stream's patch {diff:?}, {} ops",
2210                patch.ops.len()
2211            );
2212        }
2213    }
2214}