cocheck 0.0.0-stage → 0.4.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 (348) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +118 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/bin/cocheck.mjs +8 -0
  5. package/dist/agent-transcripts.js +544 -0
  6. package/dist/attribution/basis.js +31 -0
  7. package/dist/attribution/evidence.js +312 -0
  8. package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
  9. package/dist/attribution/hooks/sitecustomize.py +245 -0
  10. package/dist/attribution/names.js +163 -0
  11. package/dist/attribution/reconstruct.js +147 -0
  12. package/dist/attribution/tag.js +246 -0
  13. package/dist/attribution/write-scope-win.js +615 -0
  14. package/dist/attribution/write-scope.js +1668 -0
  15. package/dist/build-info.json +1 -0
  16. package/dist/cli-main.js +8 -0
  17. package/dist/cli.js +213 -0
  18. package/dist/codex-config.js +107 -0
  19. package/dist/connector/after-gap.js +56 -0
  20. package/dist/connector/after-snapshot.js +244 -0
  21. package/dist/connector/before-snapshot.js +168 -0
  22. package/dist/connector/builtins.js +93 -0
  23. package/dist/connector/changes-v1.js +276 -0
  24. package/dist/connector/claimed-state.js +40 -0
  25. package/dist/connector/claimed.js +86 -0
  26. package/dist/connector/conformance.js +458 -0
  27. package/dist/connector/diff-object.js +81 -0
  28. package/dist/connector/diff-samples.js +64 -0
  29. package/dist/connector/diff.js +273 -0
  30. package/dist/connector/doc-level.js +20 -0
  31. package/dist/connector/enabled-types.js +87 -0
  32. package/dist/connector/export-view.js +13 -0
  33. package/dist/connector/file-capture.js +265 -0
  34. package/dist/connector/frozen.js +213 -0
  35. package/dist/connector/installed-manifests.js +72 -0
  36. package/dist/connector/installed-match.js +161 -0
  37. package/dist/connector/local-process.js +119 -0
  38. package/dist/connector/nothing-changed-rule.js +23 -0
  39. package/dist/connector/old-rows.js +66 -0
  40. package/dist/connector/png-pixels.js +4 -0
  41. package/dist/connector/registry.js +78 -0
  42. package/dist/connector/requires.js +30 -0
  43. package/dist/connector/row-doc.js +54 -0
  44. package/dist/connector/run-argv.js +25 -0
  45. package/dist/connector/runner.js +325 -0
  46. package/dist/connector/schema.js +242 -0
  47. package/dist/connector/subject.js +8 -0
  48. package/dist/connector/subjects.js +113 -0
  49. package/dist/connector/validate.js +200 -0
  50. package/dist/connector-auth.js +101 -0
  51. package/dist/connector-create.js +55 -0
  52. package/dist/connector-doctor.js +167 -0
  53. package/dist/connector-test-cli.js +627 -0
  54. package/dist/connector-types-cli.js +43 -0
  55. package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
  56. package/dist/connectors/microsoft-excel/connector.mjs +11 -0
  57. package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
  58. package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
  59. package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
  60. package/dist/connectors/microsoft-word/connector.mjs +11 -0
  61. package/dist/copies.js +151 -0
  62. package/dist/coverage.js +279 -0
  63. package/dist/credit-guard.js +335 -0
  64. package/dist/display.js +78 -0
  65. package/dist/file-lock.js +145 -0
  66. package/dist/fingerprint.js +25 -0
  67. package/dist/formats/files/align.js +84 -0
  68. package/dist/formats/files/csv.js +78 -0
  69. package/dist/formats/files/layer.js +274 -0
  70. package/dist/formats/files/scan.js +86 -0
  71. package/dist/formats/files/textlike.js +21 -0
  72. package/dist/formats/layer.js +48 -0
  73. package/dist/harness-cmd/create.js +76 -0
  74. package/dist/harness-cmd/index.js +19 -0
  75. package/dist/harness-cmd/record.js +327 -0
  76. package/dist/harness-cmd/scrub.js +25 -0
  77. package/dist/harness-cmd/test.js +318 -0
  78. package/dist/harnesses/README.md +5 -0
  79. package/dist/harnesses/claude/cocheck-harness.json +344 -0
  80. package/dist/harnesses/codex/cocheck-harness.json +212 -0
  81. package/dist/harnesses/copilot/cocheck-harness.json +296 -0
  82. package/dist/helper-linker.js +257 -0
  83. package/dist/helpers/pdfpages +0 -0
  84. package/dist/home-page.js +173 -0
  85. package/dist/home-perms.js +59 -0
  86. package/dist/hook-adapter.js +3639 -0
  87. package/dist/hook-cli.js +542 -0
  88. package/dist/hook-journal.js +175 -0
  89. package/dist/hook.js +25 -0
  90. package/dist/hosts/claude.js +114 -0
  91. package/dist/hosts/codex-bin-macos.js +2 -0
  92. package/dist/hosts/codex-bin.js +35 -0
  93. package/dist/hosts/codex-trust-probe.js +52 -0
  94. package/dist/hosts/codex-trust.js +46 -0
  95. package/dist/hosts/codex.js +315 -0
  96. package/dist/hosts/compile.js +275 -0
  97. package/dist/hosts/copilot.js +81 -0
  98. package/dist/hosts/extras.js +55 -0
  99. package/dist/hosts/harnesses.js +66 -0
  100. package/dist/hosts/index.js +220 -0
  101. package/dist/hosts/install-block.js +332 -0
  102. package/dist/hosts/manifest.js +372 -0
  103. package/dist/hosts/session-titles.js +327 -0
  104. package/dist/hosts/shared.js +52 -0
  105. package/dist/hosts/tool-classes.js +6 -0
  106. package/dist/hosts/types.js +27 -0
  107. package/dist/html.js +4 -0
  108. package/dist/install.js +723 -0
  109. package/dist/items.js +105 -0
  110. package/dist/ledger.js +2108 -0
  111. package/dist/narration.js +202 -0
  112. package/dist/normalize.js +106 -0
  113. package/dist/office/connector/apps.js +34 -0
  114. package/dist/office/connector/docx/layer.js +247 -0
  115. package/dist/office/connector/docx/reader.js +284 -0
  116. package/dist/office/connector/excel/align.js +284 -0
  117. package/dist/office/connector/excel/answer.js +352 -0
  118. package/dist/office/connector/excel/diff.js +1310 -0
  119. package/dist/office/connector/excel/errors.js +44 -0
  120. package/dist/office/connector/excel/look.js +121 -0
  121. package/dist/office/connector/excel/print-boxes.js +432 -0
  122. package/dist/office/connector/excel/print-grid-previous.js +206 -0
  123. package/dist/office/connector/excel/print-setup.js +168 -0
  124. package/dist/office/connector/excel/workbook.js +374 -0
  125. package/dist/office/connector/export-driver.js +9 -0
  126. package/dist/office/connector/helpers/cocheck-screen +0 -0
  127. package/dist/office/connector/issues.js +31 -0
  128. package/dist/office/connector/mac-guard.js +16 -0
  129. package/dist/office/connector/main.js +23 -0
  130. package/dist/office/connector/nothing-changed.js +18 -0
  131. package/dist/office/connector/office-job.js +416 -0
  132. package/dist/office/connector/office-macos.js +473 -0
  133. package/dist/office/connector/office-win-export.js +107 -0
  134. package/dist/office/connector/office-win-lifecycle.js +194 -0
  135. package/dist/office/connector/office-win.js +209 -0
  136. package/dist/office/connector/office-win.ps1 +451 -0
  137. package/dist/office/connector/open-watch.js +46 -0
  138. package/dist/office/connector/pictures.js +156 -0
  139. package/dist/office/connector/pptx/diff.js +589 -0
  140. package/dist/office/connector/pptx/frames.js +105 -0
  141. package/dist/office/connector/pptx/layer.js +148 -0
  142. package/dist/office/connector/pptx/links.js +59 -0
  143. package/dist/office/connector/pptx/reader.js +744 -0
  144. package/dist/office/connector/pptx/spans.js +70 -0
  145. package/dist/office/connector/pptx/tags.js +86 -0
  146. package/dist/office/connector/pptx/xml.js +96 -0
  147. package/dist/office/connector/pptx/zip.js +223 -0
  148. package/dist/office/connector/pptx-boxes.js +238 -0
  149. package/dist/office/connector/print-copy-cap.js +19 -0
  150. package/dist/office/connector/print-copy.js +13 -0
  151. package/dist/office/connector/program.js +291 -0
  152. package/dist/office/connector/reach.js +27 -0
  153. package/dist/office/connector/refusal.js +16 -0
  154. package/dist/office/connector/screen-macos.js +193 -0
  155. package/dist/office/connector/screen-windows.js +34 -0
  156. package/dist/office/connector/shared/chart-diff.js +376 -0
  157. package/dist/office/connector/shared/docprops-noise.js +13 -0
  158. package/dist/office/connector/shared/lock.js +107 -0
  159. package/dist/office/connector/shared/ooxml-names.js +347 -0
  160. package/dist/office/connector/shared/owner.js +57 -0
  161. package/dist/office/connector/shared/package-media.js +703 -0
  162. package/dist/office/connector/shared/preflight.js +226 -0
  163. package/dist/office/connector/shared/structure-check.js +623 -0
  164. package/dist/office/connector/word-boxes.js +364 -0
  165. package/dist/office/connector/word-print-copy.js +234 -0
  166. package/dist/office/connector/xlsx/diff.js +1038 -0
  167. package/dist/office/connector/xlsx/formula.js +410 -0
  168. package/dist/office/connector/xlsx/layer.js +621 -0
  169. package/dist/office/connector/xlsx/memo.js +39 -0
  170. package/dist/office/connector/xlsx/numbers.js +31 -0
  171. package/dist/office/connector/xlsx/numfmt.js +913 -0
  172. package/dist/office/connector/xlsx/parts.js +66 -0
  173. package/dist/office/connector/xlsx/reader.js +394 -0
  174. package/dist/office/connector/xlsx/types.js +20 -0
  175. package/dist/office/connector/xlsx/written.js +446 -0
  176. package/dist/open-pick.js +101 -0
  177. package/dist/patch-secrets.js +194 -0
  178. package/dist/paths.js +65 -0
  179. package/dist/platform/darwin.js +179 -0
  180. package/dist/platform/index.js +61 -0
  181. package/dist/platform/spawn.js +115 -0
  182. package/dist/platform/stub.js +21 -0
  183. package/dist/platform/task-folder.js +41 -0
  184. package/dist/platform/types.js +20 -0
  185. package/dist/platform/win32-docrender.js +7 -0
  186. package/dist/platform/win32.js +265 -0
  187. package/dist/preferences.js +49 -0
  188. package/dist/reason.js +103 -0
  189. package/dist/region-delivery.js +148 -0
  190. package/dist/registry.js +68 -0
  191. package/dist/reveal.js +45 -0
  192. package/dist/review-process.js +154 -0
  193. package/dist/review-refresh-process.js +17 -0
  194. package/dist/review-refresh.js +120 -0
  195. package/dist/review-server.js +2079 -0
  196. package/dist/review-view-server.js +106 -0
  197. package/dist/review.js +8 -0
  198. package/dist/seal.js +315 -0
  199. package/dist/secret-files.js +34 -0
  200. package/dist/secret-hashes.js +27 -0
  201. package/dist/secret-rules.generated.js +3519 -0
  202. package/dist/secret-scan.js +127 -0
  203. package/dist/session-context.js +18 -0
  204. package/dist/signoff.js +419 -0
  205. package/dist/skill.js +110 -0
  206. package/dist/states.js +192 -0
  207. package/dist/tasks.js +1001 -0
  208. package/dist/timeline/attribution.js +207 -0
  209. package/dist/timeline/broken.js +55 -0
  210. package/dist/timeline/describe.js +416 -0
  211. package/dist/timeline/generic.js +195 -0
  212. package/dist/timeline/load.js +464 -0
  213. package/dist/timeline/loading.js +49 -0
  214. package/dist/timeline/notes.js +208 -0
  215. package/dist/timeline/page.js +178 -0
  216. package/dist/timeline/picture.js +303 -0
  217. package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
  218. package/dist/timeline/rail/assets/files-view.js +198 -0
  219. package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
  220. package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
  221. package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
  222. package/dist/timeline/rail/assets/review.css +992 -0
  223. package/dist/timeline/rail/assets/review.js +3365 -0
  224. package/dist/timeline/rail/assets/view-table.js +683 -0
  225. package/dist/timeline/rail/failure-line.js +26 -0
  226. package/dist/timeline/rail/files-model.js +45 -0
  227. package/dist/timeline/rail/live.js +49 -0
  228. package/dist/timeline/rail/made-pictures.js +48 -0
  229. package/dist/timeline/rail/mcp-card.js +307 -0
  230. package/dist/timeline/rail/model.js +1317 -0
  231. package/dist/timeline/rail/page.js +167 -0
  232. package/dist/timeline/rail/passes.js +106 -0
  233. package/dist/timeline/rail/regions.js +26 -0
  234. package/dist/timeline/rail/send-back.js +154 -0
  235. package/dist/timeline/rail/stop-status.js +164 -0
  236. package/dist/timeline/read-signal.js +743 -0
  237. package/dist/timeline/render/claimed.js +13 -0
  238. package/dist/timeline/render/fallback.js +36 -0
  239. package/dist/timeline/render/pdf-helper.js +71 -0
  240. package/dist/timeline/render/pdf.js +410 -0
  241. package/dist/timeline/render/pixel-pages.js +168 -0
  242. package/dist/timeline/render/png-crop.js +281 -0
  243. package/dist/timeline/render/registry.js +7 -0
  244. package/dist/timeline/render/text.js +366 -0
  245. package/dist/timeline/render/types.js +1 -0
  246. package/dist/timeline/render/view-v1.js +137 -0
  247. package/dist/timeline/render/whole.js +6 -0
  248. package/dist/timeline/rollout-failures.js +40 -0
  249. package/dist/timeline/runs.js +836 -0
  250. package/dist/timeline/stored-image.js +34 -0
  251. package/dist/timeline/subject-display.js +44 -0
  252. package/dist/timeline/timeline.js +1114 -0
  253. package/dist/timeline/write-signal.js +404 -0
  254. package/dist/tool-label.js +201 -0
  255. package/dist/tracking.js +87 -0
  256. package/dist/vendor/pdfjs/LICENSE +177 -0
  257. package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
  258. package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
  259. package/package.json +66 -4
  260. package/public-kit/GUIDE.md +189 -0
  261. package/public-kit/README.md +10 -0
  262. package/public-kit/conformance/README.md +13 -0
  263. package/public-kit/conformance/cases/C1.json +12 -0
  264. package/public-kit/conformance/cases/C10.json +15 -0
  265. package/public-kit/conformance/cases/C11.json +16 -0
  266. package/public-kit/conformance/cases/C12.json +18 -0
  267. package/public-kit/conformance/cases/C13.json +23 -0
  268. package/public-kit/conformance/cases/C14.json +16 -0
  269. package/public-kit/conformance/cases/C16.json +15 -0
  270. package/public-kit/conformance/cases/C17.json +25 -0
  271. package/public-kit/conformance/cases/C2.json +13 -0
  272. package/public-kit/conformance/cases/C3.json +44 -0
  273. package/public-kit/conformance/cases/C4.json +13 -0
  274. package/public-kit/conformance/cases/C5.json +16 -0
  275. package/public-kit/conformance/cases/C6.json +58 -0
  276. package/public-kit/conformance/generate-large.mjs +15 -0
  277. package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
  278. package/public-kit/examples/toy-export/connector.mjs +28 -0
  279. package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
  280. package/public-kit/examples/toy-helpers/connector.mjs +69 -0
  281. package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
  282. package/public-kit/examples/toy-level-1/connector.mjs +61 -0
  283. package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
  284. package/public-kit/examples/toy-level-3/connector.mjs +82 -0
  285. package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
  286. package/public-kit/examples/toy-tracker/connector.mjs +46 -0
  287. package/public-kit/examples/toy-tracker/samples/history.json +10 -0
  288. package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
  289. package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
  290. package/public-kit/examples/toy-vendor/connector.mjs +62 -0
  291. package/public-kit/harness/GUIDE.md +81 -0
  292. package/public-kit/harness/README.md +10 -0
  293. package/public-kit/harness/cases/claude/shell-writes-file.json +120 -0
  294. package/public-kit/harness/cases/codex/apply-patch-writes-files.json +177 -0
  295. package/public-kit/harness/cases/codex/helper-writes-file.json +160 -0
  296. package/public-kit/harness/cases/codex/shell-writes-and-fails.json +110 -0
  297. package/public-kit/harness/cases/copilot/camel-case-patch-and-failure.json +126 -0
  298. package/public-kit/harness/cases/copilot/helper-writes-file.json +209 -0
  299. package/public-kit/harness/cases/copilot/vscode-helper-writes-file.json +236 -0
  300. package/public-kit/harness/examples/toyagent/cases/write-notes.json +142 -0
  301. package/public-kit/harness/examples/toyagent/cocheck-harness.json +47 -0
  302. package/public-kit/harness/examples/toyagent/recordings/payloads.jsonl +8 -0
  303. package/public-kit/harness/harnesses/antigravity/README.md +32 -0
  304. package/public-kit/harness/harnesses/antigravity/cases/failed-edit.json +99 -0
  305. package/public-kit/harness/harnesses/antigravity/cases/helper-writes-file.json +270 -0
  306. package/public-kit/harness/harnesses/antigravity/cases/shell-ok-fail-and-denied.json +211 -0
  307. package/public-kit/harness/harnesses/antigravity/cases/write-then-edit.json +191 -0
  308. package/public-kit/harness/harnesses/antigravity/cocheck-harness.json +62 -0
  309. package/public-kit/harness/harnesses/antigravity/recordings/payloads.jsonl +63 -0
  310. package/public-kit/harness/harnesses/cursor/README.md +40 -0
  311. package/public-kit/harness/harnesses/cursor/cases/editor-write-edit-shell-helper.json +359 -0
  312. package/public-kit/harness/harnesses/cursor/cases/read-then-write-one-call-id.json +159 -0
  313. package/public-kit/harness/harnesses/cursor/cocheck-harness.json +67 -0
  314. package/public-kit/harness/harnesses/cursor/recordings/payloads.jsonl +28 -0
  315. package/public-kit/harness/scaffold/README.md +42 -0
  316. package/public-kit/harness/scaffold/cocheck-harness.json +72 -0
  317. package/public-kit/harness/scaffold/recordings/.gitkeep +0 -0
  318. package/public-kit/harness/spec/v1.md +286 -0
  319. package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
  320. package/public-kit/helpers/pdf-text-layout.mjs +602 -0
  321. package/public-kit/helpers/pdf-text.d.mts +56 -0
  322. package/public-kit/helpers/pdf-text.mjs +375 -0
  323. package/public-kit/helpers/pdf.d.mts +61 -0
  324. package/public-kit/helpers/pdf.mjs +251 -0
  325. package/public-kit/helpers/png.d.mts +15 -0
  326. package/public-kit/helpers/png.mjs +88 -0
  327. package/public-kit/helpers/spec.d.mts +4 -0
  328. package/public-kit/helpers/spec.mjs +2 -0
  329. package/public-kit/scaffold/README.md +23 -0
  330. package/public-kit/scaffold/template/README.md +13 -0
  331. package/public-kit/scaffold/template/cocheck-connector.json +10 -0
  332. package/public-kit/scaffold/template/connector.mjs +50 -0
  333. package/public-kit/spec/README.md +408 -0
  334. package/public-kit/spec/v1.md +598 -0
  335. package/public-kit/toy-product/README.md +7 -0
  336. package/public-kit/toy-product/notes-store.mjs +30 -0
  337. package/public-kit/toy-product/states/create.after.json +16 -0
  338. package/public-kit/toy-product/states/create.before.json +12 -0
  339. package/public-kit/toy-product/states/delete.after.json +8 -0
  340. package/public-kit/toy-product/states/delete.before.json +12 -0
  341. package/public-kit/toy-product/states/edit.after.json +12 -0
  342. package/public-kit/toy-product/states/edit.before.json +12 -0
  343. package/public-kit/toy-product/states/malformed.after.json +1 -0
  344. package/public-kit/toy-product/states/malformed.before.json +12 -0
  345. package/public-kit/toy-product/states/no-change.after.json +12 -0
  346. package/public-kit/toy-product/states/no-change.before.json +12 -0
  347. package/scripts/hook-launch.mjs +58 -0
  348. package/scripts/hook-launch.sh +52 -0
@@ -0,0 +1,44 @@
1
+ /** The most cell issues listed one by one; past it, one issue counts the rest. */
2
+ export const MAX_ERROR_ISSUES = 200;
3
+ const errorOf = (v) => (v !== null && v !== undefined && typeof v === "object" && typeof v.error === "string" ? v.error : null);
4
+ /** `#REF!` occurrences in formula text, ignoring string literals ("#REF!" typed as text is fine). */
5
+ export function brokenRefs(formula) {
6
+ return ((formula ?? "").replace(/"(?:[^"]|"")*"/g, '""').match(/#REF!/gi) ?? []).length;
7
+ }
8
+ const colName = (c) => {
9
+ let s = "";
10
+ for (let n = c; n > 0; n = Math.floor((n - 1) / 26))
11
+ s = String.fromCharCode(65 + ((n - 1) % 26)) + s;
12
+ return s;
13
+ };
14
+ /** The error values and broken references the change introduced, in sheet, row, column order. */
15
+ export function introducedErrors(sheets) {
16
+ const out = [];
17
+ let more = 0;
18
+ for (const s of sheets) {
19
+ if (s.after.kind !== "worksheet")
20
+ continue;
21
+ for (const r of [...s.after.rows.keys()].sort((x, y) => x - y)) {
22
+ const row = s.after.rows.get(r);
23
+ for (const c of [...row.keys()].sort((x, y) => x - y)) {
24
+ const now = row.get(c);
25
+ const was = s.beforeOf(r, c);
26
+ const err = errorOf(now.v);
27
+ const texts = [];
28
+ if (err !== null && errorOf(was?.v) === null)
29
+ texts.push(`Shows the error ${err}, which the change introduced.`);
30
+ if (brokenRefs(now.f) > brokenRefs(was?.f))
31
+ texts.push("The formula now points at a reference that no longer exists (#REF!).");
32
+ for (const text of texts) {
33
+ if (out.length < MAX_ERROR_ISSUES)
34
+ out.push({ text, side: "after", where: `${s.label}!${colName(c)}${r}` });
35
+ else
36
+ more++;
37
+ }
38
+ }
39
+ }
40
+ }
41
+ if (more > 0)
42
+ out.push({ text: `${more} more cell${more === 1 ? "" : "s"} now show an error value or a broken reference (#REF!) the change introduced.`, side: "after", where: "Workbook" });
43
+ return out;
44
+ }
@@ -0,0 +1,121 @@
1
+ // What the print route writes onto the change list: v1 `boxes`, `unplaced` and `looksSame` from the boxes print-boxes.ts placed on each picture, and the PNG encoder the
2
+ // tests draw their pages with. Pure.
3
+ //
4
+ // Must not happen: a box on a neighbour cell (the reviewer trusts a wrong mark). Every ambiguous case drops to unplaced words, never to a guess. A dropped box costs only a mark.
5
+ import { deflateSync } from "node:zlib";
6
+ import { decodePng } from "../../../../public-kit/helpers/png.mjs";
7
+ const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) {
8
+ let c = n;
9
+ for (let k = 0; k < 8; k++)
10
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
11
+ t[n] = c >>> 0;
12
+ } return t; })();
13
+ function chunk(type, data) {
14
+ const head = Buffer.alloc(8);
15
+ head.writeUInt32BE(data.length, 0);
16
+ head.write(type, 4, "latin1");
17
+ let c = 0xffffffff;
18
+ for (const part of [head.subarray(4), data])
19
+ for (let i = 0; i < part.length; i++)
20
+ c = CRC[(c ^ part[i]) & 0xff] ^ (c >>> 8);
21
+ const tail = Buffer.alloc(4);
22
+ tail.writeUInt32BE((c ^ 0xffffffff) >>> 0, 0);
23
+ return Buffer.concat([head, data, tail]);
24
+ }
25
+ /** An 8-bit RGBA PNG with fixed filter and level, so the same pixels always give the same bytes. */
26
+ export function encodePng(width, height, rgba) {
27
+ const ihdr = Buffer.alloc(13);
28
+ ihdr.writeUInt32BE(width, 0);
29
+ ihdr.writeUInt32BE(height, 4);
30
+ ihdr[8] = 8;
31
+ ihdr[9] = 6;
32
+ const rows = Buffer.alloc((width * 4 + 1) * height);
33
+ for (let y = 0; y < height; y++)
34
+ rgba.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
35
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(rows, { level: 6 })), chunk("IEND", Buffer.alloc(0))]);
36
+ }
37
+ /**
38
+ * True only when both pictures (or the given rectangle of each) hold the very same pixels. Different sizes, a rectangle outside a picture, or rectangles of
39
+ * different sizes answer false: "looks the same" is a claim that the value did not change, so doubt never earns it.
40
+ */
41
+ export function looksSame(before, after, rects) {
42
+ const rb = rects?.before ?? { x: 0, y: 0, w: before.width, h: before.height }, ra = rects?.after ?? { x: 0, y: 0, w: after.width, h: after.height };
43
+ if (rb.w !== ra.w || rb.h !== ra.h || rb.w < 1 || rb.h < 1)
44
+ return false;
45
+ const inside = (p, r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= p.width && r.y + r.h <= p.height;
46
+ if (!inside(before, rb) || !inside(after, ra))
47
+ return false;
48
+ for (let y = 0; y < rb.h; y++) {
49
+ const a = ((rb.y + y) * before.width + rb.x) * 4, b = ((ra.y + y) * after.width + ra.x) * 4;
50
+ if (!before.rgba.subarray(a, a + rb.w * 4).equals(after.rgba.subarray(b, b + rb.w * 4)))
51
+ return false;
52
+ }
53
+ return true;
54
+ }
55
+ const pixelsOf = (p) => { const m = /^data:image\/png;base64,(.*)$/.exec(p.src); return m ? decodePng(Buffer.from(m[1], "base64")) : undefined; };
56
+ /** Writes v1 `boxes`, `unplaced` and `looksSame` onto doc.changes. A box whose picture is not in doc.pictures is dropped, with "not pictured". */
57
+ export function applyLooks(doc, sides, plan) {
58
+ const shown = new Map();
59
+ for (const s of sides)
60
+ for (const p of s.pictures)
61
+ if (doc.pictures?.some((q) => q.id === p.id))
62
+ shown.set(p.id, p);
63
+ const sideOfPic = (id) => shown.get(id).side;
64
+ const pixels = new Map();
65
+ const px = (p) => { if (!pixels.has(p.id))
66
+ pixels.set(p.id, pixelsOf(p)); return pixels.get(p.id); };
67
+ // a (side, group, order) held by exactly one picture is a mate the checker can find
68
+ const held = new Map();
69
+ for (const p of shown.values())
70
+ held.set(`${p.side}|${p.group}|${p.order}`, (held.get(`${p.side}|${p.group}|${p.order}`) ?? 0) + 1);
71
+ const allBoxes = sides.flatMap((s) => s.boxes), allUn = sides.flatMap((s) => s.unplaced);
72
+ const mark = new Map(plan.changes.map((c) => [c.id, c.mark]));
73
+ for (const ch of doc.changes) {
74
+ // only a change the screen sides speak of is touched: whatever another route gave any other change stays as it is
75
+ if (!allBoxes.some((b) => b.change === ch.id) && !allUn.some((u) => u.change === ch.id))
76
+ continue;
77
+ const m = mark.get(ch.id);
78
+ const mine = allBoxes.filter((b) => b.change === ch.id && shown.has(b.picture)
79
+ && !(m === "added" && sideOfPic(b.picture) === "before") && !(m === "removed" && sideOfPic(b.picture) === "after"));
80
+ const un = {};
81
+ for (const side of ["before", "after"]) {
82
+ const words = allUn.filter((u) => u.change === ch.id && u.side === side && !mine.some((b) => sideOfPic(b.picture) === side)).map((u) => u.why);
83
+ const dropped = allBoxes.some((b) => b.change === ch.id && !shown.has(b.picture) && sideOf(sides, b.picture) === side) && !mine.some((b) => sideOfPic(b.picture) === side);
84
+ if (words.length)
85
+ un[side] = [...new Set(words)].join("; ");
86
+ else if (dropped)
87
+ un[side] = "not pictured";
88
+ }
89
+ const boxes = mine.map((b) => ({ picture: b.picture, rect: b.rect }));
90
+ // a box that is only part of the change says so in words, once per picture
91
+ const cut = mine.filter((b) => b.clipped === true);
92
+ for (const b of cut) {
93
+ const note = m === "added" ? `Inserted: this insertion continues outside the picture; only the inserted part inside ${shown.get(b.picture).label} is boxed.` : `Continues outside the picture: only the part inside ${shown.get(b.picture).label} is boxed.`;
94
+ if (!(ch.lines ?? []).includes(note))
95
+ ch.lines = [...(ch.lines ?? []), note];
96
+ }
97
+ const bs = boxes.filter((b) => sideOfPic(b.picture) === "before"), as = boxes.filter((b) => sideOfPic(b.picture) === "after");
98
+ // "the displayed value did not change" is never said of a change that continues outside its picture
99
+ if (cut.length === 0 && bs.length === 1 && as.length === 1) {
100
+ const pb = shown.get(bs[0].picture), pa = shown.get(as[0].picture);
101
+ if (pb.group === pa.group && pb.order === pa.order && held.get(`before|${pb.group}|${pb.order}`) === 1 && held.get(`after|${pa.group}|${pa.order}`) === 1) {
102
+ const xb = px(pb), xa = px(pa);
103
+ if (xb && xa && looksSame(xb, xa, { before: bs[0].rect, after: as[0].rect })) {
104
+ bs[0].looksSame = true;
105
+ as[0].looksSame = true;
106
+ // the person reads the words: a changed cell whose picture is the same on both sides did not change on screen
107
+ ch.text = ch.text !== undefined && ch.text !== "" ? `${ch.text}; the displayed value did not change` : "The displayed value did not change";
108
+ }
109
+ }
110
+ }
111
+ if (boxes.length)
112
+ ch.boxes = boxes;
113
+ else
114
+ delete ch.boxes;
115
+ if (un.before !== undefined || un.after !== undefined)
116
+ ch.unplaced = un;
117
+ else
118
+ delete ch.unplaced;
119
+ }
120
+ }
121
+ const sideOf = (sides, pictureId) => sides.flatMap((s) => s.pictures).find((p) => p.id === pictureId)?.side;
@@ -0,0 +1,432 @@
1
+ import { PRINT_ROW_K, printedWidthPt } from "./diff.js";
2
+ import { heightPt } from "./workbook.js";
3
+ import { previousPrintGrid } from "./print-grid-previous.js";
4
+ // Lines are found by contrast with the ground beside them, never by a fixed darkness: Excel prints heading lines black or grey, one pixel or two
5
+ // anti-aliased ones, depending on the zoom and where the line falls on the pixel grid.
6
+ const EDGE = 24; // a line's pixel is at least this much darker (0-255) than the lightest pixel beside it
7
+ const REACH = 4; // the ground beside a line is looked for up to this many pixels away, so lines up to three pixels wide read as lines
8
+ const INK = 64; // a heading letter's ink is at least this much darker than the band's ground
9
+ const COVER = 0.9; // a line spans this share of the gutter's width or the band's height
10
+ const SCALES_AGREE = 0.03; // the rows' scale and the columns' scale agree within this share
11
+ /** Pixels added outward on each side of a box, then clamped to the picture. */
12
+ export const PRINT_BOX_PAD_PX = 2;
13
+ const SAME = 0.75; // two lines of one tie are the same line within this many pixels
14
+ const fail = (why) => ({ why });
15
+ const runs = (flags) => {
16
+ const out = [];
17
+ let s = -1;
18
+ for (let i = 0; i <= flags.length; i++) {
19
+ const v = i < flags.length && flags[i];
20
+ if (v && s < 0)
21
+ s = i;
22
+ if (!v && s >= 0) {
23
+ out.push([s, i - s]);
24
+ s = -1;
25
+ }
26
+ }
27
+ return out;
28
+ };
29
+ const colNum = (s) => [...s].reduce((v, ch) => v * 26 + ch.charCodeAt(0) - 64, 0);
30
+ const colName = (n) => { let s = ""; for (let c = n; c > 0; c = Math.floor((c - 1) / 26))
31
+ s = String.fromCharCode(65 + ((c - 1) % 26)) + s; return s; };
32
+ const median = (a) => { const s = [...a].sort((x, y) => x - y); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
33
+ const meet = (a, b) => {
34
+ const x = { r1: Math.max(a.r1, b.r1), r2: Math.min(a.r2, b.r2), c1: Math.max(a.c1, b.c1), c2: Math.min(a.c2, b.c2) };
35
+ return x.r1 <= x.r2 && x.c1 <= x.c2 ? x : undefined;
36
+ };
37
+ const touches = (a, b) => meet(a, b) !== undefined;
38
+ /**
39
+ * The lines of a print picture tied to its printed labels, or why not. `region` is the rows and columns the picture must show: the labels must be exactly those.
40
+ * `sheet` gives the file's sizes for the scale check; without it nothing is confirmed.
41
+ */
42
+ export function printGrid(px, hd, region, sheet) {
43
+ // hidden rows and columns, and the size of every row and column, come from the file
44
+ if (sheet === undefined)
45
+ return fail("the sheet's sizes could not be read from the file");
46
+ const wantRows = [], wantCols = [];
47
+ for (let r = region.r1; r <= region.r2; r++)
48
+ wantRows.push(r);
49
+ for (let c = region.c1; c <= region.c2; c++)
50
+ wantCols.push(c);
51
+ const hiddenRow = wantRows.find((r) => sheet.hiddenRows.has(r) || heightPt(sheet, r) === 0);
52
+ if (hiddenRow !== undefined)
53
+ return fail(`row ${hiddenRow} is hidden, so the printed row numbers skip it`);
54
+ const hiddenCol = wantCols.find((c) => sheet.hiddenCols.has(c) || printedWidthPt(sheet, c) === 0);
55
+ if (hiddenCol !== undefined)
56
+ return fail(`column ${colName(hiddenCol)} is hidden, so the printed letters skip it`);
57
+ const { width: w, height: h } = px;
58
+ const lum = new Uint8Array(w * h);
59
+ for (let i = 0; i < w * h; i++)
60
+ lum[i] = (px.rgba[i * 4] * 77 + px.rgba[i * 4 + 1] * 150 + px.rgba[i * 4 + 2] * 29) >> 8;
61
+ const at = (x, y) => lum[y * w + x];
62
+ // How much darker (x, y) is than the lightest pixel of the small block beside it in direction (dx, dy): REACH pixels out, two pixels to either side across.
63
+ // The block's lightest pixel is the local background, so a grey line on white, a black line on white and a line on a tinted ground all read the same.
64
+ const lift = (x, y, dx, dy) => {
65
+ let m = -1;
66
+ for (let i = 1; i <= REACH; i++)
67
+ for (let j = -2; j <= 2; j++) {
68
+ const xx = x + dx * i + (dx === 0 ? j : 0), yy = y + dy * i + (dy === 0 ? j : 0);
69
+ if (xx >= 0 && xx < w && yy >= 0 && yy < h)
70
+ m = Math.max(m, at(xx, yy));
71
+ }
72
+ return m - at(x, y);
73
+ };
74
+ // a pixel of a horizontal line: darker than the ground above and below it (or on the one side named)
75
+ const hPix = (x, y, s) => (s === "both" ? Math.min(lift(x, y, 0, -1), lift(x, y, 0, 1)) : lift(x, y, 0, s)) >= EDGE;
76
+ const vPix = (x, y, s) => (s === "both" ? Math.min(lift(x, y, -1, 0), lift(x, y, 1, 0)) : lift(x, y, s, 0)) >= EDGE;
77
+ const clampX = (x) => Math.max(0, Math.min(w - 1, Math.round(x)));
78
+ const clampY = (y) => Math.max(0, Math.min(h - 1, Math.round(y)));
79
+ // lines that cross the span [a0, a1] on at least COVER of its pixels, between b0 and b1 along the other axis; each with its weighted centre
80
+ const lines = (axis, a0, a1, b0, b1, s) => {
81
+ a0 = axis === "h" ? clampX(a0) : clampY(a0);
82
+ a1 = axis === "h" ? clampX(a1) : clampY(a1);
83
+ b0 = axis === "h" ? clampY(b0) : clampX(b0);
84
+ b1 = axis === "h" ? clampY(b1) : clampX(b1);
85
+ const span = a1 - a0 + 1;
86
+ if (span < 3 || b1 < b0)
87
+ return [];
88
+ const px1 = (a, b) => (axis === "h" ? at(a, b) : at(b, a));
89
+ const hit = (a, b) => (axis === "h" ? hPix(a, b, s) : vPix(b, a, s));
90
+ const flags = [];
91
+ for (let b = b0; b <= b1; b++) {
92
+ let n = 0;
93
+ for (let a = a0; a <= a1; a++)
94
+ if (hit(a, b))
95
+ n++;
96
+ flags.push(n >= COVER * span);
97
+ }
98
+ // the weighted centre of each run, its pixels and the one next to it on each ground side (the faint half of an anti-aliased line), weighed against the
99
+ // ground two pixels out on the ground side(s), which a line never reaches
100
+ const sides = s === "both" ? [-1, 1] : [s];
101
+ return runs(flags).map(([r, n]) => {
102
+ const s0 = b0 + r, e0 = s0 + n - 1;
103
+ const out = sides.flatMap((d) => { const b = d < 0 ? s0 - 2 : e0 + 2; if (b < 0 || b >= (axis === "h" ? h : w))
104
+ return []; const v = []; for (let a = a0; a <= a1; a++)
105
+ v.push(px1(a, b)); return [median(v)]; });
106
+ const g = out.length ? Math.max(...out) : 255;
107
+ let wsum = 0, tot = 0;
108
+ for (let b = sides.includes(-1) ? Math.max(0, s0 - 1) : s0; b <= (sides.includes(1) ? Math.min((axis === "h" ? h : w) - 1, e0 + 1) : e0); b++) {
109
+ let v = 0;
110
+ for (let a = a0; a <= a1; a++)
111
+ v += Math.max(0, g - px1(a, b));
112
+ wsum += b * v;
113
+ tot += v;
114
+ }
115
+ return { centre: tot === 0 ? s0 + (n - 1) / 2 : wsum / tot, s: s0, n };
116
+ });
117
+ };
118
+ // the column band: the lines just above and below the printed letters, each read against the band side of it (the cells below may be filled)
119
+ const cols = hd.cols;
120
+ if (cols === undefined)
121
+ return fail("no column letters are printed on this picture");
122
+ const letters = cols.text.split(" ");
123
+ if (cols.chars === undefined || cols.chars.length !== letters.reduce((n, t) => n + t.length, 0))
124
+ return fail("the column letters have no per-letter bounds to check");
125
+ const lx0 = Math.min(...cols.chars.map((c) => c.x)), lx1 = Math.max(...cols.chars.map((c) => c.x + c.w));
126
+ const lyc = Math.min(h - 1, Math.max(0, cols.y + cols.h / 2));
127
+ const near = 2 * cols.h + 2 * REACH; // the band's lines sit just above and below the letters
128
+ const bandTop = lines("h", lx0, lx1, lyc - near, lyc, 1).at(-1);
129
+ const bandBot = lines("h", lx0, lx1, lyc, lyc + near, -1)[0];
130
+ if (bandTop === undefined || bandBot === undefined)
131
+ return fail("the lines above and below the column letters were not found in the picture");
132
+ const by0 = bandTop.s + bandTop.n + 1, by1 = bandBot.s - 2; // the band's inside, rows
133
+ if (by1 - by0 < 3)
134
+ return fail("the column band is too small to read");
135
+ // column lines: lines down the whole band, read against both sides (the band is never filled)
136
+ const bandLines = lines("v", by0, by1, 0, w - 1, "both");
137
+ const bl = bandLines.map((l) => l.centre);
138
+ // the letters, each with its own bounds
139
+ let k = 0;
140
+ const bounds = letters.map((t) => { const cs = cols.chars.slice(k, k + t.length); k += t.length; return { x0: Math.min(...cs.map((c) => c.x)), x1: Math.max(...cs.map((c) => c.x + c.w)) }; });
141
+ // the gutter's right edge is the band line just left of the first letter: the left line of the first column. At most one line (the frame) lies left of it.
142
+ const gi = bl.findLastIndex((x) => x < bounds[0].x0);
143
+ if (gi < 0)
144
+ return fail("no line was found left of the first column letter");
145
+ if (gi > 1)
146
+ return fail(`the column band holds ${gi + 1} lines left of the first letter, where the frame and the row gutter's edge make at most 2`);
147
+ const right = bl.slice(gi);
148
+ if (right.length !== letters.length + 1)
149
+ return fail(`the column band holds ${right.length} lines from the row gutter on, but ${letters.length} letters need ${letters.length + 1}`);
150
+ const gutX = bl[gi], frameX = gi > 0 ? bl[0] : undefined;
151
+ const gutR = bandLines[gi].s + bandLines[gi].n - 1;
152
+ // the row gutter: every printed row number lies between the frame and the gutter's edge
153
+ const rowChars = hd.rows.flatMap((r) => r.chars ?? []);
154
+ const rx0 = rowChars.length ? Math.min(...rowChars.map((c) => c.x)) : gutX - 4;
155
+ const rx1 = rowChars.length ? Math.max(...rowChars.map((c) => c.x + c.w)) : gutX - 4;
156
+ if (rx1 > gutX - 1 || (frameX !== undefined && rx0 < frameX + 1))
157
+ return fail("the printed row numbers are not inside the row gutter");
158
+ const gx0 = frameX !== undefined ? frameX + 2 : Math.min(rx0, gutX - 6), gx1 = gutX - 2; // the gutter's inside, columns
159
+ if (gx1 - gx0 < 3)
160
+ return fail("the row gutter is too small to read");
161
+ // row lines: lines across the whole gutter, read against both sides (the gutter is never filled, and nothing is drawn over it)
162
+ const gl = lines("h", gx0, gx1, 0, h - 1, "both").map((l) => l.centre);
163
+ // rows: each printed number is tied to the adjacent pair of gutter lines that hold its text, with no line through it
164
+ const rowLines = new Map();
165
+ const refuseRow = new Map();
166
+ const used = new Map();
167
+ const seen = new Set();
168
+ for (const lab of hd.rows) {
169
+ if (seen.has(lab.n))
170
+ return fail(`row number ${lab.n} is printed twice on this picture`);
171
+ seen.add(lab.n);
172
+ const digits = String(lab.n).length;
173
+ // one number per run: the digits of a real number stand side by side on one line; a run whose digits are stacked or overlap is rows fused by their shortness
174
+ if (lab.chars === undefined ? digits > 1 : lab.chars.length !== digits) {
175
+ refuseRow.set(lab.n, "its number has no per-digit bounds to check (fused rows?)");
176
+ continue;
177
+ }
178
+ if (lab.chars !== undefined && lab.chars.length > 1) {
179
+ const cs = lab.chars;
180
+ const flat = cs.every((c) => Math.abs(c.y - cs[0].y) <= 1.5 && Math.abs(c.h - cs[0].h) <= 3);
181
+ const ordered = cs.every((c, i) => i === 0 || c.x >= cs[i - 1].x + cs[i - 1].w * 0.5);
182
+ if (!flat || !ordered) {
183
+ refuseRow.set(lab.n, "its digits are not side by side on one line (short rows whose numbers run together)");
184
+ continue;
185
+ }
186
+ }
187
+ const y0 = lab.y, y1 = lab.y + lab.h;
188
+ if (gl.some((g) => g > y0 + 1 && g < y1 - 1)) {
189
+ refuseRow.set(lab.n, "a line runs through its number (the row is shorter than its number)");
190
+ continue;
191
+ }
192
+ const above = gl.filter((g) => g <= y0 + 2), below = gl.filter((g) => g >= y1 - 2);
193
+ if (!above.length || !below.length) {
194
+ refuseRow.set(lab.n, "its number is not between two lines");
195
+ continue;
196
+ }
197
+ const a = Math.max(...above), b = Math.min(...below);
198
+ if (gl.indexOf(b) !== gl.indexOf(a) + 1) {
199
+ refuseRow.set(lab.n, "its two lines are not neighbours");
200
+ continue;
201
+ }
202
+ const key = `${a}|${b}`;
203
+ if (used.has(key))
204
+ return fail(`rows ${used.get(key)} and ${lab.n} are tied to the same two lines`);
205
+ used.set(key, lab.n);
206
+ rowLines.set(lab.n, [a, b]);
207
+ }
208
+ const tiedRows = [...rowLines.keys()].sort((p, q) => p - q);
209
+ const missRow = wantRows.find((r) => !rowLines.has(r));
210
+ if (missRow !== undefined || tiedRows.length !== wantRows.length) {
211
+ if (missRow !== undefined && refuseRow.has(missRow))
212
+ return fail(`the number of row ${missRow} cannot be tied to its lines: ${refuseRow.get(missRow)}`);
213
+ return fail(`the page labels rows ${tiedRows.length ? `${tiedRows[0]} to ${tiedRows[tiedRows.length - 1]}` : "none"} but the file's region is rows ${region.r1} to ${region.r2}${missRow !== undefined ? ` (row ${missRow} is not printed on this picture)` : ""}`);
214
+ }
215
+ // consecutive rows share the line between them: each line is tied to the number above it and the number below it
216
+ for (let r = region.r1; r < region.r2; r++)
217
+ if (Math.abs(rowLines.get(r)[1] - rowLines.get(r + 1)[0]) > SAME)
218
+ return fail(`the lines of rows ${r} and ${r + 1} do not meet`);
219
+ if (Math.abs(rowLines.get(region.r1)[0] - bandBot.centre) > 1.5)
220
+ return fail("the first row's top line is not the bottom line of the column headings");
221
+ // the gutter holds exactly one line per row edge from the band down to the last row: a line more or less means a line was missed or a stray one was taken
222
+ const lastBot = rowLines.get(region.r2)[1];
223
+ const inRows = gl.filter((g) => g >= bandBot.centre - 1.5 && g <= lastBot + 1.5).length;
224
+ if (inRows !== wantRows.length + 1)
225
+ return fail(`the row gutter holds ${inRows} lines for ${wantRows.length} rows, which need ${wantRows.length + 1}`);
226
+ // the gutter's edge runs down the page from the band to the last row: read against the gutter side only (column A's cells, or a chart over them, may be dark)
227
+ {
228
+ const ya = clampY(bandBot.centre + 2), yb = clampY(lastBot - 2);
229
+ let n = 0;
230
+ for (let y = ya; y <= yb; y++) {
231
+ let on = false;
232
+ for (let x = clampX(gutX) - 1; x <= clampX(gutX) + 1 && !on; x++)
233
+ on = vPix(x, y, -1);
234
+ if (on)
235
+ n++;
236
+ }
237
+ if (yb > ya && n < COVER * (yb - ya + 1))
238
+ return fail("the line between the row numbers and the first column does not run down the page");
239
+ }
240
+ // columns: the printed letters, each tied to its interval between the band's lines
241
+ const names = letters.map(colNum);
242
+ if (!names.every((n, i) => i === 0 || n === names[i - 1] + 1))
243
+ return fail("the printed column letters are not consecutive");
244
+ if (names.length !== wantCols.length || names[0] !== region.c1)
245
+ return fail(`the page labels columns ${letters[0]} to ${letters[letters.length - 1]} but the file's region is columns ${colName(region.c1)} to ${colName(region.c2)}`);
246
+ const iv = letters.map((_, i) => [right[i], right[i + 1]]);
247
+ for (let i = 0; i < letters.length; i++)
248
+ if (!(iv[i][0] < bounds[i].x0 && bounds[i].x1 < iv[i][1]))
249
+ return fail(`the letter ${letters[i]} is not inside its own column lines`);
250
+ // the pixels agree: ink of a glyph inside every interval, none outside them. Ink is read against the band's own ground, not a fixed darkness.
251
+ const onLine = new Set();
252
+ for (const l of bandLines)
253
+ for (let x = l.s - 1; x <= l.s + l.n; x++)
254
+ onLine.add(x);
255
+ const bandGround = [];
256
+ for (let y = by0; y <= by1; y++)
257
+ for (let x = clampX(gutX); x < w; x += 3)
258
+ bandGround.push(at(x, y));
259
+ const inkBelow = median(bandGround) - INK;
260
+ const ink = Array.from({ length: w }, (_, x) => { if (onLine.has(x))
261
+ return false; for (let y = by0; y <= by1; y++)
262
+ if (at(x, y) < inkBelow)
263
+ return true; return false; });
264
+ const clusters = runs(ink).map(([s0, n]) => [s0, s0 + n - 1]).filter(([s0]) => s0 > gutR);
265
+ for (const [c0, c1] of clusters)
266
+ if (!iv.some(([a, b]) => a < c0 && c1 < b))
267
+ return fail("a glyph in the column headings lies outside every column");
268
+ for (let i = 0; i < iv.length; i++)
269
+ if (!clusters.some(([c0, c1]) => iv[i][0] < c0 && c1 < iv[i][1] && c0 >= bounds[i].x0 - 2 && c1 <= bounds[i].x1 + 2))
270
+ return fail(`no glyph is drawn for the letter ${letters[i]} where its bounds say`);
271
+ const colLines = new Map();
272
+ names.forEach((n, i) => colLines.set(n, iv[i]));
273
+ // the scale, from the page's own lines: rows and columns each give one, and one zoom prints both, so the two must agree. Every tied column, and every row whose
274
+ // height the file sets, must be the size the file gives it at that scale. A row whose height the file leaves unset is fitted by Excel to its content (a larger
275
+ // font, wrapped text), so it may print taller than the default, never shorter.
276
+ const checkScale = (tied, nominal, what, mayGrow) => {
277
+ const readable = [...tied].filter(([n]) => nominal(n) >= 20);
278
+ if (!readable.length)
279
+ return { bad: `no ${what} is large enough to read the page's scale from` };
280
+ const s = median(readable.map(([n, [a, b]]) => (b - a) / nominal(n)));
281
+ for (const [n, [a, b]] of tied) {
282
+ const want = nominal(n) * s, tol = Math.max(2.5, 0.06 * want);
283
+ if (b - a > want && mayGrow(n))
284
+ continue;
285
+ if (Math.abs(b - a - want) > tol)
286
+ return { bad: `${what} ${what === "column" ? colName(n) : n} is ${(b - a).toFixed(1)} px but the file and the page's scale say ${want.toFixed(1)} px` };
287
+ }
288
+ return { scale: s };
289
+ };
290
+ const rowScale = checkScale(rowLines, (n) => 2 * heightPt(sheet, n) * PRINT_ROW_K, "row", (n) => !sheet.heights.has(n));
291
+ if ("bad" in rowScale)
292
+ return fail(rowScale.bad);
293
+ const colScale = checkScale(colLines, (n) => 2 * printedWidthPt(sheet, n), "column", () => false);
294
+ if ("bad" in colScale)
295
+ return fail(colScale.bad);
296
+ if (Math.abs(rowScale.scale - colScale.scale) > SCALES_AGREE * colScale.scale)
297
+ return fail(`the rows give the page a scale of ${rowScale.scale.toFixed(3)} and the columns ${colScale.scale.toFixed(3)}, but one zoom prints both`);
298
+ return { rowLines, colLines, scale: { rows: rowScale.scale, cols: colScale.scale } };
299
+ }
300
+ const EMU_PER_PT = 12700;
301
+ const ZOOM_AGREES = 0.02; // the zoom the page was printed at and the scale its own lines show agree within this share
302
+ /**
303
+ * A drawing's frame on the page, from its anchor in the file and the fitted grid, or why not. A corner tied to a cell sits on that cell's fitted lines plus its
304
+ * offset; a size or an absolute position is measured at `pxPerPt`, the page's pixels per point at the zoom it was printed at, which must agree with the scale
305
+ * the page's own lines show. A frame that runs past the printed cells is cut at their edge and marked `clipped`.
306
+ */
307
+ export function drawingFrame(d, grid, region, pxPerPt) {
308
+ const pl = d.place;
309
+ if (pl === undefined)
310
+ return fail("its anchor in the file could not be read");
311
+ if (pxPerPt === undefined || !(pxPerPt > 0))
312
+ return fail("the zoom the page was printed at is not known, so the drawing cannot be measured on it");
313
+ // the lines' scale is relative to the file's sizes at 2 px a point (the print model the grid is checked with)
314
+ const seen = grid.scale.rows + grid.scale.cols; // 2 px a point times the mean of the two scales
315
+ if (Math.abs(seen - pxPerPt) > ZOOM_AGREES * pxPerPt)
316
+ return fail(`the page's lines show ${seen.toFixed(3)} px a point but its zoom gives ${pxPerPt.toFixed(3)}, so the drawing cannot be measured on it`);
317
+ const k = pxPerPt / EMU_PER_PT;
318
+ const X0 = grid.colLines.get(region.c1)[0], X1 = grid.colLines.get(region.c2)[1], Y0 = grid.rowLines.get(region.r1)[0], Y1 = grid.rowLines.get(region.r2)[1];
319
+ // a corner on the page: -Infinity / Infinity when its cell is before / after the printed range, a pixel otherwise
320
+ const along = (lines, lo, hi, cell0, off) => {
321
+ const n = cell0 + 1;
322
+ if (n < lo)
323
+ return -Infinity;
324
+ if (n > hi)
325
+ return Infinity;
326
+ const [a, b] = lines.get(n);
327
+ if (off * k > b - a + 2)
328
+ return fail("its anchor's offset runs past the cell it is anchored to");
329
+ return a + Math.min(off * k, b - a);
330
+ };
331
+ const corner = (c) => {
332
+ const x = along(grid.colLines, region.c1, region.c2, c.col, c.colOff), y = along(grid.rowLines, region.r1, region.r2, c.row, c.rowOff);
333
+ if (typeof x !== "number")
334
+ return x;
335
+ if (typeof y !== "number")
336
+ return y;
337
+ return { x, y };
338
+ };
339
+ let left, top, right, bottom;
340
+ if (pl.kind === "twoCell") {
341
+ const f = corner(pl.from), t = corner(pl.to);
342
+ if ("why" in f)
343
+ return f;
344
+ if ("why" in t)
345
+ return t;
346
+ [left, top, right, bottom] = [f.x, f.y, t.x, t.y];
347
+ }
348
+ else if (pl.kind === "oneCell") {
349
+ const f = corner(pl.from);
350
+ if ("why" in f)
351
+ return f;
352
+ if (!Number.isFinite(f.x) || !Number.isFinite(f.y))
353
+ return fail("its frame starts outside the printed cells, and its size is measured from its start");
354
+ [left, top] = [f.x, f.y];
355
+ [right, bottom] = [left + pl.ext.cx * k, top + pl.ext.cy * k];
356
+ }
357
+ else {
358
+ // an absolute position is measured from the sheet's top-left corner, which the page shows only when it prints from A1
359
+ if (region.r1 !== 1 || region.c1 !== 1)
360
+ return fail("its position is measured from cell A1, which this picture does not show");
361
+ [left, top] = [X0 + pl.pos.x * k, Y0 + pl.pos.y * k];
362
+ [right, bottom] = [left + pl.ext.cx * k, top + pl.ext.cy * k];
363
+ }
364
+ if (!(right > left && bottom > top))
365
+ return fail("its frame has no size");
366
+ const x0 = Math.max(left, X0), x1 = Math.min(right, X1), y0 = Math.max(top, Y0), y1 = Math.min(bottom, Y1);
367
+ if (x1 - x0 < 2 || y1 - y0 < 2)
368
+ return fail("its frame lies outside the printed cells");
369
+ return { x0, y0, x1, y1, clipped: x0 > left + 0.5 || x1 < right - 0.5 || y0 > top + 0.5 || y1 < bottom - 0.5 };
370
+ }
371
+ /**
372
+ * One picture's boxes. `region`: the rows and columns the picture shows. `pages`: how many pages the region printed on (a region on a second page is refused).
373
+ * `pxPerPt`: the page's pixels per point at the zoom it was printed at, for drawings (a chart, picture or shape is boxed on its frame).
374
+ * Every box in `boxes` gets a rect or words; a change that runs past the region is boxed on the part inside it, with `clipped`.
375
+ */
376
+ export function placePrintBoxes(a) {
377
+ const all = (why) => a.boxes.map((b) => ({ change: b.change, why: `not marked: ${why}` }));
378
+ if (a.pages > 1)
379
+ return all(`the region printed on ${a.pages} pages and only its first page is shown`);
380
+ const fitted = printGrid(a.pixels, a.headings, a.region, a.sheet);
381
+ // Safety net until this finder is verified on real Windows print pictures, to be removed then (with print-grid-previous.ts): when it
382
+ // refuses the page, the finder used before it is asked, and its grid, if it fits under its own checks, places the cell boxes. Drawing
383
+ // frames are boxed only from this finder's grid (the earlier one never boxed them). Only when both refuse is every change unplaced.
384
+ const grid = "why" in fitted ? previousPrintGrid(a.pixels, a.headings, a.region, a.sheet) : fitted;
385
+ if ("why" in grid)
386
+ return all("why" in fitted ? fitted.why : grid.why);
387
+ const sheet = a.sheet;
388
+ return a.boxes.map((b) => {
389
+ const no = (why) => ({ change: b.change, why: `not marked: ${why}` });
390
+ // a drawing (chart, picture, shape) is boxed on its own frame, from its anchor and the fitted grid
391
+ if (b.drawing !== undefined) {
392
+ if ("why" in fitted)
393
+ return no(fitted.why);
394
+ const same = sheet.drawings.filter((d) => (d.objectName ?? d.name) === b.drawing);
395
+ if (same.length !== 1)
396
+ return no(same.length === 0 ? "the drawing was not found on the sheet" : "two drawings on the sheet have its name");
397
+ const f = drawingFrame(same[0], fitted, a.region, a.pxPerPt);
398
+ if ("why" in f)
399
+ return no(`the ${same[0].kind === "image" ? "picture" : same[0].kind}: ${f.why}`);
400
+ const x0 = Math.max(0, Math.floor(f.x0 - PRINT_BOX_PAD_PX)), y0 = Math.max(0, Math.floor(f.y0 - PRINT_BOX_PAD_PX));
401
+ const x1 = Math.min(a.pixels.width, Math.ceil(f.x1 + PRINT_BOX_PAD_PX + 1)), y1 = Math.min(a.pixels.height, Math.ceil(f.y1 + PRINT_BOX_PAD_PX + 1));
402
+ return { change: b.change, rect: { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }, ...(f.clipped ? { clipped: true } : {}) };
403
+ }
404
+ let cells = meet(b.cells, a.region);
405
+ if (!cells)
406
+ return no("outside the cells of this picture");
407
+ const clipped = cells.r1 !== b.cells.r1 || cells.r2 !== b.cells.r2 || cells.c1 !== b.cells.c1 || cells.c2 !== b.cells.c2;
408
+ // merged cells: a changed cell is the merge's anchor. The whole merge when its outer edges are all tied on this picture, the anchor cell otherwise.
409
+ const one = cells.r1 === cells.r2 && cells.c1 === cells.c2;
410
+ if (one) {
411
+ const m = sheet.merges.find((x) => cells.r1 >= x.r1 && cells.r1 <= x.r2 && cells.c1 >= x.c1 && cells.c1 <= x.c2 && (x.r1 !== x.r2 || x.c1 !== x.c2));
412
+ if (m) {
413
+ if (m.r1 !== cells.r1 || m.c1 !== cells.c1)
414
+ return no("inside a merged cell, away from its anchor");
415
+ const whole = meet(m, a.region);
416
+ if (whole && whole.r1 === m.r1 && whole.r2 === m.r2 && whole.c1 === m.c1 && whole.c2 === m.c2)
417
+ cells = m;
418
+ }
419
+ }
420
+ // anything drawn over cells hides them: a chart, picture or shape anchored over the change
421
+ if (sheet.drawings.some((d) => d.anchor !== undefined && touches(d.anchor, cells)))
422
+ return no("the cells are under a chart or picture");
423
+ const R1 = grid.rowLines.get(cells.r1), R2 = grid.rowLines.get(cells.r2), C1 = grid.colLines.get(cells.c1), C2 = grid.colLines.get(cells.c2);
424
+ if (!R1 || !R2 || !C1 || !C2)
425
+ return no("an edge of the cells has no confirmed line tied to the printed labels");
426
+ const x0 = Math.max(0, Math.floor(C1[0] - PRINT_BOX_PAD_PX)), y0 = Math.max(0, Math.floor(R1[0] - PRINT_BOX_PAD_PX));
427
+ const x1 = Math.min(a.pixels.width, Math.ceil(C2[1] + PRINT_BOX_PAD_PX + 1)), y1 = Math.min(a.pixels.height, Math.ceil(R2[1] + PRINT_BOX_PAD_PX + 1));
428
+ if (x1 <= x0 || y1 <= y0)
429
+ return no("outside the picture");
430
+ return { change: b.change, rect: { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }, ...(clipped ? { clipped: true } : {}) };
431
+ });
432
+ }