1use std::fmt;
9
10pub mod edit;
11mod pictures;
12#[cfg(any(test, feature = "development"))]
13pub mod suite;
14
15#[cfg(any(test, feature = "development"))]
16use f_office_docx::PlacedLine;
17use f_office_docx::TextMap;
18use f_office_fonts::FontDb;
19use f_office_opc::Package;
20
21pub use f_office_docx::configuration;
24pub use f_office_docx::configuration::Error as ConfigurationError;
27pub use f_office_docx::{
28 ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
29 ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, Address,
30 AddressError, AddressStep, ArtPictures, ArtPicturesError, ArtPicturesFault, CellPlace,
31 Configuration, DateTime, EndHyphen, LineTextEnd, LineTurn, LinkTarget, NumberSeparators,
32 NumberSeparatorsError, StoryBookmark, StoryLink, StoryParagraph, Target, TextBlock,
33 TextBlockKind, TextCluster, TextLine, TextStory,
34};
35pub use f_office_fonts::FontDb as FontDatabase;
36pub use f_office_opc::{Limits, RandomAccessRead, XmlLimits};
37pub use f_office_paint::{DisplayList, ImageFault, ImageFormat, Page};
38pub use f_office_units::Length;
39pub use f_office_warnings::Name;
40
41pub mod docx {
44 pub use f_office_docx::{
45 ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
46 MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason, SubstituteLayout,
47 ValuePlace, Warning,
48 };
49 pub use f_office_fonts::ShapeFailure;
50}
51
52pub mod pdf {
54 pub use f_office_pdf::Warning;
55}
56
57const _: () = {
60 const fn shared<T: Send + Sync>() {}
61 shared::<DisplayList>();
62 shared::<Document>();
63};
64
65#[cfg(feature = "timing")]
69pub mod timing {
70 pub use f_office_docx::timing::{arm, take};
71}
72
73#[derive(Clone, Debug, PartialEq, Eq)]
75#[non_exhaustive]
76pub enum Error {
77 Package(f_office_opc::Error),
79 Docx(f_office_docx::Error),
81 Pdf(f_office_pdf::Error),
83 Configuration(ConfigurationError),
85}
86
87impl fmt::Display for Error {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 f.write_str(match self {
90 Self::Package(_) => "the package could not be read",
91 Self::Docx(_) => "the DOCX content could not be laid out",
92 Self::Pdf(_) => "the pages could not be written as PDF",
93 Self::Configuration(_) => "the configuration or the target's profile does not read",
94 })
95 }
96}
97
98impl std::error::Error for Error {
99 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
100 Some(match self {
101 Self::Package(error) => error,
102 Self::Docx(error) => error,
103 Self::Pdf(error) => error,
104 Self::Configuration(error) => error,
105 })
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq, Hash)]
113#[non_exhaustive]
114pub enum Warning {
115 Docx(docx::Warning),
117 Pdf(pdf::Warning),
119 PictureNotWrittenAgain {
122 format: ImageFormat,
124 },
125 SignatureBroken,
128 NoteKept,
131}
132
133impl Warning {
134 #[must_use]
138 pub fn kind(&self) -> &'static str {
139 match self {
140 Self::Docx(warning) => warning.kind(),
141 Self::Pdf(warning) => warning.kind(),
142 Self::PictureNotWrittenAgain { .. } => "picture-not-written-again",
143 Self::SignatureBroken => "signature-broken",
144 Self::NoteKept => "note-kept",
145 }
146 }
147}
148
149impl fmt::Display for Warning {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 match self {
152 Self::Docx(warning) => warning.fmt(f),
153 Self::Pdf(warning) => warning.fmt(f),
154 Self::PictureNotWrittenAgain { format } => write!(
155 f,
156 "a picture in {format} format keeps its own file, which the target's PDF writer \
157 writes again: its data does not decode"
158 ),
159 Self::SignatureBroken => f.write_str(
160 "the package holds a digital signature, which the edits break: sign the new file again",
161 ),
162 Self::NoteKept => f.write_str(
163 "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",
164 ),
165 }
166 }
167}
168
169pub type Warnings = f_office_warnings::Warnings<Warning>;
171
172pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
174
175#[must_use]
180pub fn error_chain(error: &dyn std::error::Error) -> String {
181 let mut text = error.to_string();
182 let mut cause = error.source();
183 while let Some(next) = cause {
184 text.push_str(": ");
185 text.push_str(&next.to_string());
186 cause = next.source();
187 }
188 text
189}
190
191#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct Options {
197 pub now: Option<DateTime>,
201 pub configuration: Configuration,
204 #[cfg(any(test, feature = "development"))]
207 pub overrides: f_office_docx::profile::Overrides,
208 pub limits: Limits,
215}
216
217impl Default for Options {
218 fn default() -> Self {
219 Self {
220 now: None,
221 configuration: Configuration::of(Target::default()),
222 #[cfg(any(test, feature = "development"))]
223 overrides: f_office_docx::profile::Overrides::default(),
224 limits: Limits::default(),
225 }
226 }
227}
228
229impl Options {
230 #[cfg(test)]
233 pub(crate) fn base() -> Self {
234 Self {
235 configuration: Configuration::of(Target::base()),
236 ..Self::default()
237 }
238 }
239
240 fn layout(&self) -> f_office_docx::Options {
243 let mut layout = f_office_docx::Options::default();
244 layout.now = self.now;
245 layout.configuration = self.configuration.clone();
246 #[cfg(any(test, feature = "development"))]
247 {
248 layout.overrides = self.overrides.clone();
249 }
250 layout
251 }
252}
253
254#[derive(Clone, Debug)]
259pub struct Document {
260 list: DisplayList,
261 #[cfg(any(test, feature = "development"))]
262 lines: Vec<PlacedLine>,
263 #[cfg(any(test, feature = "development"))]
264 tables: Vec<f_office_docx::TableColumns>,
265 text_blocks: Vec<TextBlock>,
266 text_map: TextMap,
267}
268
269impl Document {
270 pub fn open(docx: &[u8], fonts: &FontDb, options: &Options) -> Result<Warned<Self>, Error> {
278 Self::open_with_art(docx, fonts, &ArtPictures::new(), options)
279 }
280
281 pub fn open_with_art(
289 docx: &[u8],
290 fonts: &FontDb,
291 art: &ArtPictures,
292 options: &Options,
293 ) -> Result<Warned<Self>, Error> {
294 Self::open_with((docx, fonts, art), &options.limits, &options.layout())
295 }
296
297 #[cfg(not(target_arch = "wasm32"))]
306 pub fn open_file(
307 path: &std::path::Path,
308 fonts: &FontDb,
309 options: &Options,
310 ) -> Result<Warned<Self>, Error> {
311 Self::open_file_with_art(path, fonts, &ArtPictures::new(), options)
312 }
313
314 #[cfg(not(target_arch = "wasm32"))]
321 pub fn open_file_with_art(
322 path: &std::path::Path,
323 fonts: &FontDb,
324 art: &ArtPictures,
325 options: &Options,
326 ) -> Result<Warned<Self>, Error> {
327 let package =
328 f_office_docx::timing::span("open", || Package::open_file(path, &options.limits))
329 .map_err(Error::Package)?;
330 Self::open_package((&package, fonts, art), &options.layout())
331 }
332
333 pub fn open_source(
340 source: std::sync::Arc<dyn RandomAccessRead>,
341 fonts: &FontDb,
342 options: &Options,
343 ) -> Result<Warned<Self>, Error> {
344 Self::open_source_with_art(source, fonts, &ArtPictures::new(), options)
345 }
346
347 pub fn open_source_with_art(
354 source: std::sync::Arc<dyn RandomAccessRead>,
355 fonts: &FontDb,
356 art: &ArtPictures,
357 options: &Options,
358 ) -> Result<Warned<Self>, Error> {
359 let package =
360 f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
361 .map_err(Error::Package)?;
362 Self::open_package((&package, fonts, art), &options.layout())
363 }
364
365 fn open_with(
368 (docx, fonts, art): (&[u8], &FontDb, &ArtPictures),
369 limits: &Limits,
370 layout: &f_office_docx::Options,
371 ) -> Result<Warned<Self>, Error> {
372 let package = f_office_docx::timing::span("open", || Package::open(docx, limits))
373 .map_err(Error::Package)?;
374 Self::open_package((&package, fonts, art), layout)
375 }
376
377 fn open_package(
379 (package, fonts, art): (&Package, &FontDb, &ArtPictures),
380 layout: &f_office_docx::Options,
381 ) -> Result<Warned<Self>, Error> {
382 let laid_out = f_office_docx::timing::span("docx", || {
383 f_office_docx::layout_lines(package, (fonts, art), layout)
384 })
385 .map_err(|error| match error {
386 f_office_docx::Error::Configuration(error) => Error::Configuration(error),
387 error => Error::Docx(error),
388 })?;
389 let mut warnings = laid_out.warnings.map(Warning::Docx);
390 #[cfg(not(any(test, feature = "development")))]
391 let f_office_docx::LaidOut {
392 mut list,
393 lines: _,
394 text_blocks,
395 text_map,
396 tables: _,
397 writer,
398 } = laid_out.value;
399 #[cfg(any(test, feature = "development"))]
400 let f_office_docx::LaidOut {
401 mut list,
402 lines,
403 text_blocks,
404 text_map,
405 tables,
406 writer,
407 } = laid_out.value;
408 writer.finish(&mut list);
411 list = pictures::write_pictures_again(
412 list,
413 pictures::Rewriting {
414 quality: writer.jpeg_quality(),
415 jpeg_share: writer.jpeg_share(),
416 jpeg_sample: writer.jpeg_sample(),
417 crop: writer.picture_crop(),
418 alpha_mix: writer.alpha_mix(),
419 resampling: &|pixels, palette, image| {
420 writer.resampled_size(pixels, (image.width, image.height), palette)
421 },
422 },
423 &mut warnings,
424 );
425 writer.place_pictures(&mut list);
428 Ok(Warned::new(
429 Self {
430 list,
431 #[cfg(any(test, feature = "development"))]
432 lines,
433 #[cfg(any(test, feature = "development"))]
434 tables,
435 text_blocks,
436 text_map,
437 },
438 warnings,
439 ))
440 }
441
442 #[must_use]
444 pub fn display_list(&self) -> &DisplayList {
445 &self.list
446 }
447
448 #[must_use]
450 pub fn pages(&self) -> &[Page] {
451 self.list.pages()
452 }
453
454 #[must_use]
456 pub fn page_count(&self) -> usize {
457 self.pages().len()
458 }
459
460 #[must_use]
462 pub fn page(&self, index: usize) -> Option<&Page> {
463 self.pages().get(index)
464 }
465
466 #[must_use]
469 pub fn page_size(&self, index: usize) -> Option<(Length, Length)> {
470 self.page(index).map(|page| (page.width(), page.height()))
471 }
472
473 #[must_use]
481 pub fn text_blocks(&self) -> &[TextBlock] {
482 &self.text_blocks
483 }
484
485 #[must_use]
492 pub fn text_map(&self, index: usize) -> Vec<TextLine> {
493 self.text_map.page(index)
494 }
495
496 #[must_use]
500 pub fn text_maps(&self, indices: &[usize]) -> Vec<Vec<TextLine>> {
501 self.text_map.pages(indices)
502 }
503
504 #[must_use]
508 pub fn story_text(&self, story: TextStory) -> Vec<StoryParagraph> {
509 self.text_map.story(story)
510 }
511
512 pub fn write_pdf(&self, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
523 let pdf = f_office_docx::timing::span("pdf", || f_office_pdf::write_pdf(&self.list, fonts))
524 .map_err(Error::Pdf)?;
525 Ok(Warned::new(pdf.value, pdf.warnings.map(Warning::Pdf)))
526 }
527
528 pub fn write_pdf_to<W: std::io::Write>(
535 &self,
536 fonts: &FontDb,
537 writer: &mut W,
538 ) -> Result<Warned<()>, Error> {
539 let pdf = f_office_docx::timing::span("pdf", || {
540 f_office_pdf::write_pdf_to(&self.list, fonts, writer)
541 })
542 .map_err(Error::Pdf)?;
543 Ok(Warned::new((), pdf.warnings.map(Warning::Pdf)))
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::{Document, Error, FontDb, Options, error_chain};
550
551 #[test]
552 fn says_the_warnings_of_the_output_with_their_kinds() {
553 use super::{ImageFault, ImageFormat, Warning, pdf};
554 let skipped = Warning::Pdf(pdf::Warning::ImageSkipped {
555 format: ImageFormat::Wmf,
556 fault: ImageFault::Format,
557 });
558 assert_eq!(skipped.kind(), "pdf-image-skipped");
559 assert_eq!(
560 skipped.to_string(),
561 "an image in WMF format is left out of the PDF: the output draws no image of this \
562 format"
563 );
564 let kept = Warning::PictureNotWrittenAgain {
565 format: ImageFormat::Jpeg,
566 };
567 assert_eq!(kept.kind(), "picture-not-written-again");
568 assert_eq!(
569 kept.to_string(),
570 "a picture in JPEG format keeps its own file, which the target's PDF writer writes \
571 again: its data does not decode"
572 );
573 }
574
575 #[test]
576 fn rejects_a_file_that_is_not_a_package_for_every_target() {
577 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
578 assert!(matches!(error, Error::Package(_)));
579 assert_ne!(error.to_string(), "");
580 for target in super::Target::all() {
582 let options = Options {
583 configuration: super::Configuration::of(target),
584 ..Options::default()
585 };
586 let with = Document::open(b"not a zip", &FontDb::new(), &options).unwrap_err();
587 assert!(matches!(with, Error::Package(_)));
588 assert_eq!(error_chain(&with), error_chain(&error));
589 }
590 }
591
592 #[test]
593 fn gives_the_pdf_error_as_its_cause() {
594 let error = Error::Pdf(f_office_pdf::Error::NoPages);
595 assert_eq!(error.to_string(), "the pages could not be written as PDF");
596 let cause = std::error::Error::source(&error).map(ToString::to_string);
597 assert_eq!(cause.as_deref(), Some("the display list has no page"));
598 }
599
600 #[test]
601 fn writes_the_error_chain_down_to_the_first_cause() {
602 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
603 let chain = error_chain(&error);
604 assert!(
605 chain.starts_with("the package could not be read: unreadable ZIP package: "),
606 "{chain}"
607 );
608 let docx = Error::Docx(f_office_docx::Error::Package(
609 f_office_opc::Error::NoMainDocument,
610 ));
611 assert_eq!(
612 error_chain(&docx),
613 "the DOCX content could not be laid out: the package could not be read: package has \
614 no main document"
615 );
616 let leaf = f_office_pdf::Error::NoPages;
617 assert_eq!(error_chain(&leaf), "the display list has no page");
618 }
619}
620
621#[cfg(test)]
622mod comment_tests;
623#[cfg(test)]
624mod layout_tests;
625#[cfg(test)]
626mod pdf_tests;
627#[cfg(test)]
628mod picture_tests;
629#[cfg(test)]
630mod test_fonts;
631#[cfg(test)]
632mod text_block_tests;