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                    sk_runtime::frames::wake();
521                }
522            })
523            .expect("spawn the resampling thread");
524        Mutex::new(tx)
525    });
526    let _ = jobs.lock().unwrap_or_else(|e| e.into_inner()).send(job);
527}
528
529/// Once per frame group, from `crate::frame_tick`: installs the resampler, renews [`SYNC_BUDGET`],
530/// takes in landed copies, starts those whose size has held, evicts gone and least recently drawn
531/// copies, and hands the evicted ones back to gpui.
532pub(crate) fn tick(window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
533    if enabled() {
534        gpui::set_image_resampler(resampler);
535    }
536    let landed: Vec<Landed> = std::mem::take(&mut *DONE.lock().unwrap_or_else(|e| e.into_inner()));
537    let now = Instant::now();
538    let (moved, retired) = CACHE.with(|c| {
539        let mut c = c.borrow_mut();
540        c.sync_spent = Duration::ZERO;
541        let mut moved = false;
542        for (key, source, made) in landed {
543            c.in_flight.remove(&key);
544            if let Some(made) = made.filter(|_| source.strong_count() > 0) {
545                let clock = c.clock;
546                insert(&mut c, key, Arc::new(made), source, clock);
547                moved = true;
548            }
549        }
550        let due: Vec<Key> = c
551            .waiting
552            .iter()
553            .filter(|(_, (source, since))| {
554                source.strong_count() == 0 || now.duration_since(*since) >= SETTLE
555            })
556            .map(|(k, _)| *k)
557            .collect();
558        for key in due {
559            let Some((source, _)) = c.waiting.remove(&key) else {
560                continue;
561            };
562            let Some(source) = source.upgrade() else {
563                continue;
564            };
565            if c.copies.contains_key(&key) || c.in_flight.contains(&key) {
566                continue;
567            }
568            let natural = source.size(key.1);
569            let target = (
570                stepped(natural.width.0 as u32, key.2),
571                stepped(natural.height.0 as u32, key.3),
572            );
573            c.in_flight.insert(key);
574            submit(Job {
575                key,
576                source,
577                target,
578            });
579        }
580        if let Some(since) = c.waiting.values().map(|(_, since)| *since).min() {
581            sk_runtime::frames::wake_at(since + SETTLE);
582        }
583        let gone: Vec<Key> = c
584            .copies
585            .iter()
586            .filter(|(_, v)| v.source.strong_count() == 0)
587            .map(|(k, _)| *k)
588            .collect();
589        for key in gone {
590            evict(&mut c, key);
591        }
592        while c.bytes > BUDGET_BYTES {
593            let Some(oldest) = c.copies.iter().min_by_key(|(_, v)| v.used).map(|(k, _)| *k) else {
594                break;
595            };
596            evict(&mut c, oldest);
597        }
598        (moved, std::mem::take(&mut c.retired))
599    });
600    HOLD_REPLAYS.with(|h| h.set(moved || !retired.is_empty()));
601    for image in retired {
602        cx.drop_image(image, Some(window));
603    }
604    moved
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    fn checker(w: u32, h: u32) -> Vec<u8> {
612        let mut v = Vec::with_capacity((w * h * 4) as usize);
613        for y in 0..h {
614            for x in 0..w {
615                let c = if (x + y) % 2 == 0 { 255 } else { 0 };
616                v.extend_from_slice(&[c, c, c, 255]);
617            }
618        }
619        v
620    }
621
622    fn image(bytes: Vec<u8>, w: u32, h: u32) -> Arc<RenderImage> {
623        Arc::new(RenderImage::new(vec![image::Frame::new(
624            image::RgbaImage::from_raw(w, h, bytes).unwrap(),
625        )]))
626    }
627
628    fn device(w: i32, h: i32) -> Size<DevicePixels> {
629        Size {
630            width: DevicePixels(w),
631            height: DevicePixels(h),
632        }
633    }
634
635    #[test]
636    fn steps_round_up_by_a_quarter_octave_and_leave_near_sizes_alone() {
637        assert_eq!(step(1.0), 0);
638        assert_eq!(step(2.0), 0);
639        assert_eq!(step(0.8), 0);
640        assert_eq!(step(0.79), -1);
641        assert_eq!(step(0.5), -4);
642        assert_eq!(step(40.0 / 1080.0), -19);
643        for drawn in [40u32, 41, 57, 80, 120, 333] {
644            let s = stepped(1080, step(drawn as f32 / 1080.0));
645            assert!(
646                s >= drawn && s as f32 <= drawn as f32 * 1.19 + 1.0,
647                "{drawn} -> {s}"
648            );
649        }
650        assert_eq!(stepped(1080, 0), 1080);
651        assert_eq!(stepped(3, -40), 1);
652    }
653
654    fn new_frame() {
655        CACHE.with(|c| c.borrow_mut().sync_spent = Duration::ZERO);
656    }
657
658    #[test]
659    fn the_first_copy_is_made_at_once_and_reused() {
660        new_frame();
661        let img = image(checker(200, 200), 200, 200);
662        assert!(resampler(&img, 0, device(200, 200)).is_none());
663        assert!(
664            resampler(&img, 0, device(180, 180)).is_none(),
665            "0.9 of its size: drawn as it is"
666        );
667        assert!(
668            resampler(&img, 0, device(400, 400)).is_none(),
669            "drawn larger: as it is"
670        );
671        let first = resampler(&img, 0, device(40, 40))
672            .expect("a small image's first copy is made on the spot");
673        let size = first.size(0);
674        assert!(size.width.0 >= 40 && size.width.0 <= 48, "{size:?}");
675        assert!(
676            Arc::ptr_eq(&first, &resampler(&img, 0, device(41, 41)).unwrap()),
677            "same step, same copy"
678        );
679
680        let other = resampler(&img, 0, device(100, 100)).unwrap();
681        assert!(Arc::ptr_eq(&first, &other));
682        let key = (img.id, 0, step(0.5), step(0.5));
683        assert!(CACHE.with(|c| c.borrow().waiting.contains_key(&key)));
684        let since = CACHE.with(|c| c.borrow().waiting[&key].1);
685        let _ = resampler(&img, 0, device(40, 40));
686        let _ = resampler(&img, 0, device(100, 100));
687        assert_eq!(CACHE.with(|c| c.borrow().waiting[&key].1), since);
688
689        new_frame();
690        let wide = image(checker(400, 2), 400, 2);
691        let copy = resampler(&wide, 0, device(40, 2)).unwrap();
692        assert_eq!(
693            (copy.size(0).height.0, copy.size(0).width.0 >= 40),
694            (2, true)
695        );
696
697        forget(&img);
698        assert!(CACHE.with(|c| c.borrow().copies.keys().all(|k| k.0 != img.id)));
699        assert!(CACHE.with(|c| c.borrow().retired.iter().any(|r| Arc::ptr_eq(r, &first))));
700    }
701
702    #[test]
703    fn past_the_frames_budget_a_first_copy_is_made_off_the_painting_thread() {
704        CACHE.with(|c| c.borrow_mut().sync_spent = SYNC_BUDGET);
705        let img = image(checker(200, 200), 200, 200);
706        assert!(resampler(&img, 0, device(40, 40)).is_none());
707        assert!(CACHE.with(|c| c.borrow().in_flight.iter().any(|k| k.0 == img.id)));
708    }
709
710    #[test]
711    fn a_large_image_is_resampled_off_the_painting_thread() {
712        let img = image(checker(1200, 1200), 1200, 1200);
713        assert!(
714            resampler(&img, 0, device(60, 60)).is_none(),
715            "drawn as it is until the copy lands"
716        );
717        assert!(
718            resampler(&img, 0, device(60, 60)).is_none(),
719            "and asked for once"
720        );
721        assert_eq!(CACHE.with(|c| c.borrow().in_flight.len()), 1);
722        let deadline = Instant::now() + Duration::from_secs(20);
723        let landed = loop {
724            let mut done = DONE.lock().unwrap();
725            if let Some(i) = done.iter().position(|l| l.0 .0 == img.id) {
726                break done.remove(i);
727            }
728            drop(done);
729            assert!(Instant::now() < deadline, "the copy never landed");
730            std::thread::sleep(Duration::from_millis(5));
731        };
732        let (key, source, made) = landed;
733        let made = made.expect("a copy");
734        assert_eq!(made.size(0).width.0, stepped(1200, step(0.05)) as i32);
735        CACHE.with(|c| {
736            let mut c = c.borrow_mut();
737            c.in_flight.remove(&key);
738            insert(&mut c, key, Arc::new(made), source, 0);
739        });
740        assert!(resampler(&img, 0, device(60, 60)).is_some());
741    }
742
743    fn settled() -> Instant {
744        Instant::now() + REDUCE_AFTER + Duration::from_millis(50)
745    }
746
747    #[test]
748    fn a_copy_stands_in_for_a_decode_drawn_only_small() {
749        new_frame();
750        let img = image(checker(600, 600), 600, 600);
751        let copy = resampler(&img, 0, device(40, 40)).expect("the first copy, on the spot");
752        assert_eq!(
753            copy.natural_size(0),
754            img.size(0),
755            "a copy carries the picture's size"
756        );
757        assert_eq!(
758            reduced_copy(&img, Instant::now()).err(),
759            Some(KeepFull::Young),
760            "drawn for less than REDUCE_AFTER: the decode stays"
761        );
762
763        let reduced =
764            reduced_copy(&img, settled()).expect("drawn only at 40 px: the copy stands in");
765        assert!(Arc::ptr_eq(&reduced, &copy));
766        assert!(reduced.is_reduced());
767        // Out of the copy cache and NOT retired: its atlas tile is what is drawn from next.
768        CACHE.with(|c| {
769            let c = c.borrow();
770            assert!(c.copies.values().all(|v| !Arc::ptr_eq(&v.image, &reduced)));
771            assert!(c.retired.iter().all(|r| !Arc::ptr_eq(r, &reduced)));
772        });
773
774        let _ = take_wanted_full();
775        assert!(resampler(&reduced, 0, device(40, 40)).is_none());
776        assert!(take_wanted_full().is_empty());
777        assert_eq!(
778            reduced_copy(&reduced, settled()).err(),
779            Some(KeepFull::NotStill)
780        );
781        let _ = resampler(&reduced, 0, device(300, 300));
782        assert!(take_wanted_full().contains(&reduced.id));
783    }
784
785    #[test]
786    fn a_decode_stays_when_a_copy_would_save_little() {
787        new_frame();
788        let big = image(checker(600, 600), 600, 600);
789        let _ = resampler(&big, 0, device(40, 40));
790        let _ = resampler(&big, 0, device(400, 400));
791        assert_eq!(reduced_copy(&big, settled()).err(), Some(KeepFull::NoCopy));
792        new_frame();
793        let small = image(checker(120, 120), 120, 120);
794        assert!(resampler(&small, 0, device(20, 20)).is_some());
795        assert_eq!(
796            reduced_copy(&small, settled()).err(),
797            Some(KeepFull::SmallSaving)
798        );
799        let unseen = image(checker(600, 600), 600, 600);
800        assert_eq!(
801            reduced_copy(&unseen, settled()).err(),
802            Some(KeepFull::Undrawn)
803        );
804    }
805}