use std::cmp::Reverse;
use std::iter::Peekable;
use std::ops::Range;
use std::vec;
use f_office_paint::{Group, GroupClip, Item};
use f_office_units::{Edges, Length};
use super::borders::{CellSide, LineEdge, RowTop};
use super::merges::Open;
use super::{Shape, Slot};
use crate::layout::{Layout, decisions};
fn group_clip(rect: Edges<Length>) -> GroupClip {
let (left, right) = (rect.left.min(rect.right), rect.left.max(rect.right));
let height = (rect.bottom - rect.top).max(Length::ZERO);
GroupClip::rect(left, rect.top, right - left, height)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RegionClip {
page: usize,
rect: Edges<Length>,
}
impl Layout<'_> {
pub(super) fn clip_row(
&mut self,
(shape, index): (&Shape, usize),
(slots, laid): (&[Slot], &[(Range<usize>, Length)]),
(top, inner, bottom): (RowTop, Length, Length),
closed: &[Open],
) {
let Some(slots) = decisions::clipped_cells(&self.context.quirks, slots) else {
return;
};
for (slot, (items, _)) in slots.iter().zip(laid) {
if !clipped(slot) || slot.merged_above() || slot.merged_below {
continue;
}
let rect = Edges {
bottom: self.clip_bottom((shape, index), slot, bottom),
..self.clip_sides(slot, (top, inner))
};
self.items.clip_cell(items.clone(), rect);
}
let page = self.output.pages.len();
for open in closed {
let Some(clip) = open.clip.filter(|clip| clip.page == page) else {
continue;
};
let last = slots
.iter()
.find(|slot| slot.first == open.first && slot.merged_above());
if let Some(slot) = last {
let rect = Edges {
bottom: self.clip_bottom((shape, index), slot, bottom),
..clip.rect
};
self.items.clip_cell(open.items.clone(), rect);
}
}
}
pub(super) fn region_clip(
&self,
slot: &Slot,
(top, inner): (RowTop, Length),
) -> Option<RegionClip> {
decisions::clipped_cells(&self.context.quirks, slot)
.filter(|slot| clipped(slot))
.map(|slot| RegionClip {
page: self.output.pages.len(),
rect: self.clip_sides(slot, (top, inner)),
})
}
fn clip_sides(&self, slot: &Slot, (top, inner): (RowTop, Length)) -> Edges<Length> {
let left = slot.sides.edge(CellSide::Left, LineEdge::Inner);
let right = slot.sides.edge(CellSide::Right, LineEdge::Inner);
let line = (slot.borders.top).map_or(top.at, |border| self.top_line_end(border, top));
Edges {
left: left.unwrap_or(slot.left),
top: if slot.margins.top > Length::ZERO {
inner + slot.margins.top
} else {
line
},
right: right.unwrap_or(slot.right),
bottom: line,
}
}
fn clip_bottom(&self, (shape, index): (&Shape, usize), slot: &Slot, bottom: Length) -> Length {
let Some(border) = slot.borders.bottom else {
return bottom;
};
let last = index + 1 == shape.grid.table.rows.len();
let drawn = (last || shape.grid.open_below(index, slot)).then(|| {
self.bottom_parts(border, bottom)
.into_iter()
.map(|part| part.start)
.min()
});
drawn.flatten().unwrap_or_else(|| self.device.snap(bottom))
}
}
fn clipped(slot: &Slot) -> bool {
slot.upright() && slot.gaps.is_none()
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Cell {
items: Range<usize>,
rect: Edges<Length>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct CellClips {
cells: Vec<Cell>,
drawings: Vec<CellDrawing>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CellDrawing {
items: Range<usize>,
front: bool,
}
impl CellClips {
pub(in crate::layout) const fn new() -> Self {
Self {
cells: Vec::new(),
drawings: Vec::new(),
}
}
pub(in crate::layout) const fn count(&self) -> usize {
self.cells.len()
}
pub(in crate::layout) fn truncate(&mut self, count: usize) {
self.cells.truncate(count);
}
pub(in crate::layout) fn push(&mut self, items: Range<usize>, rect: Edges<Length>) {
if !items.is_empty() {
self.cells.push(Cell { items, rect });
}
}
pub(in crate::layout) fn drawing(&mut self, items: Range<usize>, front: bool) {
if !items.is_empty() {
self.drawings.push(CellDrawing { items, front });
}
}
pub(in crate::layout) fn cut(&mut self, len: usize) {
self.cells.retain(|cell| cell.items.end <= len);
self.drawings.retain(|drawing| drawing.items.end <= len);
}
pub(in crate::layout) fn moved(&mut self, range: &Range<usize>, dy: Length) {
for cell in &mut self.cells {
if range.start <= cell.items.start && cell.items.end <= range.end {
cell.rect.top += dy;
cell.rect.bottom += dy;
}
}
}
pub(in crate::layout) fn apply(&mut self, items: Vec<Item>, starts: &[usize]) -> Vec<Item> {
let (cells, drawings) = self.walk_order(starts);
let mut walk = Walk {
out: Vec::with_capacity(items.len()),
open: Vec::new(),
cells: cells.into_iter().peekable(),
drawings: drawings.into_iter().peekable(),
alone_to: 0,
lifted: false,
front: Vec::new(),
};
for (at, item) in items.into_iter().enumerate() {
walk.reach(at);
walk.take(at, item);
}
while !walk.open.is_empty() {
walk.close();
}
walk.out.append(&mut walk.front);
walk.out
}
fn walk_order(&mut self, starts: &[usize]) -> (Vec<Cell>, Vec<CellDrawing>) {
let among =
|places: &Range<usize>| Some(*starts.get(places.start)?..*starts.get(places.end)?);
let mut cells: Vec<(usize, Cell)> = std::mem::take(&mut self.cells)
.into_iter()
.enumerate()
.filter_map(|(order, cell)| {
let items = among(&cell.items).filter(|items| !items.is_empty())?;
Some((
order,
Cell {
items,
rect: cell.rect,
},
))
})
.collect();
cells.sort_by_key(|(order, cell)| {
(cell.items.start, Reverse(cell.items.end), Reverse(*order))
});
let mut drawings: Vec<CellDrawing> = std::mem::take(&mut self.drawings)
.into_iter()
.filter_map(|drawing| {
Some(CellDrawing {
items: among(&drawing.items).filter(|items| !items.is_empty())?,
front: drawing.front,
})
})
.collect();
drawings.sort_by_key(|drawing| drawing.items.start);
(cells.into_iter().map(|(_, cell)| cell).collect(), drawings)
}
}
struct OpenCell {
end: usize,
rect: Edges<Length>,
run: Vec<Item>,
}
impl OpenCell {
fn group(&mut self) -> Option<Item> {
(!self.run.is_empty()).then(|| {
Item::Group(Group::of_cell(
std::mem::take(&mut self.run),
group_clip(self.rect),
))
})
}
}
struct Walk {
out: Vec<Item>,
open: Vec<OpenCell>,
cells: Peekable<vec::IntoIter<Cell>>,
drawings: Peekable<vec::IntoIter<CellDrawing>>,
alone_to: usize,
lifted: bool,
front: Vec<Item>,
}
impl Walk {
fn reach(&mut self, at: usize) {
while self.open.last().is_some_and(|cell| cell.end <= at) {
self.close();
}
while let Some(cell) = self.cells.next_if(|cell| cell.items.start <= at) {
self.open.push(OpenCell {
end: cell.items.end,
rect: cell.rect,
run: Vec::new(),
});
}
while self
.drawings
.next_if(|drawing| drawing.items.start < at)
.is_some()
{}
}
fn take(&mut self, at: usize, item: Item) {
if at >= self.alone_to {
let innermost_end = self.open.last().map(|cell| cell.end);
let drawing = self.drawings.next_if(|drawing| {
drawing.items.start == at
&& (drawing.front || innermost_end.is_some_and(|end| drawing.items.end <= end))
});
if let Some(drawing) = drawing {
(self.alone_to, self.lifted) = (drawing.items.end, drawing.front);
} else if matches!(item, Item::Image(_)) {
self.lifted = false;
} else {
self.push(item);
return;
}
}
self.stand_alone(item);
}
fn stand_alone(&mut self, item: Item) {
if self.lifted {
self.front.push(item);
} else {
self.close_runs();
self.out.push(item);
}
}
fn push(&mut self, item: Item) {
match self.open.last_mut() {
Some(cell) => cell.run.push(item),
None => self.out.push(item),
}
}
fn close(&mut self) {
if let Some(group) = self.open.pop().and_then(|mut cell| cell.group()) {
self.push(group);
}
}
fn close_runs(&mut self) {
let mut inner = None;
for cell in self.open.iter_mut().rev() {
cell.run.extend(inner.take());
inner = cell.group();
}
self.out.extend(inner);
}
}
#[cfg(test)]
mod tests {
use f_office_paint::{Group, Image, ImageItem, Item, Rect, Rgb};
use f_office_units::{Edges, Length};
use super::{CellClips, group_clip};
fn fill(y: i64) -> Item {
Item::Rect(Rect {
x: Length::ZERO,
y: Length::from_units(y),
width: Length::from_units(1),
height: Length::from_units(1),
color: Rgb::BLACK,
})
}
fn rect(top: i64) -> Edges<Length> {
Edges {
left: Length::ZERO,
top: Length::from_units(top),
right: Length::from_units(10),
bottom: Length::from_units(top + 10),
}
}
fn picture(y: i64) -> Item {
Item::Image(ImageItem {
x: Length::ZERO,
y: Length::from_units(y),
width: Length::from_units(1),
height: Length::from_units(1),
clip: None,
turn: None,
image: Image::new(Vec::new()),
})
}
fn shape(items: &[Item]) -> String {
items
.iter()
.map(|item| match item {
Item::Rect(r) => r.y.units().to_string(),
Item::Image(i) => format!("p{}", i.y.units()),
Item::Group(g) => format!("[{}]", shape(&g.items)),
_ => "?".to_string(),
})
.collect::<Vec<_>>()
.join(" ")
}
#[test]
fn groups_each_cell_with_its_nested_cells_inside_and_leaves_its_drawings_out() {
let items: Vec<Item> = (0..10).map(fill).collect();
let mut clips = CellClips::new();
clips.push(3..5, rect(3));
clips.drawing(6..7, false);
clips.push(1..9, rect(1));
clips.push(9..10, rect(9));
let starts: Vec<usize> = (0..=items.len()).collect();
let items = clips.apply(items, &starts);
assert_eq!(shape(&items), "0 [1 2 [3 4] 5] 6 [7 8] [9]");
assert_eq!(clips, CellClips::new());
}
#[test]
fn leaves_the_pictures_of_a_cell_out_of_its_group() {
let items: Vec<Item> = vec![fill(0), fill(1), picture(2), fill(3), picture(4)];
let mut clips = CellClips::new();
clips.push(1..3, rect(1));
clips.push(0..5, rect(0));
let starts: Vec<usize> = (0..=items.len()).collect();
let items = clips.apply(items, &starts);
assert_eq!(shape(&items), "[0 [1]] p2 [3] p4");
}
fn two_cells() -> CellClips {
let mut clips = CellClips::new();
clips.push(4..6, rect(0));
clips.push(7..10, rect(0));
clips.drawing(7..8, false);
clips
}
#[test]
fn moves_the_clip_of_a_cell_whose_items_move() {
let mut clips = two_cells();
clips.moved(&(0..6), Length::from_units(5));
let rects: Vec<_> = clips.cells.iter().map(|cell| cell.rect).collect();
assert_eq!(rects, [rect(5), rect(0)]);
}
#[test]
fn groups_the_items_of_the_entries_at_a_cell_s_places() {
let items: Vec<Item> = (0..4).map(fill).collect();
let starts = [0, 1, 3, 3, 4];
let mut clips = CellClips::new();
clips.push(1..3, rect(1));
clips.push(3..4, rect(3));
let items = clips.apply(items, &starts);
assert_eq!(shape(&items), "0 [1 2] [3]");
}
#[test]
fn nests_the_earlier_of_two_cells_with_one_range_in_the_later() {
let items: Vec<Item> = (0..2).map(fill).collect();
let mut clips = CellClips::new();
clips.push(0..2, rect(0));
clips.push(0..2, rect(5));
let starts: Vec<usize> = (0..=items.len()).collect();
let inner = Item::Group(Group::of_cell(items.clone(), group_clip(rect(0))));
let outer = Item::Group(Group::of_cell(vec![inner], group_clip(rect(5))));
assert_eq!(clips.apply(items, &starts), [outer]);
}
#[test]
fn leaves_a_drawing_at_a_cell_s_first_item_out_of_its_group() {
let items: Vec<Item> = (0..4).map(fill).collect();
let mut clips = CellClips::new();
clips.push(1..4, rect(1));
clips.drawing(1..3, false);
let starts: Vec<usize> = (0..=items.len()).collect();
assert_eq!(shape(&clips.apply(items, &starts)), "0 1 2 [3]");
}
#[test]
fn puts_a_drawing_in_front_of_the_text_of_a_cell_after_all_the_page_s_items() {
let items: Vec<Item> = (0..7).map(fill).collect();
let mut clips = CellClips::new();
clips.push(1..5, rect(1));
clips.drawing(2..4, true);
clips.push(5..7, rect(5));
let starts: Vec<usize> = (0..=items.len()).collect();
assert_eq!(shape(&clips.apply(items, &starts)), "0 [1 4] [5 6] 2 3");
}
#[test]
fn puts_a_drawing_in_front_of_the_text_last_without_a_cell_clip() {
let items: Vec<Item> = (0..6).map(fill).collect();
let mut clips = CellClips::new();
clips.drawing(1..3, true);
clips.drawing(4..5, false);
let starts: Vec<usize> = (0..=items.len()).collect();
assert_eq!(shape(&clips.apply(items, &starts)), "0 3 4 5 1 2");
}
#[test]
fn leaves_out_a_drawing_without_items() {
let items: Vec<Item> = (0..4).map(fill).collect();
let mut clips = CellClips::new();
clips.push(0..5, rect(0));
clips.drawing(2..3, false);
let starts = [0, 1, 2, 2, 3, 4];
assert_eq!(shape(&clips.apply(items, &starts)), "[0 1 2 3]");
}
#[test]
fn follows_cuts_of_the_items_and_of_a_row_s_trial() {
let mut clips = two_cells();
clips.cut(9);
assert_eq!((clips.count(), clips.drawings.len()), (1, 1));
clips.truncate(0);
assert_eq!(clips.count(), 0);
}
}