-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDocumentSession.java
More file actions
1279 lines (1187 loc) · 50.6 KB
/
Copy pathDocumentSession.java
File metadata and controls
1279 lines (1187 loc) · 50.6 KB
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
package com.demcha.compose.document.api;
import com.demcha.compose.GraphCompose;
import com.demcha.compose.document.backend.fixed.FixedLayoutBackend;
import com.demcha.compose.document.backend.fixed.pdf.PdfFixedLayoutBackend;
import com.demcha.compose.document.backend.fixed.pdf.PdfMeasurementResources;
import com.demcha.compose.document.backend.fixed.pdf.options.PdfHeaderFooterOptions;
import com.demcha.compose.document.backend.fixed.pdf.options.PdfMetadataOptions;
import com.demcha.compose.document.backend.fixed.pdf.options.PdfProtectionOptions;
import com.demcha.compose.document.backend.fixed.pdf.options.PdfWatermarkOptions;
import com.demcha.compose.document.backend.semantic.SemanticBackend;
import com.demcha.compose.document.debug.snapshot.LayoutGraphSnapshotExtractor;
import com.demcha.compose.document.debug.snapshot.PageIndexExtractor;
import com.demcha.compose.document.dsl.DocumentDsl;
import com.demcha.compose.document.dsl.PageFlowBuilder;
import com.demcha.compose.document.exceptions.DocumentRenderingException;
import com.demcha.compose.document.layout.*;
import com.demcha.compose.document.node.ContainerNode;
import com.demcha.compose.document.node.DocumentNode;
import com.demcha.compose.document.node.PageReferenceNode;
import com.demcha.compose.document.output.*;
import com.demcha.compose.document.snapshot.LayoutSnapshot;
import com.demcha.compose.document.snapshot.PageIndex;
import com.demcha.compose.document.style.DocumentColor;
import com.demcha.compose.document.style.DocumentInsets;
import com.demcha.compose.font.FontFamilyDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Mutable semantic document session used by the canonical GraphCompose
* session-first API.
*
* <p>A session owns one document graph, the measurement services required to
* prepare that graph, cached layout/render artifacts, and the fluent DSL facade
* exposed through {@link #dsl()}.</p>
*
* <p>The typical lifecycle is:</p>
* <ol>
* <li>configure the session through {@link GraphCompose#document()} and this type's mutators</li>
* <li>author content with {@link #pageFlow()}, {@link #compose(Consumer)}, {@link #dsl()},
* or by adding low-level {@link DocumentNode}s directly</li>
* <li>inspect {@link #layoutGraph()} / {@link #layoutSnapshot()} as needed</li>
* <li>render with {@link #writePdf(OutputStream)}, {@link #toPdfBytes()}, {@link #buildPdf()},
* or a custom backend</li>
* </ol>
*
* <p><b>Thread-safety:</b> this type is mutable and not thread-safe.</p>
*
* @author Artem Demchyshyn
* @since 1.0.0
*/
public final class DocumentSession implements AutoCloseable {
private static final Logger LIFECYCLE_LOG = LoggerFactory.getLogger("com.demcha.compose.document.lifecycle");
/**
* Cap on page-reference recompiles after the first resolve. A table of
* contents converges in one recompile; the cap bounds a pathological document
* whose numbers keep shifting pages, falling back to the last layout.
*/
private static final int MAX_PAGE_REFERENCE_PASSES = 5;
private final String sessionId = Integer.toHexString(System.identityHashCode(this));
private final Path defaultOutputFile;
private final NodeRegistry registry;
private final LayoutCompiler compiler;
private final List<DocumentNode> roots = new ArrayList<>();
private final List<FontFamilyDefinition> customFontFamilies = new ArrayList<>();
private final DocumentChromeOptions chromeOptions = new DocumentChromeOptions();
private final DocumentLayoutCache layoutCache = new DocumentLayoutCache();
private final DocumentRenderingFacade renderingFacade = new DocumentRenderingFacade(new RenderingContextImpl());
private DocumentPageSize pageSize;
private DocumentInsets margin;
private LayoutCanvas canvas;
private boolean markdown;
private DocumentDebugOptions debug = DocumentDebugOptions.none();
private List<PageBackgroundFill> pageBackgrounds = List.of();
private PdfMeasurementResources measurementResources;
private boolean closed;
/**
* Creates a canonical document session.
*
* @param defaultOutputFile optional default PDF output path
* @param pageSize physical page size
* @param margin page margin
* @param customFontFamilies document-local font families
* @param markdown whether markdown parsing is enabled
* @param guideLines whether PDF guide-line overlays are enabled
*/
public DocumentSession(Path defaultOutputFile,
DocumentPageSize pageSize,
DocumentInsets margin,
Collection<FontFamilyDefinition> customFontFamilies,
boolean markdown,
boolean guideLines) {
this.defaultOutputFile = defaultOutputFile;
this.pageSize = Objects.requireNonNull(pageSize, "pageSize");
this.margin = margin == null ? DocumentInsets.zero() : requireNonNegativePageMargin(margin);
this.canvas = LayoutCanvas.from(pageSize.width(), pageSize.height(), toEngineMargin(this.margin));
this.markdown = markdown;
this.debug = DocumentDebugOptions.none().withGuides(guideLines);
this.registry = BuiltInNodeDefinitions.registerDefaults(new InvalidatingNodeRegistry());
this.compiler = new LayoutCompiler(registry);
this.customFontFamilies.addAll(List.copyOf(customFontFamilies));
refreshMeasurementServices();
LIFECYCLE_LOG.debug(
"document.session.created sessionId={} outputConfigured={} pageSize={}x{} customFontFamilies={} markdown={} guideLines={}",
sessionId,
defaultOutputFile != null,
Math.round(pageSize.width()),
Math.round(pageSize.height()),
this.customFontFamilies.size(),
markdown,
guideLines);
}
/**
* Runs a PDF convenience body and unifies the cross-cutting checked-exception
* wrapping: any underlying {@link Exception} is rewrapped as
* {@link DocumentRenderingException} with the supplied {@code action} fragment.
* {@link RuntimeException}s pass through unchanged so existing callers that
* already catch them keep their semantics.
*/
private static <R> R wrapPdfRendering(String action, PdfRenderingBody<R> body) throws DocumentRenderingException {
try {
return body.run();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new DocumentRenderingException("Failed to " + action + ": " + e.getMessage(), e);
}
}
/**
* Image-rendering analogue of {@link #wrapPdfRendering}: rewraps any
* underlying checked {@link Exception} as {@link DocumentRenderingException}
* while letting {@link RuntimeException}s (e.g. argument/state validation)
* propagate unchanged.
*/
private static <R> R wrapImageRendering(String action, ImageRenderingBody<R> body) throws DocumentRenderingException {
try {
return body.run();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new DocumentRenderingException("Failed to " + action + ": " + e.getMessage(), e);
}
}
/**
* Returns the fluent semantic DSL facade bound to this session.
*
* @return a new DSL facade for authoring roots and semantic nodes
* @throws IllegalStateException if this session has already been closed
*/
public DocumentDsl dsl() {
ensureOpen();
return new DocumentDsl(this);
}
/**
* Alias for {@link #dsl()} for callers that prefer a builder-oriented name.
*
* @return a new DSL facade for authoring roots and semantic nodes
* @throws IllegalStateException if this session has already been closed
* @deprecated since 1.6.0; prefer {@link #dsl()}. Carrying two names for
* the same operation on the session facade adds maintenance
* cost without clarity. Scheduled for removal in v2.0.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentDsl builder() {
return dsl();
}
/**
* Applies a batch of canonical DSL authoring calls to this session.
*
* <p>This is useful when the calling code wants one high-level authoring
* block without manually keeping a {@link DocumentDsl} reference.</p>
*
* @param spec callback that receives a live DSL facade
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession compose(Consumer<DocumentDsl> spec) {
ensureOpen();
long startNanos = System.nanoTime();
LIFECYCLE_LOG.debug("document.compose.start sessionId={} revision={} roots={}", sessionId, layoutCache.revision(), roots.size());
try {
Objects.requireNonNull(spec, "spec").accept(dsl());
LIFECYCLE_LOG.debug("document.compose.end sessionId={} revision={} roots={} durationMs={}", sessionId, layoutCache.revision(), roots.size(), elapsedMillis(startNanos));
return this;
} catch (RuntimeException | Error ex) {
LIFECYCLE_LOG.debug("document.compose.failed sessionId={} revision={} roots={} errorType={}", sessionId, layoutCache.revision(), roots.size(), ex.getClass().getSimpleName());
throw ex;
}
}
/**
* Starts a root page-flow builder bound to this session.
*
* <p>This is the recommended high-level entrypoint for the common
* compose-first authoring path.</p>
*
* @return a root flow builder that attaches to this session when built
* @throws IllegalStateException if this session has already been closed
*/
public PageFlowBuilder pageFlow() {
return dsl().pageFlow();
}
/**
* Configures, builds, and attaches one root page flow in a single call.
*
* @param spec callback that configures the root flow
* @return the built root container node
* @throws IllegalStateException if this session has already been closed
*/
public ContainerNode pageFlow(Consumer<PageFlowBuilder> spec) {
return dsl().pageFlow(spec);
}
/**
* Adds one semantic root node to the session.
*
* @param node root or detached semantic node to append
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession add(DocumentNode node) {
ensureOpen();
roots.add(Objects.requireNonNull(node, "node"));
invalidate();
return this;
}
/**
* Adds multiple semantic root nodes in iteration order.
*
* @param nodes semantic nodes to append
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession addAll(Collection<? extends DocumentNode> nodes) {
ensureOpen();
for (DocumentNode node : nodes) {
add(node);
}
return this;
}
/**
* Removes all registered roots and invalidates cached layout/render state.
*
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession clear() {
ensureOpen();
roots.clear();
invalidate();
return this;
}
/**
* Updates the physical page size for subsequent layout passes.
*
* @param pageSize target page size
* @return this session
*/
public DocumentSession pageSize(DocumentPageSize pageSize) {
ensureOpen();
this.pageSize = Objects.requireNonNull(pageSize, "pageSize");
this.canvas = LayoutCanvas.from(this.pageSize.width(), this.pageSize.height(), toEngineMargin(margin));
invalidate();
return this;
}
/**
* Updates the physical page size from point dimensions.
*
* @param width page width in points
* @param height page height in points
* @return this session
*/
public DocumentSession pageSize(double width, double height) {
return pageSize(DocumentPageSize.of(width, height));
}
/**
* Updates the outer document margin using the public canonical spacing value.
*
* @param margin new canvas margin, or {@code null} to reset to zero
* @return this session
* @throws IllegalStateException if this session has already been closed
* @throws IllegalArgumentException if any margin component is negative — a
* negative page margin overflows the sheet;
* use a node's {@code bleed(...)} instead
*/
public DocumentSession margin(DocumentInsets margin) {
ensureOpen();
this.margin = margin == null ? DocumentInsets.zero() : requireNonNegativePageMargin(margin);
this.canvas = LayoutCanvas.from(pageSize.width(), pageSize.height(), toEngineMargin(this.margin));
invalidate();
return this;
}
/**
* Rejects a negative page margin. Unlike a node margin (where a negative
* value is a valid overlap / inset trick), a negative page margin makes the
* content area larger than the page, so content silently overflows the sheet.
* To draw content past the page edge, use a node's {@code bleed(...)} instead.
*
* @param margin the requested page margin
* @return {@code margin} when every component is non-negative
* @throws IllegalArgumentException if any component is negative
*/
private static DocumentInsets requireNonNegativePageMargin(DocumentInsets margin) {
if (margin.top() < 0 || margin.right() < 0 || margin.bottom() < 0 || margin.left() < 0) {
throw new IllegalArgumentException(
"page margin must be non-negative: " + margin
+ " — use a node's bleed(...) to extend content past the page edge");
}
return margin;
}
/**
* Enables or disables markdown parsing for semantic paragraph blocks.
*
* @param enabled {@code true} to render paragraph content with markdown-aware spans
* @return this session
*/
public DocumentSession markdown(boolean enabled) {
ensureOpen();
this.markdown = enabled;
invalidate();
return this;
}
/**
* Enables or disables PDF guide-line overlays for convenience PDF output.
*
* <p>This option affects {@link #buildPdf()}, {@link #writePdf(OutputStream)},
* and {@link #toPdfBytes()}. It does not change the semantic layout graph,
* so existing layout cache entries remain valid.</p>
*
* <p>Shorthand for toggling only the guide overlay on the current
* {@link #debug(DocumentDebugOptions) debug} configuration; node-label
* settings are preserved.</p>
*
* @param enabled {@code true} to draw debug guide-line overlays
* @return this session
*/
public DocumentSession guideLines(boolean enabled) {
ensureOpen();
this.debug = this.debug.withGuides(enabled);
return this;
}
/**
* Configures PDF debug overlays (guide lines and semantic node labels)
* for convenience PDF output.
*
* <p>This option affects {@link #buildPdf()}, {@link #writePdf(OutputStream)},
* and {@link #toPdfBytes()}. Debug overlays draw on top of regular content
* and never participate in measurement or pagination, so the semantic
* layout graph and existing layout cache entries remain valid.</p>
*
* <p>Node labels print each node's stable semantic path — the same path
* reported by {@link #layoutSnapshot()} — so a misplaced block on the
* sheet can be traced straight back to the builder call that authored
* it.</p>
*
* @param options debug overlay options; {@code null} disables all overlays
* @return this session
* @since 1.8.0
*/
public DocumentSession debug(DocumentDebugOptions options) {
ensureOpen();
this.debug = options == null ? DocumentDebugOptions.none() : options;
return this;
}
/**
* Configures a document-wide page background fill applied behind every
* fragment on every page.
*
* <p>Use this for cinematic looks (cream paper, deep navy hero documents,
* etc.) without having to wrap every section in a stack and shape. Pass
* {@code null} to clear the background.</p>
*
* @param color page background color, or {@code null} to clear
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession pageBackground(DocumentColor color) {
ensureOpen();
this.pageBackgrounds = color == null
? List.of()
: List.of(PageBackgroundFill.fullPage(color));
invalidate();
return this;
}
/**
* Convenience overload that accepts a {@link Color} value.
*
* @param color page background color, or {@code null} to clear
* @return this session
*/
public DocumentSession pageBackground(Color color) {
return pageBackground(color == null ? null : DocumentColor.of(color));
}
/**
* Configures one or more rectangular background fills applied behind
* every fragment on every page. Each fill is defined as a fraction of
* the canvas (see {@link PageBackgroundFill}), so the layout works
* across page sizes. Use this for multi-column page chrome — a pale
* sidebar column plus a white main column, accent stripes, etc. —
* that should repeat automatically when content paginates onto a new
* page.
*
* <p>Pass {@code null} or an empty list to clear. Fills paint in list
* order; later entries paint on top of earlier ones where they
* overlap.</p>
*
* @param fills ordered list of fills, or {@code null}/empty to clear
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession pageBackgrounds(List<PageBackgroundFill> fills) {
ensureOpen();
this.pageBackgrounds = fills == null ? List.of() : List.copyOf(fills);
invalidate();
return this;
}
/**
* Returns a fluent facade for chrome configuration (metadata,
* watermark, protection, header, footer). The facade is a thin
* grouping of the canonical chrome methods on this session — both
* styles set the same underlying chrome state.
*
* <p>Example:</p>
* <pre>{@code
* session.chrome()
* .metadata(DocumentMetadata.builder().title("Q1").build())
* .watermark(DocumentWatermark.builder().text("DRAFT").build());
* }</pre>
*
* <p>Use {@link SessionChromeApi#session()} to chain back to the
* session if you need to mix chrome and authoring calls in a single
* fluent expression.</p>
*
* @return chrome configuration facade for this session
* @throws IllegalStateException if this session has already been closed
* @since 1.6.0
*/
public SessionChromeApi chrome() {
ensureOpen();
return new SessionChromeApi(this, chromeOptions);
}
/**
* Configures backend-neutral document metadata applied by every output
* backend that supports it (PDF and DOCX in v1.3). Pass {@code null} to
* clear.
*
* @param metadata canonical metadata, or {@code null} to clear
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession metadata(DocumentMetadata metadata) {
ensureOpen();
chromeOptions.setMetadata(metadata);
return this;
}
/**
* @param options legacy PDF metadata options, or {@code null} to clear
* @return this session
* @deprecated since 1.6.0, removal in v2.0; prefer the canonical
* {@link #metadata(DocumentMetadata)}.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentSession metadata(PdfMetadataOptions options) {
ensureOpen();
chromeOptions.setMetadata(options);
return this;
}
/**
* Configures a backend-neutral document-wide watermark. Pass {@code null}
* to clear.
*
* @param watermark canonical watermark, or {@code null} to clear
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession watermark(DocumentWatermark watermark) {
ensureOpen();
chromeOptions.setWatermark(watermark);
return this;
}
/**
* @param options legacy PDF watermark options, or {@code null} to clear
* @return this session
* @deprecated since 1.6.0, removal in v2.0; prefer the canonical
* {@link #watermark(DocumentWatermark)}.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentSession watermark(PdfWatermarkOptions options) {
ensureOpen();
chromeOptions.setWatermark(options);
return this;
}
/**
* Configures backend-neutral document protection (passwords and
* permissions). Pass {@code null} to clear.
*
* @param protection canonical protection, or {@code null} to clear
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession protect(DocumentProtection protection) {
ensureOpen();
chromeOptions.setProtection(protection);
return this;
}
/**
* @param options legacy PDF protection options, or {@code null} to clear
* @return this session
* @deprecated since 1.6.0, removal in v2.0; prefer the canonical
* {@link #protect(DocumentProtection)}.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentSession protect(PdfProtectionOptions options) {
ensureOpen();
chromeOptions.setProtection(options);
return this;
}
/**
* Registers a backend-neutral repeating page header.
*
* @param header header options
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession header(DocumentHeaderFooter header) {
ensureOpen();
chromeOptions.addHeader(header);
return this;
}
/**
* @param options legacy PDF header/footer options
* @return this session
* @deprecated since 1.6.0, removal in v2.0; prefer the canonical
* {@link #header(DocumentHeaderFooter)}.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentSession header(PdfHeaderFooterOptions options) {
ensureOpen();
chromeOptions.addHeader(options);
return this;
}
/**
* Registers a backend-neutral repeating page footer.
*
* @param footer footer options
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession footer(DocumentHeaderFooter footer) {
ensureOpen();
chromeOptions.addFooter(footer);
return this;
}
/**
* @param options legacy PDF header/footer options
* @return this session
* @deprecated since 1.6.0, removal in v2.0; prefer the canonical
* {@link #footer(DocumentHeaderFooter)}.
*/
@Deprecated(since = "1.6.0", forRemoval = true)
public DocumentSession footer(PdfHeaderFooterOptions options) {
ensureOpen();
chromeOptions.addFooter(options);
return this;
}
/**
* Removes all previously registered headers and footers from this session.
*
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public DocumentSession clearHeadersAndFooters() {
ensureOpen();
chromeOptions.clearHeadersAndFooters();
return this;
}
/**
* Registers a document-local font family for text measurement and PDF rendering.
*
* @param definition custom font family definition
* @return this session
*/
public DocumentSession registerFontFamily(FontFamilyDefinition definition) {
ensureOpen();
customFontFamilies.add(Objects.requireNonNull(definition, "definition"));
refreshMeasurementServices();
invalidate();
return this;
}
/**
* Registers a custom semantic node definition. Equivalent to
* {@code session.registry().register(definition)} — the layout
* cache is invalidated either way (the registry returned by
* {@link #registry()} is a session-owned wrapper that funnels
* mutations through {@code invalidate()} since v1.6.7).
*
* @param definition node definition implementation
* @param <E> semantic node type handled by the definition
* @return this session
* @throws IllegalStateException if this session has already been closed
*/
public <E extends DocumentNode> DocumentSession registerNodeDefinition(NodeDefinition<E> definition) {
ensureOpen();
registry.register(Objects.requireNonNull(definition, "definition"));
return this;
}
/**
* Returns a fluent facade for document-local font and node-extension
* registration. The facade is a thin grouping of
* {@link #registerFontFamily(FontFamilyDefinition)} and
* {@link #registerNodeDefinition(NodeDefinition)} — both styles mutate
* the same underlying state.
*
* @return font + extension registration facade for this session
* @throws IllegalStateException if this session has already been closed
* @since 1.6.0
*/
public SessionFontApi fonts() {
ensureOpen();
return new SessionFontApi(this);
}
/**
* Returns a fluent facade for read-only layout inspection. The
* facade is a thin grouping of {@link #layoutGraph()},
* {@link #documentGraph()}, {@link #roots()}, {@link #canvas()},
* {@link #registry()}, and {@link #layoutSnapshot()} — both styles
* read the same underlying state.
*
* <p>Example:</p>
* <pre>{@code
* LayoutGraph graph = session.layout().graph();
* LayoutSnapshot snap = session.layout().snapshot();
* }</pre>
*
* @return layout-inspection facade for this session
* @since 1.6.0
*/
public SessionLayoutApi layout() {
return new SessionLayoutApi(this);
}
/**
* Returns the live node registry backing this session. The returned
* instance is a session-owned subclass of {@link NodeRegistry} (since
* v1.6.7); calling {@link NodeRegistry#register(NodeDefinition)} on it
* mutates the registry <em>and</em> invalidates the layout cache, so it
* is interchangeable with {@link #registerNodeDefinition(NodeDefinition)}.
* Read-only access via {@link NodeRegistry#definitionFor(DocumentNode)}
* is unaffected.
*
* @return live node registry (invalidates layout cache on mutation)
*/
public NodeRegistry registry() {
return registry;
}
/**
* Returns an immutable snapshot of the current semantic root graph.
*
* @return document graph snapshot
*/
public DocumentGraph documentGraph() {
return new DocumentGraph(List.copyOf(roots));
}
/**
* Returns the current semantic layout canvas derived from page size and margin.
*
* @return current layout canvas
*/
public LayoutCanvas canvas() {
return canvas;
}
/**
* Returns the usable content height of the page in points — the page height
* minus the top and bottom margins. Convenience alias for
* {@code canvas().innerHeight()}: the value a composition reads to decide how
* much vertical space a section, sidebar, or spacer may fill.
*
* @return the inner (content) height of the current page canvas, in points
* @since 1.7.0
*/
public double availableHeight() {
return canvas().innerHeight();
}
/**
* Returns an immutable copy of the current semantic roots.
*
* @return semantic root nodes in insertion order
*/
public List<DocumentNode> roots() {
return List.copyOf(roots);
}
/**
* Compiles the semantic graph into a resolved, paginated layout graph.
*
* @return cached or freshly compiled layout graph
*/
public LayoutGraph layoutGraph() {
ensureOpen();
long revision = layoutCache.revision();
if (layoutCache.isLayoutCached()) {
LayoutGraph cached = layoutCache.layout(() -> {
throw new IllegalStateException("Cache miss after isLayoutCached() returned true.");
});
LIFECYCLE_LOG.debug("document.layout.cache.hit sessionId={} revision={} roots={} pages={} nodes={} fragments={}", sessionId, revision, roots.size(), cached.totalPages(), cached.nodes().size(), cached.fragments().size());
return cached;
}
long startNanos = System.nanoTime();
LIFECYCLE_LOG.debug("document.layout.start sessionId={} revision={} roots={}", sessionId, revision, roots.size());
try {
LayoutGraph computed = layoutCache.layout(this::computeLayout);
LIFECYCLE_LOG.debug("document.layout.end sessionId={} revision={} roots={} pages={} nodes={} fragments={} durationMs={}", sessionId, revision, roots.size(), computed.totalPages(), computed.nodes().size(), computed.fragments().size(), elapsedMillis(startNanos));
return computed;
} catch (RuntimeException ex) {
LIFECYCLE_LOG.warn("document.layout.failed sessionId={} revision={} roots={} errorType={}", sessionId, revision, roots.size(), ex.getClass().getSimpleName());
throw ex;
}
}
/**
* Compiles the semantic graph for one layout revision. A document that
* contains a {@link PageReferenceNode} is compiled in two passes — the first
* resolves every anchor's page, the next renders the references with the
* resolved numbers — then re-resolved to a fixed point: if rendering the
* numbers shifted any anchor's page (a reference whose own width re-wrapped a
* neighbour and pushed content across a boundary), it recompiles with the new
* numbers until the pages stop moving, capped at {@link #MAX_PAGE_REFERENCE_PASSES}
* recompiles. All passes run inside the cache compute, so the result is cached
* once per revision. Documents without a page reference compile once and are
* byte-identical to before.
*/
private LayoutGraph computeLayout() {
LayoutGraph graph = compilePass(Map.of());
if (!containsPageReference(roots)) {
return DocumentPageBackgrounds.apply(graph, pageBackgrounds);
}
Map<String, Integer> resolved = resolvedPageNumbers(graph);
for (int pass = 0; pass < MAX_PAGE_REFERENCE_PASSES; pass++) {
graph = compilePass(resolved);
Map<String, Integer> rendered = resolvedPageNumbers(graph);
if (rendered.equals(resolved)) {
return DocumentPageBackgrounds.apply(graph, pageBackgrounds);
}
resolved = rendered;
}
LIFECYCLE_LOG.debug("document.layout.pageReference.unconverged sessionId={} passes={}", sessionId, MAX_PAGE_REFERENCE_PASSES);
return DocumentPageBackgrounds.apply(graph, pageBackgrounds);
}
private LayoutGraph compilePass(Map<String, Integer> resolvedPages) {
DocumentLayoutPassContext context = new DocumentLayoutPassContext(registry, canvas,
measurementResources.fontLibrary(), measurementResources.textMeasurementSystem(), markdown, resolvedPages);
return compiler.compile(documentGraph(), context, context);
}
private static boolean containsPageReference(List<DocumentNode> nodes) {
for (DocumentNode node : nodes) {
if (node instanceof PageReferenceNode || containsPageReference(node.children())) {
return true;
}
}
return false;
}
private static Map<String, Integer> resolvedPageNumbers(LayoutGraph graph) {
Map<String, Integer> pages = new HashMap<>();
PageIndexExtractor.from(graph).all().forEach((anchor, reference) -> pages.put(anchor, reference.pageNumber()));
return pages;
}
/**
* Extracts the current deterministic layout snapshot used by regression tests.
*
* @return layout snapshot derived from the current layout graph
*/
public LayoutSnapshot layoutSnapshot() {
ensureOpen();
long revision = layoutCache.revision();
if (layoutCache.isSnapshotCached()) {
LayoutSnapshot cached = layoutCache.snapshot(() -> {
throw new IllegalStateException("Snapshot cache miss after isSnapshotCached() returned true.");
});
LIFECYCLE_LOG.debug("document.layoutSnapshot.cache.hit sessionId={} revision={} roots={}", sessionId, revision, roots.size());
return cached;
}
long startNanos = System.nanoTime();
LIFECYCLE_LOG.debug("document.layoutSnapshot.start sessionId={} revision={} roots={}", sessionId, revision, roots.size());
LayoutSnapshot computed = layoutCache.snapshot(() -> LayoutGraphSnapshotExtractor.extract(layoutGraph()));
LIFECYCLE_LOG.debug("document.layoutSnapshot.end sessionId={} revision={} roots={} pages={} durationMs={}", sessionId, revision, roots.size(), computed.totalPages(), elapsedMillis(startNanos));
return computed;
}
/**
* Resolves every declared {@code anchor(...)} to its final page in a single,
* backend-neutral pass over the laid-out document — the foundation for
* cross-references ("see page N") and clickable tables of contents.
*
* <p>Computed from the resolved layout graph (not from rendered output) and
* cached per layout revision alongside {@link #layoutSnapshot()}. A duplicate
* anchor resolves to its last registration, matching where a
* {@code linkTo(anchor)} jumps.</p>
*
* @return the resolved anchor-to-page index
* @throws IllegalStateException if this session has already been closed
* @since 1.9.0
*/
public PageIndex pageIndex() {
ensureOpen();
long revision = layoutCache.revision();
if (layoutCache.isPageIndexCached()) {
PageIndex cached = layoutCache.pageIndex(() -> {
throw new IllegalStateException("PageIndex cache miss after isPageIndexCached() returned true.");
});
LIFECYCLE_LOG.debug("document.pageIndex.cache.hit sessionId={} revision={} roots={}", sessionId, revision, roots.size());
return cached;
}
long startNanos = System.nanoTime();
PageIndex computed = layoutCache.pageIndex(() -> PageIndexExtractor.from(layoutGraph()));
LIFECYCLE_LOG.debug("document.pageIndex.end sessionId={} revision={} roots={} anchors={} durationMs={}", sessionId, revision, roots.size(), computed.all().size(), elapsedMillis(startNanos));
return computed;
}
/**
* Renders the current layout graph with the supplied fixed-layout backend.
*
* @param backend backend implementation that consumes the resolved layout graph
* @param <R> backend-specific result type
* @return backend render result
* @throws Exception if rendering fails
*/
public <R> R render(FixedLayoutBackend<R> backend) throws Exception {
return renderingFacade.render(backend, defaultOutputFile);
}
/**
* Renders the current layout graph with an explicit output target override.
*
* @param backend backend implementation that consumes the resolved layout graph
* @param outputFile optional output target for backends that persist to disk
* @param <R> backend-specific result type
* @return backend render result
* @throws Exception if rendering fails
*/
public <R> R render(FixedLayoutBackend<R> backend, Path outputFile) throws Exception {
return renderingFacade.render(backend, outputFile);
}
/**
* Exports the semantic graph through a semantic backend using the default output file.
*
* @param backend semantic backend implementation
* @param <R> backend-specific result type
* @return export result
* @throws Exception if export fails
*/
public <R> R export(SemanticBackend<R> backend) throws Exception {
return renderingFacade.export(backend, defaultOutputFile);
}
/**
* Exports the semantic graph through a semantic backend using an explicit output target.
*
* @param backend semantic backend implementation
* @param outputFile optional output file override
* @param <R> backend-specific result type
* @return export result
* @throws Exception if export fails
*/
public <R> R export(SemanticBackend<R> backend, Path outputFile) throws Exception {
return renderingFacade.export(backend, outputFile);
}
/**
* Renders the current session through the canonical PDF backend and returns bytes.
*
* <p>This is a convenience wrapper around {@link #writePdf(OutputStream)}.
* The returned byte array is not cached by the session, so server code that
* can write directly to a response or object-storage stream should prefer
* {@link #writePdf(OutputStream)}.</p>
*
* @return rendered PDF bytes
* @throws DocumentRenderingException if PDF rendering fails
*/
public byte[] toPdfBytes() throws DocumentRenderingException {
return wrapPdfRendering("render PDF bytes", renderingFacade::toPdfBytes);
}
/**
* Streams the current session through the canonical PDF backend.
*
* <p>The caller owns the supplied stream. GraphCompose writes the PDF bytes
* but does not close the stream, which makes this method suitable for HTTP
* responses, cloud storage uploads, and other server-side streaming paths.</p>
*
* @param output destination stream that receives the rendered PDF bytes
* @throws DocumentRenderingException if PDF rendering fails
*/
public void writePdf(OutputStream output) throws DocumentRenderingException {
wrapPdfRendering("write PDF to stream", () -> {
renderingFacade.writePdf(output);
return null;
});
}
/**
* Builds the current document into the default output file configured on the builder.
*
* @throws IllegalStateException if no default output file was configured
* @throws DocumentRenderingException if PDF rendering fails
*/
public void buildPdf() throws DocumentRenderingException {
ensureOpen();
if (defaultOutputFile == null) {
throw new IllegalStateException("No default output file was configured for this document session.");
}
wrapPdfRendering("build PDF at '" + defaultOutputFile + "'", () -> {
renderingFacade.buildPdf(defaultOutputFile);
return null;
});
}
/**
* Builds the current document into the supplied output file.
*
* @param outputFile destination PDF path
* @throws DocumentRenderingException if PDF rendering fails
*/
public void buildPdf(Path outputFile) throws DocumentRenderingException {
wrapPdfRendering("build PDF at '" + outputFile + "'", () -> {
renderingFacade.buildPdf(outputFile);
return null;
});
}
/**
* Renders every page of the current document to a raster image at the given
* resolution, with an opaque white background.
*
* <p>Renders the in-memory document directly to images — without the
* intermediate PDF byte array of {@link #toPdfBytes()} followed by a
* {@code Loader.loadPDF(...)} re-parse — so it avoids that serialize-then-reparse
* round-trip. Useful for page previews, thumbnails, and pixel diffing.</p>
*
* @param dpi target resolution in dots per inch (72 = native page size); must be {@code > 0}