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 file_name: Option<String>,
215 pub configuration: Configuration,
218 #[cfg(any(test, feature = "development"))]
221 pub overrides: f_office_docx::profile::Overrides,
222 pub limits: Limits,
229}
230
231impl Default for Options {
232 fn default() -> Self {
233 Self {
234 now: None,
235 file_name: None,
236 configuration: Configuration::of(Target::default()),
237 #[cfg(any(test, feature = "development"))]
238 overrides: f_office_docx::profile::Overrides::default(),
239 limits: Limits::default(),
240 }
241 }
242}
243
244impl Options {
245 #[cfg(test)]
248 pub(crate) fn base() -> Self {
249 Self {
250 configuration: Configuration::of(Target::base()),
251 ..Self::default()
252 }
253 }
254
255 fn layout(&self) -> f_office_docx::Options {
258 let mut layout = f_office_docx::Options::default();
259 layout.now = self.now;
260 layout.file_name.clone_from(&self.file_name);
261 layout.configuration = self.configuration.clone();
262 #[cfg(any(test, feature = "development"))]
263 {
264 layout.overrides = self.overrides.clone();
265 }
266 layout
267 }
268}
269
270#[derive(Clone, Debug)]
275pub struct Document {
276 list: DisplayList,
277 #[cfg(any(test, feature = "development"))]
278 lines: Vec<PlacedLine>,
279 #[cfg(any(test, feature = "development"))]
280 tables: Vec<f_office_docx::TableColumns>,
281 text_blocks: Vec<TextBlock>,
282 text_map: TextMap,
283 fidelity: FidelityReport,
284}
285
286impl Document {
287 pub fn open(docx: &[u8], fonts: &FontDb, options: &Options) -> Result<Warned<Self>, Error> {
295 Self::open_with_art(docx, fonts, &ArtPictures::new(), options)
296 }
297
298 pub fn open_with_art(
306 docx: &[u8],
307 fonts: &FontDb,
308 art: &ArtPictures,
309 options: &Options,
310 ) -> Result<Warned<Self>, Error> {
311 Self::open_with((docx, fonts, art), &options.limits, &options.layout())
312 }
313
314 #[cfg(not(target_arch = "wasm32"))]
323 pub fn open_file(
324 path: &std::path::Path,
325 fonts: &FontDb,
326 options: &Options,
327 ) -> Result<Warned<Self>, Error> {
328 Self::open_file_with_art(path, fonts, &ArtPictures::new(), options)
329 }
330
331 #[cfg(not(target_arch = "wasm32"))]
338 pub fn open_file_with_art(
339 path: &std::path::Path,
340 fonts: &FontDb,
341 art: &ArtPictures,
342 options: &Options,
343 ) -> Result<Warned<Self>, Error> {
344 let package =
345 f_office_docx::timing::span("open", || Package::open_file(path, &options.limits))
346 .map_err(Error::Package)?;
347 Self::open_package((&package, fonts, art), &options.layout())
348 }
349
350 pub fn open_source(
357 source: std::sync::Arc<dyn RandomAccessRead>,
358 fonts: &FontDb,
359 options: &Options,
360 ) -> Result<Warned<Self>, Error> {
361 Self::open_source_with_art(source, fonts, &ArtPictures::new(), options)
362 }
363
364 pub fn open_source_with_art(
371 source: std::sync::Arc<dyn RandomAccessRead>,
372 fonts: &FontDb,
373 art: &ArtPictures,
374 options: &Options,
375 ) -> Result<Warned<Self>, Error> {
376 let package =
377 f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
378 .map_err(Error::Package)?;
379 Self::open_package((&package, fonts, art), &options.layout())
380 }
381
382 fn open_with(
385 (docx, fonts, art): (&[u8], &FontDb, &ArtPictures),
386 limits: &Limits,
387 layout: &f_office_docx::Options,
388 ) -> Result<Warned<Self>, Error> {
389 let package = f_office_docx::timing::span("open", || Package::open(docx, limits))
390 .map_err(Error::Package)?;
391 Self::open_package((&package, fonts, art), layout)
392 }
393
394 fn open_package(
396 (package, fonts, art): (&Package, &FontDb, &ArtPictures),
397 layout: &f_office_docx::Options,
398 ) -> Result<Warned<Self>, Error> {
399 let laid_out = f_office_docx::timing::span("docx", || {
400 f_office_docx::layout_lines(package, (fonts, art), layout)
401 })
402 .map_err(|error| match error {
403 f_office_docx::Error::Configuration(error) => Error::Configuration(error),
404 error => Error::Docx(error),
405 })?;
406 let (doc, warnings) = incremental::finish_laid_out(laid_out);
407 Ok(Warned::new(doc, warnings))
408 }
409
410 #[must_use]
412 pub fn display_list(&self) -> &DisplayList {
413 &self.list
414 }
415
416 #[must_use]
418 pub fn fidelity(&self) -> &FidelityReport {
419 &self.fidelity
420 }
421
422 #[must_use]
424 pub fn pages(&self) -> &[Page] {
425 self.list.pages()
426 }
427
428 #[must_use]
430 pub fn page_count(&self) -> usize {
431 self.pages().len()
432 }
433
434 #[must_use]
436 pub fn page(&self, index: usize) -> Option<&Page> {
437 self.pages().get(index)
438 }
439
440 #[must_use]
443 pub fn page_size(&self, index: usize) -> Option<(Length, Length)> {
444 self.page(index).map(|page| (page.width(), page.height()))
445 }
446
447 #[must_use]
455 pub fn text_blocks(&self) -> &[TextBlock] {
456 &self.text_blocks
457 }
458
459 #[must_use]
466 pub fn text_map(&self, index: usize) -> Vec<TextLine> {
467 self.text_map.page(index)
468 }
469
470 #[must_use]
474 pub fn text_maps(&self, indices: &[usize]) -> Vec<Vec<TextLine>> {
475 self.text_map.pages(indices)
476 }
477
478 #[must_use]
482 pub fn story_text(&self, story: TextStory) -> Vec<StoryParagraph> {
483 self.text_map.story(story)
484 }
485
486 pub fn write_pdf(&self, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
497 let pdf = f_office_docx::timing::span("pdf", || f_office_pdf::write_pdf(&self.list, fonts))
498 .map_err(Error::Pdf)?;
499 Ok(Warned::new(pdf.value, pdf.warnings.map(Warning::Pdf)))
500 }
501
502 pub fn write_pdf_to<W: std::io::Write>(
509 &self,
510 fonts: &FontDb,
511 writer: &mut W,
512 ) -> Result<Warned<()>, Error> {
513 let pdf = f_office_docx::timing::span("pdf", || {
514 f_office_pdf::write_pdf_to(&self.list, fonts, writer)
515 })
516 .map_err(Error::Pdf)?;
517 Ok(Warned::new((), pdf.warnings.map(Warning::Pdf)))
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::{Document, Error, FontDb, Options, error_chain};
524
525 #[test]
526 fn says_the_warnings_of_the_output_with_their_kinds() {
527 use super::{ImageFault, ImageFormat, Warning, pdf};
528 let skipped = Warning::Pdf(pdf::Warning::ImageSkipped {
529 format: ImageFormat::Wmf,
530 fault: ImageFault::Format,
531 });
532 assert_eq!(skipped.kind(), "pdf-image-skipped");
533 assert_eq!(
534 skipped.to_string(),
535 "an image in WMF format is left out of the PDF: the output draws no image of this \
536 format"
537 );
538 let kept = Warning::PictureNotWrittenAgain {
539 format: ImageFormat::Jpeg,
540 };
541 assert_eq!(kept.kind(), "picture-not-written-again");
542 assert_eq!(
543 kept.to_string(),
544 "a picture in JPEG format keeps its own file, which the target's PDF writer writes \
545 again: its data does not decode"
546 );
547 }
548
549 #[test]
550 fn rejects_a_file_that_is_not_a_package_for_every_target() {
551 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
552 assert!(matches!(error, Error::Package(_)));
553 assert_ne!(error.to_string(), "");
554 for target in super::Target::all() {
556 let options = Options {
557 configuration: super::Configuration::of(target),
558 ..Options::default()
559 };
560 let with = Document::open(b"not a zip", &FontDb::new(), &options).unwrap_err();
561 assert!(matches!(with, Error::Package(_)));
562 assert_eq!(error_chain(&with), error_chain(&error));
563 }
564 }
565
566 #[test]
567 fn gives_the_pdf_error_as_its_cause() {
568 let error = Error::Pdf(f_office_pdf::Error::NoPages);
569 assert_eq!(error.to_string(), "the pages could not be written as PDF");
570 let cause = std::error::Error::source(&error).map(ToString::to_string);
571 assert_eq!(cause.as_deref(), Some("the display list has no page"));
572 }
573
574 #[test]
575 fn writes_the_error_chain_down_to_the_first_cause() {
576 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
577 let chain = error_chain(&error);
578 assert!(
579 chain.starts_with("the package could not be read: unreadable ZIP package: "),
580 "{chain}"
581 );
582 let docx = Error::Docx(f_office_docx::Error::Package(
583 f_office_opc::Error::NoMainDocument,
584 ));
585 assert_eq!(
586 error_chain(&docx),
587 "the DOCX content could not be laid out: the package could not be read: package has \
588 no main document"
589 );
590 let leaf = f_office_pdf::Error::NoPages;
591 assert_eq!(error_chain(&leaf), "the display list has no page");
592 }
593}
594
595#[cfg(test)]
596mod comment_tests;
597#[cfg(test)]
598mod layout_tests;
599#[cfg(test)]
600mod pdf_tests;
601#[cfg(test)]
602mod picture_tests;
603#[cfg(test)]
604mod test_fonts;
605#[cfg(test)]
606mod text_block_tests;