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