use f_office_paint::Orientation;
use f_office_units::{Edges, Length};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::note_setup::{ByNoteKind, NoteProps};
use crate::ns::W;
use crate::numbering::{Format, format_number, read_format};
use crate::numbers;
use crate::on_off;
use crate::props::{
ArtStyle, BORDER_NAMES, Color, Gap, LineStyle, Relief, parse_color, read_border_as,
read_line_style,
};
use crate::reader::PartReader;
use crate::styles::SideMargins;
use crate::table::turns_text;
use crate::warnings::Feature;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct References {
pub default: Option<String>,
pub first: Option<String>,
pub even: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Section {
pub width: Length,
pub height: Length,
pub orientation: Orientation,
pub top: Length,
pub right: Length,
pub bottom: Length,
pub left: Length,
pub gutter: Length,
pub header: Length,
pub footer: Length,
pub fixed: (bool, bool),
pub title_page: bool,
pub right_to_left: bool,
pub first_page_number: i64,
pub page_number_format: Format,
pub chapter: Option<Chapter>,
pub columns: Columns,
pub vertical: PageAlign,
pub line_pitch: Option<Length>,
pub(crate) spacing_line_pitch: Option<Length>,
pub char_pitch: Option<Length>,
pub line_numbers: Option<LineNumbers>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineNumbers {
pub count_by: i64,
pub start: i64,
pub distance: Length,
pub restart: LineNumberRestart,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineNumberRestart {
#[default]
NewPage,
NewSection,
Continuous,
}
pub(super) const LINE_NUMBER_RESTART: &Values<LineNumberRestart> = &Values::new(&[
own("newPage", LineNumberRestart::NewPage),
own("newSection", LineNumberRestart::NewSection),
own("continuous", LineNumberRestart::Continuous),
]);
pub(super) const PAGE_ORIENTATION: &Values<Orientation> = &Values::new(&[
own("portrait", Orientation::Portrait),
own("landscape", Orientation::Landscape),
]);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PageAlign {
#[default]
Top,
Center,
Bottom,
}
use crate::params::{
CHAR_SPACE_STEPS, COLUMN_SPACE, DEFAULT_HEADER_DISTANCE, DEFAULT_MARGIN, DEFAULT_PAGE_SIZE,
HEADING_LEVELS, LINE_NUMBER_DISTANCE, MAX_COLUMN_COUNT, MAX_COLUMNS,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Columns {
pub count: usize,
pub space: Length,
pub widths: Option<[(Length, Length); MAX_COLUMNS]>,
pub separator: bool,
}
impl Default for Columns {
fn default() -> Self {
Self {
count: 1,
space: COLUMN_SPACE,
widths: None,
separator: false,
}
}
}
impl Columns {
#[must_use]
pub fn areas(
&self,
left: Length,
width: Length,
equal: impl FnOnce(Length) -> Length,
) -> Vec<(Length, Length)> {
let count = self.count.max(1);
if count == 1 {
return vec![(left, width)];
}
if let Some(widths) = self.widths {
let mut x = left;
return widths
.iter()
.take(count)
.map(|&(column, space)| {
let area = (x, column);
x += column + space;
area
})
.collect();
}
let n = i64::try_from(count).unwrap_or(1);
let exact = (width - self.space * (n - 1)).div_toward_zero(n);
let column = equal(exact);
(0..n)
.map(|i| (left + (column + self.space) * i, column))
.collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Chapter {
pub level: u8,
pub separator: ChapterSeparator,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChapterSeparator {
Hyphen,
Period,
Colon,
EmDash,
EnDash,
}
impl ChapterSeparator {
#[must_use]
pub fn char(self) -> char {
match self {
Self::Hyphen => '-',
Self::Period => '.',
Self::Colon => ':',
Self::EmDash => '\u{2014}',
Self::EnDash => '\u{2013}',
}
}
}
pub(super) const CHAPTER_SEPARATOR: &Values<ChapterSeparator> = &Values::new(&[
own("hyphen", ChapterSeparator::Hyphen),
own("period", ChapterSeparator::Period),
own("colon", ChapterSeparator::Colon),
own("emDash", ChapterSeparator::EmDash),
own("enDash", ChapterSeparator::EnDash),
]);
impl Section {
pub(crate) fn same_page_size(&self, other: &Self) -> bool {
self.width == other.width
&& self.height == other.height
&& self.orientation == other.orientation
}
#[must_use]
pub fn page_number(&self, number: i64) -> String {
format_number(number, self.page_number_format)
}
#[must_use]
pub fn with_gutter_at_top(mut self) -> Self {
self.left = self.left.checked_sub(self.gutter).unwrap_or(self.left);
self.top = self.top.checked_add(self.gutter).unwrap_or(self.top);
self.gutter = Length::ZERO;
self
}
#[must_use]
pub fn side_margins(&self, mode: SideMargins, even: bool) -> (Length, Length) {
match mode {
SideMargins::Section => (self.left, self.right),
SideMargins::Mirrored => {
if even {
(self.right, self.left)
} else {
(self.left, self.right)
}
}
SideMargins::BookFold | SideMargins::BookFoldReverse => {
let outside = self.left.checked_sub(self.gutter).unwrap_or(self.left);
if self.orientation != Orientation::Landscape {
return (outside, self.right);
}
let inside = self.right.checked_add(self.gutter).unwrap_or(self.right);
let inside_on_left = matches!(mode, SideMargins::BookFold) ^ even;
if inside_on_left {
(inside, outside)
} else {
(outside, inside)
}
}
}
}
}
impl Default for Section {
fn default() -> Self {
let (width, height) = DEFAULT_PAGE_SIZE;
Self {
width,
height,
orientation: Orientation::Portrait,
top: DEFAULT_MARGIN,
right: DEFAULT_MARGIN,
bottom: DEFAULT_MARGIN,
left: DEFAULT_MARGIN,
gutter: Length::ZERO,
header: DEFAULT_HEADER_DISTANCE,
footer: DEFAULT_HEADER_DISTANCE,
fixed: (false, false),
title_page: false,
right_to_left: false,
first_page_number: 1,
page_number_format: Format::Decimal,
chapter: None,
columns: Columns::default(),
vertical: PageAlign::Top,
line_pitch: None,
spacing_line_pitch: None,
char_pitch: None,
line_numbers: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SectionStart {
#[default]
NextPage,
Continuous,
EvenPage,
OddPage,
}
pub(super) const SECTION_MARK: &Values<SectionStart> = &Values::new(&[
own("nextPage", SectionStart::NextPage),
another("nextColumn", SectionStart::NextPage),
own("continuous", SectionStart::Continuous),
own("evenPage", SectionStart::EvenPage),
own("oddPage", SectionStart::OddPage),
]);
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sections<T> {
first: T,
rest: Vec<T>,
}
impl<T> Sections<T> {
#[must_use]
pub const fn one(section: T) -> Self {
Self {
first: section,
rest: Vec::new(),
}
}
#[must_use]
pub fn ending_with(before: Vec<T>, last: T) -> Self {
let mut before = before.into_iter();
match before.next() {
Some(first) => Self {
first,
rest: before.chain(std::iter::once(last)).collect(),
},
None => Self::one(last),
}
}
#[must_use]
pub const fn first(&self) -> &T {
&self.first
}
#[must_use]
pub fn last(&self) -> &T {
self.rest.last().unwrap_or(&self.first)
}
#[must_use]
pub fn get(&self, index: usize) -> Option<&T> {
match index.checked_sub(1) {
Some(after_first) => self.rest.get(after_first),
None => Some(&self.first),
}
}
#[must_use]
pub const fn count(&self) -> usize {
self.rest.len() + 1
}
pub fn iter(&self) -> std::iter::Chain<std::iter::Once<&T>, std::slice::Iter<'_, T>> {
std::iter::once(&self.first).chain(&self.rest)
}
pub fn iter_mut(
&mut self,
) -> std::iter::Chain<std::iter::Once<&mut T>, std::slice::IterMut<'_, T>> {
std::iter::once(&mut self.first).chain(&mut self.rest)
}
pub fn try_map<U, E>(
&self,
mut make: impl FnMut(&T) -> Result<U, E>,
) -> Result<Sections<U>, E> {
Ok(Sections {
first: make(&self.first)?,
rest: self.rest.iter().map(make).collect::<Result<_, _>>()?,
})
}
}
impl<'a, T> IntoIterator for &'a Sections<T> {
type Item = &'a T;
type IntoIter = std::iter::Chain<std::iter::Once<&'a T>, std::slice::Iter<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Sections<T> {
type Item = &'a mut T;
type IntoIter = std::iter::Chain<std::iter::Once<&'a mut T>, std::slice::IterMut<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SectionPart {
pub section: Section,
pub headers: References,
pub footers: References,
pub start: SectionStart,
pub end: usize,
pub restarts_numbers: bool,
pub borders: Option<PageBorders>,
pub notes: ByNoteKind<NoteProps>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PageBorders {
pub sides: Edges<Option<PageSide>>,
pub from_page: bool,
pub pages: BorderPages,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageSide {
Line(crate::props::Border),
Art(ArtSide),
}
impl PageSide {
#[must_use]
pub const fn line(self) -> Option<crate::props::Border> {
match self {
Self::Line(border) => Some(border),
Self::Art(_) => None,
}
}
#[must_use]
pub const fn art(self) -> Option<ArtSide> {
match self {
Self::Line(_) => None,
Self::Art(art) => Some(art),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ArtSide {
pub style: ArtStyle,
pub size: u32,
pub space: Length,
pub color: Color,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BorderPages {
#[default]
All,
First,
NotFirst,
}
pub(super) const BORDER_DISPLAY: &Values<BorderPages> = &Values::new(&[
own("allPages", BorderPages::All),
own("firstPage", BorderPages::First),
own("notFirstPage", BorderPages::NotFirst),
]);
pub(super) const BORDER_OFFSET: &Values<bool> =
&Values::new(&[own("page", true), own("text", false)]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum DocGrid {
None,
Lines,
LinesAndChars,
SnapToChars,
}
pub(super) const DOC_GRID: &Values<DocGrid> = &Values::new(&[
own("default", DocGrid::None),
own("lines", DocGrid::Lines),
own("linesAndChars", DocGrid::LinesAndChars),
another("snapToChars", DocGrid::SnapToChars),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HeaderKind {
Default,
First,
Even,
}
pub(super) const HEADER_KIND: &Values<HeaderKind> = &Values::new(&[
own("default", HeaderKind::Default),
own("first", HeaderKind::First),
own("even", HeaderKind::Even),
]);
pub(super) const SECTION_V_ALIGN: &Values<PageAlign> = &Values::new(&[
own("top", PageAlign::Top),
own("center", PageAlign::Center),
another("both", PageAlign::Top),
own("bottom", PageAlign::Bottom),
]);
pub(crate) fn first_column_width(reader: &mut PartReader, node: NodeId) -> Option<Length> {
let section = read_section(reader, node);
let width = section.width - section.left - section.right;
let (_, column) = *section
.columns
.areas(Length::ZERO, width, |exact| exact)
.first()?;
(column > Length::ZERO).then_some(column)
}
pub(super) fn read_section_part(reader: &mut PartReader, node: NodeId, end: usize) -> SectionPart {
let doc = reader.doc;
let start = doc
.child(node, W, "type")
.and_then(|n| reader.enumeration(n, "val", SECTION_MARK))
.unwrap_or_default();
let restarts_numbers = doc
.child(node, W, "pgNumType")
.and_then(|n| doc.attribute(n, Some(W), "start"))
.is_some();
warn_of_text_direction(reader, node);
SectionPart {
section: read_section(reader, node),
headers: read_references(reader, node, "headerReference"),
footers: read_references(reader, node, "footerReference"),
start,
end,
restarts_numbers,
borders: doc
.child(node, W, "pgBorders")
.and_then(|b| read_page_borders(reader, b)),
notes: ByNoteKind::read(reader, node),
}
}
fn warn_of_text_direction(reader: &mut PartReader, node: NodeId) {
let turned = reader
.doc
.child(node, W, "textDirection")
.and_then(|direction| reader.or_missing(direction, "val", turns_text))
.unwrap_or(false);
if turned {
reader.feature_not_supported(Feature::SectionTextDirection);
}
}
pub(super) const PAGE_BORDER_LINE: &Values<LineStyle> = &Values::with_others(
&[
own("nil", LineStyle::None),
own("none", LineStyle::None),
own("single", LineStyle::Single),
own("double", LineStyle::Double),
own("triple", LineStyle::Triple),
own("thinThickSmallGap", LineStyle::ThinThick(Gap::Small)),
own("thickThinSmallGap", LineStyle::ThickThin(Gap::Small)),
own(
"thinThickThinSmallGap",
LineStyle::ThinThickThin(Gap::Small),
),
own("thinThickMediumGap", LineStyle::ThinThick(Gap::Medium)),
own("thickThinMediumGap", LineStyle::ThickThin(Gap::Medium)),
own(
"thinThickThinMediumGap",
LineStyle::ThinThickThin(Gap::Medium),
),
another("thick", LineStyle::Single),
another("dotted", LineStyle::Single),
another("dashed", LineStyle::Single),
another("dotDash", LineStyle::Single),
another("dotDotDash", LineStyle::Single),
another("dashSmallGap", LineStyle::Single),
another("dashDotStroked", LineStyle::Single),
own("thinThickLargeGap", LineStyle::ThinThick(Gap::Large)),
own("thickThinLargeGap", LineStyle::ThickThin(Gap::Large)),
own(
"thinThickThinLargeGap",
LineStyle::ThinThickThin(Gap::Large),
),
another("wave", LineStyle::Single),
another("doubleWave", LineStyle::Single),
own("threeDEmboss", LineStyle::ThreeD(Relief::Emboss)),
own("threeDEngrave", LineStyle::ThreeD(Relief::Engrave)),
own("inset", LineStyle::Single),
own("outset", LineStyle::Single),
],
BORDER_NAMES,
LineStyle::None,
);
fn read_page_borders(reader: &mut PartReader, node: NodeId) -> Option<PageBorders> {
let doc = reader.doc;
let side = |name: &str| {
let side = doc.child(node, W, name)?;
if reader.border_styles().draws_art()
&& let Some(art) = read_art_side(reader, side)
{
return Some(PageSide::Art(art));
}
let style = read_line_style(reader, side, PAGE_BORDER_LINE)?;
read_border_as(reader, side, style).map(PageSide::Line)
};
let [top, left, bottom, right] = ["top", "left", "bottom", "right"].map(side);
let sides = Edges {
left,
top,
right,
bottom,
};
let pages = reader
.enumeration(node, "display", BORDER_DISPLAY)
.unwrap_or_default();
let from_page = reader
.enumeration(node, "offsetFrom", BORDER_OFFSET)
.unwrap_or(false);
[left, top, right, bottom]
.iter()
.any(Option::is_some)
.then_some(PageBorders {
sides,
from_page,
pages,
})
}
fn read_art_side(reader: &mut PartReader, node: NodeId) -> Option<ArtSide> {
let doc = reader.doc;
let style = doc
.attribute(node, Some(W), "val")
.and_then(ArtStyle::of_name)?;
let points = u32::try_from(reader.whole_number(node, "sz").unwrap_or(0)).unwrap_or(0);
let space = Length::from_points(reader.whole_number(node, "space").unwrap_or(0))?;
Some(ArtSide {
style,
size: points,
space,
color: doc
.attribute(node, Some(W), "color")
.map_or(Color::Auto, parse_color),
})
}
pub(super) fn inherit_references(sections: &mut Sections<SectionPart>) {
let mut previous: Option<(References, References)> = None;
for current in sections {
if let Some((headers, footers)) = &previous {
fill(&mut current.headers, headers);
fill(&mut current.footers, footers);
}
previous = Some((current.headers.clone(), current.footers.clone()));
}
}
fn fill(refs: &mut References, from: &References) {
for (slot, other) in [
(&mut refs.default, &from.default),
(&mut refs.first, &from.first),
(&mut refs.even, &from.even),
] {
if slot.is_none() {
slot.clone_from(other);
}
}
}
fn read_line_numbers(reader: &mut PartReader, node: NodeId) -> Option<LineNumbers> {
let count_by = reader
.number(node, "countBy", numbers::ANY)
.filter(|count| *count >= 1)?;
Some(LineNumbers {
count_by,
start: reader
.number(node, "start", numbers::ANY)
.unwrap_or(0)
.max(0),
distance: reader
.twips(node, "distance")
.unwrap_or(LINE_NUMBER_DISTANCE),
restart: reader
.enumeration(node, "restart", LINE_NUMBER_RESTART)
.unwrap_or_default(),
})
}
fn flag(doc: &Document, node: NodeId, name: &str) -> bool {
doc.child(node, W, name)
.is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
}
fn read_section(reader: &mut PartReader, node: NodeId) -> Section {
let doc = reader.doc;
let mut section = Section::default();
let mut twips = |child: Option<NodeId>, name: &str| child.and_then(|c| reader.twips(c, name));
let size = doc.child(node, W, "pgSz");
let margins = doc.child(node, W, "pgMar");
let [width, height] = ["w", "h"].map(|name| twips(size, name));
let [top, bottom, right, left, gutter, header, footer] = [
"top", "bottom", "right", "left", "gutter", "header", "footer",
]
.map(|name| twips(margins, name));
let set = |slot: &mut Length, value: Option<Length>| {
if let Some(value) = value {
*slot = value;
}
};
set(&mut section.width, width);
set(&mut section.height, height);
section.orientation = size
.and_then(|size| reader.enumeration(size, "orient", PAGE_ORIENTATION))
.unwrap_or_default();
set(&mut section.top, top.map(abs));
set(&mut section.bottom, bottom.map(abs));
let negative = |margin: Option<Length>| margin.is_some_and(|m| m.units() < 0);
if margins.is_some() {
section.fixed = (negative(top), negative(bottom));
}
set(&mut section.right, right);
set(&mut section.left, left);
if let Some(gutter) = gutter {
section.left = section.left.checked_add(gutter).unwrap_or(section.left);
section.gutter = gutter;
}
set(&mut section.header, header.map(abs));
set(&mut section.footer, footer.map(abs));
section.title_page = flag(doc, node, "titlePg");
section.right_to_left = flag(doc, node, "bidi");
section.line_numbers = doc
.child(node, W, "lnNumType")
.and_then(|n| read_line_numbers(reader, n));
let numbering = doc.child(node, W, "pgNumType");
if let Some(start) = numbering.and_then(|n| reader.number(n, "start", numbers::ANY)) {
section.first_page_number = start;
}
section.chapter = numbering.and_then(|n| {
let level = reader.number(n, "chapStyle", 1..=i64::from(HEADING_LEVELS))?;
let separator = reader
.enumeration(n, "chapSep", CHAPTER_SEPARATOR)
.unwrap_or(ChapterSeparator::Hyphen);
Some(Chapter { level, separator })
});
section.page_number_format = numbering
.and_then(|n| read_format(reader, n, "fmt"))
.unwrap_or(Format::Decimal);
if let Some(cols) = doc.child(node, W, "cols") {
section.columns = read_columns(reader, cols);
}
let grid = doc.child(node, W, "docGrid");
let kind = grid
.and_then(|grid| reader.enumeration(grid, "type", DOC_GRID))
.unwrap_or(DocGrid::None);
let pitch = grid
.filter(|_| kind != DocGrid::None)
.and_then(|grid| reader.twips(grid, "linePitch"))
.filter(|pitch| pitch.units() > 0);
section.line_pitch = pitch.filter(|_| matches!(kind, DocGrid::Lines | DocGrid::LinesAndChars));
section.spacing_line_pitch = pitch;
section.char_pitch = grid.filter(|_| kind == DocGrid::LinesAndChars).map(|grid| {
let space = reader
.number::<i32>(grid, "charSpace", numbers::ANY)
.unwrap_or(0);
let units = i64::from(space) * Length::UNITS_PER_POINT;
Length::from_units(f_office_units::div_round(units, CHAR_SPACE_STEPS))
});
section.vertical = doc
.child(node, W, "vAlign")
.and_then(|n| reader.enumeration(n, "val", SECTION_V_ALIGN))
.unwrap_or_default();
section
}
fn read_columns(reader: &mut PartReader, node: NodeId) -> Columns {
let doc = reader.doc;
let mut columns = Columns::default();
let count = reader
.number(node, "num", numbers::NOT_NEGATIVE)
.unwrap_or(1);
let mut twips = |n: NodeId, name: &str| reader.twips(n, name);
let flag = |name: &str| {
doc.attribute(node, Some(W), name)
.is_some_and(|v| on_off::read(v) != Some(false))
};
if let Some(space) = twips(node, "space") {
columns.space = space;
}
columns.separator = flag("sep");
let own: Vec<NodeId> = doc
.child_elements(node)
.filter(|c| doc.is(*c, W, "col"))
.collect();
let equal = doc
.attribute(node, Some(W), "equalWidth")
.is_none_or(|v| on_off::read(v) != Some(false));
if !equal && !own.is_empty() && own.len() <= MAX_COLUMNS {
let mut widths = [(Length::ZERO, Length::ZERO); MAX_COLUMNS];
for (slot, col) in widths.iter_mut().zip(&own) {
*slot = (
twips(*col, "w").unwrap_or(Length::ZERO),
twips(*col, "space").unwrap_or(Length::ZERO),
);
}
columns.widths = Some(widths);
columns.count = own.len();
} else {
columns.count = count.clamp(1, MAX_COLUMN_COUNT);
}
columns
}
fn read_references(reader: &mut PartReader, node: NodeId, name: &str) -> References {
let doc = reader.doc;
let mut refs = References::default();
for child in doc.child_elements(node).filter(|c| doc.is(*c, W, name)) {
let Some(id) = doc.attribute(child, Some(crate::ns::R), "id") else {
continue;
};
let slot = match reader.enumeration(child, "type", HEADER_KIND) {
Some(HeaderKind::First) => &mut refs.first,
Some(HeaderKind::Even) => &mut refs.even,
Some(HeaderKind::Default) | None => &mut refs.default,
};
*slot = Some(id.to_owned());
}
refs
}
fn abs(length: Length) -> Length {
Length::from_units(length.units().saturating_abs())
}