f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Word's print with markup: when the body has comments, Word prints every page smaller, with a
//! markup area at its right side that holds the comments in balloons.

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,
};

/// The style whose size balloon text has.
const BALLOON_STYLE: &str = "BalloonText";
/// The color of the markup area.
const GRAY: Rgb = rgb(crate::params::MARKUP_GRAY);
/// The fill of a balloon.
const BALLOON_FILL: Rgb = rgb(crate::params::BALLOON_FILL);
/// The outline of a balloon.
const BALLOON_LINE: Rgb = rgb(crate::params::BALLOON_LINE);

/// A color of red, green and blue.
const fn rgb([r, g, b]: [u8; 3]) -> Rgb {
    Rgb { r, g, b }
}

/// A distance of the markup, which the parameters give in dots of the base device.
const fn dots(dots: i64) -> Length {
    Length::from_units(dots * DOT)
}

/// The comments of a document, and the places of their anchors in the body.
#[derive(Clone, Debug)]
pub(super) struct CommentMarkup<'a> {
    comments: &'a Comments,
    /// Comment IDs in the order of their references.
    numbers: Vec<String>,
    /// The index of each comment ID in `numbers`.
    places: HashMap<String, CommentIndex>,
    /// The lines of the references, the last place that the body gave each one.
    anchors: Vec<Anchor>,
    /// The places of the deleted table cells, the last place that the body gave each one.
    cells: Vec<CellAnchor>,
}

/// What the comments' record holds at a mark ([`super::columns::RowMark`]), which a rewind
/// takes back to: the number of comments numbered, and the anchors and deleted cells, whose
/// places a later line changes in place.
#[derive(Clone, Debug)]
pub(super) struct MarkupMark {
    numbers: usize,
    anchors: Vec<Anchor>,
    cells: Vec<CellAnchor>,
}

impl CommentMarkup<'_> {
    /// Notes what the record holds now.
    pub(super) fn mark(&self) -> MarkupMark {
        MarkupMark {
            numbers: self.numbers.len(),
            anchors: self.anchors.clone(),
            cells: self.cells.clone(),
        }
    }

    /// Takes back what the layout after `mark` numbered and placed.
    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);
    }
}

/// The first line of a deleted table cell, which shows a balloon of its own.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CellAnchor {
    /// The ID of the deletion.
    id: String,
    /// The color of the deletion's author.
    color: Rgb,
    /// The page, from 0.
    page: usize,
    /// The top of the line, from the top of the page.
    top: Length,
}

/// The line that holds a comment's reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Anchor {
    /// The comment's index in `numbers`.
    index: CommentIndex,
    /// The page, from 0.
    page: usize,
    /// The top of the line, from the top of the page.
    top: Length,
}

impl<'a> CommentMarkup<'a> {
    /// The markup of `comments`, with no reference and no anchor yet.
    pub(super) fn new(comments: &'a Comments) -> Self {
        Self {
            comments,
            numbers: Vec::new(),
            places: HashMap::new(),
            anchors: Vec::new(),
            cells: Vec::new(),
        }
    }

    /// The index of a comment by its ID, in the order of references, or none for a comment
    /// that the comments part does not have.
    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)
    }

    /// The numbers in the comments' labels, in the order of `numbers`, found in one pass.
    /// Comments that answer no other comment are numbered from 1 in the order of their
    /// references. A reply has the number of the comment that it answers, "R", and its place
    /// in that thread, where the first comment is 1: "4R2" is the first reply to comment 4. A
    /// reply to a reply has 0 for the number of the comment that it answers.
    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()
    }

    /// Whether the pages show a balloon: for a comment with an anchor in the body that shows
    /// one, or for a deleted table cell.
    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)
            })
    }

    /// The ID of the comment that a comment answers. A comment whose reference comes before
    /// that of the comment that it answers counts as a comment of its own.
    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)
    }

    /// Records the line of a comment's anchor. A reference appears once in the body, so a later
    /// record comes from laying the same line out again, as a table does after it measures
    /// its rows, and replaces the earlier one.
    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),
        }
    }

    /// Records the first line of a deleted cell. A later record of the same deletion replaces
    /// the earlier one, as for a comment's 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),
        }
    }
}

/// The map from a page's own points to the paper: x' = x0 + x * steps / 300, and the same for
/// y from y0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Transform {
    steps: i64,
    x0: Length,
    y0: Length,
}

impl Transform {
    /// The transform of a page of a width and height with a text column that ends at `right`.
    /// Word fits the page and the markup area into the paper's width, less a margin, at a scale
    /// that is a whole number of steps below the fit, and centers the page on the paper's
    /// height at the fit itself. The fit and the top count in `i128`.
    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)
    }

    /// A length on the paper. The scale comes from the page's size and the end of its text
    /// column, and has no small bound for a column that ends far left of the page's right
    /// edge, so a product that leaves an `i64` overflows as in the bare code.
    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),
        }
    }

    /// An item on the paper: each of its places and lengths scaled from the page.
    fn item(self, mut item: Item) -> Item {
        item.map_places(|p| self.point(p), |v| self.len(v));
        item
    }
}

/// A filled rectangle.
const fn fill((x, y, width, height): (Length, Length, Length, Length), color: Rgb) -> Item {
    Item::Rect(Rect {
        x,
        y,
        width,
        height,
        color,
    })
}

impl Layout<'_> {
    /// Records the comment references of a body line whose top is at `top` on the current
    /// page.
    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 });
            }
        }
    }

    /// Records a deleted table cell whose first line starts at `top` on the current page.
    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,
        });
    }

    /// Prints the pages with markup when the body has comment anchors: each page smaller, with
    /// the markup area and the balloons of the comments whose anchors are on it.
    pub(super) fn print_markup(&mut self) {
        // quirk: CommentMarkup::PrintsMarkupArea (src/quirks.rs). A target that prints without markup
        // reads no comments and no deleted cells, so that no anchor shows a balloon.
        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);
            // The markup scales the page as the layout device has it, on its grid; the page
            // itself keeps its exact size for the target's PDF writer.
            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, &section, &labels));
            fronts.push((items, t));
            // The records of the page's lines go with their glyphs.
            for line in self
                .output
                .placed
                .iter_mut()
                .filter(|line| line.page == index)
            {
                line.markup_scale = Some(t.steps);
                // A turned line keeps the places of its frame, and the frame lands on the paper.
                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);
            }
        }
        // Each page keeps its exact size, with the markup area and the balloons behind its own
        // items, and all of them on the paper.
        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();
    }

    /// The balloons of the comments whose anchors are on a page, from the top down. A balloon
    /// starts at the top of its anchor's line, or below the balloon above it.
    fn balloons(
        &mut self,
        page: usize,
        right: Length,
        section: &crate::body::Section,
        labels: &[String],
    ) -> Vec<Item> {
        // A deleted table cell's balloon is white with a line in its author's color, and
        // stacks with the comments' balloons.
        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
    }

    /// The text of a balloon: the comment's paragraphs at the balloon size, the first one
    /// after the label "Commented [initials number]: " in Times New Roman Bold, with the
    /// number of `labels` ([`CommentMarkup::labels`]).
    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)
    }

    /// The properties of a balloon's label. Balloon text has the size of the "Balloon Text"
    /// style when the document has that style, and else 9 pt. The label has that style's
    /// font in bold, and else Times New Roman Bold.
    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()
        }
    }

    /// The text of the balloon of a deleted table cell: the label "Deleted Cells".
    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)
    }
}

/// A comment's paragraphs as a balloon shows them: single-spaced, at the balloon size in
/// half-points, and without space after any of them.
fn balloon_blocks(comment: &[Block], size: i64) -> Vec<Block> {
    let mut blocks = comment.to_vec();
    // The reference mark sizes the line of the label only in a comment without text.
    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 {
            // Balloon lines are single-spaced, whatever the paragraph's style asks, and no
            // paragraph keeps space after it, so the next one and the end of the balloon
            // follow its last line.
            paragraph.props.line = Some(LineSpacing::Auto(LINE));
            paragraph.props.after = Some(Length::ZERO);
            paragraph.props.after_auto = Some(false);
            // The paragraph mark takes the balloon size too, which sizes an empty paragraph.
            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
}

/// The text column of a balloon whose left side is at `left`: a section of one column with
/// its margins around the balloon's inside.
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
}

/// The story of a balloon's text, whose fields count no pages.
const BALLOON: super::Story = super::Story {
    kind: super::StoryKind::Balloon,
    numbers: super::StoryNumbers::PAGE_ONE,
};

/// The outline of a balloon: four lines of one device dot.
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;

    /// Twips in units.
    const TWIP: i64 = 1_270;

    /// The scale steps, x offset and top of a page, in device dots, from its size and right
    /// margin in twips.
    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() {
        // US Letter with right margins of 1, 0.75 and 1.25 inches, A4, and A4 landscape, as
        // Word's PDFs draw them.
        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();
        // The trial numbers a second comment and moves the first one's anchor.
        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));
        // A comment numbered after the rewind takes the second number again.
        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)),
            // A reply whose reference comes before its comment's counts as a comment.
            ("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() {
        // Every paragraph of a comment, not only the last, loses its space after, and an empty
        // paragraph's mark takes 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,
        };
        // No anchor, and an anchor of a hidden comment only, show no balloon.
        assert!(!markup.shows_a_balloon());
        let hidden = markup.index("a").unwrap();
        markup.anchor(anchor(hidden));
        assert!(!markup.shows_a_balloon());
        // An anchor of a comment that shows does.
        let shown = markup.index("b").unwrap();
        markup.anchor(anchor(shown));
        assert!(markup.shows_a_balloon());
        // A deleted table cell shows a balloon of its own, without any comment.
        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));
        // A table lays a row out again after it measures it, and the later place counts.
        markup.cell_anchor(anchor("1", 30));
        let tops: Vec<i64> = markup.cells.iter().map(|a| a.top.units()).collect();
        assert_eq!(tops, [30, 20]);
    }
}