Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(scripts): match checker headroom in text wrap, sample the real key color on slice failure, and read run-level table styles in parity checks

hugohe3cdad162c867f
diff --git a/skills/ppt-master/scripts/slice_images.py b/skills/ppt-master/scripts/slice_images.py
index 8972f3bf..28efdd2c 100644
--- a/skills/ppt-master/scripts/slice_images.py
+++ b/skills/ppt-master/scripts/slice_images.py
@@ -61,6 +61,8 @@ _BG_SAMPLE_BORDER = 2
_BG_SAMPLE_MAX_SIDE = 256
_DEFAULT_FEATHER = 4
_BOUNDARY_OPAQUE_ALPHA = 32
+_SHEET_DIAGNOSTIC_BORDER_RATIO = 0.01
+_SHEET_DIAGNOSTIC_BUCKET_SIZE = 4
def _log(msg: str) -> None:
@@ -176,6 +178,53 @@ def _sample_bg(cell: Image.Image, tolerance: int) -> tuple[int, int, int]:
)
+def _sample_sheet_border(
+ sheet: Image.Image,
+) -> tuple[tuple[int, int, int], int]:
+ """Return the dominant RGB cluster and its spread in the outer 1% ring."""
+ rgb = sheet.convert("RGB")
+ width, height = rgb.size
+ border_x = max(1, round(width * _SHEET_DIAGNOSTIC_BORDER_RATIO))
+ border_y = max(1, round(height * _SHEET_DIAGNOSTIC_BORDER_RATIO))
+ px = rgb.load()
+ pixels: list[tuple[int, int, int]] = []
+
+ for y in range(border_y):
+ pixels.extend(px[x, y] for x in range(width))
+ for y in range(max(border_y, height - border_y), height):
+ pixels.extend(px[x, y] for x in range(width))
+ for y in range(border_y, max(border_y, height - border_y)):
+ pixels.extend(px[x, y] for x in range(border_x))
+ pixels.extend(
+ px[x, y]
+ for x in range(max(border_x, width - border_x), width)
+ )
+
+ buckets = Counter(
+ tuple(channel // _SHEET_DIAGNOSTIC_BUCKET_SIZE for channel in pixel)
+ for pixel in pixels
+ )
+ dominant_bucket = buckets.most_common(1)[0][0]
+ dominant_pixels = [
+ pixel
+ for pixel in pixels
+ if tuple(
+ channel // _SHEET_DIAGNOSTIC_BUCKET_SIZE
+ for channel in pixel
+ ) == dominant_bucket
+ ]
+ dominant = tuple(
+ round(median(channel))
+ for channel in zip(*dominant_pixels)
+ )
+ channel_spreads = [
+ max(pixel[index] for pixel in dominant_pixels)
+ - min(pixel[index] for pixel in dominant_pixels)
+ for index in range(3)
+ ]
+ return dominant, max(channel_spreads) # type: ignore[return-value]
+
+
def _max_channel_difference(cell: Image.Image, bg: tuple[int, int, int]) -> Image.Image:
"""Return the maximum absolute RGB channel difference from the background."""
diff = ImageChops.difference(cell.convert("RGB"), Image.new("RGB", cell.size, bg))
@@ -363,7 +412,7 @@ def _keying_findings(
findings.append(
f"{label}: {opaque}/{len(boundary)} boundary pixels stayed opaque "
f"after --alpha "
- f"(sampled background {hex_bg})"
+ f"(key background {hex_bg})"
)
if trim:
@@ -380,13 +429,18 @@ def _keying_findings(
if touched_edges:
findings.append(
f"{label}: content reaches the {'/'.join(touched_edges)} cell edge(s) "
- f"(sampled background {hex_bg})"
+ f"(key background {hex_bg})"
)
return findings
-def _log_keying_findings(findings: list[str]) -> None:
+def _log_keying_findings(
+ findings: list[str],
+ *,
+ sheet_border: tuple[tuple[int, int, int], int] | None = None,
+ tolerance: int,
+) -> None:
"""Report incomplete flat-background keying."""
_log("\n[WARN] Alpha extraction is incomplete — the key field or cell")
_log(" isolation failed:")
@@ -398,6 +452,18 @@ def _log_keying_findings(findings: list[str]) -> None:
"explicit")
_log(" --bg <hex> and a larger --tolerance; use --inset when a drawn "
"outer gutter is isolated from every element.")
+ if sheet_border is not None:
+ dominant, drift = sheet_border
+ hex_bg = "#{:02X}{:02X}{:02X}".format(*dominant)
+ suggested_tolerance = max(tolerance, drift)
+ _log(
+ " Measured outer 1% border/gutter: "
+ f"dominant {hex_bg}; max channel spread {drift}."
+ )
+ _log(
+ " Suggested rerun: "
+ f"--bg {hex_bg} --tolerance {suggested_tolerance}"
+ )
def slice_sheet(
@@ -508,7 +574,12 @@ def slice_sheet(
idx += 1
if findings:
- _log_keying_findings(findings)
+ sheet_border = _sample_sheet_border(sheet) if strict_alpha else None
+ _log_keying_findings(
+ findings,
+ sheet_border=sheet_border,
+ tolerance=tolerance,
+ )
if strict_alpha:
raise ValueError(
"strict alpha validation found incomplete background keying; "
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
index b82c1b63..6aaf62c2 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
@@ -659,21 +659,39 @@ def _validate_table_payload(
return payload, table_rows, col_count, merge_layout
+def _table_cell_text_parts(cell: Any) -> list[str]:
+ """Return normalized paragraph lines for one table cell."""
+ cell_data = _cell_payload(cell)
+ paragraphs = _table_cell_paragraphs(cell_data)
+ values = (
+ [paragraph.text for paragraph in paragraphs]
+ if paragraphs is not None
+ else [cell_data.get("text")]
+ )
+ return [
+ text
+ for text in (
+ _normalized_fallback_text(value)
+ for value in values
+ if value is not None
+ )
+ if text
+ ]
+
+
def _native_table_metadata_texts(table_rows: list[list[Any]]) -> dict[str, int]:
counts: dict[str, int] = {}
for row in table_rows:
for cell in row:
- cell_data = _cell_payload(cell)
- paragraphs = _table_cell_paragraphs(cell_data)
- texts = (
- [paragraph.text for paragraph in paragraphs]
- if paragraphs is not None
- else [cell_data.get("text")]
- )
- for value in texts:
- text = _normalized_fallback_text(value)
- if text:
- counts[text] = counts.get(text, 0) + 1
+ parts = _table_cell_text_parts(cell)
+ variants = list(parts)
+ if len(parts) > 1:
+ variants.extend({
+ _normalized_fallback_text("".join(parts)),
+ _normalized_fallback_text(" ".join(parts)),
+ })
+ for text in variants:
+ counts[text] = counts.get(text, 0) + 1
return counts
@@ -809,22 +827,44 @@ def _table_cell_at(
def _table_cell_texts(cell: Any) -> set[str]:
+ parts = _table_cell_text_parts(cell)
+ texts = set(parts)
+ if len(parts) > 1:
+ texts.add(_normalized_fallback_text("".join(parts)))
+ texts.add(_normalized_fallback_text(" ".join(parts)))
+ return texts
+
+
+def _table_cell_parity_text_style(
+ cell: Any,
+) -> tuple[bool | None, str | None]:
+ """Resolve cell-level parity style, falling back to uniform run values."""
cell_data = _cell_payload(cell)
paragraphs = _table_cell_paragraphs(cell_data)
- values = (
- [paragraph.text for paragraph in paragraphs]
+ runs = (
+ [run for paragraph in paragraphs for run in paragraph.runs or ()]
if paragraphs is not None
- else [cell_data.get("text")]
+ and all(paragraph.runs is not None for paragraph in paragraphs)
+ else []
)
- normalized = [
- _normalized_fallback_text(value)
- for value in values
- if value is not None
- ]
- texts = {text for text in normalized if text}
- if len(texts) > 1:
- texts.add(_normalized_fallback_text(" ".join(normalized)))
- return texts
+
+ uniform_bold: bool | None = None
+ run_bold = {run.bold for run in runs}
+ if runs and None not in run_bold and len(run_bold) == 1:
+ uniform_bold = run_bold.pop()
+
+ uniform_color: str | None = None
+ run_colors = {run.color for run in runs}
+ if runs and None not in run_colors and len(run_colors) == 1:
+ uniform_color = run_colors.pop()
+
+ bold = cell_data.get("bold") if "bold" in cell_data else uniform_bold
+ color = (
+ _hex_or_none(cell_data.get("color"))
+ if "color" in cell_data
+ else uniform_color
+ )
+ return bold, color
def _table_text_cells(
@@ -905,8 +945,9 @@ def _native_table_header_warnings(
header_text_color = max(set(header_colors), key=header_colors.count) if header_colors else None
if header_text_color is not None and style.get("header_text") is None:
if not all(
- _hex_or_none(_cell_payload(table_rows[row_idx][col_idx]).get("color"))
- == record.fill
+ _table_cell_parity_text_style(
+ table_rows[row_idx][col_idx]
+ )[1] == record.fill
for record, row_idx, col_idx in header_text_cells
if record.fill is not None
):
@@ -914,7 +955,9 @@ def _native_table_header_warnings(
if any(
record.bold
- and _cell_payload(table_rows[row_idx][col_idx]).get("bold") is not True
+ and _table_cell_parity_text_style(
+ table_rows[row_idx][col_idx]
+ )[0] is not True
for record, row_idx, col_idx in header_text_cells
):
missing.append("columns[].bold")
@@ -1023,7 +1066,9 @@ def _native_table_first_column_warnings(
missing: list[str] = []
if any(
record.bold
- and _cell_payload(table_rows[row_idx][col_idx]).get("bold") is not True
+ and _table_cell_parity_text_style(
+ table_rows[row_idx][col_idx]
+ )[0] is not True
for record, row_idx, col_idx in first_column
):
missing.append("bold")
@@ -1033,8 +1078,9 @@ def _native_table_first_column_warnings(
if (
record.fill is not None
and record.fill != body_color
- and _hex_or_none(_cell_payload(table_rows[row_idx][col_idx]).get("color"))
- != record.fill
+ and _table_cell_parity_text_style(
+ table_rows[row_idx][col_idx]
+ )[1] != record.fill
)
})
if missing_colors:
diff --git a/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py b/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
index 7bb25c23..bc93c6a2 100644
--- a/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
+++ b/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
@@ -290,6 +290,76 @@ class NativeProjectionCheckerTests(unittest.TestCase):
for text in expected:
self.assertIn(text, findings_by_page[filename])
+ def test_table_parity_accepts_uniform_run_level_bold_and_color(self) -> None:
+ marker = ET.fromstring("""
+ <g data-pptx-replace-with="table" data-pptx-bounds="0 0 200 80">
+ <metadata type="application/json">
+ {
+ "schema": "ppt-master.semantic-table.v2",
+ "x": 0, "y": 0, "width": 200, "height": 80,
+ "header_rows": 1,
+ "column_widths": [100, 100],
+ "row_heights": [40, 40],
+ "columns": [
+ {
+ "align": "l",
+ "paragraphs": [{"runs": [{
+ "text": "Level", "bold": true, "color": "#1E1A16"
+ }]}]
+ },
+ {
+ "align": "l",
+ "paragraphs": [{"runs": [{
+ "text": "Meaning", "bold": true, "color": "#1E1A16"
+ }]}]
+ }
+ ],
+ "rows": [[
+ {"paragraphs": [{"runs": [{
+ "text": "Altar", "bold": true, "color": "#1E1A16"
+ }]}]},
+ {"text": "Cosmos", "color": "#2F2A25"}
+ ]]
+ }
+ </metadata>
+ <line x1="0" y1="0" x2="200" y2="0" stroke="#999999"/>
+ <line x1="0" y1="40" x2="200" y2="40" stroke="#999999"/>
+ <line x1="0" y1="80" x2="200" y2="80" stroke="#999999"/>
+ <g font-weight="bold" fill="#1E1A16">
+ <text x="10" y="25">Level</text>
+ <text x="110" y="25">Meaning</text>
+ <text x="10" y="65">Altar</text>
+ </g>
+ <text x="110" y="65" fill="#2F2A25">Cosmos</text>
+ </g>
+ """)
+
+ joined = "\n".join(native_object_projection_warnings(marker))
+
+ self.assertNotIn("header style not projected", joined)
+ self.assertNotIn("first-column text style not projected", joined)
+
+ def test_table_parity_accepts_positioned_tspan_lines_for_paragraphs(self) -> None:
+ marker = ET.fromstring("""
+ <g data-pptx-replace-with="table" data-pptx-bounds="0 0 200 80">
+ <metadata type="application/json">
+ {
+ "schema": "ppt-master.semantic-table.v2",
+ "x": 0, "y": 0, "width": 200, "height": 80,
+ "header_rows": 0,
+ "rows": [[{"paragraphs": ["First line", "Second line"]}]]
+ }
+ </metadata>
+ <text x="10" y="25">
+ <tspan x="10" y="25">First line</tspan><tspan x="10" dy="24">Second line</tspan>
+ </text>
+ </g>
+ """)
+
+ joined = "\n".join(native_object_projection_warnings(marker))
+
+ self.assertNotIn("fallback text is missing", joined)
+
class NativeTablePayloadRoundTripTest(unittest.TestCase):
def test_marker_validation_keeps_original_table_payload(self):
diff --git a/skills/ppt-master/scripts/tests/test_slice_images.py b/skills/ppt-master/scripts/tests/test_slice_images.py
new file mode 100644
index 00000000..5466eb07
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_slice_images.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Focused tests for illustration-sheet alpha-key diagnostics."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+SCRIPT = SCRIPTS_DIR / "slice_images.py"
+
+
+class SliceImagesDiagnosticsTests(unittest.TestCase):
+ def test_strict_alpha_reports_measured_sheet_border_and_exact_rerun(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ sheet_path = root / "sheet.png"
+ output_dir = root / "output"
+ image = Image.new("RGB", (100, 80), (87, 178, 101))
+ draw = ImageDraw.Draw(image)
+ draw.rectangle((30, 22, 70, 58), fill=(170, 40, 55))
+ draw.point((0, 0), fill=(84, 176, 100))
+ draw.point((99, 79), fill=(88, 180, 102))
+ image.save(sheet_path)
+
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPT),
+ str(sheet_path),
+ "--grid", "1x1",
+ "--names", "element",
+ "--trim",
+ "--alpha",
+ "--strict-alpha",
+ "--bg", "#00FF00",
+ "--tolerance", "12",
+ "--output", str(output_dir),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("key background #00FF00", result.stderr)
+ self.assertIn("dominant #57B265", result.stderr)
+ self.assertIn("max channel spread 3", result.stderr)
+ self.assertIn("--bg #57B265 --tolerance 12", result.stderr)
+ self.assertFalse((output_dir / "element.png").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/ppt-master/scripts/tests/test_text_measure.py b/skills/ppt-master/scripts/tests/test_text_measure.py
index 233e815d..fa6e3eb2 100644
--- a/skills/ppt-master/scripts/tests/test_text_measure.py
+++ b/skills/ppt-master/scripts/tests/test_text_measure.py
@@ -3,10 +3,12 @@
from __future__ import annotations
+import json
import subprocess
import sys
import unittest
from pathlib import Path
+from xml.etree import ElementTree as ET
SCRIPTS_DIR = Path(__file__).resolve().parents[1]
@@ -17,15 +19,24 @@ from svg_to_pptx.drawingml.elements import ( # noqa: E402
estimate_single_line_text_frame_width,
)
from text_measure import ( # noqa: E402
+ _CLOSING_PUNCTUATION,
+ _OPENING_PUNCTUATION,
_render_wrapped_svg,
measure_text,
text_box,
wrap_text,
)
+from svg_quality.checker import SVGQualityChecker # noqa: E402
SCRIPT = SCRIPTS_DIR / 'text_measure.py'
SAMPLE = 'Current macro-free package; the main editable format in modern PowerPoint'
+CJK_PARAGRAPHS = (
+ '通体蓝瓦圆顶对应天穹,不靠体量压人,而用“圆”与“空”消解人与天地的隔阂;'
+ '蓝瓦贴合青天之色,模糊人间与天宇的边界。',
+ '三层汉白玉圆台层层递进,暗藏天时历法;古人在此祭天,以高台承接天地阳气,'
+ '把四时流转、阴阳交替的规律固化为仪式。',
+)
def _run_cli(*args: str) -> subprocess.CompletedProcess[str]:
@@ -68,6 +79,19 @@ class TextMeasureTests(unittest.TestCase):
self.assertAlmostEqual(width, direct)
self.assertLessEqual(direct, max_width)
+ def test_wrap_can_request_raw_width_without_headroom(self) -> None:
+ with_headroom = measure_text(SAMPLE, size=22)
+ raw = measure_text(SAMPLE, size=22, include_headroom=False)
+
+ self.assertGreater(with_headroom, raw)
+ result = _run_cli(
+ 'wrap', SAMPLE, '--size', '22', '--max-width', '900',
+ '--x', '96', '--dy', '30', '--no-headroom', '--json',
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload['widths'], [raw])
+
def test_oversized_token_is_emitted_alone_with_warning(self) -> None:
token = 'UnbreakableToken'
lines, widths, oversized = wrap_text(token, size=22, max_width=20)
@@ -90,6 +114,46 @@ class TextMeasureTests(unittest.TestCase):
self.assertEqual(oversized, [])
self.assertTrue(all(width <= 45 for width in widths))
+ def test_cjk_wrap_fits_checker_module_bounds_and_obeys_line_punctuation(self) -> None:
+ groups: list[str] = []
+ for index, paragraph in enumerate(CJK_PARAGRAPHS):
+ lines, widths, oversized = wrap_text(
+ paragraph,
+ size=24,
+ family='Microsoft YaHei',
+ max_width=540,
+ )
+
+ self.assertEqual(oversized, [])
+ self.assertTrue(all(width <= 540 for width in widths))
+ for line in lines:
+ self.assertNotIn(line[0], _CLOSING_PUNCTUATION)
+ self.assertNotIn(line[-1], _OPENING_PUNCTUATION)
+
+ top = index * 180
+ rendered = _render_wrapped_svg(
+ lines,
+ x=100,
+ y=top + 30,
+ dy=36,
+ )
+ groups.append(
+ f'<g id="module-{index}" data-pptx-bounds="100 {top} 540 160">'
+ f'{rendered}</g>'
+ )
+
+ root = ET.fromstring(
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" '
+ 'font-family="Microsoft YaHei" font-size="24">'
+ + ''.join(groups)
+ + '</svg>'
+ )
+ result = {'warnings': [], 'errors': [], 'info': {}}
+ SVGQualityChecker()._check_text_bounds(root, result)
+
+ self.assertEqual(result['warnings'], [])
+ self.assertEqual(result['errors'], [])
+
def test_box_arithmetic_and_anchor_adjustment(self) -> None:
expected_x = {'start': 100.0, 'middle': 60.0, 'end': 20.0}
for anchor, left in expected_x.items():
diff --git a/skills/ppt-master/scripts/text_measure.py b/skills/ppt-master/scripts/text_measure.py
index da12dc9a..d3f803f4 100644
--- a/skills/ppt-master/scripts/text_measure.py
+++ b/skills/ppt-master/scripts/text_measure.py
@@ -18,6 +18,7 @@ import html
import json
import math
import sys
+import unicodedata
from functools import partial
from pathlib import Path
@@ -28,11 +29,13 @@ if str(_SCRIPTS_DIR) not in sys.path:
from console_encoding import configure_utf8_stdio # noqa: E402
from svg_to_pptx.drawingml.elements import estimate_single_line_text_frame_width # noqa: E402
-from svg_to_pptx.drawingml.utils import is_cjk_char, split_project_text_clusters # noqa: E402
+from svg_to_pptx.drawingml.utils import split_project_text_clusters # noqa: E402
-_CLOSING_PUNCTUATION = frozenset(',.;:!?)]」』】》,。;:!?')
-_OPENING_PUNCTUATION = frozenset('([「『【《(')
+_CLOSING_PUNCTUATION = frozenset(',.;:!?)]}、,。;:!?)》」』】”’')
+_OPENING_PUNCTUATION = frozenset('([{(《「『【“‘')
+_PREFERRED_BREAK_PUNCTUATION = frozenset(',。;:')
+_LATIN_TOKEN_CONNECTORS = frozenset("'’._:/+%@#-")
_WEIGHTS = ('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')
@@ -65,66 +68,160 @@ def _format_number(value: float) -> str:
def measure_text(
text: str, *, size: float, family: str = 'Calibri',
weight: str = 'normal', letter_spacing: float = 0.0,
+ include_headroom: bool = True,
) -> float:
"""Measure one line with the checker-owned DrawingML estimator."""
run = dict(
text=text, font_size=size, font_family=family,
font_weight=weight, letter_spacing=letter_spacing,
)
- return estimate_single_line_text_frame_width([run])
+ return estimate_single_line_text_frame_width(
+ [run],
+ include_headroom=include_headroom,
+ )
+
+
+def _is_latin_or_number_cluster(cluster: str) -> bool:
+ """Return whether a rendered cluster belongs to a Latin/number token."""
+ bases = [
+ ch
+ for ch in cluster
+ if unicodedata.category(ch) not in {'Mn', 'Mc', 'Me'}
+ ]
+ return bool(bases) and all(
+ ch.isdigit() or 'LATIN' in unicodedata.name(ch, '')
+ for ch in bases
+ )
-def _protected_units(text: str) -> tuple[list[str], str]:
- cjk_clusters = ' ' not in text and any(is_cjk_char(ch) for ch in text)
- separator = '' if cjk_clusters else ' '
- units = split_project_text_clusters(text) if cjk_clusters else [token for token in text.split(' ') if token]
+def _lexical_units(text: str) -> list[str]:
+ """Split a paragraph while keeping Latin words and numbers atomic."""
+ clusters = split_project_text_clusters(' '.join(text.split()))
+ units: list[str] = []
+ pending_space = False
+ index = 0
+ while index < len(clusters):
+ cluster = clusters[index]
+ if cluster.isspace():
+ pending_space = bool(units)
+ index += 1
+ continue
+
+ end = index + 1
+ if _is_latin_or_number_cluster(cluster):
+ while end < len(clusters):
+ next_cluster = clusters[end]
+ if _is_latin_or_number_cluster(next_cluster):
+ end += 1
+ continue
+ connector = (
+ next_cluster in _LATIN_TOKEN_CONNECTORS
+ or (
+ next_cluster == ','
+ and clusters[end - 1].isdigit()
+ )
+ )
+ if (
+ connector
+ and end + 1 < len(clusters)
+ and _is_latin_or_number_cluster(clusters[end + 1])
+ ):
+ end += 2
+ continue
+ break
+
+ prefix = ' ' if pending_space else ''
+ units.append(prefix + ''.join(clusters[index:end]))
+ pending_space = False
+ index = end
+ return units
+
+
+def _protected_units(text: str) -> list[str]:
+ units = _lexical_units(text)
protected: list[str] = []
for unit in units:
- if protected and (unit[0] in _CLOSING_PUNCTUATION or protected[-1][-1] in _OPENING_PUNCTUATION):
- protected[-1] += separator + unit
+ content = unit.lstrip()
+ if protected and (
+ content[0] in _CLOSING_PUNCTUATION
+ or protected[-1].rstrip()[-1] in _OPENING_PUNCTUATION
+ ):
+ protected[-1] += unit
else:
protected.append(unit)
- return protected, separator
+ return protected
+
+
+def _joined_units(units: list[str], start: int, end: int) -> str:
+ return ''.join(units[start:end]).lstrip()
+
+
+def _preferred_break_after(text: str) -> bool:
+ tail = text.rstrip()
+ while (
+ tail
+ and tail[-1] in _CLOSING_PUNCTUATION
+ and tail[-1] not in _PREFERRED_BREAK_PUNCTUATION
+ ):
+ tail = tail[:-1]
+ return bool(tail) and tail[-1] in _PREFERRED_BREAK_PUNCTUATION
def wrap_text(
text: str, *, size: float, max_width: float, family: str = 'Calibri',
weight: str = 'normal', letter_spacing: float = 0.0,
+ include_headroom: bool = True,
) -> tuple[list[str], list[float], list[tuple[str, float]]]:
"""Greedily wrap text and return lines, widths, and oversized units."""
- style = dict(size=size, family=family, weight=weight, letter_spacing=letter_spacing)
- units, separator = _protected_units(text)
+ style = dict(
+ size=size,
+ family=family,
+ weight=weight,
+ letter_spacing=letter_spacing,
+ include_headroom=include_headroom,
+ )
+ units = _protected_units(text)
if not units:
return [''], [0.0], []
lines: list[str] = []
widths: list[float] = []
oversized: list[tuple[str, float]] = []
- current, current_width = '', 0.0
- for unit in units:
- unit_width = measure_text(unit, **style)
- if unit_width > max_width:
- if current:
- lines.append(current)
- widths.append(current_width)
- current = ''
+ start = 0
+ while start < len(units):
+ fit_widths: dict[int, float] = {}
+ preferred_end: int | None = None
+ end = start
+ while end < len(units):
+ candidate_end = end + 1
+ candidate = _joined_units(units, start, candidate_end)
+ candidate_width = measure_text(candidate, **style)
+ if candidate_width > max_width:
+ break
+ fit_widths[candidate_end] = candidate_width
+ if _preferred_break_after(candidate):
+ preferred_end = candidate_end
+ end = candidate_end
+
+ if end == len(units):
+ line = _joined_units(units, start, end)
+ lines.append(line)
+ widths.append(fit_widths[end])
+ break
+
+ if end == start:
+ unit = units[start].lstrip()
+ unit_width = measure_text(unit, **style)
lines.append(unit)
widths.append(unit_width)
oversized.append((unit, unit_width))
+ start += 1
continue
- candidate = unit if not current else current + separator + unit
- candidate_width = measure_text(candidate, **style)
- if current and candidate_width > max_width:
- lines.append(current)
- widths.append(current_width)
- current = unit
- current_width = unit_width
- else:
- current = candidate
- current_width = candidate_width
- if current:
- lines.append(current)
- widths.append(current_width)
+
+ line_end = preferred_end or end
+ lines.append(_joined_units(units, start, line_end))
+ widths.append(fit_widths[line_end])
+ start = line_end
return lines, widths, oversized
@@ -153,6 +250,11 @@ def _add_style_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--family', default='Calibri')
parser.add_argument('--weight', choices=_WEIGHTS, default='normal')
parser.add_argument('--letter-spacing', type=_bounded_float, default=0.0)
+ parser.add_argument(
+ '--no-headroom',
+ action='store_true',
+ help='Use the raw estimator instead of DrawingML wrapping headroom.',
+ )
def build_parser() -> argparse.ArgumentParser:
@@ -189,7 +291,13 @@ def main(argv: list[str] | None = None) -> int:
configure_utf8_stdio()
parser = build_parser()
args = parser.parse_args(argv)
- style = dict(size=args.size, family=args.family, weight=args.weight, letter_spacing=args.letter_spacing)
+ style = dict(
+ size=args.size,
+ family=args.family,
+ weight=args.weight,
+ letter_spacing=args.letter_spacing,
+ include_headroom=not args.no_headroom,
+ )
if args.command == 'measure':
if args.stdin and args.text: