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