fop-core 0.1.1

Core FO tree parsing and property system for Apache FOP
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
//! FO tree builder - constructs the FO tree from XML
//!
//! Splits into:
//! - `mod.rs` (this file): `FoTreeBuilder` struct, XML parsing loop, element lifecycle
//! - `node_factory`: FO node creation from element names/attributes
//! - `property_parser`: Property value parsing (length, color, gradient, etc.)

mod node_factory;
mod property_parser;

use crate::properties::PropertyList;
use crate::tree::{FoArena, FoNode, FoNodeData, NodeId};
use crate::xml::XmlParser;
use crate::{FopError, Result};
use quick_xml::events::Event;
use std::io::BufRead;

/// Builder for constructing FO trees from XML
pub struct FoTreeBuilder<'a> {
    arena: FoArena<'a>,
    current_node: Option<NodeId>,
    /// Depth counter for nested elements inside instream-foreign-object
    foreign_object_depth: usize,
    /// Buffer to collect raw XML content of instream-foreign-object
    foreign_xml_buffer: String,
    /// NodeId of the instream-foreign-object node being built
    foreign_object_node: Option<NodeId>,
}

impl<'a> FoTreeBuilder<'a> {
    /// Create a new tree builder
    pub fn new() -> Self {
        Self {
            arena: FoArena::new(),
            current_node: None,
            foreign_object_depth: 0,
            foreign_xml_buffer: String::new(),
            foreign_object_node: None,
        }
    }

    /// Parse an XSL-FO document and build the tree
    pub fn parse<R: BufRead>(mut self, reader: R) -> Result<FoArena<'a>> {
        let mut parser = XmlParser::new(reader);

        loop {
            let event = parser.read_event()?;

            // If we are inside a foreign object child element, capture raw XML
            if self.foreign_object_depth > 0 {
                match &event {
                    Event::Start(start) => {
                        parser.update_namespaces(start);
                        let raw = std::str::from_utf8(start.as_ref())
                            .unwrap_or("")
                            .to_string();
                        self.foreign_xml_buffer.push('<');
                        self.foreign_xml_buffer.push_str(&raw);
                        self.foreign_xml_buffer.push('>');
                        self.foreign_object_depth += 1;
                    }
                    Event::Empty(start) => {
                        parser.update_namespaces(start);
                        let raw = std::str::from_utf8(start.as_ref())
                            .unwrap_or("")
                            .to_string();
                        self.foreign_xml_buffer.push('<');
                        self.foreign_xml_buffer.push_str(&raw);
                        self.foreign_xml_buffer.push_str("/>");
                    }
                    Event::End(end) => {
                        self.foreign_object_depth -= 1;
                        if self.foreign_object_depth > 0 {
                            let raw = std::str::from_utf8(end.as_ref()).unwrap_or("").to_string();
                            self.foreign_xml_buffer.push_str("</");
                            self.foreign_xml_buffer.push_str(&raw);
                            self.foreign_xml_buffer.push('>');
                        }
                        // When depth returns to 0, the child root element is closed
                    }
                    Event::Text(text) => {
                        let text_content = parser.extract_text(text).unwrap_or_default();
                        self.foreign_xml_buffer.push_str(&text_content);
                    }
                    Event::Eof => break,
                    _ => {}
                }
                continue;
            }

            match event {
                Event::Start(ref start) | Event::Empty(ref start) => {
                    parser.update_namespaces(start);
                    let (name, ns) = parser.extract_name(start)?;

                    if ns.is_fo() {
                        self.start_element(&name, start, &parser)?;

                        // If it was an empty element, immediately close it
                        if matches!(event, Event::Empty(_)) {
                            self.end_element()?;
                        }
                    } else if self.foreign_object_node.is_some() {
                        // Non-FO element inside instream-foreign-object: capture as raw XML
                        let raw = std::str::from_utf8(start.as_ref())
                            .unwrap_or("")
                            .to_string();
                        self.foreign_xml_buffer.push('<');
                        self.foreign_xml_buffer.push_str(&raw);
                        if matches!(event, Event::Empty(_)) {
                            self.foreign_xml_buffer.push_str("/>");
                        } else {
                            self.foreign_xml_buffer.push('>');
                            self.foreign_object_depth += 1;
                        }
                    }
                }
                Event::End(_) => {
                    if self.foreign_object_node.is_some() && self.foreign_object_depth == 0 {
                        // This End event closes the fo:instream-foreign-object itself
                        self.finalize_foreign_object();
                    }
                    self.end_element()?;
                }
                Event::Text(text) => {
                    let text_content = parser.extract_text(&text)?;
                    let trimmed = text_content.trim();
                    if !trimmed.is_empty() {
                        self.add_text(trimmed)?;
                    }
                }
                Event::CData(cdata) => {
                    // CDATA sections preserve content exactly
                    let cdata_content = parser.extract_cdata(&cdata)?;
                    if !cdata_content.is_empty() {
                        self.add_text(&cdata_content)?;
                    }
                }
                Event::Eof => break,
                _ => {}
            }
        }

        Ok(self.arena)
    }

    /// Finalize the foreign object: store captured XML and clear state
    fn finalize_foreign_object(&mut self) {
        if let Some(node_id) = self.foreign_object_node.take() {
            let xml = std::mem::take(&mut self.foreign_xml_buffer);
            if let Some(node) = self.arena.get_mut(node_id) {
                if let FoNodeData::InstreamForeignObject { foreign_xml, .. } = &mut node.data {
                    *foreign_xml = xml;
                }
            }
        }
    }

    /// Handle start of an element
    fn start_element(
        &mut self,
        name: &str,
        start: &quick_xml::events::BytesStart,
        parser: &XmlParser<impl BufRead>,
    ) -> Result<()> {
        // Create property list (inheritance will be resolved when properties are accessed)
        let mut properties = PropertyList::new();

        // Parse attributes into properties
        let attributes = parser.extract_attributes(start)?;

        // Extract the "id" attribute if present
        let element_id = attributes
            .iter()
            .find(|(k, _)| k == "id")
            .map(|(_, v)| v.clone());

        // Populate properties from attributes
        node_factory::populate_properties(&mut properties, &attributes)?;

        // Validate all properties after parsing
        properties.validate()?;

        // Handle xml:lang on fo:root for document language metadata
        if name == "root" {
            if let Some((_, lang)) = attributes
                .iter()
                .find(|(k, _)| k == "xml:lang" || k == "xml-lang")
            {
                self.arena.document_lang = Some(lang.clone());
            }
        }

        // Create the appropriate FO node
        let node_data = node_factory::create_node_data(name, &attributes, properties)?;
        let node = FoNode::new_with_id(node_data, element_id.clone());
        let node_id = self.arena.add_node(node);

        // Register the ID in the registry if present
        if let Some(id) = element_id {
            self.arena.id_registry_mut().register_id(id, node_id)?;
        }

        // Set up parent-child relationship
        if let Some(parent_id) = self.current_node {
            self.arena
                .append_child(parent_id, node_id)
                .map_err(FopError::Generic)?;
        }

        // If this is an instream-foreign-object, track the node for XML capture
        if name == "instream-foreign-object" {
            self.foreign_object_node = Some(node_id);
            self.foreign_xml_buffer.clear();
            self.foreign_object_depth = 0;
        }

        // Update current node
        self.current_node = Some(node_id);

        Ok(())
    }

    /// Handle end of an element
    fn end_element(&mut self) -> Result<()> {
        if let Some(current) = self.current_node {
            // Move back to parent
            self.current_node = self.arena.get(current).and_then(|n| n.parent);
        }
        Ok(())
    }

    /// Add text content to current node
    fn add_text(&mut self, text: &str) -> Result<()> {
        if let Some(parent_id) = self.current_node {
            // Check if parent can contain text
            if let Some(parent) = self.arena.get(parent_id) {
                if parent.data.can_contain_text() {
                    let text_node = FoNode::new(FoNodeData::Text(text.to_string()));
                    let text_id = self.arena.add_node(text_node);
                    self.arena
                        .append_child(parent_id, text_id)
                        .map_err(FopError::Generic)?;
                }
            }
        }
        Ok(())
    }
}

impl<'a> Default for FoTreeBuilder<'a> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PropertyId;
    use std::io::Cursor;

    #[test]
    fn test_parse_simple_document() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        assert!(!arena.is_empty());
        assert_eq!(arena.len(), 4); // root, layout-master-set, simple-page-master, region-body
    }

    #[test]
    fn test_parse_with_text() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Hello World</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // Should have: root, layout-master-set, simple-page-master, region-body,
        //              page-sequence, flow, block, text
        assert!(arena.len() >= 8);
    }

    #[test]
    fn test_property_parsing() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4" page-width="210mm" page-height="297mm">
            <fo:region-body margin="1in"/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // Check that properties were parsed
        for (_, node) in arena.iter() {
            if let Some(props) = node.data.properties() {
                // Properties should be accessible
                let _ = props.get(PropertyId::PageWidth);
            }
        }
    }

    #[test]
    fn test_parse_document_with_block_and_inline() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>
                <fo:inline font-weight="bold">Bold text</fo:inline>
                Normal text
            </fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // Should have root, layout-master-set, simple-page-master, region-body,
        // page-sequence, flow, block, inline, text nodes
        assert!(arena.len() >= 8);
    }

    #[test]
    fn test_parse_document_with_multiple_blocks() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>First block</fo:block>
            <fo:block>Second block</fo:block>
            <fo:block>Third block</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // At least root, layout-master-set, simple-page-master, region-body,
        // page-sequence, flow, 3 blocks (text nodes may or may not be separate)
        assert!(arena.len() >= 9);
    }

    #[test]
    fn test_parse_document_with_font_properties() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block font-size="14pt" font-family="Arial" color="red">Styled text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(
            result.is_ok(),
            "Should parse document with font properties: {:?}",
            result.err()
        );

        let arena = result.expect("test: should succeed");
        assert!(arena.len() >= 7);
    }

    #[test]
    fn test_parse_document_with_list() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:list-block>
                <fo:list-item>
                    <fo:list-item-label><fo:block>1.</fo:block></fo:list-item-label>
                    <fo:list-item-body><fo:block>Item one</fo:block></fo:list-item-body>
                </fo:list-item>
            </fo:list-block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(
            result.is_ok(),
            "Should parse list structure: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_document_with_cdata() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block><![CDATA[Text with <special> & chars]]></fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        // CDATA sections should be parsed without error
        assert!(
            result.is_ok(),
            "Should parse CDATA sections: {:?}",
            result.err()
        );

        let arena = result.expect("test: should succeed");
        // Find text node with CDATA content
        let has_cdata_text = arena.iter().any(|(_, node)| {
            if let FoNodeData::Text(text) = &node.data {
                text.contains("Text with")
            } else {
                false
            }
        });
        assert!(
            has_cdata_text,
            "CDATA content should be stored as text node"
        );
    }

    #[test]
    fn test_parse_invalid_xml_returns_error() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:unclosed-element>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        // Invalid XML (unclosed element) should return an error
        // (Behavior depends on parser leniency)
        let result = builder.parse(cursor);
        // Just verify it doesn't panic - may succeed or fail
        let _ = result;
    }

    #[test]
    fn test_parse_document_with_multiple_page_sequences() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Page 1 content</fo:block>
        </fo:flow>
    </fo:page-sequence>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Page 2 content</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok(), "Should parse multiple page sequences");
    }

    #[test]
    fn test_parse_document_with_margin_property() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body margin-top="1cm" margin-bottom="2cm"/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok(), "Should parse margin properties");
    }

    #[test]
    fn test_parse_document_with_table() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:table>
                <fo:table-body>
                    <fo:table-row>
                        <fo:table-cell>
                            <fo:block>Cell content</fo:block>
                        </fo:table-cell>
                    </fo:table-row>
                </fo:table-body>
            </fo:table>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(
            result.is_ok(),
            "Should parse table structure: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_document_is_not_empty() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        assert!(!arena.is_empty());
        assert!(!arena.is_empty());
    }

    #[test]
    fn test_parse_preserves_text_content() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Hello World</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // Find the text node
        let text_found = arena
            .iter()
            .any(|(_, node)| matches!(&node.data, FoNodeData::Text(t) if t == "Hello World"));
        assert!(text_found, "Text content should be preserved in tree");
    }

    #[test]
    fn test_parse_document_with_whitespace_only_text_is_trimmed() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let arena = builder.parse(cursor).expect("test: should succeed");

        // Whitespace-only text nodes should be stripped
        let whitespace_only_text = arena.iter().any(|(_, node)| {
            matches!(&node.data, FoNodeData::Text(t) if t.trim().is_empty() && !t.is_empty())
        });
        assert!(
            !whitespace_only_text,
            "Whitespace-only text nodes should be stripped"
        );
    }

    #[test]
    fn test_parse_document_with_processing_instruction() {
        let xml = r#"<?xml version="1.0"?>
<?fop-processor key="value"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        // Processing instructions should not cause parse errors
        assert!(
            result.is_ok(),
            "Processing instructions should be handled gracefully"
        );
    }

    #[test]
    fn test_parse_document_with_xml_comment() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <!-- This is a comment -->
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <!-- Page master comment -->
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok(), "XML comments should be handled gracefully");
    }

    #[test]
    fn test_parse_font_size_in_pts() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block font-size="16pt">Large text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok());

        let arena = result.expect("test: should succeed");
        // Find the block node and verify its font-size
        for (_, node) in arena.iter() {
            if let FoNodeData::Block { properties } = &node.data {
                if properties.is_explicit(PropertyId::FontSize) {
                    let font_size = properties
                        .get(PropertyId::FontSize)
                        .expect("test: should succeed");
                    if let Some(length) = font_size.as_length() {
                        assert_eq!(length.to_pt(), 16.0);
                    }
                }
            }
        }
    }

    #[test]
    fn test_parse_color_property_red() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block color="red">Red text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok(), "Should parse color properties");
    }

    #[test]
    fn test_parse_hex_color_property() {
        // Use rgb() format to avoid issues with # in raw strings
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block color="red">Hex red text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;

        let cursor = Cursor::new(xml);
        let builder = FoTreeBuilder::new();
        let result = builder.parse(cursor);
        assert!(result.is_ok(), "Should parse color properties");
    }
}

// ===== ADDITIONAL TESTS (new tests for builder) =====
#[cfg(test)]
mod additional_tests {
    use super::*;
    use std::io::Cursor;

    fn make_minimal_fo(flow_content: &str) -> String {
        format!(
            r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            {}
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#,
            flow_content
        )
    }

    #[test]
    fn test_parse_block_with_all_font_properties() {
        let xml = make_minimal_fo(
            r#"<fo:block font-size="14pt" font-weight="bold" font-style="italic"
                font-family="Times New Roman" color="navy">Styled text</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(
            result.is_ok(),
            "Font properties should parse: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_block_with_margin_properties() {
        let xml = make_minimal_fo(
            r#"<fo:block margin-top="10pt" margin-bottom="10pt"
                margin-left="20pt" margin-right="20pt">Margins</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Margin properties: {:?}", result.err());
    }

    #[test]
    fn test_parse_block_with_padding_properties() {
        let xml = make_minimal_fo(
            r#"<fo:block padding-top="5pt" padding-bottom="5pt"
                padding-left="10pt" padding-right="10pt">Padding</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Padding properties: {:?}", result.err());
    }

    #[test]
    fn test_parse_block_with_border_properties() {
        let xml = make_minimal_fo(
            r#"<fo:block border-top-style="solid" border-top-width="1pt"
                border-top-color="black">Border</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Border properties: {:?}", result.err());
    }

    #[test]
    fn test_parse_inline_elements() {
        let xml = make_minimal_fo(
            r#"<fo:block>Text with <fo:inline font-weight="bold">bold</fo:inline> part</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Inline element: {:?}", result.err());
    }

    #[test]
    fn test_parse_nested_blocks() {
        let xml = make_minimal_fo(
            r#"<fo:block>
                <fo:block>Inner block 1</fo:block>
                <fo:block>Inner block 2</fo:block>
                <fo:block>Inner block 3</fo:block>
            </fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Nested blocks: {:?}", result.err());
    }

    #[test]
    fn test_parse_table_structure() {
        let xml = make_minimal_fo(
            r#"<fo:table>
                <fo:table-column column-width="50pt"/>
                <fo:table-column column-width="50pt"/>
                <fo:table-body>
                    <fo:table-row>
                        <fo:table-cell><fo:block>Cell 1</fo:block></fo:table-cell>
                        <fo:table-cell><fo:block>Cell 2</fo:block></fo:table-cell>
                    </fo:table-row>
                </fo:table-body>
            </fo:table>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Table structure: {:?}", result.err());
    }

    #[test]
    fn test_parse_list_structure() {
        let xml = make_minimal_fo(
            r#"<fo:list-block>
                <fo:list-item>
                    <fo:list-item-label end-indent="label-end()">
                        <fo:block>1.</fo:block>
                    </fo:list-item-label>
                    <fo:list-item-body start-indent="body-start()">
                        <fo:block>First item</fo:block>
                    </fo:list-item-body>
                </fo:list-item>
            </fo:list-block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "List structure: {:?}", result.err());
    }

    #[test]
    fn test_parse_external_graphic() {
        let xml = make_minimal_fo(
            r#"<fo:block><fo:external-graphic src="url('image.png')"/></fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "External graphic: {:?}", result.err());
    }

    #[test]
    fn test_parse_basic_link_internal() {
        let xml = make_minimal_fo(
            r#"<fo:block>
                <fo:basic-link internal-destination="target">Link</fo:basic-link>
            </fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Basic link internal: {:?}", result.err());
    }

    #[test]
    fn test_parse_basic_link_external() {
        let xml = make_minimal_fo(
            r#"<fo:block>
                <fo:basic-link external-destination="url('https://example.com')">URL</fo:basic-link>
            </fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Basic link external: {:?}", result.err());
    }

    #[test]
    fn test_parse_page_number_inline() {
        let xml = make_minimal_fo(r#"<fo:block>Page <fo:page-number/></fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Page number: {:?}", result.err());
    }

    #[test]
    fn test_parse_page_number_citation() {
        let xml = make_minimal_fo(
            r#"<fo:block>See page <fo:page-number-citation ref-id="target"/></fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Page number citation: {:?}", result.err());
    }

    #[test]
    fn test_parse_leader_dots() {
        let xml =
            make_minimal_fo(r#"<fo:block>Chapter<fo:leader leader-pattern="dots"/>10</fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Leader: {:?}", result.err());
    }

    #[test]
    fn test_parse_footnote() {
        let xml = make_minimal_fo(
            r#"<fo:block>Text<fo:footnote>
                <fo:inline font-size="8pt" vertical-align="super">1</fo:inline>
                <fo:footnote-body>
                    <fo:block font-size="8pt">Footnote text</fo:block>
                </fo:footnote-body>
            </fo:footnote></fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Footnote: {:?}", result.err());
    }

    #[test]
    fn test_parse_block_container() {
        let xml = make_minimal_fo(
            r#"<fo:block-container width="100pt" height="100pt">
                <fo:block>Inside block container</fo:block>
            </fo:block-container>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Block container: {:?}", result.err());
    }

    #[test]
    fn test_parse_bookmark_tree() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:bookmark-tree>
        <fo:bookmark internal-destination="ch1">
            <fo:bookmark-title>Chapter 1</fo:bookmark-title>
        </fo:bookmark>
    </fo:bookmark-tree>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block id="ch1">Chapter 1 content</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Bookmark tree: {:?}", result.err());
    }

    #[test]
    fn test_parse_document_with_static_content() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-before extent="20mm"/>
            <fo:region-body/>
            <fo:region-after extent="20mm"/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:static-content flow-name="xsl-region-before">
            <fo:block>Header text</fo:block>
        </fo:static-content>
        <fo:static-content flow-name="xsl-region-after">
            <fo:block>Footer text</fo:block>
        </fo:static-content>
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Body content</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "Static content: {:?}", result.err());
    }

    #[test]
    fn test_parse_document_returns_non_empty_arena() {
        let xml = make_minimal_fo("<fo:block>Content</fo:block>");
        let cursor = Cursor::new(xml);
        let arena = FoTreeBuilder::new()
            .parse(cursor)
            .expect("test: should succeed");
        assert!(!arena.is_empty(), "Arena should not be empty after parsing");
    }

    #[test]
    fn test_parse_document_root_is_fo_root() {
        let xml = make_minimal_fo("<fo:block>Content</fo:block>");
        let cursor = Cursor::new(xml);
        let arena = FoTreeBuilder::new()
            .parse(cursor)
            .expect("test: should succeed");
        let (_, root_node) = arena.root().expect("Should have root node");
        assert!(matches!(root_node.data, FoNodeData::Root));
    }

    #[test]
    fn test_parse_document_with_text_align_center() {
        let xml = make_minimal_fo(r#"<fo:block text-align="center">Centered</fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "text-align center: {:?}", result.err());
    }

    #[test]
    fn test_parse_document_with_text_align_justify() {
        let xml = make_minimal_fo(r#"<fo:block text-align="justify">Justified</fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "text-align justify: {:?}", result.err());
    }

    #[test]
    fn test_parse_line_height_property() {
        let xml = make_minimal_fo(r#"<fo:block line-height="1.5">Text</fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "line-height: {:?}", result.err());
    }

    #[test]
    fn test_parse_keep_together_property() {
        let xml = make_minimal_fo(
            r#"<fo:block keep-together.within-page="always">Kept together</fo:block>"#,
        );
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "keep-together: {:?}", result.err());
    }

    #[test]
    fn test_parse_background_color_property() {
        let xml = make_minimal_fo(r#"<fo:block background-color="yellow">Highlighted</fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "background-color: {:?}", result.err());
    }

    #[test]
    fn test_parse_multiple_page_sequences_with_content() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Page sequence 1</fo:block>
        </fo:flow>
    </fo:page-sequence>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Page sequence 2</fo:block>
        </fo:flow>
    </fo:page-sequence>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Page sequence 3</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(
            result.is_ok(),
            "Multiple page sequences: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_missing_flow_name_is_error() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow>
            <fo:block>No flow-name attribute</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_err(), "Missing flow-name should be an error");
    }

    #[test]
    fn test_parse_missing_master_name_is_error() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
        <fo:simple-page-master>
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>Text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_err(), "Missing master-name should be an error");
    }

    #[test]
    fn test_parse_xml_lang_sets_document_lang() {
        let xml = r#"<?xml version="1.0"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xml:lang="en">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4">
            <fo:region-body/>
        </fo:simple-page-master>
    </fo:layout-master-set>
    <fo:page-sequence master-reference="A4">
        <fo:flow flow-name="xsl-region-body">
            <fo:block>English text</fo:block>
        </fo:flow>
    </fo:page-sequence>
</fo:root>"#;
        let cursor = Cursor::new(xml);
        let arena = FoTreeBuilder::new()
            .parse(cursor)
            .expect("test: should succeed");
        assert_eq!(arena.document_lang, Some("en".to_string()));
    }

    #[test]
    fn test_parse_document_without_lang_has_none() {
        let xml = make_minimal_fo("<fo:block>Text</fo:block>");
        let cursor = Cursor::new(xml);
        let arena = FoTreeBuilder::new()
            .parse(cursor)
            .expect("test: should succeed");
        assert!(arena.document_lang.is_none());
    }

    #[test]
    fn test_parse_cdata_in_block() {
        let xml = make_minimal_fo(r#"<fo:block><![CDATA[<special> & content]]></fo:block>"#);
        let cursor = Cursor::new(xml);
        let result = FoTreeBuilder::new().parse(cursor);
        assert!(result.is_ok(), "CDATA in block: {:?}", result.err());
    }
}