1use std::fmt;
9
10pub mod edit;
11mod incremental;
12mod pictures;
13#[cfg(any(test, feature = "development"))]
14pub mod suite;
15
16pub use incremental::{LayoutContinuation, LayoutProgress, PreparedDocument};
17
18#[cfg(any(test, feature = "development"))]
19use f_office_docx::PlacedLine;
20use f_office_docx::TextMap;
21use f_office_fonts::FontDb;
22use f_office_opc::Package;
23
24pub use f_office_docx::configuration;
27pub use f_office_docx::configuration::Error as ConfigurationError;
30pub use f_office_docx::{
31 ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
32 ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, Address,
33 AddressError, AddressStep, ArtPictures, ArtPicturesError, ArtPicturesFault, CellPlace,
34 Configuration, DateTime, EndHyphen, LineTextEnd, LineTurn, LinkTarget, NumberSeparators,
35 NumberSeparatorsError, StoryBookmark, StoryLink, StoryParagraph, Target, TextBlock,
36 TextBlockKind, TextCluster, TextLine, TextStory,
37};
38pub use f_office_fonts::FontDb as FontDatabase;
39pub use f_office_opc::{Limits, RandomAccessRead, XmlLimits};
40pub use f_office_paint::{DisplayList, ImageFault, ImageFormat, Page};
41pub use f_office_units::Length;
42pub use f_office_warnings::Name;
43
44pub mod docx {
47 pub use f_office_docx::{
48 ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
49 MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason, SubstituteLayout,
50 ValuePlace, Warning,
51 };
52 pub use f_office_fonts::ShapeFailure;
53}
54
55pub mod pdf {
57 pub use f_office_pdf::Warning;
58}
59
60const _: () = {
63 const fn shared<T: Send + Sync>() {}
64 shared::<DisplayList>();
65 shared::<Document>();
66};
67
68#[cfg(feature = "timing")]
72pub mod timing {
73 pub use f_office_docx::timing::{arm, take};
74}
75
76#[derive(Clone, Debug, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum Error {
80 Package(f_office_opc::Error),
82 Docx(f_office_docx::Error),
84 Pdf(f_office_pdf::Error),
86 Configuration(ConfigurationError),
88}
89
90impl fmt::Display for Error {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.write_str(match self {
93 Self::Package(_) => "the package could not be read",
94 Self::Docx(_) => "the DOCX content could not be laid out",
95 Self::Pdf(_) => "the pages could not be written as PDF",
96 Self::Configuration(_) => "the configuration or the target's profile does not read",
97 })
98 }
99}
100
101impl std::error::Error for Error {
102 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
103 Some(match self {
104 Self::Package(error) => error,
105 Self::Docx(error) => error,
106 Self::Pdf(error) => error,
107 Self::Configuration(error) => error,
108 })
109 }
110}
111
112#[derive(Clone, Debug, PartialEq, Eq, Hash)]
116#[non_exhaustive]
117pub enum Warning {
118 Docx(docx::Warning),
120 Pdf(pdf::Warning),
122 PictureNotWrittenAgain {
125 format: ImageFormat,
127 },
128 SignatureBroken,
131 NoteKept,
134}
135
136impl Warning {
137 #[must_use]
141 pub fn kind(&self) -> &'static str {
142 match self {
143 Self::Docx(warning) => warning.kind(),
144 Self::Pdf(warning) => warning.kind(),
145 Self::PictureNotWrittenAgain { .. } => "picture-not-written-again",
146 Self::SignatureBroken => "signature-broken",
147 Self::NoteKept => "note-kept",
148 }
149 }
150}
151
152impl fmt::Display for Warning {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 match self {
155 Self::Docx(warning) => warning.fmt(f),
156 Self::Pdf(warning) => warning.fmt(f),
157 Self::PictureNotWrittenAgain { format } => write!(
158 f,
159 "a picture in {format} format keeps its own file, which the target's PDF writer \
160 writes again: its data does not decode"
161 ),
162 Self::SignatureBroken => f.write_str(
163 "the package holds a digital signature, which the edits break: sign the new file again",
164 ),
165 Self::NoteKept => f.write_str(
166 "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",
167 ),
168 }
169 }
170}
171
172pub type Warnings = f_office_warnings::Warnings<Warning>;
174
175pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
177
178#[must_use]
183pub fn error_chain(error: &dyn std::error::Error) -> String {
184 let mut text = error.to_string();
185 let mut cause = error.source();
186 while let Some(next) = cause {
187 text.push_str(": ");
188 text.push_str(&next.to_string());
189 cause = next.source();
190 }
191 text
192}
193
194#[derive(Clone, Debug, PartialEq, Eq)]
198#[non_exhaustive]
199pub struct Options {
200 pub now: Option<DateTime>,
204 pub configuration: Configuration,
207 #[cfg(any(test, feature = "development"))]
210 pub overrides: f_office_docx::profile::Overrides,
211 pub limits: Limits,
218}
219
220impl Default for Options {
221 fn default() -> Self {
222 Self {
223 now: None,
224 configuration: Configuration::of(Target::default()),
225 #[cfg(any(test, feature = "development"))]
226 overrides: f_office_docx::profile::Overrides::default(),
227 limits: Limits::default(),
228 }
229 }
230}
231
232impl Options {
233 #[cfg(test)]
236 pub(crate) fn base() -> Self {
237 Self {
238 configuration: Configuration::of(Target::base()),
239 ..Self::default()
240 }
241 }
242
243 fn layout(&self) -> f_office_docx::Options {
246 let mut layout = f_office_docx::Options::default();
247 layout.now = self.now;
248 layout.configuration = self.configuration.clone();
249 #[cfg(any(test, feature = "development"))]
250 {
251 layout.overrides = self.overrides.clone();
252 }
253 layout
254 }
255}
256
257#[derive(Clone, Debug)]
262pub struct Document {
263 list: DisplayList,
264 #[cfg(any(test, feature = "development"))]
265 lines: Vec<PlacedLine>,
266 #[cfg(any(test, feature = "development"))]
267 tables: Vec<f_office_docx::TableColumns>,
268 text_blocks: Vec<TextBlock>,
269 text_map: TextMap,
270}
271
272impl Document {
273 pub fn open(docx: &[u8], fonts: &FontDb, options: &Options) -> Result<Warned<Self>, Error> {
281 Self::open_with_art(docx, fonts, &ArtPictures::new(), options)
282 }
283
284 pub fn open_with_art(
292 docx: &[u8],
293 fonts: &FontDb,
294 art: &ArtPictures,
295 options: &Options,
296 ) -> Result<Warned<Self>, Error> {
297 Self::open_with((docx, fonts, art), &options.limits, &options.layout())
298 }
299
300 #[cfg(not(target_arch = "wasm32"))]
309 pub fn open_file(
310 path: &std::path::Path,
311 fonts: &FontDb,
312 options: &Options,
313 ) -> Result<Warned<Self>, Error> {
314 Self::open_file_with_art(path, fonts, &ArtPictures::new(), options)
315 }
316
317 #[cfg(not(target_arch = "wasm32"))]
324 pub fn open_file_with_art(
325 path: &std::path::Path,
326 fonts: &FontDb,
327 art: &ArtPictures,
328 options: &Options,
329 ) -> Result<Warned<Self>, Error> {
330 let package =
331 f_office_docx::timing::span("open", || Package::open_file(path, &options.limits))
332 .map_err(Error::Package)?;
333 Self::open_package((&package, fonts, art), &options.layout())
334 }
335
336 pub fn open_source(
343 source: std::sync::Arc<dyn RandomAccessRead>,
344 fonts: &FontDb,
345 options: &Options,
346 ) -> Result<Warned<Self>, Error> {
347 Self::open_source_with_art(source, fonts, &ArtPictures::new(), options)
348 }
349
350 pub fn open_source_with_art(
357 source: std::sync::Arc<dyn RandomAccessRead>,
358 fonts: &FontDb,
359 art: &ArtPictures,
360 options: &Options,
361 ) -> Result<Warned<Self>, Error> {
362 let package =
363 f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
364 .map_err(Error::Package)?;
365 Self::open_package((&package, fonts, art), &options.layout())
366 }
367
368 fn open_with(
371 (docx, fonts, art): (&[u8], &FontDb, &ArtPictures),
372 limits: &Limits,
373 layout: &f_office_docx::Options,
374 ) -> Result<Warned<Self>, Error> {
375 let package = f_office_docx::timing::span("open", || Package::open(docx, limits))
376 .map_err(Error::Package)?;
377 Self::open_package((&package, fonts, art), layout)
378 }
379
380 fn open_package(
382 (package, fonts, art): (&Package, &FontDb, &ArtPictures),
383 layout: &f_office_docx::Options,
384 ) -> Result<Warned<Self>, Error> {
385 let laid_out = f_office_docx::timing::span("docx", || {
386 f_office_docx::layout_lines(package, (fonts, art), layout)
387 })
388 .map_err(|error| match error {
389 f_office_docx::Error::Configuration(error) => Error::Configuration(error),
390 error => Error::Docx(error),
391 })?;
392 let mut warnings = laid_out.warnings.map(Warning::Docx);
393 #[cfg(not(any(test, feature = "development")))]
394 let f_office_docx::LaidOut {
395 mut list,
396 lines: _,
397 text_blocks,
398 text_map,
399 tables: _,
400 writer,
401 } = laid_out.value;
402 #[cfg(any(test, feature = "development"))]
403 let f_office_docx::LaidOut {
404 mut list,
405 lines,
406 text_blocks,
407 text_map,
408 tables,
409 writer,
410 } = laid_out.value;
411 writer.finish(&mut list);
414 list = pictures::write_pictures_again(
415 list,
416 pictures::Rewriting {
417 quality: writer.jpeg_quality(),
418 jpeg_share: writer.jpeg_share(),
419 jpeg_sample: writer.jpeg_sample(),
420 crop: writer.picture_crop(),
421 alpha_mix: writer.alpha_mix(),
422 resampling: &|pixels, palette, image| {
423 writer.resampled_size(pixels, (image.width, image.height), palette)
424 },
425 },
426 &mut warnings,
427 );
428 writer.place_pictures(&mut list);
431 Ok(Warned::new(
432 Self {
433 list,
434 #[cfg(any(test, feature = "development"))]
435 lines,
436 #[cfg(any(test, feature = "development"))]
437 tables,
438 text_blocks,
439 text_map,
440 },
441 warnings,
442 ))
443 }
444
445 #[must_use]
447 pub fn display_list(&self) -> &DisplayList {
448 &self.list
449 }
450
451 #[must_use]
453 pub fn pages(&self) -> &[Page] {
454 self.list.pages()
455 }
456
457 #[must_use]
459 pub fn page_count(&self) -> usize {
460 self.pages().len()
461 }
462
463 #[must_use]
465 pub fn page(&self, index: usize) -> Option<&Page> {
466 self.pages().get(index)
467 }
468
469 #[must_use]
472 pub fn page_size(&self, index: usize) -> Option<(Length, Length)> {
473 self.page(index).map(|page| (page.width(), page.height()))
474 }
475
476 #[must_use]
484 pub fn text_blocks(&self) -> &[TextBlock] {
485 &self.text_blocks
486 }
487
488 #[must_use]
495 pub fn text_map(&self, index: usize) -> Vec<TextLine> {
496 self.text_map.page(index)
497 }
498
499 #[must_use]
503 pub fn text_maps(&self, indices: &[usize]) -> Vec<Vec<TextLine>> {
504 self.text_map.pages(indices)
505 }
506
507 #[must_use]
511 pub fn story_text(&self, story: TextStory) -> Vec<StoryParagraph> {
512 self.text_map.story(story)
513 }
514
515 pub fn write_pdf(&self, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
526 let pdf = f_office_docx::timing::span("pdf", || f_office_pdf::write_pdf(&self.list, fonts))
527 .map_err(Error::Pdf)?;
528 Ok(Warned::new(pdf.value, pdf.warnings.map(Warning::Pdf)))
529 }
530
531 pub fn write_pdf_to<W: std::io::Write>(
538 &self,
539 fonts: &FontDb,
540 writer: &mut W,
541 ) -> Result<Warned<()>, Error> {
542 let pdf = f_office_docx::timing::span("pdf", || {
543 f_office_pdf::write_pdf_to(&self.list, fonts, writer)
544 })
545 .map_err(Error::Pdf)?;
546 Ok(Warned::new((), pdf.warnings.map(Warning::Pdf)))
547 }
548}
549
550#[cfg(test)]
551mod tests {
552 use super::{Document, Error, FontDb, Options, error_chain};
553
554 #[test]
555 fn says_the_warnings_of_the_output_with_their_kinds() {
556 use super::{ImageFault, ImageFormat, Warning, pdf};
557 let skipped = Warning::Pdf(pdf::Warning::ImageSkipped {
558 format: ImageFormat::Wmf,
559 fault: ImageFault::Format,
560 });
561 assert_eq!(skipped.kind(), "pdf-image-skipped");
562 assert_eq!(
563 skipped.to_string(),
564 "an image in WMF format is left out of the PDF: the output draws no image of this \
565 format"
566 );
567 let kept = Warning::PictureNotWrittenAgain {
568 format: ImageFormat::Jpeg,
569 };
570 assert_eq!(kept.kind(), "picture-not-written-again");
571 assert_eq!(
572 kept.to_string(),
573 "a picture in JPEG format keeps its own file, which the target's PDF writer writes \
574 again: its data does not decode"
575 );
576 }
577
578 #[test]
579 fn rejects_a_file_that_is_not_a_package_for_every_target() {
580 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
581 assert!(matches!(error, Error::Package(_)));
582 assert_ne!(error.to_string(), "");
583 for target in super::Target::all() {
585 let options = Options {
586 configuration: super::Configuration::of(target),
587 ..Options::default()
588 };
589 let with = Document::open(b"not a zip", &FontDb::new(), &options).unwrap_err();
590 assert!(matches!(with, Error::Package(_)));
591 assert_eq!(error_chain(&with), error_chain(&error));
592 }
593 }
594
595 #[test]
596 fn gives_the_pdf_error_as_its_cause() {
597 let error = Error::Pdf(f_office_pdf::Error::NoPages);
598 assert_eq!(error.to_string(), "the pages could not be written as PDF");
599 let cause = std::error::Error::source(&error).map(ToString::to_string);
600 assert_eq!(cause.as_deref(), Some("the display list has no page"));
601 }
602
603 #[test]
604 fn writes_the_error_chain_down_to_the_first_cause() {
605 let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
606 let chain = error_chain(&error);
607 assert!(
608 chain.starts_with("the package could not be read: unreadable ZIP package: "),
609 "{chain}"
610 );
611 let docx = Error::Docx(f_office_docx::Error::Package(
612 f_office_opc::Error::NoMainDocument,
613 ));
614 assert_eq!(
615 error_chain(&docx),
616 "the DOCX content could not be laid out: the package could not be read: package has \
617 no main document"
618 );
619 let leaf = f_office_pdf::Error::NoPages;
620 assert_eq!(error_chain(&leaf), "the display list has no page");
621 }
622}
623
624#[cfg(test)]
625mod comment_tests;
626#[cfg(test)]
627mod layout_tests;
628#[cfg(test)]
629mod pdf_tests;
630#[cfg(test)]
631mod picture_tests;
632#[cfg(test)]
633mod test_fonts;
634#[cfg(test)]
635mod text_block_tests;