nsh-core 0.8.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Decoded images at display size (L4 of `docs/dev/image-loading-design.md`)
//! over the shared [`Loader`]: a backend gives [`Images`] its decoder (bytes
//! to its texture type at a size) and asks for images at the size a view
//! shows them.
//!
//! An image is decoded at the [`bucket`] covering what its view needs
//! ([`Want`]), never above its natural size (an SVG: within
//! [`crate::svg::MAX_SIDE`]), and kept by (source key, bucket, frames)
//! ([`Key`]): views of similar sizes share an entry, one that grows asks
//! for the next bucket. One decode per key runs at a time; the natural sizes
//! read from the bytes' headers are kept while a decoded entry remains, so
//! cached images are answered without reading anything. Evicting the last
//! entry of a source releases its natural-size metadata too.

use std::{
    collections::HashMap,
    sync::{
        Arc, Mutex, MutexGuard,
        atomic::{AtomicU64, Ordering},
    },
};

use super::{
    Budget, ImageData, Lease, MemoryCache, Natural,
    loader::{Context, Loader, Location, Priority, Progress, Ticket, loader},
    memory::{bucket, wanted},
};
use crate::{
    ResizeMode,
    geometry::{Points, Size},
};

/// The longest side an SVG is drawn at (`svg::MAX_SIDE`).
const VECTOR_SIDE: u32 = 8192;

/// Which frames of an animated image a decode keeps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Frames {
    /// Every frame (an image view plays it).
    #[default]
    All,
    /// The first (a canvas draws a bitmap).
    First,
}

/// The size a view shows an image at.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Want {
    /// The view's box; empty: the image's natural size.
    pub size: Size<Points>,
    /// Device pixels per point.
    pub scale: f32,
    /// How the box fits it.
    pub mode: ResizeMode,
}

impl Want {
    /// The natural size at `scale` device pixels per point.
    pub fn natural(scale: f32) -> Self {
        Want {
            size: Size::default(),
            scale,
            mode: ResizeMode::Center,
        }
    }

    /// The longest side, in pixels, to decode an image of `natural` size
    /// at (`declared`: the size its source gives, in points).
    pub fn longest(&self, natural: Natural, density: f32, declared: Option<Size<Points>>) -> u32 {
        let points = declared
            .filter(|s| s.width.0 > 0.0 && s.height.0 > 0.0)
            .unwrap_or_else(|| natural.points(density));
        let mut px = (wanted(points, self.size, self.mode) as f32 * self.scale).ceil() as u32;
        match natural {
            Natural::Pixels(w, h) => bucket(w.max(h), px),
            Natural::Vector(points) => {
                if px == 0 {
                    px = (points.width.0.max(points.height.0) * self.scale).ceil() as u32;
                }
                bucket(VECTOR_SIDE, px.max(1))
            }
        }
    }
}

/// What a decode makes: the image at a size.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Target {
    /// The image's own size (`None`: its header did not say; decode it at
    /// its natural size).
    pub natural: Option<Natural>,
    /// The longest side to decode at, in pixels (at most the natural one).
    pub longest: u32,
    /// The frames to keep.
    pub frames: Frames,
}

/// A decoded image's entry key.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Key {
    /// The source key ([`Location::key`]).
    pub source: String,
    /// Its bucket ([`Target::longest`]; 0: natural, its size unknown).
    pub longest: u32,
    /// The frames kept.
    pub frames: Frames,
}

/// A decoded image.
#[derive(Clone)]
pub struct Decoded<V> {
    /// The backend's picture of it.
    pub value: V,
    /// Its own size, whatever size it was decoded at.
    pub natural: Natural,
}

/// A request for an image.
#[derive(Clone)]
pub struct Request {
    /// Where its bytes are.
    pub location: Location,
    /// What the load goes through.
    pub context: Context,
    /// The size its source declares, in points (a bundled asset's).
    pub declared: Option<Size<Points>>,
    /// The size its view shows it at.
    pub want: Want,
    /// The frames its view needs.
    pub frames: Frames,
    /// Where it goes in the queues.
    pub priority: Priority,
    /// Hears the download's progress.
    pub progress: Option<Progress>,
}

/// Decodes `bytes` at `target` into a backend's picture, its natural size
/// and its cost in bytes (pixels, GPU copies).
pub type Decoder<V> =
    dyn Fn(&ImageData, &Target) -> Result<(V, Natural, usize), String> + Send + Sync;

/// Called with an image and the lease that keeps it, or why there is none.
pub type Done<V> = Box<dyn FnOnce(Result<(Decoded<V>, Lease), String>) + Send>;

/// A backend's decoded images: decodes by [`Key`], in one budget.
pub struct Images<V> {
    memory: MemoryCache<Key, Decoded<V>>,
    shared: Arc<Shared<V>>,
    loader: &'static Loader,
}

impl<V> Clone for Images<V> {
    fn clone(&self) -> Self {
        Images {
            memory: self.memory.clone(),
            shared: self.shared.clone(),
            loader: self.loader,
        }
    }
}

struct Shared<V> {
    decoder: Box<Decoder<V>>,
    /// Decodes running, by key: who waits for them.
    pending: Mutex<HashMap<Key, Pending<V>>>,
    /// Natural sizes and the number of decoded entries that keep them.
    naturals: Arc<Mutex<HashMap<String, (Natural, usize)>>>,
    waiters: AtomicU64,
}

struct Pending<V> {
    waiters: Vec<(u64, Done<V>)>,
    ticket: Ticket,
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}

/// A request's stages: the read, then its place among a decode's waiters.
#[derive(Default)]
struct Stage {
    cancelled: bool,
    read: Option<Ticket>,
    decode: Option<Key>,
}

impl<V: Clone + Send + Sync + 'static> Images<V> {
    /// Images decoded by `decoder`, kept in `budget`.
    pub fn new(
        budget: &Arc<Budget>,
        decoder: impl Fn(&ImageData, &Target) -> Result<(V, Natural, usize), String>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        Self::with_on_evict(budget, decoder, |_| {})
    }

    /// [`Images::new`], calling `on_evict` with each picture dropped (to
    /// release its GPU copy where it lives).
    pub fn with_on_evict(
        budget: &Arc<Budget>,
        decoder: impl Fn(&ImageData, &Target) -> Result<(V, Natural, usize), String>
        + Send
        + Sync
        + 'static,
        on_evict: impl Fn(&V) + Send + Sync + 'static,
    ) -> Self {
        let naturals = Arc::new(Mutex::new(HashMap::<String, (Natural, usize)>::new()));
        let retained = naturals.clone();
        let memory = MemoryCache::with_on_evict(budget, move |key: &Key, d: &Decoded<V>| {
            {
                let mut naturals = lock(&retained);
                if let Some((_, entries)) = naturals.get_mut(&key.source) {
                    *entries -= 1;
                    if *entries == 0 {
                        naturals.remove(&key.source);
                    }
                }
            }
            on_evict(&d.value);
        });
        Images {
            loader: loader(),
            memory,
            shared: Arc::new(Shared {
                decoder: Box::new(decoder),
                pending: Mutex::default(),
                naturals,
                waiters: AtomicU64::new(0),
            }),
        }
    }

    /// These images, loaded by `loader` (tests: a loader of their own).
    #[cfg(test)]
    pub(crate) fn on(mut self, loader: &'static Loader) -> Self {
        self.loader = loader;
        self
    }

    /// The decoded entries.
    pub fn memory(&self) -> &MemoryCache<Key, Decoded<V>> {
        &self.memory
    }

    /// The natural size of `source` (a source key), while a decoded entry remains.
    pub fn natural(&self, source: &str) -> Option<Natural> {
        lock(&self.shared.naturals)
            .get(source)
            .map(|(natural, _)| *natural)
    }

    /// The key `request` is decoded by, once its natural size is known.
    fn key(&self, request: &Request, source: &str, natural: Option<Natural>) -> (Key, Target) {
        let longest = natural.map_or(0, |n| {
            request
                .want
                .longest(n, request.location.density(), request.declared)
        });
        let target = Target {
            natural,
            longest,
            frames: request.frames,
        };
        let key = Key {
            source: source.to_owned(),
            longest,
            frames: request.frames,
        };
        (key, target)
    }

    /// The key `request`'s image, of natural size `natural`, is kept under
    /// (to count what it costs elsewhere: [`MemoryCache::add_cost`]).
    pub fn key_of(&self, request: &Request, natural: Natural) -> Key {
        self.key(request, &request.location.key(), Some(natural)).0
    }

    /// The decoded image `request` asks for, when it is in memory.
    pub fn cached(&self, request: &Request) -> Option<(Decoded<V>, Lease)> {
        let source = request.location.key();
        let natural = self.natural(&source)?;
        self.memory
            .get(&self.key(request, &source, Some(natural)).0)
    }

    /// Loads `request`'s image and calls `done` with it: here and now when
    /// it is in memory, else on a loader thread. Dropping the ticket gives
    /// up waiting (and cancels the load when nobody else waits).
    pub fn load(&self, request: Request, done: Done<V>) -> Ticket {
        if let Some(hit) = self.cached(&request) {
            done(Ok(hit));
            return Ticket::done();
        }
        let id = self.shared.waiters.fetch_add(1, Ordering::Relaxed) + 1;
        let stage = Arc::new(Mutex::new(Stage::default()));
        let images = self.clone();
        let decode_stage = stage.clone();
        let source = request.location.key();
        let priority = request.priority;
        let read_request = request.clone();
        let read = self.loader.read(
            request.location,
            &request.context,
            priority,
            request.progress,
            Box::new(move |bytes| match bytes {
                Ok(bytes) => images.decode(&read_request, source, bytes, id, &decode_stage, done),
                Err(error) => done(Err(error)),
            }),
        );
        let reprioritize = read.reprioritize.clone();
        {
            let mut s = lock(&stage);
            if s.decode.is_none() {
                s.read = Some(read);
            }
        }
        let images = self.clone();
        Ticket::new(move || images.give_up(&stage, id), reprioritize)
    }

    /// The bytes of `request` arrived: decodes them, or waits for the decode
    /// of the same key running.
    fn decode(
        &self,
        request: &Request,
        source: String,
        bytes: ImageData,
        id: u64,
        stage: &Mutex<Stage>,
        done: Done<V>,
    ) {
        let natural = self
            .natural(&source)
            .or_else(|| bytes.rgba().map(|(w, h, _)| Natural::Pixels(w, h)))
            .or_else(|| Natural::of(&bytes));
        let (key, target) = self.key(request, &source, natural);
        // Lock order is strictly stage -> pending -> loader.decodes so a
        // concurrent give_up cannot slip between recording s.decode and
        // inserting the waiter + decode ticket into pending.
        let (read, hit) = {
            let mut s = lock(stage);
            if s.cancelled {
                return;
            }
            let read = s.read.take();
            let mut pending = lock(&self.shared.pending);
            if let Some(hit) = self.memory.get(&key) {
                (read, Some((done, hit)))
            } else {
                s.decode = Some(key.clone());
                if let Some(p) = pending.get_mut(&key) {
                    p.waiters.push((id, done));
                } else {
                    let images = self.clone();
                    let job_key = key.clone();
                    let transient = bytes.rgba().is_some();
                    let ticket = self.loader.decode(request.priority, move || {
                        let result = (images.shared.decoder)(&bytes, &target);
                        images.decoded(job_key, result, transient);
                    });
                    pending.insert(
                        key,
                        Pending {
                            waiters: vec![(id, done)],
                            ticket,
                        },
                    );
                }
                (read, None)
            }
        };
        drop(read);
        if let Some((done, hit)) = hit {
            done(Ok(hit));
        }
    }

    /// A decode ended: keeps the image and hands it to who waits.
    fn decoded(&self, key: Key, result: Result<(V, Natural, usize), String>, transient: bool) {
        let take = |key: &Key| {
            let entry = lock(&self.shared.pending).remove(key);
            entry.map(|p| p.waiters).unwrap_or_default()
        };
        match result {
            Ok((value, natural, cost)) => {
                let decoded = Decoded { value, natural };
                // Register before inserting: insertion can evict another bucket
                // of this source (or replace this key). Its callback releases
                // only that entry's hold, including concurrent replacements.
                {
                    let mut naturals = lock(&self.shared.naturals);
                    let entry = naturals.entry(key.source.clone()).or_insert((natural, 0));
                    entry.0 = natural;
                    entry.1 += 1;
                }
                let lease = if transient {
                    self.memory
                        .insert_transient(key.clone(), decoded.clone(), cost)
                } else {
                    self.memory.insert(key.clone(), decoded.clone(), cost)
                };
                for (_, done) in take(&key) {
                    done(Ok((decoded.clone(), lease.clone())));
                }
            }
            Err(error) => {
                for (_, done) in take(&key) {
                    done(Err(error.clone()));
                }
            }
        }
    }

    /// Request `id` gave up: its read, or its place among a decode's
    /// waiters, goes (and the decode, when nobody else waits for it).
    fn give_up(&self, stage: &Mutex<Stage>, id: u64) {
        let (read, key) = {
            let mut s = lock(stage);
            s.cancelled = true;
            (s.read.take(), s.decode.take())
        };
        drop(read);
        let Some(key) = key else { return };
        let ticket = {
            let mut pending = lock(&self.shared.pending);
            let Some(p) = pending.get_mut(&key) else {
                return;
            };
            p.waiters.retain(|(w, _)| *w != id);
            if !p.waiters.is_empty() {
                return;
            }
            pending.remove(&key).map(|p| p.ticket)
        };
        drop(ticket);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key(source: &str, longest: u32) -> Key {
        Key {
            source: source.into(),
            longest,
            frames: Frames::All,
        }
    }

    #[test]
    fn unique_sources_release_metadata_but_keep_active_images() {
        let budget = Budget::new(8);
        let images = Images::new(&budget, |_, _| unreachable!());
        let active = key("active", 1);
        images.decoded(active.clone(), Ok((7_u32, Natural::Pixels(1, 1), 4)), false);
        let (_, lease) = images.memory.get(&active).unwrap();
        for i in 0..10_000 {
            let source = format!("inline:{i}");
            images.decoded(key(&source, 1), Ok((i, Natural::Pixels(1, 1), 4)), false);
            assert_eq!(budget.used(), 8);
            assert_eq!(lock(&images.shared.naturals).len(), 2);
        }
        assert_eq!(images.natural("active"), Some(Natural::Pixels(1, 1)));
        assert_eq!(images.memory.get(&active).unwrap().0.value, 7);
        assert_eq!(images.natural("inline:0"), None);
        budget.clear();
        assert_eq!(lock(&images.shared.naturals).len(), 1);
        drop(lease);
        budget.clear();
        assert!(lock(&images.shared.naturals).is_empty());
    }

    #[test]
    fn metadata_lives_until_the_last_bucket_and_replacement_go() {
        let budget = Budget::new(100);
        let evictions = Arc::new(AtomicU64::new(0));
        let heard = evictions.clone();
        let images = Images::with_on_evict(
            &budget,
            |_, _| unreachable!(),
            move |_: &u32| {
                heard.fetch_add(1, Ordering::Relaxed);
            },
        );
        let small = key("photo", 1);
        let large = key("photo", 2);
        let natural = Natural::Pixels(2, 2);
        images.decoded(small.clone(), Ok((1, natural, 4)), false);
        images.decoded(large.clone(), Ok((2, natural, 16)), false);
        images.decoded(small.clone(), Ok((3, natural, 4)), false);
        assert_eq!(lock(&images.shared.naturals)["photo"].1, 2);
        images.memory.remove(&small);
        assert_eq!(images.natural("photo"), Some(natural));
        images.memory.remove(&large);
        assert_eq!(images.natural("photo"), None);
        assert_eq!(evictions.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn failed_decodes_keep_no_metadata_and_successful_ones_report_the_decoder_size() {
        let images = Images::new(&Budget::new(16), |_, _| unreachable!());
        images.decoded(key("bad", 0), Err("invalid pixels".into()), false);
        assert!(lock(&images.shared.naturals).is_empty());
        // Some formats have no header Natural::of can read. The decoder's
        // dimensions must still be remembered while the picture is retained.
        images.decoded(
            key("opaque-header", 0),
            Ok((1_u32, Natural::Pixels(2, 2), 16)),
            false,
        );
        assert_eq!(images.natural("opaque-header"), Some(Natural::Pixels(2, 2)));
    }

    #[test]
    fn rgba_frames_evict_when_unleased_without_displacing_static_images() {
        use std::sync::mpsc;

        let budget = Budget::new(256);
        let (evict_tx, evict_rx) = mpsc::channel();
        let images = Images::with_on_evict(
            &budget,
            |bytes, _| {
                let (w, h, pixels) = bytes.rgba().ok_or_else(|| "expected rgba".to_owned())?;
                Ok((pixels[0], Natural::Pixels(w, h), pixels.len()))
            },
            move |value: &u8| {
                let _ = evict_tx.send(*value);
            },
        );
        for i in 0..4 {
            images.decoded(
                key(&format!("asset:/icon-{i}.png"), 4),
                Ok((i as u8, Natural::Pixels(4, 4), 16)),
                false,
            );
        }
        assert_eq!(budget.used(), 64);

        let context = crate::image::loader::Context::default();
        let mut current: Option<Lease> = None;
        for i in 0u8..64 {
            let src = crate::element::ImageSrc::rgba(4, 4, vec![i; 4 * 4 * 4]);
            let uri: std::sync::Arc<str> = src.uri.to_arc();
            let request = Request {
                location: crate::image::loader::Location::Memory(uri.clone(), src.data.unwrap()),
                context: context.clone(),
                declared: None,
                want: Want::natural(1.0),
                frames: Frames::All,
                priority: crate::image::loader::Priority::Visible,
                progress: None,
            };
            let (tx, rx) = mpsc::channel();
            let _ticket = images.load(
                request,
                Box::new(move |res| {
                    let _ = tx.send(res);
                }),
            );
            let (decoded, lease) = rx.recv().unwrap().unwrap();
            assert_eq!(decoded.value, i);
            assert_eq!(images.natural(&uri), Some(Natural::Pixels(4, 4)));
            current = Some(lease);
            if i > 0 {
                // Wait for the previous frame's worker + view leases to release.
                assert_eq!(
                    evict_rx
                        .recv_timeout(std::time::Duration::from_secs(5))
                        .expect("previous transient RGBA frame should evict"),
                    i - 1
                );
            }
        }
        assert_eq!(budget.used(), 64 + 64);
        drop(current);
        assert_eq!(
            evict_rx
                .recv_timeout(std::time::Duration::from_secs(5))
                .expect("final transient RGBA frame should evict"),
            63
        );
        assert_eq!(budget.used(), 64);
        assert_eq!(lock(&images.shared.naturals).len(), 4);
        for i in 0..4 {
            assert!(
                images
                    .memory
                    .contains(&key(&format!("asset:/icon-{i}.png"), 4))
            );
        }
    }
}