use f_office_units::{Edges, Length};
use std::borrow::Cow;
use crate::body::{Content, Run};
use crate::chart::{Columns, PlotRule};
use crate::dates::{DateTime, PROPERTY_DATE_PICTURE};
use crate::grid::{Device, Rounding, in_fixed_points};
use crate::lines::{EndSpaceFit, LeadingBreaks, LineBreaking, Piece};
use crate::mode::ModeRules;
use crate::params;
use crate::props::{Anchor, Border, HtmlAutoSpacing, Kashidas, LineSpacing, ParaProps, RunProps};
use crate::quirks::GridSingleLine;
use crate::quirks::PropertyDateZone;
use crate::quirks::StoryMarginArea;
use super::output::BodyArea;
use crate::quirks::InlinePictureClip;
use crate::quirks::{
AlignedTabOverrun, AlignmentWithNotes, AutofitGrid, AutomaticHyphenation, BookmarkText,
BorderDashes, BorderWidthUnit, CarriedMergeMove, CellBreak, CellClip, CellDrawingBounds,
CellEndListSpace, CellFillRows, CellFillSides, CellFrames, CellTextRoom, CellTopBand,
CenteredLine, CenteredMultiple, ChartAxisOrder, ChartAxisRoom, ChartDataLabels, ChartLineClip,
CheckBoxSide, ColumnEdgeHalves, ComputedFieldDecorations, ComputedFieldFormat, ControlObjects,
EdgeShares, ExactRowMargin, FaceRoomSpacing, FixedAutoSpacing, FloatingTableBreaks,
FloatingTableLeft, FloatingTableTop, GrownDelimiters, HyperlinkObjects, LabelAloneRise,
LaterPartWidows, LeadingPageBreak, LeftStopPastEnd, ListLabelDescent, MarkFace, MergedCellFill,
MergedCellLines, MergedTopRoom, MetafileTopAscent, NestedRowMinimum, NoBreakSpaceShare,
NoteReferenceBreak, ObjectAscent, ObjectLineMultiple, PictureLinePlace, PictureShadows, Quirks,
RaisedRunSpacing, RemovedTextObjects, RowBelowHeaders, RowEndBorders, RowLineRoom, ScaledSteps,
ShapeShadows, SoftBreakLine, SpacedColumns, SpacedTableBreaks, SplitMergeAlign, SplitRowFills,
StretchedSpaceShare, StyleRegionBorders, TurnedLineRoom, TurnedPicture, UnderlinedObjectRoom,
VmlObjectSize, WrapEdgeDot, ZeroRevision,
};
use crate::quirks::{
BandHeight, BetweenBorders, BlockedLines, BorderSides, BottomBorderSpaceAfter, BoxLastLine,
BoxOutlineLeft, BoxTextTop, ColumnSeparator, ColumnTopSpace, ColumnWidths,
ContinuousSectionEnd, DeletedTableTop, FootBorderRoom, FrameFittedWidth, FrameLeft, FromLine,
HiddenHeaderFooterEnd, HiddenMarkBorders, KashidaJustification, LastPageBalance, LineWrapBand,
MultipleBottomBorder, MultipleTopBorder, PageBreakBeforeSpace, PolygonWrap, RestartSide,
RightToLeftEdge, RightToLeftEndSpace, RightToLeftSectionColumns, SeenKashidas,
SeparatorSpaceAfter, SmartArtLowSpacing, StepEnd, StyleRefNoBreakSpace, StyleRefTrailingSpaces,
TextBoxClip, TextBoxColumns, TurnedAcrossDots, UnsetCellMargins, VmlBoxOutline, WidowForecast,
WordPerfectJustification,
};
use crate::reader::settings::PlotRules;
use crate::styles::{Justification, Settings, SoftBreakLines};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct CellParts {
pub(in crate::layout) left: Length,
pub(in crate::layout) right: Length,
pub(in crate::layout) margins: (Length, Length),
pub(in crate::layout) left_margin_set: bool,
pub(in crate::layout) lines: (Length, Length),
pub(in crate::layout) gaps: Option<CellGaps>,
pub(in crate::layout) upright: bool,
pub(in crate::layout) text_rest: Length,
}
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct CellGaps {
pub(in crate::layout) left: Length,
pub(in crate::layout) right: Length,
pub(in crate::layout) spacing: Length,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CellRoom {
pub(in crate::layout) left: Length,
pub(in crate::layout) inner: Length,
pub(in crate::layout) width: Length,
}
pub(in crate::layout) fn cell_text_room(quirks: &Quirks, cell: &CellParts) -> CellRoom {
let (left_margin, right_margin) = cell.margins;
let (left_line, right_line) = cell.lines;
let (left, right, gap) = match cell.gaps {
Some(gaps) => {
let text = quirks.spaced_cell_text;
(
cell.left + gaps.left + text.side_room(left_line, gaps.spacing),
cell.right - gaps.right - text.side_room(right_line, gaps.spacing),
left_margin,
)
}
None if cell.left_margin_set => (cell.left, cell.right, left_margin),
None => (cell.left, cell.right, left_line),
};
let minimum = cell.gaps.is_none()
&& cell.left_margin_set
&& quirks.cell_text_room == CellTextRoom::CombinedBorderMinimum;
let half_left = left_line.div_toward_zero(2);
let gap = if minimum { gap.max(half_left) } else { gap };
let on_half_line = minimum && left_margin < half_left;
let width = if minimum {
let margins = left_margin + right_margin;
let lines = Length::from_units(i64::midpoint(left_line.units(), right_line.units()));
right - left - margins.max(lines)
} else {
right - right_margin - left - gap
};
let inner = gap;
let rest = if cell.upright && !on_half_line {
cell.text_rest
} else {
Length::ZERO
};
CellRoom {
left: left + inner + rest,
inner,
width,
}
}
pub(in crate::layout) fn html_auto_spacing(
settings: &crate::styles::Settings,
quirks: &Quirks,
) -> HtmlAutoSpacing {
if settings.html_auto_spacing == HtmlAutoSpacing::Fixed
&& quirks.fixed_auto_spacing == FixedAutoSpacing::OptionFollowed
{
HtmlAutoSpacing::Fixed
} else {
HtmlAutoSpacing::Html
}
}
pub(in crate::layout) fn cell_frame(quirks: &Quirks, in_cell: bool, props: &mut ParaProps) {
if in_cell && quirks.cell_frames == CellFrames::InFlow {
props.plain_cell_frame();
}
}
pub(in crate::layout) fn mark_face<T>(
quirks: &Quirks,
complex_formatting: bool,
face: impl FnOnce(bool) -> T,
) -> T {
face(complex_formatting && quirks.mark_face == MarkFace::ComplexFormatting)
}
pub(in crate::layout) fn starts_text_object(quirks: &Quirks, content: &Content) -> bool {
match content {
Content::FieldMark => true,
Content::HyperlinkEdge => quirks.hyperlink_objects == HyperlinkObjects::StartsObject,
Content::ControlEdge => quirks.control_objects == ControlObjects::StartsObject,
Content::RemovedEdge => quirks.removed_text_objects == RemovedTextObjects::StartsObject,
_ => false,
}
}
pub(in crate::layout) fn ends_text(quirks: &Quirks, content: &Content) -> bool {
!(matches!(content, Content::Bookmark(_)) && quirks.bookmark_text == BookmarkText::Joins)
}
pub(in crate::layout) fn grows_delimiters(quirks: &Quirks) -> bool {
quirks.grown_delimiters == GrownDelimiters::Variant
}
pub(in crate::layout) fn hyphenation<T>(
quirks: &Quirks,
rules: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.automatic_hyphenation {
AutomaticHyphenation::Off => None,
AutomaticHyphenation::EnglishFrenchSpanish => rules(),
}
}
pub(in crate::layout) fn hyphenation_language(
quirks: &Quirks,
tag: &str,
) -> Option<f_office_hyphenate::Language> {
quirks.automatic_hyphenation.language(tag)
}
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct RevisionReading(ZeroRevision);
impl RevisionReading {
pub(in crate::layout) const AS_WRITTEN: Self = Self(ZeroRevision::AnId);
pub(in crate::layout) const fn of(quirks: &Quirks) -> Self {
Self(quirks.zero_revision)
}
#[cfg(test)]
pub(in crate::layout) const fn with(zero: ZeroRevision) -> Self {
Self(zero)
}
pub(in crate::layout) fn read(self, revisions: [Option<u32>; 3]) -> [Option<u32>; 3] {
self.0.read(revisions)
}
}
pub(in crate::layout) fn turned_line_room(quirks: &Quirks) -> Option<(i64, i64)> {
match quirks.turned_line_room {
TurnedLineRoom::Upright => None,
TurnedLineRoom::SizeShare => Some(params::TURNED_LINE_ROOM),
}
}
pub(in crate::layout) fn counted_labels<T>(
quirks: &Quirks,
labels: impl FnOnce() -> T,
) -> Option<T> {
match quirks.list_label_descent {
ListLabelDescent::LeftOutOfLine => None,
ListLabelDescent::Counted => Some(labels()),
}
}
pub(in crate::layout) fn scaled_label_rise<T>(
quirks: &Quirks,
scaled: impl FnOnce() -> T,
) -> Option<T> {
match quirks.label_alone_rise {
LabelAloneRise::Unscaled => None,
LabelAloneRise::Scaled => Some(scaled()),
}
}
pub(in crate::layout) fn object_ascent<T>(
quirks: &Quirks,
ascent: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.object_ascent {
ObjectAscent::SingleLine => None,
ObjectAscent::Ascent => ascent(),
}
}
pub(in crate::layout) fn underlined_object_room(quirks: &Quirks) -> bool {
match quirks.underlined_object_room {
UnderlinedObjectRoom::None => false,
UnderlinedObjectRoom::FontDescent => true,
}
}
pub(in crate::layout) fn object_line_multiple<T>(
quirks: &Quirks,
value: impl FnOnce() -> Option<T>,
) -> Option<T> {
matches!(quirks.object_line_multiple, ObjectLineMultiple::ObjectRun)
.then(value)
.flatten()
}
pub(in crate::layout) fn face_room_once<T>(quirks: &Quirks, room: T) -> Option<T> {
match quirks.face_room_spacing {
FaceRoomSpacing::Scaled => None,
FaceRoomSpacing::Once => Some(room),
}
}
pub(in crate::layout) fn raised_room_once<T>(quirks: &Quirks, room: T) -> Option<T> {
match quirks.raised_run_spacing {
RaisedRunSpacing::Scaled => None,
RaisedRunSpacing::Once => Some(room),
}
}
pub(in crate::layout) fn line_breaking(quirks: &Quirks, rules: ModeRules) -> LineBreaking {
LineBreaking {
ends_aligned_text: match quirks.aligned_tab_overrun {
AlignedTabOverrun::RunsPast => false,
AlignedTabOverrun::EndsAtAreaEnd => true,
},
note_reference_in_word: match quirks.note_reference_break {
NoteReferenceBreak::After => false,
NoteReferenceBreak::AsText => true,
},
left_stops_to_line_end: rules.moves_tab_to_left_stop_past_end()
&& match quirks.left_stop_past_end {
LeftStopPastEnd::ToStop => false,
LeftStopPastEnd::ToLineEnd => true,
},
leading_breaks: match quirks.leading_page_break {
LeadingPageBreak::OnBreakLine => LeadingBreaks::None,
LeadingPageBreak::AfterBreak if rules.starts_after_first_leading_break() => {
LeadingBreaks::First
}
LeadingPageBreak::AfterBreak => LeadingBreaks::All,
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum KashidaJoints {
LastWords,
SeensThenFinals,
}
pub(in crate::layout) fn kashida_joints(
quirks: &Quirks,
settings: &Settings,
kashidas: Option<Kashidas>,
) -> Option<KashidaJoints> {
if kashidas != Some(Kashidas::Low) {
return None;
}
if settings.mode_rules.lengthens_last_words() {
return match quirks.kashida_justification {
KashidaJustification::SpacesOnly => None,
KashidaJustification::LastWords => Some(KashidaJoints::LastWords),
};
}
match quirks.seen_kashidas {
SeenKashidas::SpacesOnly => None,
SeenKashidas::SeenAndFinalJoints => Some(KashidaJoints::SeensThenFinals),
}
}
pub(in crate::layout) fn justification(quirks: &Quirks, settings: &Settings) -> Justification {
let follows = match quirks.word_perfect_justification {
WordPerfectJustification::Ignored => false,
WordPerfectJustification::ShrinksLine => true,
};
if follows
&& settings.justification == Justification::WordPerfect
&& !settings.mode_rules.shrinks_justified_spaces()
{
Justification::WordPerfect
} else {
Justification::Word
}
}
pub(in crate::layout) fn cell_breaks(quirks: &Quirks, pieces: &mut Vec<Piece>) {
match quirks.cell_break {
CellBreak::EndsLine => {}
CellBreak::Ignored => {
pieces.retain(|piece| !matches!(piece, Piece::PageBreak | Piece::ColumnBreak));
}
}
}
pub(in crate::layout) fn shape_shadow<T>(quirks: &Quirks, shadow: impl FnOnce() -> T) -> Option<T> {
match quirks.shape_shadows {
ShapeShadows::Unknown => None,
ShapeShadows::Picture => Some(shadow()),
}
}
pub(in crate::layout) fn picture_shadow<T>(
quirks: &Quirks,
shadow: impl FnOnce() -> T,
) -> Option<T> {
match quirks.picture_shadows {
PictureShadows::Unknown => None,
PictureShadows::Frame => Some(shadow()),
}
}
pub(in crate::layout) fn upright_picture<T>(quirks: &Quirks, picture: T) -> Option<T> {
match quirks.turned_picture {
TurnedPicture::InFrame => None,
TurnedPicture::Upright => Some(picture),
}
}
pub(in crate::layout) fn counted_edge_shares<T>(
quirks: &Quirks,
counted: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.edge_shares {
EdgeShares::Spread => None,
EdgeShares::ExactFree => counted(),
}
}
pub(in crate::layout) fn wrap_edge<T>(quirks: &Quirks, edge: Option<T>) -> Option<T> {
match quirks.wrap_edge_dot {
WrapEdgeDot::ColumnAndDistance => None,
WrapEdgeDot::WrapEdge => edge,
}
}
pub(in crate::layout) fn shared_middles<T>(
quirks: &Quirks,
centered: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.centered_line {
CenteredLine::OnBaseline => None,
CenteredLine::MiddlesShared => centered(),
}
}
pub(in crate::layout) fn rounded_middle<T>(
quirks: &Quirks,
face: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.centered_multiple {
CenteredMultiple::OnBaseline => None,
CenteredMultiple::MiddleRounded => face(),
}
}
pub(in crate::layout) fn nominal_steps<T>(quirks: &Quirks, scale: Option<T>) -> Option<T> {
match quirks.scaled_steps {
ScaledSteps::DrawnSize => None,
ScaledSteps::NominalSum => scale,
}
}
pub(in crate::layout) fn width_first_share<T>(
quirks: &Quirks,
departures: impl FnOnce() -> T,
) -> Option<T> {
match quirks.stretched_space_share {
StretchedSpaceShare::Equal => None,
StretchedSpaceShare::WidthFirst => Some(departures()),
}
}
pub(in crate::layout) fn no_break_spaces_stretch(
quirks: &Quirks,
rules: ModeRules,
east_asian_defaults: bool,
) -> bool {
match quirks.no_break_space_share {
NoBreakSpaceShare::None => false,
NoBreakSpaceShare::EastAsianDefaults => {
rules.may_stretch_no_break_spaces() && east_asian_defaults
}
}
}
pub(in crate::layout) fn column_edge_parts<T>(
quirks: &Quirks,
parts: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.column_edge_halves {
ColumnEdgeHalves::WholeEdge => None,
ColumnEdgeHalves::ColumnParts => parts(),
}
}
pub(in crate::layout) fn check_box_side(
quirks: &Quirks,
three_strokes: Length,
dot: Length,
) -> Length {
match quirks.check_box_side {
CheckBoxSide::ThreeStrokes => three_strokes,
CheckBoxSide::ThreeStrokesAndDot => three_strokes - dot,
}
}
pub(in crate::layout) fn followed_soft_break_lines(
quirks: &Quirks,
lines: SoftBreakLines,
) -> Option<SoftBreakLines> {
match quirks.soft_break_line {
SoftBreakLine::Justified => None,
SoftBreakLine::OptionFollowed => Some(lines),
}
}
pub(in crate::layout) fn anchor_stroke_room<T>(quirks: &Quirks, shape: T) -> Option<T> {
match quirks.vml_object_size {
VmlObjectSize::TakesStyleSize => None,
VmlObjectSize::TakesAnchorStrokeRoom | VmlObjectSize::TakesStrokeRoom => Some(shape),
}
}
pub(in crate::layout) fn story_margin_area(
quirks: &Quirks,
margins: BodyArea,
body: BodyArea,
) -> BodyArea {
match quirks.story_margin_area {
StoryMarginArea::SectionMargins => margins,
StoryMarginArea::BodyArea => body,
}
}
pub(in crate::layout) fn grid_single_parts(
quirks: &Quirks,
device: &Device,
(ascent, descent): (Length, Length),
pitch: Length,
) -> Option<((Length, Length), Rounding)> {
match quirks.grid_single_line {
GridSingleLine::Middle => None,
GridSingleLine::PartsRounded => {
let ties = if in_fixed_points(pitch) {
Rounding::HalfUp
} else {
Rounding::HalfDown
};
Some(((device.snap(ascent), device.snap(descent)), ties))
}
}
}
pub(in crate::layout) fn outline_stroke_room<T>(quirks: &Quirks, shape: T) -> Option<T> {
match quirks.vml_object_size {
VmlObjectSize::TakesStyleSize | VmlObjectSize::TakesAnchorStrokeRoom => None,
VmlObjectSize::TakesStrokeRoom => Some(shape),
}
}
pub(in crate::layout) fn direct_props<'r>(quirks: &Quirks, run: &'r Run) -> Cow<'r, RunProps> {
let code_format = match quirks.computed_field_format {
ComputedFieldFormat::ResultRun => false,
ComputedFieldFormat::CodeRun => true,
};
let page_decorations = match quirks.computed_field_decorations {
ComputedFieldDecorations::Drawn => true,
ComputedFieldDecorations::Dropped => false,
};
run.direct_props(code_format, page_decorations)
}
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct TableRules(Quirks);
impl TableRules {
pub(in crate::layout) const fn of(quirks: &Quirks) -> Self {
Self(*quirks)
}
pub(in crate::layout) fn cell_width_spacing<T>(self, spacing: Option<T>) -> Option<T> {
match self.0.spaced_columns {
SpacedColumns::Grid => None,
SpacedColumns::CellWidths => spacing,
}
}
pub(in crate::layout) fn page_part_lines(
self,
lines: (Option<Border>, Option<Border>),
) -> Option<(Option<Border>, Option<Border>)> {
match self.0.spaced_table_breaks {
SpacedTableBreaks::AroundTable => None,
SpacedTableBreaks::AroundPagePart => Some(lines),
}
}
pub(in crate::layout) fn unset_side_margin(self) -> Option<Length> {
match self.0.unset_cell_margins {
UnsetCellMargins::AfterLeftLine => None,
UnsetCellMargins::DefaultSides => Some(params::UNSET_SIDE_MARGIN),
}
}
pub(in crate::layout) fn fitting_cells<T>(
self,
cells: impl FnOnce() -> Option<T>,
) -> Option<T> {
match self.0.autofit_grid {
AutofitGrid::Saved => None,
AutofitGrid::FittingCells => cells(),
}
}
pub(in crate::layout) fn fixed_text_start<T>(self, cell: T, spaced: bool) -> Option<T> {
self.0.table_indent.fixes_text_start(spaced).then_some(cell)
}
pub(in crate::layout) fn leading_and_inside<T>(self, lines: impl FnOnce() -> T) -> Option<T> {
match self.0.right_to_left_edge {
RightToLeftEdge::BetweenCells => None,
RightToLeftEdge::LeadingAndInside => Some(lines()),
}
}
pub(in crate::layout) fn cells_above<T>(self, from_cells: impl FnOnce() -> T) -> Option<T> {
match self.0.row_line_room {
RowLineRoom::FirstColumn => None,
RowLineRoom::CellsAbove => Some(from_cells()),
}
}
pub(in crate::layout) fn merged_top_room<T>(self, room: T) -> Option<T> {
match self.0.merged_top_room {
MergedTopRoom::NoRoom => None,
MergedTopRoom::UndrawnLine => Some(room),
}
}
pub(in crate::layout) fn first_cell_fill<T>(self, first: impl FnOnce() -> T) -> Option<T> {
match self.0.merged_cell_fill {
MergedCellFill::EachRow => None,
MergedCellFill::FirstCell => Some(first()),
}
}
pub(in crate::layout) fn row_end_cells<T>(self, ends: impl FnOnce() -> T) -> Option<T> {
match self.0.row_end_borders {
RowEndBorders::GridEdges => None,
RowEndBorders::RowEnds => Some(ends()),
}
}
pub(in crate::layout) fn block_sides<T>(self, blocks: impl FnOnce() -> T) -> Option<T> {
match self.0.style_region_borders {
StyleRegionBorders::EachCell => None,
StyleRegionBorders::Blocks => Some(blocks()),
}
}
pub(in crate::layout) fn table_border(self, border: Border) -> Border {
match self.0.border_width_unit {
BorderWidthUnit::EighthPoints => border,
BorderWidthUnit::WholeTwips => border.in_whole_twips(),
}
}
}
pub(in crate::layout) fn page_part_merges<T>(quirks: &Quirks, merges: T) -> Option<T> {
match quirks.split_merge_align {
SplitMergeAlign::WholeCell => None,
SplitMergeAlign::PagePart => Some(merges),
}
}
pub(in crate::layout) fn exact_row_margin<T>(quirks: &Quirks, (top, bottom): (T, T)) -> T {
match quirks.exact_row_margin {
ExactRowMargin::AddsTopMargin => top,
ExactRowMargin::AddsBottomMargin => bottom,
}
}
pub(in crate::layout) fn last_header_above<T>(
quirks: &Quirks,
above: impl FnOnce() -> T,
) -> Option<T> {
match quirks.row_below_headers {
RowBelowHeaders::RowBefore => None,
RowBelowHeaders::LastHeader => Some(above()),
}
}
pub(in crate::layout) fn fill_inside_lines<T>(
quirks: &Quirks,
inside: impl FnOnce() -> T,
) -> Option<T> {
match quirks.cell_fill_sides {
CellFillSides::GridLines => None,
CellFillSides::InsideLines => Some(inside()),
}
}
pub(in crate::layout) fn fill_row_edge(
quirks: &Quirks,
place: Length,
snap: impl FnOnce(Length) -> Length,
) -> Length {
match quirks.cell_fill_rows {
CellFillRows::Exact => place,
CellFillRows::WholeDots => snap(place),
}
}
pub(in crate::layout) fn top_band_rows(
quirks: &Quirks,
(merged_above, joined_above): (bool, bool),
below_margin: impl FnOnce() -> Option<(Length, Length)>,
from_line: impl FnOnce() -> Option<(Length, Length)>,
) -> Option<(Length, Length)> {
match quirks.cell_top_band {
CellTopBand::BelowMargin => (!merged_above).then(below_margin).flatten(),
CellTopBand::FromLineEdge if joined_above => None,
CellTopBand::FromLineEdge => match from_line() {
Some((top, bottom)) => (top < bottom).then_some((top, bottom)),
None => below_margin(),
},
}
}
pub(in crate::layout) fn lines_from_aligned_top<T>(quirks: &Quirks, open: T) -> Option<T> {
match quirks.merged_cell_lines {
MergedCellLines::MovedAsBlock => None,
MergedCellLines::FromAlignedTop => Some(open),
}
}
pub(in crate::layout) fn kept_list_space<T>(quirks: &Quirks, list: Option<T>) -> Option<T> {
match quirks.cell_end_list_space {
CellEndListSpace::Dropped => None,
CellEndListSpace::Kept => list,
}
}
pub(in crate::layout) fn whole_nested_rows<T>(
quirks: &Quirks,
fits: impl FnOnce() -> T,
) -> Option<T> {
match quirks.nested_row_minimum {
NestedRowMinimum::Splits => None,
NestedRowMinimum::MovesWhole => Some(fits()),
}
}
pub(in crate::layout) fn carried_merge_move(
quirks: &Quirks,
device: &Device,
exact: Length,
) -> Length {
match quirks.carried_merge_move {
CarriedMergeMove::Exact => exact,
CarriedMergeMove::ToDot => device.snap(exact),
}
}
pub(in crate::layout) fn floating_table_shift_left(quirks: &Quirks) -> Length {
match quirks.floating_table_left {
FloatingTableLeft::TwipLeft => Length::from_units(Length::UNITS_PER_TWIP),
FloatingTableLeft::AtOffset => Length::ZERO,
}
}
pub(in crate::layout) fn floating_table_rise(quirks: &Quirks, anchor: Anchor) -> Length {
match (quirks.floating_table_top, anchor) {
(FloatingTableTop::TwipHigher, Anchor::Page | Anchor::Margin) => {
Length::from_units(Length::UNITS_PER_TWIP)
}
_ => Length::ZERO,
}
}
pub(in crate::layout) fn floating_breaks<T>(
quirks: &Quirks,
breaks: impl FnOnce() -> T,
) -> Option<T> {
match quirks.floating_table_breaks {
FloatingTableBreaks::Whole => None,
FloatingTableBreaks::AcrossPages => Some(breaks()),
}
}
pub(in crate::layout) fn cell_drawing_left(
quirks: &Quirks,
(x, width): (Length, Length),
(sides, wraps): ((Length, Length), bool),
) -> Length {
match quirks.cell_drawing_bounds {
CellDrawingBounds::InsideCell if wraps => x.min(sides.1 - width).max(sides.0),
CellDrawingBounds::Unbounded | CellDrawingBounds::InsideCell => x,
}
}
pub(in crate::layout) fn cell_drawing_top(
quirks: &Quirks,
y: Length,
(cell_top, wraps): (Length, bool),
) -> Length {
match quirks.cell_drawing_bounds {
CellDrawingBounds::InsideCell if wraps => y.max(cell_top),
CellDrawingBounds::Unbounded | CellDrawingBounds::InsideCell => y,
}
}
pub(in crate::layout) const fn aligns_at_cell_top(quirks: &Quirks) -> bool {
match quirks.cell_drawing_bounds {
CellDrawingBounds::Unbounded => false,
CellDrawingBounds::InsideCell => true,
}
}
pub(in crate::layout) fn clipped_cells<T>(quirks: &Quirks, cells: T) -> Option<T> {
match quirks.cell_clip {
CellClip::Unclipped => None,
CellClip::InsideLines => Some(cells),
}
}
pub(in crate::layout) fn table_dash<T>(quirks: &Quirks, dash: Option<T>) -> Option<T> {
match quirks.border_dashes {
BorderDashes::DrawsSolid => None,
BorderDashes::DashesCellPieces => dash,
}
}
pub(in crate::layout) fn cell_dash_cuts<T>(quirks: &Quirks, cuts: T) -> Option<T> {
match quirks.border_dashes {
BorderDashes::DrawsSolid => None,
BorderDashes::DashesCellPieces => Some(cuts),
}
}
pub(in crate::layout) fn later_part_limit<T>(quirks: &Quirks, later: T) -> Option<T> {
match quirks.later_part_widows {
LaterPartWidows::Ignored => None,
LaterPartWidows::Applied => Some(later),
}
}
pub(in crate::layout) fn split_part_fills<T>(quirks: &Quirks, part: T) -> Option<T> {
match quirks.split_row_fills {
SplitRowFills::Unfilled => None,
SplitRowFills::EachPart => Some(part),
}
}
pub(in crate::layout) fn inline_picture_cut<T>(
quirks: &Quirks,
cut: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.inline_picture_clip {
InlinePictureClip::Unknown => None,
InlinePictureClip::LineBox => cut(),
}
}
pub(in crate::layout) fn picture_line<T>(
quirks: &Quirks,
line: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.picture_line_place {
PictureLinePlace::Undrawn => None,
PictureLinePlace::Outside => line(),
}
}
pub(in crate::layout) fn metafile_top_ascent(
quirks: &Quirks,
font_units: impl FnOnce() -> i64,
logical_pixels: impl FnOnce() -> Option<i64>,
) -> i64 {
match quirks.metafile_top_ascent {
MetafileTopAscent::FontUnits => font_units(),
MetafileTopAscent::LogicalPixels => logical_pixels().unwrap_or_else(font_units),
}
}
pub(in crate::layout) fn chart_plot_rule(quirks: &Quirks, chart: &Columns) -> Option<PlotRule> {
PlotRules::of(quirks).rule(chart).ok()
}
pub(in crate::layout) fn chart_axis_room<T>(
quirks: &Quirks,
fitted: T,
roomed: impl FnOnce(T) -> Option<T>,
) -> Option<T> {
match quirks.chart_axis_room {
ChartAxisRoom::Values => Some(fitted),
ChartAxisRoom::LabelLines => roomed(fitted),
}
}
pub(in crate::layout) const fn chart_axis_before_lines(quirks: &Quirks) -> bool {
match quirks.chart_axis_order {
ChartAxisOrder::Unknown => false,
ChartAxisOrder::BeforeLines => true,
}
}
pub(in crate::layout) const fn chart_line_clip(quirks: &Quirks) -> bool {
match quirks.chart_line_clip {
ChartLineClip::Unknown => false,
ChartLineClip::PlotArea => true,
}
}
pub(in crate::layout) fn chart_data_labels<T>(
quirks: &Quirks,
drawn: impl FnOnce() -> Option<T>,
) -> Option<T> {
match quirks.chart_data_labels {
ChartDataLabels::LeftOut => None,
ChartDataLabels::OuterEnd => drawn(),
}
}
pub(in crate::layout) fn line_top_drawing<T>(
quirks: &Quirks,
from_line: impl FnOnce() -> T,
) -> Option<T> {
match quirks.from_line {
FromLine::LineTop => Some(from_line()),
FromLine::ParagraphTop => None,
}
}
pub(in crate::layout) fn band_height(quirks: &Quirks, height: Length) -> Length {
match quirks.band_height {
BandHeight::Exact => height,
BandHeight::WholeTwips => height.toward_zero_whole(Length::UNITS_PER_TWIP),
}
}
pub(in crate::layout) fn stepped_lines<T>(quirks: &Quirks, polygon: T) -> Option<T> {
match quirks.blocked_lines {
BlockedLines::BelowBox => None,
BlockedLines::LineSteps => Some(polygon),
}
}
pub(in crate::layout) fn wrap_outline<T>(quirks: &Quirks, outline: T) -> Option<T> {
match quirks.polygon_wrap {
PolygonWrap::Bounds => None,
PolygonWrap::Outline => Some(outline),
}
}
pub(in crate::layout) fn line_wrap_band(
quirks: &Quirks,
(height, single): (Length, Length),
) -> Length {
match quirks.line_wrap_band {
LineWrapBand::WholeLine => height,
LineWrapBand::SingleLine => single.min(height),
}
}
pub(in crate::layout) fn step_end(quirks: &Quirks, room: Length, step: Length) -> Length {
match quirks.step_end {
StepEnd::AtBottom => room.up_to_whole(step.units()),
StepEnd::PastBottom => (room + Length::from_units(1)).up_to_whole(step.units()),
}
}
pub(in crate::layout) fn widows_as_wrapped(quirks: &Quirks) -> bool {
match quirks.widow_forecast {
WidowForecast::WholeWidth => false,
WidowForecast::AsWrapped => true,
}
}
pub(in crate::layout) fn outline_clip<T>(quirks: &Quirks, text: T, cut: impl FnOnce(T) -> T) -> T {
match quirks.text_box_clip {
TextBoxClip::InsideOutline => cut(text),
TextBoxClip::Overflow => text,
}
}
pub(in crate::layout) fn text_box_section(
quirks: &Quirks,
mut section: crate::body::Section,
) -> crate::body::Section {
if quirks.text_box_columns == TextBoxColumns::OneColumn {
section.columns = crate::body::Columns::default();
}
section
}
pub(in crate::layout) fn smartart_low_baseline(
quirks: &Quirks,
(height, descent): (Length, Length),
baseline: Length,
) -> Length {
match quirks.smartart_low_spacing {
SmartArtLowSpacing::ScaledAscent => baseline,
SmartArtLowSpacing::FullDescent => height - descent,
}
}
pub(in crate::layout) fn box_last_line_drop(
quirks: &Quirks,
device: &Device,
lines: &[super::PlacedLine],
(box_top, height, bottom): (Length, Length, Length),
) -> Length {
match quirks.box_last_line {
BoxLastLine::Spaced => Length::ZERO,
BoxLastLine::RoomBelow => {
let Some(line) = lines.last() else {
return Length::ZERO;
};
let single = line.ascent + line.descent;
let text_bottom = box_text_top(quirks, box_top)
+ height.down_to_whole(Length::UNITS_PER_TWIP)
- bottom;
let room = text_bottom - (line.top + single);
let single_spaced = |line: &super::PlacedLine| {
line.area == super::LineArea::OutsideTables
&& line.spacing == LineSpacing::SINGLE
&& line.before == Length::ZERO
&& !line.spaced
};
if !lines.iter().all(single_spaced) || room < Length::ZERO {
return Length::ZERO;
}
let spaced = match line.baseline_form {
super::BaselineForm::SingleTop => {
device.rounded_down_baseline((line.ascent, line.descent), single, false)
}
super::BaselineForm::SingleBottom => {
line.top + line.baseline - device.snap(line.top)
}
_ => return Length::ZERO,
};
let line_bottom = device.snap(single + room) - device.snap(room);
let offset = device
.snap(line.ascent)
.max(line_bottom - device.snap(line.descent));
offset - spaced
}
}
}
pub(in crate::layout) fn box_outline_left(quirks: &Quirks, half_outline: Length) -> Length {
match quirks.box_outline_left {
BoxOutlineLeft::WholeTwipsHalf => half_outline.down_to_whole(Length::UNITS_PER_TWIP),
BoxOutlineLeft::ExactHalf => half_outline,
}
}
pub(in crate::layout) fn box_text_top(quirks: &Quirks, box_top: Length) -> Length {
match quirks.box_text_top {
BoxTextTop::NearestTwipTop => box_top.nearest_whole(Length::UNITS_PER_TWIP),
BoxTextTop::ExactTop => box_top,
}
}
pub(in crate::layout) fn box_outline_top(quirks: &Quirks, half_outline: Length) -> Length {
match quirks.box_text_top {
BoxTextTop::NearestTwipTop => half_outline.down_to_whole(Length::UNITS_PER_TWIP),
BoxTextTop::ExactTop => half_outline,
}
}
pub(in crate::layout) fn vml_box_insets(
quirks: &Quirks,
insets: Edges<Length>,
outline: Length,
) -> Edges<Length> {
match quirks.vml_box_outline {
VmlBoxOutline::InsideRoundedHalf => {
let lead = outline
.up_to_whole(2 * Length::UNITS_PER_TWIP)
.div_toward_zero(2);
let rest = outline - lead;
Edges {
top: insets.top + lead,
right: insets.right + rest,
bottom: insets.bottom + rest,
left: insets.left + lead,
}
}
VmlBoxOutline::Middle => insets,
}
}
pub(in crate::layout) fn frame_shift_left(quirks: &Quirks) -> Length {
match quirks.frame_left {
FrameLeft::TwipLeft => Length::from_units(Length::UNITS_PER_TWIP),
FrameLeft::AtOffset => Length::ZERO,
}
}
pub(in crate::layout) fn frame_fitted_room(quirks: &Quirks) -> Length {
match quirks.frame_fitted_width {
FrameFittedWidth::HalfTwipWider => params::FRAME_FITTED_ROOM,
FrameFittedWidth::Line => Length::ZERO,
}
}
pub(in crate::layout) fn style_ref_text(quirks: &Quirks, text: String) -> String {
let text = match quirks.style_ref_no_break_space {
StyleRefNoBreakSpace::Kept => text,
StyleRefNoBreakSpace::Plain => text.replace('\u{a0}', " "),
};
match quirks.style_ref_trailing_spaces {
StyleRefTrailingSpaces::Kept => text,
StyleRefTrailingSpaces::Dropped => text.trim_end_matches(' ').to_owned(),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct AutoSpace {
pub advance: Length,
pub extra: Length,
}
pub(in crate::layout) fn east_asian_auto_space(
quirks: &Quirks,
size: Length,
metrics: &crate::FaceMetrics,
balanced: bool,
) -> AutoSpace {
let quarter = size.div_toward_zero(crate::params::EAST_ASIAN_SPACING_PARTS);
match quirks.east_asian_auto_space {
crate::quirks::EastAsianAutoSpace::QuarterEm => AutoSpace {
advance: quarter,
extra: Length::ZERO,
},
crate::quirks::EastAsianAutoSpace::AverageWidthHalf => {
let width = if !balanced && !metrics.east_asian && metrics.average_width > 0 {
let em = i64::from(metrics.units_per_em.max(1));
let scaled = Length::from_units(f_office_units::div_round(
i64::from(metrics.average_width) * size.units(),
em,
));
scaled.div_toward_zero(2)
} else {
quarter
};
AutoSpace {
advance: width,
extra: width,
}
}
}
}
pub(in crate::layout) fn dropped_end_space<T>(quirks: &Quirks, hidden: T) -> Option<T> {
match quirks.hidden_header_footer_end {
HiddenHeaderFooterEnd::KeepsSpaceAfter => None,
HiddenHeaderFooterEnd::DropsSpaceAfter => Some(hidden),
}
}
pub(in crate::layout) fn space_above_after<T>(quirks: &Quirks, space: T) -> Option<T> {
match quirks.page_break_before_space {
PageBreakBeforeSpace::KeepsSpaceBefore => None,
PageBreakBeforeSpace::AboveSpaceAfter => Some(space),
}
}
pub(in crate::layout) fn aligned_room<T>(quirks: &Quirks, holds_notes: bool, room: T) -> Option<T> {
match quirks.alignment_with_notes {
AlignmentWithNotes::AlignsPage => Some(room),
AlignmentWithNotes::TopWithNotes => (!holds_notes).then_some(room),
}
}
pub(in crate::layout) fn property_date(
quirks: &Quirks,
zone_minutes: i32,
date: DateTime,
picture: Option<&str>,
) -> Option<String> {
match quirks.property_date_zone {
PropertyDateZone::Utc => picture.map(|picture| date.write(picture)),
PropertyDateZone::LocalDate => Some(
date.local_date(zone_minutes)
.write(picture.unwrap_or(PROPERTY_DATE_PICTURE)),
),
}
}
pub(in crate::layout) fn balanced_last_page<T>(quirks: &Quirks, marks: T) -> Option<T> {
match quirks.last_page_balance {
LastPageBalance::OnePage => None,
LastPageBalance::LastPage => Some(marks),
}
}
pub(in crate::layout) fn column_top_space_goes(quirks: &Quirks, at_page_top: bool) -> bool {
match quirks.column_top_space {
ColumnTopSpace::Stays => false,
ColumnTopSpace::GoesAtPageTop => at_page_top,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum DeletedTableAtTop {
Table,
Absent,
TakesSpace,
}
pub(in crate::layout) fn deleted_table_at_top(
quirks: &Quirks,
rules: ModeRules,
) -> DeletedTableAtTop {
match quirks.deleted_table_top {
DeletedTableTop::AsTable => DeletedTableAtTop::Table,
DeletedTableTop::ByMode if rules.deleted_table_keeps_top_space() => {
DeletedTableAtTop::Absent
}
DeletedTableTop::ByMode => DeletedTableAtTop::TakesSpace,
}
}
pub(in crate::layout) fn joins_hidden_mark_borders(quirks: &Quirks, rules: ModeRules) -> bool {
match quirks.hidden_mark_borders {
HiddenMarkBorders::Dropped => false,
HiddenMarkBorders::ByMode => rules.joins_hidden_mark_borders(),
}
}
pub(in crate::layout) fn multiple_top_from_text_edge(quirks: &Quirks, line: LineSpacing) -> bool {
quirks.multiple_top_border == MultipleTopBorder::FromTextEdge
&& matches!(line, LineSpacing::Auto(n) if n != f_office_units::scale::LINE)
}
pub(in crate::layout) fn multiple_bottom_from_text_edge(
quirks: &Quirks,
line: LineSpacing,
) -> bool {
quirks.multiple_bottom_border == MultipleBottomBorder::FromTextEdge
&& matches!(line, LineSpacing::Auto(n) if n > f_office_units::scale::LINE)
}
pub(in crate::layout) fn bottom_border_space_after_joined(quirks: &Quirks) -> bool {
quirks.bottom_border_space_after == BottomBorderSpaceAfter::Joined
}
pub(in crate::layout) fn take_border_sides(quirks: &Quirks, props: &mut ParaProps) {
if quirks.border_sides == BorderSides::EachSide {
props.take_border_sides();
}
}
pub(in crate::layout) fn drop_between_border(quirks: &Quirks, props: &mut ParaProps) -> bool {
match quirks.between_borders {
BetweenBorders::Dropped => props.drop_between_border(),
BetweenBorders::Drawn => false,
}
}
pub(in crate::layout) fn foot_border_room(quirks: &Quirks, bottom: Option<Border>) -> Length {
match (quirks.foot_border_room, bottom) {
(FootBorderRoom::Fits, Some(border)) => border.space + border.width,
(FootBorderRoom::Fits, None) | (FootBorderRoom::Hangs, _) => Length::ZERO,
}
}
pub(in crate::layout) fn spaced_section_end<T>(quirks: &Quirks, blocks: T) -> Option<T> {
match quirks.continuous_section_end {
ContinuousSectionEnd::OnlyBlockKeepsLine => None,
ContinuousSectionEnd::KeepsSpacesWithoutLine => Some(blocks),
}
}
pub(in crate::layout) fn page_dots_turn<T>(quirks: &Quirks, turn: T) -> Option<T> {
match quirks.turned_across_dots {
TurnedAcrossDots::FrameDots => None,
TurnedAcrossDots::PageDots => Some(turn),
}
}
pub(in crate::layout) fn equal_column_width(quirks: &Quirks, exact: Length) -> Length {
match quirks.column_widths {
ColumnWidths::Exact => exact,
ColumnWidths::WholeTwips => exact.toward_zero_whole(Length::UNITS_PER_TWIP),
}
}
pub(in crate::layout) fn kept_end_spaces(
quirks: &Quirks,
beside_left_to_right: impl FnOnce() -> bool,
in_right_to_left_runs: impl IntoIterator<Item = bool>,
) -> usize {
match quirks.right_to_left_end_space {
RightToLeftEndSpace::ParagraphLevel => 0,
RightToLeftEndSpace::RunLevelBesideLeftToRight => {
if beside_left_to_right() {
in_right_to_left_runs
.into_iter()
.take_while(|&right_to_left| right_to_left)
.count()
} else {
0
}
}
}
}
pub(in crate::layout) const fn end_space_fit(quirks: &Quirks, bidi: bool) -> EndSpaceFit {
if !bidi
&& matches!(
quirks.right_to_left_end_space,
RightToLeftEndSpace::RunLevelBesideLeftToRight
)
{
EndSpaceFit::WithRightToLeftSpaces
} else {
EndSpaceFit::WithoutSpaces
}
}
pub(in crate::layout) fn mirrored_columns<T>(
quirks: &Quirks,
mirrored: impl FnOnce() -> T,
) -> Option<T> {
match quirks.right_to_left_section_columns {
RightToLeftSectionColumns::FromLeft => None,
RightToLeftSectionColumns::FromRight => Some(mirrored()),
}
}
pub(in crate::layout) fn column_separators<T>(
quirks: &Quirks,
lines: impl FnOnce() -> T,
) -> Option<T> {
match quirks.column_separator {
ColumnSeparator::NotDrawn => None,
ColumnSeparator::SpaceMiddle => Some(lines()),
}
}
pub(in crate::layout) fn restart_side<T>(
quirks: &Quirks,
by_place: impl FnOnce() -> T,
by_number: impl FnOnce() -> T,
) -> T {
match quirks.restart_side {
RestartSide::Place => by_place(),
RestartSide::PreviousNumber => by_number(),
}
}
pub(in crate::layout) fn kept_separator_space<T>(quirks: &Quirks, last: T) -> Option<T> {
match quirks.separator_space_after {
SeparatorSpaceAfter::Dropped => None,
SeparatorSpaceAfter::Kept => Some(last),
}
}