diff --git a/paper/build_paper.py b/paper/build_paper.py index b52c230aa..8b704ab33 100644 --- a/paper/build_paper.py +++ b/paper/build_paper.py @@ -1,8 +1,10 @@ #!/usr/bin/env python3 """The single SLAS paper declaration; import shared build machinery, never copy it.""" +from copy import deepcopy from dataclasses import dataclass, replace import json +import xml.etree.ElementTree as ET from pathlib import Path from paper_build.artifacts import InputObservations @@ -16,7 +18,10 @@ PaperDefinition, Preparation, ) -from paper_build.word import CaptionedFiguresLayout, EndTextFiguresLayout +from paper_build.word import ( + CaptionedFiguresLayout, EndTextFiguresLayout, TableStyle, WordLayout, + properties, word_tag, +) ROOT = Path(__file__).resolve().parent BENCHMARK_INCLUDE = Path("figures/slas/benchmark-publication/benchmark_claims.json") @@ -94,6 +99,113 @@ def refresh(self, root: Path) -> None: ) +class ReadableTables(TableStyle, WordLayout): + """Give wide tables their own page without shrinking text or changing cells.""" + + minimum_column_width_twips = 2000 + inline_padding_twips = 80 + block_padding_twips = 20 + landscape_vertical_margin_twips = 720 + + def apply(self, root: ET.Element) -> None: + super().apply(root) + body = root.find(word_tag("body")) + portrait = body.find(word_tag("sectPr")) + page = portrait.find(word_tag("pgSz")) + width = int(page.get(word_tag("w"))) + height = int(page.get(word_tag("h"))) + landscape = deepcopy(portrait) + size = landscape.find(word_tag("pgSz")) + size.set(word_tag("w"), str(max(width, height))) + size.set(word_tag("h"), str(min(width, height))) + size.set(word_tag("orient"), "landscape") + for side in ("top", "bottom"): + landscape.find(word_tag("pgMar")).set( + word_tag(side), str(self.landscape_vertical_margin_twips) + ) + target = self.text_width(landscape) + blocks = list(body) + starts, ends = {}, {} + section = portrait + available_widths = {} + for block in reversed(blocks): + boundary = block.find(f"{word_tag('pPr')}/{word_tag('sectPr')}") + if boundary is not None: + section = boundary + available_widths[block] = self.text_width(section) + for index, table in enumerate(blocks): + if table.tag != word_tag("tbl"): + continue + padding = properties(properties(table, "tblPr"), "tblCellMar") + for side, amount in ( + ("top", self.block_padding_twips), + ("bottom", self.block_padding_twips), + ("left", self.inline_padding_twips), + ("right", self.inline_padding_twips), + ): + value = properties(padding, side) + value.set(word_tag("w"), str(amount)) + value.set(word_tag("type"), "dxa") + grid = table.find(word_tag("tblGrid")) + if len(grid) * self.minimum_column_width_twips <= available_widths[table]: + continue + original = [int(column.get(word_tag("w"))) for column in grid] + original_width = sum(original) + widths = [round(value * target / original_width) for value in original] + widths[-1] = target - sum(widths[:-1]) + for column, value in zip(grid, widths, strict=True): + column.set(word_tag("w"), str(value)) + for row in table.findall(word_tag("tr")): + offset = 0 + for cell in row.findall(word_tag("tc")): + span = cell.find(f"{word_tag('tcPr')}/{word_tag('gridSpan')}") + count = 1 if span is None else int(span.get(word_tag("val"))) + cell_width = properties(properties(cell, "tcPr"), "tcW") + cell_width.set(word_tag("w"), str(sum(widths[offset:offset + count]))) + cell_width.set(word_tag("type"), "dxa") + offset += count + start = index + while start: + previous = blocks[start - 1] + style = previous.find(f"{word_tag('pPr')}/{word_tag('pStyle')}") + if previous.tag == word_tag("bookmarkStart") or ( + style is not None + and style.get(word_tag("val")) in ("Heading2", "TableCaption") + ): + start -= 1 + else: + break + starts[start] = portrait + ends[index] = landscape + result = [] + for index, block in enumerate(blocks): + if index in starts: + result.append(self.page_end(starts[index])) + result.append(block) + if index in ends: + result.append(self.page_end(ends[index])) + body[:] = result + + @staticmethod + def text_width(section: ET.Element) -> int: + page = section.find(word_tag("pgSz")) + margins = section.find(word_tag("pgMar")) + return (int(page.get(word_tag("w"))) + - int(margins.get(word_tag("left"))) + - int(margins.get(word_tag("right")))) + + @staticmethod + def page_end(section: ET.Element) -> ET.Element: + paragraph = ET.Element(word_tag("p")) + clone = deepcopy(section) + properties(clone, "type").set(word_tag("val"), "nextPage") + properties(paragraph, "pPr").append(clone) + return paragraph + + +TABLE_STYLE = ReadableTables(font_size_half_points="21") + + PAPER = PaperDefinition( identity="slas-openhcs", output_prefix="openhcs", @@ -102,10 +214,10 @@ def refresh(self, root: Path) -> None: documents=( DocumentDefinition(DocumentRole.MANUSCRIPT, (Path("manuscript.md"),), layout=EndTextFiguresLayout( - caption_font_size_pt=10, + caption_font_size_pt=10, table_style=TABLE_STYLE, boundary_heading="OpenHCS supplementary material")), DocumentDefinition(DocumentRole.SUPPLEMENT, (Path("supplementary/README.md"),), - layout=CaptionedFiguresLayout(caption_font_size_pt=10)), + layout=CaptionedFiguresLayout(caption_font_size_pt=10, table_style=TABLE_STYLE)), ), preparation=SlasRetainedFigures(), combined_review=True, diff --git a/paper/test_table_layout.py b/paper/test_table_layout.py new file mode 100644 index 000000000..c078da0c2 --- /dev/null +++ b/paper/test_table_layout.py @@ -0,0 +1,69 @@ +"""The table policy preserves content and gives wide tables a usable page.""" +import subprocess +from xml.etree import ElementTree as ET +from zipfile import ZipFile + +from build_paper import TABLE_STYLE +from paper_build.word import CaptionedFiguresLayout, word_tag + + +def test_table_layout_preserves_content_width_units_and_sections(tmp_path): + source = """# Before + +| Item | Detail | +|---|---| +| First | A narrow table stays in portrait. | + +## Wide comparison + +Table: Every field and its meaning must survive. + +| A | B | C | D | E | +|---|---|---|---|---| +| one | two | three | four | five | +| six | seven | eight | nine | ten | + +# After + +The rest of the document returns to portrait. +""" + path = tmp_path / "tables.docx" + subprocess.run( + ["pandoc", "--from=markdown", "--to=docx", "-o", str(path)], + input=source, text=True, check=True, capture_output=True, + ) + with ZipFile(path) as archive: + root = ET.fromstring(archive.read("word/document.xml")) + tables = list(root.iter(word_tag("tbl"))) + before_text = [node.text for node in root.iter(word_tag("t"))] + before_cells = [ + [["".join(cell.itertext()) for cell in row.findall(word_tag("tc"))] + for row in table.findall(word_tag("tr"))] + for table in tables + ] + first_widths = [node.get(word_tag("w")) for node in tables[0].find(word_tag("tblGrid"))] + CaptionedFiguresLayout(table_style=TABLE_STYLE).apply(root) + assert [node.text for node in root.iter(word_tag("t"))] == before_text + assert [ + [["".join(cell.itertext()) for cell in row.findall(word_tag("tc"))] + for row in table.findall(word_tag("tr"))] + for table in tables + ] == before_cells + assert [node.get(word_tag("w")) for node in tables[0].find(word_tag("tblGrid"))] == first_widths + wide = tables[1] + wide_width = sum(int(node.get(word_tag("w"))) for node in wide.find(word_tag("tblGrid"))) + assert wide_width > sum(map(int, first_widths)) + for row in wide.findall(word_tag("tr")): + assert row.find(f"{word_tag('trPr')}/{word_tag('cantSplit')}") is not None + widths = [cell.find(f"{word_tag('tcPr')}/{word_tag('tcW')}") for cell in row.findall(word_tag("tc"))] + assert all(width.get(word_tag("type")) == "dxa" for width in widths) + assert sum(int(width.get(word_tag("w"))) for width in widths) == wide_width + sections = list(root.iter(word_tag("sectPr"))) + sizes = [section.find(word_tag("pgSz")) for section in sections] + assert len(sizes) == 3 + assert int(sizes[0].get(word_tag("w"))) < int(sizes[0].get(word_tag("h"))) + assert int(sizes[1].get(word_tag("w"))) > int(sizes[1].get(word_tag("h"))) + assert int(sizes[2].get(word_tag("w"))) < int(sizes[2].get(word_tag("h"))) + once = ET.tostring(root) + CaptionedFiguresLayout(table_style=TABLE_STYLE).apply(root) + assert ET.tostring(root) == once