Pārlūkot izejas kodu

Fix Safari PDF export of wrapped text lines

WebKit adds an empty client rect at the end of the line above for a range that starts at a wrap. getBoundingClientRect() included it, so the first character of each wrapped line was measured as sitting on the previous line ("Basics of R" / "everse Proxy"), and short lines were fitted to the width of the line above.

Add OfficePdfCore.rangeBox, which unions only the rects that have width, and use it in splitByLine and the run planner. Pieces with no width now draw nothing and never open a new line.

Add common/test_pdfcore.js with a fake DOM that simulates both Blink/Gecko and WebKit layouts, and document the pitfall and the new test command in the Office README.
Toby Chui 2 nedēļas atpakaļ
vecāks
revīzija
43854f776c

+ 10 - 1
src/web/Office/README.md

@@ -708,7 +708,7 @@ the rest of the line out of shape; when the face *is* the one the browser
 used, the ratio is 1 and nothing happens. Spaces in a highlighted span are
 still drawn as their highlight box.
 
-Two things about placing the text that are easy to get wrong, and were:
+Three things about placing the text that are easy to get wrong, and were:
 
 - **The baseline is measured, not computed.** A canvas `measureText`
   reports the ascent and descent the browser resolved for a font stack —
@@ -718,6 +718,14 @@ Two things about placing the text that are easy to get wrong, and were:
   ascent plus descent tall, not `line-height` tall. The baseline is an
   ascent below the top of that rect. Treating it as the line box puts every
   line a couple of pixels high at 30px type.
+- **In Safari a range that starts at a wrap has one rect too many.** WebKit
+  adds an empty rect at the end of the line above, ahead of the real one,
+  and `getBoundingClientRect()` takes both in. Measured that way the first
+  character of every wrapped line sits on the line before, and the export
+  showed "Basics of R" / "everse Proxy", the next line indented by one
+  character. So ranges are measured with `OfficePdfCore.rangeBox`, the
+  union of the rects that have width, never with the bounding box
+  (`node web/Office/common/test_pdfcore.js` pins it).
 
 When a whole object does have to be rasterized (only a chart whose SVG the
 translator cannot express, now), the picture is taken through an SVG
@@ -1663,6 +1671,7 @@ node --check web/Office/docs/docs.js   # etc. for each edited JS file
 node web/Office/sheets/test_formula.js    # formula engine
 node web/Office/sheets/test_formula_fns.js  # formula functions (vs. Excel examples)
 node web/Office/common/test_share.js      # share links and OOXML app detection
+node web/Office/common/test_pdfcore.js    # PDF export: which text lands on which line
 node web/Office/slides/test_lines.js      # line styles, line ends, callout adjustments
 node web/Office/docs/test_pdfimport.js    # PDF import: lines, paragraphs, lists, tables
 sh ../scripts/check-conventions.sh --diff origin/master

+ 40 - 6
src/web/Office/common/pdfcore.js

@@ -841,11 +841,43 @@ var OfficePdfCore = (function () {
         return runs;
     }
 
+    /* rangeBox is the box of what a range draws: the union of its client
+       rects that have width, or null when none has (a collapsed space).
+
+       Not getBoundingClientRect, because of WebKit (Safari). A range that
+       starts where a line wrapped gets one more rect there: an empty one at
+       the end of the line above, ahead of the real one. The bounding box
+       takes both in, so the first character of every wrapped line measured
+       as if it sat on the line before - the export moved it up there
+       ("Basics of R" / "everse Proxy") and started the next line one
+       character late, and a whole line measured that way came out as wide
+       as the line above it. Blink and Gecko add no such rect; for them this
+       is the bounding box. */
+    function rangeBox(range) {
+        var rects = range.getClientRects();
+        var box = null;
+        for (var i = 0; i < rects.length; i++) {
+            var rc = rects[i];
+            if (!(rc.width > 0.01)) continue;
+            if (!box) {
+                box = { left: rc.left, top: rc.top, right: rc.right, bottom: rc.bottom };
+                continue;
+            }
+            box.left = Math.min(box.left, rc.left);
+            box.top = Math.min(box.top, rc.top);
+            box.right = Math.max(box.right, rc.right);
+            box.bottom = Math.max(box.bottom, rc.bottom);
+        }
+        if (box) box.width = box.right - box.left;
+        return box;
+    }
+
     /* splitByLine maps a text node's client rects back onto the substrings
        that produced them, so each line can be drawn at its own baseline.
        Character-by-character is the only reliable way: the browser decides
        where the break went, and only it knows. start is where each line's
-       text begins in the node. */
+       text begins in the node. A character with no width draws nothing, so
+       it never opens a line: it stays with the text before it. */
     function splitByLine(node, text, lineRects) {
         if (lineRects.length === 1) {
             return [{ text: text, rect: lineRects[0], start: 0 }];
@@ -859,8 +891,8 @@ var OfficePdfCore = (function () {
         for (var i = 0; i < text.length; i++) {
             range.setStart(node, i);
             range.setEnd(node, i + 1);
-            var r = range.getBoundingClientRect();
-            if (r.width === 0 && r.height === 0) { cur += text[i]; continue; }
+            var r = rangeBox(range);
+            if (!r) { cur += text[i]; continue; }
             var top = Math.round(r.top * 10) / 10;
             if (curTop === null || Math.abs(top - curTop) < 0.6) {
                 if (curTop === null) { curTop = top; curRect = { left: r.left, top: r.top, bottom: r.bottom, right: r.right }; }
@@ -947,7 +979,7 @@ var OfficePdfCore = (function () {
         try {
             range.setStart(r.node, r.start);
             range.setEnd(r.node, r.start + r.text.length);
-            now = range.getBoundingClientRect();
+            now = rangeBox(range);
         } catch (e) { now = null; }
         var nodeText = String(r.node.nodeValue || "").substr(r.start, r.text.length)
             .replace(/[\u0000-\u001F\u007F]/g, " ");
@@ -968,9 +1000,10 @@ var OfficePdfCore = (function () {
             var text = r.text.substring(s, e);
             range.setStart(r.node, r.start + s);
             range.setEnd(r.node, r.start + e);
-            var b = range.getBoundingClientRect();
+            var b = rangeBox(range);
+            // a piece with no width draws nothing
+            if (!b) return;
             var dx = (b.left - now.left) * k, w = b.width * k;
-            if (!(w > 0) && !visibleText(text).trim()) return;
             out.push({ text: transformText(text, r.transform), dx: dx, w: w, fit: w, raster: !p.ok });
         });
         return out;
@@ -1315,6 +1348,7 @@ var OfficePdfCore = (function () {
         dataUrlBytes: dataUrlBytes,
         Page: Page,
         collectRuns: collectRuns,
+        rangeBox: rangeBox,
         splitByLine: splitByLine,
         canDrawAsText: canDrawAsText,
         planRun: planRun,

+ 170 - 0
src/web/Office/common/test_pdfcore.js

@@ -0,0 +1,170 @@
+/*
+    ArozOS Office Suite - PDF core line measurement tests (common/pdfcore.js)
+    Run with: node test_pdfcore.js   (exits 1 on failure)
+
+    The exporters draw each line of text where the browser laid it out, so
+    which characters splitByLine puts on which line is what the PDF shows.
+    The DOM here is a stand-in: a text node set on lines of fixed-width
+    characters, whose ranges answer getClientRects the way Blink / Gecko
+    do, or the way WebKit (Safari) does - with one more, empty rect at the
+    end of the line above for a range that starts where a line wrapped.
+*/
+"use strict";
+var fs = require("fs");
+var path = require("path");
+
+global.window = global;
+/* eslint-disable no-eval */
+eval(fs.readFileSync(path.join(__dirname, "pdfcore.js"), "utf8") + "\nglobal.OfficePdfCore = OfficePdfCore;");
+var C = OfficePdfCore;
+
+var failures = 0, passes = 0;
+function eq(name, got, want) {
+    if (JSON.stringify(got) === JSON.stringify(want)) { passes++; return; }
+    failures++;
+    console.log("FAIL " + name + "\n  got:  " + JSON.stringify(got) + "\n  want: " + JSON.stringify(want));
+}
+
+/* ---- the stand-in layout ---- */
+var CHAR_W = 10, LINE_H = 20, GLYPH_H = 16;
+
+// lines: the node's text, one string per line box; lefts: where each line
+// starts (text-align); zero: characters drawn with no width (collapsed spaces)
+function layout(lines, o) {
+    o = o || {};
+    var chars = [];
+    lines.forEach(function (ln, li) {
+        var x = o.lefts ? o.lefts[li] : 0;
+        for (var i = 0; i < ln.length; i++) {
+            var w = o.zero && o.zero.indexOf(chars.length) >= 0 ? 0 : CHAR_W;
+            chars.push({ line: li, left: x, right: x + w });
+            x += w;
+        }
+    });
+    return { text: lines.join(""), chars: chars, lines: lines, webkit: !!o.webkit };
+}
+
+function rect(left, right, line) {
+    var top = line * LINE_H;
+    return { left: left, right: right, top: top, bottom: top + GLYPH_H, width: right - left, height: GLYPH_H };
+}
+
+function FakeRange() { this.node = null; this.s = 0; this.e = 0; }
+FakeRange.prototype.setStart = function (node, i) { this.node = node; this.s = i; };
+FakeRange.prototype.setEnd = function (node, i) { this.node = node; this.e = i; };
+FakeRange.prototype.selectNodeContents = function (node) { this.node = node; this.s = 0; this.e = node.text.length; };
+FakeRange.prototype.getClientRects = function () {
+    var n = this.node, out = [], cur = null;
+    for (var i = this.s; i < this.e; i++) {
+        var c = n.chars[i];
+        if (cur && cur.line === c.line) { cur.right = c.right; continue; }
+        if (cur) out.push(rect(cur.left, cur.right, cur.line));
+        cur = { line: c.line, left: c.left, right: c.right };
+    }
+    if (cur) out.push(rect(cur.left, cur.right, cur.line));
+    // WebKit: a range starting at a wrap also reports the end of the line above
+    var first = n.chars[this.s];
+    if (n.webkit && this.e > this.s && first.line > 0 && this.s > 0 && n.chars[this.s - 1].line === first.line - 1) {
+        var above = n.chars[this.s - 1];
+        out.unshift(rect(above.right, above.right, above.line));
+    }
+    return out;
+};
+// the union of every rect, empty ones included, as the browsers compute it
+FakeRange.prototype.getBoundingClientRect = function () {
+    var rs = this.getClientRects();
+    if (!rs.length) return rect(0, 0, 0);
+    var b = { left: rs[0].left, right: rs[0].right, top: rs[0].top, bottom: rs[0].bottom };
+    rs.forEach(function (r) {
+        b.left = Math.min(b.left, r.left); b.right = Math.max(b.right, r.right);
+        b.top = Math.min(b.top, r.top); b.bottom = Math.max(b.bottom, r.bottom);
+    });
+    return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.right - b.left, height: b.bottom - b.top };
+};
+global.document = { createRange: function () { return new FakeRange(); } };
+
+// what splitByLine makes of a node: [start, text, left, right] per line
+function split(node) {
+    var r = new FakeRange();
+    r.selectNodeContents(node);
+    return C.splitByLine(node, node.text, r.getClientRects()).map(function (ln) {
+        return [ln.start, ln.text, ln.rect.left, ln.rect.right];
+    });
+}
+
+/* ---- rangeBox ---- */
+(function () {
+    var n = layout(["Basics of ", "Reverse Proxy"], { webkit: true });
+    var r = new FakeRange();
+    r.setStart(n, 10); r.setEnd(n, 11);
+    var b = C.rangeBox(r);
+    eq("rangeBox skips WebKit's empty rect", [b.left, b.right, b.top, b.width], [0, 10, LINE_H, 10]);
+    eq("the bounding box does not", r.getBoundingClientRect().top, 0);
+
+    // a short line under a long one: the bounding box is as wide as the
+    // line above, which fitted the text to the wrong width
+    var s = layout(["& why they are commonly used in ", "Homelab setups"], { webkit: true });
+    r.setStart(s, 32); r.setEnd(s, 46);
+    eq("rangeBox of a wrapped line is that line", [C.rangeBox(r).left, C.rangeBox(r).width], [0, 140]);
+    eq("the bounding box is the line above's width", r.getBoundingClientRect().width, 320);
+
+    r.setStart(n, 0); r.setEnd(n, 23);
+    b = C.rangeBox(r);
+    eq("rangeBox unions the lines", [b.left, b.right, b.top, b.bottom], [0, 130, 0, LINE_H + GLYPH_H]);
+
+    var z = layout(["a ", "b"], { zero: [1] });
+    r.setStart(z, 1); r.setEnd(z, 2);
+    eq("rangeBox of a collapsed space is null", C.rangeBox(r), null);
+})();
+
+/* ---- splitByLine: the same lines whichever engine measured them ---- */
+[
+    {
+        name: "a wrapped title",
+        lines: ["Basics of ", "Reverse Proxy"],
+        want: [[0, "Basics of ", 0, 100], [10, "Reverse Proxy", 0, 130]]
+    },
+    {
+        name: "a subtitle",
+        lines: ["& why they are commonly used in ", "Homelab setups"],
+        want: [[0, "& why they are commonly used in ", 0, 320], [32, "Homelab setups", 0, 140]]
+    },
+    {
+        name: "CJK broken before its punctuation",
+        lines: ["明明只是想遠端控制我的主機,", "結果一不小心就做出一套開源 ", "USB / IP KVM 的這件事"],
+        want: [
+            [0, "明明只是想遠端控制我的主機,", 0, 140],
+            [14, "結果一不小心就做出一套開源 ", 0, 140],
+            [28, "USB / IP KVM 的這件事", 0, 170]
+        ]
+    },
+    {
+        name: "centred lines keep their own left",
+        lines: ["A centred line that wraps onto ", "a short one"],
+        lefts: [5, 100],
+        want: [[0, "A centred line that wraps onto ", 5, 315], [31, "a short one", 100, 210]]
+    },
+    {
+        name: "a word broken mid-way",
+        lines: ["Supercalifragilistic", "expialidocious"],
+        want: [[0, "Supercalifragilistic", 0, 200], [20, "expialidocious", 0, 140]]
+    }
+].forEach(function (tc) {
+    eq(tc.name + " (Blink / Gecko)", split(layout(tc.lines, { lefts: tc.lefts })), tc.want);
+    eq(tc.name + " (WebKit)", split(layout(tc.lines, { lefts: tc.lefts, webkit: true })), tc.want);
+});
+
+// spaces collapsed to nothing at the start of a line draw nothing: they
+// stay with the line before, and the next line starts at its first ink
+eq("collapsed spaces never open a line",
+    split(layout(["one ", "  two"], { zero: [4, 5] })),
+    [[0, "one   ", 0, 40], [6, "two", 0, 30]]);
+eq("collapsed spaces never open a line (WebKit)",
+    split(layout(["one ", "  two"], { zero: [4, 5], webkit: true })),
+    [[0, "one   ", 0, 40], [6, "two", 0, 30]]);
+eq("one line is handed back whole",
+    split(layout(["Reverse Proxy"], { webkit: true })),
+    [[0, "Reverse Proxy", 0, 130]]);
+
+console.log((failures ? "FAILED " + failures : "ok") + " (" + passes + " passed)");
+process.exit(failures ? 1 : 0);