mod art_borders;
mod bidi;
mod chart;
mod columns;
mod decisions;
mod endnotes;
mod floating;
mod frames;
mod if_fields;
mod incremental_state;
mod line;
mod line_text;
mod markup;
mod measure;
mod metafile;
mod notes;
mod output;
mod page_items;
mod pages;
mod paragraph;
mod sections;
mod shadow;
mod style_refs;
mod table;
#[cfg(test)]
mod testing;
#[cfg(test)]
mod tests;
mod text_path;
pub use floating::{LaterAnchors, NoteHeights};
pub(crate) use incremental_state::{BodyCursor, LayoutState};
pub(crate) use line_text::RunSpan;
pub use line_text::{LineText, LineTextEnd, LineTurn, TextCluster};
pub(crate) use measure::{list_label_props, mark_run_props};
pub use notes::NotePlaces;
use std::borrow::Cow;
use std::rc::Rc;
use f_office_paint::{DisplayList, Item, Rect, Rgb};
use f_office_units::{Length, count_factor};
use crate::body::{Block, Body, NoteId, Notes, ParagraphId, Section, SectionStart, Sections};
use crate::comments::Comments;
use crate::dates::DateTime;
use crate::note_setup::{ByNoteKind, NoteLabel, NoteSetup};
use crate::numbering::{Label, NumberContext, Numbering};
use crate::props::{ParaProps, RunProps};
use crate::styles::{Settings, SideMargins, Styles, TableStyle};
use crate::table::Table;
use crate::text::Shaper;
use paragraph::{HeldBorders, NewPageSpace, Previous};
use sections::SectionIndex;
pub struct Context<'a> {
pub main: &'a str,
pub styles: &'a Styles,
pub settings: &'a Settings,
pub html_divs: &'a crate::web_settings::HtmlDivs<'a>,
pub numbering: Rc<Numbering>,
pub notes: Rc<Notes>,
pub endnotes: Rc<Notes>,
pub comments: Rc<Comments>,
pub device: crate::grid::Device,
pub quirks: crate::quirks::Quirks,
pub now: Option<DateTime>,
pub file_name: Option<&'a str>,
pub properties: std::sync::Arc<crate::properties::Properties>,
pub zone_minutes: i32,
pub earlier: EarlierPass,
pub deleted_cell_label: ParagraphId,
pub art: &'a crate::ArtPictures,
}
impl Context<'_> {
#[must_use]
pub fn for_stories(&self) -> Self {
Self {
numbering: Rc::new(Numbering::default()),
notes: Rc::new(Notes::default()),
endnotes: Rc::new(Notes::default()),
comments: Rc::new(Comments::default()),
properties: std::sync::Arc::clone(&self.properties),
earlier: EarlierPass::default(),
..*self
}
}
}
#[derive(Clone, Default)]
pub struct EarlierPass {
pub page_count: Option<i64>,
pub wraps: PageWraps,
pub bookmarks: Option<BookmarkPages>,
pub bookmark_numbers: BookmarkNumbers,
pub stored_number_refs: bool,
pub header_styles: HeaderStyles,
pub note_places: NotePlaces,
pub later_anchors: LaterAnchors,
pub note_heights: NoteHeights,
}
#[derive(Clone, Default)]
pub struct HeaderStyles(Option<std::rc::Rc<style_refs::StyledPages>>);
#[derive(Clone, Debug)]
pub struct SectionLayout {
pub section: Section,
pub start: SectionStart,
pub end: usize,
pub restarts_numbers: bool,
pub headers: Stories,
pub footers: Stories,
pub borders: Option<crate::body::PageBorders>,
pub notes: ByNoteKind<NoteSetup>,
}
impl SectionLayout {
#[must_use]
pub fn plain(section: &Section, blocks: usize) -> Self {
Self {
section: *section,
start: SectionStart::NextPage,
end: blocks,
restarts_numbers: false,
headers: Stories::default(),
footers: Stories::default(),
borders: None,
notes: ByNoteKind::DEFAULT,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PageInfo {
section: SectionIndex,
number: i64,
first: bool,
}
#[derive(Clone, Debug, Default)]
pub struct Stories {
pub default: Option<PartStory>,
pub first: Option<PartStory>,
pub even: Option<PartStory>,
}
#[derive(Clone, Debug)]
pub struct PartStory {
pub part: Rc<str>,
pub blocks: Rc<[Block]>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
First,
Even,
Default,
}
impl Stories {
fn get(&self, kind: Kind) -> Option<&PartStory> {
let story = match kind {
Kind::First => &self.first,
Kind::Even => &self.even,
Kind::Default => &self.default,
};
story.as_ref().filter(|story| !story.blocks.is_empty())
}
}
struct Resolved {
props: ParaProps,
run: RunProps,
label: Option<Label>,
label_shift: Length,
}
pub type BookmarkPages = std::collections::HashMap<String, String>;
pub type BookmarkNumbers = std::collections::HashMap<String, NumberContext>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Band {
top: Length,
bottom: Length,
left: Length,
right: Length,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum UpwardShape {
Band(Band),
Square(floating::Square),
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct UpwardWrap {
page: usize,
ordinal: usize,
y: Length,
wrap: UpwardShape,
}
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct WrapCounts {
bands: usize,
squares: usize,
upward: usize,
legacy_candidates: usize,
legacy_reflow_para: usize,
legacy_para_seq: usize,
}
#[derive(Clone, Debug, Default)]
pub struct PageWraps {
bands: Vec<(usize, Band)>,
squares: Vec<(usize, floating::Square)>,
upward: Vec<UpwardWrap>,
legacy_candidates: Vec<(usize, UpwardWrap)>,
legacy_reflow_para: Vec<(usize, usize)>,
legacy_para_seq: usize,
held: HeldPages,
}
#[derive(Clone, Debug, Default)]
struct HeldPages {
bands: Vec<usize>,
squares: Vec<usize>,
}
impl PageWraps {
fn counts(&self) -> WrapCounts {
WrapCounts {
bands: self.bands.len(),
squares: self.squares.len(),
upward: self.upward.len(),
legacy_candidates: self.legacy_candidates.len(),
legacy_reflow_para: self.legacy_reflow_para.len(),
legacy_para_seq: self.legacy_para_seq,
}
}
fn take_back(&mut self, counts: WrapCounts) {
self.bands.truncate(counts.bands);
self.squares.truncate(counts.squares);
self.upward.truncate(counts.upward);
self.legacy_candidates.truncate(counts.legacy_candidates);
self.legacy_reflow_para.truncate(counts.legacy_reflow_para);
self.legacy_para_seq = counts.legacy_para_seq;
}
fn next_legacy_para(&mut self) -> usize {
self.legacy_para_seq += 1;
self.legacy_para_seq
}
fn note_legacy_reflow(&mut self, page: usize, para_order: usize) {
self.legacy_reflow_para.push((page, para_order));
for (cand_para, entry) in &self.legacy_candidates {
if entry.page == page
&& *cand_para <= para_order
&& !self.upward.iter().any(|u| u.ordinal == entry.ordinal)
{
self.upward.push(entry.clone());
}
}
}
fn note_legacy_candidate(&mut self, para_order: usize, entry: UpwardWrap) {
if self
.legacy_reflow_para
.iter()
.any(|&(p, o)| p == entry.page && o >= para_order)
{
if !self.upward.iter().any(|u| u.ordinal == entry.ordinal) {
self.upward.push(entry);
}
} else {
self.legacy_candidates.push((para_order, entry));
}
}
pub fn is_empty(&self) -> bool {
self.bands.is_empty() && self.squares.is_empty() && self.upward.is_empty()
}
#[must_use]
pub fn after(&self, found: &Self) -> Option<Self> {
let given: Vec<usize> = self.pages().collect();
let pages: Vec<usize> = found.pages().collect();
let same_drawings =
self.bands.len() == found.bands.len() && self.squares.len() == found.squares.len();
let early_moved = same_drawings && given != pages;
let upward_moved = self.upward != found.upward;
if !early_moved && !upward_moved {
return None;
}
let mut next = found.clone();
next.legacy_candidates.clear();
next.legacy_reflow_para.clear();
next.legacy_para_seq = 0;
if early_moved {
let (bands, squares) = pages.split_at(self.bands.len());
let (given_bands, given_squares) = given.split_at(self.bands.len());
next.held = HeldPages {
bands: holds(&self.held.bands, given_bands, bands),
squares: holds(&self.held.squares, given_squares, squares),
};
} else {
next.held = self.held.clone();
}
Some(next)
}
fn pages(&self) -> impl Iterator<Item = usize> + '_ {
let bands = self.bands.iter().map(|(page, _)| *page);
bands.chain(self.squares.iter().map(|(page, _)| *page))
}
}
fn holds(held: &[usize], given: &[usize], found: &[usize]) -> Vec<usize> {
let before = |at: usize| held.get(at).copied().unwrap_or(0);
given
.iter()
.zip(found)
.enumerate()
.map(|(at, (given, found))| {
if found > given {
before(at).max(*found)
} else {
before(at)
}
})
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LineStory {
Body,
Header,
Footer,
Footnote,
TextBox,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StoryPart {
#[default]
Own,
Endnotes,
Frame(u32),
TextBox(u32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LineArea {
OutsideTables,
TableCell,
}
impl LineArea {
pub(crate) const fn of(paginate: bool) -> Self {
if paginate {
Self::OutsideTables
} else {
Self::TableCell
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BaselineForm {
SingleBottom,
SingleTop,
AtLeastBox,
ExactBox,
Bottom,
SpacedBottom,
HeldSpaces,
SpaceAndAscent,
WholeDotsBelowTop,
GridSteps,
CenteredMiddle,
HeightFraction,
Baseline,
}
fn goes_on(table: &Table, next: Option<&Block>) -> bool {
let floats = table.props.placement.is_some();
matches!(next, Some(Block::Table(next)) if floats && next.props.lays_out_as(&table.props) && next.grid == table.grid)
}
#[derive(Clone, Copy, Default)]
pub(super) struct Rest<'b>(&'b [&'b [Block]]);
impl<'b> Rest<'b> {
pub(super) const fn is_end(self) -> bool {
self.0.is_empty()
}
pub(super) fn table(self) -> Option<(&'b Table, Self)> {
let (first, rest) = self.0.split_first()?;
match first.first() {
Some(Block::Table(table)) => Some((table, Self(rest))),
_ => None,
}
}
pub(super) fn paragraphs(self) -> (Vec<&'b crate::body::Paragraph>, Self) {
let paragraph = |block: &'b Block| match block {
Block::Paragraph(paragraph) => Some(paragraph),
Block::Table(_) => None,
};
match self.0.split_first() {
Some((first, rest)) if self.table().is_none() => {
(first.iter().filter_map(paragraph).collect(), Self(rest))
}
_ => (Vec::new(), self),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CellEdgeParts {
pub table: Length,
pub grid: Length,
pub inner: Length,
pub outer: Option<crate::grid::FixedPlace>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AlignedParts {
pub start: Length,
pub end: Length,
pub edge: Length,
pub indent: Length,
pub width: Length,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CellPlace {
pub table: usize,
pub row: usize,
pub column: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableColumns {
pub table: usize,
pub widths: Vec<Length>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FirstItem {
At(usize),
Carried,
}
impl FirstItem {
#[must_use]
pub const fn index(self) -> Option<usize> {
match self {
Self::At(index) => Some(index),
Self::Carried => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawnGlyph {
pub spacing: Length,
pub x: Length,
pub place: Length,
pub spaces: u32,
pub started: StepsStart,
pub checked: Option<crate::grid::EdgeCheck>,
pub object_start: Option<crate::grid::ObjectStart>,
pub start_place: Option<Length>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StepsStart {
#[default]
Stepped,
Glyph,
Space(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlacedLine {
pub paragraph: ParagraphId,
pub page: usize,
pub story: LineStory,
pub part: StoryPart,
pub area: LineArea,
pub cell: Option<CellPlace>,
pub item: FirstItem,
pub top: Length,
pub top_rests: (i64, Option<i64>),
pub height: Length,
pub height_rests: (i64, Option<i64>),
pub baseline: Length,
pub unrounded_baseline: Length,
pub baseline_form: BaselineForm,
pub ascent: Length,
pub descent: Length,
pub spacing: crate::props::LineSpacing,
pub index: usize,
pub last: bool,
pub spaced: bool,
pub before: Length,
pub kept: Option<crate::lines::Fit>,
pub wrapped: Option<crate::lines::Fit>,
pub justified: bool,
pub alignment: crate::props::Alignment,
pub steps: Vec<crate::lines::Step>,
pub drawn: Vec<DrawnGlyph>,
pub spread: Length,
pub free_space: Length,
pub free_rounding_thousandths: i64,
pub edge: Length,
pub column_left: Length,
pub column_origin: Length,
pub cell_edge: Option<CellEdgeParts>,
pub aligned: Option<AlignedParts>,
pub markup_scale: Option<i64>,
pub text: LineText,
}
impl PlacedLine {
pub(crate) fn move_down(&mut self, dy: Length) {
match &mut self.text.turn {
Some(turn) => turn.to.1 += dy,
None => self.top += dy,
}
}
pub(crate) fn move_right(&mut self, dx: Length) {
if dx == Length::ZERO {
return;
}
self.edge += dx;
self.column_left += dx;
self.column_origin += dx;
if let Some(turn) = &mut self.text.turn {
turn.to.0 += dx;
} else {
self.text.left += dx;
for cluster in &mut self.text.clusters {
cluster.left += dx;
cluster.right += dx;
}
}
}
pub(crate) const fn upright(&self) -> bool {
self.text.turn.is_none()
}
}
fn last_columns(starts: Vec<TableColumns>) -> Vec<TableColumns> {
let mut last = std::collections::BTreeMap::new();
for columns in starts {
last.insert(columns.table, columns);
}
last.into_values().collect()
}
pub struct Pass {
pub list: DisplayList,
pub wraps: PageWraps,
pub bookmarks: BookmarkPages,
pub bookmark_numbers: BookmarkNumbers,
pub styles: HeaderStyles,
pub note_places: NotePlaces,
pub later_anchors: LaterAnchors,
pub note_heights: NoteHeights,
pub notes_missed: bool,
pub lines: Vec<PlacedLine>,
pub tables: Vec<TableColumns>,
pub warnings: crate::Warnings,
pub font_notes: crate::text::FontNotes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EmptyLines {
Wrap,
Stay,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum StoryKind {
Header {
several_blocks: bool,
part: Rc<str>,
},
Footer {
part: Rc<str>,
},
Footnote {
id: NoteId,
},
NoteSeparator(notes::Separator),
EndnoteContinuation,
Frame {
inside: Option<f_office_units::Edges<Length>>,
},
TextBox {
text_color: Option<[u8; 3]>,
turn: Option<(f_office_paint::Turn, TurnedGlyphs)>,
box_text: crate::floating::BoxText,
inside: Option<f_office_units::Edges<Length>>,
},
Balloon,
}
impl StoryKind {
const fn empty_lines(&self) -> EmptyLines {
match self {
Self::Header {
several_blocks: true,
..
} => EmptyLines::Stay,
_ => EmptyLines::Wrap,
}
}
const fn ties(&self) -> line::height::Ties {
match self {
Self::Header { .. } => line::height::Ties::TowardTop,
Self::Footer { .. } => line::height::Ties::Footer,
_ => line::height::Ties::AwayFromTop,
}
}
fn key(&self) -> Option<output::StoryKey> {
match self {
Self::Header { part, .. } | Self::Footer { part } => {
Some(output::StoryKey::Part(Rc::clone(part)))
}
Self::Footnote { id } => Some(output::StoryKey::Footnote(*id)),
Self::NoteSeparator(separator) => Some(output::StoryKey::Separator(*separator)),
Self::EndnoteContinuation
| Self::Frame { .. }
| Self::TextBox { .. }
| Self::Balloon => None,
}
}
const fn part(&self, number: u32) -> Option<StoryPart> {
match self {
Self::Frame { .. } => Some(StoryPart::Frame(number)),
Self::TextBox { .. } => Some(StoryPart::TextBox(number)),
_ => None,
}
}
const fn ends_below_space_after(&self) -> bool {
matches!(self, Self::Frame { .. })
}
const fn holds_frames(&self) -> bool {
!matches!(self, Self::Frame { .. } | Self::TextBox { .. })
}
const fn line_story(&self) -> Option<LineStory> {
match self {
Self::Header { .. } => Some(LineStory::Header),
Self::Footer { .. } => Some(LineStory::Footer),
Self::Footnote { .. } => Some(LineStory::Footnote),
Self::TextBox { .. } => Some(LineStory::TextBox),
Self::Frame { .. } => Some(LineStory::Body),
Self::NoteSeparator(_) | Self::EndnoteContinuation | Self::Balloon => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StoryNumbers {
page: i64,
pages: i64,
note: Option<NoteLabel>,
}
impl StoryNumbers {
const PAGE_ONE: Self = Self::on_page(1, 1);
const fn on_page(page: i64, pages: i64) -> Self {
Self {
page,
pages,
note: None,
}
}
const fn of_note(label: NoteLabel) -> Self {
Self {
note: Some(label),
..Self::PAGE_ONE
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Story {
kind: StoryKind,
numbers: StoryNumbers,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TwipsRest {
at: Length,
rest: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct CellRests {
end: Option<TwipsRest>,
top: Option<i64>,
top_height: i64,
end_height: Option<i64>,
bottom: Option<i64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RowRests {
at: Length,
twips: i64,
height: i64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct MovedTop {
twips: Option<i64>,
rest: i64,
}
#[derive(Clone, Copy, Default)]
struct TableTwips {
row: Option<RowRests>,
cell: CellRests,
row_end: Option<RowRests>,
moved: Option<MovedTop>,
carried: bool,
}
impl Layout<'_> {
fn move_to(&mut self, y: Length) {
self.y = y;
self.y_rest = 0;
self.y_twips = None;
}
fn empty_lines(&self) -> EmptyLines {
self.story
.as_ref()
.map_or(EmptyLines::Wrap, |story| story.kind.empty_lines())
}
fn ties(&self) -> line::height::Ties {
if matches!(self.column.within, Within::TurnedFrame(true, ..)) {
return line::height::Ties::TurnedFrame;
}
let ties = self
.story
.as_ref()
.map_or(line::height::Ties::AwayFromTop, |story| story.kind.ties());
if ties == line::height::Ties::AwayFromTop
&& self.column.cell.is_some()
&& !self.table_twips.carried
{
return line::height::Ties::Cell;
}
ties
}
fn box_top(&self, (top, space): (Length, line::height::SpaceBefore)) -> line::height::BoxTop {
if self.story.is_none() && top - space.length() == self.page_top(self.output.pages.len()) {
line::height::BoxTop::PageTop
} else {
line::height::BoxTop::Lower
}
}
fn holds_frames(&self) -> bool {
self.story
.as_ref()
.is_none_or(|story| story.kind.holds_frames())
}
fn story_pages(&self) -> Option<(i64, i64)> {
self.story
.as_ref()
.map(|story| (story.numbers.page, story.numbers.pages))
}
fn footnote_label(&self) -> Option<NoteLabel> {
self.story.as_ref().and_then(|story| story.numbers.note)
}
fn inner_numbers(&self) -> StoryNumbers {
let (page, pages) = self.story_pages().unwrap_or_else(|| {
let number = self.page_number(self.output.pages.len());
(number, number)
});
StoryNumbers::on_page(page, pages)
}
fn warn_of_feature(&mut self, feature: crate::Feature, part: &str) {
self.output
.warnings
.push(crate::Warning::FeatureNotSupported {
part: f_office_warnings::Name::new(part),
feature,
});
}
}
impl<'a> Layout<'a> {
fn setting_part<'p>(&self, part: Option<&'p str>) -> &'p str
where
'a: 'p,
{
part.unwrap_or(self.context.main)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum TableChain {
#[default]
Ends,
GoesOn,
}
pub struct Layout<'a> {
context: &'a Context<'a>,
stories: &'a Context<'a>,
styles: &'a Styles,
settings: &'a Settings,
numbering: Numbering,
device: crate::grid::Device,
sections: Cow<'a, Sections<SectionLayout>>,
section: Section,
shaper: Shaper<'a>,
items: page_items::PageItems,
y: Length,
y_rest: i64,
y_twips: Option<TwipsRest>,
table_twips: TableTwips,
previous: Option<Previous>,
tops: [Length; 3],
bottoms: [Length; 3],
story: Option<Story>,
body_part: std::rc::Rc<f_office_warnings::Name>,
output: output::PassOutput,
page_notes: notes::PageNotes,
endnote: Option<NoteLabel>,
comment_markup: markup::CommentMarkup<'a>,
page: Option<Section>,
story_notes: Length,
story_page: Option<usize>,
style_page: Option<(std::rc::Rc<style_refs::StyledPages>, usize)>,
number_context: Option<NumberContext>,
bands: Vec<Band>,
hyphen_runs: Option<Vec<measure::HyphenRun>>,
paragraph_bidi: measure::ParagraphDirection,
squares: Vec<floating::Square>,
frame_boxes: Vec<frames::FrameBox>,
frame_places: Vec<(usize, Length)>,
same_baseline: Vec<floating::NarrowedPiece>,
line_floor: Option<Length>,
behind: Vec<(u64, Item)>,
front: Vec<(u64, Item)>,
column: Column,
columns: Vec<(Length, Length)>,
column_index: usize,
column_top: Length,
column_ends: Vec<Length>,
section_end_paragraph: Option<ParagraphId>,
balance: Option<columns::Balance>,
section_top: columns::SectionTop,
page_marks: Option<columns::PageMarks>,
fragment: Option<table::Fragment>,
cell_carried: bool,
cell_floor: Option<table::CellFloor>,
cell_top: Option<Length>,
cell_sides: Option<(Length, Length)>,
cell_prev_style: Option<String>,
table_prev_style: Option<String>,
body_floatings: usize,
cell_floatings: usize,
cell_upward_earlier: Vec<UpwardWrap>,
cell_upward_found: Vec<UpwardWrap>,
story_earlier_wraps: Option<Box<PageWraps>>,
started: bool,
after_break: bool,
alone_break: Option<Previous>,
section_previous: Option<Previous>,
table_chain: TableChain,
page_from_break: Option<usize>,
break_numbers: (usize, (i64, usize)),
grid_pitch: Option<Length>,
following_after: Option<Length>,
kept_tail: Option<usize>,
centered_middle: Option<line::centered::CenteredMiddle>,
line_band: Option<(Length, Length)>,
east_asian_axis: Option<Length>,
aligned_parts: Option<AlignedParts>,
glyph_places: Vec<(usize, Length)>,
own_space_before: Length,
first_space_before: Length,
held_borders: HeldBorders,
drawings_under_fill: Option<page_items::FillsEntry>,
new_page_space: NewPageSpace,
last_bar: Option<(usize, usize)>,
text_part: ((usize, usize), u32),
section_index: SectionIndex,
section_first_page: usize,
section_title_page: Option<usize>,
number_start: i64,
pending: Option<usize>,
table_number: usize,
cell_place: Option<CellPlace>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Within {
Page,
Cell(CellEdgeParts),
TurnedFrame(bool, f_office_paint::Turn, TurnedGlyphs),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TurnedGlyphs {
WithLine,
EastAsianUpright,
}
impl Within {
const fn cell_edge(self) -> Option<CellEdgeParts> {
match self {
Self::Cell(parts) => Some(parts),
Self::Page | Self::TurnedFrame(..) => None,
}
}
}
#[derive(Clone, Debug)]
struct Column {
left: Length,
width: Length,
within: Within,
origin: Length,
cell: Option<Rc<TableStyle>>,
}
impl Column {
const fn page(left: Length, width: Length) -> Self {
Self {
left,
width,
within: Within::Page,
origin: left,
cell: None,
}
}
}
impl<'a> Layout<'a> {
#[must_use]
pub fn new(
contexts: (&'a Context<'a>, &'a Context<'a>),
sections: &'a Sections<SectionLayout>,
shaper: Shaper<'a>,
) -> Self {
let numbering = (*contexts.0.numbering).clone();
Self::with_sections(contexts, Cow::Borrowed(sections), shaper, numbering)
}
fn story(
contexts: (&'a Context<'a>, &'a Context<'a>),
section: &Section,
blocks: usize,
shaper: Shaper<'a>,
numbering: Numbering,
) -> Self {
let sections = Sections::one(SectionLayout::plain(section, blocks));
Self::with_sections(contexts, Cow::Owned(sections), shaper, numbering)
}
fn with_sections(
(context, stories): (&'a Context<'a>, &'a Context<'a>),
sections: Cow<'a, Sections<SectionLayout>>,
shaper: Shaper<'a>,
numbering: Numbering,
) -> Self {
let section = sections.first().section;
let top = section.top;
let columns = columns::areas(§ion, &context.quirks);
let (left, width) = columns.first().copied().unwrap_or_default();
Self {
context,
stories,
styles: context.styles,
settings: context.settings,
numbering,
device: context
.device
.with_page(section.width, section.height, section.orientation),
sections,
section,
shaper,
items: page_items::PageItems::new(),
y: top,
y_rest: 0,
y_twips: None,
table_twips: TableTwips::default(),
previous: None,
tops: [top; 3],
bottoms: [section.height - section.bottom; 3],
story: None,
body_part: std::rc::Rc::default(),
output: output::PassOutput::default(),
page_notes: notes::PageNotes::default(),
endnote: None,
comment_markup: markup::CommentMarkup::new(&context.comments),
page: None,
story_notes: Length::ZERO,
story_page: None,
style_page: None,
number_context: None,
bands: Vec::new(),
hyphen_runs: None,
paragraph_bidi: measure::ParagraphDirection::LeftToRight,
squares: Vec::new(),
frame_boxes: Vec::new(),
frame_places: Vec::new(),
same_baseline: Vec::new(),
line_floor: None,
behind: Vec::new(),
front: Vec::new(),
column: Column::page(left, width),
columns,
column_index: 0,
column_top: top,
column_ends: Vec::new(),
section_end_paragraph: None,
balance: None,
section_top: columns::SectionTop::Placed,
page_marks: None,
fragment: None,
cell_carried: false,
cell_floor: None,
cell_top: None,
cell_sides: None,
cell_prev_style: None,
table_prev_style: None,
body_floatings: 0,
cell_floatings: 0,
cell_upward_earlier: Vec::new(),
cell_upward_found: Vec::new(),
story_earlier_wraps: None,
started: false,
after_break: false,
alone_break: None,
section_previous: None,
table_chain: TableChain::Ends,
page_from_break: None,
break_numbers: (0, (0, 0)),
grid_pitch: None,
following_after: None,
kept_tail: None,
centered_middle: None,
line_band: None,
east_asian_axis: None,
aligned_parts: None,
glyph_places: Vec::new(),
own_space_before: Length::ZERO,
first_space_before: Length::ZERO,
held_borders: HeldBorders::NONE,
drawings_under_fill: None,
new_page_space: NewPageSpace::Goes,
last_bar: None,
text_part: ((0, 0), 0),
section_index: SectionIndex::FIRST,
section_first_page: 0,
section_title_page: Some(0),
number_start: section.first_page_number,
pending: None,
table_number: 0,
cell_place: None,
}
}
pub(crate) fn begin_body(&mut self, body: &Body) {
self.body_part = std::rc::Rc::clone(&body.part);
self.output.styled = Some(style_refs::Record::default());
if self.settings.side_margins != SideMargins::Section {
let section = self.section_of(SectionIndex::FIRST);
self.take_side_margins(§ion);
self.set_columns();
}
self.measure_body();
self.start_wraps();
self.move_to_body_top(0);
self.column_top = self.y;
}
#[must_use]
pub(crate) fn finish_body_pass(mut self) -> Pass {
self.endnotes_flow();
let trailing = !self.output.pages.is_empty()
&& self.page_from_break == Some(self.output.pages.len())
&& self.page_is_empty()
&& self.y == self.page_top(self.output.pages.len());
if !trailing {
self.new_page();
}
if self.rest_waits() {
self.new_page();
}
self.output.style_pages = self.output.styled.take().map(style_refs::Record::finish);
let count = count_factor(self.output.pages.len());
let mut behind = Vec::with_capacity(self.output.pages.len());
for index in 0..self.output.pages.len() {
if self.output.blank_pages.contains(&index) {
behind.push(Vec::new());
continue;
}
let (items, lines) = self.headers_and_footers(index, count);
behind.push(items);
self.output.placed.extend(lines);
}
let pages = std::mem::take(&mut self.output.pages);
let page_color = self.settings.page_color;
self.output.pages = pages
.into_iter()
.zip(behind)
.map(|(page, items)| {
let color = page_color.map(|[r, g, b]| {
Item::Rect(Rect {
x: Length::ZERO,
y: Length::ZERO,
width: page.width(),
height: page.height(),
color: Rgb { r, g, b },
})
});
page.map_items(|mut body| {
body.splice(0..0, color.into_iter().chain(items));
body
})
})
.collect();
self.print_markup();
let styles = HeaderStyles(self.output.style_pages.clone());
let note_places = self.output.notes.take_places();
let areas = &self.output.body_areas;
let notes_missed = self
.output
.margin_notes
.iter()
.any(|&(page, notes)| areas.get(page).is_some_and(|area| area.notes != notes));
let note_heights = NoteHeights::of_areas(areas);
Pass {
list: DisplayList::new(self.output.pages),
wraps: self.output.found,
bookmarks: self.output.found_bookmarks.into_values(),
bookmark_numbers: self.output.found_numbers.into_values(),
styles,
note_places,
later_anchors: LaterAnchors::found(&self.output.found_later),
note_heights,
notes_missed,
lines: self.output.placed,
tables: last_columns(self.output.table_columns),
warnings: self.output.warnings,
font_notes: self.shaper.take_notes(),
}
}
#[must_use]
pub fn run_with_wraps(mut self, body: &Body) -> Pass {
self.begin_body(body);
self.sections_flow(&body.blocks);
self.finish_body_pass()
}
fn blocks(&mut self, blocks: &[Block]) {
self.blocks_from(blocks, columns::BlockStart::default());
}
fn blocks_from(&mut self, blocks: &[Block], start: columns::BlockStart) {
let chunks = paragraph_chunks(blocks);
let mut joined: Option<Table> = None;
self.enter_blocks();
for (index, chunk) in chunks.iter().enumerate().skip(start.chunk) {
self.note_chunk(index);
let mut group = Vec::new();
let rest = Rest(chunks.get(index + 1..).unwrap_or_default());
let next = chunks.get(index + 1).and_then(|next| next.first());
for block in *chunk {
match block {
Block::Paragraph(paragraph) => group.push(paragraph),
Block::Table(table) => {
let more = goes_on(table, next);
match joined.as_mut() {
Some(whole) => whole.rows.extend(table.rows.iter().cloned()),
None if more => joined = Some(table.clone()),
None => self.table(table, rest),
}
if let Some(whole) = joined.take_if(|_| !more) {
self.table(&whole, rest);
}
}
}
}
let first = if index == start.chunk {
start.paragraph
} else {
0
};
self.flow(&group, rest, first);
}
self.leave_blocks();
}
}
fn paragraph_chunks(blocks: &[Block]) -> Vec<&[Block]> {
blocks
.chunk_by(|a, b| matches!((a, b), (Block::Paragraph(_), Block::Paragraph(_))))
.collect()
}