1
//! ABI-stable snapshot handles for the app's live resources.
2
//!
3
//! [`FontCacheSnapshot`] and [`ImageCacheSnapshot`] are `#[repr(C)]` boxed handles a callback
4
//! obtains via `CallbackInfo::get_font_cache_clone()` /
5
//! `CallbackInfo::get_image_cache_clone()` and hands to consumers that lay
6
//! content out OUTSIDE the window pipeline - `Pdf::from_styled_dom_with_resources`
7
//! being the canonical one ("print exactly what is on screen").
8
//!
9
//! Both are SNAPSHOT HANDLES, not live views: cloning is cheap because the
10
//! heavy state is refcounted (parsed font faces sit behind
11
//! `Arc<Mutex<HashMap<..>>>` shared by [`FontManager::clone_shared`]; decoded
12
//! image pixels sit behind refcounted `ImageRef`s), so nothing is re-parsed,
13
//! re-discovered or re-decoded - the point is speed, not memory. The handle
14
//! stays valid after the callback returns, so a print job can run off-thread.
15

            
16
use core::ffi::c_void;
17

            
18
#[cfg(feature = "text_layout")]
19
use azul_css::props::basic::FontRef;
20

            
21
#[cfg(feature = "text_layout")]
22
type InnerFontManager = crate::text3::cache::FontManager<FontRef>;
23

            
24
/// Boxed snapshot of the window's font resolution state: shared parsed-font
25
/// pool, resolved fallback chains, embedded/in-memory fonts, registry link.
26
///
27
/// Obtain via `CallbackInfo::get_font_cache_clone()`. `Clone` derives another
28
/// shared handle (cheap); dropping releases only this handle's box.
29
#[repr(C)]
30
#[derive(Debug)]
31
pub struct FontCacheSnapshot {
32
    /// Boxed [`FontManager`](crate::text3::cache::FontManager) (opaque over
33
    /// the ABI; null when the `text_layout` feature is compiled out).
34
    pub ptr: *mut c_void,
35
    /// Standard azul destructor latch: `false` on moved-out copies so only
36
    /// one side of an FFI move runs the destructor.
37
    pub run_destructor: bool,
38
}
39

            
40
impl FontCacheSnapshot {
41
    /// Snapshot for use inside a LAYOUT callback: builds family resolution +
42
    /// fallback chains over the system font cache the callback exposes. No
43
    /// per-window embedded fonts exist yet at layout time, so nothing is
44
    /// lost versus `CallbackInfo::get_font_cache_clone` - this is the
45
    /// off-thread-pagination input an app can hand to
46
    /// `Pdf::compute_pagination` without ever seeing the internal manager.
47
    #[cfg(feature = "text_layout")]
48
    #[must_use]
49
    pub fn from_layout_info(info: &azul_core::callbacks::LayoutCallbackInfo) -> Self {
50
        match crate::font_traits::FontManager::new(info.get_font_cache()) {
51
            Ok(fm) => Self::from_font_manager(fm),
52
            Err(_) => Self::empty(),
53
        }
54
    }
55

            
56
    /// Wrap a font manager into an ABI handle.
57
    #[cfg(feature = "text_layout")]
58
    #[must_use]
59
    pub fn from_font_manager(fm: InnerFontManager) -> Self {
60
        Self {
61
            ptr: Box::into_raw(Box::new(fm)).cast(),
62
            run_destructor: true,
63
        }
64
    }
65

            
66
    /// Borrow the wrapped font manager, if any.
67
    #[cfg(feature = "text_layout")]
68
    #[must_use]
69
    pub const fn as_font_manager(&self) -> Option<&InnerFontManager> {
70
        unsafe { self.ptr.cast::<InnerFontManager>().as_ref() }
71
    }
72

            
73
    /// An empty handle (also what the non-`text_layout` build returns).
74
    #[must_use]
75
1
    pub const fn empty() -> Self {
76
1
        Self {
77
1
            ptr: core::ptr::null_mut(),
78
1
            run_destructor: false,
79
1
        }
80
1
    }
81
}
82

            
83
impl Clone for FontCacheSnapshot {
84
    fn clone(&self) -> Self {
85
        #[cfg(feature = "text_layout")]
86
        {
87
            if let Some(fm) = self.as_font_manager() {
88
                return Self::from_font_manager(fm.clone_shared());
89
            }
90
        }
91
        Self::empty()
92
    }
93
}
94

            
95
impl Drop for FontCacheSnapshot {
96
1
    fn drop(&mut self) {
97
1
        if self.run_destructor && !self.ptr.is_null() {
98
            #[cfg(feature = "text_layout")]
99
            unsafe {
100
                drop(Box::from_raw(self.ptr.cast::<InnerFontManager>()));
101
            }
102
            self.ptr = core::ptr::null_mut();
103
            self.run_destructor = false;
104
1
        }
105
1
    }
106
}
107

            
108
// SAFETY: the wrapped FontManager's shared state is Arc/Mutex-guarded; the
109
// handle exists precisely so print jobs can run off the UI thread.
110
#[cfg(feature = "text_layout")]
111
unsafe impl Send for FontCacheSnapshot {}
112

            
113
/// Boxed snapshot of the app's registered images (`css id -> ImageRef`).
114
///
115
/// Obtain via `CallbackInfo::get_image_cache_clone()`. The map is copied but
116
/// every `ImageRef` is a refcounted handle - decoded pixel data is shared,
117
/// never duplicated or re-decoded.
118
#[repr(C)]
119
#[derive(Debug)]
120
pub struct ImageCacheSnapshot {
121
    /// Boxed [`azul_core::resources::ImageCache`] (opaque over the ABI).
122
    pub ptr: *mut c_void,
123
    /// Standard azul destructor latch (see [`FontCacheSnapshot::run_destructor`]).
124
    pub run_destructor: bool,
125
}
126

            
127
impl ImageCacheSnapshot {
128
    /// Wrap an image cache into an ABI handle.
129
    #[must_use]
130
2
    pub fn from_image_cache(cache: azul_core::resources::ImageCache) -> Self {
131
2
        Self {
132
2
            ptr: Box::into_raw(Box::new(cache)).cast(),
133
2
            run_destructor: true,
134
2
        }
135
2
    }
136

            
137
    /// Borrow the wrapped image cache, if any.
138
    #[must_use]
139
5
    pub const fn as_image_cache(&self) -> Option<&azul_core::resources::ImageCache> {
140
5
        unsafe { self.ptr.cast::<azul_core::resources::ImageCache>().as_ref() }
141
5
    }
142

            
143
    /// An empty handle.
144
    #[must_use]
145
1
    pub const fn empty() -> Self {
146
1
        Self {
147
1
            ptr: core::ptr::null_mut(),
148
1
            run_destructor: false,
149
1
        }
150
1
    }
151
}
152

            
153
impl Clone for ImageCacheSnapshot {
154
1
    fn clone(&self) -> Self {
155
        // `azul_core::resources::ImageCache` has no `Clone` impl (house rule
156
        // after the derive(Clone)+Drop double-free audit); clone the map of
157
        // refcounted `ImageRef` handles explicitly — pixels stay shared.
158
1
        self.as_image_cache().map_or_else(Self::empty, |c| {
159
1
            Self::from_image_cache(azul_core::resources::ImageCache {
160
1
                image_id_map: c.image_id_map.clone(),
161
1
            })
162
1
        })
163
1
    }
164
}
165

            
166
impl Drop for ImageCacheSnapshot {
167
3
    fn drop(&mut self) {
168
3
        if self.run_destructor && !self.ptr.is_null() {
169
2
            unsafe {
170
2
                drop(Box::from_raw(
171
2
                    self.ptr.cast::<azul_core::resources::ImageCache>(),
172
2
                ));
173
2
            }
174
2
            self.ptr = core::ptr::null_mut();
175
2
            self.run_destructor = false;
176
2
        }
177
3
    }
178
}
179

            
180
// SAFETY: ImageRef's refcount is atomic; the snapshot exists to outlive the
181
// callback (off-thread print jobs).
182
unsafe impl Send for ImageCacheSnapshot {}
183

            
184
/// Boxed pagination analysis (`page_breaks::PaginationInfo`) over the ABI.
185
///
186
/// The document-editor precalculation result: page count, page of any Y, and
187
/// every break position, WITHOUT any per-page display list having been
188
/// materialized. Obtain via `Pdf::compute_pagination`.
189
#[cfg(feature = "text_layout")]
190
#[repr(C)]
191
#[derive(Debug)]
192
pub struct PaginationSnapshot {
193
    /// Boxed [`crate::solver3::page_breaks::PaginationInfo`] (opaque over the ABI).
194
    pub ptr: *mut c_void,
195
    /// Standard azul destructor latch (see [`FontCacheSnapshot::run_destructor`]).
196
    pub run_destructor: bool,
197
}
198

            
199
/// The boxed payload behind [`PaginationSnapshot::ptr`]: the break analysis
200
/// plus (when the computing entry had the layout cache in scope) every
201
/// break's STRUCTURAL DOM position. Internal - the handle is opaque over the
202
/// ABI, which is exactly what lets this grow without an ABI change.
203
#[cfg(feature = "text_layout")]
204
#[derive(Debug)]
205
pub struct PaginationAnalysis {
206
    pub info: crate::solver3::page_breaks::PaginationInfo,
207
    /// One entry per break of `info.breaks` when available; empty when the
208
    /// computing path could not derive structural positions.
209
    pub structural: Vec<crate::solver3::paged_layout::StructuralBreak>,
210
}
211

            
212
#[cfg(feature = "text_layout")]
213
impl PaginationSnapshot {
214
    /// Wrap a pagination analysis into an ABI handle (no structural breaks -
215
    /// prefer [`Self::from_analysis`] where the layout cache was in scope).
216
    #[must_use]
217
    pub fn from_info(info: crate::solver3::page_breaks::PaginationInfo) -> Self {
218
        Self::from_analysis(PaginationAnalysis {
219
            info,
220
            structural: Vec::new(),
221
        })
222
    }
223

            
224
    /// Wrap the full analysis (break positions + structural DOM paths).
225
    #[must_use]
226
    pub fn from_analysis(analysis: PaginationAnalysis) -> Self {
227
        Self {
228
            ptr: Box::into_raw(Box::new(analysis)).cast(),
229
            run_destructor: true,
230
        }
231
    }
232

            
233
    /// Borrow the full boxed payload, if any.
234
    #[must_use]
235
    const fn as_analysis(&self) -> Option<&PaginationAnalysis> {
236
        unsafe { self.ptr.cast::<PaginationAnalysis>().as_ref() }
237
    }
238

            
239
    /// Borrow the wrapped analysis, if any.
240
    #[must_use]
241
    pub const fn as_info(&self) -> Option<&crate::solver3::page_breaks::PaginationInfo> {
242
        match self.as_analysis() {
243
            Some(a) => Some(&a.info),
244
            None => None,
245
        }
246
    }
247

            
248
    /// Root-to-node child-index DOM path of break `index` - where inserting a
249
    /// break node BEFORE the addressed node reproduces this page boundary
250
    /// structurally (consumable by `DomSplit::at_path`). EMPTY when out of
251
    /// range, when the break has no block at/after it, or when the snapshot
252
    /// was computed by a path without structural mapping.
253
    #[must_use]
254
    pub fn break_path(&self, index: usize) -> azul_css::corety::U32Vec {
255
        self.as_analysis()
256
            .and_then(|a| a.structural.get(index))
257
            .and_then(|b| b.path.clone())
258
            .map_or_else(azul_css::corety::U32Vec::new, Into::into)
259
    }
260

            
261
    /// An empty handle (0 pages - the failure value).
262
    #[must_use]
263
    pub const fn empty() -> Self {
264
        Self {
265
            ptr: core::ptr::null_mut(),
266
            run_destructor: false,
267
        }
268
    }
269

            
270
    /// Number of pages (0 for an empty/failed handle).
271
    #[must_use]
272
    pub fn page_count(&self) -> usize {
273
        self.as_info().map_or(0, |i| i.page_count)
274
    }
275

            
276
    /// Total document-space content height.
277
    #[must_use]
278
    pub fn total_content_height(&self) -> f32 {
279
        self.as_info().map_or(0.0, |i| i.total_content_height)
280
    }
281

            
282
    /// Number of page BREAKS (= `page_count - 1` for non-degenerate docs).
283
    #[must_use]
284
    pub fn break_count(&self) -> usize {
285
        self.as_info().map_or(0, |i| i.breaks.len())
286
    }
287

            
288
    /// Document-space Y of break `index` (0.0 out of range).
289
    #[must_use]
290
    pub fn break_y(&self, index: usize) -> f32 {
291
        self.as_info()
292
            .and_then(|i| i.breaks.get(index))
293
            .map_or(0.0, |b| b.y)
294
    }
295

            
296
    /// Whether break `index` was FORCED by CSS (`break-before/after`).
297
    #[must_use]
298
    pub fn break_is_forced(&self, index: usize) -> bool {
299
        self.as_info()
300
            .and_then(|i| i.breaks.get(index))
301
            .is_some_and(|b| matches!(b.kind, crate::solver3::page_breaks::BreakKind::Forced))
302
    }
303

            
304
    /// Whether break `index` was MOVED by an avoid-rule (break-inside /
305
    /// widows-orphans / atomic lines or rows).
306
    #[must_use]
307
    pub fn break_was_avoided(&self, index: usize) -> bool {
308
        self.as_info()
309
            .and_then(|i| i.breaks.get(index))
310
            .is_some_and(|b| matches!(b.kind, crate::solver3::page_breaks::BreakKind::Avoided(..)))
311
    }
312

            
313
    /// Which page a document-space Y lands on ("what page is this node on?"
314
    /// - the editor query that needs NO page to be materialized).
315
    #[must_use]
316
    pub fn page_of_y(&self, y: f32) -> usize {
317
        self.as_info().map_or(0, |i| {
318
            crate::solver3::page_breaks::page_of_y(i.breaks.as_ref(), y)
319
        })
320
    }
321
}
322

            
323
#[cfg(feature = "text_layout")]
324
impl Clone for PaginationSnapshot {
325
    fn clone(&self) -> Self {
326
        self.as_info()
327
            .map_or_else(Self::empty, |i| Self::from_info(i.clone()))
328
    }
329
}
330

            
331
#[cfg(feature = "text_layout")]
332
impl Drop for PaginationSnapshot {
333
    fn drop(&mut self) {
334
        if self.run_destructor && !self.ptr.is_null() {
335
            unsafe {
336
                drop(Box::from_raw(self.ptr.cast::<PaginationAnalysis>()));
337
            }
338
            self.ptr = core::ptr::null_mut();
339
            self.run_destructor = false;
340
        }
341
    }
342
}
343

            
344
// SAFETY: plain data (Ys + kinds), no interior mutability.
345
#[cfg(feature = "text_layout")]
346
unsafe impl Send for PaginationSnapshot {}
347

            
348
#[cfg(test)]
349
mod tests {
350
    use super::*;
351

            
352
    #[test]
353
1
    fn image_cache_handle_clone_shares_refs_and_drops_clean() {
354
1
        let inner = azul_core::resources::ImageCache::default();
355
1
        let handle = ImageCacheSnapshot::from_image_cache(inner);
356
1
        let clone = handle.clone();
357
1
        assert!(handle.as_image_cache().is_some());
358
1
        assert!(clone.as_image_cache().is_some());
359
1
        drop(handle);
360
1
        assert!(clone.as_image_cache().is_some());
361
1
    }
362

            
363
    #[test]
364
1
    fn empty_handles_are_null_and_droppable() {
365
1
        let f = FontCacheSnapshot::empty();
366
1
        let i = ImageCacheSnapshot::empty();
367
1
        assert!(i.as_image_cache().is_none());
368
1
        drop(f);
369
1
        drop(i);
370
1
    }
371
}