zcode-app-cli 3.3.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,1337 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ poster_validate.py — Pre- and post-generation quality checks for poster/creative PDFs.
4
+
5
+ Usage:
6
+ # Check HTML before PDF generation
7
+ python3 poster_validate.py check-html poster.html [--fix] [--output fixed.html]
8
+
9
+ # Check PDF after generation
10
+ python3 poster_validate.py check-pdf poster.pdf --source-html poster.html
11
+
12
+ Both commands emit a JSON report to stdout:
13
+ {"pass": bool, "source": "...", "check_type": "html"|"pdf",
14
+ "errors": [...], "warnings": [...], "info": [...]}
15
+
16
+ Exit codes:
17
+ 0 pass (no errors; warnings/info are OK)
18
+ 1 fail (at least one error)
19
+ 2 script-level failure (bad arguments, unreadable file, …)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import math
27
+ import os
28
+ import re
29
+ import sys
30
+ from html.parser import HTMLParser
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Constants
36
+ # ---------------------------------------------------------------------------
37
+
38
+ GENERIC_FAMILIES = frozenset(
39
+ ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif",
40
+ "ui-sans-serif", "ui-monospace", "ui-rounded", "math", "emoji", "fangsong"]
41
+ )
42
+
43
+ SERIF_FONTS = frozenset(f.lower() for f in [
44
+ "Playfair Display", "Georgia", "Times New Roman", "Times", "Noto Serif",
45
+ "Noto Serif SC", "Noto Serif TC", "Noto Serif JP", "Noto Serif KR",
46
+ "Source Serif Pro", "Source Serif 4", "Merriweather", "Lora", "PT Serif",
47
+ "Libre Baskerville", "EB Garamond", "Cormorant Garamond", "Crimson Text",
48
+ "STSong", "FangSong", "KaiTi", "STKaiti", "Songti SC",
49
+ ])
50
+
51
+ CHINESE_FONTS = frozenset(f.lower() for f in [
52
+ "SimHei", "Microsoft YaHei", "Noto Sans SC", "Noto Sans TC",
53
+ "Noto Sans CJK SC", "Noto Sans CJK TC", "PingFang SC", "PingFang TC",
54
+ "Source Han Sans SC", "Source Han Sans TC", "WenQuanYi Micro Hei",
55
+ "WenQuanYi Zen Hei", "Hiragino Sans GB", "STHeiti", "STXihei",
56
+ "Noto Serif SC", "Noto Serif TC", "Noto Serif CJK SC",
57
+ "Source Han Serif SC", "SimSun", "NSimSun", "FangSong", "KaiTi",
58
+ "STSong", "STFangsong", "STKaiti", "Songti SC", "Heiti SC",
59
+ ])
60
+
61
+ # Selectors we treat as "main containers" whose overflow:hidden is dangerous.
62
+ # NOTE: .poster and .page are EXCLUDED because html2poster.js auto-injects
63
+ # overflow:hidden on them at render time. See SKILL.md Engine Selection Rules.
64
+ CONTAINER_SELECTORS = {"body", "html", ".slide",
65
+ "#app", "#root", ".container", ".wrapper", "main",
66
+ "section", "article"}
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Helpers
70
+ # ---------------------------------------------------------------------------
71
+
72
+
73
+ def _issue(code: str, message: str, severity: str = "error", line: int | None = None) -> dict:
74
+ d: dict[str, Any] = {"code": code, "message": message, "severity": severity}
75
+ if line is not None:
76
+ d["line"] = line
77
+ return d
78
+
79
+
80
+ def _line_number(full_text: str, pos: int) -> int:
81
+ """Return 1-based line number for character position *pos*."""
82
+ return full_text.count("\n", 0, pos) + 1
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # CSS regex helpers
87
+ # ---------------------------------------------------------------------------
88
+
89
+ _RE_FONT_FAMILY = re.compile(
90
+ r"font-family\s*:\s*([^;}\n]+)", re.IGNORECASE
91
+ )
92
+
93
+ _RE_FONT_SIZE = re.compile(
94
+ r"font-size\s*:\s*(\d+(?:\.\d+)?)\s*(px|pt|em|rem)", re.IGNORECASE
95
+ )
96
+
97
+ _RE_PAGE_SIZE = re.compile(
98
+ r"@page\s*\{[^}]*\bsize\s*:", re.IGNORECASE | re.DOTALL
99
+ )
100
+
101
+ _RE_CSS_URL = re.compile(
102
+ r"url\(\s*['\"]?(https?://[^'\")\s]+)['\"]?\s*\)", re.IGNORECASE
103
+ )
104
+
105
+ _RE_OVERFLOW = re.compile(
106
+ r"overflow\s*:\s*hidden", re.IGNORECASE
107
+ )
108
+
109
+ _RE_BG_WHITE = re.compile(
110
+ r"background(?:-color)?\s*:\s*(white|#fff(?:fff)?|transparent)\b", re.IGNORECASE
111
+ )
112
+
113
+ _RE_COLOR_HEX = re.compile(r"#([0-9a-fA-F]{3,8})")
114
+ _RE_COLOR_RGB = re.compile(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
115
+
116
+ _RE_STYLE_BLOCK = re.compile(r"<style[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)
117
+ _RE_INLINE_STYLE = re.compile(r'style\s*=\s*["\']([^"\']*)["\']', re.IGNORECASE)
118
+
119
+ _RE_CSS_RULE = re.compile(
120
+ r"([^{]+)\{([^}]*)\}", re.DOTALL
121
+ )
122
+
123
+ _RE_WIDTH_PX = re.compile(r"width\s*:\s*(\d+(?:\.\d+)?)\s*px", re.IGNORECASE)
124
+
125
+
126
+ def _parse_font_list(raw: str) -> list[str]:
127
+ """Split a font-family value into individual font names (unquoted, stripped)."""
128
+ fonts: list[str] = []
129
+ for part in raw.split(","):
130
+ name = part.strip().strip("'\"").strip()
131
+ if name:
132
+ fonts.append(name)
133
+ return fonts
134
+
135
+
136
+ def _has_generic(fonts: list[str]) -> bool:
137
+ return any(f.lower() in GENERIC_FAMILIES for f in fonts)
138
+
139
+
140
+ def _best_generic(fonts: list[str]) -> str:
141
+ """Pick the best generic fallback for a list of named fonts."""
142
+ lower = [f.lower() for f in fonts]
143
+ if any(f in CHINESE_FONTS for f in lower):
144
+ return "sans-serif"
145
+ if any(f in SERIF_FONTS for f in lower):
146
+ return "serif"
147
+ return "sans-serif"
148
+
149
+
150
+ # ---------------------------------------------------------------------------
151
+ # Color / contrast helpers
152
+ # ---------------------------------------------------------------------------
153
+
154
+ def _hex_to_rgb(h: str) -> tuple[int, int, int] | None:
155
+ h = h.lstrip("#")
156
+ if len(h) == 3:
157
+ h = h[0]*2 + h[1]*2 + h[2]*2
158
+ if len(h) == 4:
159
+ h = h[0]*2 + h[1]*2 + h[2]*2 # ignore alpha
160
+ if len(h) == 8:
161
+ h = h[:6] # strip alpha
162
+ if len(h) != 6:
163
+ return None
164
+ try:
165
+ return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
166
+ except ValueError:
167
+ return None
168
+
169
+
170
+ def _relative_luminance(r: int, g: int, b: int) -> float:
171
+ """WCAG 2.x relative luminance."""
172
+ def _c(v: int) -> float:
173
+ s = v / 255.0
174
+ return s / 12.92 if s <= 0.03928 else ((s + 0.055) / 1.055) ** 2.4
175
+ return 0.2126 * _c(r) + 0.7152 * _c(g) + 0.0722 * _c(b)
176
+
177
+
178
+ def _contrast_ratio(rgb1: tuple[int, int, int], rgb2: tuple[int, int, int]) -> float:
179
+ l1 = _relative_luminance(*rgb1)
180
+ l2 = _relative_luminance(*rgb2)
181
+ lighter = max(l1, l2)
182
+ darker = min(l1, l2)
183
+ return (lighter + 0.05) / (darker + 0.05)
184
+
185
+
186
+ def _extract_color(css_text: str, prop: str) -> tuple[int, int, int] | None:
187
+ """Try to extract an RGB color for a given CSS property from a rule body."""
188
+ pat = re.compile(rf"{prop}\s*:\s*([^;]+)", re.IGNORECASE)
189
+ m = pat.search(css_text)
190
+ if not m:
191
+ return None
192
+ val = m.group(1).strip()
193
+ # Named colours (just the common ones)
194
+ named = {
195
+ "white": (255, 255, 255), "black": (0, 0, 0), "red": (255, 0, 0),
196
+ "green": (0, 128, 0), "blue": (0, 0, 255), "yellow": (255, 255, 0),
197
+ "grey": (128, 128, 128), "gray": (128, 128, 128), "transparent": (255, 255, 255),
198
+ }
199
+ low = val.lower().split()[0].rstrip(";")
200
+ if low in named:
201
+ return named[low]
202
+ m_rgb = _RE_COLOR_RGB.search(val)
203
+ if m_rgb:
204
+ return int(m_rgb.group(1)), int(m_rgb.group(2)), int(m_rgb.group(3))
205
+ m_hex = _RE_COLOR_HEX.search(val)
206
+ if m_hex:
207
+ return _hex_to_rgb(m_hex.group(1))
208
+ return None
209
+
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # HTML visible text extractor (stdlib only)
213
+ # ---------------------------------------------------------------------------
214
+
215
+ class _TextExtractor(HTMLParser):
216
+ """Extract visible text from HTML, skipping <script>, <style>, etc."""
217
+
218
+ _SKIP_TAGS = frozenset(["script", "style", "noscript", "template", "svg"])
219
+
220
+ def __init__(self) -> None:
221
+ super().__init__()
222
+ self._skip_depth = 0
223
+ self.parts: list[str] = []
224
+
225
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
226
+ if tag.lower() in self._SKIP_TAGS:
227
+ self._skip_depth += 1
228
+
229
+ def handle_endtag(self, tag: str) -> None:
230
+ if tag.lower() in self._SKIP_TAGS and self._skip_depth > 0:
231
+ self._skip_depth -= 1
232
+
233
+ def handle_data(self, data: str) -> None:
234
+ if self._skip_depth == 0:
235
+ self.parts.append(data)
236
+
237
+ def get_text(self) -> str:
238
+ return " ".join(self.parts)
239
+
240
+
241
+ def _html_visible_text(html: str) -> str:
242
+ ext = _TextExtractor()
243
+ try:
244
+ ext.feed(html)
245
+ except Exception:
246
+ pass
247
+ return ext.get_text()
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # CHECK-HTML
252
+ # ---------------------------------------------------------------------------
253
+
254
+ def check_html(html_path: str, *, fix: bool = False, output_path: str | None = None) -> dict:
255
+ """Run all HTML pre-checks. Return the JSON-serialisable report dict."""
256
+
257
+ path = Path(html_path)
258
+ if not path.is_file():
259
+ return {"pass": False, "source": html_path, "check_type": "html",
260
+ "errors": [_issue("FILE_NOT_FOUND", f"Cannot read '{html_path}'.")],
261
+ "warnings": [], "info": []}
262
+
263
+ raw = path.read_text(encoding="utf-8", errors="replace")
264
+ original = raw # keep for line-number lookup
265
+ # For fix mode: we collect all replacements and apply them at the end
266
+ # using re.sub on the original to avoid offset corruption
267
+ _all_fixes: list[tuple[str, str]] = [] # (old_text, new_text) applied in order
268
+
269
+ errors: list[dict] = []
270
+ warnings: list[dict] = []
271
+ info: list[dict] = []
272
+
273
+ # Collect all CSS text (style blocks + inline styles)
274
+ all_css_positions: list[tuple[str, int]] = [] # (css_text, char_offset_in_raw)
275
+ for m in _RE_STYLE_BLOCK.finditer(raw):
276
+ all_css_positions.append((m.group(1), m.start(1)))
277
+ for m in _RE_INLINE_STYLE.finditer(raw):
278
+ all_css_positions.append((m.group(1), m.start(1)))
279
+
280
+ all_css = "\n".join(c for c, _ in all_css_positions)
281
+
282
+ # ---- 1. FONT_NO_FALLBACK ----
283
+ for css_text, css_offset in all_css_positions:
284
+ for m in _RE_FONT_FAMILY.finditer(css_text):
285
+ fonts = _parse_font_list(m.group(1))
286
+ if fonts and not _has_generic(fonts):
287
+ abs_pos = css_offset + m.start()
288
+ ln = _line_number(original, abs_pos)
289
+ generic = _best_generic(fonts)
290
+ errors.append(_issue(
291
+ "FONT_NO_FALLBACK",
292
+ f"font-family {', '.join(repr(f) for f in fonts)} has no generic fallback. "
293
+ f"Add '{generic}' at the end.",
294
+ line=ln
295
+ ))
296
+ if fix:
297
+ old_decl = m.group(0) # e.g. "font-family: 'Montserrat'"
298
+ val_part = m.group(1).rstrip().rstrip(";").rstrip()
299
+ new_decl = f"font-family: {val_part}, {generic}"
300
+ _all_fixes.append((old_decl, new_decl))
301
+
302
+ # ---- 2. OVERFLOW_HIDDEN_CONTAINER ----
303
+ for css_text, css_offset in all_css_positions:
304
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
305
+ selector_raw = rule_m.group(1).strip()
306
+ body = rule_m.group(2)
307
+ if not _RE_OVERFLOW.search(body):
308
+ continue
309
+ # Check if this selector is a container
310
+ selectors = [s.strip().lower() for s in selector_raw.split(",")]
311
+ for sel in selectors:
312
+ # Strip pseudo-classes/elements for matching
313
+ base_sel = re.split(r"[:>\s+~]", sel)[0].strip()
314
+ if base_sel in CONTAINER_SELECTORS:
315
+ # Check for width < 200px exemption
316
+ w_m = _RE_WIDTH_PX.search(body)
317
+ if w_m and float(w_m.group(1)) < 200:
318
+ continue
319
+ abs_pos = css_offset + rule_m.start()
320
+ ln = _line_number(original, abs_pos)
321
+ errors.append(_issue(
322
+ "OVERFLOW_HIDDEN_CONTAINER",
323
+ f"'{base_sel}' has 'overflow: hidden' which clips content in PDF rendering. "
324
+ "Remove it or use 'overflow: visible'.",
325
+ line=ln
326
+ ))
327
+ if fix:
328
+ old_rule = rule_m.group(0)
329
+ fixed_body = re.sub(r"overflow\s*:\s*hidden\s*;?\s*", "", body, flags=re.IGNORECASE)
330
+ new_rule = f"{rule_m.group(1)}{{{fixed_body}}}"
331
+ _all_fixes.append((old_rule, new_rule))
332
+ break # only report once per rule
333
+
334
+ # Also check inline styles on body/html tags
335
+ for tag_name in ("body", "html"):
336
+ tag_pat = re.compile(rf"<{tag_name}([^>]*)>", re.IGNORECASE)
337
+ for tm in tag_pat.finditer(raw):
338
+ attrs_str = tm.group(1)
339
+ style_m = re.search(r'style\s*=\s*["\']([^"\']*)["\']', attrs_str, re.IGNORECASE)
340
+ if style_m and _RE_OVERFLOW.search(style_m.group(1)):
341
+ ln = _line_number(original, tm.start())
342
+ errors.append(_issue(
343
+ "OVERFLOW_HIDDEN_CONTAINER",
344
+ f"<{tag_name}> has inline 'overflow: hidden' which clips content. Remove it.",
345
+ line=ln
346
+ ))
347
+ if fix:
348
+ old_style = style_m.group(1)
349
+ new_style = re.sub(r"overflow\s*:\s*hidden\s*;?\s*", "", old_style, flags=re.IGNORECASE)
350
+ _all_fixes.append((old_style, new_style))
351
+
352
+ # ---- 2b. FIXED_SIZE_NO_SCREEN_ADAPT ----
353
+ # For fixed-size single-page designs (poster, infographic, certificate, card),
354
+ # check that @media screen auto-scale CSS is present.
355
+ # Detect fixed-size pages: html/body with explicit px width+height
356
+ _has_fixed_width = False
357
+ _has_fixed_height = False
358
+ _fixed_h_value = None
359
+ for css_text, css_offset in all_css_positions:
360
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
361
+ selector_raw = rule_m.group(1).strip().lower()
362
+ body_text = rule_m.group(2)
363
+ selectors = [s.strip() for s in selector_raw.split(",")]
364
+ if any(s in ("body", "html", "html, body", "body, html") for s in selectors):
365
+ if re.search(r"(?<!max-)(?<!min-)width\s*:\s*\d+(?:\.\d+)?\s*px", body_text, re.IGNORECASE):
366
+ _has_fixed_width = True
367
+ h_m = re.search(r"(?<!max-)(?<!min-)height\s*:\s*(\d+(?:\.\d+)?)\s*px", body_text, re.IGNORECASE)
368
+ if h_m:
369
+ _has_fixed_height = True
370
+ _fixed_h_value = h_m.group(1)
371
+ # Also check .page / .poster containers
372
+ for css_text, css_offset in all_css_positions:
373
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
374
+ selector_raw = rule_m.group(1).strip().lower()
375
+ body_text = rule_m.group(2)
376
+ selectors = [s.strip() for s in selector_raw.split(",")]
377
+ if any(s in (".page", ".poster", "#page", "#poster", ".slide") for s in selectors):
378
+ if re.search(r"(?<!max-)(?<!min-)width\s*:\s*\d+(?:\.\d+)?\s*px", body_text, re.IGNORECASE):
379
+ _has_fixed_width = True
380
+ h_m = re.search(r"(?<!max-)(?<!min-)height\s*:\s*(\d+(?:\.\d+)?)\s*px", body_text, re.IGNORECASE)
381
+ if h_m:
382
+ _has_fixed_height = True
383
+ if not _fixed_h_value:
384
+ _fixed_h_value = h_m.group(1)
385
+
386
+ _is_fixed_size_page = _has_fixed_width and _has_fixed_height
387
+
388
+ if _is_fixed_size_page:
389
+ # Check for @media screen rule
390
+ _has_media_screen = bool(re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE))
391
+ if not _has_media_screen:
392
+ _height_hint = _fixed_h_value or "1400"
393
+ warnings.append(_issue(
394
+ "FIXED_SIZE_NO_SCREEN_ADAPT",
395
+ f"Fixed-size page detected ({_height_hint}px tall) but no @media screen rule found. "
396
+ "Browser preview will require scrolling to see the full page. "
397
+ "Add @media screen {{ html {{ height:auto; display:flex; justify-content:center; }} "
398
+ f"body {{ transform-origin:top center; scale:min(1, calc(100vh / {_height_hint})); "
399
+ "margin:0 auto; }} }} for auto-scaling preview.",
400
+ severity="warning"
401
+ ))
402
+
403
+ # Check for @media screen + scale/transform (more specific)
404
+ if _has_media_screen:
405
+ # Extract full @media screen block content (handles nested braces)
406
+ _media_screen_content = ""
407
+ _ms_match = re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE)
408
+ if _ms_match:
409
+ # Find matching closing brace (count nested braces)
410
+ _depth = 1
411
+ _start = _ms_match.end()
412
+ for _ci in range(_start, len(all_css)):
413
+ if all_css[_ci] == '{':
414
+ _depth += 1
415
+ elif all_css[_ci] == '}':
416
+ _depth -= 1
417
+ if _depth == 0:
418
+ _media_screen_content = all_css[_start:_ci]
419
+ break
420
+ _has_scale = bool(re.search(
421
+ r"(?:scale|transform|zoom)",
422
+ _media_screen_content, re.IGNORECASE
423
+ ))
424
+ if not _has_scale:
425
+ warnings.append(_issue(
426
+ "SCREEN_ADAPT_NO_SCALE",
427
+ "@media screen block exists but lacks scale/transform/zoom for auto-fitting. "
428
+ f"Add: body {{ scale: min(1, calc(100vh / {_fixed_h_value or '1400'})); }}",
429
+ severity="warning"
430
+ ))
431
+
432
+ # ---- 3. REMOTE_IMAGE ----
433
+ # <img src="http...">
434
+ for m in re.finditer(r'<img\s[^>]*src\s*=\s*["\']?(https?://[^\s"\'>\)]+)', raw, re.IGNORECASE):
435
+ url = m.group(1)
436
+ ln = _line_number(original, m.start())
437
+ warnings.append(_issue(
438
+ "REMOTE_IMAGE",
439
+ f"img src='{_truncate(url, 80)}' is a remote URL. "
440
+ "Download to images/ subdirectory and use relative path (src=\"images/filename.jpg\").",
441
+ severity="warning", line=ln
442
+ ))
443
+ # CSS url(http...)
444
+ for css_text, css_offset in all_css_positions:
445
+ for m in _RE_CSS_URL.finditer(css_text):
446
+ url = m.group(1)
447
+ abs_pos = css_offset + m.start()
448
+ ln = _line_number(original, abs_pos)
449
+ warnings.append(_issue(
450
+ "REMOTE_IMAGE",
451
+ f"CSS url('{_truncate(url, 80)}') is a remote URL. "
452
+ "Download locally for reliable PDF generation.",
453
+ severity="warning", line=ln
454
+ ))
455
+
456
+ # ---- 3b. ABSOLUTE_PATH ----
457
+ # <img src="file:///..." or src="/absolute/path">
458
+ for m in re.finditer(r'<img\s[^>]*src\s*=\s*["\']?(file://[^\s"\'>\)]+|/[^\s"\'>\)]+)', raw, re.IGNORECASE):
459
+ path_val = m.group(1)
460
+ ln = _line_number(original, m.start())
461
+ warnings.append(_issue(
462
+ "ABSOLUTE_PATH",
463
+ f"img src='{_truncate(path_val, 80)}' uses an absolute path. "
464
+ "Use relative path (src=\"images/filename.jpg\") for portability.",
465
+ severity="warning", line=ln
466
+ ))
467
+
468
+ # ---- 4. NO_PAGE_SIZE ----
469
+ if not _RE_PAGE_SIZE.search(all_css):
470
+ warnings.append(_issue(
471
+ "NO_PAGE_SIZE",
472
+ "@page { size: ... } not found in CSS. Playwright will use default A4 "
473
+ "which may not match the poster design. Add explicit page size.",
474
+ severity="warning"
475
+ ))
476
+
477
+ # ---- 4b. MISSING_MARGIN_RESET ----
478
+ # Check if html/body has margin:0 reset (Chromium defaults to body { margin: 8px })
479
+ has_margin_reset = bool(re.search(
480
+ r'(?:html|body|\*)\s*(?:,\s*(?:html|body|\*)\s*)?{[^}]*margin\s*:\s*0',
481
+ all_css, re.IGNORECASE
482
+ ))
483
+ if not has_margin_reset:
484
+ warnings.append(_issue(
485
+ "MISSING_MARGIN_RESET",
486
+ "No 'margin: 0' found on html/body/*. Chromium's default body { margin: 8px } "
487
+ "will cause black edges on top/left/bottom of the poster PDF. "
488
+ "Add: html, body { margin: 0; padding: 0; }",
489
+ severity="warning"
490
+ ))
491
+
492
+ # ---- 4c. PAGE_SIZE_CSS_VAR ----
493
+ # CSS variables are NOT resolved in @page rules — will silently fallback to A4
494
+ page_size_var_match = re.search(
495
+ r'@page\s*\{[^}]*\bsize\s*:[^;]*var\s*\(',
496
+ all_css, re.IGNORECASE | re.DOTALL
497
+ )
498
+ if page_size_var_match:
499
+ errors.append(_issue(
500
+ "PAGE_SIZE_CSS_VAR",
501
+ "@page { size } uses CSS variables (var(...)). Chromium does NOT resolve "
502
+ "CSS variables in @page rules — the page size will silently fallback to A4, "
503
+ "causing content to be off-center. Use concrete px values instead: "
504
+ "@page { size: 720px 960px; }",
505
+ severity="error"
506
+ ))
507
+
508
+ # ---- 5. WHITE_BACKGROUND ----
509
+ _has_styled_bg = False
510
+ for css_text, _ in all_css_positions:
511
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
512
+ selector_raw = rule_m.group(1).strip().lower()
513
+ body = rule_m.group(2)
514
+ selectors = [s.strip() for s in selector_raw.split(",")]
515
+ if any(s in ("body", "html", ":root") for s in selectors):
516
+ bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body, re.IGNORECASE)
517
+ if bg_m:
518
+ val = bg_m.group(1).strip().lower()
519
+ if val in ("white", "#fff", "#ffffff", "transparent", "rgba(0,0,0,0)",
520
+ "rgba(255,255,255,1)", "rgb(255,255,255)"):
521
+ pass # still "white"-ish
522
+ else:
523
+ _has_styled_bg = True
524
+ if not _has_styled_bg:
525
+ warnings.append(_issue(
526
+ "WHITE_BACKGROUND",
527
+ "body/html has white, transparent, or no background. "
528
+ "Posters typically need a styled background colour or gradient.",
529
+ severity="warning"
530
+ ))
531
+
532
+ # ---- 6. TINY_FONT ----
533
+ for css_text, css_offset in all_css_positions:
534
+ for m in _RE_FONT_SIZE.finditer(css_text):
535
+ size = float(m.group(1))
536
+ unit = m.group(2).lower()
537
+ # Convert to rough px
538
+ if unit == "pt":
539
+ size_px = size * (4 / 3)
540
+ elif unit in ("em", "rem"):
541
+ size_px = size * 16 # assume base 16px
542
+ else:
543
+ size_px = size
544
+ if size_px < 10:
545
+ abs_pos = css_offset + m.start()
546
+ ln = _line_number(original, abs_pos)
547
+ warnings.append(_issue(
548
+ "TINY_FONT",
549
+ f"font-size: {m.group(1)}{m.group(2)} ({size_px:.0f}px) may be unreadable in PDF output.",
550
+ severity="warning", line=ln
551
+ ))
552
+
553
+ # ---- 7. COLOR_CONTRAST ----
554
+ _checked_pairs: set[tuple] = set()
555
+ for css_text, css_offset in all_css_positions:
556
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
557
+ body = rule_m.group(2)
558
+ fg = _extract_color(body, "color")
559
+ bg = _extract_color(body, "background(?:-color)?")
560
+ if fg and bg:
561
+ pair = (fg, bg)
562
+ if pair not in _checked_pairs:
563
+ _checked_pairs.add(pair)
564
+ ratio = _contrast_ratio(fg, bg)
565
+ if ratio < 3.0:
566
+ abs_pos = css_offset + rule_m.start()
567
+ ln = _line_number(original, abs_pos)
568
+ warnings.append(_issue(
569
+ "COLOR_CONTRAST",
570
+ f"Text color rgb{fg} on background rgb{bg} has contrast ratio "
571
+ f"{ratio:.1f}:1 (< 3:1 minimum). May be hard to read.",
572
+ severity="warning", line=ln
573
+ ))
574
+
575
+ # ---- 8. MISSING_PRINT_BG_NOTE ----
576
+ info.append(_issue(
577
+ "MISSING_PRINT_BG_NOTE",
578
+ "Remember to set print_background=True when calling page.pdf() in Playwright, "
579
+ "otherwise CSS backgrounds won't render.",
580
+ severity="info"
581
+ ))
582
+
583
+ # ---- 9. OVERFLOW_DECORATION ----
584
+ # Detect decorative position:absolute elements that might overflow body width
585
+ # Look for patterns like: left: -50px, right: -100px, left: 120%, transform: translateX(...)
586
+ _overflow_positions = re.findall(
587
+ r'(?:left|right)\s*:\s*(-\d+(?:\.\d+)?(?:px|%|rem|em))\s*;',
588
+ all_css, re.IGNORECASE
589
+ ) if all_css else []
590
+ for pos_val in _overflow_positions:
591
+ if pos_val.startswith('-') or (pos_val.endswith('%') and float(re.match(r'-?[\d.]+', pos_val).group()) > 100):
592
+ warnings.append(_issue(
593
+ "OVERFLOW_DECORATION",
594
+ f"CSS position '{pos_val}' may push decorative elements outside body width, "
595
+ "causing black edges in PDF. Keep absolute-positioned elements within [0, body_width].",
596
+ severity="warning"
597
+ ))
598
+ break # Only warn once
599
+
600
+ # ---- 10. BG_COLOR_MISMATCH ----
601
+ # Check if body/html background matches main content container background
602
+ _body_bg = None
603
+ _canvas_bg = None
604
+ for css_text, css_offset in all_css_positions:
605
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
606
+ selector_raw = rule_m.group(1).strip().lower()
607
+ body_text = rule_m.group(2)
608
+ selectors = [s.strip() for s in selector_raw.split(",")]
609
+ bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
610
+ if bg_m:
611
+ bg_val = bg_m.group(1).strip().lower()
612
+ if any(s in ("body", "html") for s in selectors):
613
+ _body_bg = bg_val
614
+ if any(s in (".canvas", ".poster", ".poster-container", ".page") for s in selectors):
615
+ _canvas_bg = bg_val
616
+ # Helper: normalize a CSS background value to (r,g,b) for comparison.
617
+ # Returns None if value uses var(), gradient, url(), or unparseable.
618
+ def _bg_to_rgb(val: str):
619
+ if not val:
620
+ return None
621
+ v = val.strip().lower()
622
+ # Skip CSS variables, gradients, url() — can't compare reliably
623
+ if v.startswith("var(") or "gradient" in v or "url(" in v:
624
+ return None
625
+ # Use _extract_color machinery: wrap as "background: <val>" and extract
626
+ return _extract_color(f"background: {val};", "background")
627
+
628
+ _body_bg_rgb = _bg_to_rgb(_body_bg)
629
+ _canvas_bg_rgb = _bg_to_rgb(_canvas_bg)
630
+
631
+ if _body_bg and _canvas_bg and _body_bg != _canvas_bg:
632
+ # Skip if either uses CSS variables / gradients (can't reliably compare)
633
+ if _body_bg_rgb is not None and _canvas_bg_rgb is not None:
634
+ if _body_bg_rgb != _canvas_bg_rgb:
635
+ warnings.append(_issue(
636
+ "BG_COLOR_MISMATCH",
637
+ f"body background '{_body_bg}' differs from content container background "
638
+ f"'{_canvas_bg}'. This may cause visible color borders in PDF output. "
639
+ "Ensure html/body background matches the poster canvas color.",
640
+ severity="warning"
641
+ ))
642
+ # else: unparseable (var/gradient/url) → skip, no warning
643
+
644
+ # ---- 10b. SCREEN_BG_MISMATCH ----
645
+ # Check if @media screen html background matches body/canvas background
646
+ # Parse @media screen independently (check 2b only runs for fixed-size pages)
647
+ _screen_has_media = bool(re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE))
648
+ _screen_content = ""
649
+ if _screen_has_media:
650
+ _ms_m = re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE)
651
+ if _ms_m:
652
+ _d = 1
653
+ _s = _ms_m.end()
654
+ for _ci in range(_s, len(all_css)):
655
+ if all_css[_ci] == '{':
656
+ _d += 1
657
+ elif all_css[_ci] == '}':
658
+ _d -= 1
659
+ if _d == 0:
660
+ _screen_content = all_css[_s:_ci]
661
+ break
662
+ if _screen_has_media and _screen_content:
663
+ _screen_html_bg = None
664
+ for rule_m in _RE_CSS_RULE.finditer(_screen_content):
665
+ selector_raw = rule_m.group(1).strip().lower()
666
+ body_text = rule_m.group(2)
667
+ selectors = [s.strip() for s in selector_raw.split(",")]
668
+ if any(s in ("html",) for s in selectors):
669
+ bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
670
+ if bg_m:
671
+ _screen_html_bg = bg_m.group(1).strip().lower()
672
+ _ref_bg = _body_bg or _canvas_bg
673
+ if _screen_html_bg and _ref_bg and _screen_html_bg != _ref_bg:
674
+ # Normalize to RGB for comparison (skip if either is var/gradient/url)
675
+ _screen_rgb = _bg_to_rgb(_screen_html_bg)
676
+ _ref_rgb = _bg_to_rgb(_ref_bg)
677
+ if _screen_rgb is not None and _ref_rgb is not None:
678
+ if _screen_rgb != _ref_rgb:
679
+ warnings.append(_issue(
680
+ "SCREEN_BG_MISMATCH",
681
+ f"@media screen html background '{_screen_html_bg}' differs from "
682
+ f"body/canvas background '{_ref_bg}'. Browser preview will show "
683
+ "a different color border around the poster. "
684
+ "Set @media screen html background to match the poster background.",
685
+ severity="warning"
686
+ ))
687
+ # else: unparseable (var/gradient) → skip
688
+ if _is_fixed_size_page and not _screen_html_bg:
689
+ # Check if body/html already sets background globally (would be inherited)
690
+ # If so, @media screen doesn't need its own background
691
+ if not _body_bg:
692
+ warnings.append(_issue(
693
+ "SCREEN_NO_BG",
694
+ "@media screen block exists but html has no explicit background color "
695
+ "(neither globally nor in @media screen). "
696
+ "Browser preview may show white borders around the poster. "
697
+ "Add: @media screen { html { background: <poster-bg-color>; } }",
698
+ severity="warning"
699
+ ))
700
+ # ---- 10c. MULTIPAGE_BODY_BG_MISSING ----
701
+ # Multi-page documents with dark/colored .page backgrounds but no body background
702
+ # → sub-pixel gap between .page and @page reveals white body, causing white edges
703
+ _has_colored_page = False
704
+ # Resolve CSS variables from :root for var() expansion
705
+ _css_vars = {}
706
+ for css_text, _ in all_css_positions:
707
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
708
+ sel = rule_m.group(1).strip().lower()
709
+ if ":root" in sel:
710
+ for vm in re.finditer(r"--(\w[\w-]*)\s*:\s*([^;]+)", rule_m.group(2)):
711
+ _css_vars[vm.group(1)] = vm.group(2).strip()
712
+
713
+ def _resolve_bg(val):
714
+ """Resolve a CSS background value, expanding var() references once."""
715
+ v = val.strip().lower()
716
+ var_m = re.match(r"var\(--(\w[\w-]*)\)", v)
717
+ if var_m and var_m.group(1) in _css_vars:
718
+ return _css_vars[var_m.group(1)].strip().lower()
719
+ return v
720
+
721
+ for css_text, css_offset in all_css_positions:
722
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
723
+ selector_raw = rule_m.group(1).strip().lower()
724
+ body_text = rule_m.group(2)
725
+ selectors = [s.strip() for s in selector_raw.split(",")]
726
+ if any(".page" in s for s in selectors):
727
+ bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
728
+ if bg_m:
729
+ val = _resolve_bg(bg_m.group(1))
730
+ rgb = _bg_to_rgb(val)
731
+ if rgb is not None:
732
+ r_v, g_v, b_v = rgb
733
+ luminance = 0.299 * r_v + 0.587 * g_v + 0.114 * b_v
734
+ if luminance < 80:
735
+ _has_colored_page = True
736
+ elif "gradient" in val:
737
+ dark_hex = re.findall(r"#([0-9a-f]{3,6})", val)
738
+ for h in dark_hex:
739
+ if len(h) == 3:
740
+ h = h[0]*2 + h[1]*2 + h[2]*2
741
+ if len(h) == 6:
742
+ rv = int(h[0:2], 16)
743
+ gv = int(h[2:4], 16)
744
+ bv = int(h[4:6], 16)
745
+ if 0.299*rv + 0.587*gv + 0.114*bv < 80:
746
+ _has_colored_page = True
747
+ break
748
+ _page_div_count = len(re.findall(r'class\s*=\s*["\'][^"\']*\bpage\b', original, re.IGNORECASE))
749
+ if _page_div_count >= 2 and _has_colored_page and not _has_styled_bg:
750
+ warnings.append(_issue(
751
+ "MULTIPAGE_BODY_BG_MISSING",
752
+ "Multi-page document has dark/colored .page backgrounds but html/body has no "
753
+ "explicit background color. Playwright sub-pixel rounding creates <1px gaps "
754
+ "at .page edges where body background shows through — white body = visible "
755
+ "white edges on dark pages. Fix: set html,body { background: <darkest-page-color> }.",
756
+ severity="warning"
757
+ ))
758
+ # ---- 11. HEIGHT_LOCKED ----
759
+ # Check if content containers use height:100% instead of min-height
760
+ _height_locked_selectors = set()
761
+ # Selectors that are content containers (not SVG/img/shape)
762
+ _content_containers = {".glass-canvas", ".shaped-canvas", ".process-list-container",
763
+ ".process-list", ".grid-item", ".stat-block", ".delta-widget"}
764
+ for css_text, css_offset in all_css_positions:
765
+ for rule_m in _RE_CSS_RULE.finditer(css_text):
766
+ selector_raw = rule_m.group(1).strip()
767
+ body_text = rule_m.group(2)
768
+ # Check for height: 100% (not min-height)
769
+ if re.search(r"(?<!min-)height\s*:\s*100%", body_text, re.IGNORECASE):
770
+ selectors = [s.strip().lower() for s in selector_raw.split(",")]
771
+ for sel in selectors:
772
+ base_sel = re.split(r"[:>\s+~]", sel)[0].strip()
773
+ # Skip non-content elements
774
+ if base_sel in (".bg-layer", "svg", "img", ".shape-float",
775
+ ".shape-circle", ".shape-wave", ".shape-diagonal_slash",
776
+ ".shape-diamond", ".shape-wedge_right"):
777
+ continue
778
+ if base_sel in _content_containers:
779
+ _height_locked_selectors.add(base_sel)
780
+ # Also check inline styles
781
+ for m in re.finditer(r'class\s*=\s*["\']([^"\']*)["\']\s*[^>]*style\s*=\s*["\']([^"\']*)["\']', raw, re.IGNORECASE):
782
+ classes = m.group(1).lower().split()
783
+ style = m.group(2)
784
+ if re.search(r"(?<!min-)height\s*:\s*100%", style, re.IGNORECASE):
785
+ for cls in classes:
786
+ dotcls = f".{cls}"
787
+ if dotcls in _content_containers:
788
+ _height_locked_selectors.add(dotcls)
789
+ if _height_locked_selectors:
790
+ warnings.append(_issue(
791
+ "HEIGHT_LOCKED",
792
+ f"Content containers {', '.join(sorted(_height_locked_selectors))} use 'height: 100%' "
793
+ "instead of 'min-height: 100%'. This locks the container height and may clip content "
794
+ "when it exceeds the allocated grid area. Use 'min-height: 100%' to allow content to grow.",
795
+ severity="warning"
796
+ ))
797
+
798
+ # ---- Apply all fixes (unified, avoids offset corruption) ----
799
+ # Apply larger replacements (full CSS rules like overflow fixes) before smaller
800
+ # ones (font-family declarations), so the larger match strings are still valid.
801
+ # Sort by length of old_text descending to ensure this order.
802
+ if fix and _all_fixes:
803
+ _all_fixes.sort(key=lambda pair: len(pair[0]), reverse=True)
804
+ for old_text, new_text in _all_fixes:
805
+ if old_text in raw:
806
+ raw = raw.replace(old_text, new_text, 1)
807
+
808
+ # ---- Build report ----
809
+ has_errors = len(errors) > 0
810
+ report: dict[str, Any] = {
811
+ "pass": not has_errors,
812
+ "source": html_path,
813
+ "check_type": "html",
814
+ "errors": errors,
815
+ "warnings": warnings,
816
+ "info": info,
817
+ }
818
+
819
+ # ---- Fix mode output ----
820
+ if fix:
821
+ if output_path:
822
+ Path(output_path).write_text(raw, encoding="utf-8")
823
+ report["fixed_file"] = output_path
824
+ else:
825
+ # Write fixed HTML to stdout after the JSON report to stderr
826
+ report["fixed_output"] = "stdout"
827
+ # We'll handle this in main()
828
+
829
+ report["_fixed_html"] = raw if fix else None
830
+ return report
831
+
832
+
833
+ # ---------------------------------------------------------------------------
834
+ # CHECK-PDF
835
+ # ---------------------------------------------------------------------------
836
+
837
+ def check_pdf(pdf_path: str, *, source_html: str | None = None, poster: bool = False) -> dict:
838
+ """Run all PDF post-checks. Return the JSON-serialisable report dict."""
839
+
840
+ path = Path(pdf_path)
841
+ errors: list[dict] = []
842
+ warnings: list[dict] = []
843
+ info: list[dict] = []
844
+
845
+ if not path.is_file():
846
+ return {"pass": False, "source": pdf_path, "check_type": "pdf",
847
+ "errors": [_issue("FILE_NOT_FOUND", f"Cannot read '{pdf_path}'.")],
848
+ "warnings": [], "info": []}
849
+
850
+ # ---- 1. FILE_TOO_SMALL ----
851
+ file_size = path.stat().st_size
852
+ if file_size < 10 * 1024:
853
+ errors.append(_issue(
854
+ "FILE_TOO_SMALL",
855
+ f"PDF is only {file_size} bytes ({file_size/1024:.1f} KB). "
856
+ "Likely empty or broken.",
857
+ ))
858
+
859
+ # ---- Import pdfplumber ----
860
+ try:
861
+ import pdfplumber
862
+ except ImportError:
863
+ errors.append(_issue(
864
+ "DEPENDENCY_MISSING",
865
+ "pdfplumber is not installed. Cannot perform PDF text checks. "
866
+ "Install with: pip install pdfplumber",
867
+ ))
868
+ return {"pass": False, "source": pdf_path, "check_type": "pdf",
869
+ "errors": errors, "warnings": warnings, "info": info}
870
+
871
+ # ---- Open PDF ----
872
+ try:
873
+ pdf = pdfplumber.open(str(path))
874
+ except Exception as exc:
875
+ errors.append(_issue(
876
+ "PDF_UNREADABLE",
877
+ f"Cannot open PDF: {exc}",
878
+ ))
879
+ return {"pass": False, "source": pdf_path, "check_type": "pdf",
880
+ "errors": errors, "warnings": warnings, "info": info}
881
+
882
+ pages = pdf.pages
883
+
884
+ # ---- 2. TEXT_MISSING (requires source HTML) ----
885
+ pdf_text_parts: list[str] = []
886
+ page_char_counts: list[int] = []
887
+
888
+ for page in pages:
889
+ try:
890
+ txt = page.extract_text() or ""
891
+ except Exception:
892
+ txt = ""
893
+ pdf_text_parts.append(txt)
894
+ meaningful = len(re.sub(r"\s", "", txt))
895
+ page_char_counts.append(meaningful)
896
+
897
+ pdf_chars = sum(page_char_counts)
898
+
899
+ if source_html:
900
+ html_p = Path(source_html)
901
+ if html_p.is_file():
902
+ html_raw = html_p.read_text(encoding="utf-8", errors="replace")
903
+ html_text = _html_visible_text(html_raw)
904
+ html_chars = len(re.sub(r"\s", "", html_text))
905
+
906
+ if html_chars > 0 and pdf_chars < html_chars * 0.30:
907
+ errors.append(_issue(
908
+ "TEXT_MISSING",
909
+ f"PDF contains only {pdf_chars} meaningful characters vs {html_chars} in "
910
+ f"source HTML ({pdf_chars/html_chars*100:.0f}%). "
911
+ "Fonts may have failed to load during rendering.",
912
+ ))
913
+ else:
914
+ warnings.append(_issue(
915
+ "SOURCE_HTML_NOT_FOUND",
916
+ f"Source HTML '{source_html}' not found; skipping TEXT_MISSING check.",
917
+ severity="warning"
918
+ ))
919
+
920
+ # ---- 3. DIMENSIONS_UNREASONABLE ----
921
+ for i, page in enumerate(pages):
922
+ w = page.width # in points
923
+ h = page.height
924
+ if w < 200 or h < 200:
925
+ warnings.append(_issue(
926
+ "DIMENSIONS_UNREASONABLE",
927
+ f"Page {i+1} dimensions are {w:.0f}×{h:.0f}pt "
928
+ f"({w/72:.1f}×{h/72:.1f}in). Unusually small for a poster.",
929
+ severity="warning"
930
+ ))
931
+ break # only warn once
932
+
933
+ # ---- 4. ORPHAN_PAGE ----
934
+ # Skip for poster mode: seamlessly-paginated posters naturally have less content on the last page
935
+ if not poster and len(pages) > 1:
936
+ avg_chars = sum(page_char_counts[:-1]) / max(len(page_char_counts) - 1, 1)
937
+ last_chars = page_char_counts[-1]
938
+ if avg_chars > 0 and last_chars < avg_chars * 0.10:
939
+ warnings.append(_issue(
940
+ "ORPHAN_PAGE",
941
+ f"Last page (page {len(pages)}) has very little content "
942
+ f"({last_chars} chars vs avg {avg_chars:.0f}). "
943
+ "This may indicate accidental overflow. Check your page sizing.",
944
+ severity="warning"
945
+ ))
946
+
947
+ pdf.close()
948
+
949
+ has_errors = len(errors) > 0
950
+ return {
951
+ "pass": not has_errors,
952
+ "source": pdf_path,
953
+ "check_type": "pdf",
954
+ "errors": errors,
955
+ "warnings": warnings,
956
+ "info": info,
957
+ }
958
+
959
+
960
+ # ---------------------------------------------------------------------------
961
+ # Utilities
962
+ # ---------------------------------------------------------------------------
963
+
964
+ def _truncate(s: str, max_len: int = 80) -> str:
965
+ return s if len(s) <= max_len else s[:max_len - 3] + "..."
966
+
967
+
968
+ # ---------------------------------------------------------------------------
969
+ # CLI
970
+ # ---------------------------------------------------------------------------
971
+ # LaTeX .tex file checks
972
+ # ---------------------------------------------------------------------------
973
+
974
+ def check_tex(tex_path: str) -> dict:
975
+ """Check a LaTeX .tex file for common issues, especially table overflow in dual-column layouts."""
976
+ errors = []
977
+ warnings = []
978
+ info = []
979
+
980
+ if not os.path.exists(tex_path):
981
+ return {"pass": False, "source": tex_path, "check_type": "tex",
982
+ "errors": [_issue("FILE_NOT_FOUND", f"File not found: {tex_path}")], "warnings": [], "info": []}
983
+
984
+ with open(tex_path, "r", encoding="utf-8", errors="replace") as f:
985
+ content = f.read()
986
+
987
+ lines = content.split("\n")
988
+
989
+ # Detect if this is a two-column document
990
+ is_twocolumn = bool(re.search(
991
+ r"\\documentclass\[.*?twocolumn.*?\]"
992
+ r"|\\twocolumn"
993
+ r"|\\begin\{multicols\}"
994
+ r"|IEEEtran|acmart|sig-alternate",
995
+ content, re.IGNORECASE
996
+ ))
997
+
998
+ # ---- 1. BARE_TABULAR_IN_TWOCOLUMN ----
999
+ # Find \begin{tabular} not wrapped in resizebox/adjustbox/tabularx/tabular*
1000
+ # and not inside a table* (full-width) environment
1001
+ if is_twocolumn:
1002
+ info.append(_issue("TWOCOLUMN_DETECTED",
1003
+ "Two-column layout detected. Checking tables for overflow risk.",
1004
+ severity="info"))
1005
+
1006
+ # Parse all tabular environments with line numbers
1007
+ tabular_pattern = re.compile(r"\\begin\{tabular\}\s*\{([^}]*)\}", re.IGNORECASE)
1008
+ for i, line in enumerate(lines, 1):
1009
+ m = tabular_pattern.search(line)
1010
+ if not m:
1011
+ continue
1012
+
1013
+ col_spec = m.group(1)
1014
+ # Count data columns (l, c, r, p{}, X — skip @{}, |, >{}, <{})
1015
+ col_count = len(re.findall(r"[lcrX]|p\{[^}]*\}", col_spec))
1016
+
1017
+ # Check if this tabular is wrapped in protective environments
1018
+ # Look backwards up to 10 lines for wrapping context
1019
+ context_start = max(0, i - 11)
1020
+ context = "\n".join(lines[context_start:i])
1021
+ has_resizebox = bool(re.search(r"\\resizebox", context))
1022
+ has_adjustbox = bool(re.search(r"\\adjustbox|\\begin\{adjustbox\}", context))
1023
+ has_table_star = bool(re.search(r"\\begin\{table\*\}", context))
1024
+ has_makebox = bool(re.search(r"\\makebox\[.*?\\textwidth\]", context))
1025
+ is_protected = has_resizebox or has_adjustbox or has_table_star or has_makebox
1026
+
1027
+ if is_twocolumn and col_count >= 5 and not is_protected:
1028
+ errors.append(_issue(
1029
+ "BARE_TABULAR_OVERFLOW",
1030
+ f"Line {i}: \\begin{{tabular}} with {col_count} columns in a two-column document, "
1031
+ f"not wrapped in resizebox/adjustbox/table*. This WILL overflow \\columnwidth. "
1032
+ f"Fix: use tabularx{{\\columnwidth}}, or wrap in \\resizebox{{\\columnwidth}}{{!}}{{...}}, "
1033
+ f"or use table* for full-width.",
1034
+ severity="error"
1035
+ ))
1036
+ elif is_twocolumn and col_count >= 4 and not is_protected:
1037
+ warnings.append(_issue(
1038
+ "TABULAR_OVERFLOW_RISK",
1039
+ f"Line {i}: \\begin{{tabular}} with {col_count} columns in two-column layout. "
1040
+ f"May overflow \\columnwidth depending on content width. "
1041
+ f"Consider tabularx{{\\columnwidth}} or \\small font size.",
1042
+ severity="warning"
1043
+ ))
1044
+ elif not is_twocolumn and col_count >= 7 and not is_protected:
1045
+ warnings.append(_issue(
1046
+ "TABULAR_WIDE",
1047
+ f"Line {i}: \\begin{{tabular}} with {col_count} columns. "
1048
+ f"May overflow \\textwidth. Consider tabularx or resizebox.",
1049
+ severity="warning"
1050
+ ))
1051
+
1052
+ # ---- 2. TABULAR_WITHOUT_TABLE ----
1053
+ # tabular not inside table/table* environment (no caption, no float)
1054
+ for i, line in enumerate(lines, 1):
1055
+ if re.search(r"\\begin\{tabular\}", line):
1056
+ context_start = max(0, i - 6)
1057
+ context = "\n".join(lines[context_start:i])
1058
+ if not re.search(r"\\begin\{table\*?\}", context):
1059
+ warnings.append(_issue(
1060
+ "TABULAR_NO_FLOAT",
1061
+ f"Line {i}: \\begin{{tabular}} not inside a table/table* float environment. "
1062
+ f"Table will be inline (no caption, no \\label, no float positioning).",
1063
+ severity="warning"
1064
+ ))
1065
+
1066
+ # ---- 3. PREFER_TABULARX ----
1067
+ # Check if tabularx is loaded in preamble
1068
+ has_tabularx_pkg = bool(re.search(r"\\usepackage.*\{tabularx\}", content))
1069
+ tabular_count = len(re.findall(r"\\begin\{tabular\}", content))
1070
+ tabularx_count = len(re.findall(r"\\begin\{tabularx\}", content))
1071
+ tabular_star_count = len(re.findall(r"\\begin\{tabular\*\}", content))
1072
+
1073
+ if tabular_count > 0 and tabularx_count == 0 and tabular_star_count == 0:
1074
+ if not has_tabularx_pkg:
1075
+ warnings.append(_issue(
1076
+ "TABULARX_NOT_LOADED",
1077
+ f"Document has {tabular_count} tabular environment(s) but tabularx package is not loaded. "
1078
+ f"Add \\usepackage{{tabularx}} to preamble for auto-width column support.",
1079
+ severity="warning"
1080
+ ))
1081
+
1082
+ # ---- 4. IMAGE_NO_WIDTH ----
1083
+ # \includegraphics without width/max width constraint
1084
+ img_pattern = re.compile(r"\\includegraphics\s*(\[[^\]]*\])?\s*\{")
1085
+ for i, line in enumerate(lines, 1):
1086
+ m = img_pattern.search(line)
1087
+ if m:
1088
+ opts = m.group(1) or ""
1089
+ if not re.search(r"width|max width|scale|height", opts, re.IGNORECASE):
1090
+ warnings.append(_issue(
1091
+ "IMAGE_NO_WIDTH",
1092
+ f"Line {i}: \\includegraphics without width/height constraint. "
1093
+ f"Add [max width=\\columnwidth] or [width=\\columnwidth] to prevent overflow.",
1094
+ severity="warning"
1095
+ ))
1096
+
1097
+ # ---- 5. CJK_ASCII_QUOTES ----
1098
+ # Detect ASCII " adjacent to CJK characters (common LLM mistake).
1099
+ # LaTeX interprets " as right double quote, so "北漂" renders with two
1100
+ # right quotes. Chinese text must use Unicode smart quotes “…”.
1101
+ cjk_quote_pattern = re.compile(
1102
+ r'[\u4e00-\u9fff\u3400-\u4dbf]"'
1103
+ r'|"[\u4e00-\u9fff\u3400-\u4dbf]'
1104
+ )
1105
+ # Regex to strip inline command content that legitimately contains ASCII quotes
1106
+ _inline_cmd_re = re.compile(
1107
+ r'\\(?:texttt|url|path|lstinline)\{[^}]*\}'
1108
+ r'|\\href\{[^}]*\}\{[^}]*\}'
1109
+ r"|\\verb([|!@#])(.*?)\1"
1110
+ )
1111
+ # Track verbatim-like environments to skip
1112
+ in_verbatim = False
1113
+ for i, line in enumerate(lines, 1):
1114
+ # Skip comment lines
1115
+ if line.lstrip().startswith('%'):
1116
+ continue
1117
+ # Track verbatim/lstlisting/minted environments
1118
+ if re.search(r'\\begin\{(verbatim|lstlisting|minted|Verbatim|lstcode)\}', line):
1119
+ in_verbatim = True
1120
+ continue
1121
+ if re.search(r'\\end\{(verbatim|lstlisting|minted|Verbatim|lstcode)\}', line):
1122
+ in_verbatim = False
1123
+ continue
1124
+ if in_verbatim:
1125
+ continue
1126
+ # Strip inline command arguments that may legitimately contain ASCII quotes
1127
+ check_line = _inline_cmd_re.sub('', line)
1128
+ if cjk_quote_pattern.search(check_line):
1129
+ errors.append(_issue(
1130
+ "CJK_ASCII_QUOTES",
1131
+ f'Line {i}: ASCII \'"\' found adjacent to CJK characters. '
1132
+ f'LaTeX interprets " as right double quote (\u201d), so "\u5317\u6f02" renders as \u201d\u5317\u6f02\u201d. '
1133
+ f'Fix: use Unicode smart quotes \u201c\u5317\u6f02\u201d (U+201C / U+201D) for Chinese text. '
1134
+ f'(This check skips verbatim/lstlisting/minted environments and '
1135
+ f'\\texttt{{}}/\\url{{}}/\\href{{}}{{}}/\\verb|| inline commands.)',
1136
+ severity="error"
1137
+ ))
1138
+ break # One error is enough
1139
+
1140
+ # ---- 6. EQUATION_OVERFLOW_RISK ----
1141
+ # Detect equations that are likely too wide for dual-column
1142
+ if is_twocolumn:
1143
+ in_equation = False
1144
+ eq_start_line = 0
1145
+ eq_content = ""
1146
+ eq_env_name = ""
1147
+ eq_envs = ["equation", "displaymath"]
1148
+ for i, line in enumerate(lines, 1):
1149
+ stripped = line.strip()
1150
+ if stripped.startswith('%'):
1151
+ continue
1152
+ for env in eq_envs:
1153
+ if f"\\begin{{{env}}}" in stripped:
1154
+ in_equation = True
1155
+ eq_start_line = i
1156
+ eq_content = ""
1157
+ eq_env_name = env
1158
+ if f"\\end{{{env}}}" in stripped and in_equation:
1159
+ in_equation = False
1160
+ # Check for two equations joined by \quad on same line
1161
+ if re.search(r'\\quad\s*\\math', eq_content) or eq_content.count('=') >= 2:
1162
+ if '\\\\' not in eq_content and 'aligned' not in eq_content and 'split' not in eq_content:
1163
+ warnings.append(_issue(
1164
+ "EQUATION_DUAL_ON_LINE",
1165
+ f"Line {eq_start_line}: {eq_env_name} environment contains multiple equations "
1166
+ f"joined by \\quad (or 2+ '=' signs) without line breaks. "
1167
+ f"In dual-column format this will overflow. "
1168
+ f"Fix: use align/split/aligned environment with \\\\ line breaks.",
1169
+ severity="warning"
1170
+ ))
1171
+ # Check for very long equation content
1172
+ math_len = len(re.sub(r'\\[a-zA-Z]+|\s|\{|\}|\[|\]|\^|_', '', eq_content))
1173
+ if math_len > 80:
1174
+ warnings.append(_issue(
1175
+ "EQUATION_OVERFLOW_RISK",
1176
+ f"Line {eq_start_line}: {eq_env_name} has ~{math_len} math chars "
1177
+ f"(threshold 80). Likely overflows single column. "
1178
+ f"Consider split, multline, or factoring out sub-expressions.",
1179
+ severity="warning"
1180
+ ))
1181
+ if in_equation:
1182
+ eq_content += stripped + " "
1183
+
1184
+ # ---- 7. RESIZEBOX_TEXTWIDTH_IN_TWOCOLUMN ----
1185
+ # \resizebox{\textwidth} inside table (not table*) in twocolumn
1186
+ if is_twocolumn:
1187
+ in_table_star = False
1188
+ for i, line in enumerate(lines, 1):
1189
+ stripped = line.strip()
1190
+ if '\\begin{table*}' in stripped:
1191
+ in_table_star = True
1192
+ if '\\end{table*}' in stripped:
1193
+ in_table_star = False
1194
+ if not in_table_star and '\\resizebox' in stripped and '\\textwidth' in stripped:
1195
+ errors.append(_issue(
1196
+ "RESIZEBOX_TEXTWIDTH",
1197
+ f"Line {i}: \\resizebox{{\\textwidth}} used inside single-column float. "
1198
+ f"In two-column layouts, \\textwidth = full page width (~504pt), but "
1199
+ f"a table float is only one column (~252pt). This causes ~50% overflow. "
1200
+ f"Fix: use \\resizebox{{\\columnwidth}}{{!}} for single-column, "
1201
+ f"or change to table* for full-width.",
1202
+ severity="error"
1203
+ ))
1204
+
1205
+ # ---- 8. ALGORITHM_OVERFLOW_RISK ----
1206
+ if is_twocolumn:
1207
+ in_algo = False
1208
+ algo_start = 0
1209
+ has_small_font = False
1210
+ for i, line in enumerate(lines, 1):
1211
+ if '\\SetAlFnt' in line and '\\small' in line:
1212
+ has_small_font = True
1213
+ if '\\begin{algorithm}' in line and '\\begin{algorithm*}' not in line:
1214
+ in_algo = True
1215
+ algo_start = i
1216
+ if '\\end{algorithm}' in line and in_algo:
1217
+ in_algo = False
1218
+ if not has_small_font:
1219
+ warnings.append(_issue(
1220
+ "ALGORITHM_NO_SMALL_FONT",
1221
+ f"Line {algo_start}: algorithm environment in dual-column without \\SetAlFnt{{\\small}}. "
1222
+ f"Algorithm text at default size frequently overflows narrow columns. "
1223
+ f"Add \\SetAlFnt{{\\small}} before the algorithm.",
1224
+ severity="warning"
1225
+ ))
1226
+ # Check for very long KwInput/KwOutput lines
1227
+ if in_algo and ('\\KwInput' in line or '\\KwOutput' in line or '\\KwIn' in line or '\\KwOut' in line):
1228
+ content_len = len(line.strip())
1229
+ if content_len > 120:
1230
+ warnings.append(_issue(
1231
+ "ALGORITHM_LONG_IO",
1232
+ f"Line {i}: Algorithm Input/Output line is {content_len} chars (threshold 120). "
1233
+ f"Long I/O lines overflow column width. Break into multiple lines with \\\\ or "
1234
+ f"abbreviate parameter names.",
1235
+ severity="warning"
1236
+ ))
1237
+
1238
+ # Summary info
1239
+ info.append(_issue(
1240
+ "TABLE_SUMMARY",
1241
+ f"Tables: {tabular_count} tabular, {tabularx_count} tabularx, {tabular_star_count} tabular*. "
1242
+ f"Two-column: {'yes' if is_twocolumn else 'no'}.",
1243
+ severity="info"
1244
+ ))
1245
+
1246
+ has_errors = any(e["severity"] == "error" for e in errors)
1247
+ return {
1248
+ "pass": not has_errors,
1249
+ "source": tex_path,
1250
+ "check_type": "tex",
1251
+ "errors": errors,
1252
+ "warnings": warnings,
1253
+ "info": info,
1254
+ }
1255
+
1256
+
1257
+ # ---------------------------------------------------------------------------
1258
+
1259
+ def main() -> int:
1260
+ parser = argparse.ArgumentParser(
1261
+ description="Validate poster HTML/PDF for common quality issues."
1262
+ )
1263
+ sub = parser.add_subparsers(dest="command")
1264
+
1265
+ # -- check-html --
1266
+ p_html = sub.add_parser("check-html", help="Pre-check an HTML file before PDF generation.")
1267
+ p_html.add_argument("html_file", help="Path to the HTML file.")
1268
+ p_html.add_argument("--fix", action="store_true",
1269
+ help="Auto-fix issues where possible and output corrected HTML.")
1270
+ p_html.add_argument("--output", "-o", default=None,
1271
+ help="Write fixed HTML to this file (default: stdout).")
1272
+
1273
+ # -- check-pdf --
1274
+ p_pdf = sub.add_parser("check-pdf", help="Post-check a generated PDF file.")
1275
+ p_pdf.add_argument("pdf_file", help="Path to the PDF file.")
1276
+ p_pdf.add_argument("--source-html", default=None,
1277
+ help="Path to the source HTML (enables TEXT_MISSING check).")
1278
+ p_pdf.add_argument("--poster", action="store_true",
1279
+ help="Poster mode: suppress ORPHAN_PAGE for seamlessly-paginated posters.")
1280
+
1281
+ # -- check-tex --
1282
+ p_tex = sub.add_parser("check-tex", help="Check a LaTeX .tex file for common issues (table overflow, etc.).")
1283
+ p_tex.add_argument("tex_file", help="Path to the .tex file.")
1284
+
1285
+ args = parser.parse_args()
1286
+
1287
+ if not args.command:
1288
+ parser.print_help()
1289
+ return 2
1290
+
1291
+ try:
1292
+ if args.command == "check-html":
1293
+ report = check_html(
1294
+ args.html_file,
1295
+ fix=args.fix,
1296
+ output_path=args.output,
1297
+ )
1298
+ fixed_html = report.pop("_fixed_html", None)
1299
+
1300
+ if args.fix and fixed_html and not args.output:
1301
+ # JSON report goes to stderr, fixed HTML to stdout
1302
+ print(json.dumps(report, indent=2, ensure_ascii=False), file=sys.stderr)
1303
+ print(fixed_html)
1304
+ else:
1305
+ report.pop("_fixed_html", None)
1306
+ print(json.dumps(report, indent=2, ensure_ascii=False))
1307
+
1308
+ return 0 if report["pass"] else 1
1309
+
1310
+ elif args.command == "check-pdf":
1311
+ report = check_pdf(
1312
+ args.pdf_file,
1313
+ source_html=args.source_html,
1314
+ poster=getattr(args, 'poster', False),
1315
+ )
1316
+ print(json.dumps(report, indent=2, ensure_ascii=False))
1317
+ return 0 if report["pass"] else 1
1318
+
1319
+ elif args.command == "check-tex":
1320
+ report = check_tex(args.tex_file)
1321
+ print(json.dumps(report, indent=2, ensure_ascii=False))
1322
+ return 0 if report["pass"] else 1
1323
+
1324
+ except Exception as exc:
1325
+ err_report = {
1326
+ "pass": False,
1327
+ "error": f"Script error: {exc}",
1328
+ "check_type": args.command.replace("check-", ""),
1329
+ }
1330
+ print(json.dumps(err_report, indent=2, ensure_ascii=False), file=sys.stderr)
1331
+ return 2
1332
+
1333
+ return 0
1334
+
1335
+
1336
+ if __name__ == "__main__":
1337
+ sys.exit(main())