1use std::fmt;
9
10pub mod edit;
11mod export;
12mod fidelity;
13mod incremental;
14mod pictures;
15#[cfg(any(test, feature = "development"))]
16pub mod suite;
17
18pub use fidelity::{
19 FidelityLevel, FidelityReport, FontMatchKind, FontStatus, MissingGlyphGroup, Omission,
20 OmissionKind,
21};
22pub use incremental::{LayoutContinuation, LayoutProgress, PreparedDocument};
23
24#[cfg(any(test, feature = "development"))]
25use f_office_docx::PlacedLine;
26use f_office_docx::TextMap;
27use f_office_fonts::FontDb;
28use f_office_opc::Package;
29
30pub use f_office_docx::configuration;
33pub use f_office_docx::configuration::Error as ConfigurationError;
36pub use f_office_docx::{
37 ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
38 ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, Address,
39 AddressError, AddressStep, ArtPictures, ArtPicturesError, ArtPicturesFault, CellPlace,
40 Configuration, DateTime, EndHyphen, LineTextEnd, LineTurn, LinkTarget, NumberSeparators,
41 NumberSeparatorsError, StoryBookmark, StoryLink, StoryParagraph, Target, TextBlock,
42 TextBlockKind, TextCluster, TextLine, TextStory,
43};
44pub use f_office_fonts::FontDb as FontDatabase;
45pub use f_office_opc::{Limits, RandomAccessRead, XmlLimits};
46pub use f_office_paint::{DisplayList, ImageFault, ImageFormat, Page};
47pub use f_office_units::Length;
48pub use f_office_warnings::Name;
49
50pub mod docx {
53 pub use f_office_docx::{
54 ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
55 MatchedFont, MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason,
56 SubstituteLayout, UnicodeBlock, ValuePlace, Warning,
57 };
58 pub use f_office_fonts::ShapeFailure;
59}
60
61pub mod pdf {
63 pub use f_office_pdf::Warning;
64}
65
66const _: () = {
69 const fn shared<T: Send + Sync>() {}
70 shared::<DisplayList>();
71 shared::<Document>();
72};
73
74#[cfg(feature = "timing")]
78pub mod timing {
79 pub use f_office_docx::timing::{arm, take};
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum Error {
86 Package(f_office_opc::Error),
88 Docx(f_office_docx::Error),
90 Pdf(f_office_pdf::Error),
92 Configuration(ConfigurationError),
94}
95
96impl fmt::Display for Error {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.write_str(match self {
99 Self::Package(_) => "the package could not be read",
100 Self::Docx(_) => "the DOCX content could not be laid out",
101 Self::Pdf(_) => "the pages could not be written as PDF",
102 Self::Configuration(_) => "the configuration or the target's profile does not read",
103 })
104 }
105}
106
107impl std::error::Error for Error {
108 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109 Some(match self {
110 Self::Package(error) => error,
111 Self::Docx(error) => error,
112 Self::Pdf(error) => error,
113 Self::Configuration(error) => error,
114 })
115 }
116}
117
118#[derive(Clone, Debug, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum Warning {
124 Docx(docx::Warning),
126 Pdf(pdf::Warning),
128 PictureNotWrittenAgain {
131 format: ImageFormat,
133 },
134 SignatureBroken,
137 NoteKept,
140}
141
142impl Warning {
143 #[must_use]
147 pub fn kind(&self) -> &'static str {
148 match self {
149 Self::Docx(warning) => warning.kind(),
150 Self::Pdf(warning) => warning.kind(),
151 Self::PictureNotWrittenAgain { .. } => "picture-not-written-again",
152 Self::SignatureBroken => "signature-broken",
153 Self::NoteKept => "note-kept",
154 }
155 }
156}
157
158impl fmt::Display for Warning {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 match self {
161 Self::Docx(warning) => warning.fmt(f),
162 Self::Pdf(warning) => warning.fmt(f),
163 Self::PictureNotWrittenAgain { format } => write!(
164 f,
165 "a picture in {format} format keeps its own file, which the target's PDF writer \
166 writes again: its data does not decode"
167 ),
168 Self::SignatureBroken => f.write_str(
169 "the package holds a digital signature, which the edits break: sign the new file again",
170 ),
171 Self::NoteKept => f.write_str(
172 "a deleted block held the reference of a footnote or an endnote, and the note stays in its part: delete it with a raw edit if it must go",
173 ),
174 }
175 }
176}
177
178pub type Warnings = f_office_warnings::Warnings<Warning>;
180
181pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
183
184#[must_use]
189pub fn error_chain(error: &dyn std::error::Error) -> String {
190 let mut text = error.to_string();
191 let mut cause = error.source();
192 while let Some(next) = cause {
193 text.push_str(": ");
194 text.push_str(&next.to_string());
195 cause = next.source();
196 }
197 text
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
204#[non_exhaustive]
205pub struct Options {
206 pub now: Option<DateTime>,
210 pub configuration: Configuration,
213 #[cfg(any(test, feature = "development"))]
216 pub overrides: f_office_docx::profile::Overrides,
217 pub limits: Limits,
224}
225
226impl Default for Options {
227 fn default() -> Self {
228 Self {
229 now: None,
230 configuration: Configuration::of(Target::default()),
231 #[cfg(any(test, feature = "development"))]
232 overrides: f_office_docx::profile::Overrides::default(),
233 limits: Limits::default(),
234 }
235 }
236}
237
238impl Options {
239 #[cfg(test)]
242 pub(crate) fn base() -> Self {
243 Self {
244 configuration: Configuration::of(Target::base()),
245 ..Self::default()
246 }
247 }
248
249 fn layout(&self) -> f_office_docx::Options {
252 let mut layout = f_office_docx::Options::default();
253 layout.now = self.now;
254 layout.configuration = self.configuration.clone();
255 #[cfg(any(test, feature = "development"))]
256 {
257 layout.overrides = self.overrides.clone();
258 }
259 layout
260 }
261}
262
263#[derive(Clone, Debug)]
268pub struct Document {
269 list: DisplayList,
270 #[cfg(any(test, feature = "development"))]
271 lines: Vec<PlacedLine>,
272 #[cfg(any(test, feature = "development"))]
273 tables: Vec<f_office_docx::TableColumns>,
274 text_blocks: Vec<TextBlock>,
275 text_map: TextMap,
276 fidelity: FidelityReport,
277}
278
279impl Document {
280 pub fn open(docx: &[u8], fonts: &FontDb, options: &Options) -> Result<Warned<Self>, Error> {
288 Self::open_with_art(docx, fonts, &ArtPictures::new(), options)
289 }
290
291 pub fn open_with_art(
299 docx: &[u8],
300 fonts: &FontDb,
301 art: &ArtPictures,
302 options: &Options,
303 ) -> Result<Warned<Self>, Error> {
304 Self::open_with((docx, fonts, art), &options.limits, &options.layout())
305 }
306
307 #[cfg(not(target_arch = "wasm32"))]
316 pub fn open_file(
317 path: &std::path::Path,
318 fonts: &FontDb,
319 options: &Options,
320 ) -> Result<Warned<Self>, Error> {
321 Self::open_file_with_art(path, fonts, &ArtPictures::new(), options)
322 }
323
324 #[cfg(not(target_arch = "wasm32"))]
331 pub fn open_file_with_art(
332 path: &std::path::Path,
333 fonts: &FontDb,
334 art: &ArtPictures,
335 options: &Options,
336 ) -> Result<Warned<Self>, Error> {
337 let package =
338 f_office_docx::timing::span("open", || Package::open_file(path, &options.limits))
339 .map_err(Error::Package)?;
340 Self::open_package((&package, fonts, art), &options.layout())
341 }
342
343 pub fn open_source(
350 source: std::sync::Arc<dyn RandomAccessRead>,
351 fonts: &FontDb,
352 options: &Options,
353 ) -> Result<Warned<Self>, Error> {
354 Self::open_source_with_art(source, fonts, &ArtPictures::new(), options)
355 }
356
357 pub fn open_source_with_art(
364 source: std::sync::Arc<dyn RandomAccessRead>,
365 fonts: &FontDb,
366 art: &ArtPictures,
367 options: &Options,
368 ) -> Result<Warned<Self>, Error> {
369 let package =
370 f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
371 .map_err(Error::Package)?;
372 Self::open_package((&package, fonts, art), &options.layout())
373 }
374
375 fn open_with(
378 (docx, fonts, art): (&[u8], &FontDb, &ArtPictures),
379 limits: &Limits,
380 layout: &f_office_docx::Options,
381 ) -> Result<Warned<Self>, Error> {
382 let package = f_office_docx::timing::span("open", || Package::open(docx, limits))
383 .map_err(Error::Package)?;
384 Self::open_package((&package, fonts, art), layout)
385 }
386
387 fn open_package(
389 (package, fonts, art): (&Package, &FontDb, &ArtPictures),
390 layout: &f_office_docx::Options,
391 ) -> Result<Warned<Self>, Error> {
392 let laid_out = f_office_docx::timing::span("docx", || {
393 f_office_docx::layout_lines(package, (fonts, art), layout)
394 })
395 .map_err(|error| match error {
396 f_office_docx::Error::Configuration(error) => Error::Configuration(error),
397 error => Error::Docx(error),
398 })?;
399 let (doc, warnings) = incremental::finish_laid_out(laid_out);
400 Ok(Warned::new(doc, warnings))
401 }
402
403 #[must_use]
405 pub fn display_list(&self) -> &DisplayList {
406 &self.list
407 }
408
409 #[must_use]
411 pub fn fidelity(&self) -> &FidelityReport {
412 &self.fidelity
413 }
414
415 #[must_use]
417 pub fn pages(&self) -> &[Page] {
418 self.list.pages()
419 }
420
421 #[must_use]
423 pub fn page_count(&self) -> usize {
424 self.pages().len()
425 }
426
427 #[must_use]
429 pub fn page(&self, index: usize) -> Option<&Page> {
430 self.pages().get(index)
431 }
432
433 #[must_use]
436 pub fn page_size(&self, index: usize) -> Option<(Length, Length)> {
437 self.page(index).map(|page| (page.width(), page.height()))
438 }
439
440 #[must_use]
448 pub fn text_blocks(&self) -> &[TextBlock] {
449 &self.text_blocks
450 }
451
452 #[must_use]
459 pub fn text_map(&self, index: usize) -> Vec<TextLine> {
460 self.text_map.page(index)
461 }
462
463 #[must_use]
467 pub fn text_maps(&self, indices: &[usize]) -> Vec<Vec<TextLine>> {
468 self.text_map.pages(indices)
469 }
470
471 #[must_use]
475 pub fn story_text(&self, story: TextStory) -> Vec<StoryParagraph> {
476 self.text_map.story(story)
477 }
478
479 pub fn write_pdf(&self, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
490 let pdf = f_office_docx::timing::span("pdf", || f_office_pdf::write_pdf(&self.list, fonts))
491 .map_err(Error::Pdf)?;
492 Ok(Warned::new(pdf.value, pdf.warnings.map(Warning::Pdf)))
493 }
494
495 pub fn write_pdf_to<W: std::io::Write>(
502 &self,
503 fonts: &FontDb,
504 writer: &mut W,
505 ) -> Result<Warned<()>, Error> {
506 let pdf = f_office_docx::timing::span("pdf", || {
507 f_office_pdf::write_pdf_to(&self.list, fonts, writer)
508 })
509 .map_err(Error::Pdf)?;
510 Ok(Warned::new((), pdf.warnings.map(Warning::Pdf)))
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::{Document, Error, FontDb, Options, error_chain};
517
518 #[test]
519 fn says_the_warnings_of_the_output_with_their_kinds() {
520 use super::{ImageFault, ImageFormat, Warning, pdf};
521 let skipped = Warning::Pdf(pdf::Warning::ImageSkipped {
522 format: ImageFormat::Wmf,
523 fault: ImageFault::Format,
524 });
525 assert_eq!(skipped.kind(), "pdf-image-skipped");
526 assert_eq!(
527 skipped.to_string(),
528 "an image in WMF format is left out of the PDF: the output draws no image of this \
529 format"
530 );
531 let kept = Warning::PictureNotWrittenAgain {
532 format: ImageFormat::Jpeg,
533 };
534 assert_eq!(kept.kind(), "picture-not-written-again");
535 assert_eq!(
536 kept.to_string(),
537 "a picture in JPEG format keeps its own file, which the target's PDF writer writes \
538 again: its data does not decode"
539 );
540 }
541
542 #[test]
543 fn rejects_a_file_that_is_not_a_package_for_every_target() {
544 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
545 assert!(matches!(error, Error::Package(_)));
546 assert_ne!(error.to_string(), "");
547 for target in super::Target::all() {
549 let options = Options {
550 configuration: super::Configuration::of(target),
551 ..Options::default()
552 };
553 let with = Document::open(b"not a zip", &FontDb::new(), &options).unwrap_err();
554 assert!(matches!(with, Error::Package(_)));
555 assert_eq!(error_chain(&with), error_chain(&error));
556 }
557 }
558
559 #[test]
560 fn gives_the_pdf_error_as_its_cause() {
561 let error = Error::Pdf(f_office_pdf::Error::NoPages);
562 assert_eq!(error.to_string(), "the pages could not be written as PDF");
563 let cause = std::error::Error::source(&error).map(ToString::to_string);
564 assert_eq!(cause.as_deref(), Some("the display list has no page"));
565 }
566
567 #[test]
568 fn writes_the_error_chain_down_to_the_first_cause() {
569 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
570 let chain = error_chain(&error);
571 assert!(
572 chain.starts_with("the package could not be read: unreadable ZIP package: "),
573 "{chain}"
574 );
575 let docx = Error::Docx(f_office_docx::Error::Package(
576 f_office_opc::Error::NoMainDocument,
577 ));
578 assert_eq!(
579 error_chain(&docx),
580 "the DOCX content could not be laid out: the package could not be read: package has \
581 no main document"
582 );
583 let leaf = f_office_pdf::Error::NoPages;
584 assert_eq!(error_chain(&leaf), "the display list has no page");
585 }
586}
587
588#[cfg(test)]
589mod comment_tests;
590#[cfg(test)]
591mod layout_tests;
592#[cfg(test)]
593mod pdf_tests;
594#[cfg(test)]
595mod picture_tests;
596#[cfg(test)]
597mod test_fonts;
598#[cfg(test)]
599mod text_block_tests;