Skip to main content

sk_tree/
img.rs

1//! `<img src>` — the browser's URL grammar, resolved against a native base.
2//!
3//! Relative `src`s resolve against the app root ([`set_asset_base`]) through [`content_key`], as
4//! `fetch()` does; a packaged app looks them up in the payload store, never the disk. Every
5//! URL-taking feature resolves through here.
6
7use std::cell::{Cell, RefCell};
8use std::collections::HashMap;
9use std::path::{Component, Path, PathBuf};
10use std::sync::{OnceLock, RwLock};
11
12use gpui::{Image, ImageFormat, ImageSource, Resource};
13pub use sk_payload::content_key;
14use sk_payload::KeyError;
15use sk_runtime::redjs;
16use sk_runtime::redjs::webapi::url::BlobTarget;
17use sk_runtime::JsRuntime;
18
19/// A packaged app's asset store: app-root-relative key → bytes (mapped in the exe for the process's life).
20pub type AssetLookup = fn(&str) -> Option<&'static [u8]>;
21
22/// Explicit imported files outside a dev app's root.
23fn dev_asset_files() -> &'static RwLock<HashMap<String, PathBuf>> {
24    static FILES: OnceLock<RwLock<HashMap<String, PathBuf>>> = OnceLock::new();
25    FILES.get_or_init(|| RwLock::new(HashMap::new()))
26}
27
28/// Replaces the dev manifest's imported-file map, also visible to fetch's background threads. Only
29/// canonical generated keys and absolute paths pass.
30pub fn set_dev_asset_files(files: HashMap<String, PathBuf>) {
31    let files = files
32        .into_iter()
33        .filter(|(key, path)| {
34            key.starts_with("_vn/fs/")
35                && path.is_absolute()
36                && !key.contains(['\\', '\0'])
37                && key
38                    .split('/')
39                    .all(|part| !part.is_empty() && part != "." && part != "..")
40        })
41        .collect();
42    *dev_asset_files().write().unwrap() = files;
43}
44
45/// Resolves one explicitly mapped dev URL with the same normalization as image/font/video URLs and
46/// fetch. Unknown keys never escape the app root.
47pub fn dev_asset_file(src: &str) -> Option<PathBuf> {
48    let key = content_key(src)?;
49    dev_asset_files().read().unwrap().get(&key).cloned()
50}
51
52thread_local! {
53    static BASE: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
54    static STORE: Cell<Option<AssetLookup>> = const { Cell::new(None) };
55    static RESOLVED: RefCell<HashMap<u32, Memo>> = RefCell::new(HashMap::new());
56    static BLOB_PATHS: RefCell<HashMap<PathBuf, Snapshot>> = RefCell::new(HashMap::new());
57    /// Sources gpui's asset cache must drop at the next point with a `Window` ([`evict_pending`]).
58    static EVICT: RefCell<Vec<ImageSource>> = const { RefCell::new(Vec::new()) };
59}
60
61type Snapshot = (u64, Option<std::time::SystemTime>);
62
63/// What this module holds for devtools `mem`: (per-node memos, bytes of their src strings, distinct
64/// in-memory encoded images, their bytes, CSS background entries). The decodes are gpui's.
65pub(crate) fn mem_stats() -> (usize, usize, usize, usize, usize) {
66    let mut seen = std::collections::HashSet::new();
67    let (mut memos, mut src_bytes, mut images, mut image_bytes) = (0, 0, 0, 0);
68    let mut count = |source: &ImageSource| {
69        if let ImageSource::Image(img) = source {
70            if seen.insert(img.id) {
71                images += 1;
72                image_bytes += img.bytes.capacity();
73            }
74        }
75    };
76    RESOLVED.with(|m| {
77        for memo in m.borrow().values() {
78            memos += 1;
79            src_bytes += memo.src.capacity();
80            if let Some(s) = &memo.source {
81                count(s);
82            }
83        }
84    });
85    let backgrounds = BACKGROUNDS.with(|b| {
86        let b = b.borrow();
87        for layers in b.values() {
88            for (_, s) in layers {
89                if let Some(s) = s {
90                    count(s);
91                }
92            }
93        }
94        b.values().map(Vec::len).sum::<usize>()
95    });
96    (memos, src_bytes, images, image_bytes, backgrounds)
97}
98
99struct Memo {
100    src: String,
101    source: Option<ImageSource>,
102    blob: bool,
103}
104
105/// gpui caches a `Resource::Path` decode under the path and an `Image` under its id and drops neither:
106/// a blob source is handed back when no node shows it, and a picked file whose snapshot changed
107/// loses its stale decode.
108fn release(map: &HashMap<u32, Memo>, gone: Memo) {
109    let Memo {
110        source: Some(source),
111        blob: true,
112        ..
113    } = gone
114    else {
115        return;
116    };
117    if map
118        .values()
119        .any(|m| m.source.as_ref().is_some_and(|s| same_source(s, &source)))
120    {
121        return;
122    }
123    if let ImageSource::Resource(Resource::Path(p)) = &source {
124        BLOB_PATHS.with(|b| b.borrow_mut().remove(p.as_ref()));
125    }
126    EVICT.with(|e| e.borrow_mut().push(source));
127}
128
129fn same_source(a: &ImageSource, b: &ImageSource) -> bool {
130    match (a, b) {
131        (ImageSource::Resource(x), ImageSource::Resource(y)) => x == y,
132        (ImageSource::Image(x), ImageSource::Image(y)) => std::sync::Arc::ptr_eq(x, y),
133        _ => false,
134    }
135}
136
137/// Records that `path` goes to gpui as the file with `snap`; a decode of a different file is queued
138/// for eviction.
139fn note_blob_path(path: &Path, snap: Snapshot) {
140    let stale = BLOB_PATHS
141        .with(|b| b.borrow_mut().insert(path.to_path_buf(), snap))
142        .is_some_and(|old| old != snap);
143    if stale {
144        EVICT.with(|e| e.borrow_mut().push(path_source(path.to_path_buf())));
145    }
146}
147
148/// Hands queued sources back to gpui (the decode, and for a path its atlas tiles in every window).
149/// Needs a `Window`: called after `<img>` resolves its `src`, and once per frame ([`crate::frame_tick`]).
150pub(crate) fn evict_pending(window: &mut gpui::Window, cx: &mut gpui::App) {
151    let queued = EVICT.with(|e| std::mem::take(&mut *e.borrow_mut()));
152    for source in queued {
153        if let ImageSource::Resource(r) = &source {
154            if let Some(Ok(image)) = window.get_asset::<gpui::ImgResourceLoader>(r, cx) {
155                cx.drop_image(image, Some(window));
156            }
157        }
158        source.remove_asset(cx);
159    }
160}
161
162// gpui keeps every decode until told otherwise; the sweep evicts unshown sources, reduces decodes
163// drawn well below their size, and restores a reduced one that is drawn larger again.
164const EVICT_AFTER: std::time::Duration = std::time::Duration::from_secs(30);
165const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(1);
166
167#[derive(Clone, PartialEq, Eq, Hash)]
168enum SourceKey {
169    Resource(Resource),
170    Image(u64),
171}
172
173fn source_key(source: &ImageSource) -> Option<SourceKey> {
174    match source {
175        ImageSource::Resource(r) => Some(SourceKey::Resource(r.clone())),
176        ImageSource::Image(img) => Some(SourceKey::Image(img.id)),
177        _ => None,
178    }
179}
180
181#[derive(Default)]
182struct Residency {
183    known: HashMap<SourceKey, (ImageSource, std::time::Instant)>,
184    restoring: std::collections::HashSet<SourceKey>,
185    keep_full: std::collections::HashSet<SourceKey>,
186    /// Reduced decodes replaced by their full decode, whose tiles go next tick.
187    replaced: Vec<std::sync::Arc<gpui::RenderImage>>,
188    restored: bool,
189    last_sweep: Option<std::time::Instant>,
190    stats: ResidencyStats,
191}
192
193#[derive(Default, Clone, Copy, Debug)]
194pub struct ResidencyStats {
195    pub reduced: usize,
196    pub reduced_freed: usize,
197    pub restored: usize,
198    pub evicted: usize,
199    pub evicted_freed: usize,
200    pub known: usize,
201    pub kept_full: KeptFull,
202}
203
204#[derive(Default, Clone, Copy, Debug)]
205pub struct KeptFull {
206    pub not_still: usize,
207    pub undrawn: usize,
208    pub young: usize,
209    pub drawn_large: usize,
210    pub no_copy: usize,
211    pub small_saving: usize,
212    pub canvas_read: usize,
213    /// A window that keeps full decodes (`windows::WindowState::full_res_images`).
214    pub full_res_window: usize,
215}
216
217impl KeptFull {
218    fn count(&mut self, why: crate::resample::KeepFull) {
219        use crate::resample::KeepFull as K;
220        *match why {
221            K::NotStill => &mut self.not_still,
222            K::Undrawn => &mut self.undrawn,
223            K::Young => &mut self.young,
224            K::DrawnLarge => &mut self.drawn_large,
225            K::NoCopy => &mut self.no_copy,
226            K::SmallSaving => &mut self.small_saving,
227        } += 1;
228    }
229}
230
231thread_local! {
232    static RESIDENCY: RefCell<Residency> = RefCell::new(Residency::default());
233}
234
235pub(crate) fn note_known(source: Option<&ImageSource>) {
236    let Some(source) = source else { return };
237    let Some(key) = source_key(source) else {
238        return;
239    };
240    let now = std::time::Instant::now();
241    RESIDENCY.with(|r| r.borrow_mut().known.insert(key, (source.clone(), now)));
242}
243
244pub fn residency_stats() -> ResidencyStats {
245    RESIDENCY.with(|r| {
246        let r = r.borrow();
247        ResidencyStats {
248            known: r.known.len(),
249            ..r.stats
250        }
251    })
252}
253
254fn pixel_bytes(image: &gpui::RenderImage) -> usize {
255    (0..image.frame_count())
256        .map(|i| {
257            let s = image.size(i);
258            s.width.0.max(0) as usize * s.height.0.max(0) as usize * 4
259        })
260        .sum()
261}
262
263fn shown_sources() -> Vec<ImageSource> {
264    let mut out: Vec<ImageSource> = RESOLVED.with(|m| {
265        m.borrow()
266            .values()
267            .filter_map(|memo| memo.source.clone())
268            .collect()
269    });
270    BACKGROUNDS.with(|b| {
271        for layers in b.borrow().values() {
272            out.extend(layers.iter().filter_map(|(_, s)| s.clone()));
273        }
274    });
275    out
276}
277
278pub(crate) fn residency_tick(window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
279    let now = std::time::Instant::now();
280    let wanted = crate::resample::take_wanted_full();
281    let (replaced, restored, due) = RESIDENCY.with(|r| {
282        let mut r = r.borrow_mut();
283        let due = r
284            .last_sweep
285            .is_none_or(|t| now.duration_since(t) >= SWEEP_EVERY);
286        if due {
287            r.last_sweep = Some(now);
288        }
289        (
290            std::mem::take(&mut r.replaced),
291            std::mem::replace(&mut r.restored, false),
292            due,
293        )
294    });
295    let mut moved_tiles = !replaced.is_empty();
296    for image in replaced {
297        cx.drop_image(image, Some(window));
298    }
299    if !wanted.is_empty() {
300        restore(&wanted, cx);
301    }
302    if due {
303        moved_tiles |= sweep(now, window, cx);
304    }
305    if moved_tiles {
306        crate::resample::hold_replays_too();
307    }
308    restored
309}
310
311fn restore(wanted: &std::collections::HashSet<gpui::ImageId>, cx: &mut gpui::App) {
312    let shown = shown_sources();
313    for source in shown {
314        let Some(key) = source_key(&source) else {
315            continue;
316        };
317        let Some(cached) = source.cached(cx) else {
318            continue;
319        };
320        if !cached.is_reduced() || !wanted.contains(&cached.id) {
321            continue;
322        }
323        if !RESIDENCY.with(|r| r.borrow_mut().restoring.insert(key.clone())) {
324            continue;
325        }
326        let Some(task) = source.load_detached(cx) else {
327            RESIDENCY.with(|r| r.borrow_mut().restoring.remove(&key));
328            continue;
329        };
330        cx.spawn(async move |cx| {
331            let loaded = task.await;
332            cx.update(|cx| {
333                RESIDENCY.with(|r| r.borrow_mut().restoring.remove(&key));
334                let Ok(full) = loaded else { return };
335                let Some(reduced) = source.cached(cx).filter(|c| c.is_reduced()) else {
336                    return;
337                };
338                if source.replace_cached(full, cx) {
339                    RESIDENCY.with(|r| {
340                        let mut r = r.borrow_mut();
341                        r.replaced.push(reduced);
342                        r.restored = true;
343                        r.stats.restored += 1;
344                    });
345                }
346            });
347        })
348        .detach();
349    }
350}
351
352fn sweep(now: std::time::Instant, window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
353    let shown = shown_sources();
354    crate::resample::prune_uses();
355    let mut moved = false;
356    RESIDENCY.with(|r| {
357        let mut r = r.borrow_mut();
358        for source in &shown {
359            if let Some(key) = source_key(source) {
360                r.known.insert(key, (source.clone(), now));
361            }
362        }
363    });
364    let stale: Vec<(SourceKey, ImageSource)> = RESIDENCY.with(|r| {
365        let mut r = r.borrow_mut();
366        let keys: Vec<SourceKey> = r
367            .known
368            .iter()
369            .filter(|(_, (_, seen))| now.duration_since(*seen) >= EVICT_AFTER)
370            .map(|(k, _)| k.clone())
371            .collect();
372        keys.into_iter()
373            .filter_map(|k| r.known.remove(&k).map(|(s, _)| (k, s)))
374            .collect()
375    });
376    for (key, source) in stale {
377        if let Some(image) = source.cached(cx) {
378            let bytes = pixel_bytes(&image);
379            RESIDENCY.with(|r| {
380                let mut r = r.borrow_mut();
381                r.stats.evicted += 1;
382                r.stats.evicted_freed += bytes;
383            });
384            cx.drop_image(image, Some(window));
385            moved = true;
386        }
387        source.remove_asset(cx);
388        RESIDENCY.with(|r| r.borrow_mut().keep_full.remove(&key));
389    }
390    let mut kept = KeptFull::default();
391    let mut seen = std::collections::HashSet::new();
392    let pinned = full_res_sources();
393    for source in &shown {
394        let Some(key) = source_key(source) else {
395            continue;
396        };
397        if !seen.insert(key.clone()) {
398            continue;
399        }
400        let Some(full) = source.cached(cx) else {
401            continue;
402        };
403        if full.is_reduced() {
404            continue;
405        }
406        if pinned.contains(&key) {
407            kept.full_res_window += 1;
408            continue;
409        }
410        let (canvas_read, restoring) = RESIDENCY.with(|r| {
411            let r = r.borrow();
412            (r.keep_full.contains(&key), r.restoring.contains(&key))
413        });
414        if canvas_read || restoring {
415            kept.canvas_read += usize::from(canvas_read);
416            continue;
417        }
418        let copy = match crate::resample::reduced_copy(&full, now) {
419            Ok(copy) => copy,
420            Err(why) => {
421                kept.count(why);
422                continue;
423            }
424        };
425        let freed = pixel_bytes(&full).saturating_sub(pixel_bytes(&copy));
426        if source.replace_cached(copy, cx) {
427            RESIDENCY.with(|r| {
428                let mut r = r.borrow_mut();
429                r.stats.reduced += 1;
430                r.stats.reduced_freed += freed;
431            });
432            cx.drop_image(full, Some(window));
433            moved = true;
434        }
435    }
436    RESIDENCY.with(|r| r.borrow_mut().stats.kept_full = kept);
437    moved
438}
439
440/// Sources an `<img>` shows in a window that keeps full decodes: a media viewer zooms to 1:1, so a
441/// reduced copy would blur until the restore landed.
442fn full_res_sources() -> std::collections::HashSet<SourceKey> {
443    if !crate::windows::any_full_res() {
444        return std::collections::HashSet::new();
445    }
446    let nodes: Vec<(u32, SourceKey)> = RESOLVED.with(|m| {
447        m.borrow()
448            .iter()
449            .filter_map(|(id, memo)| Some((*id, source_key(memo.source.as_ref()?)?)))
450            .collect()
451    });
452    nodes
453        .into_iter()
454        .filter(|(id, _)| {
455            let k = crate::windows::window_of_node(*id);
456            crate::windows::peek(k, |w| w.full_res_images).unwrap_or(false)
457        })
458        .map(|(_, key)| key)
459        .collect()
460}
461
462fn keep_full(source: &ImageSource, image: &gpui::RenderImage) -> bool {
463    let Some(key) = source_key(source) else {
464        return true;
465    };
466    RESIDENCY.with(|r| r.borrow_mut().keep_full.insert(key));
467    if image.is_reduced() {
468        crate::resample::want_full(image.id);
469        return false;
470    }
471    true
472}
473
474#[cfg(test)]
475fn take_evictions() -> Vec<ImageSource> {
476    EVICT.with(|e| std::mem::take(&mut *e.borrow_mut()))
477}
478
479pub fn set_asset_base(dir: PathBuf) {
480    BASE.with(|b| *b.borrow_mut() = Some(dir));
481}
482
483pub fn asset_base() -> Option<PathBuf> {
484    BASE.with(|b| b.borrow().clone())
485}
486
487/// Makes relative `src`s resolve out of `lookup` instead of the disk; set once at boot, on the
488/// render thread, by a packaged exe.
489pub fn set_asset_store(lookup: AssetLookup) {
490    STORE.with(|s| s.set(Some(lookup)));
491}
492
493/// The bytes of one of the app's own files by URL path (`/games/pong/index.html`): from the package,
494/// or off disk under the app root (or its `public/`) in a dev host.
495pub fn read_app_asset(src: &str) -> Option<Vec<u8>> {
496    let key = sk_payload::content_key(src)?;
497    if let Some(store) = asset_store() {
498        return store(&key).map(<[u8]>::to_vec);
499    }
500    if let Some(path) = dev_asset_file(src) {
501        return std::fs::read(path).ok();
502    }
503    let base = asset_base()?;
504    let relative = key.replace('/', std::path::MAIN_SEPARATOR_STR);
505    std::fs::read(base.join(&relative))
506        .or_else(|_| std::fs::read(base.join("public").join(&relative)))
507        .ok()
508}
509
510pub fn asset_store() -> Option<AssetLookup> {
511    STORE.with(Cell::get)
512}
513
514fn stored(tag: &str, src: &str) -> Option<Result<(String, &'static [u8]), String>> {
515    let store = asset_store()?;
516    Some(match sk_payload::content_key_checked(src) {
517        Ok(key) => match store(&key) {
518            Some(bytes) => Ok((key, bytes)),
519            None => Err(format!(
520                "<{tag} src=\"{src}\">: {key:?} is not in this app's package — a packaged exe carries \
521                 only the files its sk.config.json \"assets\" names (default: the assets/ directory). \
522                 A browser would have answered 404; the element is broken."
523            )),
524        },
525        Err(KeyError::EscapesRoot) => Err(format!(
526            "<{tag} src=\"{src}\">: the path climbs out of the app root, and a packaged app has \
527             nothing outside its package."
528        )),
529        Err(_) => Err(format!("<{tag} src=\"{src}\">: names no file inside the app — nothing to load.")),
530    })
531}
532
533pub(crate) fn gc(live: impl Fn(u32) -> bool) {
534    RESOLVED.with(|m| {
535        let mut map = m.borrow_mut();
536        let dead: Vec<u32> = map.keys().copied().filter(|&id| !live(id)).collect();
537        let gone: Vec<Memo> = dead.iter().filter_map(|id| map.remove(id)).collect();
538        for g in gone {
539            release(&map, g);
540        }
541    });
542    BACKGROUNDS.with(|m| m.borrow_mut().retain(|&id, _| live(id)));
543}
544
545thread_local! {
546    /// `background-image: url()` sources per node as `(url, source)`; a node may carry several layers.
547    static BACKGROUNDS: RefCell<HashMap<u32, Vec<(std::rc::Rc<str>, Option<ImageSource>)>>> =
548        RefCell::new(HashMap::new());
549}
550
551pub(crate) fn background_source(id: u32, url: &str) -> Option<ImageSource> {
552    BACKGROUNDS.with(|m| {
553        let mut m = m.borrow_mut();
554        let list = m.entry(id).or_default();
555        if let Some((_, source)) = list.iter().find(|(u, _)| &**u == url) {
556            return source.clone();
557        }
558        let source = resolve(url);
559        note_known(source.as_ref());
560        // An animated sprite sheet swapping URLs must not grow this without bound.
561        if list.len() >= 8 {
562            list.clear();
563        }
564        list.push((std::rc::Rc::from(url), source.clone()));
565        source
566    })
567}
568
569pub(crate) fn source_for(id: u32, src: &str) -> Option<ImageSource> {
570    RESOLVED.with(|m| {
571        let mut map = m.borrow_mut();
572        if let Some(memo) = map.get(&id) {
573            if memo.src == src {
574                return memo.source.clone();
575            }
576        }
577        let source = resolve(src);
578        note_known(source.as_ref());
579        let blob = src
580            .trim()
581            .get(..5)
582            .is_some_and(|s| s.eq_ignore_ascii_case("blob:"));
583        let old = map.insert(
584            id,
585            Memo {
586                src: src.to_string(),
587                source: source.clone(),
588                blob,
589            },
590        );
591        if let Some(old) = old {
592            release(&map, old);
593        }
594        source
595    })
596}
597
598// `load` is a header read, not a decode: the probe must not hold a second full-size copy of a photo
599// a script only wanted to measure. An http(s) image waits on gpui's own decode and shares it.
600
601thread_local! {
602    static LOADS: RefCell<std::collections::HashSet<u32>> = RefCell::new(std::collections::HashSet::new());
603}
604
605pub(crate) fn loads_pending() -> bool {
606    LOADS.with(|l| !l.borrow().is_empty())
607}
608
609pub(crate) fn note_src(id: u32) {
610    LOADS.with(|l| l.borrow_mut().insert(id));
611}
612
613#[derive(Debug, PartialEq)]
614pub(crate) enum Probe {
615    Pending,
616    Loaded(f64, f64),
617    Failed,
618}
619
620pub(crate) fn tick(window: &mut gpui::Window, cx: &mut gpui::App) {
621    let pending: Vec<u32> = LOADS.with(|l| l.borrow().iter().copied().collect());
622    for id in pending {
623        let Some(src) =
624            crate::tree::read_tree(|t| t.node(id).map(|_| t.prop(id, "src").map(str::to_string)))
625        else {
626            LOADS.with(|l| l.borrow_mut().remove(&id));
627            continue;
628        };
629        let Some(src) = src else {
630            LOADS.with(|l| l.borrow_mut().remove(&id));
631            continue;
632        };
633        let probe = probe(id, &src, cx);
634        let (event, a, b) = match probe {
635            Probe::Pending => continue,
636            Probe::Loaded(w, h) => (crate::tree::EV_LOAD, w, h),
637            Probe::Failed => (crate::tree::EV_ERROR, 0.0, 0.0),
638        };
639        LOADS.with(|l| l.borrow_mut().remove(&id));
640        let payload = crate::EventPayload {
641            a,
642            b,
643            key: Some(&src),
644            ..Default::default()
645        };
646        crate::render::js_dispatch_app(id, event, &payload, window, cx);
647    }
648}
649
650pub(crate) fn probe(id: u32, src: &str, cx: &mut gpui::App) -> Probe {
651    // HTML: an empty `src` fires `error` (it is not "no src").
652    if src.trim().is_empty() {
653        return Probe::Failed;
654    }
655    let svg_named = names_svg(src);
656    match source_for(id, src) {
657        None => Probe::Failed,
658        Some(ImageSource::Resource(Resource::Uri(uri))) => {
659            match cx.fetch_asset::<gpui::ImgResourceLoader>(&Resource::Uri(uri)) {
660                None => Probe::Pending,
661                Some(Err(_)) => Probe::Failed,
662                Some(Ok(image)) => {
663                    let size = image.natural_size(0);
664                    // gpui rasterises an SVG at twice its size for smoothness.
665                    let scale = if svg_named {
666                        gpui::SMOOTH_SVG_SCALE_FACTOR as f64
667                    } else {
668                        1.0
669                    };
670                    Probe::Loaded(size.width.0 as f64 / scale, size.height.0 as f64 / scale)
671                }
672            }
673        }
674        Some(ImageSource::Resource(Resource::Path(path))) => file_natural_size(path.as_ref()),
675        Some(ImageSource::Resource(Resource::Embedded(key))) => {
676            match asset_store().and_then(|store| store(key.as_ref())) {
677                Some(bytes) => natural_size(bytes),
678                None => Probe::Failed,
679            }
680        }
681        Some(ImageSource::Image(image)) => natural_size(&image.bytes),
682        Some(_) => Probe::Failed,
683    }
684}
685
686pub(crate) fn names_svg(src: &str) -> bool {
687    let path = src.split(['?', '#']).next().unwrap_or(src).trim();
688    path.len() > 4
689        && path.is_char_boundary(path.len() - 4)
690        && path[path.len() - 4..].eq_ignore_ascii_case(".svg")
691}
692
693/// A file's natural size: only the header of a raster (a picked photo is measured, not loaded); an
694/// SVG is read whole.
695fn file_natural_size(path: &Path) -> Probe {
696    let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else {
697        return Probe::Failed;
698    };
699    if reader.format().is_some() {
700        return upright_size(reader);
701    }
702    match std::fs::read(path) {
703        Ok(bytes) => svg_size(&bytes),
704        Err(_) => Probe::Failed,
705    }
706}
707
708/// The natural size a format's header declares: the raster formats gpui decodes (sniffed through the
709/// same `image` crate, so the set cannot drift), or an SVG's own size.
710pub(crate) fn natural_size(bytes: &[u8]) -> Probe {
711    if let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format() {
712        if reader.format().is_some() {
713            return upright_size(reader);
714        }
715    }
716    svg_size(bytes)
717}
718
719/// A raster's natural size as painted: EXIF orientation applied (`image-orientation: from-image`, as
720/// gpui's decoder and `drawImage` do), so a sideways phone photo measures upright.
721fn upright_size<R: std::io::BufRead + std::io::Seek>(reader: image::ImageReader<R>) -> Probe {
722    use image::metadata::Orientation;
723    use image::ImageDecoder;
724    let Ok(mut decoder) = reader.into_decoder() else {
725        return Probe::Failed;
726    };
727    let (w, h) = decoder.dimensions();
728    if w == 0 || h == 0 {
729        return Probe::Failed;
730    }
731    let turned = matches!(
732        decoder.orientation(),
733        Ok(Orientation::Rotate90
734            | Orientation::Rotate270
735            | Orientation::Rotate90FlipH
736            | Orientation::Rotate270FlipH)
737    );
738    if turned {
739        Probe::Loaded(h as f64, w as f64)
740    } else {
741        Probe::Loaded(w as f64, h as f64)
742    }
743}
744
745fn svg_size(bytes: &[u8]) -> Probe {
746    match usvg::Tree::from_data(bytes, &usvg::Options::default()) {
747        Ok(tree) => Probe::Loaded(tree.size().width() as f64, tree.size().height() as f64),
748        Err(_) => Probe::Failed,
749    }
750}
751
752// `drawImage` pixels: http(s) uses gpui's decode (BGRA, SVG at twice size, halved back); everything
753// else is read and decoded here, synchronously, since gpui cannot be asked without starting a load.
754
755pub(crate) enum Pixels {
756    Ready {
757        width: u32,
758        height: u32,
759        rgba: Vec<u8>,
760    },
761    NotYet,
762    Broken(String),
763}
764
765pub(crate) fn pixels(id: u32, cx: Option<&mut gpui::App>) -> Pixels {
766    let Some(raw) = crate::tree::read_tree(|t| t.prop(id, "src").map(str::to_string)) else {
767        return Pixels::NotYet;
768    };
769    let src = raw.trim();
770    if src.is_empty() {
771        return Pixels::NotYet;
772    }
773    if matches!(scheme_of(src).as_str(), "http" | "https") {
774        let Some(cx) = cx else { return Pixels::NotYet };
775        let source = source_for(id, &raw);
776        let Some(Ok(image)) = (match &source {
777            Some(ImageSource::Resource(r @ Resource::Uri(_))) => {
778                cx.fetch_asset::<gpui::ImgResourceLoader>(r)
779            }
780            _ => {
781                return Pixels::Broken(format!("<img src=\"{}\">: not a URL gpui loads", head(src)))
782            }
783        }) else {
784            return Pixels::NotYet;
785        };
786        // A canvas read: a reduced copy must not stand in; if one does, bring the full decode back
787        // (NotYet meanwhile).
788        if let Some(source) = &source {
789            if !keep_full(source, &image) {
790                return Pixels::NotYet;
791            }
792        }
793        let size = image.size(0);
794        let (w, h) = (size.width.0.max(0) as u32, size.height.0.max(0) as u32);
795        let Some(bgra) = image
796            .as_bytes(0)
797            .filter(|b| w > 0 && h > 0 && b.len() >= (w * h * 4) as usize)
798        else {
799            return Pixels::Broken(format!(
800                "<img src=\"{}\">: the decoded image has no pixels",
801                head(src)
802            ));
803        };
804        let mut rgba = bgra[..(w * h * 4) as usize].to_vec();
805        for px in rgba.chunks_exact_mut(4) {
806            px.swap(0, 2);
807        }
808        if names_svg(src) {
809            let (rgba, w, h) = halve(&rgba, w, h);
810            return Pixels::Ready {
811                width: w,
812                height: h,
813                rgba,
814            };
815        }
816        return Pixels::Ready {
817            width: w,
818            height: h,
819            rgba,
820        };
821    }
822    let bytes = match read_bytes("img", src) {
823        Ok(b) => b,
824        Err(why) => return Pixels::Broken(why),
825    };
826    match redjs::webapi::image::decode(&bytes, None) {
827        Some(b) => Pixels::Ready {
828            width: b.width,
829            height: b.height,
830            rgba: b.rgba,
831        },
832        None => Pixels::Broken(format!(
833            "<img src=\"{}\">: the bytes are not an image this build decodes",
834            head(src)
835        )),
836    }
837}
838
839/// Straight-alpha RGBA halved by 2×2 averaging weighted by alpha: undoes gpui's SVG raster at twice
840/// the natural size.
841fn halve(rgba: &[u8], w: u32, h: u32) -> (Vec<u8>, u32, u32) {
842    let (ow, oh) = ((w / 2).max(1), (h / 2).max(1));
843    let mut out = vec![0u8; (ow * oh * 4) as usize];
844    for y in 0..oh {
845        for x in 0..ow {
846            let (mut c, mut a) = ([0u32; 3], 0u32);
847            for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
848                let (sx, sy) = ((x * 2 + dx).min(w - 1), (y * 2 + dy).min(h - 1));
849                let p = &rgba[((sy * w + sx) * 4) as usize..][..4];
850                let pa = p[3] as u32;
851                for i in 0..3 {
852                    c[i] += p[i] as u32 * pa;
853                }
854                a += pa;
855            }
856            let o = &mut out[((y * ow + x) * 4) as usize..][..4];
857            if a > 0 {
858                for i in 0..3 {
859                    o[i] = ((c[i] + a / 2) / a) as u8;
860                }
861            }
862            o[3] = ((a + 2) / 4) as u8;
863        }
864    }
865    (out, ow, oh)
866}
867
868/// The raw file bytes behind a `src`, for elements that parse the document themselves (`<lottie>`).
869pub(crate) fn read_bytes(tag: &str, src: &str) -> Result<Vec<u8>, String> {
870    let src = own_origin(src.trim());
871    if src.is_empty() {
872        return Err(format!(
873            "<{tag} src=\"\">: the src is empty — nothing to load"
874        ));
875    }
876    if scheme_of(src) == "data" {
877        return data_bytes(tag, src);
878    }
879    if scheme_of(src) == "blob" {
880        return blob_bytes(tag, src, blob_target(src));
881    }
882    if scheme_of(src).is_empty() {
883        if let Some(hit) = stored(tag, src) {
884            return hit.map(|(_, bytes)| bytes.to_vec());
885        }
886    }
887    let path = resolve_path(tag, src)?;
888    read_file(tag, src, &path)
889}
890
891/// What [`read_bytes`] reads without reading a file yet: in-memory bytes (`data:`, `blob:`, packaged
892/// asset), or a file path for a caller that reads it on another thread ([`read_file`]).
893pub(crate) enum Readable {
894    Bytes(Vec<u8>),
895    File(PathBuf),
896}
897
898pub(crate) fn readable(tag: &str, src: &str) -> Result<Readable, String> {
899    let src = own_origin(src.trim());
900    let scheme = scheme_of(src);
901    if src.is_empty() || scheme == "data" || scheme == "blob" {
902        return read_bytes(tag, src).map(Readable::Bytes);
903    }
904    if scheme.is_empty() {
905        if let Some(hit) = stored(tag, src) {
906            return hit.map(|(_, bytes)| Readable::Bytes(bytes.to_vec()));
907        }
908    }
909    resolve_path(tag, src).map(Readable::File)
910}
911
912pub(crate) fn read_file(tag: &str, src: &str, path: &std::path::Path) -> Result<Vec<u8>, String> {
913    std::fs::read(path).map_err(|e| {
914        format!(
915            "<{tag} src=\"{src}\">: could not read {} — {e}",
916            path.display()
917        )
918    })
919}
920
921/// The file PATH behind a `src`, for `<video>`: the OS owns the read-ahead, so a long clip never
922/// becomes a `Vec<u8>`.
923pub(crate) fn resolve_path(tag: &str, src: &str) -> Result<PathBuf, String> {
924    let src = own_origin(src.trim());
925    if src.is_empty() {
926        return Err(format!(
927            "<{tag} src=\"\">: the src is empty — nothing to load"
928        ));
929    }
930    match scheme_of(src).as_str() {
931        "data" => Err(format!(
932            "<{tag} src=\"data:…\">: this element loads by PATH, and a data: URI has none. \
933             (`<video>` takes them — see `resolve_media`.)"
934        )),
935        "http" | "https" => Err(format!(
936            "<{tag} src=\"{src}\">: this element loads by PATH, and an http(s) URL is not one. \
937             (`<img>` and `<video>` take them — see `resolve` and `resolve_media`.)"
938        )),
939        "file" => {
940            file_url(src).ok_or_else(|| format!("<{tag} src=\"{src}\">: malformed file: URL"))
941        }
942        // A blob: URL of a whole picked file IS a path; a slice or an in-memory Blob is not one.
943        "blob" => match blob_target(src) {
944            Some(t @ BlobTarget::Path { range: None, .. }) => {
945                check_snapshot(tag, src, &t)?;
946                let BlobTarget::Path { path, .. } = t else {
947                    unreachable!()
948                };
949                Ok(path)
950            }
951            Some(_) => Err(format!(
952                "<{tag} src=\"{src}\">: this element loads by PATH, and this blob: URL names bytes \
953                 in memory or a slice of a file, which have none."
954            )),
955            None => Err(unknown_blob(tag, src)),
956        },
957        s if s.len() == 1 && s.chars().all(|c| c.is_ascii_alphabetic()) => Ok(PathBuf::from(src)),
958        "" => Ok(relative_to_base(tag, src)),
959        other => Err(format!(
960            "<{tag} src=\"{src}\">: the `{other}:` URL scheme is not supported — use a file \
961             path or a data: URI."
962        )),
963    }
964}
965
966#[cfg(feature = "video")]
967/// The [`sk_video::MediaSource`] behind a `<video src>`: a path, an http(s) URL verbatim (the
968/// platform streams it), or bytes for `data:`.
969pub(crate) fn resolve_media(tag: &str, src: &str) -> Result<sk_video::MediaSource, String> {
970    let src = own_origin(src.trim());
971    if src.is_empty() {
972        return Err(format!(
973            "<{tag} src=\"\">: the src is empty — nothing to load"
974        ));
975    }
976    match scheme_of(src).as_str() {
977        "data" => {
978            // The media type is the platform's only hint about the bytes.
979            let mime = src
980                .get(5..)
981                .unwrap_or_default()
982                .split_once(',')
983                .map(|(meta, _)| {
984                    meta.split(';')
985                        .next()
986                        .unwrap_or("")
987                        .trim()
988                        .to_ascii_lowercase()
989                })
990                .unwrap_or_default();
991            let data = data_bytes(tag, src)?;
992            if data.is_empty() {
993                return Err(format!(
994                    "<{tag} src=\"{}…\">: the data: URI decoded to zero bytes",
995                    head(src)
996                ));
997            }
998            Ok(sk_video::MediaSource::Bytes {
999                mime,
1000                data: std::sync::Arc::new(data),
1001            })
1002        }
1003        "http" | "https" => Ok(sk_video::MediaSource::Uri(src.to_string())),
1004        "blob" => blob_media(tag, src, blob_target(src)),
1005        "" if asset_store().is_some() => {
1006            let (key, bytes) = stored(tag, src).expect("asset_store() is set")?;
1007            Ok(sk_video::MediaSource::StaticBytes {
1008                mime: sk_payload::media_type_for(&key).to_string(),
1009                data: bytes,
1010            })
1011        }
1012        _ => resolve_path(tag, src).map(sk_video::MediaSource::Path),
1013    }
1014}
1015
1016const PAGE_ORIGIN: &str = "app://redjs/";
1017
1018/// A URL on the page's own origin (`new URL("/a.png", location.href)`) names the app's file `/a.png`.
1019fn own_origin(src: &str) -> &str {
1020    match src.get(..PAGE_ORIGIN.len()) {
1021        Some(head) if head.eq_ignore_ascii_case(PAGE_ORIGIN) => &src[PAGE_ORIGIN.len() - 1..],
1022        _ => src,
1023    }
1024}
1025
1026fn scheme_of(src: &str) -> String {
1027    src.split_once(':')
1028        .map(|(s, _)| s.to_ascii_lowercase())
1029        .unwrap_or_default()
1030}
1031
1032fn data_bytes(tag: &str, src: &str) -> Result<Vec<u8>, String> {
1033    let body = src.get(5..).unwrap_or_default();
1034    let Some((meta, payload)) = body.split_once(',') else {
1035        return Err(format!(
1036            "<{tag} src=\"{}…\">: malformed data: URL (no comma)",
1037            head(src)
1038        ));
1039    };
1040    if meta
1041        .to_ascii_lowercase()
1042        .split(';')
1043        .any(|p| p.trim() == "base64")
1044    {
1045        base64_decode(payload).ok_or_else(|| {
1046            format!(
1047                "<{tag} src=\"{}…\">: data: URL payload is not valid base64",
1048                head(src)
1049            )
1050        })
1051    } else {
1052        Ok(percent_decode_bytes(payload))
1053    }
1054}
1055
1056fn warn(msg: String) {
1057    thread_local! {
1058        static SEEN: RefCell<std::collections::HashSet<String>> =
1059            RefCell::new(std::collections::HashSet::new());
1060    }
1061    SEEN.with(|s| {
1062        if s.borrow_mut().insert(msg.clone()) {
1063            eprintln!("[skathi compat] {msg}");
1064            crate::log::record("advisory", msg);
1065        }
1066    });
1067}
1068
1069pub(crate) fn resolve(src: &str) -> Option<ImageSource> {
1070    let src = own_origin(src.trim());
1071    if src.is_empty() {
1072        return None;
1073    }
1074    let lower_scheme = src
1075        .split_once(':')
1076        .map(|(s, _)| s.to_ascii_lowercase())
1077        .unwrap_or_default();
1078
1079    match lower_scheme.as_str() {
1080        "data" => data_url(src),
1081        // Fetched asynchronously by gpui, so the element shows `alt` for a frame or two. NOT
1082        // `ImageSource::from(&str)`: gpui's `is_uri` classifies a bare relative path as `Embedded`.
1083        "http" | "https" => Some(ImageSource::Resource(Resource::Uri(src.to_string().into()))),
1084        "blob" => blob_image(src, blob_target(src)),
1085        "file" => file_url(src).map(path_source),
1086        s if s.len() == 1 && s.chars().all(|c| c.is_ascii_alphabetic()) => {
1087            Some(path_source(PathBuf::from(src)))
1088        }
1089        "" => match stored("img", src) {
1090            // gpui reads `Embedded` through the app's `AssetSource` (the payload) off the render
1091            // thread and caches the decode by key.
1092            Some(Ok((key, _))) => Some(ImageSource::Resource(Resource::Embedded(key.into()))),
1093            Some(Err(msg)) => {
1094                warn(msg);
1095                None
1096            }
1097            None => Some(path_source(relative_to_base("img", src))),
1098        },
1099        other => {
1100            warn(format!(
1101                "<img src=\"{src}\">: the `{other}:` URL scheme is not supported — use a file \
1102                 path, a data: URI, or (once an HTTP client is wired) http(s)."
1103            ));
1104            None
1105        }
1106    }
1107}
1108
1109fn path_source(p: PathBuf) -> ImageSource {
1110    // Explicitly `Resource::Path`: `ImageSource::from(&str)` would parse `C:` as a URL scheme.
1111    ImageSource::Resource(Resource::Path(p.into()))
1112}
1113
1114/// Joins a relative or root-relative `src` onto the app root through [`content_key`], as `fetch()` does.
1115fn relative_to_base(tag: &str, src: &str) -> PathBuf {
1116    if let Some(path) = dev_asset_file(src) {
1117        return path;
1118    }
1119    let base = match asset_base() {
1120        Some(b) => b,
1121        None => {
1122            warn(
1123                "<img src>: no app root is published, so relative image paths resolve against the \
1124                 process working directory. Set SK_APP_ROOT, or run the dev host on a dev build \
1125                 (which records the app root)."
1126                    .into(),
1127            );
1128            std::env::current_dir().unwrap_or_default()
1129        }
1130    };
1131    let sep = std::path::MAIN_SEPARATOR_STR;
1132    match sk_payload::content_key_checked(src) {
1133        Ok(key) => base.join(key.replace('/', sep)),
1134        Err(why) => {
1135            if why == KeyError::EscapesRoot {
1136                warn(format!(
1137                    "<{tag} src=\"{src}\"> climbs out of the app root ({}) — it resolves in a dev host, \
1138                     but a packaged exe carries only the app's own files, so there it will be broken.",
1139                    base.display()
1140                ));
1141            }
1142            let rel = src.split(['?', '#']).next().unwrap_or_default();
1143            let rel = rel.trim_start_matches(['/', '\\']);
1144            normalize(&base.join(rel.replace('/', sep)))
1145        }
1146    }
1147}
1148
1149fn normalize(p: &Path) -> PathBuf {
1150    let mut out = PathBuf::new();
1151    for c in p.components() {
1152        match c {
1153            Component::CurDir => {}
1154            Component::ParentDir => {
1155                if !out.pop() {
1156                    out.push("..");
1157                }
1158            }
1159            other => out.push(other.as_os_str()),
1160        }
1161    }
1162    out
1163}
1164
1165fn file_url(src: &str) -> Option<PathBuf> {
1166    file_url_for(src, cfg!(windows))
1167}
1168
1169fn file_url_for(src: &str, windows: bool) -> Option<PathBuf> {
1170    let rest = src.get(5..)?;
1171    let rest = rest.strip_prefix("//").unwrap_or(rest);
1172    let decoded = percent_decode(rest);
1173    if !windows {
1174        let path = match decoded.find('/') {
1175            Some(at) => &decoded[at..],
1176            None => decoded.as_str(),
1177        };
1178        return Some(PathBuf::from(path));
1179    }
1180    let decoded = decoded.replace('/', "\\");
1181    // "///C:/x" → "\C:\x": drop the empty authority's slash before a drive.
1182    let trimmed = decoded.strip_prefix('\\').unwrap_or(&decoded);
1183    if trimmed.len() >= 2 && trimmed.as_bytes()[1] == b':' {
1184        return Some(PathBuf::from(trimmed));
1185    }
1186    Some(PathBuf::from(decoded))
1187}
1188
1189fn percent_decode(s: &str) -> String {
1190    String::from_utf8_lossy(&percent_decode_bytes(s)).into_owned()
1191}
1192
1193/// The bytes a percent-encoded string stands for (a `data:` payload is bytes, not text).
1194fn percent_decode_bytes(s: &str) -> Vec<u8> {
1195    let bytes = s.as_bytes();
1196    let mut out = Vec::with_capacity(bytes.len());
1197    let mut i = 0;
1198    while i < bytes.len() {
1199        if bytes[i] == b'%' && i + 2 < bytes.len() {
1200            if let (Some(h), Some(l)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2])) {
1201                out.push(h * 16 + l);
1202                i += 3;
1203                continue;
1204            }
1205        }
1206        out.push(bytes[i]);
1207        i += 1;
1208    }
1209    out
1210}
1211
1212fn hex_val(b: u8) -> Option<u8> {
1213    match b {
1214        b'0'..=b'9' => Some(b - b'0'),
1215        b'a'..=b'f' => Some(b - b'a' + 10),
1216        b'A'..=b'F' => Some(b - b'A' + 10),
1217        _ => None,
1218    }
1219}
1220
1221// blob: URLs. A whole picked file is handed on as its path, like an absolute `src`; a path-backed
1222// URL fails when the file's size or mtime changed since it was picked.
1223
1224fn blob_target(src: &str) -> Option<BlobTarget> {
1225    JsRuntime::try_with(|rt| redjs::webapi::url::resolve_blob_url(rt.raw(), src)).flatten()
1226}
1227
1228fn unknown_blob(tag: &str, src: &str) -> String {
1229    format!(
1230        "<{tag} src=\"{src}\">: this blob: URL is not in the blob URL store — it was revoked \
1231         (URL.revokeObjectURL), or was never created in this window."
1232    )
1233}
1234
1235fn check_snapshot(tag: &str, src: &str, t: &BlobTarget) -> Result<(), String> {
1236    if t.snapshot_holds() {
1237        return Ok(());
1238    }
1239    let path = match t {
1240        BlobTarget::Path { path, .. } => path.display().to_string(),
1241        BlobTarget::Bytes { .. } => String::new(),
1242    };
1243    Err(format!(
1244        "<{tag} src=\"{src}\">: {path} changed (or is gone) since its File was made, so the load \
1245         fails — as a browser's does (NotReadableError). Pick the file again for its new contents."
1246    ))
1247}
1248
1249/// The bytes a blob: URL names: a copy of the in-memory window, or read from the file for a path-backed one.
1250fn blob_bytes(tag: &str, src: &str, target: Option<BlobTarget>) -> Result<Vec<u8>, String> {
1251    match target {
1252        None => Err(unknown_blob(tag, src)),
1253        Some(BlobTarget::Bytes {
1254            bytes, offset, len, ..
1255        }) => match bytes.get(offset..offset + len) {
1256            Some(b) => Ok(b.to_vec()),
1257            None => Err(format!(
1258                "<{tag} src=\"{src}\">: the blob: URL's window lies outside its bytes"
1259            )),
1260        },
1261        Some(t @ BlobTarget::Path { .. }) => {
1262            check_snapshot(tag, src, &t)?;
1263            let BlobTarget::Path {
1264                path, range, size, ..
1265            } = t
1266            else {
1267                unreachable!()
1268            };
1269            let (offset, len) = range.unwrap_or((0, size));
1270            read_window(&path, offset, len).map_err(|e| {
1271                format!(
1272                    "<{tag} src=\"{src}\">: could not read {} — {e}",
1273                    path.display()
1274                )
1275            })
1276        }
1277    }
1278}
1279
1280/// `len` bytes of `path` from `offset`, or an error: never a truncated decode or an OOM abort.
1281fn read_window(path: &Path, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
1282    use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
1283    let mut f = std::fs::File::open(path)?;
1284    f.seek(SeekFrom::Start(offset))?;
1285    let want = usize::try_from(len)
1286        .map_err(|_| Error::new(ErrorKind::OutOfMemory, "too large to hold in memory"))?;
1287    let mut out = Vec::new();
1288    out.try_reserve_exact(want).map_err(|_| {
1289        Error::new(
1290            ErrorKind::OutOfMemory,
1291            format!("{len} bytes could not be held in memory"),
1292        )
1293    })?;
1294    f.take(len).read_to_end(&mut out)?;
1295    if out.len() != want {
1296        return Err(Error::new(
1297            ErrorKind::UnexpectedEof,
1298            format!(
1299                "the file ended after {} of the {len} bytes the blob: URL names",
1300                out.len()
1301            ),
1302        ));
1303    }
1304    Ok(out)
1305}
1306
1307fn blob_image(src: &str, target: Option<BlobTarget>) -> Option<ImageSource> {
1308    if let Some(t @ BlobTarget::Path { range: None, .. }) = &target {
1309        if let Err(msg) = check_snapshot("img", src, t) {
1310            warn(msg);
1311            return None;
1312        }
1313        let BlobTarget::Path {
1314            path, size, mtime, ..
1315        } = t
1316        else {
1317            unreachable!()
1318        };
1319        note_blob_path(path, (*size, *mtime));
1320        return Some(path_source(path.clone()));
1321    }
1322    let mime = target
1323        .as_ref()
1324        .map(|t| t.mime().to_ascii_lowercase())
1325        .unwrap_or_default();
1326    let bytes = match blob_bytes("img", src, target) {
1327        Ok(b) => b,
1328        Err(msg) => {
1329            warn(msg);
1330            return None;
1331        }
1332    };
1333    let Some(format) = sniff(&bytes).or_else(|| image_format(&mime)) else {
1334        warn(format!(
1335            "<img src=\"{src}\">: the Blob is not an image this renderer decodes (type {mime:?}) — png, \
1336             jpeg, webp, gif, bmp, tiff, ico and svg+xml do"
1337        ));
1338        return None;
1339    };
1340    Some(ImageSource::Image(std::sync::Arc::new(Image::from_bytes(
1341        format, bytes,
1342    ))))
1343}
1344
1345#[cfg(feature = "video")]
1346/// `<video src="blob:…">`: a whole picked file is a path (the OS streams it); an in-memory Blob is
1347/// its own `Arc`.
1348fn blob_media(
1349    tag: &str,
1350    src: &str,
1351    target: Option<BlobTarget>,
1352) -> Result<sk_video::MediaSource, String> {
1353    match target {
1354        None => Err(unknown_blob(tag, src)),
1355        Some(t @ BlobTarget::Path { range: None, .. }) => {
1356            check_snapshot(tag, src, &t)?;
1357            let BlobTarget::Path { path, .. } = t else {
1358                unreachable!()
1359            };
1360            Ok(sk_video::MediaSource::Path(path))
1361        }
1362        Some(BlobTarget::Bytes {
1363            bytes,
1364            offset: 0,
1365            len,
1366            mime,
1367        }) if len == bytes.len() => {
1368            if len == 0 {
1369                return Err(format!("<{tag} src=\"{src}\">: the Blob is empty"));
1370            }
1371            Ok(sk_video::MediaSource::Bytes {
1372                mime: mime.to_ascii_lowercase(),
1373                data: bytes,
1374            })
1375        }
1376        Some(t) => {
1377            let mime = t.mime().to_ascii_lowercase();
1378            let data = blob_bytes(tag, src, Some(t))?;
1379            if data.is_empty() {
1380                return Err(format!("<{tag} src=\"{src}\">: the Blob is empty"));
1381            }
1382            Ok(sk_video::MediaSource::Bytes {
1383                mime,
1384                data: std::sync::Arc::new(data),
1385            })
1386        }
1387    }
1388}
1389
1390/// `data:[<mediatype>][;base64],<data>` (RFC 2397).
1391fn data_url(src: &str) -> Option<ImageSource> {
1392    let body = src.get(5..)?;
1393    let (meta, payload) = match body.split_once(',') {
1394        Some(pair) => pair,
1395        None => {
1396            warn(format!(
1397                "<img src=\"{}…\">: malformed data: URL (no comma)",
1398                head(src)
1399            ));
1400            return None;
1401        }
1402    };
1403    let meta_lower = meta.to_ascii_lowercase();
1404    let is_base64 = meta_lower.split(';').any(|p| p.trim() == "base64");
1405    let mime = meta_lower
1406        .split(';')
1407        .next()
1408        .unwrap_or("")
1409        .trim()
1410        .to_string();
1411
1412    let bytes = if is_base64 {
1413        match base64_decode(payload) {
1414            Some(b) => b,
1415            None => {
1416                warn(format!(
1417                    "<img src=\"{}…\">: data: URL payload is not valid base64",
1418                    head(src)
1419                ));
1420                return None;
1421            }
1422        }
1423    } else {
1424        percent_decode_bytes(payload)
1425    };
1426
1427    let format = image_format(&mime).or_else(|| sniff(&bytes));
1428    let Some(format) = format else {
1429        warn(format!(
1430            "<img src=\"{}…\">: unsupported data: URL media type {mime:?} — png, jpeg, webp, gif, \
1431             bmp, tiff, ico and svg+xml decode",
1432            head(src)
1433        ));
1434        return None;
1435    };
1436    Some(ImageSource::Image(std::sync::Arc::new(Image::from_bytes(
1437        format, bytes,
1438    ))))
1439}
1440
1441/// A data: URL IS its content — never echo the whole thing into the log.
1442fn head(src: &str) -> String {
1443    src.chars().take(40).collect()
1444}
1445
1446fn image_format(mime: &str) -> Option<ImageFormat> {
1447    Some(match mime {
1448        "image/png" => ImageFormat::Png,
1449        "image/jpeg" | "image/jpg" => ImageFormat::Jpeg,
1450        "image/webp" => ImageFormat::Webp,
1451        "image/gif" => ImageFormat::Gif,
1452        "image/svg+xml" => ImageFormat::Svg,
1453        "image/bmp" | "image/x-bmp" => ImageFormat::Bmp,
1454        "image/tiff" | "image/tif" => ImageFormat::Tiff,
1455        "image/x-icon" | "image/vnd.microsoft.icon" | "image/ico" => ImageFormat::Ico,
1456        _ => return None,
1457    })
1458}
1459
1460fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
1461    let b = bytes;
1462    if b.starts_with(&[0x89, b'P', b'N', b'G']) {
1463        Some(ImageFormat::Png)
1464    } else if b.starts_with(&[0xFF, 0xD8, 0xFF]) {
1465        Some(ImageFormat::Jpeg)
1466    } else if b.starts_with(b"GIF8") {
1467        Some(ImageFormat::Gif)
1468    } else if b.len() > 12 && &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP" {
1469        Some(ImageFormat::Webp)
1470    } else if b.starts_with(b"BM") {
1471        Some(ImageFormat::Bmp)
1472    } else if b.starts_with(b"<svg") || b.starts_with(b"<?xml") {
1473        Some(ImageFormat::Svg)
1474    } else {
1475        None
1476    }
1477}
1478
1479/// Standard base64 with optional padding; whitespace is skipped.
1480fn base64_decode(s: &str) -> Option<Vec<u8>> {
1481    let mut out = Vec::with_capacity(s.len() / 4 * 3);
1482    let mut acc: u32 = 0;
1483    let mut bits = 0u32;
1484    for c in s.bytes() {
1485        let v = match c {
1486            b'A'..=b'Z' => c - b'A',
1487            b'a'..=b'z' => c - b'a' + 26,
1488            b'0'..=b'9' => c - b'0' + 52,
1489            b'+' | b'-' => 62,
1490            b'/' | b'_' => 63,
1491            b'=' => break,
1492            b' ' | b'\n' | b'\r' | b'\t' | 0x0c => continue,
1493            _ => return None,
1494        };
1495        acc = (acc << 6) | v as u32;
1496        bits += 6;
1497        if bits >= 8 {
1498            bits -= 8;
1499            out.push((acc >> bits) as u8);
1500        }
1501    }
1502    Some(out)
1503}
1504
1505#[cfg(test)]
1506mod tests {
1507    use super::*;
1508
1509    /// `Y:\a\b` on Windows, `/Y/a/b` elsewhere.
1510    fn at(windows: &str) -> PathBuf {
1511        if cfg!(windows) {
1512            PathBuf::from(windows)
1513        } else {
1514            PathBuf::from(windows.replacen("Y:", "/Y", 1).replace('\\', "/"))
1515        }
1516    }
1517
1518    fn as_path(s: Option<ImageSource>) -> Option<PathBuf> {
1519        match s {
1520            Some(ImageSource::Resource(Resource::Path(p))) => Some(p.to_path_buf()),
1521            _ => None,
1522        }
1523    }
1524
1525    fn png(w: u32, h: u32) -> Vec<u8> {
1526        let mut out = std::io::Cursor::new(Vec::new());
1527        image::RgbaImage::new(w, h)
1528            .write_to(&mut out, image::ImageFormat::Png)
1529            .unwrap();
1530        out.into_inner()
1531    }
1532
1533    #[test]
1534    fn an_img_hands_a_canvas_its_pixels() {
1535        let dir = std::env::temp_dir().join(format!("sk-img-pixels-{}", std::process::id()));
1536        std::fs::create_dir_all(&dir).unwrap();
1537        set_asset_base(dir.clone());
1538        let good = dir.join("a.png");
1539        let mut out = std::io::Cursor::new(Vec::new());
1540        image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255]))
1541            .write_to(&mut out, image::ImageFormat::Png)
1542            .unwrap();
1543        std::fs::write(&good, out.into_inner()).unwrap();
1544        let bad = dir.join("b.png");
1545        std::fs::write(&bad, b"not a png").unwrap();
1546        let node = |src: Option<&str>| {
1547            crate::tree::with_tree(|t| {
1548                let tag = t.intern("img");
1549                let id = t.create_element(tag);
1550                let key = t.intern("src");
1551                t.set_prop(id, key, src.map(str::to_string));
1552                id
1553            })
1554        };
1555        match pixels(node(Some("a.png")), None) {
1556            Pixels::Ready {
1557                width,
1558                height,
1559                rgba,
1560            } => {
1561                assert_eq!((width, height), (3, 2));
1562                assert_eq!(&rgba[..4], &[10, 20, 30, 255]);
1563            }
1564            _ => panic!("a PNG file did not decode"),
1565        }
1566        let turned = dir.join("c.jpg");
1567        std::fs::write(&turned, sideways_jpeg()).unwrap();
1568        assert_eq!(file_natural_size(&turned), Probe::Loaded(16.0, 32.0));
1569        assert_eq!(natural_size(&sideways_jpeg()), Probe::Loaded(16.0, 32.0));
1570        assert!(matches!(
1571            pixels(node(Some("c.jpg")), None),
1572            Pixels::Ready {
1573                width: 16,
1574                height: 32,
1575                ..
1576            }
1577        ));
1578        assert!(matches!(
1579            pixels(node(Some("b.png")), None),
1580            Pixels::Broken(_)
1581        ));
1582        assert!(matches!(
1583            pixels(node(Some("https://cdn.example/a.png")), None),
1584            Pixels::NotYet
1585        ));
1586        assert!(matches!(pixels(node(None), None), Pixels::NotYet));
1587        assert!(matches!(pixels(node(Some("  ")), None), Pixels::NotYet));
1588        let _ = std::fs::remove_dir_all(&dir);
1589    }
1590
1591    /// A 32×16 JPEG with Exif orientation 6: upright it is 16×32.
1592    fn sideways_jpeg() -> Vec<u8> {
1593        let mut out = std::io::Cursor::new(Vec::new());
1594        image::RgbImage::from_pixel(32, 16, image::Rgb([200, 0, 0]))
1595            .write_to(&mut out, image::ImageFormat::Jpeg)
1596            .unwrap();
1597        let jpeg = out.into_inner();
1598        let tiff = [
1599            0x4D, 0x4D, 0, 0x2A, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0,
1600            0, 0,
1601        ];
1602        let len = (2 + 6 + tiff.len()) as u16;
1603        let mut with = jpeg[..2].to_vec();
1604        with.extend_from_slice(&[0xFF, 0xE1, (len >> 8) as u8, len as u8]);
1605        with.extend_from_slice(b"Exif\0\0");
1606        with.extend_from_slice(&tiff);
1607        with.extend_from_slice(&jpeg[2..]);
1608        with
1609    }
1610
1611    #[test]
1612    fn halving_weighs_colour_by_alpha() {
1613        let px = [
1614            [255, 0, 0, 255],
1615            [0, 0, 255, 0],
1616            [255, 0, 0, 255],
1617            [0, 0, 255, 0],
1618        ]
1619        .concat();
1620        let (out, w, h) = halve(&px, 2, 2);
1621        assert_eq!((w, h), (1, 1));
1622        assert_eq!(out, vec![255, 0, 0, 128]);
1623        let (out, w, h) = halve(&[9, 9, 9, 255].repeat(3), 3, 1);
1624        assert_eq!((w, h, out), (1, 1, vec![9, 9, 9, 255]));
1625    }
1626
1627    #[test]
1628    fn the_probe_reads_the_natural_size_off_the_header() {
1629        assert_eq!(natural_size(&png(7, 3)), Probe::Loaded(7.0, 3.0));
1630        let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="24"></svg>"#;
1631        assert_eq!(natural_size(svg), Probe::Loaded(40.0, 24.0));
1632        assert_eq!(natural_size(b"not an image"), Probe::Failed);
1633        assert_eq!(natural_size(&png(4, 4)[..12]), Probe::Failed);
1634    }
1635
1636    #[test]
1637    fn a_file_is_measured_from_its_header() {
1638        let dir = std::env::temp_dir().join(format!("sk-img-probe-{}", std::process::id()));
1639        std::fs::create_dir_all(&dir).unwrap();
1640        let raster = dir.join("a.png");
1641        std::fs::write(&raster, png(9, 4)).unwrap();
1642        assert_eq!(file_natural_size(&raster), Probe::Loaded(9.0, 4.0));
1643        let svg = dir.join("b.svg");
1644        std::fs::write(
1645            &svg,
1646            br#"<svg xmlns="http://www.w3.org/2000/svg" width="3" height="2"/>"#,
1647        )
1648        .unwrap();
1649        assert_eq!(file_natural_size(&svg), Probe::Loaded(3.0, 2.0));
1650        assert_eq!(file_natural_size(&dir.join("missing.png")), Probe::Failed);
1651        std::fs::remove_dir_all(&dir).ok();
1652    }
1653
1654    #[test]
1655    fn an_svg_url_is_known_by_its_path() {
1656        assert!(names_svg("https://cdn.example/icons/a.svg"));
1657        assert!(names_svg("https://cdn.example/a.SVG?v=2#frag"));
1658        assert!(!names_svg("https://cdn.example/a.png?x=.svg"));
1659        assert!(!names_svg("svg"));
1660    }
1661
1662    #[test]
1663    fn relative_paths_resolve_against_the_app_root() {
1664        set_asset_base(at("Y:\\skathi\\apps\\imgperf"));
1665        for src in ["assets/a.png", "./assets/a.png", "/assets/a.png"] {
1666            assert_eq!(
1667                as_path(resolve(src)),
1668                Some(at("Y:\\skathi\\apps\\imgperf\\assets\\a.png")),
1669                "{src}"
1670            );
1671        }
1672        assert_eq!(
1673            as_path(resolve("../hello/assets/a.png")),
1674            Some(at("Y:\\skathi\\apps\\hello\\assets\\a.png"))
1675        );
1676    }
1677
1678    #[test]
1679    fn absolute_windows_paths_are_paths_not_uris() {
1680        set_asset_base(at("Y:\\skathi\\apps\\imgperf"));
1681        assert_eq!(
1682            as_path(resolve("C:/pics/a.png")),
1683            Some(PathBuf::from("C:/pics/a.png"))
1684        );
1685        assert_eq!(
1686            as_path(resolve("C:\\pics\\a.png")),
1687            Some(PathBuf::from("C:\\pics\\a.png"))
1688        );
1689    }
1690
1691    #[test]
1692    #[cfg(windows)]
1693    fn file_urls_decode_to_paths() {
1694        assert_eq!(
1695            as_path(resolve("file:///C:/my%20pics/a.png")),
1696            Some(PathBuf::from("C:\\my pics\\a.png"))
1697        );
1698    }
1699
1700    #[test]
1701    fn file_urls_keep_their_path_off_windows() {
1702        let unix = |src| file_url_for(src, false).map(|p| p.to_string_lossy().into_owned());
1703        assert_eq!(
1704            unix("file:///home/u/my%20pics/a.png").as_deref(),
1705            Some("/home/u/my pics/a.png")
1706        );
1707        assert_eq!(
1708            unix("file://localhost/home/u/a.png").as_deref(),
1709            Some("/home/u/a.png")
1710        );
1711        assert_eq!(unix("file:/home/u/a.png").as_deref(), Some("/home/u/a.png"));
1712        let windows = |src| file_url_for(src, true).map(|p| p.to_string_lossy().into_owned());
1713        assert_eq!(
1714            windows("file:///C:/x/a.png").as_deref(),
1715            Some("C:\\x\\a.png")
1716        );
1717    }
1718
1719    #[cfg(feature = "video")]
1720    #[test]
1721    fn video_sources_resolve_to_the_shape_the_platform_wants() {
1722        use sk_video::MediaSource;
1723        assert!(matches!(
1724            resolve_media("video", "https://example.com/a.mp4"),
1725            Ok(MediaSource::Uri(u)) if u == "https://example.com/a.mp4"
1726        ));
1727        match resolve_media("video", "data:video/mp4;base64,AAAA") {
1728            Ok(MediaSource::Bytes { mime, data }) => {
1729                assert_eq!(mime, "video/mp4");
1730                assert_eq!(&*data, &[0u8, 0, 0]);
1731            }
1732            other => panic!("{other:?}"),
1733        }
1734        // Not a zero-byte load that fails deep inside Media Foundation.
1735        assert!(resolve_media("video", "data:video/mp4;base64,").is_err());
1736        assert!(resolve_media("video", "").is_err());
1737        assert!(matches!(
1738            resolve_media("video", "assets/clip.mp4"),
1739            Ok(MediaSource::Path(_))
1740        ));
1741    }
1742
1743    #[test]
1744    fn data_urls_decode_and_sniff() {
1745        const PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
1746        let Some(ImageSource::Image(img)) = resolve(PNG) else {
1747            panic!("data: URL did not resolve to an image");
1748        };
1749        assert_eq!(img.format, ImageFormat::Png);
1750        assert!(img.bytes.starts_with(&[0x89, b'P', b'N', b'G']));
1751
1752        let sniffed = resolve("data:;base64,iVBORw0KGgoAAAANSUhEUg==");
1753        assert!(matches!(sniffed, Some(ImageSource::Image(_))));
1754
1755        let svg =
1756            resolve("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22/%3E");
1757        let Some(ImageSource::Image(img)) = svg else {
1758            panic!("percent-encoded data: URL did not resolve");
1759        };
1760        assert_eq!(img.format, ImageFormat::Svg);
1761        assert!(String::from_utf8_lossy(&img.bytes).starts_with("<svg"));
1762
1763        let Some(ImageSource::Image(img)) = resolve("data:image/png,%89PNG%0D%0A%1A%0A%FF%00")
1764        else {
1765            panic!("percent-encoded binary data: URL did not resolve");
1766        };
1767        assert_eq!(
1768            &img.bytes[..],
1769            &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0x00]
1770        );
1771    }
1772
1773    #[test]
1774    fn empty_and_unknown_schemes_yield_nothing() {
1775        assert!(resolve("").is_none());
1776        assert!(resolve("   ").is_none());
1777        assert!(resolve("gopher://x/a.png").is_none());
1778    }
1779
1780    #[test]
1781    fn base64_ignores_wrapping_whitespace() {
1782        assert_eq!(base64_decode("QUJD").unwrap(), b"ABC");
1783        assert_eq!(base64_decode("QU\n JD\r\n").unwrap(), b"ABC");
1784        assert_eq!(base64_decode("QQ==").unwrap(), b"A");
1785        assert!(base64_decode("**").is_none());
1786    }
1787
1788    const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1789    static FAKE: &[(&str, &[u8])] = &[
1790        ("assets/a.png", PNG),
1791        ("assets/clip.mp4", b"mp4bytes"),
1792        ("assets/s.tgs", b"tgs"),
1793        ("assets/my pic.png", PNG),
1794    ];
1795    fn fake_store(key: &str) -> Option<&'static [u8]> {
1796        FAKE.iter().find(|(k, _)| *k == key).map(|(_, v)| *v)
1797    }
1798    /// The store is thread-local; take it away again so a reused thread does not inherit it.
1799    struct StoreGuard;
1800    impl Drop for StoreGuard {
1801        fn drop(&mut self) {
1802            STORE.with(|s| s.set(None));
1803        }
1804    }
1805    fn packaged() -> StoreGuard {
1806        set_asset_store(fake_store);
1807        StoreGuard
1808    }
1809
1810    #[test]
1811    fn a_packaged_app_resolves_relative_srcs_out_of_its_store() {
1812        let _g = packaged();
1813        for src in [
1814            "assets/a.png",
1815            "./assets/a.png",
1816            "/assets/a.png",
1817            "assets/a.png?v=2",
1818            "assets/x/../a.png",
1819        ] {
1820            match resolve(src) {
1821                Some(ImageSource::Resource(Resource::Embedded(key))) => {
1822                    assert_eq!(key.as_ref(), "assets/a.png", "{src}")
1823                }
1824                other => panic!(
1825                    "{src}: not an embedded resource (some: {})",
1826                    other.is_some()
1827                ),
1828            }
1829        }
1830        assert!(matches!(
1831            resolve("assets/my%20pic.png"),
1832            Some(ImageSource::Resource(Resource::Embedded(k))) if k.as_ref() == "assets/my pic.png"
1833        ));
1834        // A miss is a broken image (alt text), NEVER the disk — even with a base set.
1835        set_asset_base(at("Y:\\skathi\\apps\\hello"));
1836        assert!(resolve("assets/nope.png").is_none());
1837        assert!(resolve("../hello/assets/a.png").is_none());
1838        assert!(matches!(
1839            resolve("C:/pics/a.png"),
1840            Some(ImageSource::Resource(Resource::Path(_)))
1841        ));
1842        assert!(matches!(
1843            resolve("https://example.com/a.png"),
1844            Some(ImageSource::Resource(Resource::Uri(_)))
1845        ));
1846        assert!(matches!(
1847            resolve("data:;base64,iVBORw0KGgo="),
1848            Some(ImageSource::Image(_))
1849        ));
1850    }
1851
1852    #[cfg(feature = "video")]
1853    #[test]
1854    fn lottie_and_video_read_the_same_store() {
1855        use sk_video::MediaSource;
1856        let _g = packaged();
1857        assert_eq!(read_bytes("lottie", "assets/s.tgs").unwrap(), b"tgs");
1858        assert_eq!(read_bytes("lottie", "/assets/s.tgs?x").unwrap(), b"tgs");
1859        assert_eq!(
1860            read_bytes("lottie", "app://redjs/assets/s.tgs").unwrap(),
1861            b"tgs"
1862        );
1863        assert!(read_bytes("lottie", "assets/missing.tgs").is_err());
1864        match resolve_media("video", "assets/clip.mp4") {
1865            Ok(MediaSource::StaticBytes { mime, data }) => {
1866                assert_eq!(mime, "video/mp4");
1867                assert_eq!(data, &b"mp4bytes"[..]);
1868                assert!(
1869                    std::ptr::eq(data, fake_store("assets/clip.mp4").unwrap()),
1870                    "mapped package bytes must be borrowed"
1871                );
1872            }
1873            other => panic!("{other:?}"),
1874        }
1875        assert!(resolve_media("video", "assets/missing.mp4").is_err());
1876        assert!(matches!(
1877            resolve_media("video", "https://example.com/a.mp4"),
1878            Ok(MediaSource::Uri(_))
1879        ));
1880    }
1881
1882    #[test]
1883    fn a_dev_host_has_no_store_and_joins_the_same_key_onto_the_app_root() {
1884        assert!(asset_store().is_none());
1885        set_asset_base(at("Y:\\base"));
1886        // Browser-shaped: the server never sees the query, and decodes escapes.
1887        assert_eq!(as_path(resolve("a.png?v=2")), Some(at("Y:\\base\\a.png")));
1888        assert_eq!(
1889            as_path(resolve("my%20pic.png")),
1890            Some(at("Y:\\base\\my pic.png"))
1891        );
1892        assert_eq!(
1893            as_path(resolve("dir\\a.png")),
1894            Some(at("Y:\\base\\dir\\a.png"))
1895        );
1896        // A decoded drive letter must not replace the app root.
1897        assert_eq!(
1898            as_path(resolve("C%3A/x.png")),
1899            Some(at("Y:\\base\\C%3A\\x.png"))
1900        );
1901        #[cfg(feature = "video")]
1902        assert!(matches!(
1903            resolve_media("video", "assets/clip.mp4"),
1904            Ok(sk_video::MediaSource::Path(_))
1905        ));
1906    }
1907
1908    /// The memo must follow the `src`, not the node id — Vue reuses ids.
1909    #[test]
1910    fn the_per_node_memo_follows_the_src_string() {
1911        set_asset_base(at("Y:\\base"));
1912        assert_eq!(as_path(source_for(7, "a.png")), Some(at("Y:\\base\\a.png")));
1913        assert_eq!(as_path(source_for(7, "b.png")), Some(at("Y:\\base\\b.png")));
1914    }
1915
1916    /// A temp file with the target a picked File over it would resolve to; removed on drop.
1917    struct Picked(PathBuf);
1918
1919    impl Picked {
1920        fn new(name: &str, bytes: &[u8]) -> Picked {
1921            let dir =
1922                std::env::temp_dir().join(format!("sk-tree-blob-{}-{name}", std::process::id()));
1923            std::fs::create_dir_all(&dir).unwrap();
1924            let p = dir.join(name);
1925            std::fs::write(&p, bytes).unwrap();
1926            Picked(p)
1927        }
1928
1929        fn target(&self, range: Option<(u64, u64)>, mime: &str) -> BlobTarget {
1930            let m = std::fs::metadata(&self.0).unwrap();
1931            BlobTarget::Path {
1932                path: self.0.clone(),
1933                range,
1934                size: m.len(),
1935                mtime: m.modified().ok(),
1936                mime: mime.into(),
1937            }
1938        }
1939    }
1940
1941    impl Drop for Picked {
1942        fn drop(&mut self) {
1943            let _ = std::fs::remove_file(&self.0);
1944            let _ = std::fs::remove_dir(self.0.parent().unwrap());
1945        }
1946    }
1947
1948    const PNG_1PX: &[u8] = &[
1949        0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, b'I', b'H', b'D', b'R', 0,
1950        0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4, 0x89,
1951    ];
1952
1953    #[test]
1954    fn a_whole_picked_file_loads_by_path_without_a_copy() {
1955        let f = Picked::new("pic.png", PNG_1PX);
1956        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000001";
1957        assert_eq!(
1958            as_path(blob_image(src, Some(f.target(None, "image/png")))),
1959            Some(f.0.clone())
1960        );
1961        #[cfg(feature = "video")]
1962        assert!(matches!(
1963            blob_media("video", src, Some(f.target(None, "video/mp4"))),
1964            Ok(sk_video::MediaSource::Path(p)) if p == f.0
1965        ));
1966    }
1967
1968    #[test]
1969    fn a_slice_or_bytes_in_memory_decode_from_their_bytes() {
1970        let mut body = b"xx".to_vec();
1971        body.extend_from_slice(PNG_1PX);
1972        let f = Picked::new("two.bin", &body);
1973        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000002";
1974        let t = f.target(Some((2, PNG_1PX.len() as u64)), "");
1975        assert!(matches!(
1976            blob_image(src, Some(t)),
1977            Some(ImageSource::Image(_))
1978        ));
1979        let arc = std::sync::Arc::new(PNG_1PX.to_vec());
1980        #[cfg(feature = "video")]
1981        let whole = BlobTarget::Bytes {
1982            bytes: arc.clone(),
1983            offset: 0,
1984            len: arc.len(),
1985            mime: "video/mp4".into(),
1986        };
1987        #[cfg(feature = "video")]
1988        match blob_media("video", src, Some(whole)) {
1989            Ok(sk_video::MediaSource::Bytes { data, mime }) => {
1990                assert!(std::sync::Arc::ptr_eq(&data, &arc));
1991                assert_eq!(mime, "video/mp4");
1992            }
1993            other => panic!("{other:?}"),
1994        }
1995        let part = BlobTarget::Bytes {
1996            bytes: arc.clone(),
1997            offset: 1,
1998            len: 3,
1999            mime: String::new(),
2000        };
2001        assert_eq!(blob_bytes("lottie", src, Some(part)).unwrap(), b"PNG");
2002        let text = BlobTarget::Bytes {
2003            bytes: std::sync::Arc::new(b"hello".to_vec()),
2004            offset: 0,
2005            len: 5,
2006            mime: "text/plain".into(),
2007        };
2008        assert!(blob_image(src, Some(text)).is_none());
2009    }
2010
2011    #[test]
2012    fn a_changed_file_or_an_unknown_url_fails_the_load() {
2013        let f = Picked::new("snap.png", PNG_1PX);
2014        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000003";
2015        let t = f.target(None, "image/png");
2016        std::fs::write(&f.0, b"a different file now").unwrap();
2017        assert!(blob_image(src, Some(t.clone())).is_none());
2018        #[cfg(feature = "video")]
2019        assert!(blob_media("video", src, Some(t)).is_err());
2020        assert!(resolve(src).is_none());
2021        assert!(read_bytes("lottie", src).is_err());
2022        #[cfg(feature = "video")]
2023        assert!(resolve_media("video", src).is_err());
2024    }
2025
2026    #[test]
2027    fn a_window_is_read_whole_or_refused() {
2028        let f = Picked::new("window.bin", b"0123456789");
2029        assert_eq!(read_window(&f.0, 4, 4).unwrap(), b"4567");
2030        let short = read_window(&f.0, 8, 10).unwrap_err();
2031        assert_eq!(short.kind(), std::io::ErrorKind::UnexpectedEof, "{short}");
2032        let huge = read_window(&f.0, 0, u64::MAX).unwrap_err();
2033        assert_eq!(huge.kind(), std::io::ErrorKind::OutOfMemory, "{huge}");
2034    }
2035
2036    /// A URL a script made in this thread's runtime is found by the render walk's lookup.
2037    #[test]
2038    fn a_url_made_by_script_resolves_through_the_runtimes_store() {
2039        let f = Picked::new("picked.png", PNG_1PX);
2040        sk_runtime::testing::on_js_thread(move || {
2041            let eval = |src: &str| -> String {
2042                JsRuntime::with(|rt| {
2043                    let v = rt
2044                        .ctx()
2045                        .eval(src)
2046                        .unwrap_or_else(|e| panic!("{src}: {e:?}"));
2047                    rt.ctx().to_rust_string(v).unwrap()
2048                })
2049            };
2050            let bytes: Vec<String> = PNG_1PX.iter().map(|b| b.to_string()).collect();
2051            let mem = eval(&format!(
2052                "URL.createObjectURL(new Blob([new Uint8Array([{}])], {{ type: 'image/png' }}))",
2053                bytes.join(",")
2054            ));
2055            assert!(
2056                matches!(resolve(&mem), Some(ImageSource::Image(_))),
2057                "{mem}"
2058            );
2059            JsRuntime::with(|rt| unsafe {
2060                let g = rt.raw();
2061                let file = redjs::webapi::file::file_from_path(g, &f.0, "").unwrap();
2062                redjs::webapi::util::define(g, redjs::glue::rjs_global(g), "picked", file, 0);
2063            });
2064            let by_path = eval("URL.createObjectURL(picked)");
2065            assert_eq!(
2066                as_path(resolve(&by_path)),
2067                Some(f.0.clone()),
2068                "a picked file is handed on by path"
2069            );
2070            #[cfg(feature = "video")]
2071            assert!(
2072                matches!(resolve_media("video", &by_path), Ok(sk_video::MediaSource::Path(p)) if p == f.0)
2073            );
2074            let again = eval("URL.createObjectURL(picked)");
2075            let _ = take_evictions();
2076            assert!(source_for(901, &mem).is_some());
2077            assert!(source_for(902, &by_path).is_some());
2078            assert!(
2079                source_for(903, &again).is_some(),
2080                "a second URL of the same File: the same path"
2081            );
2082            gc(|id| id != 901 && id != 902);
2083            let ev = take_evictions();
2084            assert_eq!(
2085                ev.len(),
2086                1,
2087                "the memory decode goes; the path is still shown by 903"
2088            );
2089            assert!(matches!(&ev[0], ImageSource::Image(_)));
2090            gc(|id| id != 903);
2091            let ev = take_evictions();
2092            assert!(
2093                matches!(&ev[..], [ImageSource::Resource(Resource::Path(p))] if p.as_ref() == f.0),
2094                "{} queued",
2095                ev.len()
2096            );
2097            eval(&format!("URL.revokeObjectURL('{mem}'); 'ok'"));
2098            assert!(resolve(&mem).is_none(), "revoked");
2099        });
2100    }
2101
2102    #[test]
2103    fn a_file_picked_again_after_it_changed_evicts_the_old_decode() {
2104        let f = Picked::new("again.png", PNG_1PX);
2105        let first = "blob:app://redjs/00000000-0000-4000-8000-0000000000a1";
2106        let t1 = f.target(None, "image/png");
2107        assert!(blob_image(first, Some(t1.clone())).is_some());
2108        assert!(
2109            take_evictions().is_empty(),
2110            "first sight: nothing of it is cached"
2111        );
2112        assert!(blob_image(first, Some(t1)).is_some());
2113        assert!(
2114            take_evictions().is_empty(),
2115            "the same file again: the cached decode is right"
2116        );
2117        let mut edited = PNG_1PX.to_vec();
2118        edited.extend([0u8; 16]);
2119        std::fs::write(&f.0, &edited).unwrap();
2120        let t2 = f.target(None, "image/png");
2121        assert!(blob_image(
2122            "blob:app://redjs/00000000-0000-4000-8000-0000000000a2",
2123            Some(t2)
2124        )
2125        .is_some());
2126        let ev = take_evictions();
2127        assert!(
2128            matches!(&ev[..], [ImageSource::Resource(Resource::Path(p))] if p.as_ref() == f.0),
2129            "{} queued",
2130            ev.len()
2131        );
2132    }
2133}