#![deny(clippy::float_arithmetic)]
mod art_pictures;
mod body;
mod buffers;
mod character_class;
mod chart;
mod comments;
pub mod configuration;
mod dates;
mod enumerations;
mod floating;
mod font_choice;
mod grid;
mod kinsoku;
mod layout;
mod lengths;
mod lines;
mod math;
mod mode;
pub mod named_edits;
mod note_setup;
mod ns;
mod numbering;
mod numbers;
pub mod on_off;
mod params;
mod parts;
mod picture;
#[cfg(feature = "development")]
pub mod profile;
#[cfg(not(feature = "development"))]
mod profile;
mod properties;
mod props;
#[cfg(feature = "development")]
pub mod quirks;
#[cfg(not(feature = "development"))]
mod quirks;
mod reader;
mod revisions;
mod smartart;
mod source_span;
mod styles;
mod table;
mod tabs;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod text;
mod text_addresses;
mod text_blocks;
mod text_links;
mod text_map;
pub mod timing;
mod toc_links;
mod vml;
pub mod warnings;
mod web_settings;
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use f_office_fonts::{
FamilyName, FontId, Ligature, OutlineError, ShapeFailure, ShapeRequest, ShapedGlyph,
};
use f_office_opc::{Package, Relationship};
use f_office_paint::{DisplayList, Image, InkConversion};
use f_office_xml::Document;
use crate::body::{Block, Body, ParagraphIds, References, Sections, read_header_story};
use crate::layout::{
Context, EarlierPass, HeaderStyles, Layout, PartStory, Pass, SectionLayout, Stories,
};
use crate::note_setup::NotePosition;
use crate::numbering::Numbering;
use crate::parts::{Reading, Role};
use crate::reader::settings::ReaderSettings;
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::text::Shaper;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FaceMetrics {
pub units_per_em: u16,
pub hhea_ascender: i16,
pub hhea_descender: i16,
pub hhea_line_gap: i16,
pub descent: u16,
pub underline_position: i16,
pub underline_thickness: i16,
pub strikeout_position: i16,
pub strikeout_thickness: i16,
pub superscript_offset: i16,
pub subscript_offset: i16,
pub superscript_size: i16,
pub subscript_size: i16,
pub line_top: u16,
pub script_top: u16,
pub east_asian: bool,
pub average_width: i16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChosenFace {
pub font: FontId,
pub metrics: FaceMetrics,
pub synthetic_bold: bool,
pub synthetic_italic: bool,
pub stands_in: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KerningTable {
FaceSource,
KernTable,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutlineCommand {
MoveTo([i32; 2]),
LineTo([i32; 2]),
QuadTo([i32; 2], [i32; 2]),
CubicTo([i32; 2], [i32; 2], [i32; 2]),
Close,
}
pub trait Fonts {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace>;
fn substitute(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
self.face(family, bold, italic)
}
fn family_substitute(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
) -> Option<ChosenFace> {
let _ = (family, bold, italic);
None
}
fn metafile_face(
&self,
family: &FamilyName,
charset: u8,
pitch_and_family: u8,
) -> Option<FamilyName> {
let _ = (family, charset, pitch_and_family);
None
}
fn glyph(&self, font: FontId, ch: char) -> Option<u32>;
fn advance(&self, font: FontId, glyph: u32) -> Option<u16>;
fn kerning(&self, font: FontId, left: u32, right: u32, table: KerningTable) -> i32 {
let _ = (font, left, right, table);
0
}
fn kerning_source(&self, font: FontId) -> f_office_fonts::KerningSource {
let _ = font;
f_office_fonts::KerningSource::KernTable
}
fn ligatures(&self, font: FontId, glyphs: &[u32]) -> Vec<Ligature> {
let _ = (font, glyphs);
Vec::new()
}
fn shape(
&self,
font: FontId,
request: &ShapeRequest<'_>,
) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
let _ = (font, request);
Err(ShapeFailure::NoShaper)
}
fn files_not_read(&self) -> Vec<f_office_fonts::FileNotRead> {
Vec::new()
}
fn family_name(&self, font: FontId) -> Option<String> {
let _ = font;
None
}
fn layout_family(&self, font: FontId) -> Option<String> {
self.family_name(font)
}
fn face_version(&self, font: FontId) -> Option<String> {
let _ = font;
None
}
fn substitute_layout(&self, font: FontId) -> SubstituteLayout {
let _ = font;
SubstituteLayout::Widths
}
fn classification(&self, font: FontId) -> Option<f_office_fonts::FaceClassification> {
let _ = font;
None
}
fn target_face(&self, font: FontId) -> Option<(String, String)> {
let _ = font;
None
}
fn bi_level_advance(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
let _ = (font, glyph, ppem);
None
}
fn device_width(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
let _ = (font, glyph, ppem);
None
}
fn device_heights(&self, font: FontId, pels: u16) -> Option<(i16, i16)> {
let _ = (font, pels);
None
}
fn ink(&self, font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
let _ = (font, glyph);
Ok(None)
}
fn outline(&self, font: FontId, glyph: u32) -> Result<Vec<OutlineCommand>, OutlineError> {
let _ = (font, glyph);
Err(OutlineError::NoOutlines)
}
fn math_limits(&self, font: FontId) -> Option<f_office_fonts::MathLimits> {
let _ = font;
None
}
fn math_radical(&self, font: FontId) -> Option<f_office_fonts::MathRadical> {
let _ = font;
None
}
fn math_bars(&self, font: FontId) -> Option<f_office_fonts::MathBars> {
let _ = font;
None
}
fn math_skewed_fraction(&self, font: FontId) -> Option<f_office_fonts::MathSkewedFraction> {
let _ = font;
None
}
fn display_variant(&self, font: FontId, glyph: u32) -> Option<u32> {
let _ = (font, glyph);
None
}
fn vertical_variant(&self, font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
let _ = (font, glyph, least);
None
}
fn math_accent(&self, font: FontId) -> Option<f_office_fonts::MathAccent> {
let _ = font;
None
}
fn top_accent_attachment(&self, font: FontId, glyph: u32) -> Option<i32> {
let _ = (font, glyph);
None
}
fn horizontal_construction(
&self,
font: FontId,
glyph: u32,
) -> Option<f_office_fonts::HorizontalConstruction> {
let _ = (font, glyph);
None
}
fn flattened_accent(&self, font: FontId, glyph: u32) -> Option<u32> {
let _ = (font, glyph);
None
}
fn dotless_form(&self, font: FontId, glyph: u32) -> Option<u32> {
let _ = (font, glyph);
None
}
fn italic_correction(&self, font: FontId, glyph: u32) -> Option<i32> {
let _ = (font, glyph);
None
}
fn space_after_script(&self, font: FontId) -> Option<i32> {
let _ = font;
None
}
fn math_kern(
&self,
font: FontId,
glyph: u32,
corner: f_office_fonts::MathCorner,
height: i32,
) -> Option<i32> {
let _ = (font, glyph, corner, height);
None
}
fn script_glyph(
&self,
font: FontId,
glyph: u32,
level: f_office_fonts::ScriptLevel,
) -> Option<u32> {
let _ = (font, glyph, level);
None
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
Package(f_office_opc::Error),
Xml(f_office_xml::Error),
MissingPart(String),
NoBody,
Configuration(configuration::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Package(_) => f.write_str("the package could not be read"),
Self::Xml(_) => f.write_str("a part is not valid XML"),
Self::MissingPart(name) => write!(f, "missing part {name}"),
Self::NoBody => f.write_str("the document has no body"),
Self::Configuration(_) => {
f.write_str("the configuration or the target's profile does not read")
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Package(error) => Some(error),
Self::Xml(error) => Some(error),
Self::Configuration(error) => Some(error),
Self::MissingPart(_) | Self::NoBody => None,
}
}
}
pub use art_pictures::{
ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, ArtPictures,
ArtPicturesError, ArtPicturesFault,
};
pub use body::ParagraphId;
pub use body::links::LinkTarget;
pub use configuration::{
Configuration, NumberSeparators, NumberSeparatorsError, PageOffset, PageOffsetError, Printer,
Target,
};
pub use dates::DateTime;
pub(crate) use font_choice::FontChoice;
pub use grid::{EdgeCheck, FixedPlace, ObjectStart};
pub use layout::{
AlignedParts, BaselineForm, CellEdgeParts, CellPlace, DrawnGlyph, FirstItem, LineArea,
LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, StepsStart, StoryPart, TableColumns,
TextCluster,
};
pub use lines::{EndHyphen, Fit, Step};
pub use props::{Alignment, LineSpacing};
pub use text_blocks::{Address, AddressError, AddressStep, TextBlock, TextBlockKind};
pub use text_map::{StoryBookmark, StoryLink, StoryParagraph, TextLine, TextMap, TextStory};
pub use warnings::{
ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason, SubstituteLayout, ValuePlace,
Warned, Warning, Warnings,
};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Options {
pub now: Option<DateTime>,
pub configuration: Configuration,
#[cfg(feature = "development")]
pub overrides: profile::Overrides,
#[cfg(all(test, not(feature = "development")))]
pub(crate) overrides: profile::Overrides,
pub device_places: bool,
}
pub fn layout(
package: &Package,
(fonts, art): (&dyn Fonts, &ArtPictures),
options: &Options,
) -> Result<Warned<DisplayList>, Error> {
layout_with_fonts(package, (fonts, art), options)
.map(|warned| warned.map(|laid_out| laid_out.list))
}
#[derive(Clone, Debug)]
pub struct LaidOut {
pub list: DisplayList,
pub lines: Vec<PlacedLine>,
pub text_blocks: Vec<TextBlock>,
pub text_map: TextMap,
pub tables: Vec<TableColumns>,
pub writer: f_office_paint::Writer,
}
fn equivalent_entries(package: &Package) -> Warnings {
let mut warnings = Warnings::new();
for entry in package.equivalent_entries() {
warnings.push(Warning::PartSkipped {
part: f_office_warnings::Name::new(entry),
reason: Reason::Equivalent,
});
}
warnings
}
pub fn layout_lines(
package: &Package,
(fonts, art): (&f_office_fonts::FontDb, &ArtPictures),
options: &Options,
) -> Result<Warned<LaidOut>, Error> {
let profile = options.profile().map_err(Error::Configuration)?;
let font_choice = FontChoice::of(fonts, &profile);
let laid_out = lay_out(package, (&font_choice, art), options, &profile)?;
Ok(laid_out.map(|laid_out| LaidOut {
list: font_choice.draw_symbol_stand_ins(laid_out.list),
..laid_out
}))
}
pub(crate) fn layout_with_fonts(
package: &Package,
(fonts, art): (&dyn Fonts, &ArtPictures),
options: &Options,
) -> Result<Warned<LaidOut>, Error> {
let profile = options.profile().map_err(Error::Configuration)?;
lay_out(package, (fonts, art), options, &profile)
}
fn lay_out(
package: &Package,
(fonts, art): (&dyn Fonts, &ArtPictures),
options: &Options,
profile: &profile::Profile,
) -> Result<Warned<LaidOut>, Error> {
let mut warnings = equivalent_entries(package);
let paragraph_ids = ParagraphIds::default();
let (quirks, device, reader, zone_minutes) = quirks_and_device(profile)?;
let device = device.with_device_places(options.device_places);
let main = package.main_document().map_err(Error::Package)?;
let (mut doc, root) = parts::parse_text(package, (Role::Main, &main), reader, &mut warnings)?
.ok_or(Error::MissingPart(main.clone()))?;
let relationships = parts::relationships(package, &main, &mut warnings)?;
let related =
|suffix: &str| Relationship::by_type(relationships, suffix).map(|rel| rel.target.clone());
let mut reading = Reading {
warnings: &mut warnings,
ids: ¶graph_ids,
settings: reader,
notes: None,
colors: f_office_drawingml::color::SchemeColors::default(),
styles: None,
};
let (settings, styles, theme, table, numbering) =
read_main_parts(package, &related, (&doc, root), &mut reading)?;
reading.styles = Some(&styles);
reader.prepare_toc_links(&mut doc, (&main, ¶graph_ids), &styles);
let (notes, endnotes) = read_footnotes_and_endnotes(
package,
&related,
(&styles, &theme, &settings),
&mut reading,
)?;
let body_node = doc.child(root, ns::W, "body").ok_or(Error::NoBody)?;
let comments = read_comments(package, &related, (&doc, body_node), &theme, &mut reading)?;
let mut body = parts::read_with(&doc, (&main, body_node), &mut reading, |part, node| {
Body::read(part, node, (reader, settings.mode_rules))
});
drop(doc);
body.place_pages(&reader.template_section(), settings.gutter_at_top);
attach_parts(
package,
(&main, relationships),
&theme,
&mut [&mut body.blocks],
&mut reading,
);
mark_buffers(&mut body.blocks, reader, relationships);
let shaper_settings = text::ShaperSettings::of(&settings, &quirks, device.dot_size());
let shaper = Shaper::new(fonts, &theme, &table, &shaper_settings);
let mut stories = StoryParts::new(
package,
relationships,
(reader, &styles, &theme),
¶graph_ids,
);
let sections = body.sections.try_map(|part| {
Ok::<_, Error>(SectionLayout {
section: part.section,
start: part.start,
end: part.end,
restarts_numbers: part.restarts_numbers,
headers: stories.stories(&part.headers, reading.warnings)?,
footers: stories.stories(&part.footers, reading.warnings)?,
borders: part.borders,
notes: part.notes.over(settings.notes),
})
})?;
warn_of_note_positions(§ions, (¬es, &endnotes), &main, reading.warnings);
let web_part = related(ns::REL_WEB_SETTINGS);
let html_divs = web_settings::HtmlDivs::of_part(package, web_part, (¶graph_ids, reader));
let context = Context {
main: &main,
styles: &styles,
settings: &settings,
html_divs: &html_divs,
numbering,
notes,
endnotes,
comments,
device,
quirks,
now: options.now,
properties: std::sync::Arc::new(read_custom_properties(package, &mut reading)?),
zone_minutes,
earlier: EarlierPass::default(),
deleted_cell_label: paragraph_ids.next(),
art,
};
let paragraphs = text_addresses::story_paragraphs(
&body.blocks,
§ions,
(&context.notes, &context.endnotes),
);
let pass = run_passes(context, (§ions, shaper), &body);
LaidOut::of(
pass,
(&body, &styles, paragraphs),
(html_divs, fonts, profile.writer()),
warnings,
)
}
impl LaidOut {
fn of(
pass: Pass,
(body, styles, paragraphs): (&body::Body, &Styles, text_addresses::StoryParagraphs),
(html_divs, fonts, writer): (
web_settings::HtmlDivs<'_>,
&dyn Fonts,
f_office_paint::Writer,
),
mut warnings: Warnings,
) -> Result<Warned<Self>, Error> {
warnings.extend(pass.warnings, std::convert::identity);
warnings.extend(html_divs.finish()?, std::convert::identity);
warnings::of_fonts(&pass.font_notes, fonts, &mut warnings);
let (lines, turned) = text_map::turned_apart(pass.lines);
let toc = body.table_of_contents.as_ref();
let text_blocks = text_blocks::text_blocks(&body.blocks, &lines, (styles, toc));
let laid_out = Self {
text_blocks,
text_map: TextMap::new(paragraphs, turned),
list: pass.list,
lines,
tables: pass.tables,
writer,
};
Ok(Warned::new(laid_out, warnings))
}
}
impl Default for Options {
fn default() -> Self {
Self {
now: None,
configuration: Configuration::of(Target::default()),
#[cfg(any(test, feature = "development"))]
overrides: profile::Overrides::default(),
device_places: false,
}
}
}
impl Options {
#[cfg(test)]
pub(crate) fn base() -> Self {
Self {
configuration: Configuration::of(Target::base()),
..Self::default()
}
}
pub(crate) fn profile(&self) -> Result<profile::Profile, profile::Error> {
#[cfg(any(test, feature = "development"))]
let overrides = &self.overrides;
#[cfg(not(any(test, feature = "development")))]
let overrides = &profile::Overrides::default();
profile::Profile::resolve(&self.configuration, overrides)
}
}
fn quirks_and_device(
profile: &profile::Profile,
) -> Result<(quirks::Quirks, grid::Device, ReaderSettings, i32), Error> {
Ok((
profile.quirks(),
profile.device(),
profile.reader_settings(),
profile.zone_minutes().map_err(Error::Configuration)?,
))
}
fn run_passes(
context: Context<'_>,
sections_and_shaper: (&Sections<SectionLayout>, Shaper<'_>),
body: &Body,
) -> Pass {
timing::span("layout", || {
layout_passes(context, sections_and_shaper, body)
})
}
fn layout_passes(
mut context: Context<'_>,
(sections, shaper): (&Sections<SectionLayout>, Shaper<'_>),
body: &Body,
) -> Pass {
let stories = context.for_stories();
let first_pass =
Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
let counts = body::refers_to_pages(&body.blocks);
let header_fields = stories_refer_to_styles(sections);
if !counts
&& first_pass.wraps.is_empty()
&& !header_fields
&& first_pass.note_places.is_empty()
&& first_pass.later_anchors.is_empty()
&& !first_pass.notes_missed
{
return first_pass;
}
let page_count = f_office_units::count_factor(first_pass.list.pages().len());
let stored_refs = body::refers_to_pages_and_numbers(&body.blocks);
let mut font_notes = first_pass.font_notes;
context.earlier = EarlierPass {
page_count: counts.then_some(page_count),
wraps: first_pass.wraps,
bookmarks: Some(first_pass.bookmarks),
bookmark_numbers: first_pass.bookmark_numbers,
stored_number_refs: stored_refs,
header_styles: if header_fields {
first_pass.styles
} else {
HeaderStyles::default()
},
note_places: first_pass.note_places,
later_anchors: first_pass.later_anchors,
note_heights: first_pass.note_heights,
};
let mut pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
for _ in 0..params::FURTHER_PASSES {
let moved = context.earlier.wraps.after(&pass.wraps);
let grew = context.earlier.later_anchors.join(&pass.later_anchors);
if moved.is_none()
&& context.earlier.bookmarks.as_ref() == Some(&pass.bookmarks)
&& pass.bookmark_numbers == context.earlier.bookmark_numbers
&& pass.note_places == context.earlier.note_places
&& !grew
&& !pass.notes_missed
{
break;
}
if let Some(wraps) = moved {
context.earlier.wraps = wraps;
}
context.earlier.bookmarks = Some(pass.bookmarks);
context.earlier.bookmark_numbers = pass.bookmark_numbers;
context.earlier.note_places = pass.note_places;
context.earlier.note_heights = pass.note_heights;
font_notes.add(pass.font_notes);
drop(pass.list);
drop(pass.lines);
drop(pass.tables);
pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
}
if stored_refs {
context.earlier.bookmarks = Some(pass.bookmarks);
context.earlier.stored_number_refs = false;
font_notes.add(pass.font_notes);
drop(pass.list);
drop(pass.lines);
drop(pass.tables);
pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
}
font_notes.add(pass.font_notes);
pass.font_notes = font_notes;
pass
}
fn read_comments(
package: &Package,
related: &dyn Fn(&str) -> Option<String>,
(doc, body): (&Document, f_office_xml::NodeId),
theme: &Theme,
reading: &mut Reading<'_>,
) -> Result<comments::Comments, Error> {
if !reading.settings.prints_comments() {
return Ok(comments::Comments::default());
}
let target = related(ns::REL_COMMENTS);
let mut comments = parts::read(
package,
(Role::Comments, target.clone()),
reading,
comments::Comments::read,
)?;
if let Some(target) = target {
let own = parts::relationships(package, &target, reading.warnings)?;
let mut by_id: Vec<_> = comments.by_id.iter_mut().collect();
by_id.sort_unstable_by(|a, b| a.0.cmp(b.0));
let mut stories: Vec<&mut [Block]> = by_id
.into_iter()
.map(|(_, comment)| comment.blocks.as_mut_slice())
.collect();
attach_parts(package, (&target, own), theme, &mut stories, reading);
}
let parents = parts::read(
package,
(Role::Comments, related(ns::REL_COMMENTS_EXTENDED)),
reading,
|reader, root| comments::read_parents(reader.doc, root),
)?;
comments.link_replies(&parents);
comments.hide(&comments::marked_outside_paragraphs(doc, body));
comments.deleted_cells = comments::holds_deleted_cells(doc, body);
Ok(comments)
}
fn stories_refer_to_styles(sections: &Sections<SectionLayout>) -> bool {
let stories = |s: &Stories| {
[&s.default, &s.first, &s.even]
.into_iter()
.flatten()
.any(|story| body::refers_to_styles(&story.blocks))
};
sections
.iter()
.any(|s| stories(&s.headers) || stories(&s.footers))
}
fn warn_of_note_positions(
sections: &Sections<SectionLayout>,
(notes, endnotes): (&body::Notes, &body::Notes),
main: &str,
warnings: &mut Warnings,
) {
let mut warn = |feature| {
warnings.push(Warning::FeatureNotSupported {
part: f_office_warnings::Name::new(main),
feature,
});
};
for section in sections {
if !notes.by_id.is_empty() && section.notes.footnotes.position != NotePosition::PageBottom {
warn(Feature::FootnotePosition);
}
if !endnotes.by_id.is_empty() && section.notes.endnotes.position == NotePosition::SectionEnd
{
warn(Feature::EndnotePosition);
}
}
}
fn mark_buffers(blocks: &mut [Block], settings: ReaderSettings, relationships: &[Relationship]) {
let target = |id: &str| {
relationships
.iter()
.find(|rel| rel.id == id && rel.external)
.map_or(0, |rel| buffers::address_characters(&rel.target))
};
buffers::mark(
blocks,
&buffers::Counting {
settings,
target: &target,
},
);
}
fn attach_parts(
package: &Package,
part: (&str, &[Relationship]),
theme: &Theme,
stories: &mut [&mut [Block]],
reading: &mut Reading<'_>,
) {
{
let mut find = diagrams(package, part, &theme.shapes, reading);
for blocks in stories.iter_mut() {
smartart::attach_drawings(blocks, &mut find);
}
}
{
let mut find = charts(package, part, reading);
for blocks in stories.iter_mut() {
chart::attach_charts(blocks, &mut find);
}
}
let inks = reading.settings.ink_conversion();
let mut find = images(package, part, inks, reading.warnings);
for blocks in stories.iter_mut() {
picture::attach_images(blocks, &mut find);
body::links::give_addresses(blocks, part.1);
}
}
fn images<'a>(
package: &'a Package,
(source, relationships): (&'a str, &'a [Relationship]),
inks: InkConversion,
warnings: &'a mut Warnings,
) -> impl FnMut(&str) -> Option<Image> + 'a {
let mut loaded: HashMap<&str, Option<Image>> = HashMap::new();
move |id| {
let Some(rel) = Relationship::by_id(relationships, id) else {
warnings.push(warnings::skipped(
Drawing::Picture,
source,
Reason::Unlinked,
));
return None;
};
let image = loaded
.entry(rel.target.as_str())
.or_insert_with(|| {
let image = package
.read_part(&rel.target)
.ok()
.flatten()
.map(|data| Image {
inks,
..Image::new(data)
});
if let Some(image) = &image {
warnings::of_metafile(image, &rel.target, warnings);
}
image
})
.clone();
if image.is_none() {
warnings.push(warnings::skipped(
Drawing::Picture,
&rel.target,
Reason::Missing,
));
}
image
}
}
fn diagrams<'a>(
package: &'a Package,
part: (&'a str, &'a [Relationship]),
theme: &'a f_office_drawingml::theme::ShapeTheme,
reading: &'a mut Reading<'_>,
) -> impl FnMut(&smartart::Diagram) -> smartart::Parts + 'a {
move |diagram| {
let found = related_xml(package, part, &diagram.data, reading.warnings);
let (data_name, data, data_root) = match found {
Ok(found) => found,
Err((name, reason)) => {
reading
.warnings
.push(warnings::skipped(Drawing::SmartArt, &name, reason));
return Vec::new();
}
};
let colors = diagram
.colors
.as_deref()
.map(|id| related_xml(package, part, id, reading.warnings));
let text_colors = match colors {
Some(Ok((colors_name, doc, root))) => {
parts::read_with(&doc, (&colors_name, root), reading, |reader, root| {
smartart::text_colors((&data, data_root), (reader, root), theme)
})
}
Some(Err((name, reason))) => {
reading.warnings.push(Warning::PartSkipped {
part: f_office_warnings::Name::new(&name),
reason,
});
HashMap::default()
}
None => HashMap::default(),
};
let Some(drawing) = smartart::drawing_id(&data, data_root) else {
reading.warnings.push(warnings::skipped(
Drawing::SmartArt,
&data_name,
Reason::Unsupported,
));
return Vec::new();
};
match related_xml(package, part, &drawing, reading.warnings) {
Ok((name, doc, root)) => {
parts::read_with(&doc, (&name, root), reading, |reader, root| {
smartart::read_drawing(reader, root, theme, &text_colors)
})
}
Err((name, reason)) => {
reading
.warnings
.push(warnings::skipped(Drawing::SmartArt, &name, reason));
Vec::new()
}
}
}
}
fn charts<'a>(
package: &'a Package,
part: (&'a str, &'a [Relationship]),
reading: &'a mut Reading<'_>,
) -> impl FnMut(&str) -> Option<chart::Part> + 'a {
let rules = reading.settings.plot_rules();
move |id| match related_xml(package, part, id, reading.warnings) {
Ok((name, doc, root)) => {
let chart = parts::read_with(&doc, (&name, root), reading, |reader, space| {
chart::read(reader, space, rules)
});
chart
.inspect_err(|&reason| {
reading.warnings.push(warnings::skipped(
Drawing::Chart,
&name,
Reason::Chart(reason),
));
})
.ok()
}
Err((name, reason)) => {
reading
.warnings
.push(warnings::skipped(Drawing::Chart, &name, reason));
None
}
}
}
fn related_xml(
package: &Package,
(source, relationships): (&str, &[Relationship]),
id: &str,
warnings: &mut Warnings,
) -> Result<(String, Document, f_office_xml::NodeId), (String, Reason)> {
let rel = Relationship::by_id(relationships, id)
.ok_or_else(|| (source.to_owned(), Reason::Unlinked))?;
let fault = |reason| (rel.target.clone(), reason);
let bytes = package
.read_part(&rel.target)
.ok()
.flatten()
.ok_or_else(|| fault(Reason::Missing))?;
let (doc, root) =
parts::xml(package, (&rel.target, &bytes), warnings).map_err(|_| fault(Reason::NotXml))?;
Ok((rel.target.clone(), doc, root))
}
fn read_footnotes_and_endnotes(
package: &Package,
related: &dyn Fn(&str) -> Option<String>,
(styles, theme, settings): (&Styles, &Theme, &Settings),
reading: &mut Reading<'_>,
) -> Result<(body::Notes, body::Notes), Error> {
let parts = (styles, theme);
let endnotes = read_notes(package, related(ns::REL_ENDNOTES), parts, reading)?;
let notes = read_notes(package, related(ns::REL_FOOTNOTES), parts, reading)?;
let notes = match settings.footnote_separators {
styles::NoteSeparators::Listed => notes,
styles::NoteSeparators::Own => {
notes.with_own_separator(reading.ids, &reading.settings.own_separator_props())
}
};
reading.notes = Some(note_setup::ByNoteKind {
footnotes: notes.ids(),
endnotes: endnotes.ids(),
});
Ok((notes, endnotes))
}
fn read_custom_properties(
package: &Package,
reading: &mut Reading<'_>,
) -> Result<properties::Properties, Error> {
let own = parts::relationships(package, parts::PACKAGE, reading.warnings)?;
let custom =
Relationship::by_type(own, ns::REL_CUSTOM_PROPERTIES).map(|rel| rel.target.clone());
parts::read(
package,
(Role::CustomProperties, custom),
reading,
|reader, root| properties::read(reader.doc, root),
)
}
fn read_notes(
package: &Package,
target: Option<String>,
(styles, theme): (&Styles, &Theme),
reading: &mut Reading<'_>,
) -> Result<body::Notes, Error> {
let settings = reading.settings;
let mut notes = parts::read_text(
package,
(Role::Notes, target.clone()),
styles,
reading,
|reader, root| body::Notes::read(reader, root, settings),
)?;
if let Some(target) = target {
let own = parts::relationships(package, &target, reading.warnings)?;
let mut stories: Vec<&mut [Block]> =
notes.by_id.values_mut().map(Vec::as_mut_slice).collect();
attach_parts(package, (&target, own), theme, &mut stories, reading);
}
Ok(notes)
}
struct StoryParts<'p> {
package: &'p Package,
relationships: &'p [Relationship],
settings: ReaderSettings,
styles: &'p Styles,
theme: &'p Theme,
ids: &'p ParagraphIds,
read: HashMap<String, Option<PartStory>>,
}
impl<'p> StoryParts<'p> {
fn new(
package: &'p Package,
relationships: &'p [Relationship],
(settings, styles, theme): (ReaderSettings, &'p Styles, &'p Theme),
ids: &'p ParagraphIds,
) -> Self {
Self {
package,
relationships,
settings,
styles,
theme,
ids,
read: HashMap::new(),
}
}
fn stories(&mut self, refs: &References, warnings: &mut Warnings) -> Result<Stories, Error> {
Ok(Stories {
default: self.story(refs.default.as_deref(), warnings)?,
first: self.story(refs.first.as_deref(), warnings)?,
even: self.story(refs.even.as_deref(), warnings)?,
})
}
fn story(
&mut self,
id: Option<&str>,
warnings: &mut Warnings,
) -> Result<Option<PartStory>, Error> {
let Some(target) = id.and_then(|id| {
Relationship::by_id(self.relationships, id).map(|rel| rel.target.clone())
}) else {
return Ok(None);
};
if let Some(story) = self.read.get(&target) {
return Ok(story.clone());
}
let story = self.read_story(&target, warnings)?.map(|blocks| PartStory {
part: Rc::from(target.as_str()),
blocks: Rc::from(blocks),
});
self.read.insert(target, story.clone());
Ok(story)
}
fn read_story(
&self,
target: &str,
warnings: &mut Warnings,
) -> Result<Option<Vec<Block>>, Error> {
let package = self.package;
let mut reading = Reading {
warnings,
ids: self.ids,
settings: self.settings,
notes: None,
colors: self.theme.shapes.colors,
styles: Some(self.styles),
};
let mut story = parts::read_text(
package,
(Role::Story, Some(target.to_owned())),
self.styles,
&mut reading,
|reader, root| Some(read_header_story(reader, root, self.settings)),
)?;
if let Some(paragraphs) = &mut story {
let own = parts::relationships(package, target, reading.warnings)?;
let stories: &mut [&mut [Block]] = &mut [paragraphs];
attach_parts(package, (target, own), self.theme, stories, &mut reading);
}
Ok(story)
}
}
fn read_main_parts(
package: &Package,
related: &dyn Fn(&str) -> Option<String>,
main: (&Document, f_office_xml::NodeId),
reading: &mut Reading<'_>,
) -> Result<(Settings, Styles, Theme, FontTable, Numbering), Error> {
let settings_of_reader = reading.settings;
let mut settings = parts::read(
package,
(Role::Settings, related(ns::REL_SETTINGS)),
reading,
|reader, root| {
let settings = Settings::read(reader, root);
settings_of_reader.check_hyphenation(reader, settings.hyphenation.is_some());
settings
},
)?;
settings.page_color = props::read_page_color(main.0, main.1);
let (styles, theme) = read_styles_and_theme(package, related, &settings, reading)?;
let table = parts::read(
package,
(Role::FontTable, related(ns::REL_FONT_TABLE)),
reading,
|reader, root| FontTable::read(reader.doc, root),
)?;
let numbering = match related(ns::REL_NUMBERING) {
Some(name) => {
let mut numbering = parts::read(
package,
(Role::Numbering, Some(name.clone())),
reading,
|reader, root| Numbering::read(reader, root, settings_of_reader),
)?;
if numbering.has_picture_embeds() {
let rels = parts::relationships(package, &name, reading.warnings)?;
let inks = reading.settings.ink_conversion();
let mut find = images(package, (&name, rels), inks, reading.warnings);
numbering.attach_images(&mut find);
}
numbering
}
None => Numbering::without_part(settings_of_reader),
};
Ok((settings, styles, theme, table, numbering))
}
fn read_styles_and_theme(
package: &Package,
related: &dyn Fn(&str) -> Option<String>,
settings: &Settings,
reading: &mut Reading<'_>,
) -> Result<(Styles, Theme), Error> {
let theme_part = related(ns::REL_THEME);
let parsed = match &theme_part {
Some(name) => parts::parse(package, Role::Theme, name, reading.warnings)?,
None => None,
};
let theme = match (parsed, theme_part) {
(Some((doc, root)), Some(name)) => {
parts::read_with(&doc, (&name, root), reading, Theme::read)
}
_ => reading.settings.template_theme(),
};
reading.colors = theme.shapes.colors;
let styles_part = related(ns::REL_STYLES);
let parsed = match &styles_part {
Some(name) => parts::parse(package, Role::Styles, name, reading.warnings)?,
None => None,
};
let mut styles = match (parsed, styles_part) {
(Some((doc, root)), Some(name)) => {
parts::read_with(&doc, (&name, root), reading, Styles::read)
}
_ => Styles::without_part(),
};
reading
.settings
.link_template_styles(settings.template_styles, &mut styles);
reading.settings.refer_paragraphs(&mut styles);
Ok((styles, theme))
}