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
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
//! Editing authority for disconnected axial subpaths of one source stroke.
//! Intersections retain the union of their actual ink owners, not their bbox owners.
use super::*;
use crate::model::{
    bin_data::{self, BinDataContent},
    border_paint::CellBorderPaint,
    pdf_stroke::PdfStroke,
};

type CellPart = (Frame, Option<CellBorderPaint>);
type OutsidePart = (Frame, Option<(usize, usize, CellBorderPaint)>);

struct Band {
    axis: StrokeAxis,
    frame: Frame,
    ink: Vec<Frame>,
}
pub(super) struct Compound<'a> {
    allocation: Allocation<'a>,
    target: usize,
    bands: Vec<Band>,
    source_id: u32,
}

fn mapped(rect: [f64; 4], source: Frame, size: [f64; 2]) -> Frame {
    let x = |p: f64| source.x + (p * (source.right - source.x) as f64 / size[0]).round() as i64;
    let y = |p: f64| source.y + (p * (source.bottom - source.y) as f64 / size[1]).round() as i64;
    Frame {
        x: x(rect[0]),
        y: y(rect[1]),
        right: x(rect[2]),
        bottom: y(rect[3]),
    }
}

// A coverage envelope rounds outwards in the native HWPUNIT lattice. This is
// ownership of source ink, not a relocation of its exact vector coordinates.
fn support(rect: [f64; 4], source: Frame, size: [f64; 2]) -> Frame {
    let x = |p: f64| p * (source.right - source.x) as f64 / size[0];
    let y = |p: f64| p * (source.bottom - source.y) as f64 / size[1];
    Frame {
        x: source.x + x(rect[0]).floor() as i64,
        y: source.y + y(rect[1]).floor() as i64,
        right: source.x + x(rect[2]).ceil() as i64,
        bottom: source.y + y(rect[3]).ceil() as i64,
    }
}
#[allow(clippy::too_many_arguments)]
pub(super) fn plan<'a>(
    original: &Control,
    source: Frame,
    path: &pdf_oxide::elements::PathContent,
    control: usize,
    targets: &[Target<'_>],
    frames: &[Vec<Frame>],
    required: &[BTreeSet<usize>],
    resources: &[BinDataContent],
    work: &mut usize,
    allocation: Allocation<'a>,
) -> Result<Option<Compound<'a>>, String> {
    use pdf_oxide::elements::{LineCap, PathOperation};
    if path.operations.len()<4 || path.operations.len()>64 || !path.operations.len().is_multiple_of(2)
        || path.fill_color.is_some() || path.stroke_color.is_none() || path.matrix.is_some()
        || path.line_cap!=LineCap::Butt
        || !path.operations.chunks_exact(2).all(|p|matches!(p,[PathOperation::MoveTo(x,y),PathOperation::LineTo(a,b)] if (x==a&&y!=b)||(y==b&&x!=a))) {return Ok(None);}
    let Control::Picture(p) = original else {
        return Ok(None);
    };
    let Some(i) = bin_data::content_index(resources, p.image_attr.bin_data_id) else {
        return Ok(None);
    };
    // PDF lowering stores resident PNG bytes. Borrow them rather than copy
    // the whole image to inspect its small generated stroke witness.
    let bytes = match &resources[i].data {
        bin_data::BinDataBytes::Loaded(bytes) => std::borrow::Cow::Borrowed(bytes.as_slice()),
        other => {
            allocation
                .bytes(bin_data::MAX_BIN_DATA_BYTES)
                .map_err(message)?;
            let Some(bytes) = other.load_limited(bin_data::MAX_BIN_DATA_BYTES) else {
                return Ok(None);
            };
            std::borrow::Cow::Owned(bytes)
        }
    };
    if let Some(length) = bytes
        .get(33..37)
        .and_then(|b| <[u8; 4]>::try_from(b).ok())
        .map(u32::from_be_bytes)
        .filter(|&n| n <= 4096)
    {
        // Only typed numeric vectors are allocated by this derived witness
        // parser. 32 bytes per encoded byte covers their geometric replacement
        // buffers; PNG pixels are not decoded here. Allocator metadata is separate.
        allocation
            .bytes(length as usize * 32 + std::mem::size_of::<PdfStroke>() + 32)
            .map_err(message)?;
    }
    let Some(stroke) = PdfStroke::read(&bytes) else {
        return Ok(None);
    };
    if stroke.segments.len() + 1 != path.operations.len() / 2 {
        return Ok(None);
    }
    let mut bands = Vec::new();
    let mut ink_count = 0;
    for e in std::iter::once(stroke.endpoints).chain(stroke.segments.iter().copied()) {
        tick(work)?;
        let horizontal = e[1] == e[3];
        let endpoints = mapped([e[0], e[1], e[2], e[3]], source, stroke.frame);
        let axis = StrokeAxis {
            horizontal,
            at: if horizontal { endpoints.y } else { endpoints.x },
            from: if horizontal {
                endpoints.x.min(endpoints.right)
            } else {
                endpoints.y.min(endpoints.bottom)
            },
            to: if horizontal {
                endpoints.x.max(endpoints.right)
            } else {
                endpoints.y.max(endpoints.bottom)
            },
        };
        let rect = if horizontal {
            [
                e[0].min(e[2]),
                e[1] - stroke.width / 2.,
                e[0].max(e[2]),
                e[1] + stroke.width / 2.,
            ]
        } else {
            [
                e[0] - stroke.width / 2.,
                e[1].min(e[3]),
                e[0] + stroke.width / 2.,
                e[1].max(e[3]),
            ]
        };
        let Some(frame) = intersection(support(rect, source, stroke.frame), source, None) else {
            return Ok(None);
        };
        let Some(rects) = stroke.try_segment_rectangles(e, |out, rectangle| {
            allocation.push(out, rectangle).map_err(message)
        })?
        else {
            return Ok(None);
        };
        ink_count += rects.len();
        if ink_count > 8192 {
            return Ok(None);
        }
        let ink = allocation
            .collect(
                rects
                    .into_iter()
                    .filter_map(|r| intersection(support(r, source, stroke.frame), source, None)),
            )
            .map_err(message)?;
        allocation
            .push(&mut bands, Band { axis, frame, ink })
            .map_err(message)?;
    }
    let mut target = None;
    for (ti, t) in targets.iter().enumerate() {
        tick(work)?;
        if !t.root || !required[ti].contains(&control) {
            continue;
        }
        // Ownership follows the actual cell perimeters, including merged cells.
        // The segment-coverage proof below rejects ink crossing a cell interior;
        // native side replacement separately rejects a partial merged neighbour.
        let region = bounds(t.grid)?;
        let mut certified = true;
        for band in &bands {
            tick(work)?;
            let a = band.axis;
            let (lo, hi) = if a.horizontal {
                (region.x, region.right)
            } else {
                (region.y, region.bottom)
            };
            if a.from < lo - 1 || a.to > hi + 1 || !frames[ti].iter().any(|c| side(a, *c).is_some())
            {
                certified = false;
                break;
            }
            // The entire segment must follow logical edges, including empty cells.
            let mut covered = Vec::new();
            for c in &frames[ti] {
                tick(work)?;
                if side(a, *c).is_some() {
                    allocation
                        .push(
                            &mut covered,
                            if a.horizontal {
                                (c.x, c.right)
                            } else {
                                (c.y, c.bottom)
                            },
                        )
                        .map_err(message)?;
                }
            }
            covered.sort_unstable();
            let mut end = a.from;
            for (x, y) in covered {
                if x <= end + 1 && y > end {
                    end = y;
                }
            }
            if end < a.to - 1 {
                certified = false;
                break;
            }
        }
        if certified {
            // A descendant sharing a source boundary needs a separate logical
            // edge-closure contract. Mere geometric contact is not edit ownership.
            for (other, cells) in frames.iter().enumerate() {
                if other == ti {
                    continue;
                }
                for cell in cells {
                    for band in &bands {
                        tick(work)?;
                        if intersection(*cell, band.frame, None).is_some() {
                            certified = false;
                        }
                    }
                }
            }
        }
        if certified {
            if target.is_some() {
                return Ok(None);
            }
            target = Some(ti);
        }
    }
    Ok(target.map(|target| Compound {
        allocation,
        target,
        bands,
        source_id: common(original).unwrap().instance_id,
    }))
}
fn side(axis: StrokeAxis, cell: Frame) -> Option<usize> {
    let (a, b, start, end, first) = if axis.horizontal {
        (cell.y, cell.bottom, cell.x, cell.right, 2)
    } else {
        (cell.x, cell.right, cell.y, cell.bottom, 0)
    };
    if axis.from >= end || axis.to <= start {
        return None;
    }
    match ((axis.at - a).abs() <= 1, (axis.at - b).abs() <= 1) {
        (true, false) => Some(first),
        (false, true) => Some(first + 1),
        _ => None,
    }
}

// Rectangular set overlay. Every output piece has one physical owner; masks
// describe which surviving source axes still require its ink.
fn overlay(
    pieces: &mut Vec<(Frame, u8)>,
    cut: Frame,
    bit: u8,
    work: &mut usize,
    allocation: Allocation<'_>,
) -> Result<(), String> {
    let mut next = Vec::new();
    for (frame, mask) in pieces.drain(..) {
        tick(work)?;
        if let Some(hit) = intersection(frame, cut, None) {
            let mut rest = allocation.collect([frame]).map_err(message)?;
            subtract(&mut rest, hit, None, work, allocation)?;
            allocation.reserve(&mut next, rest.len()).map_err(message)?;
            next.extend(rest.into_iter().map(|r| (r, mask)));
            allocation
                .push(&mut next, (hit, mask | bit))
                .map_err(message)?;
        } else {
            allocation.push(&mut next, (frame, mask)).map_err(message)?;
        }
        if next.len() > MAX_FRAGMENTS {
            return Err("compound paint fragment budget exceeded".into());
        }
    }
    *pieces = next;
    Ok(())
}
impl Compound<'_> {
    fn split(
        &self,
        piece: Frame,
        cell: Frame,
        outer: Option<Frame>,
        work: &mut usize,
    ) -> Result<Vec<CellPart>, String> {
        let allocation = self.allocation;
        let mut pieces = allocation.collect([(piece, 0)]).map_err(message)?;
        let mut candidates = Vec::new();
        for band in &self.bands {
            tick(work)?;
            let Some(dir) = side(band.axis, cell) else {
                continue;
            };
            if let Some(region) = outer {
                if !match dir {
                    0 => cell.x == region.x,
                    1 => cell.right == region.right,
                    2 => cell.y == region.y,
                    _ => cell.bottom == region.bottom,
                } {
                    continue;
                }
            }
            let clip = if band.axis.horizontal {
                Frame {
                    x: cell.x,
                    right: cell.right,
                    ..band.frame
                }
            } else {
                Frame {
                    y: cell.y,
                    bottom: cell.bottom,
                    ..band.frame
                }
            };
            if let Some(cut) = intersection(band.frame, clip, None) {
                overlay(&mut pieces, cut, 1 << dir, work, allocation)?;
                allocation
                    .push(&mut candidates, (band, dir))
                    .map_err(message)?;
            }
        }
        let mut result = Vec::new();
        for (frame, mask) in pieces {
            if mask.count_ones() <= 1 {
                allocation
                    .push(
                        &mut result,
                        (frame, CellBorderPaint::from_mask(mask, self.source_id)),
                    )
                    .map_err(message)?;
                continue;
            }
            // Coarse bands overlap at joints. Refine only these small regions
            // by actual dash ink, so a gap cannot preserve the removed axis.
            let mut joint = allocation.collect([(frame, 0)]).map_err(message)?;
            for (band, dir) in &candidates {
                if mask & (1 << dir) == 0 {
                    continue;
                }
                for &ink in &band.ink {
                    tick(work)?;
                    if intersection(frame, ink, None).is_some() {
                        overlay(&mut joint, ink, 1 << dir, work, allocation)?;
                    }
                }
            }
            allocation
                .reserve(&mut result, joint.len())
                .map_err(message)?;
            result.extend(
                joint
                    .into_iter()
                    .map(|(r, m)| (r, CellBorderPaint::from_mask(m, self.source_id))),
            );
            if result.len() > MAX_FRAGMENTS {
                return Err("compound paint fragment budget exceeded".into());
            }
        }
        Ok(result)
    }
    pub(super) fn cell(
        &self,
        ti: usize,
        piece: Frame,
        cell: Frame,
        work: &mut usize,
    ) -> Result<Vec<CellPart>, String> {
        let allocation = self.allocation;
        if ti != self.target {
            // A path's raster frame can enclose a descendant without any of
            // its ink entering that cell. Do not materialize that empty crop
            // as a selectable, cell-sized picture. Use the certified source
            // stroke envelopes, including width and outward HU rounding;
            // bitmap/frame overlap alone is not evidence of painted content.
            let mut painted = false;
            for band in &self.bands {
                tick(work)?;
                painted |= intersection(band.frame, piece, None).is_some();
            }
            if !painted {
                return Ok(Vec::new());
            }
            return allocation.collect([(piece, None)]).map_err(message);
        }
        // Every certified segment follows this grid. The untagged remainder
        // has no PDF ink. Keeping it as a native crop can reintroduce filtered
        // edge samples after a neighbouring owned stroke is explicitly erased.
        allocation
            .collect(
                self.split(piece, cell, None, work)?
                    .into_iter()
                    .filter(|(_, tag)| tag.is_some()),
            )
            .map_err(message)
    }
    pub(super) fn outside(
        &self,
        remaining: Vec<Frame>,
        frames: &[Vec<Frame>],
        targets: &[Target<'_>],
        work: &mut usize,
    ) -> Result<Vec<OutsidePart>, String> {
        let allocation = self.allocation;
        let ti = self.target;
        let region = bounds(targets[ti].grid)?;
        let mut unowned = remaining;
        let mut out = Vec::new();
        for (ci, cell) in frames[ti].iter().enumerate() {
            let mut next = Vec::new();
            for frame in unowned {
                for (r, tag) in self.split(frame, *cell, Some(region), work)? {
                    if let Some(tag) = tag {
                        allocation
                            .push(&mut out, (r, Some((ti, ci, tag))))
                            .map_err(message)?;
                    } else {
                        allocation.push(&mut next, r).map_err(message)?;
                    }
                }
                if out.len() + next.len() > MAX_FRAGMENTS {
                    return Err("compound outside fragment budget exceeded".into());
                }
            }
            unowned = next;
        }
        // All segments were certified inside this root. Remaining page regions
        // are geometrically empty source padding, not another paint owner.
        Ok(out)
    }
}