Skip to main content

sk_tree/
resample.rs

1//! Smaller copies of images drawn well below their own size. gpui's atlas keeps one mip level and
2//! samples it linearly, so a large image drawn small aliases. The fork asks this module at paint
3//! (`gpui::ImageResampler`, with the device-pixel size about to be drawn) and gets a copy filtered down:
4//! 2×2 box steps while more than twice the target, then Lanczos3, in premultiplied floating point.
5//! The hook is paint, not decode, because only paint knows the size after `object-fit` and scale, and
6//! a smaller decode would shrink the intrinsic size `<img>` layout reads.
7
8use std::cell::{Cell, RefCell};
9use std::collections::{HashMap, HashSet};
10use std::sync::{mpsc, Arc, Mutex, OnceLock, Weak};
11use std::time::{Duration, Instant};
12
13use gpui::{DevicePixels, ImageId, RenderImage, Size};
14use sk_resample::downscale;
15
16/// Below this fraction of its size along an axis, an image is drawn from a copy.
17const RESAMPLE_BELOW: f32 = 0.8;
18/// Size steps per octave.
19const STEPS: f32 = 4.0;
20/// The largest image (source pixels) whose first copy is made on the painting thread (a 1080 × 1080
21/// avatar takes about 1.5 ms).
22const SYNC_PIXELS: u64 = 1_300_000;
23/// What one frame may spend making first copies on the painting thread.
24const SYNC_BUDGET: Duration = Duration::from_millis(4);
25/// How long another size of an image must be asked for before it gets a copy.
26const SETTLE: Duration = Duration::from_millis(100);
27/// The bytes of copies kept.
28const BUDGET_BYTES: usize = 64 << 20;
29/// How long an image must have been painted before a copy may stand in for its decode.
30const REDUCE_AFTER: Duration = Duration::from_secs(2);
31/// The span of each of the two windows the largest drawn size is kept over: a large draw holds the
32/// full decode 15–30 s after it ends.
33const USE_WINDOW: Duration = Duration::from_secs(15);
34/// A copy stands in for a decode only when that frees at least this much and at least three
35/// quarters of the decode.
36const MIN_SAVING: usize = 256 << 10;
37/// How much larger than its pixels a reduced image may be drawn before the full decode is wanted
38/// back (the quarter-octave step a copy is rounded up to).
39const UPSCALE_TOLERANCE: f32 = 1.2;
40
41/// A copy's key: the image, its frame, and the size step on each axis (0 = the natural size on that
42/// axis, -1 = 2^(-1/4) of it, …).
43type Key = (ImageId, usize, i32, i32);
44
45struct Copy {
46    image: Arc<RenderImage>,
47    source: Weak<RenderImage>,
48    bytes: usize,
49    used: u64,
50}
51
52#[derive(Default)]
53struct Cache {
54    copies: HashMap<Key, Copy>,
55    in_flight: HashSet<Key>,
56    waiting: HashMap<Key, (Weak<RenderImage>, Instant)>,
57    clock: u64,
58    bytes: usize,
59    sync_spent: Duration,
60    retired: Vec<Arc<RenderImage>>,
61}
62
63thread_local! {
64    static CACHE: RefCell<Cache> = RefCell::new(Cache::default());
65    static HOLD_REPLAYS: Cell<bool> = const { Cell::new(false) };
66    static USES: RefCell<HashMap<ImageId, Use>> = RefCell::new(HashMap::new());
67    static WANT_FULL: RefCell<HashSet<ImageId>> = RefCell::new(HashSet::new());
68}
69
70struct Use {
71    image: Weak<RenderImage>,
72    first: Instant,
73    cur: (i32, i32),
74    prev: (i32, i32),
75    rotated: Instant,
76    /// The size of the latest draw: what an image stands for once a retained subtree replays it.
77    last: (i32, i32),
78}
79
80fn note_use(image: &Arc<RenderImage>, device: Size<DevicePixels>, now: Instant) {
81    let d = (device.width.0, device.height.0);
82    if image.is_reduced() {
83        let px = image.size(0);
84        let over = |d: i32, p: i32| d as f32 > p as f32 * UPSCALE_TOLERANCE;
85        if over(d.0, px.width.0) || over(d.1, px.height.0) {
86            WANT_FULL.with(|w| w.borrow_mut().insert(image.id));
87        }
88    }
89    USES.with(|u| {
90        let mut u = u.borrow_mut();
91        let e = u.entry(image.id).or_insert_with(|| Use {
92            image: Arc::downgrade(image),
93            first: now,
94            cur: (0, 0),
95            prev: (0, 0),
96            rotated: now,
97            last: d,
98        });
99        let since = now.duration_since(e.rotated);
100        if since >= USE_WINDOW {
101            e.prev = if since >= USE_WINDOW * 2 {
102                (0, 0)
103            } else {
104                e.cur
105            };
106            e.cur = (0, 0);
107            e.rotated = now;
108        }
109        e.cur = (e.cur.0.max(d.0), e.cur.1.max(d.1));
110        e.last = d;
111    });
112}
113
114fn recent_use(id: ImageId, now: Instant) -> Option<((i32, i32), Duration)> {
115    USES.with(|u| {
116        let u = u.borrow();
117        let e = u.get(&id)?;
118        let since = now.duration_since(e.rotated);
119        let (cur, prev) = if since >= USE_WINDOW * 2 {
120            ((0, 0), (0, 0))
121        } else if since >= USE_WINDOW {
122            ((0, 0), e.cur)
123        } else {
124            (e.cur, e.prev)
125        };
126        let w = cur.0.max(prev.0).max(e.last.0);
127        let h = cur.1.max(prev.1).max(e.last.1);
128        Some(((w, h), now.duration_since(e.first)))
129    })
130}
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub(crate) enum KeepFull {
134    /// Already a copy, or not a still picture (an animation, a moving frame).
135    NotStill,
136    Undrawn,
137    /// Drawn for less than [`REDUCE_AFTER`].
138    Young,
139    /// Drawn at 0.8 of its size or more along an axis lately.
140    DrawnLarge,
141    NoCopy,
142    /// The copy would free less than [`MIN_SAVING`] or a quarter of it.
143    SmallSaving,
144}
145
146pub(crate) fn reduced_copy(
147    full: &Arc<RenderImage>,
148    now: Instant,
149) -> Result<Arc<RenderImage>, KeepFull> {
150    if full.is_reduced() || full.is_dynamic() || full.frame_count() != 1 {
151        return Err(KeepFull::NotStill);
152    }
153    let (drawn, age) = recent_use(full.id, now).ok_or(KeepFull::Undrawn)?;
154    if drawn.0 <= 0 || drawn.1 <= 0 {
155        return Err(KeepFull::Undrawn);
156    }
157    if age < REDUCE_AFTER {
158        return Err(KeepFull::Young);
159    }
160    let natural = full.size(0);
161    let (nw, nh) = (natural.width.0, natural.height.0);
162    if nw <= 0 || nh <= 0 {
163        return Err(KeepFull::NotStill);
164    }
165    let need = (
166        step(drawn.0 as f32 / nw as f32),
167        step(drawn.1 as f32 / nh as f32),
168    );
169    if need.0 == 0 || need.1 == 0 {
170        return Err(KeepFull::DrawnLarge);
171    }
172    let full_bytes = nw as usize * nh as usize * 4;
173    CACHE.with(|c| {
174        let mut c = c.borrow_mut();
175        let key = c
176            .copies
177            .keys()
178            .filter(|k| k.0 == full.id && k.1 == 0 && k.2 >= need.0 && k.3 >= need.1)
179            .min_by_key(|k| (k.2 + k.3, k.2))
180            .copied()
181            .ok_or(KeepFull::NoCopy)?;
182        let bytes = c.copies.get(&key).ok_or(KeepFull::NoCopy)?.bytes;
183        if bytes.saturating_mul(4) > full_bytes || full_bytes - bytes < MIN_SAVING {
184            return Err(KeepFull::SmallSaving);
185        }
186        let copy = c.copies.remove(&key).ok_or(KeepFull::NoCopy)?;
187        c.bytes -= copy.bytes;
188        Ok(copy.image)
189    })
190}
191
192pub(crate) fn take_wanted_full() -> HashSet<ImageId> {
193    WANT_FULL.with(|w| std::mem::take(&mut *w.borrow_mut()))
194}
195
196pub(crate) fn want_full(id: ImageId) {
197    WANT_FULL.with(|w| w.borrow_mut().insert(id));
198}
199
200pub(crate) fn prune_uses() {
201    USES.with(|u| u.borrow_mut().retain(|_, e| e.image.strong_count() > 0));
202}
203
204/// Something other than this module swapped or freed an atlas tile: no retained-render boundary may
205/// replay ([`holds_replays`]).
206pub(crate) fn hold_replays_too() {
207    HOLD_REPLAYS.with(|h| h.set(true));
208}
209
210struct Job {
211    key: Key,
212    source: Arc<RenderImage>,
213    target: (u32, u32),
214}
215
216type Landed = (Key, Weak<RenderImage>, Option<RenderImage>);
217
218static DONE: Mutex<Vec<Landed>> = Mutex::new(Vec::new());
219static JOBS: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
220
221/// `SK_NO_RESAMPLE=1` leaves every image to the atlas's own sampling (A/B and field diagnosis).
222fn enabled() -> bool {
223    static ON: OnceLock<bool> = OnceLock::new();
224    *ON.get_or_init(|| {
225        let off = std::env::var("SK_NO_RESAMPLE").map(|v| {
226            let v = v.trim().to_ascii_lowercase();
227            !(v.is_empty() || v == "0" || v == "false" || v == "off")
228        });
229        !off.unwrap_or(false)
230    })
231}
232
233pub(crate) fn forget(image: &RenderImage) {
234    CACHE.with(|c| {
235        let mut c = c.borrow_mut();
236        let keys: Vec<Key> = c
237            .copies
238            .keys()
239            .filter(|k| k.0 == image.id)
240            .copied()
241            .collect();
242        for k in keys {
243            evict(&mut c, k);
244        }
245        c.waiting.retain(|k, _| k.0 != image.id);
246    });
247}
248
249pub(crate) fn holds_replays() -> bool {
250    HOLD_REPLAYS.with(Cell::get)
251}
252
253pub(crate) fn step(scale: f32) -> i32 {
254    if !(scale > 0.0) || scale >= RESAMPLE_BELOW {
255        return 0;
256    }
257    ((scale.log2() * STEPS).ceil() as i32).min(-1)
258}
259
260pub(crate) fn stepped(natural: u32, step: i32) -> u32 {
261    if step == 0 {
262        return natural;
263    }
264    ((natural as f32 * (step as f32 / STEPS).exp2()).ceil() as u32).clamp(1, natural)
265}
266
267fn resampler(
268    image: &Arc<RenderImage>,
269    frame: usize,
270    device: Size<DevicePixels>,
271) -> Option<Arc<RenderImage>> {
272    note_use(image, device, Instant::now());
273    let out = choose(image, frame, device);
274    if TRACK.load(std::sync::atomic::Ordering::Relaxed) {
275        note_seen(image, device, out.is_none());
276    }
277    out
278}
279
280// gpui keeps every decoded image in its asset cache and gives nobody outside it a way to list them.
281
282static TRACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
283
284struct Seen {
285    image: Weak<RenderImage>,
286    bytes: usize,
287    natural: (i32, i32),
288    drawn: (i32, i32),
289    full_drawn: bool,
290}
291
292thread_local! {
293    static SEEN: RefCell<HashMap<ImageId, Seen>> = RefCell::new(HashMap::new());
294}
295
296pub fn set_tracking(on: bool) {
297    TRACK.store(on, std::sync::atomic::Ordering::Relaxed);
298}
299
300fn note_seen(image: &Arc<RenderImage>, device: Size<DevicePixels>, full: bool) {
301    SEEN.with(|s| {
302        let mut s = s.borrow_mut();
303        let e = s.entry(image.id).or_insert_with(|| {
304            let natural = image.size(0);
305            let bytes = (0..image.frame_count())
306                .map(|i| {
307                    let z = image.size(i);
308                    (z.width.0.max(0) as usize) * (z.height.0.max(0) as usize) * 4
309                })
310                .sum();
311            Seen {
312                image: Arc::downgrade(image),
313                bytes,
314                natural: (natural.width.0, natural.height.0),
315                drawn: (0, 0),
316                full_drawn: false,
317            }
318        });
319        e.drawn = (
320            e.drawn.0.max(device.width.0),
321            e.drawn.1.max(device.height.0),
322        );
323        e.full_drawn |= full;
324    });
325}
326
327#[derive(Default, Debug, Clone)]
328pub struct ImageStats {
329    pub tracking: bool,
330    pub live: usize,
331    pub live_bytes: usize,
332    pub live_bytes_at_drawn: usize,
333    pub oversized: usize,
334    pub oversized_bytes: usize,
335    /// Images drawn at least once from the full-size decode (estimate: a later `drop_image` is not seen).
336    pub full_in_atlas: usize,
337    pub full_in_atlas_bytes: usize,
338    pub gone: usize,
339    pub copies: usize,
340    pub copies_bytes: usize,
341    pub copies_in_flight: usize,
342    pub largest: Vec<(i32, i32, i32, i32, usize)>,
343}
344
345pub fn image_stats() -> ImageStats {
346    let mut out = ImageStats {
347        tracking: TRACK.load(std::sync::atomic::Ordering::Relaxed),
348        ..Default::default()
349    };
350    CACHE.with(|c| {
351        let c = c.borrow();
352        out.copies = c.copies.len();
353        out.copies_bytes = c.bytes;
354        out.copies_in_flight = c.in_flight.len();
355    });
356    SEEN.with(|s| {
357        let s = s.borrow();
358        let mut largest: Vec<(i32, i32, i32, i32, usize)> = Vec::new();
359        for e in s.values() {
360            if e.full_drawn {
361                out.full_in_atlas += 1;
362                out.full_in_atlas_bytes += e.bytes;
363            }
364            if e.image.strong_count() == 0 {
365                out.gone += 1;
366                continue;
367            }
368            out.live += 1;
369            out.live_bytes += e.bytes;
370            let (nw, nh) = (e.natural.0.max(1) as usize, e.natural.1.max(1) as usize);
371            let (dw, dh) = (
372                e.drawn.0.clamp(1, nw as i32) as usize,
373                e.drawn.1.clamp(1, nh as i32) as usize,
374            );
375            let ratio = (dw * dh) as f64 / (nw * nh) as f64;
376            out.live_bytes_at_drawn += (e.bytes as f64 * ratio) as usize;
377            if nw * nh >= 4 * dw * dh {
378                out.oversized += 1;
379                out.oversized_bytes += e.bytes;
380            }
381            largest.push((e.natural.0, e.natural.1, e.drawn.0, e.drawn.1, e.bytes));
382        }
383        largest.sort_by(|a, b| b.4.cmp(&a.4));
384        largest.truncate(5);
385        out.largest = largest;
386    });
387    out
388}
389
390fn choose(
391    image: &Arc<RenderImage>,
392    frame: usize,
393    device: Size<DevicePixels>,
394) -> Option<Arc<RenderImage>> {
395    let natural = image.size(frame);
396    let (nw, nh) = (natural.width.0, natural.height.0);
397    if nw <= 0 || nh <= 0 || device.width.0 <= 0 || device.height.0 <= 0 {
398        return None;
399    }
400    let steps = (
401        step(device.width.0 as f32 / nw as f32),
402        step(device.height.0 as f32 / nh as f32),
403    );
404    if steps == (0, 0) {
405        return None;
406    }
407    let key = (image.id, frame, steps.0, steps.1);
408    CACHE.with(|c| {
409        let mut c = c.borrow_mut();
410        c.clock += 1;
411        let clock = c.clock;
412        if let Some(copy) = c.copies.get_mut(&key) {
413            copy.used = clock;
414            return Some(copy.image.clone());
415        }
416        match nearest(&c, image.id, frame, steps) {
417            None => {
418                if c.in_flight.iter().any(|k| k.0 == image.id && k.1 == frame) {
419                    return None;
420                }
421                let target = (stepped(nw as u32, steps.0), stepped(nh as u32, steps.1));
422                if (nw as u64) * (nh as u64) <= SYNC_PIXELS && c.sync_spent < SYNC_BUDGET {
423                    let t = Instant::now();
424                    let made = Arc::new(make(image, frame, target)?);
425                    c.sync_spent += t.elapsed();
426                    crate::perf::note_resample(Some(t.elapsed().as_secs_f32() * 1000.0));
427                    insert(&mut c, key, made.clone(), Arc::downgrade(image), clock);
428                    Some(made)
429                } else {
430                    c.in_flight.insert(key);
431                    crate::perf::note_resample(None);
432                    submit(Job {
433                        key,
434                        source: image.clone(),
435                        target,
436                    });
437                    None
438                }
439            }
440            Some(near) => {
441                if !c.in_flight.contains(&key) {
442                    c.waiting
443                        .entry(key)
444                        .or_insert_with(|| (Arc::downgrade(image), Instant::now()));
445                }
446                let copy = c.copies.get_mut(&near)?;
447                copy.used = clock;
448                Some(copy.image.clone())
449            }
450        }
451    })
452}
453
454fn nearest(c: &Cache, id: ImageId, frame: usize, steps: (i32, i32)) -> Option<Key> {
455    c.copies
456        .keys()
457        .filter(|k| k.0 == id && k.1 == frame)
458        .min_by_key(|k| {
459            let distance = (k.2 - steps.0).abs() + (k.3 - steps.1).abs();
460            let smaller = k.2 < steps.0 || k.3 < steps.1;
461            (distance, smaller)
462        })
463        .copied()
464}
465
466fn insert(c: &mut Cache, key: Key, image: Arc<RenderImage>, source: Weak<RenderImage>, clock: u64) {
467    let size = image.size(0);
468    let bytes = (size.width.0.max(0) as usize) * (size.height.0.max(0) as usize) * 4;
469    c.bytes += bytes;
470    if let Some(old) = c.copies.insert(
471        key,
472        Copy {
473            image,
474            source,
475            bytes,
476            used: clock,
477        },
478    ) {
479        c.bytes -= old.bytes;
480        c.retired.push(old.image);
481    }
482}
483
484fn evict(c: &mut Cache, key: Key) {
485    if let Some(copy) = c.copies.remove(&key) {
486        c.bytes -= copy.bytes;
487        c.retired.push(copy.image);
488    }
489}
490
491fn make(image: &RenderImage, frame: usize, target: (u32, u32)) -> Option<RenderImage> {
492    let size = image.size(frame);
493    let bytes = image.as_bytes(frame)?;
494    let out = downscale(
495        bytes,
496        size.width.0 as u32,
497        size.height.0 as u32,
498        target.0,
499        target.1,
500        false,
501    );
502    let buffer = image::RgbaImage::from_raw(target.0, target.1, out)?;
503    Some(
504        RenderImage::new(vec![image::Frame::new(buffer)])
505            .with_natural_size(image.natural_size(frame)),
506    )
507}
508
509fn submit(job: Job) {
510    let jobs = JOBS.get_or_init(|| {
511        let (tx, rx) = mpsc::channel::<Job>();
512        std::thread::Builder::new()
513            .name("sk-resample".into())
514            .spawn(move || {
515                while let Ok(job) = rx.recv() {
516                    let made = make(&job.source, job.key.1, job.target);
517                    let landed = (job.key, Arc::downgrade(&job.source), made);
518                    drop(job.source);
519                    DONE.lock().unwrap_or_else(|e| e.into_inner()).push(landed);
520                }
521            })
522            .expect("spawn the resampling thread");
523        Mutex::new(tx)
524    });
525    let _ = jobs.lock().unwrap_or_else(|e| e.into_inner()).send(job);
526}
527
528/// Once per frame group, from `crate::frame_tick`: installs the resampler, renews [`SYNC_BUDGET`],
529/// takes in landed copies, starts those whose size has held, evicts gone and least recently drawn
530/// copies, and hands the evicted ones back to gpui.
531pub(crate) fn tick(window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
532    if enabled() {
533        gpui::set_image_resampler(resampler);
534    }
535    let landed: Vec<Landed> = std::mem::take(&mut *DONE.lock().unwrap_or_else(|e| e.into_inner()));
536    let now = Instant::now();
537    let (moved, retired) = CACHE.with(|c| {
538        let mut c = c.borrow_mut();
539        c.sync_spent = Duration::ZERO;
540        let mut moved = false;
541        for (key, source, made) in landed {
542            c.in_flight.remove(&key);
543            if let Some(made) = made.filter(|_| source.strong_count() > 0) {
544                let clock = c.clock;
545                insert(&mut c, key, Arc::new(made), source, clock);
546                moved = true;
547            }
548        }
549        let due: Vec<Key> = c
550            .waiting
551            .iter()
552            .filter(|(_, (source, since))| {
553                source.strong_count() == 0 || now.duration_since(*since) >= SETTLE
554            })
555            .map(|(k, _)| *k)
556            .collect();
557        for key in due {
558            let Some((source, _)) = c.waiting.remove(&key) else {
559                continue;
560            };
561            let Some(source) = source.upgrade() else {
562                continue;
563            };
564            if c.copies.contains_key(&key) || c.in_flight.contains(&key) {
565                continue;
566            }
567            let natural = source.size(key.1);
568            let target = (
569                stepped(natural.width.0 as u32, key.2),
570                stepped(natural.height.0 as u32, key.3),
571            );
572            c.in_flight.insert(key);
573            submit(Job {
574                key,
575                source,
576                target,
577            });
578        }
579        let gone: Vec<Key> = c
580            .copies
581            .iter()
582            .filter(|(_, v)| v.source.strong_count() == 0)
583            .map(|(k, _)| *k)
584            .collect();
585        for key in gone {
586            evict(&mut c, key);
587        }
588        while c.bytes > BUDGET_BYTES {
589            let Some(oldest) = c.copies.iter().min_by_key(|(_, v)| v.used).map(|(k, _)| *k) else {
590                break;
591            };
592            evict(&mut c, oldest);
593        }
594        (moved, std::mem::take(&mut c.retired))
595    });
596    HOLD_REPLAYS.with(|h| h.set(moved || !retired.is_empty()));
597    for image in retired {
598        cx.drop_image(image, Some(window));
599    }
600    moved
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606
607    fn checker(w: u32, h: u32) -> Vec<u8> {
608        let mut v = Vec::with_capacity((w * h * 4) as usize);
609        for y in 0..h {
610            for x in 0..w {
611                let c = if (x + y) % 2 == 0 { 255 } else { 0 };
612                v.extend_from_slice(&[c, c, c, 255]);
613            }
614        }
615        v
616    }
617
618    fn image(bytes: Vec<u8>, w: u32, h: u32) -> Arc<RenderImage> {
619        Arc::new(RenderImage::new(vec![image::Frame::new(
620            image::RgbaImage::from_raw(w, h, bytes).unwrap(),
621        )]))
622    }
623
624    fn device(w: i32, h: i32) -> Size<DevicePixels> {
625        Size {
626            width: DevicePixels(w),
627            height: DevicePixels(h),
628        }
629    }
630
631    #[test]
632    fn steps_round_up_by_a_quarter_octave_and_leave_near_sizes_alone() {
633        assert_eq!(step(1.0), 0);
634        assert_eq!(step(2.0), 0);
635        assert_eq!(step(0.8), 0);
636        assert_eq!(step(0.79), -1);
637        assert_eq!(step(0.5), -4);
638        assert_eq!(step(40.0 / 1080.0), -19);
639        for drawn in [40u32, 41, 57, 80, 120, 333] {
640            let s = stepped(1080, step(drawn as f32 / 1080.0));
641            assert!(
642                s >= drawn && s as f32 <= drawn as f32 * 1.19 + 1.0,
643                "{drawn} -> {s}"
644            );
645        }
646        assert_eq!(stepped(1080, 0), 1080);
647        assert_eq!(stepped(3, -40), 1);
648    }
649
650    fn new_frame() {
651        CACHE.with(|c| c.borrow_mut().sync_spent = Duration::ZERO);
652    }
653
654    #[test]
655    fn the_first_copy_is_made_at_once_and_reused() {
656        new_frame();
657        let img = image(checker(200, 200), 200, 200);
658        assert!(resampler(&img, 0, device(200, 200)).is_none());
659        assert!(
660            resampler(&img, 0, device(180, 180)).is_none(),
661            "0.9 of its size: drawn as it is"
662        );
663        assert!(
664            resampler(&img, 0, device(400, 400)).is_none(),
665            "drawn larger: as it is"
666        );
667        let first = resampler(&img, 0, device(40, 40))
668            .expect("a small image's first copy is made on the spot");
669        let size = first.size(0);
670        assert!(size.width.0 >= 40 && size.width.0 <= 48, "{size:?}");
671        assert!(
672            Arc::ptr_eq(&first, &resampler(&img, 0, device(41, 41)).unwrap()),
673            "same step, same copy"
674        );
675
676        let other = resampler(&img, 0, device(100, 100)).unwrap();
677        assert!(Arc::ptr_eq(&first, &other));
678        let key = (img.id, 0, step(0.5), step(0.5));
679        assert!(CACHE.with(|c| c.borrow().waiting.contains_key(&key)));
680        let since = CACHE.with(|c| c.borrow().waiting[&key].1);
681        let _ = resampler(&img, 0, device(40, 40));
682        let _ = resampler(&img, 0, device(100, 100));
683        assert_eq!(CACHE.with(|c| c.borrow().waiting[&key].1), since);
684
685        new_frame();
686        let wide = image(checker(400, 2), 400, 2);
687        let copy = resampler(&wide, 0, device(40, 2)).unwrap();
688        assert_eq!(
689            (copy.size(0).height.0, copy.size(0).width.0 >= 40),
690            (2, true)
691        );
692
693        forget(&img);
694        assert!(CACHE.with(|c| c.borrow().copies.keys().all(|k| k.0 != img.id)));
695        assert!(CACHE.with(|c| c.borrow().retired.iter().any(|r| Arc::ptr_eq(r, &first))));
696    }
697
698    #[test]
699    fn past_the_frames_budget_a_first_copy_is_made_off_the_painting_thread() {
700        CACHE.with(|c| c.borrow_mut().sync_spent = SYNC_BUDGET);
701        let img = image(checker(200, 200), 200, 200);
702        assert!(resampler(&img, 0, device(40, 40)).is_none());
703        assert!(CACHE.with(|c| c.borrow().in_flight.iter().any(|k| k.0 == img.id)));
704    }
705
706    #[test]
707    fn a_large_image_is_resampled_off_the_painting_thread() {
708        let img = image(checker(1200, 1200), 1200, 1200);
709        assert!(
710            resampler(&img, 0, device(60, 60)).is_none(),
711            "drawn as it is until the copy lands"
712        );
713        assert!(
714            resampler(&img, 0, device(60, 60)).is_none(),
715            "and asked for once"
716        );
717        assert_eq!(CACHE.with(|c| c.borrow().in_flight.len()), 1);
718        let deadline = Instant::now() + Duration::from_secs(20);
719        let landed = loop {
720            let mut done = DONE.lock().unwrap();
721            if let Some(i) = done.iter().position(|l| l.0 .0 == img.id) {
722                break done.remove(i);
723            }
724            drop(done);
725            assert!(Instant::now() < deadline, "the copy never landed");
726            std::thread::sleep(Duration::from_millis(5));
727        };
728        let (key, source, made) = landed;
729        let made = made.expect("a copy");
730        assert_eq!(made.size(0).width.0, stepped(1200, step(0.05)) as i32);
731        CACHE.with(|c| {
732            let mut c = c.borrow_mut();
733            c.in_flight.remove(&key);
734            insert(&mut c, key, Arc::new(made), source, 0);
735        });
736        assert!(resampler(&img, 0, device(60, 60)).is_some());
737    }
738
739    fn settled() -> Instant {
740        Instant::now() + REDUCE_AFTER + Duration::from_millis(50)
741    }
742
743    #[test]
744    fn a_copy_stands_in_for_a_decode_drawn_only_small() {
745        new_frame();
746        let img = image(checker(600, 600), 600, 600);
747        let copy = resampler(&img, 0, device(40, 40)).expect("the first copy, on the spot");
748        assert_eq!(
749            copy.natural_size(0),
750            img.size(0),
751            "a copy carries the picture's size"
752        );
753        assert_eq!(
754            reduced_copy(&img, Instant::now()).err(),
755            Some(KeepFull::Young),
756            "drawn for less than REDUCE_AFTER: the decode stays"
757        );
758
759        let reduced =
760            reduced_copy(&img, settled()).expect("drawn only at 40 px: the copy stands in");
761        assert!(Arc::ptr_eq(&reduced, &copy));
762        assert!(reduced.is_reduced());
763        // Out of the copy cache and NOT retired: its atlas tile is what is drawn from next.
764        CACHE.with(|c| {
765            let c = c.borrow();
766            assert!(c.copies.values().all(|v| !Arc::ptr_eq(&v.image, &reduced)));
767            assert!(c.retired.iter().all(|r| !Arc::ptr_eq(r, &reduced)));
768        });
769
770        let _ = take_wanted_full();
771        assert!(resampler(&reduced, 0, device(40, 40)).is_none());
772        assert!(take_wanted_full().is_empty());
773        assert_eq!(
774            reduced_copy(&reduced, settled()).err(),
775            Some(KeepFull::NotStill)
776        );
777        let _ = resampler(&reduced, 0, device(300, 300));
778        assert!(take_wanted_full().contains(&reduced.id));
779    }
780
781    #[test]
782    fn a_decode_stays_when_a_copy_would_save_little() {
783        new_frame();
784        let big = image(checker(600, 600), 600, 600);
785        let _ = resampler(&big, 0, device(40, 40));
786        let _ = resampler(&big, 0, device(400, 400));
787        assert_eq!(reduced_copy(&big, settled()).err(), Some(KeepFull::NoCopy));
788        new_frame();
789        let small = image(checker(120, 120), 120, 120);
790        assert!(resampler(&small, 0, device(20, 20)).is_some());
791        assert_eq!(
792            reduced_copy(&small, settled()).err(),
793            Some(KeepFull::SmallSaving)
794        );
795        let unseen = image(checker(600, 600), 600, 600);
796        assert_eq!(
797            reduced_copy(&unseen, settled()).err(),
798            Some(KeepFull::Undrawn)
799        );
800    }
801}