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 note_src(id: u32) {
606    LOADS.with(|l| l.borrow_mut().insert(id));
607}
608
609#[derive(Debug, PartialEq)]
610pub(crate) enum Probe {
611    Pending,
612    Loaded(f64, f64),
613    Failed,
614}
615
616pub(crate) fn tick(window: &mut gpui::Window, cx: &mut gpui::App) {
617    let pending: Vec<u32> = LOADS.with(|l| l.borrow().iter().copied().collect());
618    for id in pending {
619        let Some(src) =
620            crate::tree::read_tree(|t| t.node(id).map(|_| t.prop(id, "src").map(str::to_string)))
621        else {
622            LOADS.with(|l| l.borrow_mut().remove(&id));
623            continue;
624        };
625        let Some(src) = src else {
626            LOADS.with(|l| l.borrow_mut().remove(&id));
627            continue;
628        };
629        let probe = probe(id, &src, cx);
630        let (event, a, b) = match probe {
631            Probe::Pending => continue,
632            Probe::Loaded(w, h) => (crate::tree::EV_LOAD, w, h),
633            Probe::Failed => (crate::tree::EV_ERROR, 0.0, 0.0),
634        };
635        LOADS.with(|l| l.borrow_mut().remove(&id));
636        let payload = crate::EventPayload {
637            a,
638            b,
639            key: Some(&src),
640            ..Default::default()
641        };
642        crate::render::js_dispatch_app(id, event, &payload, window, cx);
643    }
644}
645
646pub(crate) fn probe(id: u32, src: &str, cx: &mut gpui::App) -> Probe {
647    // HTML: an empty `src` fires `error` (it is not "no src").
648    if src.trim().is_empty() {
649        return Probe::Failed;
650    }
651    let svg_named = names_svg(src);
652    match source_for(id, src) {
653        None => Probe::Failed,
654        Some(ImageSource::Resource(Resource::Uri(uri))) => {
655            match cx.fetch_asset::<gpui::ImgResourceLoader>(&Resource::Uri(uri)) {
656                None => Probe::Pending,
657                Some(Err(_)) => Probe::Failed,
658                Some(Ok(image)) => {
659                    let size = image.natural_size(0);
660                    // gpui rasterises an SVG at twice its size for smoothness.
661                    let scale = if svg_named {
662                        gpui::SMOOTH_SVG_SCALE_FACTOR as f64
663                    } else {
664                        1.0
665                    };
666                    Probe::Loaded(size.width.0 as f64 / scale, size.height.0 as f64 / scale)
667                }
668            }
669        }
670        Some(ImageSource::Resource(Resource::Path(path))) => file_natural_size(path.as_ref()),
671        Some(ImageSource::Resource(Resource::Embedded(key))) => {
672            match asset_store().and_then(|store| store(key.as_ref())) {
673                Some(bytes) => natural_size(bytes),
674                None => Probe::Failed,
675            }
676        }
677        Some(ImageSource::Image(image)) => natural_size(&image.bytes),
678        Some(_) => Probe::Failed,
679    }
680}
681
682pub(crate) fn names_svg(src: &str) -> bool {
683    let path = src.split(['?', '#']).next().unwrap_or(src).trim();
684    path.len() > 4
685        && path.is_char_boundary(path.len() - 4)
686        && path[path.len() - 4..].eq_ignore_ascii_case(".svg")
687}
688
689/// A file's natural size: only the header of a raster (a picked photo is measured, not loaded); an
690/// SVG is read whole.
691fn file_natural_size(path: &Path) -> Probe {
692    let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else {
693        return Probe::Failed;
694    };
695    if reader.format().is_some() {
696        return upright_size(reader);
697    }
698    match std::fs::read(path) {
699        Ok(bytes) => svg_size(&bytes),
700        Err(_) => Probe::Failed,
701    }
702}
703
704/// The natural size a format's header declares: the raster formats gpui decodes (sniffed through the
705/// same `image` crate, so the set cannot drift), or an SVG's own size.
706pub(crate) fn natural_size(bytes: &[u8]) -> Probe {
707    if let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format() {
708        if reader.format().is_some() {
709            return upright_size(reader);
710        }
711    }
712    svg_size(bytes)
713}
714
715/// A raster's natural size as painted: EXIF orientation applied (`image-orientation: from-image`, as
716/// gpui's decoder and `drawImage` do), so a sideways phone photo measures upright.
717fn upright_size<R: std::io::BufRead + std::io::Seek>(reader: image::ImageReader<R>) -> Probe {
718    use image::metadata::Orientation;
719    use image::ImageDecoder;
720    let Ok(mut decoder) = reader.into_decoder() else {
721        return Probe::Failed;
722    };
723    let (w, h) = decoder.dimensions();
724    if w == 0 || h == 0 {
725        return Probe::Failed;
726    }
727    let turned = matches!(
728        decoder.orientation(),
729        Ok(Orientation::Rotate90
730            | Orientation::Rotate270
731            | Orientation::Rotate90FlipH
732            | Orientation::Rotate270FlipH)
733    );
734    if turned {
735        Probe::Loaded(h as f64, w as f64)
736    } else {
737        Probe::Loaded(w as f64, h as f64)
738    }
739}
740
741fn svg_size(bytes: &[u8]) -> Probe {
742    match usvg::Tree::from_data(bytes, &usvg::Options::default()) {
743        Ok(tree) => Probe::Loaded(tree.size().width() as f64, tree.size().height() as f64),
744        Err(_) => Probe::Failed,
745    }
746}
747
748// `drawImage` pixels: http(s) uses gpui's decode (BGRA, SVG at twice size, halved back); everything
749// else is read and decoded here, synchronously, since gpui cannot be asked without starting a load.
750
751pub(crate) enum Pixels {
752    Ready {
753        width: u32,
754        height: u32,
755        rgba: Vec<u8>,
756    },
757    NotYet,
758    Broken(String),
759}
760
761pub(crate) fn pixels(id: u32, cx: Option<&mut gpui::App>) -> Pixels {
762    let Some(raw) = crate::tree::read_tree(|t| t.prop(id, "src").map(str::to_string)) else {
763        return Pixels::NotYet;
764    };
765    let src = raw.trim();
766    if src.is_empty() {
767        return Pixels::NotYet;
768    }
769    if matches!(scheme_of(src).as_str(), "http" | "https") {
770        let Some(cx) = cx else { return Pixels::NotYet };
771        let source = source_for(id, &raw);
772        let Some(Ok(image)) = (match &source {
773            Some(ImageSource::Resource(r @ Resource::Uri(_))) => {
774                cx.fetch_asset::<gpui::ImgResourceLoader>(r)
775            }
776            _ => {
777                return Pixels::Broken(format!("<img src=\"{}\">: not a URL gpui loads", head(src)))
778            }
779        }) else {
780            return Pixels::NotYet;
781        };
782        // A canvas read: a reduced copy must not stand in; if one does, bring the full decode back
783        // (NotYet meanwhile).
784        if let Some(source) = &source {
785            if !keep_full(source, &image) {
786                return Pixels::NotYet;
787            }
788        }
789        let size = image.size(0);
790        let (w, h) = (size.width.0.max(0) as u32, size.height.0.max(0) as u32);
791        let Some(bgra) = image
792            .as_bytes(0)
793            .filter(|b| w > 0 && h > 0 && b.len() >= (w * h * 4) as usize)
794        else {
795            return Pixels::Broken(format!(
796                "<img src=\"{}\">: the decoded image has no pixels",
797                head(src)
798            ));
799        };
800        let mut rgba = bgra[..(w * h * 4) as usize].to_vec();
801        for px in rgba.chunks_exact_mut(4) {
802            px.swap(0, 2);
803        }
804        if names_svg(src) {
805            let (rgba, w, h) = halve(&rgba, w, h);
806            return Pixels::Ready {
807                width: w,
808                height: h,
809                rgba,
810            };
811        }
812        return Pixels::Ready {
813            width: w,
814            height: h,
815            rgba,
816        };
817    }
818    let bytes = match read_bytes("img", src) {
819        Ok(b) => b,
820        Err(why) => return Pixels::Broken(why),
821    };
822    match redjs::webapi::image::decode(&bytes, None) {
823        Some(b) => Pixels::Ready {
824            width: b.width,
825            height: b.height,
826            rgba: b.rgba,
827        },
828        None => Pixels::Broken(format!(
829            "<img src=\"{}\">: the bytes are not an image this build decodes",
830            head(src)
831        )),
832    }
833}
834
835/// Straight-alpha RGBA halved by 2×2 averaging weighted by alpha: undoes gpui's SVG raster at twice
836/// the natural size.
837fn halve(rgba: &[u8], w: u32, h: u32) -> (Vec<u8>, u32, u32) {
838    let (ow, oh) = ((w / 2).max(1), (h / 2).max(1));
839    let mut out = vec![0u8; (ow * oh * 4) as usize];
840    for y in 0..oh {
841        for x in 0..ow {
842            let (mut c, mut a) = ([0u32; 3], 0u32);
843            for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
844                let (sx, sy) = ((x * 2 + dx).min(w - 1), (y * 2 + dy).min(h - 1));
845                let p = &rgba[((sy * w + sx) * 4) as usize..][..4];
846                let pa = p[3] as u32;
847                for i in 0..3 {
848                    c[i] += p[i] as u32 * pa;
849                }
850                a += pa;
851            }
852            let o = &mut out[((y * ow + x) * 4) as usize..][..4];
853            if a > 0 {
854                for i in 0..3 {
855                    o[i] = ((c[i] + a / 2) / a) as u8;
856                }
857            }
858            o[3] = ((a + 2) / 4) as u8;
859        }
860    }
861    (out, ow, oh)
862}
863
864/// The raw file bytes behind a `src`, for elements that parse the document themselves (`<lottie>`).
865pub(crate) fn read_bytes(tag: &str, src: &str) -> Result<Vec<u8>, String> {
866    let src = src.trim();
867    if src.is_empty() {
868        return Err(format!(
869            "<{tag} src=\"\">: the src is empty — nothing to load"
870        ));
871    }
872    if scheme_of(src) == "data" {
873        return data_bytes(tag, src);
874    }
875    if scheme_of(src) == "blob" {
876        return blob_bytes(tag, src, blob_target(src));
877    }
878    if scheme_of(src).is_empty() {
879        if let Some(hit) = stored(tag, src) {
880            return hit.map(|(_, bytes)| bytes.to_vec());
881        }
882    }
883    let path = resolve_path(tag, src)?;
884    read_file(tag, src, &path)
885}
886
887/// What [`read_bytes`] reads without reading a file yet: in-memory bytes (`data:`, `blob:`, packaged
888/// asset), or a file path for a caller that reads it on another thread ([`read_file`]).
889pub(crate) enum Readable {
890    Bytes(Vec<u8>),
891    File(PathBuf),
892}
893
894pub(crate) fn readable(tag: &str, src: &str) -> Result<Readable, String> {
895    let src = src.trim();
896    let scheme = scheme_of(src);
897    if src.is_empty() || scheme == "data" || scheme == "blob" {
898        return read_bytes(tag, src).map(Readable::Bytes);
899    }
900    if scheme.is_empty() {
901        if let Some(hit) = stored(tag, src) {
902            return hit.map(|(_, bytes)| Readable::Bytes(bytes.to_vec()));
903        }
904    }
905    resolve_path(tag, src).map(Readable::File)
906}
907
908pub(crate) fn read_file(tag: &str, src: &str, path: &std::path::Path) -> Result<Vec<u8>, String> {
909    std::fs::read(path).map_err(|e| {
910        format!(
911            "<{tag} src=\"{src}\">: could not read {} — {e}",
912            path.display()
913        )
914    })
915}
916
917/// The file PATH behind a `src`, for `<video>`: the OS owns the read-ahead, so a long clip never
918/// becomes a `Vec<u8>`.
919pub(crate) fn resolve_path(tag: &str, src: &str) -> Result<PathBuf, String> {
920    let src = src.trim();
921    if src.is_empty() {
922        return Err(format!(
923            "<{tag} src=\"\">: the src is empty — nothing to load"
924        ));
925    }
926    match scheme_of(src).as_str() {
927        "data" => Err(format!(
928            "<{tag} src=\"data:…\">: this element loads by PATH, and a data: URI has none. \
929             (`<video>` takes them — see `resolve_media`.)"
930        )),
931        "http" | "https" => Err(format!(
932            "<{tag} src=\"{src}\">: this element loads by PATH, and an http(s) URL is not one. \
933             (`<img>` and `<video>` take them — see `resolve` and `resolve_media`.)"
934        )),
935        "file" => {
936            file_url(src).ok_or_else(|| format!("<{tag} src=\"{src}\">: malformed file: URL"))
937        }
938        // A blob: URL of a whole picked file IS a path; a slice or an in-memory Blob is not one.
939        "blob" => match blob_target(src) {
940            Some(t @ BlobTarget::Path { range: None, .. }) => {
941                check_snapshot(tag, src, &t)?;
942                let BlobTarget::Path { path, .. } = t else {
943                    unreachable!()
944                };
945                Ok(path)
946            }
947            Some(_) => Err(format!(
948                "<{tag} src=\"{src}\">: this element loads by PATH, and this blob: URL names bytes \
949                 in memory or a slice of a file, which have none."
950            )),
951            None => Err(unknown_blob(tag, src)),
952        },
953        s if s.len() == 1 && s.chars().all(|c| c.is_ascii_alphabetic()) => Ok(PathBuf::from(src)),
954        "" => Ok(relative_to_base(tag, src)),
955        other => Err(format!(
956            "<{tag} src=\"{src}\">: the `{other}:` URL scheme is not supported — use a file \
957             path or a data: URI."
958        )),
959    }
960}
961
962/// The [`sk_video::MediaSource`] behind a `<video src>`: a path, an http(s) URL verbatim (the
963/// platform streams it), or bytes for `data:`.
964pub(crate) fn resolve_media(tag: &str, src: &str) -> Result<sk_video::MediaSource, String> {
965    let src = src.trim();
966    if src.is_empty() {
967        return Err(format!(
968            "<{tag} src=\"\">: the src is empty — nothing to load"
969        ));
970    }
971    match scheme_of(src).as_str() {
972        "data" => {
973            // The media type is the platform's only hint about the bytes.
974            let mime = src
975                .get(5..)
976                .unwrap_or_default()
977                .split_once(',')
978                .map(|(meta, _)| {
979                    meta.split(';')
980                        .next()
981                        .unwrap_or("")
982                        .trim()
983                        .to_ascii_lowercase()
984                })
985                .unwrap_or_default();
986            let data = data_bytes(tag, src)?;
987            if data.is_empty() {
988                return Err(format!(
989                    "<{tag} src=\"{}…\">: the data: URI decoded to zero bytes",
990                    head(src)
991                ));
992            }
993            Ok(sk_video::MediaSource::Bytes {
994                mime,
995                data: std::sync::Arc::new(data),
996            })
997        }
998        "http" | "https" => Ok(sk_video::MediaSource::Uri(src.to_string())),
999        "blob" => blob_media(tag, src, blob_target(src)),
1000        "" if asset_store().is_some() => {
1001            let (key, bytes) = stored(tag, src).expect("asset_store() is set")?;
1002            Ok(sk_video::MediaSource::StaticBytes {
1003                mime: sk_payload::media_type_for(&key).to_string(),
1004                data: bytes,
1005            })
1006        }
1007        _ => resolve_path(tag, src).map(sk_video::MediaSource::Path),
1008    }
1009}
1010
1011fn scheme_of(src: &str) -> String {
1012    src.split_once(':')
1013        .map(|(s, _)| s.to_ascii_lowercase())
1014        .unwrap_or_default()
1015}
1016
1017fn data_bytes(tag: &str, src: &str) -> Result<Vec<u8>, String> {
1018    let body = src.get(5..).unwrap_or_default();
1019    let Some((meta, payload)) = body.split_once(',') else {
1020        return Err(format!(
1021            "<{tag} src=\"{}…\">: malformed data: URL (no comma)",
1022            head(src)
1023        ));
1024    };
1025    if meta
1026        .to_ascii_lowercase()
1027        .split(';')
1028        .any(|p| p.trim() == "base64")
1029    {
1030        base64_decode(payload).ok_or_else(|| {
1031            format!(
1032                "<{tag} src=\"{}…\">: data: URL payload is not valid base64",
1033                head(src)
1034            )
1035        })
1036    } else {
1037        Ok(percent_decode_bytes(payload))
1038    }
1039}
1040
1041fn warn(msg: String) {
1042    thread_local! {
1043        static SEEN: RefCell<std::collections::HashSet<String>> =
1044            RefCell::new(std::collections::HashSet::new());
1045    }
1046    SEEN.with(|s| {
1047        if s.borrow_mut().insert(msg.clone()) {
1048            eprintln!("[skathi compat] {msg}");
1049            crate::log::record("advisory", msg);
1050        }
1051    });
1052}
1053
1054pub(crate) fn resolve(src: &str) -> Option<ImageSource> {
1055    let src = src.trim();
1056    if src.is_empty() {
1057        return None;
1058    }
1059    let lower_scheme = src
1060        .split_once(':')
1061        .map(|(s, _)| s.to_ascii_lowercase())
1062        .unwrap_or_default();
1063
1064    match lower_scheme.as_str() {
1065        "data" => data_url(src),
1066        // Fetched asynchronously by gpui, so the element shows `alt` for a frame or two. NOT
1067        // `ImageSource::from(&str)`: gpui's `is_uri` classifies a bare relative path as `Embedded`.
1068        "http" | "https" => Some(ImageSource::Resource(Resource::Uri(src.to_string().into()))),
1069        "blob" => blob_image(src, blob_target(src)),
1070        "file" => file_url(src).map(path_source),
1071        s if s.len() == 1 && s.chars().all(|c| c.is_ascii_alphabetic()) => {
1072            Some(path_source(PathBuf::from(src)))
1073        }
1074        "" => match stored("img", src) {
1075            // gpui reads `Embedded` through the app's `AssetSource` (the payload) off the render
1076            // thread and caches the decode by key.
1077            Some(Ok((key, _))) => Some(ImageSource::Resource(Resource::Embedded(key.into()))),
1078            Some(Err(msg)) => {
1079                warn(msg);
1080                None
1081            }
1082            None => Some(path_source(relative_to_base("img", src))),
1083        },
1084        other => {
1085            warn(format!(
1086                "<img src=\"{src}\">: the `{other}:` URL scheme is not supported — use a file \
1087                 path, a data: URI, or (once an HTTP client is wired) http(s)."
1088            ));
1089            None
1090        }
1091    }
1092}
1093
1094fn path_source(p: PathBuf) -> ImageSource {
1095    // Explicitly `Resource::Path`: `ImageSource::from(&str)` would parse `C:` as a URL scheme.
1096    ImageSource::Resource(Resource::Path(p.into()))
1097}
1098
1099/// Joins a relative or root-relative `src` onto the app root through [`content_key`], as `fetch()` does.
1100fn relative_to_base(tag: &str, src: &str) -> PathBuf {
1101    if let Some(path) = dev_asset_file(src) {
1102        return path;
1103    }
1104    let base = match asset_base() {
1105        Some(b) => b,
1106        None => {
1107            warn(
1108                "<img src>: no app root is published, so relative image paths resolve against the \
1109                 process working directory. Set SK_APP_ROOT, or run the dev host on a dev build \
1110                 (which records the app root)."
1111                    .into(),
1112            );
1113            std::env::current_dir().unwrap_or_default()
1114        }
1115    };
1116    let sep = std::path::MAIN_SEPARATOR_STR;
1117    match sk_payload::content_key_checked(src) {
1118        Ok(key) => base.join(key.replace('/', sep)),
1119        Err(why) => {
1120            if why == KeyError::EscapesRoot {
1121                warn(format!(
1122                    "<{tag} src=\"{src}\"> climbs out of the app root ({}) — it resolves in a dev host, \
1123                     but a packaged exe carries only the app's own files, so there it will be broken.",
1124                    base.display()
1125                ));
1126            }
1127            let rel = src.split(['?', '#']).next().unwrap_or_default();
1128            let rel = rel.trim_start_matches(['/', '\\']);
1129            normalize(&base.join(rel.replace('/', sep)))
1130        }
1131    }
1132}
1133
1134fn normalize(p: &Path) -> PathBuf {
1135    let mut out = PathBuf::new();
1136    for c in p.components() {
1137        match c {
1138            Component::CurDir => {}
1139            Component::ParentDir => {
1140                if !out.pop() {
1141                    out.push("..");
1142                }
1143            }
1144            other => out.push(other.as_os_str()),
1145        }
1146    }
1147    out
1148}
1149
1150fn file_url(src: &str) -> Option<PathBuf> {
1151    file_url_for(src, cfg!(windows))
1152}
1153
1154fn file_url_for(src: &str, windows: bool) -> Option<PathBuf> {
1155    let rest = src.get(5..)?;
1156    let rest = rest.strip_prefix("//").unwrap_or(rest);
1157    let decoded = percent_decode(rest);
1158    if !windows {
1159        let path = match decoded.find('/') {
1160            Some(at) => &decoded[at..],
1161            None => decoded.as_str(),
1162        };
1163        return Some(PathBuf::from(path));
1164    }
1165    let decoded = decoded.replace('/', "\\");
1166    // "///C:/x" → "\C:\x": drop the empty authority's slash before a drive.
1167    let trimmed = decoded.strip_prefix('\\').unwrap_or(&decoded);
1168    if trimmed.len() >= 2 && trimmed.as_bytes()[1] == b':' {
1169        return Some(PathBuf::from(trimmed));
1170    }
1171    Some(PathBuf::from(decoded))
1172}
1173
1174fn percent_decode(s: &str) -> String {
1175    String::from_utf8_lossy(&percent_decode_bytes(s)).into_owned()
1176}
1177
1178/// The bytes a percent-encoded string stands for (a `data:` payload is bytes, not text).
1179fn percent_decode_bytes(s: &str) -> Vec<u8> {
1180    let bytes = s.as_bytes();
1181    let mut out = Vec::with_capacity(bytes.len());
1182    let mut i = 0;
1183    while i < bytes.len() {
1184        if bytes[i] == b'%' && i + 2 < bytes.len() {
1185            if let (Some(h), Some(l)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2])) {
1186                out.push(h * 16 + l);
1187                i += 3;
1188                continue;
1189            }
1190        }
1191        out.push(bytes[i]);
1192        i += 1;
1193    }
1194    out
1195}
1196
1197fn hex_val(b: u8) -> Option<u8> {
1198    match b {
1199        b'0'..=b'9' => Some(b - b'0'),
1200        b'a'..=b'f' => Some(b - b'a' + 10),
1201        b'A'..=b'F' => Some(b - b'A' + 10),
1202        _ => None,
1203    }
1204}
1205
1206// blob: URLs. A whole picked file is handed on as its path, like an absolute `src`; a path-backed
1207// URL fails when the file's size or mtime changed since it was picked.
1208
1209fn blob_target(src: &str) -> Option<BlobTarget> {
1210    JsRuntime::try_with(|rt| redjs::webapi::url::resolve_blob_url(rt.raw(), src)).flatten()
1211}
1212
1213fn unknown_blob(tag: &str, src: &str) -> String {
1214    format!(
1215        "<{tag} src=\"{src}\">: this blob: URL is not in the blob URL store — it was revoked \
1216         (URL.revokeObjectURL), or was never created in this window."
1217    )
1218}
1219
1220fn check_snapshot(tag: &str, src: &str, t: &BlobTarget) -> Result<(), String> {
1221    if t.snapshot_holds() {
1222        return Ok(());
1223    }
1224    let path = match t {
1225        BlobTarget::Path { path, .. } => path.display().to_string(),
1226        BlobTarget::Bytes { .. } => String::new(),
1227    };
1228    Err(format!(
1229        "<{tag} src=\"{src}\">: {path} changed (or is gone) since its File was made, so the load \
1230         fails — as a browser's does (NotReadableError). Pick the file again for its new contents."
1231    ))
1232}
1233
1234/// The bytes a blob: URL names: a copy of the in-memory window, or read from the file for a path-backed one.
1235fn blob_bytes(tag: &str, src: &str, target: Option<BlobTarget>) -> Result<Vec<u8>, String> {
1236    match target {
1237        None => Err(unknown_blob(tag, src)),
1238        Some(BlobTarget::Bytes {
1239            bytes, offset, len, ..
1240        }) => match bytes.get(offset..offset + len) {
1241            Some(b) => Ok(b.to_vec()),
1242            None => Err(format!(
1243                "<{tag} src=\"{src}\">: the blob: URL's window lies outside its bytes"
1244            )),
1245        },
1246        Some(t @ BlobTarget::Path { .. }) => {
1247            check_snapshot(tag, src, &t)?;
1248            let BlobTarget::Path {
1249                path, range, size, ..
1250            } = t
1251            else {
1252                unreachable!()
1253            };
1254            let (offset, len) = range.unwrap_or((0, size));
1255            read_window(&path, offset, len).map_err(|e| {
1256                format!(
1257                    "<{tag} src=\"{src}\">: could not read {} — {e}",
1258                    path.display()
1259                )
1260            })
1261        }
1262    }
1263}
1264
1265/// `len` bytes of `path` from `offset`, or an error: never a truncated decode or an OOM abort.
1266fn read_window(path: &Path, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
1267    use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
1268    let mut f = std::fs::File::open(path)?;
1269    f.seek(SeekFrom::Start(offset))?;
1270    let want = usize::try_from(len)
1271        .map_err(|_| Error::new(ErrorKind::OutOfMemory, "too large to hold in memory"))?;
1272    let mut out = Vec::new();
1273    out.try_reserve_exact(want).map_err(|_| {
1274        Error::new(
1275            ErrorKind::OutOfMemory,
1276            format!("{len} bytes could not be held in memory"),
1277        )
1278    })?;
1279    f.take(len).read_to_end(&mut out)?;
1280    if out.len() != want {
1281        return Err(Error::new(
1282            ErrorKind::UnexpectedEof,
1283            format!(
1284                "the file ended after {} of the {len} bytes the blob: URL names",
1285                out.len()
1286            ),
1287        ));
1288    }
1289    Ok(out)
1290}
1291
1292fn blob_image(src: &str, target: Option<BlobTarget>) -> Option<ImageSource> {
1293    if let Some(t @ BlobTarget::Path { range: None, .. }) = &target {
1294        if let Err(msg) = check_snapshot("img", src, t) {
1295            warn(msg);
1296            return None;
1297        }
1298        let BlobTarget::Path {
1299            path, size, mtime, ..
1300        } = t
1301        else {
1302            unreachable!()
1303        };
1304        note_blob_path(path, (*size, *mtime));
1305        return Some(path_source(path.clone()));
1306    }
1307    let mime = target
1308        .as_ref()
1309        .map(|t| t.mime().to_ascii_lowercase())
1310        .unwrap_or_default();
1311    let bytes = match blob_bytes("img", src, target) {
1312        Ok(b) => b,
1313        Err(msg) => {
1314            warn(msg);
1315            return None;
1316        }
1317    };
1318    let Some(format) = sniff(&bytes).or_else(|| image_format(&mime)) else {
1319        warn(format!(
1320            "<img src=\"{src}\">: the Blob is not an image this renderer decodes (type {mime:?}) — png, \
1321             jpeg, webp, gif, bmp, tiff, ico and svg+xml do"
1322        ));
1323        return None;
1324    };
1325    Some(ImageSource::Image(std::sync::Arc::new(Image::from_bytes(
1326        format, bytes,
1327    ))))
1328}
1329
1330/// `<video src="blob:…">`: a whole picked file is a path (the OS streams it); an in-memory Blob is
1331/// its own `Arc`.
1332fn blob_media(
1333    tag: &str,
1334    src: &str,
1335    target: Option<BlobTarget>,
1336) -> Result<sk_video::MediaSource, String> {
1337    match target {
1338        None => Err(unknown_blob(tag, src)),
1339        Some(t @ BlobTarget::Path { range: None, .. }) => {
1340            check_snapshot(tag, src, &t)?;
1341            let BlobTarget::Path { path, .. } = t else {
1342                unreachable!()
1343            };
1344            Ok(sk_video::MediaSource::Path(path))
1345        }
1346        Some(BlobTarget::Bytes {
1347            bytes,
1348            offset: 0,
1349            len,
1350            mime,
1351        }) if len == bytes.len() => {
1352            if len == 0 {
1353                return Err(format!("<{tag} src=\"{src}\">: the Blob is empty"));
1354            }
1355            Ok(sk_video::MediaSource::Bytes {
1356                mime: mime.to_ascii_lowercase(),
1357                data: bytes,
1358            })
1359        }
1360        Some(t) => {
1361            let mime = t.mime().to_ascii_lowercase();
1362            let data = blob_bytes(tag, src, Some(t))?;
1363            if data.is_empty() {
1364                return Err(format!("<{tag} src=\"{src}\">: the Blob is empty"));
1365            }
1366            Ok(sk_video::MediaSource::Bytes {
1367                mime,
1368                data: std::sync::Arc::new(data),
1369            })
1370        }
1371    }
1372}
1373
1374/// `data:[<mediatype>][;base64],<data>` (RFC 2397).
1375fn data_url(src: &str) -> Option<ImageSource> {
1376    let body = src.get(5..)?;
1377    let (meta, payload) = match body.split_once(',') {
1378        Some(pair) => pair,
1379        None => {
1380            warn(format!(
1381                "<img src=\"{}…\">: malformed data: URL (no comma)",
1382                head(src)
1383            ));
1384            return None;
1385        }
1386    };
1387    let meta_lower = meta.to_ascii_lowercase();
1388    let is_base64 = meta_lower.split(';').any(|p| p.trim() == "base64");
1389    let mime = meta_lower
1390        .split(';')
1391        .next()
1392        .unwrap_or("")
1393        .trim()
1394        .to_string();
1395
1396    let bytes = if is_base64 {
1397        match base64_decode(payload) {
1398            Some(b) => b,
1399            None => {
1400                warn(format!(
1401                    "<img src=\"{}…\">: data: URL payload is not valid base64",
1402                    head(src)
1403                ));
1404                return None;
1405            }
1406        }
1407    } else {
1408        percent_decode_bytes(payload)
1409    };
1410
1411    let format = image_format(&mime).or_else(|| sniff(&bytes));
1412    let Some(format) = format else {
1413        warn(format!(
1414            "<img src=\"{}…\">: unsupported data: URL media type {mime:?} — png, jpeg, webp, gif, \
1415             bmp, tiff, ico and svg+xml decode",
1416            head(src)
1417        ));
1418        return None;
1419    };
1420    Some(ImageSource::Image(std::sync::Arc::new(Image::from_bytes(
1421        format, bytes,
1422    ))))
1423}
1424
1425/// A data: URL IS its content — never echo the whole thing into the log.
1426fn head(src: &str) -> String {
1427    src.chars().take(40).collect()
1428}
1429
1430fn image_format(mime: &str) -> Option<ImageFormat> {
1431    Some(match mime {
1432        "image/png" => ImageFormat::Png,
1433        "image/jpeg" | "image/jpg" => ImageFormat::Jpeg,
1434        "image/webp" => ImageFormat::Webp,
1435        "image/gif" => ImageFormat::Gif,
1436        "image/svg+xml" => ImageFormat::Svg,
1437        "image/bmp" | "image/x-bmp" => ImageFormat::Bmp,
1438        "image/tiff" | "image/tif" => ImageFormat::Tiff,
1439        "image/x-icon" | "image/vnd.microsoft.icon" | "image/ico" => ImageFormat::Ico,
1440        _ => return None,
1441    })
1442}
1443
1444fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
1445    let b = bytes;
1446    if b.starts_with(&[0x89, b'P', b'N', b'G']) {
1447        Some(ImageFormat::Png)
1448    } else if b.starts_with(&[0xFF, 0xD8, 0xFF]) {
1449        Some(ImageFormat::Jpeg)
1450    } else if b.starts_with(b"GIF8") {
1451        Some(ImageFormat::Gif)
1452    } else if b.len() > 12 && &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP" {
1453        Some(ImageFormat::Webp)
1454    } else if b.starts_with(b"BM") {
1455        Some(ImageFormat::Bmp)
1456    } else if b.starts_with(b"<svg") || b.starts_with(b"<?xml") {
1457        Some(ImageFormat::Svg)
1458    } else {
1459        None
1460    }
1461}
1462
1463/// Standard base64 with optional padding; whitespace is skipped.
1464fn base64_decode(s: &str) -> Option<Vec<u8>> {
1465    let mut out = Vec::with_capacity(s.len() / 4 * 3);
1466    let mut acc: u32 = 0;
1467    let mut bits = 0u32;
1468    for c in s.bytes() {
1469        let v = match c {
1470            b'A'..=b'Z' => c - b'A',
1471            b'a'..=b'z' => c - b'a' + 26,
1472            b'0'..=b'9' => c - b'0' + 52,
1473            b'+' | b'-' => 62,
1474            b'/' | b'_' => 63,
1475            b'=' => break,
1476            b' ' | b'\n' | b'\r' | b'\t' | 0x0c => continue,
1477            _ => return None,
1478        };
1479        acc = (acc << 6) | v as u32;
1480        bits += 6;
1481        if bits >= 8 {
1482            bits -= 8;
1483            out.push((acc >> bits) as u8);
1484        }
1485    }
1486    Some(out)
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492
1493    /// `Y:\a\b` on Windows, `/Y/a/b` elsewhere.
1494    fn at(windows: &str) -> PathBuf {
1495        if cfg!(windows) {
1496            PathBuf::from(windows)
1497        } else {
1498            PathBuf::from(windows.replacen("Y:", "/Y", 1).replace('\\', "/"))
1499        }
1500    }
1501
1502    fn as_path(s: Option<ImageSource>) -> Option<PathBuf> {
1503        match s {
1504            Some(ImageSource::Resource(Resource::Path(p))) => Some(p.to_path_buf()),
1505            _ => None,
1506        }
1507    }
1508
1509    fn png(w: u32, h: u32) -> Vec<u8> {
1510        let mut out = std::io::Cursor::new(Vec::new());
1511        image::RgbaImage::new(w, h)
1512            .write_to(&mut out, image::ImageFormat::Png)
1513            .unwrap();
1514        out.into_inner()
1515    }
1516
1517    #[test]
1518    fn an_img_hands_a_canvas_its_pixels() {
1519        let dir = std::env::temp_dir().join(format!("sk-img-pixels-{}", std::process::id()));
1520        std::fs::create_dir_all(&dir).unwrap();
1521        set_asset_base(dir.clone());
1522        let good = dir.join("a.png");
1523        let mut out = std::io::Cursor::new(Vec::new());
1524        image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255]))
1525            .write_to(&mut out, image::ImageFormat::Png)
1526            .unwrap();
1527        std::fs::write(&good, out.into_inner()).unwrap();
1528        let bad = dir.join("b.png");
1529        std::fs::write(&bad, b"not a png").unwrap();
1530        let node = |src: Option<&str>| {
1531            crate::tree::with_tree(|t| {
1532                let tag = t.intern("img");
1533                let id = t.create_element(tag);
1534                let key = t.intern("src");
1535                t.set_prop(id, key, src.map(str::to_string));
1536                id
1537            })
1538        };
1539        match pixels(node(Some("a.png")), None) {
1540            Pixels::Ready {
1541                width,
1542                height,
1543                rgba,
1544            } => {
1545                assert_eq!((width, height), (3, 2));
1546                assert_eq!(&rgba[..4], &[10, 20, 30, 255]);
1547            }
1548            _ => panic!("a PNG file did not decode"),
1549        }
1550        let turned = dir.join("c.jpg");
1551        std::fs::write(&turned, sideways_jpeg()).unwrap();
1552        assert_eq!(file_natural_size(&turned), Probe::Loaded(16.0, 32.0));
1553        assert_eq!(natural_size(&sideways_jpeg()), Probe::Loaded(16.0, 32.0));
1554        assert!(matches!(
1555            pixels(node(Some("c.jpg")), None),
1556            Pixels::Ready {
1557                width: 16,
1558                height: 32,
1559                ..
1560            }
1561        ));
1562        assert!(matches!(
1563            pixels(node(Some("b.png")), None),
1564            Pixels::Broken(_)
1565        ));
1566        assert!(matches!(
1567            pixels(node(Some("https://cdn.example/a.png")), None),
1568            Pixels::NotYet
1569        ));
1570        assert!(matches!(pixels(node(None), None), Pixels::NotYet));
1571        assert!(matches!(pixels(node(Some("  ")), None), Pixels::NotYet));
1572        let _ = std::fs::remove_dir_all(&dir);
1573    }
1574
1575    /// A 32×16 JPEG with Exif orientation 6: upright it is 16×32.
1576    fn sideways_jpeg() -> Vec<u8> {
1577        let mut out = std::io::Cursor::new(Vec::new());
1578        image::RgbImage::from_pixel(32, 16, image::Rgb([200, 0, 0]))
1579            .write_to(&mut out, image::ImageFormat::Jpeg)
1580            .unwrap();
1581        let jpeg = out.into_inner();
1582        let tiff = [
1583            0x4D, 0x4D, 0, 0x2A, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0,
1584            0, 0,
1585        ];
1586        let len = (2 + 6 + tiff.len()) as u16;
1587        let mut with = jpeg[..2].to_vec();
1588        with.extend_from_slice(&[0xFF, 0xE1, (len >> 8) as u8, len as u8]);
1589        with.extend_from_slice(b"Exif\0\0");
1590        with.extend_from_slice(&tiff);
1591        with.extend_from_slice(&jpeg[2..]);
1592        with
1593    }
1594
1595    #[test]
1596    fn halving_weighs_colour_by_alpha() {
1597        let px = [
1598            [255, 0, 0, 255],
1599            [0, 0, 255, 0],
1600            [255, 0, 0, 255],
1601            [0, 0, 255, 0],
1602        ]
1603        .concat();
1604        let (out, w, h) = halve(&px, 2, 2);
1605        assert_eq!((w, h), (1, 1));
1606        assert_eq!(out, vec![255, 0, 0, 128]);
1607        let (out, w, h) = halve(&[9, 9, 9, 255].repeat(3), 3, 1);
1608        assert_eq!((w, h, out), (1, 1, vec![9, 9, 9, 255]));
1609    }
1610
1611    #[test]
1612    fn the_probe_reads_the_natural_size_off_the_header() {
1613        assert_eq!(natural_size(&png(7, 3)), Probe::Loaded(7.0, 3.0));
1614        let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="24"></svg>"#;
1615        assert_eq!(natural_size(svg), Probe::Loaded(40.0, 24.0));
1616        assert_eq!(natural_size(b"not an image"), Probe::Failed);
1617        assert_eq!(natural_size(&png(4, 4)[..12]), Probe::Failed);
1618    }
1619
1620    #[test]
1621    fn a_file_is_measured_from_its_header() {
1622        let dir = std::env::temp_dir().join(format!("sk-img-probe-{}", std::process::id()));
1623        std::fs::create_dir_all(&dir).unwrap();
1624        let raster = dir.join("a.png");
1625        std::fs::write(&raster, png(9, 4)).unwrap();
1626        assert_eq!(file_natural_size(&raster), Probe::Loaded(9.0, 4.0));
1627        let svg = dir.join("b.svg");
1628        std::fs::write(
1629            &svg,
1630            br#"<svg xmlns="http://www.w3.org/2000/svg" width="3" height="2"/>"#,
1631        )
1632        .unwrap();
1633        assert_eq!(file_natural_size(&svg), Probe::Loaded(3.0, 2.0));
1634        assert_eq!(file_natural_size(&dir.join("missing.png")), Probe::Failed);
1635        std::fs::remove_dir_all(&dir).ok();
1636    }
1637
1638    #[test]
1639    fn an_svg_url_is_known_by_its_path() {
1640        assert!(names_svg("https://cdn.example/icons/a.svg"));
1641        assert!(names_svg("https://cdn.example/a.SVG?v=2#frag"));
1642        assert!(!names_svg("https://cdn.example/a.png?x=.svg"));
1643        assert!(!names_svg("svg"));
1644    }
1645
1646    #[test]
1647    fn relative_paths_resolve_against_the_app_root() {
1648        set_asset_base(at("Y:\\skathi\\apps\\imgperf"));
1649        for src in ["assets/a.png", "./assets/a.png", "/assets/a.png"] {
1650            assert_eq!(
1651                as_path(resolve(src)),
1652                Some(at("Y:\\skathi\\apps\\imgperf\\assets\\a.png")),
1653                "{src}"
1654            );
1655        }
1656        assert_eq!(
1657            as_path(resolve("../hello/assets/a.png")),
1658            Some(at("Y:\\skathi\\apps\\hello\\assets\\a.png"))
1659        );
1660    }
1661
1662    #[test]
1663    fn absolute_windows_paths_are_paths_not_uris() {
1664        set_asset_base(at("Y:\\skathi\\apps\\imgperf"));
1665        assert_eq!(
1666            as_path(resolve("C:/pics/a.png")),
1667            Some(PathBuf::from("C:/pics/a.png"))
1668        );
1669        assert_eq!(
1670            as_path(resolve("C:\\pics\\a.png")),
1671            Some(PathBuf::from("C:\\pics\\a.png"))
1672        );
1673    }
1674
1675    #[test]
1676    #[cfg(windows)]
1677    fn file_urls_decode_to_paths() {
1678        assert_eq!(
1679            as_path(resolve("file:///C:/my%20pics/a.png")),
1680            Some(PathBuf::from("C:\\my pics\\a.png"))
1681        );
1682    }
1683
1684    #[test]
1685    fn file_urls_keep_their_path_off_windows() {
1686        let unix = |src| file_url_for(src, false).map(|p| p.to_string_lossy().into_owned());
1687        assert_eq!(
1688            unix("file:///home/u/my%20pics/a.png").as_deref(),
1689            Some("/home/u/my pics/a.png")
1690        );
1691        assert_eq!(
1692            unix("file://localhost/home/u/a.png").as_deref(),
1693            Some("/home/u/a.png")
1694        );
1695        assert_eq!(unix("file:/home/u/a.png").as_deref(), Some("/home/u/a.png"));
1696        let windows = |src| file_url_for(src, true).map(|p| p.to_string_lossy().into_owned());
1697        assert_eq!(
1698            windows("file:///C:/x/a.png").as_deref(),
1699            Some("C:\\x\\a.png")
1700        );
1701    }
1702
1703    #[test]
1704    fn video_sources_resolve_to_the_shape_the_platform_wants() {
1705        use sk_video::MediaSource;
1706        assert!(matches!(
1707            resolve_media("video", "https://example.com/a.mp4"),
1708            Ok(MediaSource::Uri(u)) if u == "https://example.com/a.mp4"
1709        ));
1710        match resolve_media("video", "data:video/mp4;base64,AAAA") {
1711            Ok(MediaSource::Bytes { mime, data }) => {
1712                assert_eq!(mime, "video/mp4");
1713                assert_eq!(&*data, &[0u8, 0, 0]);
1714            }
1715            other => panic!("{other:?}"),
1716        }
1717        // Not a zero-byte load that fails deep inside Media Foundation.
1718        assert!(resolve_media("video", "data:video/mp4;base64,").is_err());
1719        assert!(resolve_media("video", "").is_err());
1720        assert!(matches!(
1721            resolve_media("video", "assets/clip.mp4"),
1722            Ok(MediaSource::Path(_))
1723        ));
1724    }
1725
1726    #[test]
1727    fn data_urls_decode_and_sniff() {
1728        const PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
1729        let Some(ImageSource::Image(img)) = resolve(PNG) else {
1730            panic!("data: URL did not resolve to an image");
1731        };
1732        assert_eq!(img.format, ImageFormat::Png);
1733        assert!(img.bytes.starts_with(&[0x89, b'P', b'N', b'G']));
1734
1735        let sniffed = resolve("data:;base64,iVBORw0KGgoAAAANSUhEUg==");
1736        assert!(matches!(sniffed, Some(ImageSource::Image(_))));
1737
1738        let svg =
1739            resolve("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22/%3E");
1740        let Some(ImageSource::Image(img)) = svg else {
1741            panic!("percent-encoded data: URL did not resolve");
1742        };
1743        assert_eq!(img.format, ImageFormat::Svg);
1744        assert!(String::from_utf8_lossy(&img.bytes).starts_with("<svg"));
1745
1746        let Some(ImageSource::Image(img)) = resolve("data:image/png,%89PNG%0D%0A%1A%0A%FF%00")
1747        else {
1748            panic!("percent-encoded binary data: URL did not resolve");
1749        };
1750        assert_eq!(
1751            &img.bytes[..],
1752            &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0x00]
1753        );
1754    }
1755
1756    #[test]
1757    fn empty_and_unknown_schemes_yield_nothing() {
1758        assert!(resolve("").is_none());
1759        assert!(resolve("   ").is_none());
1760        assert!(resolve("gopher://x/a.png").is_none());
1761    }
1762
1763    #[test]
1764    fn base64_ignores_wrapping_whitespace() {
1765        assert_eq!(base64_decode("QUJD").unwrap(), b"ABC");
1766        assert_eq!(base64_decode("QU\n JD\r\n").unwrap(), b"ABC");
1767        assert_eq!(base64_decode("QQ==").unwrap(), b"A");
1768        assert!(base64_decode("**").is_none());
1769    }
1770
1771    const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1772    static FAKE: &[(&str, &[u8])] = &[
1773        ("assets/a.png", PNG),
1774        ("assets/clip.mp4", b"mp4bytes"),
1775        ("assets/s.tgs", b"tgs"),
1776        ("assets/my pic.png", PNG),
1777    ];
1778    fn fake_store(key: &str) -> Option<&'static [u8]> {
1779        FAKE.iter().find(|(k, _)| *k == key).map(|(_, v)| *v)
1780    }
1781    /// The store is thread-local; take it away again so a reused thread does not inherit it.
1782    struct StoreGuard;
1783    impl Drop for StoreGuard {
1784        fn drop(&mut self) {
1785            STORE.with(|s| s.set(None));
1786        }
1787    }
1788    fn packaged() -> StoreGuard {
1789        set_asset_store(fake_store);
1790        StoreGuard
1791    }
1792
1793    #[test]
1794    fn a_packaged_app_resolves_relative_srcs_out_of_its_store() {
1795        let _g = packaged();
1796        for src in [
1797            "assets/a.png",
1798            "./assets/a.png",
1799            "/assets/a.png",
1800            "assets/a.png?v=2",
1801            "assets/x/../a.png",
1802        ] {
1803            match resolve(src) {
1804                Some(ImageSource::Resource(Resource::Embedded(key))) => {
1805                    assert_eq!(key.as_ref(), "assets/a.png", "{src}")
1806                }
1807                other => panic!(
1808                    "{src}: not an embedded resource (some: {})",
1809                    other.is_some()
1810                ),
1811            }
1812        }
1813        assert!(matches!(
1814            resolve("assets/my%20pic.png"),
1815            Some(ImageSource::Resource(Resource::Embedded(k))) if k.as_ref() == "assets/my pic.png"
1816        ));
1817        // A miss is a broken image (alt text), NEVER the disk — even with a base set.
1818        set_asset_base(at("Y:\\skathi\\apps\\hello"));
1819        assert!(resolve("assets/nope.png").is_none());
1820        assert!(resolve("../hello/assets/a.png").is_none());
1821        assert!(matches!(
1822            resolve("C:/pics/a.png"),
1823            Some(ImageSource::Resource(Resource::Path(_)))
1824        ));
1825        assert!(matches!(
1826            resolve("https://example.com/a.png"),
1827            Some(ImageSource::Resource(Resource::Uri(_)))
1828        ));
1829        assert!(matches!(
1830            resolve("data:;base64,iVBORw0KGgo="),
1831            Some(ImageSource::Image(_))
1832        ));
1833    }
1834
1835    #[test]
1836    fn lottie_and_video_read_the_same_store() {
1837        use sk_video::MediaSource;
1838        let _g = packaged();
1839        assert_eq!(read_bytes("lottie", "assets/s.tgs").unwrap(), b"tgs");
1840        assert_eq!(read_bytes("lottie", "/assets/s.tgs?x").unwrap(), b"tgs");
1841        assert!(read_bytes("lottie", "assets/missing.tgs").is_err());
1842        match resolve_media("video", "assets/clip.mp4") {
1843            Ok(MediaSource::StaticBytes { mime, data }) => {
1844                assert_eq!(mime, "video/mp4");
1845                assert_eq!(data, &b"mp4bytes"[..]);
1846                assert!(
1847                    std::ptr::eq(data, fake_store("assets/clip.mp4").unwrap()),
1848                    "mapped package bytes must be borrowed"
1849                );
1850            }
1851            other => panic!("{other:?}"),
1852        }
1853        assert!(resolve_media("video", "assets/missing.mp4").is_err());
1854        assert!(matches!(
1855            resolve_media("video", "https://example.com/a.mp4"),
1856            Ok(MediaSource::Uri(_))
1857        ));
1858    }
1859
1860    #[test]
1861    fn a_dev_host_has_no_store_and_joins_the_same_key_onto_the_app_root() {
1862        assert!(asset_store().is_none());
1863        set_asset_base(at("Y:\\base"));
1864        // Browser-shaped: the server never sees the query, and decodes escapes.
1865        assert_eq!(as_path(resolve("a.png?v=2")), Some(at("Y:\\base\\a.png")));
1866        assert_eq!(
1867            as_path(resolve("my%20pic.png")),
1868            Some(at("Y:\\base\\my pic.png"))
1869        );
1870        assert_eq!(
1871            as_path(resolve("dir\\a.png")),
1872            Some(at("Y:\\base\\dir\\a.png"))
1873        );
1874        // A decoded drive letter must not replace the app root.
1875        assert_eq!(
1876            as_path(resolve("C%3A/x.png")),
1877            Some(at("Y:\\base\\C%3A\\x.png"))
1878        );
1879        assert!(matches!(
1880            resolve_media("video", "assets/clip.mp4"),
1881            Ok(sk_video::MediaSource::Path(_))
1882        ));
1883    }
1884
1885    /// The memo must follow the `src`, not the node id — Vue reuses ids.
1886    #[test]
1887    fn the_per_node_memo_follows_the_src_string() {
1888        set_asset_base(at("Y:\\base"));
1889        assert_eq!(as_path(source_for(7, "a.png")), Some(at("Y:\\base\\a.png")));
1890        assert_eq!(as_path(source_for(7, "b.png")), Some(at("Y:\\base\\b.png")));
1891    }
1892
1893    /// A temp file with the target a picked File over it would resolve to; removed on drop.
1894    struct Picked(PathBuf);
1895
1896    impl Picked {
1897        fn new(name: &str, bytes: &[u8]) -> Picked {
1898            let dir =
1899                std::env::temp_dir().join(format!("sk-tree-blob-{}-{name}", std::process::id()));
1900            std::fs::create_dir_all(&dir).unwrap();
1901            let p = dir.join(name);
1902            std::fs::write(&p, bytes).unwrap();
1903            Picked(p)
1904        }
1905
1906        fn target(&self, range: Option<(u64, u64)>, mime: &str) -> BlobTarget {
1907            let m = std::fs::metadata(&self.0).unwrap();
1908            BlobTarget::Path {
1909                path: self.0.clone(),
1910                range,
1911                size: m.len(),
1912                mtime: m.modified().ok(),
1913                mime: mime.into(),
1914            }
1915        }
1916    }
1917
1918    impl Drop for Picked {
1919        fn drop(&mut self) {
1920            let _ = std::fs::remove_file(&self.0);
1921            let _ = std::fs::remove_dir(self.0.parent().unwrap());
1922        }
1923    }
1924
1925    const PNG_1PX: &[u8] = &[
1926        0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, b'I', b'H', b'D', b'R', 0,
1927        0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4, 0x89,
1928    ];
1929
1930    #[test]
1931    fn a_whole_picked_file_loads_by_path_without_a_copy() {
1932        let f = Picked::new("pic.png", PNG_1PX);
1933        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000001";
1934        assert_eq!(
1935            as_path(blob_image(src, Some(f.target(None, "image/png")))),
1936            Some(f.0.clone())
1937        );
1938        assert!(matches!(
1939            blob_media("video", src, Some(f.target(None, "video/mp4"))),
1940            Ok(sk_video::MediaSource::Path(p)) if p == f.0
1941        ));
1942    }
1943
1944    #[test]
1945    fn a_slice_or_bytes_in_memory_decode_from_their_bytes() {
1946        let mut body = b"xx".to_vec();
1947        body.extend_from_slice(PNG_1PX);
1948        let f = Picked::new("two.bin", &body);
1949        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000002";
1950        let t = f.target(Some((2, PNG_1PX.len() as u64)), "");
1951        assert!(matches!(
1952            blob_image(src, Some(t)),
1953            Some(ImageSource::Image(_))
1954        ));
1955        let arc = std::sync::Arc::new(PNG_1PX.to_vec());
1956        let whole = BlobTarget::Bytes {
1957            bytes: arc.clone(),
1958            offset: 0,
1959            len: arc.len(),
1960            mime: "video/mp4".into(),
1961        };
1962        match blob_media("video", src, Some(whole)) {
1963            Ok(sk_video::MediaSource::Bytes { data, mime }) => {
1964                assert!(std::sync::Arc::ptr_eq(&data, &arc));
1965                assert_eq!(mime, "video/mp4");
1966            }
1967            other => panic!("{other:?}"),
1968        }
1969        let part = BlobTarget::Bytes {
1970            bytes: arc.clone(),
1971            offset: 1,
1972            len: 3,
1973            mime: String::new(),
1974        };
1975        assert_eq!(blob_bytes("lottie", src, Some(part)).unwrap(), b"PNG");
1976        let text = BlobTarget::Bytes {
1977            bytes: std::sync::Arc::new(b"hello".to_vec()),
1978            offset: 0,
1979            len: 5,
1980            mime: "text/plain".into(),
1981        };
1982        assert!(blob_image(src, Some(text)).is_none());
1983    }
1984
1985    #[test]
1986    fn a_changed_file_or_an_unknown_url_fails_the_load() {
1987        let f = Picked::new("snap.png", PNG_1PX);
1988        let src = "blob:app://redjs/00000000-0000-4000-8000-000000000003";
1989        let t = f.target(None, "image/png");
1990        std::fs::write(&f.0, b"a different file now").unwrap();
1991        assert!(blob_image(src, Some(t.clone())).is_none());
1992        assert!(blob_media("video", src, Some(t)).is_err());
1993        assert!(resolve(src).is_none());
1994        assert!(read_bytes("lottie", src).is_err());
1995        assert!(resolve_media("video", src).is_err());
1996    }
1997
1998    #[test]
1999    fn a_window_is_read_whole_or_refused() {
2000        let f = Picked::new("window.bin", b"0123456789");
2001        assert_eq!(read_window(&f.0, 4, 4).unwrap(), b"4567");
2002        let short = read_window(&f.0, 8, 10).unwrap_err();
2003        assert_eq!(short.kind(), std::io::ErrorKind::UnexpectedEof, "{short}");
2004        let huge = read_window(&f.0, 0, u64::MAX).unwrap_err();
2005        assert_eq!(huge.kind(), std::io::ErrorKind::OutOfMemory, "{huge}");
2006    }
2007
2008    /// A URL a script made in this thread's runtime is found by the render walk's lookup.
2009    #[test]
2010    fn a_url_made_by_script_resolves_through_the_runtimes_store() {
2011        let f = Picked::new("picked.png", PNG_1PX);
2012        sk_runtime::testing::on_js_thread(move || {
2013            let eval = |src: &str| -> String {
2014                JsRuntime::with(|rt| {
2015                    let v = rt
2016                        .ctx()
2017                        .eval(src)
2018                        .unwrap_or_else(|e| panic!("{src}: {e:?}"));
2019                    rt.ctx().to_rust_string(v).unwrap()
2020                })
2021            };
2022            let bytes: Vec<String> = PNG_1PX.iter().map(|b| b.to_string()).collect();
2023            let mem = eval(&format!(
2024                "URL.createObjectURL(new Blob([new Uint8Array([{}])], {{ type: 'image/png' }}))",
2025                bytes.join(",")
2026            ));
2027            assert!(
2028                matches!(resolve(&mem), Some(ImageSource::Image(_))),
2029                "{mem}"
2030            );
2031            JsRuntime::with(|rt| unsafe {
2032                let g = rt.raw();
2033                let file = redjs::webapi::file::file_from_path(g, &f.0, "").unwrap();
2034                redjs::webapi::util::define(g, redjs::glue::rjs_global(g), "picked", file, 0);
2035            });
2036            let by_path = eval("URL.createObjectURL(picked)");
2037            assert_eq!(
2038                as_path(resolve(&by_path)),
2039                Some(f.0.clone()),
2040                "a picked file is handed on by path"
2041            );
2042            assert!(
2043                matches!(resolve_media("video", &by_path), Ok(sk_video::MediaSource::Path(p)) if p == f.0)
2044            );
2045            let again = eval("URL.createObjectURL(picked)");
2046            let _ = take_evictions();
2047            assert!(source_for(901, &mem).is_some());
2048            assert!(source_for(902, &by_path).is_some());
2049            assert!(
2050                source_for(903, &again).is_some(),
2051                "a second URL of the same File: the same path"
2052            );
2053            gc(|id| id != 901 && id != 902);
2054            let ev = take_evictions();
2055            assert_eq!(
2056                ev.len(),
2057                1,
2058                "the memory decode goes; the path is still shown by 903"
2059            );
2060            assert!(matches!(&ev[0], ImageSource::Image(_)));
2061            gc(|id| id != 903);
2062            let ev = take_evictions();
2063            assert!(
2064                matches!(&ev[..], [ImageSource::Resource(Resource::Path(p))] if p.as_ref() == f.0),
2065                "{} queued",
2066                ev.len()
2067            );
2068            eval(&format!("URL.revokeObjectURL('{mem}'); 'ok'"));
2069            assert!(resolve(&mem).is_none(), "revoked");
2070        });
2071    }
2072
2073    #[test]
2074    fn a_file_picked_again_after_it_changed_evicts_the_old_decode() {
2075        let f = Picked::new("again.png", PNG_1PX);
2076        let first = "blob:app://redjs/00000000-0000-4000-8000-0000000000a1";
2077        let t1 = f.target(None, "image/png");
2078        assert!(blob_image(first, Some(t1.clone())).is_some());
2079        assert!(
2080            take_evictions().is_empty(),
2081            "first sight: nothing of it is cached"
2082        );
2083        assert!(blob_image(first, Some(t1)).is_some());
2084        assert!(
2085            take_evictions().is_empty(),
2086            "the same file again: the cached decode is right"
2087        );
2088        let mut edited = PNG_1PX.to_vec();
2089        edited.extend([0u8; 16]);
2090        std::fs::write(&f.0, &edited).unwrap();
2091        let t2 = f.target(None, "image/png");
2092        assert!(blob_image(
2093            "blob:app://redjs/00000000-0000-4000-8000-0000000000a2",
2094            Some(t2)
2095        )
2096        .is_some());
2097        let ev = take_evictions();
2098        assert!(
2099            matches!(&ev[..], [ImageSource::Resource(Resource::Path(p))] if p.as_ref() == f.0),
2100            "{} queued",
2101            ev.len()
2102        );
2103    }
2104}