use std::collections::HashMap;
use f_office_paint::{Item, Point, Rect, Rgb};
use f_office_units::scale::{LINE, TENTHS};
use f_office_units::{Length, div_round};
use super::Layout;
use crate::body::{Block, Content, Run, RunRecord};
use crate::comments::Comments;
use crate::grid::{DOT, Device};
use crate::lines::CommentIndex;
use crate::props::{FontRef, LineSpacing, RunProps};
use crate::params::{
BALLOON_BOTTOM, BALLOON_PADDING, BALLOON_SIZE, BALLOON_START, BALLOON_TOP, BALLOON_WIDTH,
MARKUP_GRAY_START as GRAY_START, MARKUP_PAPER_MARGIN as PAPER_MARGIN, MARKUP_REACH,
MARKUP_SCALE_STEPS as STEPS, MARKUP_TOP_OFFSET as TOP_OFFSET_TENTHS, MARKUP_X_PIVOT as X_PIVOT,
};
const BALLOON_STYLE: &str = "BalloonText";
const GRAY: Rgb = rgb(crate::params::MARKUP_GRAY);
const BALLOON_FILL: Rgb = rgb(crate::params::BALLOON_FILL);
const BALLOON_LINE: Rgb = rgb(crate::params::BALLOON_LINE);
const fn rgb([r, g, b]: [u8; 3]) -> Rgb {
Rgb { r, g, b }
}
const fn dots(dots: i64) -> Length {
Length::from_units(dots * DOT)
}
#[derive(Clone, Debug)]
pub(super) struct CommentMarkup<'a> {
comments: &'a Comments,
numbers: Vec<String>,
places: HashMap<String, CommentIndex>,
anchors: Vec<Anchor>,
cells: Vec<CellAnchor>,
}
#[derive(Clone, Debug)]
pub(super) struct MarkupMark {
numbers: usize,
anchors: Vec<Anchor>,
cells: Vec<CellAnchor>,
}
impl CommentMarkup<'_> {
pub(super) fn mark(&self) -> MarkupMark {
MarkupMark {
numbers: self.numbers.len(),
anchors: self.anchors.clone(),
cells: self.cells.clone(),
}
}
pub(super) fn rewind(&mut self, mark: &MarkupMark) {
while self.numbers.len() > mark.numbers {
if let Some(id) = self.numbers.pop() {
self.places.remove(&id);
}
}
self.anchors.clone_from(&mark.anchors);
self.cells.clone_from(&mark.cells);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CellAnchor {
id: String,
color: Rgb,
page: usize,
top: Length,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Anchor {
index: CommentIndex,
page: usize,
top: Length,
}
impl<'a> CommentMarkup<'a> {
pub(super) fn new(comments: &'a Comments) -> Self {
Self {
comments,
numbers: Vec::new(),
places: HashMap::new(),
anchors: Vec::new(),
cells: Vec::new(),
}
}
pub(super) fn index(&mut self, id: &str) -> Option<CommentIndex> {
if !self.comments.by_id.contains_key(id) {
return None;
}
if let Some(&index) = self.places.get(id) {
return Some(index);
}
let index = CommentIndex::new(self.numbers.len());
self.numbers.push(id.to_owned());
self.places.insert(id.to_owned(), index);
Some(index)
}
fn labels(&self) -> Vec<String> {
let mut tops: HashMap<&str, usize> = HashMap::new();
let mut replies: HashMap<&str, usize> = HashMap::new();
self.numbers
.iter()
.map(|id| {
if let Some(parent) = self.parent_of(id) {
let place = replies.entry(parent).or_insert(1);
*place += 1;
format!("{}R{place}", tops.get(parent).copied().unwrap_or(0))
} else {
let number = tops.len() + 1;
tops.insert(id, number);
number.to_string()
}
})
.collect()
}
fn shows_a_balloon(&self) -> bool {
self.comments.deleted_cells
|| self.anchors.iter().any(|anchor| {
self.numbers
.get(anchor.index.get())
.and_then(|id| self.comments.by_id.get(id))
.is_some_and(|comment| !comment.hidden)
})
}
fn parent_of(&self, id: &str) -> Option<&str> {
let parent = self.comments.by_id.get(id)?.parent.as_deref()?;
let place = |id: &str| self.places.get(id).copied();
(place(parent)? < place(id)?).then_some(parent)
}
fn anchor(&mut self, anchor: Anchor) {
match self.anchors.iter_mut().find(|a| a.index == anchor.index) {
Some(old) => *old = anchor,
None => self.anchors.push(anchor),
}
}
fn cell_anchor(&mut self, anchor: CellAnchor) {
match self.cells.iter_mut().find(|a| a.id == anchor.id) {
Some(old) => *old = anchor,
None => self.cells.push(anchor),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Transform {
steps: i64,
x0: Length,
y0: Length,
}
impl Transform {
fn of(device: &Device, (width, height): (Length, Length), right: Length) -> Self {
let (width, height) = (device.snap(width), device.snap(height));
let fit = (
i128::from((width - dots(PAPER_MARGIN)).units()),
i128::from((right + dots(MARKUP_REACH)).units()).max(1),
);
let steps = i64::try_from(i128::from(STEPS) * fit.0 / fit.1).unwrap_or(STEPS);
let h = i128::from(height.units());
let tenths = i128::from(TENTHS);
let numerator =
h * (fit.1 - fit.0) * tenths + i128::from(TOP_OFFSET_TENTHS * DOT) * 2 * fit.1;
let top = i64::try_from(numerator / (2 * tenths * fit.1)).unwrap_or(0);
Self {
steps,
x0: dots(div_round(X_PIVOT * (STEPS - steps), STEPS)),
y0: device.snap(Length::from_units(top)),
}
}
fn x(self, v: Length) -> Length {
self.x0 + self.len(v)
}
fn y(self, v: Length) -> Length {
self.y0 + self.len(v)
}
fn len(self, v: Length) -> Length {
(v * self.steps).div_round(STEPS)
}
fn point(self, p: Point) -> Point {
Point {
x: self.x(p.x),
y: self.y(p.y),
}
}
fn item(self, mut item: Item) -> Item {
item.map_places(|p| self.point(p), |v| self.len(v));
item
}
}
const fn fill((x, y, width, height): (Length, Length, Length, Length), color: Rgb) -> Item {
Item::Rect(Rect {
x,
y,
width,
height,
color,
})
}
impl Layout<'_> {
pub(super) fn note_comments(&mut self, line: &crate::lines::Line, top: Length) {
let page = self.output.pages.len();
for placed in &line.placed {
if let crate::lines::Piece::Comment(index) = placed.piece {
self.comment_markup.anchor(Anchor { index, page, top });
}
}
}
pub(super) fn note_deleted_cell(&mut self, deletion: &crate::table::CellDeletion, top: Length) {
let [r, g, b] = crate::body::author_color(&deletion.author);
self.comment_markup.cell_anchor(CellAnchor {
id: deletion.id.clone(),
color: Rgb { r, g, b },
page: self.output.pages.len(),
top,
});
}
pub(super) fn print_markup(&mut self) {
if !self.comment_markup.shows_a_balloon() {
return;
}
let labels = self.comment_markup.labels();
let sizes: Vec<(Length, Length)> = self
.output
.pages
.iter()
.map(|page| (page.width(), page.height()))
.collect();
let mut fronts = Vec::with_capacity(sizes.len());
for (index, (width, height)) in sizes.into_iter().enumerate() {
let section = self.section_of(self.page_info(index).section);
let (width, height) = (self.device.snap(width), self.device.snap(height));
let right = self.device.snap(width - section.right);
let t = Transform::of(&self.device, (width, height), right);
let gray = (
right + dots(GRAY_START),
Length::ZERO,
dots(MARKUP_REACH - GRAY_START),
height,
);
let mut items = vec![fill(gray, GRAY)];
items.extend(self.balloons(index, right, §ion, &labels));
fronts.push((items, t));
for line in self
.output
.placed
.iter_mut()
.filter(|line| line.page == index)
{
line.markup_scale = Some(t.steps);
if let Some(turn) = &mut line.text.turn {
turn.to = (t.x(turn.to.0), t.y(turn.to.1));
continue;
}
let top = t.y(line.top);
let base = t.y(line.top + line.baseline);
(line.top, line.baseline) = (top, base - top);
}
}
let pages = std::mem::take(&mut self.output.pages);
self.output.pages = pages
.into_iter()
.zip(fronts)
.map(|(page, (mut items, t))| {
page.map_items(|body| {
items.extend(body);
items.into_iter().map(|item| t.item(item)).collect()
})
})
.collect();
}
fn balloons(
&mut self,
page: usize,
right: Length,
section: &crate::body::Section,
labels: &[String],
) -> Vec<Item> {
let comments = self
.comment_markup
.anchors
.iter()
.filter(|a| a.page == page)
.filter_map(|a| {
Some((
a.top,
self.balloon_text(a.index, labels)?,
BALLOON_FILL,
BALLOON_LINE,
))
});
let cells = self
.comment_markup
.cells
.iter()
.filter(|a| a.page == page)
.map(|a| (a.top, self.cell_balloon_text(), Rgb::WHITE, a.color));
let mut balloons: Vec<_> = comments.chain(cells).collect();
balloons.sort_by_key(|b| b.0);
let mut items = Vec::new();
let mut bottom = None;
let left = right + dots(BALLOON_START);
for (anchor, blocks, color, line) in balloons {
let top = bottom.map_or(anchor, |bottom| anchor.max(bottom));
let inside = top + dots(BALLOON_TOP);
let column = balloon_column(section, left);
let (text, end) = self.story_in(&column, &blocks, inside, BALLOON);
let end = end + dots(BALLOON_BOTTOM);
let balloon = (left, top, dots(BALLOON_WIDTH), end - top);
items.push(fill(balloon, color));
items.extend(outline(&self.device, balloon, line));
items.extend(text);
bottom = Some(end);
}
items
}
fn balloon_text(&self, index: CommentIndex, labels: &[String]) -> Option<Vec<Block>> {
let id = self.comment_markup.numbers.get(index.get())?;
let comment = self
.comment_markup
.comments
.by_id
.get(id)
.filter(|c| !c.hidden)?;
let props = self.label_props();
let blocks = balloon_blocks(&comment.blocks, props.size.unwrap_or(BALLOON_SIZE));
let label = format!(
"Commented [{}{}]: ",
comment.initials,
labels.get(index.get()).map_or("", String::as_str)
);
let run = Run {
style: None,
props,
content: vec![Content::Text(label)],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
};
let mut blocks = blocks;
let first = blocks.iter_mut().find_map(|b| match b {
Block::Paragraph(p) => Some(p),
Block::Table(_) => None,
})?;
first.runs.insert(0, run);
Some(blocks)
}
fn label_props(&self) -> RunProps {
let style = self
.styles
.has(BALLOON_STYLE)
.then(|| self.styles.paragraph(Some(BALLOON_STYLE), None).1);
let size = style.as_ref().and_then(|s| s.size).unwrap_or(BALLOON_SIZE);
let times = Some(FontRef::Name("Times New Roman".to_owned()));
let (font_ascii, font_hansi) = match style {
Some(s) => (
s.font_ascii.or_else(|| times.clone()),
s.font_hansi.or(times),
),
None => (times.clone(), times),
};
RunProps {
font_ascii,
font_hansi,
bold: Some(true),
size: Some(size),
..RunProps::default()
}
}
fn cell_balloon_text(&self) -> Vec<Block> {
let props = self.label_props();
let size = props.size.unwrap_or(BALLOON_SIZE);
let paragraph = Block::Paragraph(crate::body::Paragraph {
id: self.context.deleted_cell_label,
props: crate::props::ParaProps {
before: Some(Length::ZERO),
..crate::props::ParaProps::default()
},
runs: vec![Run {
style: None,
props,
content: vec![Content::Text("Deleted Cells".to_owned())],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}],
source: crate::source_span::SourceSpan::NONE,
});
balloon_blocks(&[paragraph], size)
}
}
fn balloon_blocks(comment: &[Block], size: i64) -> Vec<Block> {
let mut blocks = comment.to_vec();
let has_text = blocks.iter().any(|block| match block {
Block::Paragraph(paragraph) => paragraph
.runs
.iter()
.flat_map(|run| &run.content)
.any(|content| matches!(content, Content::Text(text) if !text.is_empty())),
Block::Table(_) => true,
});
for block in &mut blocks {
if let Block::Paragraph(paragraph) = block {
paragraph.props.line = Some(LineSpacing::Auto(LINE));
paragraph.props.after = Some(Length::ZERO);
paragraph.props.after_auto = Some(false);
paragraph.props.mark.size = Some(size);
paragraph.props.mark.size_cs = Some(size);
for run in &mut paragraph.runs {
run.props.size = Some(size);
run.props.size_cs = Some(size);
if has_text {
run.content
.retain(|content| *content != Content::CommentMark);
}
}
}
}
blocks
}
fn balloon_column(section: &crate::body::Section, left: Length) -> crate::body::Section {
let mut column = *section;
column.left = left + dots(BALLOON_PADDING);
column.right = Length::ZERO;
column.width = left + dots(BALLOON_WIDTH - BALLOON_PADDING);
column.columns = crate::body::Columns {
count: 1,
space: Length::ZERO,
widths: None,
separator: false,
};
column
}
const BALLOON: super::Story = super::Story {
kind: super::StoryKind::Balloon,
numbers: super::StoryNumbers::PAGE_ONE,
};
fn outline(
device: &Device,
(x, y, width, height): (Length, Length, Length, Length),
color: Rgb,
) -> Vec<Item> {
let line = device.dots(1);
vec![
fill((x, y, width, line), color),
fill((x, y + height - line, width, line), color),
fill((x, y, line, height), color),
fill((x + width - line, y, line, height), color),
]
}
#[cfg(test)]
mod tests {
use super::{Anchor, CellAnchor, CommentMarkup, Transform, balloon_blocks};
use crate::body::{Block, Content, Paragraph, Run, RunRecord};
use crate::comments::{Comment, Comments};
use crate::grid::DOT;
use crate::lines::CommentIndex;
use crate::props::{LineSpacing, RunProps};
use f_office_paint::Rgb;
use f_office_units::Length;
use f_office_units::scale::LINE;
const TWIP: i64 = 1_270;
fn transform(width: i64, height: i64, right: i64) -> (i64, i64, i64) {
let twips = |n: i64| Length::from_units(n * TWIP);
let t = Transform::of(
&crate::grid::base_device(),
(twips(width), twips(height)),
twips(width - right),
);
(t.steps, t.x0.units() / DOT, t.y0.units() / DOT)
}
#[test]
fn fits_the_page_and_the_markup_area_into_the_paper() {
assert_eq!(transform(12_240, 15_840, 1_440), (224, 4, 416));
assert_eq!(transform(12_240, 15_840, 1_080), (219, 4, 443));
assert_eq!(transform(12_240, 15_840, 1_800), (229, 4, 388));
assert_eq!(transform(11_906, 16_838, 1_440), (223, 4, 452));
assert_eq!(transform(16_838, 11_906, 1_440).0, 241);
assert_eq!(transform(16_838, 11_906, 1_440).1, 3);
}
#[test]
fn takes_back_the_numbers_and_places_that_a_trial_gave() {
let by_id = ["a", "b"]
.into_iter()
.map(|id| (id.to_owned(), Comment::default()))
.collect();
let comments = Comments {
by_id,
deleted_cells: false,
};
let mut markup = CommentMarkup::new(&comments);
let first = markup.index("a");
markup.anchor(Anchor {
index: first.unwrap(),
page: 0,
top: Length::ZERO,
});
let mark = markup.mark();
markup.index("b");
markup.anchor(Anchor {
index: first.unwrap(),
page: 1,
top: Length::ZERO,
});
markup.rewind(&mark);
assert_eq!(markup.labels(), ["1"]);
assert_eq!(markup.anchors.first().map(|anchor| anchor.page), Some(0));
assert_eq!(markup.index("b"), Some(CommentIndex::new(1)));
}
#[test]
fn takes_back_at_a_row_mark_the_comments_that_a_row_trial_numbered_and_placed() {
crate::layout::testing::with_layout(|layout| {
let mark = layout.row_mark();
layout.comment_markup.numbers.push("a".to_owned());
let index = CommentIndex::new(0);
layout.comment_markup.places.insert("a".to_owned(), index);
layout.comment_markup.anchor(Anchor {
index,
page: 0,
top: Length::ZERO,
});
layout.back_to_row_mark(&mark);
assert_eq!(layout.comment_markup.numbers, Vec::<String>::new());
assert!(layout.comment_markup.places.is_empty());
assert_eq!(layout.comment_markup.anchors, Vec::new());
});
}
#[test]
fn numbers_replies_after_the_comments_that_they_answer() {
let comment = |parent: Option<&str>| Comment {
parent: parent.map(str::to_owned),
..Comment::default()
};
let by_id = [
("a", comment(None)),
("b", comment(None)),
("c", comment(Some("b"))),
("d", comment(Some("b"))),
("e", comment(None)),
("f", comment(Some("g"))),
("g", comment(None)),
]
.into_iter()
.map(|(id, c)| (id.to_owned(), c))
.collect();
let comments = Comments {
by_id,
deleted_cells: false,
};
let mut markup = CommentMarkup::new(&comments);
for id in ["a", "b", "c", "d", "e", "f", "g", "missing"] {
markup.index(id);
}
assert_eq!(markup.labels(), ["1", "2", "2R2", "2R3", "3", "4", "5"]);
assert_eq!(markup.index("missing"), None);
}
#[test]
fn keeps_the_reference_mark_only_in_a_comment_without_text() {
let paragraph = |content: Vec<Content>| {
Block::Paragraph(Paragraph {
runs: vec![Run {
style: None,
props: RunProps::default(),
content,
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}],
..Paragraph::empty()
})
};
let marks = |blocks: &[Block]| -> usize {
blocks
.iter()
.filter_map(|b| match b {
Block::Paragraph(p) => Some(p),
Block::Table(_) => None,
})
.flat_map(|p| &p.runs)
.flat_map(|r| &r.content)
.filter(|c| **c == Content::CommentMark)
.count()
};
let size = crate::params::BALLOON_SIZE;
let empty = balloon_blocks(&[paragraph(vec![Content::CommentMark])], size);
assert_eq!(marks(&empty), 1);
let text = vec![Content::CommentMark, Content::Text("a".to_owned())];
let with_text = balloon_blocks(&[paragraph(text)], size);
assert_eq!(marks(&with_text), 0);
let Some(Block::Paragraph(p)) = with_text.first() else {
panic!("a paragraph");
};
assert_eq!(p.props.line, Some(LineSpacing::Auto(LINE)));
assert_eq!(p.props.after, Some(Length::ZERO));
assert_eq!(p.runs.first().and_then(|r| r.props.size), Some(size));
}
#[test]
fn lays_out_every_balloon_paragraph_without_space_after_at_the_balloon_size() {
let paragraph = |content: Vec<Content>| {
Block::Paragraph(Paragraph {
runs: vec![Run {
style: None,
props: RunProps::default(),
content,
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}],
..Paragraph::empty()
})
};
let size = crate::params::BALLOON_SIZE;
let blocks = balloon_blocks(
&[
paragraph(vec![Content::Text("a".to_owned())]),
paragraph(Vec::new()),
paragraph(vec![Content::Text("b".to_owned())]),
],
size,
);
for block in &blocks {
let Block::Paragraph(p) = block else {
panic!("a paragraph");
};
assert_eq!(p.props.after, Some(Length::ZERO));
assert_eq!(p.props.mark.size, Some(size));
}
}
#[test]
fn prints_markup_only_for_a_comment_that_shows_a_balloon() {
let comment = |hidden: bool| Comment {
hidden,
..Comment::default()
};
let by_id = [("a", comment(true)), ("b", comment(false))]
.into_iter()
.map(|(id, c)| (id.to_owned(), c))
.collect();
let comments = Comments {
by_id,
deleted_cells: false,
};
let mut markup = CommentMarkup::new(&comments);
let anchor = |index: CommentIndex| Anchor {
index,
page: 0,
top: Length::ZERO,
};
assert!(!markup.shows_a_balloon());
let hidden = markup.index("a").unwrap();
markup.anchor(anchor(hidden));
assert!(!markup.shows_a_balloon());
let shown = markup.index("b").unwrap();
markup.anchor(anchor(shown));
assert!(markup.shows_a_balloon());
let deleted_cells = Comments {
deleted_cells: true,
..Comments::default()
};
let cells = CommentMarkup::new(&deleted_cells);
assert!(cells.shows_a_balloon());
}
#[test]
fn keeps_the_last_place_of_each_deleted_cell() {
let comments = Comments::default();
let mut markup = CommentMarkup::new(&comments);
let anchor = |id: &str, top: i64| CellAnchor {
id: id.to_owned(),
color: Rgb::BLACK,
page: 0,
top: Length::from_units(top),
};
markup.cell_anchor(anchor("1", 10));
markup.cell_anchor(anchor("2", 20));
markup.cell_anchor(anchor("1", 30));
let tops: Vec<i64> = markup.cells.iter().map(|a| a.top.units()).collect();
assert_eq!(tops, [30, 20]);
}
}