caj2pdf-core 0.5.0

Platform-neutral CAJ-family conversion core
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
// SPDX-License-Identifier: MIT

//! Incremental composition of the independently controlled C8 native subset.

use super::{
    C8GlyphClass, EmpiricalPageGeometry, Hnc8Reader, Location, NativeRecord, NativeRecordVisitor,
    Variant, decode_native_character, decode_native_character_for_mode,
    decode_native_image_coordinate, empirical_c8_horizontal_decoration, empirical_c8_segment,
};
use crate::pdf::{ContentPageWriter, FontObject, ImageObject, PdfDocument};
use crate::{Cancellation, Error, RangedSource, Result};
use std::io::Write;

/// Indices into the font handles supplied to the native page writer.
///
/// Only `cjk` and `latin` are required. Every glyph first uses the font of the
/// role the source selects. When that role is absent, or its font does not
/// map the character, the glyph falls back by character: CJK-coded
/// characters (CJK radicals and punctuation, kana, Han, compatibility
/// ideographs, vertical and small forms, and halfwidth/fullwidth forms) use
/// `cjk` and all others use `latin`.
/// A glyph missing from that fallback font still fails with a located error.
/// No system lookup or other substitution is performed.
#[derive(Clone, Copy, Debug)]
pub struct C8PageFonts {
    pub cjk: usize,
    pub latin: usize,
    /// Resource selected by the observed ordinary Latin `801d/4` state.
    /// This is not a universal bold flag.
    pub alternate_latin: Option<usize>,
    /// Font index and nonsemantic character-map alias for horizontal decoration.
    /// When absent, [`C8_DEFAULT_DECORATION_ALIAS`] is drawn by fallback.
    pub decoration: Option<(usize, char)>,
    /// Semantic symbols and spaces in the controlled HN-B mode-0 profile.
    pub symbols: Option<usize>,
    /// HN-B/C8 Latin resource selected by `801d/3`.
    pub latin_state3: Option<usize>,
    /// C8 Latin resources selected by `801d/28` and `801d/31`.
    pub latin_state28: Option<usize>,
    pub latin_state31: Option<usize>,
}

/// Nonsemantic decoration alias drawn when no decoration role is supplied.
pub const C8_DEFAULT_DECORATION_ALIAS: char = '\u{25ba}';

/// Whether native glyph font fallback treats `character` as CJK-coded.
///
/// This covers CJK radicals, ideographic punctuation, kana, Han, compatibility
/// ideographs, vertical and small forms, and halfwidth/fullwidth forms. It
/// selects only a fallback resource; it does not change glyph placement.
pub fn is_cjk_coded(character: char) -> bool {
    matches!(
        character,
        '\u{2e80}'..='\u{9fff}'
            | '\u{f900}'..='\u{faff}'
            | '\u{fe10}'..='\u{fe1f}'
            | '\u{fe30}'..='\u{fe6f}'
            | '\u{ff00}'..='\u{ffef}'
    )
}

/// Write and finish the current C8 or text/vector HN-B native page using already embedded resources.
///
/// Call `next_page` first. Images must be supplied in descriptor order, decoded
/// through the existing codecs. `top_first` identifies each emitted image's row
/// representation: JPEG emitters use false; type-0 and type-3 use true.
/// Fonts are embedded once per document and may share resource indices.
///
/// Records are consumed one at a time; no glyph or page-content vector is kept.
/// This translation admits measured CJK/ASCII and symbol glyphs, segments,
/// horizontal decoration and the controlled image form. Required symbols and
/// other unresolved controls fail explicitly rather than being skipped. It does
/// not establish whole-document C8 support or provide the adapter font transport.
/// Returns the zero-based PDF page index. Any failure after opening the page
/// leaves the PDF unfinished and unusable.
/// Whether native composition admits the document's variant and rendering
/// mode. Character mapping, font selection and placement are mode-specific:
/// C8 and HN-B mode 2 are admitted, and only HN-B has independently
/// controlled mode-0 records.
pub(crate) fn admits_native_mode(header: super::Header) -> bool {
    match header.variant {
        Variant::C8 => header.native_mode == Some(2),
        Variant::HnB => matches!(header.native_mode, Some(0 | 2)),
        Variant::HnA => false,
    }
}

pub fn write_c8_native_page<S, W, C>(
    reader: &mut Hnc8Reader<'_, S, C>,
    document: &mut PdfDocument<'_, W, C>,
    fonts: &[&FontObject],
    roles: C8PageFonts,
    images: &[ImageObject],
    top_first: &[bool],
) -> Result<u32>
where
    S: RangedSource,
    W: Write,
    C: Cancellation,
{
    let header = reader.header();
    let loc = Location {
        variant: Some(header.variant),
        page: reader.current.map(|p| p.page.page_number),
        image: None,
        offset: reader.current.map_or(0, |p| p.page.text.offset),
    };
    let source_error = |source| loc.locate(source);
    if !matches!(header.variant, Variant::C8 | Variant::HnB) {
        return Err(loc.unsupported("native page composition variant"));
    }
    if !admits_native_mode(header) {
        return Err(loc.unsupported("native page rendering mode"));
    }
    if header.variant == Variant::HnB && header.native_mode == Some(0) && !images.is_empty() {
        return Err(source_error(invalid(
            "unverified HN-B mode-0 image composition",
        )));
    }
    let current = reader
        .current
        .ok_or_else(|| loc.malformed("no current page"))?;
    if images.len() as u64 != u64::from(current.page.image_count) || top_first.len() != images.len()
    {
        return Err(source_error(invalid(
            "native page image resources differ from declared count",
        )));
    }
    let size = header
        .page_size
        .ok_or_else(|| source_error(invalid("native page size is missing")))?;
    let mut geometry = super::placement::source_page_geometry(size).map_err(source_error)?;
    let legacy = header.native_mode == Some(0);
    if legacy {
        // Add in source units before conversion, without overflowing u16 extents.
        let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
        geometry.size.width_points = (f64::from(size[0]) + 100.0) * unit;
        geometry.size.height_points = (f64::from(size[1]) + 100.0) * unit;
    }
    let origin = header
        .native_origin
        .ok_or_else(|| source_error(invalid("native page origin is missing")))?;
    let mut page = document
        .begin_content_page(geometry.size, fonts, images)
        .map_err(source_error)?;
    let mut writer = PageWriter {
        page: &mut page,
        fonts,
        roles,
        geometry,
        origin,
        top_first,
        image: 0,
        non_image_painted: false,
        image_overlay: None,
        style: None,
        axes: [None; 2],
        latin: Some(roles.latin),
        skew: 0.0,
        gray: 68,
        cjk_mode: false,
        variant: header.variant,
        legacy,
    };
    reader.visit_native_records(&mut writer)?;
    page.finish().map_err(source_error)
}

fn invalid(reason: &'static str) -> Error {
    Error::invalid(reason)
}

struct PageWriter<'p, 'd, 'a, 'r, W: Write, C: Cancellation> {
    page: &'p mut ContentPageWriter<'d, 'a, 'r, W, C>,
    fonts: &'r [&'r FontObject],
    roles: C8PageFonts,
    geometry: EmpiricalPageGeometry,
    origin: [u16; 2],
    top_first: &'r [bool],
    image: usize,
    non_image_painted: bool,
    /// HN-B fixes its image raster operation at the first image: text or
    /// drawing before that image selects binary AND; leading images replace.
    image_overlay: Option<bool>,
    style: Option<u16>,
    axes: [Option<u16>; 2],
    /// Current Latin resource state; `None` selects the role fallback.
    latin: Option<usize>,
    skew: f64,
    gray: u8,
    cjk_mode: bool,
    variant: Variant,
    legacy: bool,
}

impl<W: Write, C: Cancellation> NativeRecordVisitor for PageWriter<'_, '_, '_, '_, W, C> {
    fn visit(&mut self, _: u64, record: NativeRecord) -> crate::Result<()> {
        if self.legacy {
            return self.visit_mode_zero(record);
        }
        if matches!(
            record,
            NativeRecord::Glyph { .. } | NativeRecord::Drawing { .. }
        ) {
            self.non_image_painted = true;
        }
        match record {
            NativeRecord::Control { tag: 0x8001, .. } => (), // y is carried by each glyph.
            // The parser validates the bounded ASCII payload. Original mixed
            // controls preserve font state, glyphs, drawings and images; the
            // encoded value is not a resource path to open.
            NativeRecord::EncodedString { .. } if self.variant == Variant::C8 => (),
            // Independent mixed controls preserve both ordinary and CJK mode
            // across source, extreme and marker-like atomic payload values.
            NativeRecord::ExtendedControl {
                tag: 0x80cc,
                value: 0x0204,
                ..
            } if self.variant == Variant::C8 => (),
            // Original mixed controls establish black glyphs for this exact
            // payload, retained across later style/resource selections.
            NativeRecord::ExtendedControl {
                tag: 0x81ff,
                value: 1..=3,
                words: [0, 200],
            } if self.variant == Variant::C8 => self.gray = 0,
            NativeRecord::Control {
                tag: 0x8021,
                value: 0x2000,
            }
            | NativeRecord::Control {
                tag: 0x80d0 | 0x80d2 | 0x80d5 | 0x9002,
                value: 0,
            }
            | NativeRecord::Control {
                tag: 0x80d3,
                value: 0..=2,
            }
            | NativeRecord::Control {
                tag: 0x80d1,
                value: 1,
            } if self.variant == Variant::C8 => (),
            NativeRecord::Control {
                tag: 0x8024,
                value: 0x2800,
            } => self.skew = 0.0,
            NativeRecord::Control {
                tag: 0x8024,
                value: 0x281d,
            } => self.skew = 0.24,
            NativeRecord::Control {
                tag: 0x8024,
                value: 0x281c,
            } if self.variant == Variant::C8 => self.skew = 0.225,
            NativeRecord::Control {
                tag: 0x8024,
                value: 0x2815,
            } if self.variant == Variant::HnB => self.skew = 0.105,
            NativeRecord::Control { tag: 0x8002, value } => {
                self.style = Some(value);
                self.axes = [None; 2];
            }
            NativeRecord::Control {
                tag: 0x801c,
                value: 2..=4,
            } => (),
            NativeRecord::Control {
                tag: tag @ (0x8070 | 0x8071),
                value,
            } if matches!(
                (self.variant, value),
                (Variant::C8, 4 | 22 | 34 | 36 | 38 | 40) | (Variant::HnB, 28 | 36 | 43)
            ) =>
            {
                self.axes[usize::from(tag - 0x8070)] = Some(value)
            }
            NativeRecord::Control {
                tag: 0x801d,
                value: 0,
            } => self.latin = Some(self.roles.latin),
            NativeRecord::Control {
                tag: 0x801d,
                value: 4,
            } => self.latin = self.roles.alternate_latin,
            NativeRecord::Control {
                tag: 0x801d,
                value: 3,
            } => self.latin = self.roles.latin_state3,
            NativeRecord::Control {
                tag: 0x801d,
                value: 28,
            } if self.variant == Variant::C8 => self.latin = self.roles.latin_state28,
            NativeRecord::Control {
                tag: 0x801d,
                value: 31,
            } if self.variant == Variant::C8 => self.latin = self.roles.latin_state31,
            // Independently controlled ordinary resource combinations.
            NativeRecord::Control {
                tag: 0x8067,
                value: 5 | 6 | 8 | 9,
            } => (),
            // C8 zero mode persists across style/resource selections; one
            // restores the ordinary per-code resource and placement rules.
            NativeRecord::Control {
                tag: 0x80ce,
                value: 0,
            } if self.variant == Variant::C8 => self.cjk_mode = true,
            NativeRecord::Control {
                tag: 0x80ce,
                value: 1,
            } => self.cjk_mode = false,
            // Independent mixed-page controls preserve painting for opaque values.
            NativeRecord::Control {
                tag: 0x8073 | 0x8074,
                ..
            } => (),
            NativeRecord::Control {
                tag: 0x8072,
                value: 0 | 0x1042 | 0xa3a8 | 0xa0f2 | 0xd2e5,
            }
            | NativeRecord::Control {
                tag: 0xc053 | 0xc054,
                ..
            } => (),
            NativeRecord::Control {
                tag: 0x8067,
                value: 7 | 18,
            }
            | NativeRecord::Control {
                tag: 0x8069,
                value: 0x1084,
            }
            | NativeRecord::Control {
                // Independently varied metadata words preserve glyph state,
                // including values that resemble record tags and coordinates.
                tag: 0x8072,
                ..
            }
            | NativeRecord::ExtendedControl {
                tag: 0xc052,
                value: 0xa385,
                ..
            } if self.variant == Variant::HnB => (),
            NativeRecord::Glyph { x, y, style, code } => {
                // Original CJK/Latin/symbol pairs establish these regular flags
                // across fields 2..=8, including a rectangular held-out control.
                let style = if self.variant == Variant::HnB
                    && style & 0xfc00 == 0x0400
                    && (2..=8).contains(&((style >> 5) & 31))
                    && (2..=8).contains(&(style & 31))
                {
                    (style & 0x03ff) | 0x1000
                } else {
                    style
                };
                if self.variant == Variant::HnB
                    && self.axes == [None; 2]
                    && matches!(style, 0x1001 | 0x1020)
                {
                    return Err(invalid("unverified HN-B mode-2 zero-field glyph style"));
                }
                let character = match (self.variant, code) {
                    (Variant::C8, 0x006c) => 'l',
                    (Variant::C8, 0x0070) => 'p',
                    // Keep the source's private-use identity; its display alias
                    // below does not establish a standard Unicode character.
                    (Variant::HnB, 0xa661) => '\u{e6c7}',
                    _ => decode_native_character(code)
                        .ok_or_else(|| invalid("unsupported C8 native character"))?,
                };
                if (style == 0x114a && self.variant != Variant::HnB)
                    || (style == 0xb94c && self.variant != Variant::C8)
                {
                    return Err(invalid("unverified C8 title style"));
                }
                if matches!(style, 0xe58c | 0x114a | 0x154a | 0xb94c)
                    && self.axes == [None; 2]
                    && !('㐀'..='鿿').contains(&character)
                {
                    return Err(invalid("unverified large native glyph class"));
                }
                let axis_offset = if (self.variant == Variant::C8 || style == 0x1021)
                    && self.axes == [None; 2]
                    && matches!(code, 0xa3db | 0xa3dd)
                {
                    match style {
                        0x1021 => Some((21.0, 3.0)),
                        0x1022 => Some((21.0, 1.0)),
                        0x1041 => Some((24.0, 3.0)),
                        _ => None,
                    }
                } else if self.variant == Variant::C8 && style == 0x10a5 && self.axes == [None; 2] {
                    match code {
                        0xa1b6 => Some((30.0, -4.0)),
                        0xa1b7 => Some((20.0, -4.0)),
                        _ => None,
                    }
                } else if self.variant == Variant::HnB {
                    match (self.axes, code) {
                        ([Some(43), Some(43)], 0xa3a8) => Some((27.0, -4.0)),
                        ([Some(43), Some(43)], 0xa1b0 | 0xa1b1 | 0xa3a9) => Some((25.0, -4.0)),
                        ([Some(43), Some(43)], 0xa1b6) => Some((30.0, -4.0)),
                        ([Some(43), Some(43)], 0xa1b7) => Some((20.0, -4.0)),
                        ([Some(43), Some(43)], 0xa1b2 | 0xa1b3) => Some((25.0, 4.0)),
                        ([Some(28), Some(28)], 0xa1b2 | 0xa1b3) => Some((16.0, 8.0)),
                        _ => None,
                    }
                } else if let [Some(width), Some(height)] = self.axes
                    && width == height
                {
                    // Original full-em controls, including distinct opening,
                    // closing and square marks at each observed explicit size.
                    let offsets = match width {
                        22 => Some([14.0, 13.0, 6.0, 19.0, 4.0]),
                        34 => Some([21.0, 20.0, 0.0, 29.0, -3.0]),
                        40 => Some([25.0, 23.0, -2.0, 34.0, -5.0]),
                        _ => None,
                    };
                    offsets.and_then(|[open, close, down, square, square_down]| match code {
                        0xa3a8 => Some((open, down)),
                        0xa3a9 => Some((close, down)),
                        0xa3db | 0xa3dd => Some((square, square_down)),
                        _ => None,
                    })
                } else {
                    None
                };
                if matches!(code, 0xa1b2 | 0xa1b3 | 0xa1b6 | 0xa1b7)
                    && axis_offset.is_none()
                    && (self.variant != Variant::HnB
                        || !(style == 0x10a5
                            || (matches!(style, 0x08a5 | 0x0ca5 | 0x1084 | 0x0884)
                                && matches!(code, 0xa1b2 | 0xa1b3)))
                        || self.axes != [None; 2])
                {
                    return Err(invalid("unverified native bracket geometry"));
                }
                if self.axes != [None; 2]
                    && axis_offset.is_none()
                    && matches!(
                        code,
                        0xa1a4 | 0xa1af | 0xa1b0 | 0xa1b1 | 0xa3a8 | 0xa3a9 | 0xa3db | 0xa3dd
                    )
                {
                    return Err(invalid("unverified explicit-axis punctuation offsets"));
                }
                if matches!(
                    code,
                    0xa1a4 | 0xa1af | 0xa1b0 | 0xa1b1 | 0xa3a8 | 0xa3a9 | 0xa3db | 0xa3dd
                ) && self.axes == [None; 2]
                    && axis_offset.is_none()
                    && (!matches!((style >> 5) & 31, 2..=8) || !matches!(style & 31, 2..=8))
                {
                    return Err(invalid("unverified native punctuation size fields"));
                }
                let latin = self.latin;
                // Select by raw code: Unicode alone does not establish the
                // resource or placement of the source's symbol variants.
                let (class, font, baseline_fraction) = match code {
                    // These observed low-byte C8 letters retain the CJK resource
                    // and symbol baseline in both glyph-selection modes.
                    0x006c | 0x0070 => (C8GlyphClass::Cjk, Some(self.roles.cjk), Some(0.0)),
                    _ if self.cjk_mode => {
                        if !character.is_ascii_alphanumeric()
                            && !('\u{3400}'..='\u{9fff}').contains(&character)
                            && !matches!(code, 0xa3c1..=0xa3da | 0xa3e1..=0xa3fa)
                        {
                            return Err(invalid("unverified C8 CJK-mode glyph placement"));
                        }
                        (C8GlyphClass::Cjk, Some(self.roles.cjk), None)
                    }
                    0xa0a6
                    | 0xa0ae
                    | 0xa0af
                    | 0xa0ba
                    | 0xaab1
                    | 0xaab2
                    | 0xa1aa
                    | 0xa1ab
                    | 0xa1ad
                    | 0xa1ae
                    | 0xa1af
                    | 0xa2d9..=0xa2df
                    | 0xa3a3
                    | 0xa3a5
                    | 0xa3a7
                    | 0xa3ab..=0xa3b9
                    | 0xa3bb..=0xa3c0
                    | 0xa3dc
                    | 0xa3fb..=0xa3fd => (C8GlyphClass::Cjk, latin, Some(0.0)),
                    // These symbols retain the ordinary Latin resource even
                    // under the alternate-resource state.
                    0xa1c6 | 0xa1c8 | 0xa9aa | 0xaab3 | 0xaca3 => {
                        (C8GlyphClass::Cjk, Some(self.roles.latin), Some(0.0))
                    }
                    0xa1ce | 0xa1fa
                        if self.variant == Variant::C8
                            && (code == 0xa1ce || (style == 0x10a5 && self.axes == [None; 2])) =>
                    {
                        // Original following-glyph controls confirm this persistent reset.
                        self.latin = Some(self.roles.latin);
                        (C8GlyphClass::Cjk, self.latin, Some(0.0))
                    }
                    0xa1c1 | 0xa1de | 0xa1e4 | 0xa6b8 | 0xa6c4 | 0xa6c5 | 0xa6c8
                        if self.variant == Variant::C8 =>
                    {
                        (C8GlyphClass::Cjk, latin, Some(0.0))
                    }
                    0xa0ad | 0xa1b4 | 0xa1b5 | 0xa1c0 | 0xa1c1 | 0xa1c3 | 0xa1e4 | 0xa2f2
                    | 0xa6b8 | 0xa6c4 | 0xa6cc | 0xa6d2 | 0xa661
                        if self.variant == Variant::HnB =>
                    {
                        (C8GlyphClass::Cjk, latin, Some(0.0))
                    }
                    0xa1d6 | 0xa1dd if self.variant == Variant::HnB => {
                        // Single-symbol controls establish a persistent reset,
                        // including the following ordinary Latin glyph.
                        self.latin = Some(self.roles.latin);
                        (C8GlyphClass::Cjk, self.latin, Some(0.0))
                    }
                    0xa6c2
                        if self.variant == Variant::HnB
                            && style == 0x10a5
                            && self.axes == [None; 2] =>
                    {
                        (C8GlyphClass::Cjk, latin, Some(0.0))
                    }
                    0xa1a4 | 0xa3ba => (C8GlyphClass::Cjk, latin, Some(1.0 / 8.0)),
                    0xa1b0 | 0xa1b1 | 0xa1b2 | 0xa1b3 | 0xa1b6 | 0xa1b7 | 0xa3a8 | 0xa3a9 => {
                        (C8GlyphClass::Cjk, latin, None)
                    }
                    0xa3db | 0xa3dd => (C8GlyphClass::Cjk, Some(self.roles.latin), None),
                    0xa1a1 | 0xa3a6 => (C8GlyphClass::Cjk, Some(self.roles.cjk), None),
                    0xa3c1..=0xa3da | 0xa3e1..=0xa3fa if self.variant == Variant::C8 => {
                        (C8GlyphClass::Cjk, Some(self.roles.cjk), None)
                    }
                    0xa1a2 | 0xa1a3 => (C8GlyphClass::Latin, latin, None),
                    _ if character.is_ascii_alphanumeric() => (C8GlyphClass::Latin, latin, None),
                    _ if ('\u{3400}'..='\u{9fff}').contains(&character) => {
                        (C8GlyphClass::Cjk, Some(self.roles.cjk), None)
                    }
                    _ => return Err(invalid("unverified C8 glyph resource or placement class")),
                };
                let mut transform = super::placement::native_glyph_transform(
                    self.geometry,
                    self.origin,
                    [x, y],
                    style,
                    class,
                    self.axes,
                )?;
                if let Some(fraction) = baseline_fraction {
                    // Controlled symbol baselines use independent em height;
                    // resource choice does not imply ordinary Latin geometry.
                    transform[5] += transform[3] * fraction
                        - 15.0 * super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                }
                if matches!(code, 0xa1a2 | 0xa1a3) {
                    // Verified ideographic punctuation shares the Latin baseline,
                    // but retains the CJK horizontal origin.
                    transform[4] -= transform[0] / 8.0;
                }
                if self.variant == Variant::HnB && code == 0xa6c2 {
                    // Independently paired style-5 controls match a comma
                    // shifted down by 25 source units in both Latin resources.
                    transform[5] -= 25.0 * super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                }
                if let Some((dx, dy)) = axis_offset {
                    let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                    transform[4] += dx * unit;
                    transform[5] -= dy * unit;
                } else {
                    if matches!(code, 0xa1b2 | 0xa1b3) {
                        // Original pairs establish separate size-4/size-5 offsets;
                        // resource selection remains independent of placement.
                        let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                        let (dx, dy) = if style & 0x03ff == 0x0084 {
                            (21.0, 6.0)
                        } else {
                            (25.0, 5.0)
                        };
                        transform[4] += dx * unit;
                        transform[5] -= dy * unit;
                    }
                    let offset_columns = match code {
                        0xa1b6 | 0xa1b7 | 0xa3a8 => Some((0, 2)),
                        0xa1b0 | 0xa1b1 | 0xa3a9 => Some((1, 2)),
                        0xa3db | 0xa3dd => Some((3, 4)),
                        _ => None,
                    };
                    if let Some((x_column, y_column)) = offset_columns {
                        // Raw offsets checked with independent width/height controls.
                        // Columns: opening-parenthesis x, closing-parenthesis x,
                        // parenthesis downward y, square-bracket x and downward y.
                        const OFFSETS: [[i16; 5]; 7] = [
                            [18, 16, 3, 24, 1],
                            [19, 18, 1, 27, -1],
                            [22, 21, 0, 30, -3],
                            [26, 25, -4, 36, -7],
                            [30, 28, -7, 41, -10],
                            [35, 33, -10, 48, -15],
                            [39, 37, -14, 54, -18],
                        ];
                        // The matrix evaluator above has validated both fields.
                        let width = usize::from((style >> 5) & 31) - 2;
                        let height = usize::from(style & 31) - 2;
                        let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                        // Controlled HN-B style-5 book marks share parenthesis y;
                        // their x differs by +4/-6 source units from the opener.
                        let book_x = match code {
                            0xa1b6 => 4,
                            0xa1b7 => -6,
                            _ => 0,
                        };
                        transform[4] += f64::from(OFFSETS[width][x_column] + book_x) * unit;
                        transform[5] -= f64::from(OFFSETS[height][y_column]) * unit;
                    }
                    if matches!(code, 0xa1a4 | 0xa1af) {
                        // Middle dot and right single quote share a horizontal
                        // correction but keep their separately controlled baselines.
                        const X_OFFSETS: [i16; 7] = [7, 7, 8, 10, 11, 13, 15];
                        let width = usize::from((style >> 5) & 31) - 2;
                        transform[4] += f64::from(X_OFFSETS[width])
                            * super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                    }
                }
                if self.skew != 0.0 {
                    // Measured width-relative shear; style changes retain it.
                    transform[2] = transform[0] * self.skew;
                }
                // Keep the verified current gray local to each glyph draw.
                let font = self.font(font, character);
                if character == '\u{e6c7}'
                    && self
                        .fonts
                        .get(font)
                        .is_some_and(|font| !font.supports(character))
                {
                    // The viewer paints an acute-accented Gamma-like shape for
                    // A661, but Copy yields a bullet. Use a visual substitute
                    // from the caller's font and retain the PUA in ActualText.
                    let alias = '\u{0403}';
                    let font = self.font(Some(self.roles.latin), alias);
                    self.page.glyph_with_replacement_text(
                        font, alias, transform, self.gray, character,
                    )?;
                } else {
                    self.page
                        .glyph_with_gray(font, character, transform, self.gray)?;
                }
            }
            NativeRecord::Drawing { .. }
            | NativeRecord::Image { .. }
            | NativeRecord::ImageReference { .. }
                if self.skew != 0.0 =>
            {
                return Err(invalid("unverified drawing or image in skewed text state"));
            }
            NativeRecord::Drawing {
                tag: 0x8090,
                style: _,
                points: [[raw_x, y], [raw_width, height]],
            } => {
                // The radical value word is opaque and does not change painting state.
                let flags = raw_x & 0xc000;
                let width = raw_width & 0x3fff;
                if !matches!(flags, 0 | 0xc000)
                    || raw_width & 0xc000 != flags
                    || y & 0xc000 != 0
                    || height & 0xc000 != 0
                    || width < 30
                    || height < 45
                    || self.axes != [None; 2]
                {
                    return Err(invalid("unverified C8 radical flags, dimensions or axes"));
                }
                let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                let [left, _, _, top] = self.geometry.media_box()?;
                let x = f64::from(raw_x & 0x3fff) - f64::from(self.origin[0]);
                let y = f64::from(y) - f64::from(self.origin[1]);
                let width = f64::from(width);
                let height = f64::from(height);
                let path = [
                    [x - 45.0, y + height - 25.0],
                    [x - 25.0, y + height - 45.0],
                    [x + 10.0, y + height],
                    [x + 30.0, y],
                    [x + width + 20.0, y],
                ]
                .map(|[x, y]| [left + x * unit, top - y * unit]);
                self.page.stroke_polyline(&path, 4.0 * unit, self.gray)?;
            }
            NativeRecord::Drawing {
                tag: 0x8006 | 0x8007,
                style,
                points,
            } => {
                let [from, to] = empirical_c8_segment(self.geometry, self.origin, points, style)?;
                self.page.segment(from, to, 0.0)?;
            }
            NativeRecord::Drawing {
                tag: 0x8010,
                style: value @ (1 | 2 | 46 | 117),
                points,
            } => {
                if value == 117
                    && (self.variant != Variant::C8
                        || self.axes != [None; 2]
                        || !matches!(self.style, Some(0x1084 | 0x10a5)))
                {
                    return Err(invalid("unverified C8 decoration 117 state"));
                }
                let (font, alias) = self
                    .roles
                    .decoration
                    .map_or((None, C8_DEFAULT_DECORATION_ALIAS), |(font, alias)| {
                        (Some(font), alias)
                    });
                let font = self.font(font, alias);
                let style = self
                    .style
                    .or_else(|| (self.axes != [None; 2]).then_some(0))
                    .ok_or_else(|| invalid("missing C8 decoration style"))?;
                let decoration = empirical_c8_horizontal_decoration(
                    self.geometry,
                    self.origin,
                    points,
                    style,
                    self.axes,
                )?;
                for index in 0..decoration.glyph_count {
                    let mut transform = decoration.first_glyph;
                    transform[4] += f64::from(index) * transform[0];
                    self.page
                        .decoration_glyph(font, alias, transform, decoration.clip)?;
                }
            }
            NativeRecord::Image { words } => {
                // Only bilevel image samples have independently controlled
                // overlay semantics. Color raster operations remain unverified.
                if self.variant == Variant::HnB
                    && self.non_image_painted
                    && !self.page.image_is_bilevel(self.image)
                {
                    return Err(invalid("unverified HN-B image after text or drawing"));
                }
                let coordinate = decode_native_image_coordinate(&words)
                    .ok_or_else(|| invalid("unsupported C8 native image coordinates"))?;
                // Independent tail controls vary all eight low bytes without
                // changing the embedded image or its placement. Other high
                // prefixes remain unverified; never interpret this as a path.
                if words[5..].iter().any(|word| word & 0xff00 != 0xc000) {
                    return Err(invalid("unverified C8 native image payload"));
                }
                self.draw_image(coordinate)?;
            }
            NativeRecord::ImageReference { coordinate, .. } if self.variant == Variant::C8 => {
                // Independent swapped-name controls establish descriptor order.
                // The bounded reference span remains opaque; never open it.
                self.draw_image(coordinate)?;
            }
            NativeRecord::Control {
                tag: 0xffff,
                value: 5,
            }
            | NativeRecord::End { .. } => (),
            _ => return Err(invalid("unverified C8 native rendering record")),
        }
        Ok(())
    }
}

impl<W: Write, C: Cancellation> PageWriter<'_, '_, '_, '_, W, C> {
    /// Apply the [`C8PageFonts`] fallback rule to a selected role. An index
    /// outside the page resources is kept so the draw reports it.
    fn font(&self, role: Option<usize>, character: char) -> usize {
        match role.map(|index| (index, self.fonts.get(index))) {
            Some((index, None)) => index,
            Some((index, Some(font))) if font.supports(character) => index,
            _ if is_cjk_coded(character) => self.roles.cjk,
            _ => self.roles.latin,
        }
    }

    fn draw_image(&mut self, coordinate: super::RawTextCoordinate) -> crate::Result<()> {
        if coordinate.width == 0 || coordinate.height == 0 {
            return Err(invalid("native image extents must be nonzero"));
        }
        let unit = super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
        let x = (f64::from(coordinate.x) - f64::from(self.origin[0])) * unit;
        let y = self.geometry.size.height_points
            - (f64::from(coordinate.y) - f64::from(self.origin[1])) * unit;
        let width = f64::from(coordinate.width) * unit;
        let height = f64::from(coordinate.height) * unit;
        let mut transform = [width, 0.0, 0.0, -height, x, y];
        if self.top_first[self.image] {
            transform[3] = height;
            transform[5] -= height;
        }
        let overlay = self.variant == Variant::HnB
            && *self.image_overlay.get_or_insert(self.non_image_painted);
        if overlay {
            self.page.bilevel_overlay(self.image, transform)?;
        } else {
            self.page.image(self.image, transform)?;
        }
        self.image += 1;
        Ok(())
    }

    fn visit_mode_zero(&mut self, record: NativeRecord) -> crate::Result<()> {
        match record {
            NativeRecord::Control { tag: 0x8001, .. }
            // Original paired rows preserve resources, geometry and explicit axes.
            | NativeRecord::Control { tag: 0x8072, value: 0 | 0xc2c7 }
            | NativeRecord::Control { tag: 0x8073, value: 41..=43 }
            | NativeRecord::Control { tag: 0x8074, value: 0xc8ce | 0xb5c8 | 0xb5c4 }
            | NativeRecord::Control { tag: 0xc053, .. }
            | NativeRecord::Control { tag: 0x80ce, value: 1 }
            | NativeRecord::Control {
                tag: 0x801d,
                value: 0 | 4,
            }
            | NativeRecord::Control {
                tag: 0x8067,
                value: 6,
            }
            | NativeRecord::Control {
                tag: 0xffff,
                value: 5,
            }
            | NativeRecord::End { .. } => (),
            NativeRecord::Control { tag: 0x8002, .. } => self.axes = [None; 2],
            NativeRecord::Control {
                tag: 0x8070,
                value: 36,
            } => self.axes[0] = Some(36),
            NativeRecord::Control {
                tag: 0x8071,
                value: 36,
            } => self.axes[1] = Some(36),
            NativeRecord::Drawing {
                tag: 0x8006,
                style: 0xa385,
                points,
            } => {
                // Both mode-0 endpoints can carry the high-bit marker. The
                // controlled y origin is five units above the mode-2 segment.
                let points =
                    points.map(|[x, y]| [if x & 0xc000 == 0xc000 { x & 0x3fff } else { x }, y]);
                let mut ends = empirical_c8_segment(self.geometry, self.origin, points, 0xa385)?;
                for end in &mut ends {
                    end[1] += 5.0 * super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                }
                self.page.segment(ends[0], ends[1], 0.0)?;
            }
            NativeRecord::Glyph { x, y, style, code } => {
                let character = decode_native_character_for_mode(0, code)
                    .ok_or_else(|| invalid("unsupported HN-B mode-0 character"))?;
                // The raw alphabet selects its resource independently of 801d.
                // Digits have a separate matrix; remaining symbols need another resource.
                let (class, font) = match code {
                    0x9ff5
                    | 0xa1a1..=0xa1a3
                    | 0xa1aa
                    | 0xa1ae..=0xa1b1
                    | 0xa3a7
                    | 0xa3ab..=0xa3ae
                    | 0xa3ba
                    | 0xa3bb
                    | 0xa3bf
                    | 0xa3db
                    | 0xa3dd
                    | 0xaab1
                    | 0xaab2 => {
                        let class = if matches!(code, 0xa3ba | 0xa3db | 0xa3dd) {
                            C8GlyphClass::Cjk
                        } else {
                            C8GlyphClass::Latin
                        };
                        (class, self.roles.symbols)
                    }
                    0xa3a8 | 0xa3a9 => (C8GlyphClass::Cjk, Some(self.roles.latin)),
                    0xa3af => (C8GlyphClass::Cjk, Some(self.roles.cjk)),
                    0xa980..=0xa9b3 => (C8GlyphClass::Latin, self.roles.alternate_latin),
                    0xa3b0..=0xa3b9 | 0xa3c1..=0xa3da | 0xa3e1..=0xa3fa => {
                        (C8GlyphClass::Latin, Some(self.roles.latin))
                    }
                    // The mode-0 decoder accepts only Han after the explicit
                    // alphabet and symbol classes handled above.
                    _ => (C8GlyphClass::Cjk, Some(self.roles.cjk)),
                };
                let font = self.font(font, character);
                let mut transform = if (0xa3b0..=0xa3b9).contains(&code) {
                    super::placement::mode_zero_digit_transform(
                        self.geometry,
                        self.origin,
                        [x, y],
                        style,
                        self.axes,
                    )?
                } else {
                    super::placement::mode_zero_glyph_transform(
                        self.geometry,
                        self.origin,
                        [x, y],
                        style,
                        class,
                        self.axes,
                    )?
                };
                if code == 0xaab2 {
                    let left = match (style & 31, self.axes) {
                        (_, [Some(36), Some(36)]) | (4, [None, None]) => 33.0,
                        (0, [None, None]) => 31.0,
                        (5, [None, None]) => 34.0,
                        _ => return Err(invalid("unverified HN-B mode-0 hyphen geometry")),
                    };
                    transform[4] -= left * super::EMPIRICAL_COORDINATE_POINTS_PER_UNIT;
                }
                self.page
                    .glyph_with_gray(font, character, transform, 68)?;
            }
            _ => return Err(invalid("unverified HN-B mode-0 rendering record")),
        }
        Ok(())
    }
}

#[cfg(test)]
pub(crate) use tests::mixed_page;
#[cfg(test)]
mod tests;