use std::collections::{HashMap, HashSet};
use f_office_paint::{Item, Point, Rect, Rgb};
use f_office_units::{Edges, Length};
use super::{Gaps, Shape, Sides, Slot, TopPart, width};
use crate::grid::{Device, Rounding};
use crate::layout::line::height::{BoxTop, SpaceBefore, row_line_dot};
use crate::layout::page_items::PageItems;
use crate::layout::{Layout, decisions};
use crate::params::MAX_DASHED_PAGE_ITEMS;
use crate::props::{Border, DashStyle};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum OutlineEnd {
Row,
Table,
Page(Option<Border>),
}
impl OutlineEnd {
pub(super) fn of_row(shape: &Shape, index: usize) -> Self {
if index + 1 == shape.grid.table.rows.len() {
Self::Table
} else {
Self::Row
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RowTop {
pub(super) at: Length,
pub(super) rest: Option<i64>,
}
impl RowTop {
pub(super) fn without_rest(at: Length) -> Self {
Self { at, rest: None }
}
}
#[derive(Clone, Copy, Debug)]
enum Join {
Covered,
Cut { vertical: Border, as_wide: Border },
}
fn joins(parts: &[TopPart], (low, high): (Length, Length)) -> Vec<Option<Join>> {
parts
.iter()
.zip(parts.iter().skip(1).map(Some).chain([None]))
.map(|(part, next)| {
let next = next?;
let vertical = part
.sides
.1
.filter(|_| low < part.right && part.right < high)?;
let as_wide = [part.border, next.border]
.into_iter()
.find(|border| border.width == vertical.width);
Some(as_wide.map_or(Join::Covered, |as_wide| Join::Cut { vertical, as_wide }))
})
.collect()
}
fn part_slot<'t>(device: &Device, slot: &Slot<'t>, part: &TopPart) -> Slot<'t> {
let side = |line: Option<Border>, edge: Length, own: Option<Border>| {
line.or(own.filter(|_| edge == slot.left || edge == slot.right))
};
let mut cell = Slot {
left: part.left,
right: part.right,
borders: Sides {
left: side(part.sides.0, part.left, slot.borders.left),
right: side(part.sides.1, part.right, slot.borders.right),
..slot.borders
},
top_parts: Vec::new(),
..slot.clone()
};
cell.sides = SideLines::of(device, &cell);
cell
}
fn part_ends(cell: &Slot, join_after: bool, after_cut: bool, forward: bool) -> (Length, Length) {
let (a, b) = Layout::line_ends(cell);
let (mut from, mut to) = (a.min(b), a.max(b));
let near = |side| cell.sides.parts(side).iter().map(|line| line.start).min();
let far = |side| {
cell.sides
.parts(side)
.iter()
.copied()
.map(LinePart::end)
.max()
};
if join_after {
if forward {
to = near(CellSide::Right).unwrap_or(to);
} else {
from = far(CellSide::Right).unwrap_or(from);
}
}
if after_cut {
if forward {
from = far(CellSide::Left).unwrap_or(from);
} else {
to = near(CellSide::Left).unwrap_or(to);
}
}
(from.min(to), from.max(to))
}
impl Layout<'_> {
fn top_parts_lines(&mut self, slot: &Slot, top: RowTop, (low, high): (Length, Length)) {
let device = self.device;
let joins = joins(&slot.top_parts, (low, high));
let forward = slot.left <= slot.right;
for (i, part) in slot.top_parts.iter().enumerate() {
let cell = part_slot(&device, slot, part);
let after = joins.get(i).copied().flatten();
let after_cut = i
.checked_sub(1)
.and_then(|j| joins.get(j).copied().flatten())
.is_some_and(|join| matches!(join, Join::Cut { .. }));
if let Some(Join::Cut { vertical, as_wide }) = after {
self.cut_vertical(&cell, (vertical, as_wide), top);
}
let (from, to) = part_ends(&cell, after.is_some(), after_cut, forward);
let (from, to) = (from.max(low), to.min(high));
if from < to {
self.row_top_border(part.border, (device.snap(from), device.snap(to)), top);
}
}
}
fn cut_vertical(&mut self, cell: &Slot, (vertical, as_wide): (Border, Border), top: RowTop) {
let line_top = self.top_line_dot(top, Length::ZERO);
let height = self.top_line_end(as_wide, top) - line_top;
for line in cell.sides.parts(CellSide::Right) {
let at = Point {
x: line.start,
y: line_top,
};
self.push_line(vertical, line_rect(vertical, at, line.thick, height));
}
}
pub(super) fn cell_borders(
&mut self,
slot: &Slot,
(top, bottom): (RowTop, Length),
last: bool,
) {
if let Some(gaps) = slot.gaps {
self.cell_box(slot, gaps, (top.at, bottom));
return;
}
let b = &slot.borders;
let (x0, x1) = Self::line_ends(slot);
if slot.top_parts.is_empty() {
if let Some(border) = b.top {
self.row_top_border(border, (x0, x1), top);
}
} else {
self.top_parts_lines(slot, top, (x0.min(x1), x0.max(x1)));
}
if last {
self.bottom_line(slot, bottom);
}
let device = self.device;
let end = match b.bottom.filter(|_| last) {
Some(border) => self.bottom_end(border, bottom),
None => device.snap(bottom),
};
let line_top = self.top_line_dot(top, Length::ZERO);
let (y, height) = (line_top, end - line_top);
for (border, side) in [(b.left, CellSide::Left), (b.right, CellSide::Right)] {
let Some(border) = border else { continue };
for part in slot.sides.parts(side) {
let at = Point { x: part.start, y };
self.push_line(border, line_rect(border, at, part.thick, height));
}
}
}
pub(super) fn bottom_parts(&self, border: Border, y: Length) -> Vec<LinePart> {
let device = self.device;
let rest = self
.table_twips
.row_end
.filter(|end| end.at == y)
.map(|end| end.twips);
if let Some(parts) = device.whole_table_border(&border) {
let whole: Length = parts.iter().copied().sum();
let start = device
.centered_table_line(|| {
row_line_dot(&device, y + border.width, rest, BoxTop::Lower) - whole
})
.unwrap_or_else(|| device.snap(y));
return whole_parts(start, &parts);
}
border
.lines()
.into_iter()
.map(|(offset, thickness)| {
let thick = device.table_line_thickness(thickness);
let start = device
.centered_table_line(|| {
let end = y + offset + thickness;
row_line_dot(&device, end, rest, BoxTop::Lower) - thick
})
.unwrap_or_else(|| device.snap(y + offset));
LinePart { start, thick }
})
.collect()
}
fn top_line_dot(&self, top: RowTop, offset: Length) -> Length {
let box_top = self.box_top((top.at, SpaceBefore::Absent));
row_line_dot(&self.device, top.at + offset, top.rest, box_top)
}
fn top_parts(&self, border: Border, top: RowTop) -> Vec<LinePart> {
let device = self.device;
if let Some(parts) = device.whole_table_border(&border) {
return whole_parts(self.top_line_dot(top, Length::ZERO), &parts);
}
border
.lines()
.into_iter()
.map(|(offset, thickness)| LinePart {
start: self.top_line_dot(top, offset),
thick: device.table_line_thickness(thickness),
})
.collect()
}
fn row_top_border(&mut self, border: Border, (x0, x1): (Length, Length), top: RowTop) {
let device = self.device;
for part in self.top_parts(border, top) {
let at = Point {
x: device.snap(x0),
y: part.start,
};
self.push_line(
border,
line_rect(border, at, device.snap(x1 - x0), part.thick),
);
}
}
pub(super) fn top_line_end(&self, border: Border, top: RowTop) -> Length {
self.top_parts(border, top)
.into_iter()
.map(LinePart::end)
.max()
.unwrap_or_else(|| self.top_line_dot(top, Length::ZERO))
}
fn bottom_end(&self, border: Border, bottom: Length) -> Length {
let device = self.device;
device
.centered_table_line(|| {
self.bottom_parts(border, bottom)
.into_iter()
.map(LinePart::end)
.max()
.unwrap_or_else(|| device.snap(bottom))
})
.unwrap_or_else(|| device.snap(bottom + border.width))
}
pub(super) fn top_bands(
&mut self,
slots: &[Slot],
(top, inner): (RowTop, Length),
lines_from: usize,
) {
for slot in slots {
let Some(band) = self.top_band(slot, (top, inner)) else {
continue;
};
let rows = (band.y, band.y + band.height);
self.items.push(Item::Rect(band));
let right = slot.sides.parts(CellSide::Right);
let lifted = lift(&mut self.items, lines_from, right, rows);
self.items.extend_lines(lifted);
}
}
fn top_band(&self, slot: &Slot, (top, inner): (RowTop, Length)) -> Option<Rect> {
let color = super::rows::cell_fill_color(slot)?;
if slot.gaps.is_some() {
return None;
}
let margin = slot.margins.top;
let device = self.device;
let below_margin =
|| (margin > Length::ZERO).then(|| (device.snap(inner), device.snap(inner + margin)));
let from_line = || {
let borders: Vec<Border> = if slot.top_parts.is_empty() {
slot.borders.top.into_iter().collect()
} else {
slot.top_parts.iter().map(|part| part.border).collect()
};
let end = borders
.iter()
.map(|&border| self.top_line_end(border, top))
.max()?;
let width = borders.iter().map(|border| border.width).max()?;
let line_top = self.top_line_dot(top, Length::ZERO);
Some((end, device.snap(line_top + width + margin)))
};
let (y0, y1) = decisions::top_band_rows(
&self.context.quirks,
(slot.merged_above(), slot.joined_above()),
below_margin,
from_line,
)?;
let sides = &slot.sides;
let (x0, x1) = (
sides
.edge(CellSide::Left, LineEdge::Inner)
.unwrap_or(slot.left),
sides
.edge(CellSide::Right, LineEdge::Inner)
.unwrap_or(slot.right),
);
Some(Rect {
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
color,
})
}
fn line_ends(slot: &Slot) -> (Length, Length) {
let sides = &slot.sides;
(
sides
.edge(CellSide::Left, LineEdge::Outer)
.unwrap_or(slot.left),
sides
.edge(CellSide::Right, LineEdge::Outer)
.unwrap_or(slot.right),
)
}
fn cell_box(&mut self, slot: &Slot, gaps: Gaps, (top, bottom): (Length, Length)) {
let b = &slot.borders;
let device = self.device;
let inward = |v: Length, up: bool| {
let down = device.floor(v);
if up && down < v { device.ceil(v) } else { down }
};
let (x0, x1) = (
inward(slot.left + gaps.left, true),
inward(slot.right - gaps.right, false),
);
let (y0, y1) = (
inward(top + gaps.top, true),
inward(bottom + width(b.bottom), false),
);
for (border, y) in [(b.top, y0), (b.bottom, y1 - width(b.bottom))] {
if let Some(border) = border {
self.border_rect(border, Point { x: x0, y }, x1 - x0, Direction::Across);
}
}
for (border, x) in [(b.left, x0), (b.right, x1 - width(b.right))] {
if let Some(border) = border {
self.border_rect(border, Point { x, y: y0 }, y1 - y0, Direction::Down);
}
}
}
pub(super) fn table_outline(
&mut self,
shape: &Shape,
(index, slots): (usize, &[Slot]),
(top, bottom): (Length, Length),
(opening, end): (Option<Border>, OutlineEnd),
) {
let Some(spacing) = shape.grid.spacing() else {
return;
};
let (Some(first), Some(last)) = (slots.first(), slots.last()) else {
return;
};
let lines = shape.grid.outline(index);
let x0 = first.left - width(lines.left).div_toward_zero(2);
let x1 = last.right + width(lines.right).div_toward_zero(2);
if let Some(border) = opening {
self.border_rect(border, Point { x: x0, y: top }, x1 - x0, Direction::Across);
}
let closing = match end {
OutlineEnd::Row => None,
OutlineEnd::Table => Some((spacing, lines.bottom)),
OutlineEnd::Page(line) => Some((Length::ZERO, line)),
};
let mut end = bottom;
if let Some((gap, line)) = closing {
end += gap;
if let Some(border) = line {
self.border_rect(border, Point { x: x0, y: end }, x1 - x0, Direction::Across);
}
end += width(line);
}
for (border, x) in [(lines.left, first.left), (lines.right, last.right)] {
if let Some(border) = border {
let start = x - border.width.div_toward_zero(2);
self.border_rect(
border,
Point { x: start, y: top },
end - top,
Direction::Down,
);
}
}
}
pub(super) fn bottom_line(&mut self, slot: &Slot, y: Length) {
if let Some(border) = slot.borders.bottom {
for line in self.bottom_rects(slot, border, y) {
self.push_line(border, line);
}
}
}
pub(super) fn take_back_bottom_line(&mut self, slot: &Slot, y: Length) {
if let Some(border) = slot.borders.bottom {
for line in self.bottom_rects(slot, border, y) {
if let Some(at) = self.items.place_of_line(&Item::Rect(line)) {
self.items.take_out(at);
}
}
}
}
fn bottom_rects(&self, slot: &Slot, border: Border, y: Length) -> Vec<Rect> {
let (x0, x1) = Self::line_ends(slot);
let (left, length) = (self.device.snap(x0), self.device.snap(x1 - x0));
self.bottom_parts(border, y)
.into_iter()
.map(|part| {
line_rect(
border,
Point {
x: left,
y: part.start,
},
length,
part.thick,
)
})
.collect()
}
fn border_rect(&mut self, border: Border, start: Point, length: Length, direction: Direction) {
let device = self.device;
for (offset, thickness) in border.lines() {
let thick = device.table_line_thickness(thickness);
let line = match direction {
Direction::Down => {
let at = Point {
x: device.snap(start.x + offset),
y: device.snap(start.y),
};
line_rect(border, at, thick, device.snap(length))
}
Direction::Across => {
let at = Point {
x: device.snap(start.x),
y: device.snap(start.y + offset),
};
line_rect(border, at, device.snap(length), thick)
}
};
self.push_line(border, line);
}
}
pub(super) fn split_at_junctions(
&mut self,
from: usize,
above: &[Point],
part: &f_office_warnings::Name,
) -> Vec<Point> {
let items = self.items.placed(from..self.items.len());
let Some(lines) = drawn_lines(items, |at| self.items.line_dash(at)) else {
self.output.warnings.push(crate::Warning::LimitReached {
part: part.clone(),
limit: crate::warnings::Limit::LineRange,
});
return Vec::new();
};
let (horizontal, vertical): (Vec<_>, Vec<_>) = lines
.into_iter()
.partition(|line| Direction::of(line.edges) == Direction::Across);
let cell_cuts = decisions::cell_dash_cuts(&self.context.quirks, ())
.map_or_else(Vec::new, |()| cell_cuts(&horizontal, &vertical));
let horizontal = joined(horizontal);
let drawn = drawn_once(&vertical);
let squares = junctions(&horizontal, &drawn, above);
let order = SquareOrder::of(&squares);
let dashed_order = SquareOrder::of(&[squares.as_slice(), &cell_cuts].concat());
let held = self.items.count_before(from);
let mut pieces: Vec<(Edges<Length>, Rgb)> = Vec::new();
let mut whole = false;
for (lines, direction) in [(&horizontal, Direction::Across), (&drawn, Direction::Down)] {
for line in lines {
let order = if line.dash.is_some() && direction == Direction::Across {
&dashed_order
} else {
&order
};
for piece in cut(line.edges, order, direction) {
let (drawn, limited) =
drawn_piece(piece, line.dash, direction, held + pieces.len());
whole |= limited;
pieces.extend(drawn.into_iter().map(|b| (b, line.color)));
}
}
}
if whole {
self.output.warnings.push(crate::Warning::LimitReached {
part: part.clone(),
limit: crate::warnings::Limit::TableDashes,
});
}
for square in &squares {
pieces.extend(std::iter::repeat_n(
(square.edges, square.color),
square.count,
));
}
self.items.cut(from);
self.items
.extend_lines(pieces.into_iter().map(|(b, color)| {
Item::Rect(Rect {
x: b.left,
y: b.top,
width: b.width(),
height: b.height(),
color,
})
}));
vertical
.iter()
.map(|v| Point {
x: v.edges.left,
y: v.edges.bottom,
})
.collect()
}
fn push_line(&mut self, border: Border, line: Rect) {
let line = Item::Rect(line);
if !self.items.holds_line(&line) {
let dash = decisions::table_dash(&self.context.quirks, border.dash);
self.items.push_line(line, dash);
}
}
}
fn line_rect(border: Border, at: Point, width: Length, height: Length) -> Rect {
Rect {
x: at.x,
y: at.y,
width,
height,
color: border.color.drawn(),
}
}
fn centered(device: &Device, center: Length, thick: Length) -> Length {
around(device, device.snap(center), thick)
}
fn around(device: &Device, dot: Length, thick: Length) -> Length {
let dots = device.count(thick, Rounding::TowardZero);
dot - device.dots((dots + 1) / 2)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct LinePart {
pub(super) start: Length,
pub(super) thick: Length,
}
impl LinePart {
fn end(self) -> Length {
self.start + self.thick
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CellSide {
Left,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum LineEdge {
Inner,
Outer,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct SideLines {
left: Vec<LinePart>,
right: Vec<LinePart>,
fill: (Length, Length),
}
impl SideLines {
pub(super) fn of(device: &Device, slot: &Slot) -> Self {
let parts = |border: Option<Border>, x| {
border.map_or_else(Vec::new, |border| vertical_parts(device, border, x, slot))
};
let inset = |border: Option<Border>| {
width(border)
.div_toward_zero(2)
.down_to_whole(Length::UNITS_PER_TWIP)
};
let fill_end = |x, inset| center_dot(device, slot, line_place(slot, x) + inset);
Self {
left: parts(slot.borders.left, slot.left),
right: parts(slot.borders.right, slot.right),
fill: (
fill_end(slot.left, inset(slot.own_borders.left)),
fill_end(slot.right, -inset(slot.own_borders.right)),
),
}
}
pub(super) const fn fill(&self) -> (Length, Length) {
self.fill
}
pub(super) fn parts(&self, side: CellSide) -> &[LinePart] {
match side {
CellSide::Left => &self.left,
CellSide::Right => &self.right,
}
}
pub(super) fn edge(&self, side: CellSide, edge: LineEdge) -> Option<Length> {
let parts = self.parts(side).iter();
match (side, edge) {
(CellSide::Left, LineEdge::Inner) | (CellSide::Right, LineEdge::Outer) => {
parts.map(|part| part.end()).max()
}
(CellSide::Left, LineEdge::Outer) | (CellSide::Right, LineEdge::Inner) => {
parts.map(|part| part.start).min()
}
}
}
}
fn line_place(slot: &Slot, middle: Length) -> Length {
middle + slot.twip_rest - slot.rounding.unwrap_or(Length::ZERO)
}
fn center_dot(device: &Device, slot: &Slot, center: Length) -> Length {
match slot.halves_away_from {
Some(edge) if center < edge => device.snap_half_down(center),
_ => device.snap(center),
}
}
fn vertical_parts(device: &Device, border: Border, x: Length, slot: &Slot) -> Vec<LinePart> {
let left = x - border.width.div_toward_zero(2);
let start_of = |middle: Length, exact: Length, thick: Length| {
let around_center = || {
around(
device,
center_dot(device, slot, line_place(slot, middle)),
thick,
)
};
device
.centered_table_line(around_center)
.unwrap_or_else(|| match slot.rounding {
Some(rounding) if x != slot.edge => centered(device, middle - rounding, thick),
_ => device.snap(exact),
})
};
if let Some(parts) = device.whole_table_border(&border) {
let middle = left + border.width.div_toward_zero(2);
let whole: Length = parts.iter().copied().sum();
return whole_parts(start_of(middle, left, whole), &parts);
}
border
.lines()
.into_iter()
.map(|(offset, thickness)| {
let thick = device.table_line_thickness(thickness);
let middle = left + offset + thickness.div_toward_zero(2);
LinePart {
start: start_of(middle, left + offset, thick),
thick,
}
})
.collect()
}
fn whole_parts(start: Length, parts: &[Length]) -> Vec<LinePart> {
parts
.iter()
.scan(start, |at, thick| {
let line = LinePart {
start: *at,
thick: *thick,
};
*at += *thick;
Some(line)
})
.step_by(2)
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DrawnLine {
edges: Edges<Length>,
color: Rgb,
dash: Option<DashStyle>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Junction {
edges: Edges<Length>,
color: Rgb,
count: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
Across,
Down,
}
impl Direction {
fn of(b: Edges<Length>) -> Self {
if b.width() > b.height() {
Self::Across
} else {
Self::Down
}
}
}
fn drawn_lines<'i>(
items: impl Iterator<Item = (usize, &'i Item)>,
dash: impl Fn(usize) -> Option<DashStyle>,
) -> Option<Vec<DrawnLine>> {
items
.map(|(at, item)| match item {
Item::Rect(r) => Some(DrawnLine {
edges: Edges::placed(r.x, r.y, r.width, r.height)?,
color: r.color,
dash: dash(at),
}),
_ => None,
})
.collect()
}
fn joined(mut lines: Vec<DrawnLine>) -> Vec<DrawnLine> {
lines.sort_by_key(|line| (line.edges.top, line.edges.bottom, line.edges.left));
let mut out: Vec<DrawnLine> = Vec::new();
for line in lines {
let b = line.edges;
match out.last_mut() {
Some(last)
if (last.color, last.dash) == (line.color, line.dash)
&& (last.edges.top, last.edges.bottom) == (b.top, b.bottom)
&& b.left <= last.edges.right =>
{
last.edges.right = last.edges.right.max(b.right);
}
_ => out.push(line),
}
}
out
}
fn drawn_once(lines: &[DrawnLine]) -> Vec<DrawnLine> {
let mut out: Vec<DrawnLine> = Vec::new();
let mut alike: HashMap<_, Vec<usize>> = HashMap::new();
for &line in lines {
let b = line.edges;
let places = alike
.entry((b.left, b.right, line.color, line.dash))
.or_default();
let on = places
.iter()
.filter_map(|&at| out.get(at).map(|o| (at, o.edges)))
.find(|(_, o)| b.top < o.bottom && o.top < b.bottom);
if let Some(o) = on.and_then(|(at, _)| out.get_mut(at)) {
o.edges.top = o.edges.top.min(b.top);
o.edges.bottom = o.edges.bottom.max(b.bottom);
} else {
places.push(out.len());
out.push(line);
}
}
out
}
fn lift(
items: &mut PageItems,
from: usize,
parts: &[LinePart],
(y0, y1): (Length, Length),
) -> Vec<Item> {
let mut lifted = Vec::new();
for index in from..items.len() {
let Some(Item::Rect(r)) = items.item(index) else {
continue;
};
let (top, bottom) = (r.y, r.y + r.height);
if !parts.contains(&LinePart {
start: r.x,
thick: r.width,
}) || top >= y1
|| bottom <= y0
{
continue;
}
let cut = bottom.min(y1);
lifted.push(Item::Rect(Rect {
height: cut - top,
..r.clone()
}));
if cut < bottom {
if let Some(Item::Rect(r)) = items.item_mut(index) {
r.y = cut;
r.height = bottom - cut;
}
} else {
items.take_out(index);
}
}
lifted
}
fn cell_cuts(horizontal: &[DrawnLine], vertical: &[DrawnLine]) -> Vec<Junction> {
let mut lines: Vec<DrawnLine> = horizontal
.iter()
.copied()
.filter(|line| line.dash.is_some())
.collect();
lines.sort_by_key(|line| (line.edges.top, line.edges.bottom, line.edges.left));
lines
.windows(2)
.filter_map(|pair| {
let [before, after] = pair else {
return None;
};
let (a, b) = (before.edges, after.edges);
let thick = b.height();
let continues = (before.color, before.dash) == (after.color, after.dash)
&& (a.top, a.bottom) == (b.top, b.bottom)
&& a.left < b.left
&& b.left < a.right + thick;
let room = Edges {
right: b.left + thick,
..b
};
let crossed = vertical.iter().any(|v| {
let v = v.edges;
v.left < room.right
&& v.right > room.left - thick
&& v.top < room.bottom
&& v.bottom > room.top
});
(continues && !crossed).then_some(Junction {
edges: room,
color: after.color,
count: 0,
})
})
.collect()
}
fn junctions(horizontal: &[DrawnLine], vertical: &[DrawnLine], above: &[Point]) -> Vec<Junction> {
let mut squares: Vec<Junction> = Vec::new();
let mut seen = HashSet::new();
for line in horizontal {
let h = line.edges;
for v in vertical.iter().map(|line| line.edges) {
let j = Edges {
left: h.left.max(v.left),
top: h.top.max(v.top),
right: h.right.min(v.right),
bottom: h.bottom.min(v.bottom),
};
if j.right <= j.left
|| j.bottom <= j.top
|| !seen.insert((j.left, j.top, j.right, j.bottom))
{
continue;
}
let h_ends = j.left <= h.left || j.right >= h.right;
let runs_on = above.contains(&Point {
x: v.left,
y: v.top,
});
let v_ends = (j.top <= v.top && !runs_on) || j.bottom >= v.bottom;
let ends = usize::from(h_ends) + usize::from(v_ends);
squares.push(Junction {
edges: j,
color: line.color,
count: ends.max(1),
});
}
}
squares
}
struct SquareOrder {
down: Vec<Edges<Length>>,
across: Vec<Edges<Length>>,
height: Length,
width: Length,
}
impl SquareOrder {
fn of(squares: &[Junction]) -> Self {
let mut down: Vec<_> = squares.iter().map(|square| square.edges).collect();
let mut across = down.clone();
down.sort_unstable_by_key(|j| j.top);
across.sort_unstable_by_key(|j| j.left);
let most = |size: fn(Edges<Length>) -> Length| {
down.iter().copied().map(size).max().unwrap_or(Length::ZERO)
};
let (height, width) = (most(Edges::height), most(Edges::width));
Self {
down,
across,
height,
width,
}
}
fn near(&self, b: Edges<Length>, direction: Direction) -> &[Edges<Length>] {
let (order, size, start, end, first): (_, _, _, _, fn(&Edges<Length>) -> Length) =
match direction {
Direction::Across => (&self.down, self.height, b.top, b.bottom, |j| j.top),
Direction::Down => (&self.across, self.width, b.left, b.right, |j| j.left),
};
let from = order.partition_point(|j| first(j) + size <= start);
let to = order.partition_point(|j| first(j) < end);
order.get(from..to.max(from)).unwrap_or_default()
}
}
fn cut(b: Edges<Length>, squares: &SquareOrder, direction: Direction) -> Vec<Edges<Length>> {
let mut gaps: Vec<(Length, Length)> = squares
.near(b, direction)
.iter()
.copied()
.filter(|j| j.left < b.right && j.right > b.left && j.top < b.bottom && j.bottom > b.top)
.map(|j| span(j, direction))
.collect();
gaps.sort_unstable();
let (start, end) = span(b, direction);
let mut spans = Vec::new();
let mut at = start;
for (g0, g1) in gaps {
if g0 > at {
spans.push((at, g0.min(end)));
}
at = at.max(g1);
}
if at < end {
spans.push((at, end));
}
spans
.into_iter()
.map(|span| along(b, span, direction))
.collect()
}
fn span(b: Edges<Length>, direction: Direction) -> (Length, Length) {
match direction {
Direction::Across => (b.left, b.right),
Direction::Down => (b.top, b.bottom),
}
}
fn along(b: Edges<Length>, (a, z): (Length, Length), direction: Direction) -> Edges<Length> {
match direction {
Direction::Across => Edges {
left: a,
right: z,
..b
},
Direction::Down => Edges {
top: a,
bottom: z,
..b
},
}
}
fn drawn_piece(
b: Edges<Length>,
dash: Option<DashStyle>,
direction: Direction,
held: usize,
) -> (Vec<Edges<Length>>, bool) {
match dash {
Some(dash)
if held.saturating_add(dash_count(b, dash, direction)) <= MAX_DASHED_PAGE_ITEMS =>
{
(dashes(b, dash, direction), false)
}
Some(_) => (vec![b], true),
None => (vec![b], false),
}
}
fn along_and_across(b: Edges<Length>, direction: Direction) -> (Length, Length, Length) {
let (start, end) = span(b, direction);
let width = match direction {
Direction::Across => b.height(),
Direction::Down => b.width(),
};
(start, end, width)
}
fn dash_count(b: Edges<Length>, dash: DashStyle, direction: Direction) -> usize {
let (start, end, width) = along_and_across(b, direction);
let pattern = dash.pattern();
let widths: i64 = pattern.iter().sum();
let repeat = width.units().saturating_mul(widths);
if repeat <= 0 {
return 1;
}
let repeats = (end - start).units().max(0) / repeat + 1;
usize::try_from(repeats)
.unwrap_or(usize::MAX)
.saturating_mul(pattern.len().div_ceil(2))
}
fn dashes(b: Edges<Length>, dash: DashStyle, direction: Direction) -> Vec<Edges<Length>> {
let (start, end, width) = along_and_across(b, direction);
if width <= Length::ZERO {
return vec![b];
}
let mut out = Vec::new();
let mut at = start;
for (index, widths) in dash.pattern().iter().cycle().enumerate() {
if at >= end {
break;
}
let next = at + width * *widths;
if index % 2 == 0 {
out.push(along(b, (at, next.min(end)), direction));
}
at = next;
}
out
}
#[cfg(test)]
mod tests;