use std::collections::HashSet;
use f_office_drawingml::color::on_white;
use f_office_drawingml::custom::OutOfRange;
use f_office_drawingml::shape::{CompoundLine, ShapeLook};
use f_office_drawingml::{Feature as DrawingMlFeature, Warning as DrawingMlWarning};
use f_office_paint::{Group, GroupClip, GroupPlaces, Item, Turn};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length};
use f_office_warnings::Name;
use crate::body::{Block, Content, Paragraph, ParagraphId, Section};
use crate::floating::{
Floating, InsetEdge, PageArea, Position, Relative, Room, TextAnchor, TextPath, TextTurn, Wrap,
WrapSides,
};
use crate::lines::Line;
use crate::params::NARROWEST_WRAP;
use crate::props::Align;
use super::output::BodyArea;
use super::table::{DOWN, UP, turn_item};
use super::{Layout, PlacedLine, TurnedGlyphs, decisions, text_path};
impl Layout<'_> {
pub(super) fn floating(
&mut self,
paragraph: &Paragraph,
(top, lines): (Length, &[Line]),
later: &[usize],
) -> Waiting {
let drawings: Vec<usize> = lines
.iter()
.skip(1)
.flat_map(anchor_marks)
.filter(|&index| {
later.contains(&index)
|| floatings(paragraph)
.nth(index)
.is_some_and(|drawing| self.waits_for_line(drawing))
})
.collect();
let para_order = self.output.found.next_legacy_para();
for (index, drawing) in floatings(paragraph).enumerate() {
if !drawings.contains(&index) {
self.place_floating(drawing, top, para_order);
}
}
Waiting {
top,
drawings,
later: later.to_vec(),
part: (self.output.pages.len(), top),
para_order,
}
}
pub(super) fn floating_on_line(
&mut self,
paragraph: &Paragraph,
(lines, index): (&[Line], usize),
waiting: &mut Waiting,
) {
let Some(line) = lines.get(index).filter(|_| !waiting.drawings.is_empty()) else {
return;
};
let page = self.output.pages.len();
if waiting.part.0 != page {
waiting.part = (page, self.y);
}
let top = if index == 0 { waiting.top } else { self.y };
for mark in anchor_marks(line) {
let Some(at) = waiting.drawings.iter().position(|&wait| wait == mark) else {
continue;
};
waiting.drawings.swap_remove(at);
let from = if waiting.later.contains(&mark) {
waiting.part.1
} else {
top
};
if let Some(drawing) = floatings(paragraph).nth(mark) {
self.place_floating(drawing, from, waiting.para_order);
}
}
}
pub(super) fn waits_for_line(&self, drawing: &Floating) -> bool {
decisions::line_top_drawing(&self.context.quirks, || drawing.v.from == Relative::Line)
.unwrap_or(false)
}
pub(super) fn marks_anchor(&self, drawing: &Floating) -> bool {
self.waits_for_line(drawing) || drawing.v.from == Relative::Paragraph
}
pub(super) fn may_anchor_later(&self, paragraph: &Paragraph, lines: &[Line]) -> bool {
self.story.is_none()
&& self.column.cell.is_none()
&& lines
.iter()
.skip(1)
.flat_map(anchor_marks)
.any(|index| from_paragraph(paragraph, index))
}
pub(super) fn held_for_wrap(&self, paragraph: &Paragraph) -> bool {
let earlier = &self.context.earlier.wraps.held;
let (mut next_band, mut next_square) = (
self.output.found.bands.len(),
self.output.found.squares.len(),
);
let mut held = false;
for drawing in floatings(paragraph).filter(|drawing| early_wrap(drawing)) {
let (at, pages) = match drawing.wrap {
Some(Wrap::TopAndBottom { .. }) => (&mut next_band, &earlier.bands),
Some(Wrap::Beside { .. }) => (&mut next_square, &earlier.squares),
None => continue,
};
held |= pages
.get(*at)
.is_some_and(|page| *page > self.output.pages.len());
*at += 1;
}
held
}
fn lays_out_in_cell(&self, drawing: &Floating) -> bool {
self.column.cell.is_some()
&& (drawing.cell_layout == crate::floating::CellLayout::InCell
|| self.uses_modern_floating_layout())
}
fn cell_down(&self, drawing: &Floating) -> (Position, Option<Length>) {
let position = drawing.v;
if !self.lays_out_in_cell(drawing) {
return (position, None);
}
let inside_cell = decisions::aligns_at_cell_top(&self.context.quirks);
let area = match position.from {
Relative::Area(PageArea::Margin) => true,
Relative::Area(_) => inside_cell,
_ => false,
};
let by_offset = area && position.align.is_none() && position.share.is_none();
let at_cell_top = self.on_cells_first_page()
&& inside_cell
&& matches!(position.from, Relative::Area(_))
&& position.align.is_some();
let cell_top = self.cell_top.filter(|_| by_offset || at_cell_top);
let position = if at_cell_top {
Position {
from: Relative::Area(PageArea::Margin),
align: Some(Align::Start),
..position
}
} else if cell_top.is_some() {
Position {
from: Relative::Area(PageArea::Margin),
..position
}
} else {
position
};
(position, cell_top)
}
fn in_cell(
&self,
drawing: &Floating,
(x, y): (Length, Length),
width: Length,
) -> (Length, Length) {
if !self.lays_out_in_cell(drawing) {
return (x, y);
}
let (quirks, wraps) = (&self.context.quirks, drawing.wrap.is_some());
let x = self.cell_sides.map_or(x, |sides| {
decisions::cell_drawing_left(quirks, (x, width), (sides, wraps))
});
let top = self.cell_top.filter(|_| self.on_cells_first_page());
let y = top.map_or(y, |top| {
decisions::cell_drawing_top(quirks, y, (top, wraps))
});
(x, y)
}
fn on_cells_first_page(&self) -> bool {
self.cell_top.is_some() && self.filled_part().is_none_or(|part| part == 0)
}
fn place_floating(&mut self, drawing: &Floating, paragraph: Length, para_order: usize) {
let s = self.section;
let (p, notes) = match self.page {
Some(page) if drawing.wrap.is_none() => (page, self.story_notes),
Some(page) => (page, Length::ZERO),
None => self.body_margins(drawing),
};
let horizontal = areas(s.width, s.left, s.right);
let vertical = areas(p.height, p.top, p.bottom + notes);
let (size, inset) = sized(drawing, &horizontal, &vertical);
let size = self.fitted(drawing, size);
let Edges {
left,
top,
right,
bottom,
} = self.aligned_effect(drawing, size);
let (position, across) = self.across(drawing, horizontal);
let x = place(
position,
(size.width, left, right),
inset.0,
&across,
self.column.left,
);
let (place_down, cell_top) = self.cell_down(drawing);
let down = match cell_top {
Some(top) => Areas {
text: (top, vertical.text.1),
..vertical
},
None => vertical,
};
let y = place(
place_down,
(size.height, top, bottom),
inset.1,
&down,
paragraph,
);
let y = if !self.uses_modern_floating_layout()
&& drawing.vml_shadow.is_some()
&& drawing.h.align.is_some()
&& place_down.align.is_none()
{
y + top
} else {
y
};
let (x, y) = self.in_cell(drawing, (x, y), size.width);
let x = self.within_page_width(drawing, x, size, s.width);
let y = self.below_top_margin(drawing, y, size, paragraph);
let (upward, pinned) = self.upward_wrap_slot(drawing);
let y = pinned.as_ref().map_or(y, |p| p.y);
self.lower_cell_floor(drawing, y + size.height, cell_top.is_some());
let height = self.drawn_height(drawing, size, (x, y));
self.record_floating_wrap(
drawing,
(x, y, size, height, paragraph),
(upward, pinned),
para_order,
);
self.show_floating((drawing, size), (x, y), (s.width, p.height));
}
pub(super) fn is_header_or_footer_story(&self) -> bool {
matches!(
self.story.as_ref().map(|story| &story.kind),
Some(super::StoryKind::Header { .. } | super::StoryKind::Footer { .. })
)
}
fn upward_wrap_slot(
&mut self,
drawing: &Floating,
) -> (Option<(bool, usize)>, Option<super::UpwardWrap>) {
if !drawing.v.from.follows_text() || drawing.wrap.is_none() {
return (None, None);
}
let in_body = self.column.cell.is_none() && self.story.is_none() && self.page.is_none();
let in_modern_hf = self.column.cell.is_none()
&& self.is_header_or_footer_story()
&& self.uses_modern_floating_layout();
if in_body || in_modern_hf {
let ordinal = self.body_floatings;
self.body_floatings += 1;
let page = self.output.pages.len();
let earlier = self
.story_earlier_wraps
.as_deref()
.unwrap_or(&self.context.earlier.wraps);
let pinned = earlier
.upward
.iter()
.find(|u| u.ordinal == ordinal && u.page == page)
.cloned();
return (Some((false, ordinal)), pinned);
}
if self.column.cell.is_some() {
let ordinal = self.cell_floatings;
self.cell_floatings += 1;
let pinned = self
.cell_upward_earlier
.iter()
.find(|u| u.ordinal == ordinal)
.cloned();
return (Some((true, ordinal)), pinned);
}
(None, None)
}
fn record_floating_wrap(
&mut self,
drawing: &Floating,
(x, y, size, height, paragraph): (Length, Length, Size, Length, Length),
(upward, pinned): (Option<(bool, usize)>, Option<super::UpwardWrap>),
para_order: usize,
) {
if let Some(pinned) = pinned {
if matches!(upward, Some((false, _))) {
self.output.found.upward.push(pinned);
}
return;
}
let early = early_wrap(drawing) && self.column.cell.is_none();
let page = (self.output.pages.len(), early);
let earlier = self
.story_earlier_wraps
.as_deref()
.unwrap_or(&self.context.earlier.wraps);
let band_height = decisions::band_height(&self.context.quirks, height);
let (shape, new_early) = match drawing.wrap {
Some(Wrap::TopAndBottom { above, below }) => {
let band = super::Band {
top: y - above,
bottom: y + band_height + below,
left: x,
right: x + size.width,
};
let new_early = keep_wrap(
page,
band,
&mut self.bands,
&mut self.output.found.bands,
&earlier.bands,
);
(Some((band.top, super::UpwardShape::Band(band))), new_early)
}
Some(Wrap::Beside {
distances,
sides,
polygon,
}) => {
let has_polygon = polygon.is_some();
let line_steps = polygon
.and_then(|polygon| decisions::stepped_lines(&self.context.quirks, polygon))
.is_some();
let polygon = polygon.unwrap_or_default();
let below = y + band_height + distances.bottom;
let outline = Some(&drawing.outline)
.filter(|points| !points.is_empty())
.and_then(|points| decisions::wrap_outline(&self.context.quirks, points))
.map(|points| {
Outline::on_page(points, (x, y), (size.width, size.height), distances)
});
let square = Square {
top: y - distances.top + polygon.top,
bottom: below - polygon.bottom,
left: x - distances.left + polygon.left,
right: x + size.width + distances.right - polygon.right,
below: below.max(below - polygon.bottom),
sides,
line_steps,
polygon: has_polygon,
outline,
narrowest: NARROWEST_WRAP,
start_past: StartPastWrap::FirstLineIndent,
table: false,
};
let new_early = keep_wrap(
page,
square.clone(),
&mut self.squares,
&mut self.output.found.squares,
&earlier.squares,
);
(
Some((square.top, super::UpwardShape::Square(square))),
new_early,
)
}
None => (None, false),
};
let legacy_body = self.column.cell.is_none()
&& self.story.is_none()
&& self.page.is_none()
&& !self.uses_modern_floating_layout();
if new_early && legacy_body {
self.output
.found
.note_legacy_reflow(self.output.pages.len(), para_order);
}
if let (Some((in_cell, ordinal)), Some((wrap_top, wrap))) = (upward, shape) {
self.note_upward_wrap(
in_cell,
ordinal,
(y, wrap_top, paragraph),
wrap,
(legacy_body, para_order),
);
}
}
fn note_upward_wrap(
&mut self,
in_cell: bool,
ordinal: usize,
(y, wrap_top, paragraph): (Length, Length, Length),
wrap: super::UpwardShape,
(legacy_body, para_order): (bool, usize),
) {
if wrap_top >= paragraph {
if !in_cell && legacy_body {
let entry = super::UpwardWrap {
page: self.output.pages.len(),
ordinal,
y,
wrap,
};
self.output.found.note_legacy_candidate(para_order, entry);
}
return;
}
if in_cell {
if self.cell_top.is_some_and(|ct| paragraph > ct) {
self.cell_upward_found.push(super::UpwardWrap {
page: 0,
ordinal,
y,
wrap,
});
}
} else if paragraph > self.column_top {
let page = self.output.pages.len();
self.output.found.upward.push(super::UpwardWrap {
page,
ordinal,
y,
wrap,
});
if legacy_body {
self.output.found.note_legacy_reflow(page, para_order);
}
}
}
fn fitted(&mut self, drawing: &Floating, size: Size) -> Size {
let body_turned = body_turn(drawing.text_turn).is_some();
if !drawing.fits_width || drawing.blocks.is_empty() || body_turned {
return size;
}
let section = decisions::text_box_section(&self.context.quirks, self.section);
let story = self.text_box_story(drawing, None, None);
let widest = self.layout_without_warnings(|layout| {
let mut inner = layout.story_layout(§ion, &[], Length::ZERO, story);
drawing
.blocks
.iter()
.filter_map(|block| match block {
Block::Paragraph(paragraph) => {
let resolved = inner.resolve(paragraph);
Some(inner.unbroken_width(paragraph, &resolved))
}
Block::Table(_) => None,
})
.max()
.unwrap_or(Length::ZERO)
});
let insets = self.text_insets(drawing, size);
Size {
width: (widest + insets.left + insets.right).up_to_whole(Length::UNITS_PER_TWIP),
..size
}
}
fn text_box_story(
&self,
drawing: &Floating,
turn: Option<(Turn, TurnedGlyphs)>,
inside: Option<Edges<Length>>,
) -> super::Story {
super::Story {
kind: super::StoryKind::TextBox {
text_color: drawing.text_color,
turn,
box_text: drawing.box_text,
inside,
},
numbers: self.inner_numbers(),
}
}
fn show_floating(
&mut self,
(drawing, size): (&Floating, Size),
(x, y): (Length, Length),
page: (Length, Length),
) {
let Some(bounds) = Edges::placed(x, y, size.width, size.height) else {
self.skip_out_of_range(kind_of(drawing), drawing);
return;
};
if !self.device.draws_object(bounds, page) {
return;
}
let items = self.draw_sized((drawing, size), x, y);
let behind = drawing.behind && drawing.wrap.is_none();
if self.column.cell.is_some() {
self.cell_drawing(items, !behind);
} else if behind {
self.behind
.extend(items.into_iter().map(|item| (drawing.stack, item)));
} else {
self.front
.extend(items.into_iter().map(|item| (drawing.stack, item)));
}
}
fn lower_cell_floor(&mut self, drawing: &Floating, bottom: Length, from_cell: bool) {
if !drawing.v.from.follows_text() && !from_cell {
return;
}
let wraps = drawing.wrap.is_some();
self.cell_floor = self.cell_floor.map(|floor| floor.lowered(bottom, wraps));
}
fn body_margins(&mut self, drawing: &Floating) -> (Section, Length) {
let s = self.section;
let from_margins = matches!(
drawing.v.from,
Relative::Area(PageArea::Margin | PageArea::StartMargin | PageArea::EndMargin)
);
if self.story.is_some() || self.column.cell.is_some() || !from_margins {
return (s, Length::ZERO);
}
let index = self.output.pages.len();
let notes = self
.context
.earlier
.note_heights
.of(index)
.unwrap_or_else(|| self.notes_height());
let margins = BodyArea {
top: s.top,
end: s.height - s.bottom,
notes: Length::ZERO,
};
let body = BodyArea {
top: self.page_top(index),
end: self.body_bottom_of(index),
notes,
};
let area = decisions::story_margin_area(&self.context.quirks, margins, body);
if area == body {
self.output.margin_notes.push((index, notes));
}
let frame = Section {
top: area.top,
bottom: s.height - area.end,
..s
};
(frame, area.notes)
}
fn within_page_width(
&self,
drawing: &Floating,
x: Length,
size: Size,
page_width: Length,
) -> Length {
let wraps = drawing.wrap.is_some();
let body = self.page.is_none() && self.column.cell.is_none();
if !wraps || !body {
return x;
}
let Some((vis_width, _)) = visual_size(drawing, size) else {
return x;
};
let eff = drawing.effect;
let offset = (size.width - vis_width).div_toward_zero(2);
let vis_left = x + offset;
let clamped = vis_left
.min(page_width - vis_width - eff.right)
.max(eff.left);
clamped - offset
}
pub(super) fn uses_modern_floating_layout(&self) -> bool {
self.settings.mode_rules.keeps_drawings_below_top_margin()
}
fn clamps_floating_vertically(&self, drawing: &Floating) -> bool {
drawing.wrap.is_some()
&& self.page.is_none()
&& self.column.cell.is_none()
&& drawing.v.from.follows_text()
&& self.uses_modern_floating_layout()
}
pub(super) fn floating_overflows_page(
&mut self,
paragraph: &Paragraph,
paragraph_top: Length,
) -> bool {
if self.page.is_some() || self.column.cell.is_some() || self.story.is_some() {
return false;
}
let later = self.context.earlier.later_anchors.of(paragraph.id);
let page = self.output.pages.len();
let body_bottom = self.body_bottom_of(page);
let s = self.section;
let horizontal = areas(s.width, s.left, s.right);
for (index, drawing) in floatings(paragraph).enumerate() {
if later.contains(&index) || !self.clamps_floating_vertically(drawing) {
continue;
}
let (p, notes) = self.body_margins(drawing);
let vertical = areas(p.height, p.top, p.bottom + notes);
let (size, inset) = sized(drawing, &horizontal, &vertical);
let size = self.fitted(drawing, size);
let Edges { top, bottom, .. } = self.aligned_effect(drawing, size);
let y = place(
drawing.v,
(size.height, top, bottom),
inset.1,
&vertical,
paragraph_top,
);
let Some((_, vis_height)) = visual_size(drawing, size) else {
continue;
};
let offset = (size.height - vis_height).div_toward_zero(2);
let vis_top = y + offset;
let ceiling = body_bottom - vis_height - drawing.effect.bottom;
if vis_top > ceiling && ceiling < paragraph_top {
return true;
}
}
false
}
fn below_top_margin(
&self,
drawing: &Floating,
y: Length,
size: Size,
paragraph: Length,
) -> Length {
if !self.clamps_floating_vertically(drawing) || self.story.is_some() {
return y;
}
let page = self.output.pages.len();
let eff = drawing.effect;
let floor = self.page_top(page) + eff.top;
let Some((_, vis_height)) = visual_size(drawing, size) else {
return y.max(floor);
};
let offset = (size.height - vis_height).div_toward_zero(2);
let vis_top = y + offset;
let ceiling = self.body_bottom_of(page) - vis_height - eff.bottom;
let bottom_clamped = if ceiling >= paragraph {
vis_top.min(ceiling)
} else {
vis_top
};
bottom_clamped.max(floor) - offset
}
fn across(&self, drawing: &Floating, areas: Areas) -> (Position, Areas) {
let h = Position {
align: drawing
.h
.align
.map(|align| align.on_page(self.current_page_is_even())),
..drawing.h
};
let in_cell_layout = self.lays_out_in_cell(drawing);
if self.column.cell.is_some() && !in_cell_layout {
return (h, areas);
}
if in_cell_layout
&& h.from == Relative::Area(PageArea::Page)
&& h.share.is_none()
&& decisions::aligns_at_cell_top(&self.context.quirks)
&& let Some(sides) = self.cell_sides
{
return (
h,
Areas {
page: sides,
..areas
},
);
}
if h.from != Relative::Column
&& !(in_cell_layout && h.from == Relative::Area(PageArea::Margin))
{
return (h, areas);
}
let column = (self.column.left, self.column.left + self.column.width);
let position = Position {
from: Relative::Area(PageArea::Margin),
..h
};
(
position,
Areas {
text: column,
..areas
},
)
}
pub(super) fn draw_sized(
&mut self,
(drawing, size): (&Floating, Size),
x: Length,
y: Length,
) -> Vec<Item> {
self.draw_placed((drawing, size), (x, y), false)
}
fn draw_placed(
&mut self,
(drawing, size): (&Floating, Size),
(x, y): (Length, Length),
in_group: bool,
) -> Vec<Item> {
let mut items = Vec::new();
for &(left, top, ref part) in &drawing.parts {
items.extend(self.draw_placed((part, Size::of(part)), (x + left, y + top), true));
}
if let Some(chart) = drawing.chart.as_ref().and_then(|c| c.columns.as_deref()) {
items.extend(self.shape_items(drawing, (x, y), size));
let Some(frame) = Edges::placed(x, y, size.width, size.height) else {
self.skip_out_of_range(crate::Drawing::Chart, drawing);
return items;
};
match self.columns(chart, frame) {
Some((columns, drawn)) => {
items.extend(columns);
if !drawn.axes_and_legend {
self.warn_of_feature(crate::Feature::ChartLabels, drawing.part.as_str());
}
if !drawn.data_labels {
self.warn_of_feature(crate::Feature::DataLabels, drawing.part.as_str());
}
}
None => self.skip(crate::Drawing::Chart, drawing, crate::Reason::NotPlaced),
}
return items;
}
if let Some(path) = &drawing.text_path {
items.extend(self.text_path_items(drawing, path, (x, y), size));
return items;
}
if let Some(picture) = &drawing.picture
&& drawing.blocks.is_empty()
{
items.extend(self.shape_items(drawing, (x, y), size));
items.extend(self.picture_items(picture, x, y));
return items;
}
if drawing.blocks.is_empty() {
items.extend(self.shape_items(drawing, (x, y), size));
return items;
}
items.extend(self.text_box((drawing, size), (x, y), in_group));
items
}
fn text_box(
&mut self,
(drawing, size): (&Floating, Size),
(x, y): (Length, Length),
in_group: bool,
) -> Vec<Item> {
if let Some(turn) = body_turn(drawing.text_turn) {
return self.turned_text_box((drawing, size), (x, y), turn);
}
let s = self.section;
let insets = self.text_insets(drawing, size);
let Edges { top, bottom, .. } = insets;
let (section, mut text_top) = self.text_section(drawing, (size, insets), (x, y));
let paragraphs = crate::body::all_paragraphs(&drawing.blocks);
self.warn_of_box_note_marks(paragraphs.iter().copied(), false, drawing.part.as_str());
let mut height = size.height;
if drawing.anchor != TextAnchor::Top || drawing.fits_text {
let end = self.text_end(drawing, §ion, text_top);
if drawing.fits_text {
height = end + bottom - y;
}
let room = y + height - bottom - end;
let room = match drawing.room {
Room::TextBox => room.max(Length::ZERO),
Room::Shape => room,
};
text_top += match drawing.anchor {
TextAnchor::Top => Length::ZERO,
TextAnchor::Center => room.div_toward_zero(2),
TextAnchor::Bottom => room,
};
}
let mut items = self.shape_items(drawing, (x, y), size.with_height(height));
if let Some(picture) = &drawing.picture {
items.extend(self.picture_items(picture, x, y));
}
let area = self.text_area(drawing, (x, y), size, height);
let story = self.text_box_story(drawing, None, area);
let drops = drops_last_line(drawing, in_group);
let device = self.device;
let quirks = &self.context.quirks;
let drop = |lines: &[PlacedLine]| {
if drops {
decisions::box_last_line_drop(quirks, &device, lines, (y, height, bottom))
} else {
Length::ZERO
}
};
let (text, _, lines) =
self.placed_story_dropping_last(§ion, &drawing.blocks, text_top, story, drop);
let page_height = self.page.unwrap_or(s).height;
let band = |line: &PlacedLine| (line.top, line.top + line.height);
let text_bottom = y + height - bottom;
let hidden: Vec<(Length, Length)> = lines
.iter()
.map(band)
.filter(|&(top, _)| !self.device.draws_box_line((top, text_bottom), page_height))
.collect();
let on_hidden = |at: Length| {
hidden
.iter()
.any(|&(top, bottom)| (top..bottom).contains(&at))
};
let shown = without_hidden(text, &on_hidden);
let mut text = self.cut_text(drawing, shown, (x, size.width), (y + top, text_bottom));
if let Some(turn) = shape_text_turn(drawing) {
let centre = (
x + size.width.div_toward_zero(2),
y + height.div_toward_zero(2),
);
for item in &mut text {
turn_item(item, (centre, centre), turn, true);
}
items.extend(text);
return items;
}
items.extend(text);
self.output.placed.extend(
lines
.into_iter()
.filter(|line| !hidden.contains(&band(line))),
);
items
}
fn text_section(
&self,
drawing: &Floating,
(size, insets): (Size, Edges<Length>),
(x, y): (Length, Length),
) -> (Section, Length) {
let s = self.section;
let mut section = decisions::text_box_section(&self.context.quirks, s);
section.left = x + insets.left;
section.right = s.width - (x + size.width - insets.right);
(section, self.text_origin(drawing, y) + insets.top)
}
fn text_end(&mut self, drawing: &Floating, section: &Section, text_top: Length) -> Length {
let story = self.text_box_story(drawing, None, None);
self.layout_without_warnings(|layout| {
if drawing.room == Room::TextBox {
layout.story_end(section, &drawing.blocks, text_top, story)
} else if drawing.box_text == crate::floating::BoxText::SmartArt {
layout.smartart_text_end(section, &drawing.blocks, text_top, story)
} else {
layout.story_in(section, &drawing.blocks, text_top, story).1
}
})
}
fn drawn_height(&mut self, drawing: &Floating, size: Size, (x, y): (Length, Length)) -> Length {
let chart = drawing
.chart
.as_ref()
.is_some_and(|chart| chart.columns.is_some());
let text_box = !chart && drawing.text_path.is_none() && !drawing.blocks.is_empty();
if !drawing.fits_text || !text_box || body_turn(drawing.text_turn).is_some() {
return size.height;
}
let insets = self.text_insets(drawing, size);
let (section, text_top) = self.text_section(drawing, (size, insets), (x, y));
self.text_end(drawing, §ion, text_top) + insets.bottom - y
}
fn turned_text_box(
&mut self,
(drawing, size): (&Floating, Size),
(x, y): (Length, Length),
(turn, glyphs): (Turn, TurnedGlyphs),
) -> Vec<Item> {
let insets = self.text_insets(drawing, size);
let (start, end, first, last) = if turn == DOWN {
(insets.top, insets.bottom, insets.right, insets.left)
} else {
(insets.bottom, insets.top, insets.left, insets.right)
};
let mut section = decisions::text_box_section(&self.context.quirks, self.section);
section.left = y + start;
section.width = section.left + (size.height - start - end).max(Length::ZERO);
section.right = Length::ZERO;
let story = self.text_box_story(drawing, Some((turn, glyphs)), None);
let paragraphs = crate::body::all_paragraphs(&drawing.blocks);
self.warn_of_box_note_marks(paragraphs.iter().copied(), false, drawing.part.as_str());
let mut text_top = y;
if drawing.anchor != TextAnchor::Top {
let end = self.layout_without_warnings(|layout| {
layout.story_end(§ion, &drawing.blocks, y, story.clone())
});
let room = (y + size.width - first - last - end).max(Length::ZERO);
text_top += match drawing.anchor {
TextAnchor::Top => Length::ZERO,
TextAnchor::Center => room.div_toward_zero(2),
TextAnchor::Bottom => room,
};
}
let mut items = self.shape_items(drawing, (x, y), size);
if let Some(picture) = &drawing.picture {
items.extend(self.picture_items(picture, x, y));
}
let (mut text, ..) = self.placed_story(§ion, &drawing.blocks, text_top, story);
let origin = if turn == DOWN {
(x + size.width - first, y + start)
} else {
(x + first, y + size.height - start)
};
for item in &mut text {
turn_item(item, ((section.left, y), origin), turn, true);
}
let along = (y + insets.top, y + size.height - insets.bottom);
items.extend(self.cut_text(drawing, text, (x, size.width), along));
items
}
fn text_area(
&self,
drawing: &Floating,
(x, y): (Length, Length),
size: Size,
height: Length,
) -> Option<Edges<Length>> {
let insets = self.text_insets(drawing, size);
(drawing.box_text == crate::floating::BoxText::Paragraphs).then(|| Edges {
left: x + insets.left,
top: self.text_origin(drawing, y) + insets.top,
right: x + size.width - insets.right,
bottom: y + height - insets.bottom,
})
}
fn text_insets(&self, drawing: &Floating, size: Size) -> Edges<Length> {
let outline = drawing
.look
.as_ref()
.and_then(|look| look.inset_line_width(&self.shaper.theme().shapes))
.unwrap_or(Length::ZERO);
match drawing.inset_edge {
InsetEdge::Middle => drawing.insets,
InsetEdge::Vml => {
let insets =
decisions::vml_box_insets(&self.context.quirks, drawing.insets, outline);
let inner = drawing.text_rect.and_then(|rect| {
rect.insets_in(
drawing.width - insets.left - insets.right,
drawing.height - insets.top - insets.bottom,
)
});
inner.map_or(insets, |inner| insets.with(inner, |a, b| a + b))
}
InsetEdge::Inside => {
let half_line = outline.div_toward_zero(2);
let horizontal = decisions::box_outline_left(&self.context.quirks, half_line);
let insets = Edges {
left: drawing.insets.left + horizontal,
right: drawing.insets.right + horizontal,
top: drawing.insets.top
+ decisions::box_outline_top(&self.context.quirks, half_line),
bottom: drawing.insets.bottom + half_line,
};
let flips = drawing.look.as_ref().map_or([false; 2], ShapeLook::flips);
let rect = drawing
.preset_rect
.as_ref()
.and_then(|rect| rect.insets_in(size.width, size.height))
.map(|rect| mirrored(rect, flips));
rect.map_or(insets, |rect| insets.with(rect, |a, b| a + b))
}
}
}
fn text_origin(&self, drawing: &Floating, y: Length) -> Length {
match drawing.inset_edge {
InsetEdge::Inside => decisions::box_text_top(&self.context.quirks, y),
InsetEdge::Middle | InsetEdge::Vml => y,
}
}
fn cut_text(
&self,
drawing: &Floating,
text: Vec<Item>,
(left, width): (Length, Length),
(top, bottom): (Length, Length),
) -> Vec<Item> {
if drawing.room != Room::TextBox {
return text;
}
decisions::outline_clip(&self.context.quirks, text, |text| {
let half_outline = drawing
.look
.as_ref()
.and_then(|look| look.inset_line_width(&self.shaper.theme().shapes))
.map_or(Length::ZERO, |width| width.div_toward_zero(2));
let clip = GroupClip::rect(
left + half_outline,
top,
width - half_outline - half_outline,
bottom - top,
);
let mut out = Vec::new();
let mut cut = Vec::new();
for item in text {
let clipped = match &item {
Item::Glyphs(_) | Item::Rect(_) => true,
Item::Group(group) => group.places == GroupPlaces::Cell,
Item::Path(_) | Item::Gradient(_) | Item::Image(_) => false,
};
if clipped {
cut.push(item);
} else {
if !cut.is_empty() {
out.push(Item::Group(Group::of_page(
std::mem::take(&mut cut),
clip.clone(),
)));
}
out.push(item);
}
}
if !cut.is_empty() {
out.push(Item::Group(Group::of_page(cut, clip)));
}
out
})
}
fn cast_shape_shadow(
&mut self,
drawing: &Floating,
look: &ShapeLook,
(items, drawn): (&[Item], &mut Vec<Item>),
glow_radius: Length,
) {
let theme = &self.shaper.theme().shapes;
let shadow = look
.shadow_in(theme)
.map(|s| (s.blur, s.offset(), s.color(theme), false))
.or_else(|| {
drawing
.vml_shadow
.map(|s| (Length::ZERO, s.offset, Some(s.color), true))
});
let Some((blur, offset, color, is_vml)) = shadow else {
return;
};
let cast = decisions::shape_shadow(&self.context.quirks, || {
super::shadow::items_with_glow(blur, offset, color?, glow_radius, items)
})
.flatten();
if let Some(shadow_items) = cast {
drawn.extend(shadow_items);
} else if !is_vml {
self.output.warnings.push(crate::Warning::DrawingMl {
part: drawing.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Shadow,
},
});
}
}
fn shape_items(
&mut self,
drawing: &Floating,
(x, y): (Length, Length),
size: Size,
) -> Vec<Item> {
let Some(look) = &drawing.look else {
return Vec::new();
};
let theme = &self.shaper.theme().shapes;
let fill = look.fill(theme).map(|(rgb, alpha)| on_white(rgb, alpha));
let line = look
.line(theme)
.map(|(rgb, alpha, width)| (on_white(rgb, alpha), width));
let compound = line
.is_some()
.then_some(DrawingMlFeature::CompoundOutline)
.filter(|_| look.compound_left_out());
for feature in look.theme_features(theme).into_iter().chain(compound) {
self.output.warnings.push(crate::Warning::DrawingMl {
part: drawing.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported { feature },
});
}
let Some(frame) = Edges::placed(x, y, size.width, size.height) else {
self.skip_out_of_range(crate::Drawing::Shape, drawing);
return Vec::new();
};
let thick = crate::params::COMPOUND_LINE_THICK_PARTS;
let parts: &[i64] = match look.compound {
CompoundLine::Single => &[1],
CompoundLine::Double => &[1, 1, 1],
CompoundLine::ThickThin => &[thick, 1, 1],
CompoundLine::ThinThick => &[1, 1, thick],
CompoundLine::Triple => &[1, 1, 2, 1, 1],
};
let effect_gradient = look.resolve_effect_gradient(theme, frame).ok().flatten();
let fill = fill.or_else(|| effect_gradient.as_ref().map(|_| f_office_paint::Rgb::BLACK));
let mut items = look
.items_with_theme(theme, frame, fill, line, parts)
.unwrap_or_else(|OutOfRange| {
self.skip_out_of_range(crate::Drawing::Shape, drawing);
Vec::new()
});
let mut drawn = Vec::new();
let glow_radius = look.glow().map_or(Length::ZERO, |glow| glow.radius);
self.cast_shape_shadow(drawing, look, (&items, &mut drawn), glow_radius);
let theme = &self.shaper.theme().shapes;
if let Some(glow) = look.glow() {
let cast = decisions::shape_shadow(&self.context.quirks, || {
let color = glow.color(theme)?;
super::shadow::glow_items(glow.radius, color, &items)
})
.flatten();
if let Some(glow_items) = cast {
drawn.extend(glow_items);
} else {
self.output.warnings.push(crate::Warning::DrawingMl {
part: drawing.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Glow,
},
});
}
}
if let Some(reflection) = look.reflection() {
drawn.extend(self.shape_reflection(*reflection, &items, &drawing.part));
}
if let (Some(gradient), Some(first)) = (effect_gradient.as_ref(), items.first_mut())
&& let Item::Path(fill_path) = first
&& let Some(picture) = super::shadow::effect_gradient_item(gradient, fill_path)
{
*first = picture;
}
drawn.extend(items);
drawn
}
fn shape_reflection(
&mut self,
reflection: f_office_drawingml::effect::Reflection,
items: &[Item],
part: &f_office_warnings::Name,
) -> Option<Item> {
let cast = decisions::shape_shadow(&self.context.quirks, || {
super::shadow::shape_reflection_item(reflection, items)
})
.flatten();
if cast.is_none() {
self.output.warnings.push(crate::Warning::DrawingMl {
part: part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Reflection,
},
});
}
cast
}
fn aligned_effect(&self, drawing: &Floating, size: Size) -> Edges<Length> {
let Some(path) = &drawing.text_path else {
return drawing.effect;
};
let Ok((letters, em)) = self.text_path_letters(path) else {
return drawing.effect;
};
Edges::placed(Length::ZERO, Length::ZERO, size.width, size.height)
.and_then(|frame| {
let items =
text_path::letter_items(&letters, em, frame, (path.rotation, path.color))?;
Some(text_path::aligned_extents(&items, frame, path.rotation))
})
.unwrap_or(drawing.effect)
}
fn text_path_letters(
&self,
path: &TextPath,
) -> Result<(Vec<text_path::Letter>, text_path::Em), NoLetters> {
let fonts = self.shaper.fonts();
let face = fonts
.face(&path.face, false, false)
.or_else(|| fonts.family_substitute(&path.face, false, false))
.ok_or(NoLetters::NoFace)?;
let letters = path
.string
.chars()
.map(|ch| {
let glyph = fonts.glyph(face.font, ch).unwrap_or(0);
Some(text_path::Letter {
advance: fonts.advance(face.font, glyph).unwrap_or(0),
outline: fonts.outline(face.font, glyph).ok()?,
})
})
.collect::<Option<Vec<_>>>()
.ok_or(NoLetters::NoOutline)?;
let em = text_path::Em {
units_per_em: face.metrics.units_per_em,
descent: face.metrics.descent,
};
Ok((letters, em))
}
fn text_path_items(
&mut self,
drawing: &Floating,
path: &TextPath,
(x, y): (Length, Length),
size: Size,
) -> Vec<Item> {
let (letters, em) = match self.text_path_letters(path) {
Ok(found) => found,
Err(NoLetters::NoFace) => {
self.output.warnings.push(crate::Warning::TextNotDrawn {
asked: Some(Name::new(path.face.as_str())),
tried: vec![Name::new(path.face.as_str())],
});
return Vec::new();
}
Err(NoLetters::NoOutline) => {
self.skip(crate::Drawing::Shape, drawing, crate::Reason::Unsupported);
return Vec::new();
}
};
let items = Edges::placed(x, y, size.width, size.height).and_then(|frame| {
text_path::letter_items(&letters, em, frame, (path.rotation, path.color))
});
items.unwrap_or_else(|| {
self.skip_out_of_range(crate::Drawing::Shape, drawing);
Vec::new()
})
}
fn skip_out_of_range(&mut self, kind: crate::Drawing, drawing: &Floating) {
self.skip(kind, drawing, crate::Reason::OutOfRange);
}
fn skip(&mut self, kind: crate::Drawing, drawing: &Floating, reason: crate::Reason) {
self.output.warnings.push(crate::Warning::DrawingSkipped {
drawing: kind,
part: drawing.part.clone(),
reason,
});
}
}
pub(super) fn keep_wrap<T: Clone + PartialEq>(
(page, early): (usize, bool),
wrap: T,
own: &mut Vec<T>,
found: &mut Vec<(usize, T)>,
earlier: &[(usize, T)],
) -> bool {
let at = (page, wrap);
let is_new = early && earlier.get(found.len()) != Some(&at);
if !early || is_new {
own.push(at.1.clone());
}
if early {
found.push(at);
}
is_new
}
fn drops_last_line(drawing: &Floating, in_group: bool) -> bool {
drawing.anchor == TextAnchor::Top
&& !in_group
&& !drawing.fits_text
&& drawing.room == Room::TextBox
&& drawing.inset_edge == InsetEdge::Inside
}
fn kind_of(drawing: &Floating) -> crate::Drawing {
if drawing
.chart
.as_ref()
.is_some_and(|chart| chart.columns.is_some())
{
crate::Drawing::Chart
} else if drawing.picture.is_some() && drawing.blocks.is_empty() {
crate::Drawing::Picture
} else {
crate::Drawing::Shape
}
}
fn floatings(paragraph: &Paragraph) -> impl Iterator<Item = &Floating> {
let content = paragraph.runs.iter().flat_map(|run| &run.content);
content.filter_map(|content| match content {
Content::Floating(floating) => Some(&**floating),
_ => None,
})
}
pub(super) struct Waiting {
top: Length,
drawings: Vec<usize>,
later: Vec<usize>,
part: (usize, Length),
para_order: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NoteHeights(Vec<Length>);
impl NoteHeights {
pub(super) fn of_areas(areas: &[BodyArea]) -> Self {
Self(areas.iter().map(|area| area.notes).collect())
}
pub(super) fn of(&self, page: usize) -> Option<Length> {
self.0.get(page).copied()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LaterAnchors(HashSet<(ParagraphId, usize)>);
impl LaterAnchors {
pub(super) fn found(found: &[(ParagraphId, usize)]) -> Self {
Self(found.iter().copied().collect())
}
pub(super) fn of(&self, paragraph: ParagraphId) -> Vec<usize> {
let mut drawings: Vec<usize> = self
.0
.iter()
.filter(|(id, _)| *id == paragraph)
.map(|&(_, drawing)| drawing)
.collect();
drawings.sort_unstable();
drawings
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn join(&mut self, other: &Self) -> bool {
let before = self.0.len();
self.0.extend(other.0.iter().copied());
self.0.len() != before
}
}
#[derive(Default)]
pub(super) struct AnchorPages {
first: Option<usize>,
marks: Vec<(usize, usize)>,
}
impl AnchorPages {
pub(super) fn note(&mut self, paragraph: &Paragraph, line: &Line, page: usize) {
self.first.get_or_insert(page);
for mark in anchor_marks(line).filter(|&mark| from_paragraph(paragraph, mark)) {
self.marks.push((mark, page));
}
}
pub(super) fn later(&self) -> Vec<usize> {
let first = self.first.unwrap_or(0);
let later = self.marks.iter().filter(|&&(_, page)| page > first);
later.map(|&(drawing, _)| drawing).collect()
}
}
fn anchor_marks(line: &Line) -> impl Iterator<Item = usize> + '_ {
line.anchors.iter().map(|mark| mark.drawing)
}
fn from_paragraph(paragraph: &Paragraph, index: usize) -> bool {
floatings(paragraph)
.nth(index)
.is_some_and(|drawing| drawing.v.from == Relative::Paragraph)
}
pub(super) fn holds_later(line: &Line, later: &[usize]) -> bool {
anchor_marks(line).any(|mark| later.contains(&mark))
}
fn early_wrap(drawing: &Floating) -> bool {
!drawing.v.from.follows_text()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Square {
pub(super) top: Length,
pub(super) bottom: Length,
pub(super) left: Length,
pub(super) right: Length,
pub(super) below: Length,
pub(super) sides: Option<WrapSides>,
pub(super) line_steps: bool,
pub(super) polygon: bool,
pub(super) outline: Option<Outline>,
pub(super) narrowest: Length,
pub(super) start_past: StartPastWrap,
pub(super) table: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StartPastWrap {
FirstLineIndent,
Whole,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct NarrowedPiece {
pub(super) start: Length,
pub(super) width: Length,
pub(super) edge: Option<Length>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Outline {
points: Vec<(Length, Length)>,
distances: Edges<Length>,
}
impl Outline {
fn on_page(
points: &[(i64, i64)],
corner: (Length, Length),
size: (Length, Length),
distances: Edges<Length>,
) -> Self {
let whole = i128::from(crate::params::WRAP_POLYGON_WHOLE);
let scale = |value: i64, side: Length| {
let share = i128::from(value) * i128::from(side.units()) / whole;
Length::from_units(i64::try_from(share).unwrap_or_default())
};
let points = points
.iter()
.map(|&(x, y)| (corner.0 + scale(x, size.0), corner.1 + scale(y, size.1)))
.collect();
Self { points, distances }
}
fn across(&self, (top, bottom): (Length, Length)) -> Option<(Length, Length)> {
let (low, high) = (top - self.distances.bottom, bottom + self.distances.top);
let closing = self.points.last().zip(self.points.first());
let edges = self
.points
.windows(2)
.filter_map(|pair| pair.first().zip(pair.get(1)))
.chain(closing);
let mut xs = edges
.filter_map(|(&a, &b)| inside_band(a, b, (low, high)))
.flatten();
let first = xs.next()?;
let (left, right) = xs.fold((first, first), |(l, r), x| (l.min(x), r.max(x)));
Some((left - self.distances.left, right + self.distances.right))
}
}
fn inside_band(
(ax, ay): (Length, Length),
(bx, by): (Length, Length),
(low, high): (Length, Length),
) -> Option<[Length; 2]> {
if ay == by {
return (low < ay && ay < high).then_some([ax, bx]);
}
let (top, bottom) = (ay.min(by), ay.max(by));
if bottom <= low || top >= high {
return None;
}
let at = |y: Length| {
let part = i128::from((y - ay).units()) * i128::from((bx - ax).units())
/ i128::from((by - ay).units());
ax + Length::from_units(i64::try_from(part).unwrap_or_default())
};
Some([at(low.max(top)), at(high.min(bottom))])
}
impl Square {
pub(super) fn across(&self, band: (Length, Length)) -> Option<(Length, Length)> {
match &self.outline {
Some(outline) => outline.across(band),
None => Some((self.left, self.right)),
}
}
fn line_end(
&self,
(top, height, step): (Length, Length, Length),
(left, right): (Length, Length),
quirks: &crate::quirks::Quirks,
) -> Length {
if !self.line_steps || step <= Length::ZERO {
return self.below;
}
let end = top + decisions::step_end(quirks, self.bottom - top, step);
if self.outline.is_none() {
return end;
}
let mut at = top + step;
while at < end.min(self.bottom) {
let free = self.across((at, at + height)).is_none_or(|(a, b)| {
right.min(a) - left >= NARROWEST_WRAP || right - left.max(b) >= NARROWEST_WRAP
});
if free {
return at;
}
at += step;
}
end
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct LineWrap {
pub(super) top: Length,
pub(super) band: Length,
pub(super) step: Length,
pub(super) before: Length,
pub(super) after: Length,
}
impl Layout<'_> {
pub(super) fn beside(
&self,
span: LineWrap,
(start, width): (Length, Length),
kept: Length,
) -> Option<Beside> {
let (meeting, across): (Vec<&Square>, Vec<(Length, Length)>) = self
.squares
.iter()
.filter_map(|s| {
let (span_top, span_bottom) = if s.polygon {
(span.top, span.top + span.band)
} else {
(span.top - span.before, span.top + span.band + span.after)
};
(span_top < s.bottom && span_bottom > s.top)
.then(|| s.across((span_top, span_bottom)).map(|edges| (s, edges)))
.flatten()
})
.unzip();
let column_left = self.column.left;
let left = column_left + start;
let right = left + width;
let quirks = &self.context.quirks;
let first_end = meeting
.iter()
.map(|s| s.line_end((span.top, span.band, span.step), (left, right), quirks))
.min()?;
let mut pieces = vec![(left, right)];
for &(square_left, square_right) in &across {
pieces = pieces
.into_iter()
.flat_map(|(a, b)| [(a, b.min(square_left)), (a.max(square_right), b)])
.filter(|(a, b)| b > a)
.collect();
}
let chosen = chosen_pieces(&meeting, pieces);
let Some(&(a, b)) = chosen.first() else {
if meeting.iter().any(|s| s.outline.is_some()) {
return Some(Beside::Step(first_end));
}
return Some(Beside::Below(first_end));
};
let past = |edge: Length| {
let whole = meeting.iter().zip(&across).any(|(square, &(_, right))| {
right == edge && square.start_past == StartPastWrap::Whole
});
if whole { start } else { kept }
};
let place = |(a, b): (Length, Length)| {
let edge = (a > left).then(|| a - column_left);
let from = edge.map_or(start, |edge| edge + past(a));
NarrowedPiece {
start: from,
width: (b - column_left - from).min(width),
edge,
}
};
let line_steps = meeting.iter().any(|s| s.line_steps);
Some(Beside::Line(
place((a, b)),
first_end,
line_steps,
chosen.iter().skip(1).map(|&piece| place(piece)).collect(),
))
}
pub(super) fn wrap_band(&self, size: &super::line::height::LineBox) -> Length {
decisions::line_wrap_band(&self.context.quirks, (size.height, size.step()))
}
pub(super) fn keep_lines_wrap_target(
&self,
line_bands: &[(Length, Length)],
) -> Option<(Length, bool)> {
if self.uses_modern_floating_layout()
|| self.column.cell.is_some()
|| self.story.is_some()
|| self.squares.is_empty()
{
return None;
}
let col_left = self.column.left;
let col_right = col_left + self.column.width;
let mut y = self.y;
for (idx, &(height, band)) in line_bands.iter().enumerate() {
let bottom = y + band;
let hit = self
.squares
.iter()
.filter(|sq| {
sq.start_past == StartPastWrap::FirstLineIndent
&& sq.right > col_left
&& sq.left < col_right
&& y < sq.top
&& sq.top < bottom
})
.map(|sq| sq.top)
.min();
if let Some(sq_top) = hit {
return Some(if idx == 0 { (sq_top, true) } else { (y, false) });
}
y += height;
}
None
}
pub(super) fn clear_floats(&mut self) {
while let Some(below) = self
.squares
.iter()
.filter(|s| s.top <= self.y && self.y < s.below)
.map(|s| s.below)
.max()
{
self.move_to(below);
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Beside {
Line(NarrowedPiece, Length, bool, Vec<NarrowedPiece>),
Below(Length),
Step(Length),
}
#[derive(Clone, Copy, Debug)]
struct Areas {
page: (Length, Length),
text: (Length, Length),
start_margin: (Length, Length),
end_margin: (Length, Length),
}
impl Areas {
const fn of(&self, area: PageArea) -> (Length, Length) {
match area {
PageArea::Page => self.page,
PageArea::Margin => self.text,
PageArea::StartMargin => self.start_margin,
PageArea::EndMargin => self.end_margin,
}
}
}
enum NoLetters {
NoFace,
NoOutline,
}
fn place(
position: Position,
(size, lead, trail): (Length, Length, Length),
inset: Length,
areas: &Areas,
paragraph: Length,
) -> Length {
let (start, end) = match position.from {
Relative::Area(area) => areas.of(area),
Relative::Column => areas.text,
Relative::Paragraph | Relative::Line => (paragraph, paragraph + size),
};
match (position.align, position.share) {
(Some(Align::Start | Align::Inside), _) => start + lead,
(Some(Align::Center), _) => {
start + lead + (end - start - size - lead - trail).div_toward_zero(2)
}
(Some(Align::End | Align::Outside), _) => end - size - trail,
(None, Some(share)) => {
(end - start)
.checked_mul(share)
.and_then(|part| part.checked_div_round(DRAWING_WHOLE))
.map_or(start + position.offset, |part| start + part)
+ inset
}
(None, None) => start + position.offset + inset,
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct Size {
width: Length,
height: Length,
}
impl Size {
pub(super) const fn of(drawing: &Floating) -> Self {
Self {
width: drawing.width,
height: drawing.height,
}
}
pub(super) const fn with_height(self, height: Length) -> Self {
Self { height, ..self }
}
}
fn sized(drawing: &Floating, horizontal: &Areas, vertical: &Areas) -> (Size, (Length, Length)) {
let mut size = Size::of(drawing);
let mut inset = (Length::ZERO, Length::ZERO);
if drawing.picture.is_some() {
return (size, inset);
}
let effect = drawing.effect;
let span = |(from, share): (PageArea, i64), areas: &Areas| {
let (start, end) = areas.of(from);
(end - start)
.checked_mul(share)
.map(|part| part.div_toward_zero(DRAWING_WHOLE))
};
if let Some(width) = drawing.relative_width.and_then(|w| span(w, horizontal)) {
size.width = width - effect.left - effect.right;
inset.0 = effect.left;
}
if let Some(height) = drawing.relative_height.and_then(|h| span(h, vertical)) {
size.height = height - effect.top - effect.bottom;
inset.1 = effect.top;
}
(size, inset)
}
fn without_hidden(text: Vec<Item>, on_hidden: &dyn Fn(Length) -> bool) -> Vec<Item> {
text.into_iter()
.filter_map(|item| match item {
Item::Glyphs(run) if run.glyphs.first().is_some_and(|g| on_hidden(g.y)) => None,
Item::Rect(rect) if on_hidden(rect.y) => None,
Item::Group(mut group) if group.places == GroupPlaces::Cell => {
group.items = without_hidden(group.items, on_hidden);
(!group.items.is_empty()).then_some(Item::Group(group))
}
item => Some(item),
})
.collect()
}
fn areas(length: Length, start: Length, end: Length) -> Areas {
Areas {
page: (Length::ZERO, length),
text: (start, length - end),
start_margin: (Length::ZERO, start),
end_margin: (length - end, length),
}
}
fn chosen_pieces(meeting: &[&Square], pieces: Vec<(Length, Length)>) -> Vec<(Length, Length)> {
let usable: Vec<(Length, Length)> = pieces
.into_iter()
.filter(|&piece| piece.1 - piece.0 >= narrowest(meeting, piece))
.collect();
let widest = |usable: Vec<(Length, Length)>, rightmost: bool| -> Vec<(Length, Length)> {
let best = if rightmost {
usable.iter().copied().max_by_key(|&(a, b)| b - a)
} else {
usable.iter().copied().rev().max_by_key(|&(a, b)| b - a)
};
best.into_iter().collect()
};
if meeting.iter().all(|s| s.sides == Some(WrapSides::Both)) {
return usable;
}
match meeting {
[square] => match square.sides {
Some(WrapSides::Left) => usable
.into_iter()
.filter(|(_, b)| *b <= square.left)
.collect(),
Some(WrapSides::Right) => usable
.into_iter()
.filter(|(a, _)| *a >= square.right)
.collect(),
Some(WrapSides::Largest) => widest(usable, false),
_ => widest(usable, true),
},
_ => widest(usable, true),
}
}
fn narrowest(meeting: &[&Square], (a, b): (Length, Length)) -> Length {
meeting
.iter()
.filter(|square| b == square.left || a == square.right)
.fold(NARROWEST_WRAP, |least, square| least.max(square.narrowest))
}
const fn mirrored(rect: Edges<Length>, [across, down]: [bool; 2]) -> Edges<Length> {
let (left, right) = if across {
(rect.right, rect.left)
} else {
(rect.left, rect.right)
};
let (top, bottom) = if down {
(rect.bottom, rect.top)
} else {
(rect.top, rect.bottom)
};
Edges {
left,
top,
right,
bottom,
}
}
fn visual_size(drawing: &Floating, size: Size) -> Option<(Length, Length)> {
if drawing.text_path.as_ref().is_some_and(|t| t.rotation != 0)
|| drawing.picture.as_ref().is_some_and(|p| p.turn.is_some())
{
return None;
}
let Some(look) = &drawing.look else {
return Some((size.width, size.height));
};
let quarters = look.quarter_turns()?;
if quarters % 2 != 0 {
Some((size.height, size.width))
} else {
Some((size.width, size.height))
}
}
const fn body_turn(turn: TextTurn) -> Option<(Turn, TurnedGlyphs)> {
match turn {
TextTurn::Down => Some((DOWN, TurnedGlyphs::WithLine)),
TextTurn::Up => Some((UP, TurnedGlyphs::WithLine)),
TextTurn::EastAsianDown => Some((DOWN, TurnedGlyphs::EastAsianUpright)),
TextTurn::Upright | TextTurn::WithShape => None,
}
}
fn shape_text_turn(drawing: &Floating) -> Option<Turn> {
(drawing.text_turn == TextTurn::WithShape)
.then(|| {
drawing
.look
.as_ref()
.and_then(ShapeLook::text_quarter_turns)
})
.flatten()
.and_then(|quarters| crate::picture::turn(quarters, [false, false]))
}
#[cfg(test)]
mod tests;