fret-canvas 0.1.0

Canvas and node-graph substrate for interactive Fret tooling.
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
use std::collections::HashMap;
use std::sync::Arc;

use fret_core::{SceneOp, SvgId, UiServices};

use super::CacheStats;

/// Bytes for registering an SVG in retained caches.
///
/// Callers should prefer `Static` or `Bytes(Arc<[u8]>)` so the underlying pointer is stable.
#[derive(Clone)]
pub enum SvgBytes {
    Static(&'static [u8]),
    Bytes(Arc<[u8]>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct SvgCacheKey {
    key: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SvgFingerprint {
    Static { ptr: usize, len: usize },
    Bytes { ptr: usize, len: usize },
}

impl SvgBytes {
    fn fingerprint(&self) -> SvgFingerprint {
        match self {
            SvgBytes::Static(bytes) => SvgFingerprint::Static {
                ptr: bytes.as_ptr() as usize,
                len: bytes.len(),
            },
            SvgBytes::Bytes(bytes) => SvgFingerprint::Bytes {
                ptr: bytes.as_ptr() as usize,
                len: bytes.len(),
            },
        }
    }

    fn bytes(&self) -> &[u8] {
        match self {
            SvgBytes::Static(bytes) => bytes,
            SvgBytes::Bytes(bytes) => bytes,
        }
    }
}

#[derive(Debug, Default)]
struct SvgCacheEntry {
    svg: Option<SvgId>,
    bytes_len: u64,
    fingerprint: Option<SvgFingerprint>,
    last_used_frame: u64,
}

/// A small keyed cache for registered SVG IDs.
///
/// The cache owns the `SvgId`s and must be cleared (or dropped) with access to `UiServices`
/// so resources can be released deterministically.
#[derive(Debug, Default)]
pub struct SvgCache {
    frame: u64,
    bytes_ready: u64,
    entries: HashMap<SvgCacheKey, SvgCacheEntry>,
    id_to_key: HashMap<SvgId, u64>,
    stats: CacheStats,
}

impl SvgCache {
    /// Increments and returns the internal frame counter used for pruning.
    pub fn begin_frame(&mut self) -> u64 {
        self.frame = self.frame.wrapping_add(1);
        self.frame
    }

    pub fn stats(&self) -> CacheStats {
        self.stats
    }

    pub fn reset_stats(&mut self) {
        self.stats = CacheStats::default();
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn bytes_ready(&self) -> u64 {
        self.bytes_ready
    }

    /// Returns a cached SVG ID for `key` if present, updating `last_used_frame`.
    pub fn get(&mut self, key: u64) -> Option<SvgId> {
        self.stats.get_calls = self.stats.get_calls.saturating_add(1);
        let cache_key = SvgCacheKey { key };
        let entry = match self.entries.get_mut(&cache_key) {
            Some(entry) => entry,
            None => {
                self.stats.get_misses = self.stats.get_misses.saturating_add(1);
                return None;
            }
        };
        entry.last_used_frame = self.frame;
        let svg = match entry.svg {
            Some(svg) => svg,
            None => {
                self.stats.get_misses = self.stats.get_misses.saturating_add(1);
                return None;
            }
        };
        self.stats.get_hits = self.stats.get_hits.saturating_add(1);
        Some(svg)
    }

    /// Returns a cached SVG ID for `key` if present, without updating `last_used_frame`.
    pub fn peek(&self, key: u64) -> Option<SvgId> {
        self.entries.get(&SvgCacheKey { key })?.svg
    }

    /// Releases all cached SVG IDs.
    pub fn clear(&mut self, services: &mut dyn UiServices) {
        self.stats.clear_calls = self.stats.clear_calls.saturating_add(1);
        for entry in self.entries.values_mut() {
            if let Some(svg) = entry.svg.take() {
                let _ = services.svg().unregister_svg(svg);
                self.stats.release_clear = self.stats.release_clear.saturating_add(1);
                self.id_to_key.remove(&svg);
            }
        }
        self.entries.clear();
        self.id_to_key.clear();
        self.bytes_ready = 0;
    }

    /// Touch an existing cached SVG ID so it is not pruned.
    pub fn touch_svg(&mut self, svg: SvgId) -> bool {
        let Some(key) = self.id_to_key.get(&svg).copied() else {
            return false;
        };
        let Some(entry) = self.entries.get_mut(&SvgCacheKey { key }) else {
            self.id_to_key.remove(&svg);
            return false;
        };
        entry.last_used_frame = self.frame;
        true
    }

    /// Touch any SVG IDs referenced by `SceneOp::SvgMaskIcon` / `SceneOp::SvgImage` so they are not pruned.
    pub fn touch_svgs_in_scene_ops(&mut self, ops: &[SceneOp]) -> u32 {
        let mut touched: u32 = 0;
        for op in ops {
            let svg = match *op {
                SceneOp::SvgMaskIcon { svg, .. } => svg,
                SceneOp::SvgImage { svg, .. } => svg,
                _ => continue,
            };
            if self.touch_svg(svg) {
                touched = touched.saturating_add(1);
            }
        }
        touched
    }

    pub fn evict(&mut self, services: &mut dyn UiServices, key: u64) -> bool {
        self.stats.evict_calls = self.stats.evict_calls.saturating_add(1);
        let Some(mut entry) = self.entries.remove(&SvgCacheKey { key }) else {
            return false;
        };
        self.bytes_ready = self.bytes_ready.saturating_sub(entry.bytes_len);
        if let Some(svg) = entry.svg.take() {
            let _ = services.svg().unregister_svg(svg);
            self.stats.release_evict = self.stats.release_evict.saturating_add(1);
            self.id_to_key.remove(&svg);
        }
        true
    }

    /// Registers `bytes` as an SVG and caches the resulting `SvgId` by `key`.
    ///
    /// If `bytes` change for the same `key`, the cached `SvgId` is replaced and the previous one
    /// is unregistered immediately.
    pub fn prepare(&mut self, services: &mut dyn UiServices, key: u64, bytes: SvgBytes) -> SvgId {
        self.stats.prepare_calls = self.stats.prepare_calls.saturating_add(1);
        let cache_key = SvgCacheKey { key };
        let entry = self.entries.entry(cache_key).or_default();
        entry.last_used_frame = self.frame;

        let fingerprint = bytes.fingerprint();
        let needs_prepare = entry.svg.is_none() || entry.fingerprint.as_ref() != Some(&fingerprint);
        if needs_prepare {
            let bytes_len = bytes.bytes().len() as u64;
            let svg_id = services.svg().register_svg(bytes.bytes());
            if let Some(old) = entry.svg.replace(svg_id) {
                let _ = services.svg().unregister_svg(old);
                self.stats.release_replaced = self.stats.release_replaced.saturating_add(1);
                self.id_to_key.remove(&old);
            }
            self.id_to_key.insert(svg_id, key);
            self.bytes_ready = self
                .bytes_ready
                .saturating_sub(entry.bytes_len)
                .saturating_add(bytes_len);
            entry.bytes_len = bytes_len;
            entry.fingerprint = Some(fingerprint);
            self.stats.prepare_misses = self.stats.prepare_misses.saturating_add(1);
        } else {
            self.stats.prepare_hits = self.stats.prepare_hits.saturating_add(1);
        }

        entry.svg.unwrap_or_default()
    }

    /// Drops old cache entries and unregisters their SVG IDs.
    pub fn prune(
        &mut self,
        services: &mut dyn UiServices,
        max_age_frames: u64,
        max_entries: usize,
    ) {
        self.prune_with_budget(services, max_age_frames, max_entries, u64::MAX);
    }

    pub fn prune_with_budget(
        &mut self,
        services: &mut dyn UiServices,
        max_age_frames: u64,
        max_entries: usize,
        max_bytes: u64,
    ) {
        self.stats.prune_calls = self.stats.prune_calls.saturating_add(1);
        let now = self.frame;

        let mut removed_ids: Vec<SvgId> = Vec::new();
        self.entries.retain(|_, entry| {
            let keep = now.saturating_sub(entry.last_used_frame) <= max_age_frames;
            if !keep {
                if let Some(svg) = entry.svg.take() {
                    let _ = services.svg().unregister_svg(svg);
                    self.stats.release_prune_age = self.stats.release_prune_age.saturating_add(1);
                    removed_ids.push(svg);
                }
                self.bytes_ready = self.bytes_ready.saturating_sub(entry.bytes_len);
            }
            keep
        });
        for id in removed_ids {
            self.id_to_key.remove(&id);
        }

        if max_entries == 0 || max_bytes == 0 {
            self.clear(services);
            return;
        }

        if self.entries.len() <= max_entries && self.bytes_ready <= max_bytes {
            return;
        }

        let mut candidates: Vec<(u64, u64)> = self
            .entries
            .iter()
            .map(|(k, v)| (v.last_used_frame, k.key))
            .collect();
        candidates.sort_by_key(|(last_used, _)| *last_used);

        for (_, key) in candidates {
            if self.entries.len() <= max_entries && self.bytes_ready <= max_bytes {
                break;
            }
            if let Some(mut entry) = self.entries.remove(&SvgCacheKey { key }) {
                self.bytes_ready = self.bytes_ready.saturating_sub(entry.bytes_len);
                if let Some(svg) = entry.svg.take() {
                    let _ = services.svg().unregister_svg(svg);
                    self.stats.release_prune_budget =
                        self.stats.release_prune_budget.saturating_add(1);
                    self.id_to_key.remove(&svg);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fret_core::{
        PathCommand, PathConstraints, PathId, PathMetrics, PathService, PathStyle, Px, Size,
        TextBlobId, TextConstraints, TextInput, TextMetrics, TextService,
    };

    #[derive(Default)]
    struct FakeServices {
        svg_register_calls: u64,
        svg_unregister_calls: u64,
    }

    impl TextService for FakeServices {
        fn prepare(
            &mut self,
            _input: &TextInput,
            _constraints: TextConstraints,
        ) -> (TextBlobId, TextMetrics) {
            (
                TextBlobId::default(),
                TextMetrics {
                    size: Size::default(),
                    baseline: Px(0.0),
                },
            )
        }

        fn release(&mut self, _blob: TextBlobId) {}
    }

    impl PathService for FakeServices {
        fn prepare(
            &mut self,
            _commands: &[PathCommand],
            _style: PathStyle,
            _constraints: PathConstraints,
        ) -> (PathId, PathMetrics) {
            (PathId::default(), PathMetrics::default())
        }

        fn release(&mut self, _path: PathId) {}
    }

    impl fret_core::SvgService for FakeServices {
        fn register_svg(&mut self, _bytes: &[u8]) -> SvgId {
            self.svg_register_calls += 1;
            SvgId::default()
        }

        fn unregister_svg(&mut self, _svg: SvgId) -> bool {
            self.svg_unregister_calls += 1;
            true
        }
    }

    impl fret_core::MaterialService for FakeServices {
        fn register_material(
            &mut self,
            _desc: fret_core::MaterialDescriptor,
        ) -> Result<fret_core::MaterialId, fret_core::MaterialRegistrationError> {
            Err(fret_core::MaterialRegistrationError::Unsupported)
        }

        fn unregister_material(&mut self, _id: fret_core::MaterialId) -> bool {
            true
        }
    }

    #[test]
    fn prepare_hits_cache_for_same_key_and_fingerprint() {
        let mut cache = SvgCache::default();
        let mut services = FakeServices::default();
        cache.begin_frame();

        let bytes: Arc<[u8]> = Arc::from(&b"<svg/>"[..]);
        let a = cache.prepare(&mut services, 1, SvgBytes::Bytes(bytes.clone()));
        let b = cache.prepare(&mut services, 1, SvgBytes::Bytes(bytes));

        let _ = (a, b);
        assert_eq!(services.svg_register_calls, 1);
        assert_eq!(services.svg_unregister_calls, 0);
        assert_eq!(cache.stats().prepare_hits, 1);
        assert_eq!(cache.stats().prepare_misses, 1);
    }

    #[test]
    fn prepare_replaces_when_bytes_change_for_same_key() {
        let mut cache = SvgCache::default();
        let mut services = FakeServices::default();
        cache.begin_frame();

        let a = cache.prepare(&mut services, 1, SvgBytes::Static(b"<svg/>"));
        let b = cache.prepare(&mut services, 1, SvgBytes::Static(b"<svg2/>"));

        let _ = (a, b);
        assert_eq!(services.svg_register_calls, 2);
        assert_eq!(services.svg_unregister_calls, 1);
    }

    #[test]
    fn prune_evicts_by_age_and_budget() {
        let mut cache = SvgCache::default();
        let mut services = FakeServices::default();

        cache.begin_frame();
        cache.prepare(&mut services, 1, SvgBytes::Static(b"<svg/>"));
        cache.begin_frame();
        cache.prepare(&mut services, 2, SvgBytes::Static(b"<svg/>"));
        cache.begin_frame();

        cache.prune(&mut services, 1, 99);
        assert_eq!(services.svg_unregister_calls, 1);

        cache.prepare(&mut services, 3, SvgBytes::Static(b"<svg/>"));
        cache.prune(&mut services, 99, 1);
        assert!(services.svg_unregister_calls >= 2);
    }

    #[test]
    fn touch_svg_prevents_prune_age_release() {
        let mut cache = SvgCache::default();
        let mut services = FakeServices::default();

        cache.begin_frame(); // frame 1
        let id = cache.prepare(&mut services, 1, SvgBytes::Static(b"<svg/>"));
        assert_eq!(services.svg_register_calls, 1);

        cache.begin_frame(); // frame 2
        assert!(cache.touch_svg(id));
        cache.prune(&mut services, 0, 10);
        assert_eq!(services.svg_unregister_calls, 0);
    }

    #[test]
    fn touch_svgs_in_scene_ops_prevents_prune_age_release() {
        let mut cache = SvgCache::default();
        let mut services = FakeServices::default();

        cache.begin_frame(); // frame 1
        let id = cache.prepare(&mut services, 1, SvgBytes::Static(b"<svg/>"));

        let ops = [fret_core::SceneOp::SvgImage {
            order: fret_core::DrawOrder(0),
            rect: fret_core::Rect::new(
                fret_core::Point::new(Px(0.0), Px(0.0)),
                fret_core::Size::new(Px(1.0), Px(1.0)),
            ),
            svg: id,
            fit: fret_core::SvgFit::Contain,
            opacity: 1.0,
        }];

        cache.begin_frame(); // frame 2
        let touched = cache.touch_svgs_in_scene_ops(&ops);
        assert_eq!(touched, 1);
        cache.prune(&mut services, 0, 10);
        assert_eq!(services.svg_unregister_calls, 0);
    }
}