rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! Bounded LRU CPU page snapshots per native session. This cache is optional;
//! misses and rejected retention never change the region pixel contract.

use serde::Serialize;
use std::collections::VecDeque;

use super::{NativeDocumentSession, NativeFrame, NativeHostError, MAX_FRAME_PIXELS};
use crate::renderer::layer_renderer::RasterRenderOptions;
use crate::renderer::raster_pixels::{RasterRegion, RasterRegionPixels};
use crate::renderer::skia::{
    PreparedSkiaPage, PreparedSkiaTile, SkiaRegionPlan, SkiaTileBounds, SkiaTilePlan,
};

pub const DEFAULT_REGION_CACHE_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_REGION_CACHE_BYTES: usize = 64 * 1024 * 1024;
/// Bound metadata as well as pixel storage, including very small page rasters.
pub const MAX_REGION_CACHE_ENTRIES: usize = 4;
pub const MAX_TILE_CACHE_ENTRIES: usize = 64;

/// Counters accumulate for the session lifetime, including across cache clears.
/// `replays` counts successful full-page rasterizations for region requests.
/// Hits count successful requests served by the matching retained snapshot;
/// `off_page_requests` counts successful clear-only requests on a cold key.
/// `entries` counts full-page snapshots; tile counters count individual tiles,
/// including successful tiles from a request that later fails. Tile hits and
/// misses count lookups. `retained_bytes` includes both kinds of N32 images.
/// Gauges exclude output buffers, renderer
/// resources, layout data and Skia intermediates. This is not an RSS estimate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeRegionCacheStats {
    pub entries: usize,
    pub retained_bytes: usize,
    pub hits: u64,
    pub misses: u64,
    pub replays: u64,
    pub evictions: u64,
    pub invalidations: u64,
    pub bypassed_oversized: u64,
    pub off_page_requests: u64,
    pub tile_entries: usize,
    pub tile_retained_bytes: usize,
    pub tile_hits: u64,
    pub tile_misses: u64,
    pub tile_replays: u64,
    pub tile_evictions: u64,
    pub tile_bypassed_oversized: u64,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct RegionKey {
    revision: u64,
    font_generation: u64,
    page: u32,
    scale: u64,
}

struct RegionEntry {
    key: RegionKey,
    raster: RegionRaster,
}

enum RegionRaster {
    Page(PreparedSkiaPage),
    Tile {
        origin: (i32, i32),
        tile: PreparedSkiaTile,
    },
}

impl RegionEntry {
    fn page(&self) -> Option<&PreparedSkiaPage> {
        match &self.raster {
            RegionRaster::Page(page) => Some(page),
            RegionRaster::Tile { .. } => None,
        }
    }

    fn retained_bytes(&self) -> usize {
        match &self.raster {
            RegionRaster::Page(page) => page.retained_bytes(),
            RegionRaster::Tile { tile, .. } => tile.retained_bytes(),
        }
    }
}

pub(super) struct NativeRegionCache {
    // Least recently used first. A successful read moves its entry to the back.
    entries: VecDeque<RegionEntry>,
    max_bytes: usize,
    stats: NativeRegionCacheStats,
}

impl Default for NativeRegionCache {
    fn default() -> Self {
        Self {
            entries: VecDeque::new(),
            max_bytes: DEFAULT_REGION_CACHE_BYTES,
            stats: NativeRegionCacheStats::default(),
        }
    }
}

impl NativeRegionCache {
    fn evict(&mut self, index: usize) {
        if let Some(entry) = self.entries.remove(index) {
            let counter = if entry.page().is_some() {
                &mut self.stats.evictions
            } else {
                &mut self.stats.tile_evictions
            };
            *counter = counter.saturating_add(1);
        }
    }

    fn evict_oldest(&mut self) {
        self.evict(0);
    }

    fn evict_all(&mut self) {
        while !self.entries.is_empty() {
            self.evict_oldest();
        }
    }

    fn retained_bytes(&self) -> usize {
        self.entries.iter().map(RegionEntry::retained_bytes).sum()
    }

    fn page_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.page().is_some())
            .count()
    }

    fn reserve(&mut self, bytes: usize, for_tile: bool, allocation_bytes: u64) {
        if bytes > self.max_bytes {
            // Preserve oversized full-page bypass and use the same policy for
            // tiles. No old raster remains alive during the new allocation.
            self.evict_all();
        } else {
            let count = if for_tile {
                self.entries.len() - self.page_count()
            } else {
                self.page_count()
            };
            let cap = if for_tile {
                MAX_TILE_CACHE_ENTRIES
            } else {
                MAX_REGION_CACHE_ENTRIES
            };
            if count >= cap {
                let index = self
                    .entries
                    .iter()
                    .position(|entry| entry.page().is_none() == for_tile)
                    .expect("entry at kind limit");
                self.evict(index);
            }
            while self.retained_bytes() + bytes > self.max_bytes {
                self.evict_oldest();
            }
        }
        self.evict_for_allocation(allocation_bytes);
    }

    fn evict_for_allocation(&mut self, allocation_bytes: u64) {
        // The region planner bounds each allocation to 128 MiB, and retained
        // images total at most 64 MiB. Include every image before allocating.
        while !self.entries.is_empty()
            && self.retained_bytes() as u64 + allocation_bytes > SkiaRegionPlan::MAX_BITMAP_BYTES
        {
            self.evict_oldest();
        }
    }

    pub(super) fn invalidate(&mut self) {
        self.evict_all();
        self.stats.invalidations = self.stats.invalidations.saturating_add(1);
    }

    fn stats(&self) -> NativeRegionCacheStats {
        let mut stats = self.stats;
        stats.entries = self.page_count();
        stats.retained_bytes = self.retained_bytes();
        stats.tile_entries = self.entries.len() - stats.entries;
        stats.tile_retained_bytes = self
            .entries
            .iter()
            .filter(|entry| entry.page().is_none())
            .map(RegionEntry::retained_bytes)
            .sum();
        stats
    }

    fn tile(
        &mut self,
        key: RegionKey,
        bounds: SkiaTileBounds,
        output_bytes: usize,
        render: impl FnOnce() -> crate::renderer::layer_renderer::LayerRenderResult<PreparedSkiaTile>,
    ) -> crate::renderer::layer_renderer::LayerRenderResult<PreparedSkiaTile> {
        if let Some(index) = self.entries.iter().position(|entry| {
            entry.key == key
                && matches!(entry.raster, RegionRaster::Tile { origin, .. } if origin == bounds.origin)
        }) {
            let entry = self.entries.remove(index).expect("matching tile");
            let RegionRaster::Tile { tile, .. } = &entry.raster else {
                unreachable!("matching tile kind")
            };
            let tile = tile.clone();
            self.entries.push_back(entry);
            self.stats.tile_hits = self.stats.tile_hits.saturating_add(1);
            return Ok(tile);
        }
        self.stats.tile_misses = self.stats.tile_misses.saturating_add(1);
        let bytes = bounds.retained_bytes();
        self.reserve(bytes, true, bytes as u64 + output_bytes as u64);
        let tile = render()?;
        self.stats.tile_replays = self.stats.tile_replays.saturating_add(1);
        if tile.retained_bytes() <= self.max_bytes {
            self.entries.push_back(RegionEntry {
                key,
                raster: RegionRaster::Tile {
                    origin: bounds.origin,
                    tile: tile.clone(),
                },
            });
        } else {
            self.stats.tile_bypassed_oversized =
                self.stats.tile_bypassed_oversized.saturating_add(1);
        }
        Ok(tile)
    }
}

impl NativeDocumentSession {
    /// Configure combined retention for up to four full-page snapshots and 64
    /// fixed-grid tiles, from zero (disabled) to 64 MiB. Changing the limit evicts all
    /// entries before returning. Rejected values leave the existing limit,
    /// snapshots and counters intact.
    /// The per-request 128 MiB bitmap peak remains independent of this limit.
    pub fn set_region_cache_limit(&self, max_bytes: usize) -> Result<(), NativeHostError> {
        if max_bytes > MAX_REGION_CACHE_BYTES {
            return Err(NativeHostError::LimitExceeded(
                "native region cache limit exceeds 64 MiB".into(),
            ));
        }
        let mut cache = self.region_cache.borrow_mut();
        if cache.max_bytes != max_bytes {
            cache.invalidate();
            cache.max_bytes = max_bytes;
        }
        Ok(())
    }

    pub fn region_cache_stats(&self) -> NativeRegionCacheStats {
        self.region_cache.borrow().stats()
    }

    pub(super) fn render_region_cached(
        &self,
        page: u32,
        region: RasterRegion,
        scale: f64,
    ) -> Result<NativeFrame, NativeHostError> {
        let options = RasterRenderOptions {
            scale,
            max_pixels: MAX_FRAME_PIXELS,
            transparent: false,
            ..Default::default()
        };
        let key = RegionKey {
            revision: self.revision,
            font_generation: self.font_generation,
            page,
            scale: scale.to_bits(),
        };
        let mut cache = self.region_cache.borrow_mut();
        let find_page = |entry: &RegionEntry| entry.key == key && entry.page().is_some();
        if let Some(index) = cache.entries.iter().position(find_page) {
            let plan = cache.entries[index]
                .page()
                .expect("matching page")
                .plan_region(region)?;
            cache.evict_for_allocation(plan.output_bytes() as u64);
            if let Some(index) = cache.entries.iter().position(find_page) {
                let output = cache.entries[index]
                    .page()
                    .expect("matching page")
                    .render_region(region)?;
                let entry = cache.entries.remove(index).expect("matching cache entry");
                cache.entries.push_back(entry);
                cache.stats.hits = cache.stats.hits.saturating_add(1);
                return Ok(self.region_frame(output));
            }
            // If the matching image was evicted, preserve the direct API's
            // clear-only allowance without retaining it alongside the output.
        }

        let tree = self
            .core
            .build_page_layer_tree_shared_with_profile(page, crate::paint::RenderProfile::Screen)?;
        let plan = SkiaRegionPlan::new(tree.page_width, tree.page_height, region, options)?;
        cache.stats.misses = cache.stats.misses.saturating_add(1);
        if plan.intersection().is_none() {
            cache.evict_for_allocation(plan.output_bytes() as u64);
            let (output, prepared) = self
                .renderer()
                .prepare_page_for_region(&tree, region, options)?;
            debug_assert!(prepared.is_none());
            cache.stats.off_page_requests = cache.stats.off_page_requests.saturating_add(1);
            return Ok(self.region_frame(output));
        }

        // Reserve room before creating the new surface. Its immutable snapshot
        // shares that allocation, so working_bytes is also its retention cost.
        // Preserve the existing oversized-page bypass: release all old images.
        cache.reserve(
            plan.working_bytes() as usize,
            false,
            plan.peak_bitmap_bytes(),
        );
        let (output, prepared) = self
            .renderer()
            .prepare_page_for_region(&tree, region, options)?;
        cache.stats.replays = cache.stats.replays.saturating_add(1);
        if let Some(prepared) = prepared {
            debug_assert_eq!(prepared.retained_bytes() as u64, plan.working_bytes());
            if prepared.retained_bytes() <= cache.max_bytes {
                cache.entries.push_back(RegionEntry {
                    key,
                    raster: RegionRaster::Page(prepared),
                });
            } else {
                cache.stats.bypassed_oversized = cache.stats.bypassed_oversized.saturating_add(1);
            }
        }
        Ok(self.region_frame(output))
    }

    pub(super) fn render_tiled_region_cached(
        &self,
        page: u32,
        region: RasterRegion,
        scale: f64,
    ) -> Result<NativeFrame, NativeHostError> {
        self.render_tiled_region_cancellable(page, region, scale, || true)?
            .ok_or_else(|| {
                NativeHostError::Core(crate::HwpError::RenderError(
                    "uninterrupted tiled render stopped".into(),
                ))
            })
    }

    /// Cooperatively stop between complete tile operations. `None` never
    /// contains a partial frame. Successful tiles can remain in the bounded LRU.
    /// The callback must not reenter this session or mutate its renderer/cache.
    pub fn render_tiled_region_cancellable(
        &self,
        page: u32,
        region: RasterRegion,
        scale: f64,
        should_continue: impl FnMut() -> bool,
    ) -> Result<Option<NativeFrame>, NativeHostError> {
        self.check_page(page)?;
        Self::check_scale(scale)?;
        let options = RasterRenderOptions {
            scale,
            max_pixels: MAX_FRAME_PIXELS,
            transparent: false,
            ..Default::default()
        };
        let tree = self
            .core
            .build_page_layer_tree_shared_with_profile(page, crate::paint::RenderProfile::Screen)?;
        let plan = SkiaTilePlan::new(tree.page_width, tree.page_height, region, options)?;
        // Reserve before the output, then before each new tile. Tile snapshots
        // share the same byte budget and LRU as exact full-page snapshots.
        let mut cache = self.region_cache.borrow_mut();
        cache.evict_for_allocation(plan.peak_bitmap_bytes());
        let key = RegionKey {
            revision: self.revision,
            font_generation: self.font_generation,
            page,
            scale: scale.to_bits(),
        };
        let renderer = self.renderer();
        let output = self
            .renderer()
            .render_tiled_region_with_provider_cancellable(
                &tree,
                region,
                options,
                |bounds| {
                    cache.tile(key, bounds, plan.output_bytes(), || {
                        renderer.prepare_tile(&tree, bounds, options)
                    })
                },
                should_continue,
            )?;
        Ok(output.map(|output| self.region_frame(output)))
    }

    fn region_frame(&self, output: RasterRegionPixels) -> NativeFrame {
        NativeFrame {
            pixels: output.pixels,
            revision: self.revision,
            font_generation: self.font_generation,
            origin_x: output.origin_x,
            origin_y: output.origin_y,
        }
    }
}