@deepseek-ai/libreoffice-kit 0.0.2-rc4 → 0.0.2-rc6

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 (48) hide show
  1. package/NOTICE +238 -0
  2. package/README.md +5 -3
  3. package/README.zh.md +3 -3
  4. package/assets/font-subset.json +4 -4
  5. package/lib/browser/assets.json +2 -2
  6. package/lib/browser/index.js +92 -72
  7. package/lib/browser/types/connection.d.ts +3 -3
  8. package/lib/browser/types/font-channel.d.ts +5 -4
  9. package/lib/browser/types/index.d.ts +2 -2
  10. package/lib/browser/types/office-engine.d.ts +48 -0
  11. package/lib/browser/types/office-types.d.ts +107 -0
  12. package/lib/browser/types/office.d.ts +4 -0
  13. package/lib/browser/types/protocol.d.ts +34 -37
  14. package/lib/browser/types/types.d.ts +3 -1
  15. package/lib/browser/worker.js +338 -507
  16. package/lib/browser-assets.js +1 -1
  17. package/lib/cli.js +91 -58
  18. package/lib/font-source.js +89 -56
  19. package/lib/font-worker.js +717 -45
  20. package/lib/index.js +91 -58
  21. package/lib/types/default-fonts.d.ts +3 -0
  22. package/lib/types/engine.d.ts +1 -1
  23. package/lib/types/font-preferences-data.d.ts +16 -0
  24. package/lib/types/font-preferences.d.ts +29 -0
  25. package/lib/types/font-source-types.d.ts +2 -0
  26. package/lib/types/fonts.d.ts +11 -8
  27. package/lib/types/options.d.ts +1 -1
  28. package/lib/worker.js +707 -37
  29. package/package.json +3 -3
  30. package/sources/browser/packages/browser/package.json +2 -2
  31. package/sources/browser/packages/browser/src/connection.ts +8 -10
  32. package/sources/browser/packages/browser/src/font-channel.ts +22 -12
  33. package/sources/browser/packages/browser/src/index.ts +3 -3
  34. package/sources/browser/packages/browser/src/office-engine.ts +323 -0
  35. package/sources/browser/packages/browser/src/office-types.ts +77 -0
  36. package/sources/browser/packages/browser/src/office.ts +62 -0
  37. package/sources/browser/packages/browser/src/protocol.ts +19 -18
  38. package/sources/browser/packages/browser/src/types.ts +3 -1
  39. package/sources/browser/packages/browser/src/worker.ts +37 -33
  40. package/sources/browser/scripts/build-browser.mjs +9 -1
  41. package/sources/font-subset/scripts/platform-matrix.mjs +1 -1
  42. package/sources/font-subset/scripts/verify-artifacts.mjs +2 -2
  43. package/lib/browser/types/editor-engine.d.ts +0 -50
  44. package/lib/browser/types/editor-types.d.ts +0 -141
  45. package/lib/browser/types/editor.d.ts +0 -9
  46. package/sources/browser/packages/browser/src/editor-engine.ts +0 -382
  47. package/sources/browser/packages/browser/src/editor-types.ts +0 -106
  48. package/sources/browser/packages/browser/src/editor.ts +0 -55
@@ -2457,7 +2457,7 @@ ${XMLNS_NAMESPACE}.`);
2457
2457
  bytes: new Uint8Array(channel, 8)
2458
2458
  };
2459
2459
  }
2460
- /** The synchronous reader installs immutable subsets before returning their MEMFS paths and aliases. */
2460
+ /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
2461
2461
  function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing) {
2462
2462
  const { control, bytes } = fontViews(channel);
2463
2463
  const installed = /* @__PURE__ */ new Map();
@@ -2493,7 +2493,11 @@ ${XMLNS_NAMESPACE}.`);
2493
2493
  const key = JSON.stringify(original);
2494
2494
  const cached = requests.get(key);
2495
2495
  if (cached) return cached;
2496
- request(original);
2496
+ request(original, [...installed].map(([id, font]) => ({
2497
+ id,
2498
+ bytes: font.bytes,
2499
+ ...font.format ? { format: font.format } : {}
2500
+ })));
2497
2501
  const first = read();
2498
2502
  if (first.state !== 1) throw new BrowserRenderError("font-unavailable", "Expected font transfer metadata.");
2499
2503
  let header;
@@ -2511,15 +2515,17 @@ ${XMLNS_NAMESPACE}.`);
2511
2515
  "otf",
2512
2516
  "ttc"
2513
2517
  ].includes(font.format)) throw new BrowserRenderError("font-unavailable", "Invalid full font format.");
2518
+ if (font.reference !== void 0 && font.reference !== true) throw new BrowserRenderError("font-unavailable", "Invalid font reference descriptor.");
2514
2519
  const prior = installed.get(font.id);
2515
- if (prior && (prior.format !== font.format || font.format === void 0 && prior.face.family !== font.alias)) throw new BrowserRenderError("font-unavailable", "Font identity has conflicting aliases or formats.");
2520
+ if (font.reference && !prior) throw new BrowserRenderError("font-unavailable", "Font reference has not been installed.");
2521
+ if (prior && (prior.bytes !== font.bytes || prior.format !== font.format || font.format === void 0 && prior.face.family !== font.alias)) throw new BrowserRenderError("font-unavailable", "Font identity has conflicting bytes, aliases or formats.");
2516
2522
  const alias = normalize(font.alias);
2517
2523
  const previousAlias = aliases.get(alias);
2518
2524
  if (previousAlias && (previousAlias.family !== font.family || font.format === void 0 && previousAlias.id !== font.id)) throw new BrowserRenderError("font-unavailable", "Font alias identifies conflicting subsets.");
2519
2525
  if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2520
2526
  const buffer = prior ? void 0 : new Uint8Array(font.bytes);
2521
2527
  let received = 0;
2522
- while (received < font.bytes) {
2528
+ while (!font.reference && received < font.bytes) {
2523
2529
  const frame = read();
2524
2530
  if (frame.state !== 2 || frame.data.length === 0 || received + frame.data.length > font.bytes) throw new BrowserRenderError("font-unavailable", "Incomplete font file transfer.");
2525
2531
  buffer?.set(frame.data, received);
@@ -2533,6 +2539,7 @@ ${XMLNS_NAMESPACE}.`);
2533
2539
  install(face.path, buffer);
2534
2540
  installed.set(font.id, {
2535
2541
  face,
2542
+ bytes: buffer.length,
2536
2543
  format: font.format
2537
2544
  });
2538
2545
  loadedBytes += buffer.length;
@@ -2557,14 +2564,6 @@ ${XMLNS_NAMESPACE}.`);
2557
2564
  //#region ../entry/lib/sheet-geometry.js
2558
2565
  const MAX_COLUMN = 16383;
2559
2566
  const MAX_ROW = 1048575;
2560
- function column(index) {
2561
- let name = "";
2562
- for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) name = String.fromCharCode(65 + (value - 1) % 26) + name;
2563
- return name;
2564
- }
2565
- function rangeName(range) {
2566
- return `${column(range.firstColumn)}${range.firstRow + 1}:${column(range.lastColumn)}${range.lastRow + 1}`;
2567
- }
2568
2567
  function parseCellRange(value) {
2569
2568
  const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?$/i.exec(value);
2570
2569
  if (!match) throw new TypeError("range must be an A1 cell or rectangle without a sheet prefix.");
@@ -2581,92 +2580,10 @@ ${XMLNS_NAMESPACE}.`);
2581
2580
  lastRow
2582
2581
  };
2583
2582
  }
2584
- function sheetPartInfo(value) {
2585
- const info = JSON.parse(value);
2586
- if (!info || typeof info.name !== "string" || ![0, 1].includes(info.visible) || ![0, 1].includes(info.rtllayout) || !Number.isInteger(info.lastcolumn) || !Number.isInteger(info.lastrow) || info.lastcolumn < 0 || info.lastrow < 0 || info.lastcolumn > MAX_COLUMN || info.lastrow > MAX_ROW) throw new Error("LibreOffice returned invalid worksheet data-area metadata.");
2587
- return info;
2588
- }
2589
- /** Formatting-only cells and standalone drawings do not enlarge LibreOffice's data area. */
2590
- function dataArea(info) {
2591
- return {
2592
- firstColumn: 0,
2593
- firstRow: 0,
2594
- lastColumn: info.lastcolumn,
2595
- lastRow: info.lastrow
2596
- };
2597
- }
2598
- function spans(encoded, flags, maximum) {
2599
- if (typeof encoded !== "string" || encoded.length > 33554432) throw new Error("Invalid worksheet geometry span encoding.");
2600
- const tokens = encoded.trim().split(/\s+/);
2601
- let previous = -1;
2602
- let flag = 0;
2603
- const result = tokens.map((token, i) => {
2604
- const fields = token.split(":");
2605
- let value;
2606
- let end;
2607
- if (flags && i > 0) {
2608
- value = flag = 1 - flag;
2609
- end = Number(fields[0]);
2610
- if (fields.length !== 1) throw new Error("Invalid worksheet flag span.");
2611
- } else {
2612
- value = Number(fields[0]);
2613
- end = Number(fields[1]);
2614
- flag = value;
2615
- if (fields.length !== 2) throw new Error("Invalid worksheet size span.");
2616
- }
2617
- if (!Number.isSafeInteger(value) || value < 0 || (flags ? value > 1 : value > 65535) || !Number.isSafeInteger(end) || end <= previous || end > maximum) throw new Error("Invalid worksheet geometry span.");
2618
- previous = end;
2619
- return {
2620
- end,
2621
- value
2622
- };
2623
- });
2624
- if (previous !== maximum) throw new Error("Worksheet geometry does not cover the complete dimension.");
2625
- return result;
2626
- }
2627
- function dimension(data, first, last, maximum, scale) {
2628
- const sizes = spans(data?.sizes, false, maximum);
2629
- const hidden = spans(data?.hidden, true, maximum);
2630
- const filtered = spans(data?.filtered, true, maximum);
2631
- let position = 0, start = 0, index = 0, si = 0, hi = 0, fi = 0;
2632
- while (index <= last) {
2633
- const size = sizes[si], hide = hidden[hi], filter = filtered[fi];
2634
- const end = Math.min(size.end, hide.end, filter.end, last, index < first ? first - 1 : last);
2635
- const pixels = hide.value || filter.value || size.value === 0 ? 0 : Math.max(1, Math.floor(size.value * scale / 15));
2636
- if (index === first) start = position;
2637
- position += (end - index + 1) * pixels;
2638
- index = end + 1;
2639
- if (index > size.end) si++;
2640
- if (index > hide.end) hi++;
2641
- if (index > filter.end) fi++;
2642
- }
2643
- return [start / scale, (position - start) / scale];
2644
- }
2645
- /** Logical columns advance from A; LOK itself mirrors RTL sheet painting. No manual x inversion. */
2646
- function sheetRangeRectangle(geometry, range, scale) {
2647
- if (!Number.isFinite(scale) || scale <= 0 || scale > 16) throw new TypeError("Invalid worksheet raster scale.");
2648
- const [x, width] = dimension(geometry.columns, range.firstColumn, range.lastColumn, MAX_COLUMN, scale);
2649
- const [y, height] = dimension(geometry.rows, range.firstRow, range.lastRow, MAX_ROW, scale);
2650
- if (width <= 0 || height <= 0) throw new Error("The selected worksheet range is entirely hidden or filtered.");
2651
- if ([
2652
- x,
2653
- y,
2654
- width,
2655
- height,
2656
- x + width,
2657
- y + height
2658
- ].some((value) => !Number.isFinite(value) || value * 15 > 2147483647)) throw new Error("The selected worksheet range exceeds the supported coordinate range.");
2659
- return {
2660
- x,
2661
- y,
2662
- width,
2663
- height
2664
- };
2665
- }
2666
2583
  //#endregion
2667
2584
  //#region ../entry/lib/engine-rendering.js
2668
2585
  /** Validate coordinates before allocation or wasm32 integer conversion. */
2669
- function tileDimensions$1(request, pages) {
2586
+ function tileDimensions(request, pages) {
2670
2587
  const page = pages[request.pageIndex];
2671
2588
  if (!Number.isSafeInteger(request.pageIndex) || !page || ![
2672
2589
  request.x,
@@ -2712,7 +2629,7 @@ ${XMLNS_NAMESPACE}.`);
2712
2629
  /** Paint into a temporary allocation; copy pixels before free or another engine call. */
2713
2630
  function renderRegion(module, document, request, pages, failure, pdf = false) {
2714
2631
  const call = (name, args) => numericCall(module, name, args);
2715
- const { page, width, height } = tileDimensions$1(request, pages);
2632
+ const { page, width, height } = tileDimensions(request, pages);
2716
2633
  const size = width * height * 4;
2717
2634
  const pointer = call("malloc", [size]);
2718
2635
  if (!pointer) throw failure();
@@ -2790,35 +2707,9 @@ ${XMLNS_NAMESPACE}.`);
2790
2707
  if (pages.length === 0) throw new Error("LibreOffice returned no document pages.");
2791
2708
  return pages;
2792
2709
  }
2793
- /** Validate coordinates before allocation or wasm32 integer conversion. */
2794
- function tileDimensions(request, pages) {
2795
- const page = pages[request.pageIndex];
2796
- if (!Number.isSafeInteger(request.pageIndex) || !page || ![
2797
- request.x,
2798
- request.y,
2799
- request.width,
2800
- request.height,
2801
- request.scale
2802
- ].every(Number.isFinite) || request.x < 0 || request.y < 0 || request.width <= 0 || request.height <= 0 || request.scale <= 0 || request.x + request.width > page.width + .001 || request.y + request.height > page.height + .001) throw new Error("Tile rectangle lies outside its page.");
2803
- const width = Math.ceil(request.width * request.scale - 1e-9);
2804
- const height = Math.ceil(request.height * request.scale - 1e-9);
2805
- if (width <= 0 || height <= 0 || !Number.isSafeInteger(width * height) || width * height > 16777216) throw new Error("Tile exceeds the 16 megapixel allocation limit.");
2806
- const twips = [
2807
- page.x + Math.round(request.x * 15),
2808
- page.y + Math.round(request.y * 15),
2809
- Math.round(request.width * 15),
2810
- Math.round(request.height * 15)
2811
- ];
2812
- if (twips.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || twips[0] + twips[2] > 2147483647 || twips[1] + twips[3] > 2147483647) throw new Error("Tile coordinates exceed the wasm32 range.");
2813
- return {
2814
- page,
2815
- width,
2816
- height
2817
- };
2818
- }
2819
2710
  //#endregion
2820
- //#region lib/types/editor-engine.js
2821
- /** Worker-owned editing, VCL event slices and immutable editing notifications. */
2711
+ //#region lib/types/office-engine.js
2712
+ /** Worker-owned reading, bounded VCL event slices and immutable notifications. */
2822
2713
  function rectangle(payload) {
2823
2714
  if (payload.startsWith("{")) {
2824
2715
  const value = JSON.parse(payload);
@@ -2844,46 +2735,50 @@ ${XMLNS_NAMESPACE}.`);
2844
2735
  if (!Number.isFinite(value) || Math.abs(value * 15) > 2147483647) throw new BrowserRenderError("render-failed", "Office input lies outside document coordinates.");
2845
2736
  return Math.round(value * 15);
2846
2737
  }
2847
- /** One editor, driven exclusively by its owning Worker's messages and timer. */
2848
- var EditorEngine = class {
2738
+ const navigationKeys = {
2739
+ down: 1024,
2740
+ up: 1025,
2741
+ left: 1026,
2742
+ right: 1027,
2743
+ home: 1028,
2744
+ end: 1029,
2745
+ pageUp: 1030,
2746
+ pageDown: 1031
2747
+ };
2748
+ /** One read-only document, driven exclusively by its Worker's messages and timer. */
2749
+ var OfficeEngine = class {
2849
2750
  module;
2850
2751
  document;
2851
- format;
2852
- maxBytes;
2853
2752
  emit;
2854
2753
  failure;
2855
- readOnly;
2856
2754
  state;
2857
2755
  timer;
2858
2756
  callbacks = [];
2859
- phase = "view";
2860
- modified = false;
2861
2757
  geometryDirty = false;
2862
2758
  stopped = false;
2863
- renderView = -1;
2759
+ layoutWidth = 0;
2760
+ viewport = "";
2761
+ captureView;
2762
+ readingView;
2864
2763
  commandResult;
2865
- constructor(module, document, format, maxBytes, emit, failure, readOnly = false) {
2764
+ constructor(module, document, format, emit, failure) {
2866
2765
  this.module = module;
2867
2766
  this.document = document;
2868
- this.format = format;
2869
- this.maxBytes = maxBytes;
2870
2767
  this.emit = emit;
2871
2768
  this.failure = failure;
2872
- this.readOnly = readOnly;
2873
2769
  this.state = {
2874
2770
  documentType: format === "docx" || format === "doc" ? "text" : format === "xlsx" || format === "xls" ? "spreadsheet" : "presentation",
2875
- revision: 0,
2876
2771
  renderGeneration: 0,
2772
+ layoutGeneration: 0,
2773
+ layout: "paginated",
2877
2774
  part: 0,
2878
2775
  parts: [],
2879
2776
  pages: [],
2880
2777
  cursor: null,
2881
- cursorVisible: false,
2882
2778
  selection: [],
2883
2779
  graphicSelection: null,
2884
2780
  cellAddress: "",
2885
- cellFormula: "",
2886
- commands: {}
2781
+ cellFormula: ""
2887
2782
  };
2888
2783
  }
2889
2784
  call(name, args = []) {
@@ -2902,32 +2797,41 @@ ${XMLNS_NAMESPACE}.`);
2902
2797
  if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError("render-failed", `LibreOffice could not complete ${name}.`);
2903
2798
  }
2904
2799
  requireOpen() {
2905
- if (this.stopped) throw new BrowserRenderError("disposed", "Office editor is closed.");
2800
+ if (this.stopped) throw new BrowserRenderError("disposed", "Office document is closed.");
2906
2801
  }
2907
- /** Collect callbacks without reentering LibreOffice from inside its own callback. */
2802
+ /** Collect callbacks without reentering LibreOffice inside its callback. */
2908
2803
  callback(type, payload) {
2909
2804
  if (!this.stopped) this.callbacks.push({
2910
2805
  type,
2911
- payload,
2912
- phase: this.phase
2806
+ payload
2913
2807
  });
2914
2808
  }
2915
- /** Register callbacks after document initialization, then begin bounded event slices. */
2809
+ /** Enforce the native read-only view before accepting any input. */
2916
2810
  async start() {
2917
2811
  this.requireOpen();
2812
+ if (this.state.documentType === "presentation") {
2813
+ const view = this.call("dsh_lok_document_get_view", [this.document]);
2814
+ try {
2815
+ const created = this.call("dsh_lok_document_create_view", [this.document]);
2816
+ if (created < 0) throw new BrowserRenderError("render-failed", "LibreOffice could not create a slide capture view.");
2817
+ this.captureView = created;
2818
+ this.invoke("initialize_rendering");
2819
+ this.configure({ mode: "paginated" });
2820
+ this.pump();
2821
+ } finally {
2822
+ this.invoke("set_view", [view]);
2823
+ }
2824
+ this.readingView = view;
2825
+ }
2826
+ this.configure({ mode: "paginated" });
2918
2827
  this.invoke("listen");
2919
2828
  this.refreshGeometry();
2920
2829
  this.pump();
2921
2830
  this.schedule();
2922
2831
  await this.command(".uno:ReportWhenIdle", { idleID: {
2923
2832
  type: "string",
2924
- value: "editor-open"
2833
+ value: "office-open"
2925
2834
  } });
2926
- this.state = {
2927
- ...this.state,
2928
- revision: 0
2929
- };
2930
- this.phase = "idle";
2931
2835
  }
2932
2836
  schedule() {
2933
2837
  this.timer = setTimeout(() => {
@@ -2941,23 +2845,18 @@ ${XMLNS_NAMESPACE}.`);
2941
2845
  }
2942
2846
  }, 16);
2943
2847
  }
2944
- /** Cancel the owned timer before the document or office is destroyed. */
2848
+ /** Stop event processing before destroying the document. */
2945
2849
  stop() {
2946
2850
  this.stopped = true;
2947
2851
  clearTimeout(this.timer);
2948
2852
  this.callbacks.length = 0;
2949
- this.commandResult?.reject(new BrowserRenderError("disposed", "Office editor is closed."));
2853
+ this.commandResult?.reject(new BrowserRenderError("disposed", "Office document is closed."));
2950
2854
  this.commandResult = void 0;
2951
- if (this.renderView >= 0) {
2952
- this.call("dsh_lok_document_destroy_view", [this.document, this.renderView]);
2953
- this.renderView = -1;
2954
- }
2955
2855
  }
2856
+ /** Return the part whose cached coordinates changed, or -1 when part identities changed. */
2956
2857
  refreshGeometry() {
2957
- const phase = this.phase;
2958
- this.phase = "view";
2959
2858
  const count = this.state.documentType === "text" ? 1 : this.call("dsh_lok_document_parts", [this.document]);
2960
- if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError("invalid-document", "Office document has no editable parts.");
2859
+ if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError("invalid-document", "Office document has no parts.");
2961
2860
  const pointer = this.call("malloc", [8]);
2962
2861
  if (!pointer) throw new BrowserRenderError("render-failed", "Office geometry allocation failed.");
2963
2862
  try {
@@ -2975,44 +2874,49 @@ ${XMLNS_NAMESPACE}.`);
2975
2874
  width: index === part ? width : this.state.parts[index]?.width ?? width,
2976
2875
  height: index === part ? height : this.state.parts[index]?.height ?? height
2977
2876
  }));
2978
- const pages = this.state.documentType === "text" ? writerPages(this.text("dsh_lok_document_page_rectangles", [this.document])).map((page) => ({
2877
+ const pages = this.state.documentType !== "text" ? [] : this.state.layout === "continuous" ? [{
2878
+ x: 0,
2879
+ y: 0,
2880
+ width,
2881
+ height
2882
+ }] : writerPages(this.text("dsh_lok_document_page_rectangles", [this.document])).map((page) => ({
2979
2883
  x: page.x / 15,
2980
2884
  y: page.y / 15,
2981
2885
  width: page.width,
2982
2886
  height: page.height
2983
- })) : [];
2887
+ }));
2888
+ const previous = this.state;
2889
+ const identitiesChanged = previous.parts.length > 0 && (previous.parts.length !== parts.length || parts.some((value, index) => value.name !== previous.parts[index].name));
2890
+ const measured = previous.parts[part];
2891
+ const geometryChanged = measured !== void 0 && (measured.width !== width || measured.height !== height || JSON.stringify(previous.pages) !== JSON.stringify(pages));
2984
2892
  this.state = {
2985
- ...this.state,
2893
+ ...previous,
2986
2894
  part,
2987
2895
  parts,
2988
2896
  pages
2989
2897
  };
2898
+ this.geometryDirty = false;
2899
+ return identitiesChanged ? -1 : geometryChanged ? part : void 0;
2990
2900
  } finally {
2991
2901
  this.call("free", [pointer]);
2992
- this.phase = phase;
2993
2902
  }
2994
- this.geometryDirty = false;
2995
2903
  }
2996
2904
  pump() {
2905
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
2997
2906
  const deadline = performance.now() + 8;
2998
- const view = this.renderView >= 0 ? this.call("dsh_lok_document_get_view", [this.document]) : -1;
2999
- try {
3000
- for (let pass = 0; pass < 8; pass++) {
3001
- const result = this.call("dsh_lok_pump");
3002
- if (result < 0) throw new BrowserRenderError("render-failed", "LibreOffice event processing failed.");
3003
- if (!result || performance.now() >= deadline) break;
3004
- }
3005
- } finally {
3006
- if (view >= 0 && !this.call("dsh_lok_document_set_view", [this.document, view])) throw new BrowserRenderError("render-failed", "The editor view could not be restored after event processing.");
2907
+ for (let pass = 0; pass < 8; pass++) {
2908
+ const result = this.call("dsh_lok_pump");
2909
+ if (result < 0) throw new BrowserRenderError("render-failed", "LibreOffice event processing failed.");
2910
+ if (!result || performance.now() >= deadline) break;
3007
2911
  }
2912
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3008
2913
  this.flush();
3009
2914
  }
3010
2915
  flush() {
3011
2916
  if (this.callbacks.length === 0) return;
3012
2917
  let changed = false;
3013
- let edited = false;
3014
2918
  const invalidations = [];
3015
- for (const { type, payload, phase } of this.callbacks.splice(0)) switch (type) {
2919
+ for (const { type, payload } of this.callbacks.splice(0)) switch (type) {
3016
2920
  case 0: {
3017
2921
  const fields = payload.split(",");
3018
2922
  const index = fields[0]?.trim() === "EMPTY" ? fields[1] : fields[4];
@@ -3021,15 +2925,10 @@ ${XMLNS_NAMESPACE}.`);
3021
2925
  part,
3022
2926
  rectangle: rectangle(payload)
3023
2927
  });
3024
- edited ||= ![
3025
- "paint",
3026
- "view",
3027
- "save",
3028
- "capture"
3029
- ].includes(phase);
3030
2928
  break;
3031
2929
  }
3032
2930
  case 1:
2931
+ case 17:
3033
2932
  this.state = {
3034
2933
  ...this.state,
3035
2934
  cursor: rectangle(payload)
@@ -3043,13 +2942,6 @@ ${XMLNS_NAMESPACE}.`);
3043
2942
  };
3044
2943
  changed = true;
3045
2944
  break;
3046
- case 5:
3047
- this.state = {
3048
- ...this.state,
3049
- cursorVisible: payload === "true"
3050
- };
3051
- changed = true;
3052
- break;
3053
2945
  case 6:
3054
2946
  this.state = {
3055
2947
  ...this.state,
@@ -3057,51 +2949,27 @@ ${XMLNS_NAMESPACE}.`);
3057
2949
  };
3058
2950
  changed = true;
3059
2951
  break;
3060
- case 8: {
3061
- const separator = payload.indexOf("=");
3062
- if (separator < 0) break;
3063
- const command = payload.slice(0, separator), value = payload.slice(separator + 1);
3064
- if (command === ".uno:ModifiedStatus") {
3065
- this.modified = value === "true";
3066
- edited ||= this.modified;
3067
- }
3068
- this.state = {
3069
- ...this.state,
3070
- commands: {
3071
- ...this.state.commands,
3072
- [command]: value
3073
- }
3074
- };
3075
- changed = true;
3076
- break;
3077
- }
3078
2952
  case 13:
3079
2953
  this.geometryDirty = true;
3080
- changed = true;
3081
2954
  break;
3082
2955
  case 14: {
3083
2956
  const part = Number(payload);
3084
- if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) this.state = {
3085
- ...this.state,
3086
- part
3087
- };
3088
- changed = true;
2957
+ if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
2958
+ this.state = {
2959
+ ...this.state,
2960
+ part
2961
+ };
2962
+ this.viewport = "";
2963
+ this.geometryDirty = true;
2964
+ changed = true;
2965
+ }
3089
2966
  break;
3090
2967
  }
3091
2968
  case 16: {
3092
2969
  const result = JSON.parse(payload);
3093
- if (typeof result !== "object" || result === null || !("commandName" in result) || result.commandName !== this.commandResult?.name) break;
3094
- this.commandResult.resolve();
2970
+ if (typeof result === "object" && result !== null && "commandName" in result && result.commandName === this.commandResult?.name) this.commandResult?.resolve();
3095
2971
  break;
3096
2972
  }
3097
- case 17:
3098
- this.state = {
3099
- ...this.state,
3100
- cursor: rectangle(payload),
3101
- cursorVisible: true
3102
- };
3103
- changed = true;
3104
- break;
3105
2973
  case 19:
3106
2974
  this.state = {
3107
2975
  ...this.state,
@@ -3116,21 +2984,27 @@ ${XMLNS_NAMESPACE}.`);
3116
2984
  };
3117
2985
  changed = true;
3118
2986
  }
3119
- if (edited && this.modified) {
2987
+ const geometry = this.geometryDirty ? this.refreshGeometry() : void 0;
2988
+ if (geometry !== void 0) {
3120
2989
  this.state = {
3121
2990
  ...this.state,
3122
- revision: this.state.revision + 1
2991
+ layoutGeneration: this.state.layoutGeneration + 1
3123
2992
  };
3124
- changed = true;
2993
+ if (!invalidations.some((value) => value.rectangle === null && (value.part === -1 || value.part === geometry))) {
2994
+ for (let index = invalidations.length - 1; index >= 0; index--) if (geometry === -1 || invalidations[index].part === geometry) invalidations.splice(index, 1);
2995
+ invalidations.push({
2996
+ part: geometry,
2997
+ rectangle: null
2998
+ });
2999
+ }
3125
3000
  }
3126
- if (invalidations.length > 0 || this.geometryDirty) {
3001
+ if (invalidations.length > 0) {
3127
3002
  this.state = {
3128
3003
  ...this.state,
3129
3004
  renderGeneration: this.state.renderGeneration + 1
3130
3005
  };
3131
3006
  changed = true;
3132
3007
  }
3133
- if (this.geometryDirty) this.refreshGeometry();
3134
3008
  if (changed) this.emit({
3135
3009
  type: "state",
3136
3010
  state: this.state
@@ -3138,109 +3012,191 @@ ${XMLNS_NAMESPACE}.`);
3138
3012
  for (const invalidation of invalidations) this.emit({
3139
3013
  type: "invalidate",
3140
3014
  ...invalidation,
3141
- revision: this.state.revision
3015
+ generation: this.state.renderGeneration
3142
3016
  });
3143
3017
  }
3144
- /** Apply one ordered command and collect the resulting notifications before acknowledgement. */
3018
+ /** The Worker permits only these typed reading operations, including at runtime. */
3145
3019
  async operation(operation) {
3146
3020
  this.requireOpen();
3147
- if (this.readOnly && [
3148
- "input",
3149
- "command",
3150
- "paste",
3151
- "save"
3152
- ].includes(operation.type)) throw new BrowserRenderError("render-failed", "This Office document is read-only.");
3153
- this.phase = operation.type === "part" || operation.type === "viewport" ? "view" : operation.type === "save" ? "save" : "edit";
3154
- try {
3155
- switch (operation.type) {
3156
- case "input": {
3157
- const event = operation.event;
3158
- if (event.type === "key") this.invoke("key", [
3159
- event.action === "down" ? 0 : 1,
3160
- integer(event.character, 1114111),
3161
- integer(event.key, 65535)
3162
- ]);
3163
- else if (event.type === "pointer") this.invoke("mouse", [
3164
- event.action === "down" ? 0 : event.action === "up" ? 1 : 2,
3165
- twips(event.x),
3166
- twips(event.y),
3167
- integer(event.clicks, 3),
3168
- integer(event.buttons, 7),
3169
- integer(event.modifiers, 65535)
3170
- ]);
3171
- else {
3172
- this.checkText(event.text);
3173
- this.invoke("composition", [event.action === "update" ? 0 : 2, event.text]);
3174
- }
3175
- break;
3176
- }
3177
- case "command":
3178
- if (!/^\.uno:[A-Za-z][A-Za-z0-9]*$/.test(operation.command)) throw new BrowserRenderError("render-failed", "Office command must name a UNO command.");
3179
- await this.command(operation.command, operation.arguments ?? {});
3180
- break;
3181
- case "paste":
3182
- this.checkText(operation.text);
3183
- this.invoke("paste", [
3184
- "text/plain;charset=utf-8",
3185
- operation.text,
3186
- new TextEncoder().encode(operation.text).byteLength
3187
- ]);
3188
- break;
3189
- case "copy": return { text: this.text("dsh_lok_document_selection", [this.document]) };
3190
- case "part": {
3191
- const part = integer(operation.part, this.state.parts.length - 1);
3192
- this.invoke("part", [part]);
3193
- this.state = {
3194
- ...this.state,
3195
- part,
3196
- cursor: null,
3197
- selection: [],
3198
- graphicSelection: null
3199
- };
3200
- this.refreshGeometry();
3201
- this.emit({
3202
- type: "state",
3203
- state: this.state
3204
- });
3205
- break;
3206
- }
3207
- case "viewport": {
3208
- const { x, y, width, height } = operation.rectangle;
3209
- if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError("render-failed", "Office viewport is invalid.");
3210
- this.invoke("viewport", [
3211
- Math.max(1, Math.round(256 * operation.scale)),
3212
- 3840,
3213
- twips(x),
3214
- twips(y),
3215
- twips(width),
3216
- twips(height)
3217
- ]);
3218
- break;
3021
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3022
+ if (!operation || typeof operation !== "object") throw new BrowserRenderError("render-failed", "Invalid Office reading operation.");
3023
+ switch (operation.type) {
3024
+ case "pointer": {
3025
+ const event = operation.event;
3026
+ if (!event || ![
3027
+ "down",
3028
+ "up",
3029
+ "move"
3030
+ ].includes(event.action) || ![0, 1].includes(event.buttons) || ![
3031
+ 0,
3032
+ 4096,
3033
+ 8192,
3034
+ 12288
3035
+ ].includes(event.modifiers)) throw new BrowserRenderError("render-failed", "Invalid Office selection pointer.");
3036
+ this.invoke("mouse", [
3037
+ event.action === "down" ? 0 : event.action === "up" ? 1 : 2,
3038
+ twips(event.x),
3039
+ twips(event.y),
3040
+ integer(event.clicks, 3),
3041
+ event.buttons,
3042
+ event.modifiers
3043
+ ]);
3044
+ break;
3045
+ }
3046
+ case "navigate": {
3047
+ const event = operation.event;
3048
+ if (!event || !Object.hasOwn(navigationKeys, event.key) || event.extend !== void 0 && typeof event.extend !== "boolean" || event.word !== void 0 && typeof event.word !== "boolean") throw new BrowserRenderError("render-failed", "Invalid Office navigation key.");
3049
+ const key = navigationKeys[event.key] | (event.extend ? 4096 : 0) | (event.word ? 8192 : 0);
3050
+ this.invoke("key", [
3051
+ 0,
3052
+ 0,
3053
+ key
3054
+ ]);
3055
+ this.invoke("key", [
3056
+ 1,
3057
+ 0,
3058
+ key
3059
+ ]);
3060
+ break;
3061
+ }
3062
+ case "select-all":
3063
+ await this.command(".uno:SelectAll", {});
3064
+ break;
3065
+ case "cell":
3066
+ if (this.state.documentType !== "spreadsheet" || typeof operation.address !== "string") throw new BrowserRenderError("render-failed", "Cell navigation requires a spreadsheet address.");
3067
+ try {
3068
+ parseCellRange(operation.address);
3069
+ } catch {
3070
+ throw new BrowserRenderError("render-failed", "Cell navigation requires a bounded A1 cell or range.");
3219
3071
  }
3220
- case "save": {
3221
- this.pump();
3222
- const path = `/dsh/export.${this.format}`;
3223
- this.invoke("save", [`file://${path}`, this.format]);
3224
- const data = this.module.FS.readFile(path);
3225
- this.module.FS.unlink(path);
3226
- if (data.length === 0 || data.length > this.maxBytes) throw new BrowserRenderError("render-failed", "Office export exceeds the configured byte limit.");
3227
- this.pump();
3228
- return { snapshot: {
3229
- data,
3230
- revision: this.state.revision,
3231
- extension: this.format
3232
- } };
3072
+ await this.command(".uno:GoToCell", { ToPoint: {
3073
+ type: "string",
3074
+ value: operation.address
3075
+ } });
3076
+ break;
3077
+ case "copy":
3078
+ this.pump();
3079
+ return { text: this.text("dsh_lok_document_selection", [this.document]) };
3080
+ case "part": {
3081
+ const part = integer(operation.part, this.state.parts.length - 1);
3082
+ if (part === this.state.part) break;
3083
+ this.invoke("part", [part]);
3084
+ this.viewport = "";
3085
+ this.state = {
3086
+ ...this.state,
3087
+ part,
3088
+ cursor: null,
3089
+ selection: [],
3090
+ graphicSelection: null,
3091
+ cellAddress: "",
3092
+ cellFormula: ""
3093
+ };
3094
+ const geometry = this.refreshGeometry();
3095
+ if (geometry !== void 0) this.state = {
3096
+ ...this.state,
3097
+ layoutGeneration: this.state.layoutGeneration + 1,
3098
+ renderGeneration: this.state.renderGeneration + 1
3099
+ };
3100
+ this.emit({
3101
+ type: "state",
3102
+ state: this.state
3103
+ });
3104
+ if (geometry !== void 0) this.emit({
3105
+ type: "invalidate",
3106
+ part: geometry,
3107
+ rectangle: null,
3108
+ generation: this.state.renderGeneration
3109
+ });
3110
+ break;
3111
+ }
3112
+ case "viewport": {
3113
+ const { x, y, width, height } = operation.rectangle;
3114
+ if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError("render-failed", "Office viewport is invalid.");
3115
+ const args = [
3116
+ Math.max(1, Math.round(256 * operation.scale)),
3117
+ 3840,
3118
+ twips(x),
3119
+ twips(y),
3120
+ twips(width),
3121
+ twips(height)
3122
+ ];
3123
+ const key = args.join(",");
3124
+ if (key !== this.viewport) {
3125
+ this.invoke("viewport", args);
3126
+ this.viewport = key;
3233
3127
  }
3128
+ break;
3234
3129
  }
3235
- this.pump();
3236
- return {};
3237
- } finally {
3238
- this.phase = "idle";
3130
+ case "layout": {
3131
+ const request = operation.request;
3132
+ if (!request || !["paginated", "continuous"].includes(request.mode) || request.mode === "continuous" && this.state.documentType !== "text") throw new BrowserRenderError("render-failed", "Continuous layout is only available for Writer documents.");
3133
+ const width = request.mode === "continuous" ? twips(request.width) : 0;
3134
+ if (request.mode === "continuous" && width <= 0) throw new BrowserRenderError("render-failed", "Continuous layout requires a positive width.");
3135
+ if (request.anchor && (twips(request.anchor.x) < 0 || twips(request.anchor.y) < 0)) throw new BrowserRenderError("render-failed", "Reading anchors must lie within positive document coordinates.");
3136
+ if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } };
3137
+ const result = this.configure(request);
3138
+ this.layoutWidth = width;
3139
+ this.viewport = "";
3140
+ this.state = {
3141
+ ...this.state,
3142
+ layout: request.mode,
3143
+ layoutGeneration: this.state.layoutGeneration + 1,
3144
+ renderGeneration: this.state.renderGeneration + 1
3145
+ };
3146
+ this.refreshGeometry();
3147
+ await this.command(".uno:ReportWhenIdle", { idleID: {
3148
+ type: "string",
3149
+ value: "office-layout"
3150
+ } });
3151
+ this.refreshGeometry();
3152
+ this.emit({
3153
+ type: "state",
3154
+ state: this.state
3155
+ });
3156
+ this.emit({
3157
+ type: "invalidate",
3158
+ part: -1,
3159
+ rectangle: null,
3160
+ generation: this.state.renderGeneration
3161
+ });
3162
+ return { layout: result };
3163
+ }
3164
+ default: throw new BrowserRenderError("render-failed", "Unsupported Office reading operation.");
3239
3165
  }
3166
+ this.pump();
3167
+ return {};
3240
3168
  }
3241
- checkText(text) {
3242
- if (typeof text !== "string" || text.includes("\0") || new TextEncoder().encode(text).length > this.maxBytes) throw new BrowserRenderError("render-failed", "Office input exceeds the text limit or contains NUL.");
3169
+ configure(request) {
3170
+ const raw = this.text("dsh_lok_document_configure_view", [
3171
+ this.document,
3172
+ 1,
3173
+ request.mode === "continuous" ? 1 : 0,
3174
+ request.mode === "continuous" ? twips(request.width) : 0,
3175
+ request.anchor ? twips(request.anchor.x) : -1,
3176
+ request.anchor ? twips(request.anchor.y) : -1
3177
+ ]);
3178
+ if (!raw) throw new BrowserRenderError("render-failed", "LibreOffice could not configure its read-only view.");
3179
+ const result = JSON.parse(raw);
3180
+ if (typeof result.changed !== "boolean" || !(result.width > 0 && result.height > 0)) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid reading layout.");
3181
+ if (result.anchor === void 0) return { changed: result.changed };
3182
+ const { x, y, width, height } = result.anchor;
3183
+ if (![
3184
+ x,
3185
+ y,
3186
+ width,
3187
+ height
3188
+ ].every((value) => Number.isFinite(value) && value >= 0)) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid reading anchor.");
3189
+ return {
3190
+ changed: result.changed,
3191
+ anchor: {
3192
+ x: x / 15,
3193
+ y: y / 15,
3194
+ width: width / 15,
3195
+ height: height / 15
3196
+ }
3197
+ };
3243
3198
  }
3199
+ /** Internal whitelist commands only; no arbitrary command crosses the public API. */
3244
3200
  async command(name, args) {
3245
3201
  const result = Promise.withResolvers();
3246
3202
  this.commandResult = {
@@ -3256,12 +3212,16 @@ ${XMLNS_NAMESPACE}.`);
3256
3212
  this.commandResult = void 0;
3257
3213
  }
3258
3214
  }
3259
- /** Painting preserves the active selection and cannot itself mark the document edited. */
3215
+ /** Direct tiles preserve the active view, navigation state and selection. */
3260
3216
  render(request) {
3261
3217
  this.requireOpen();
3218
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3219
+ this.flush();
3262
3220
  const part = this.state.parts[integer(request.part, this.state.parts.length - 1)];
3263
- this.phase = "paint";
3221
+ const capture = request.part !== this.state.part;
3222
+ if (capture && this.state.documentType !== "presentation") throw new BrowserRenderError("stale-part", "The Office tile belongs to an inactive worksheet.");
3264
3223
  try {
3224
+ if (capture) this.invoke("set_view", [this.captureView]);
3265
3225
  return renderRegion(this.module, this.document, {
3266
3226
  ...request,
3267
3227
  pageIndex: 0
@@ -3272,144 +3232,9 @@ ${XMLNS_NAMESPACE}.`);
3272
3232
  part: this.state.documentType === "text" ? -1 : request.part
3273
3233
  }], () => new BrowserRenderError("render-failed", "Office tile rendering failed."));
3274
3234
  } finally {
3235
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3275
3236
  this.flush();
3276
- this.phase = "idle";
3277
- }
3278
- }
3279
- /** Capture one bounded batch with no input interleaving; cached tiles are checked at the same generation. */
3280
- async capture(request) {
3281
- this.requireOpen();
3282
- integer(request.maxPixels);
3283
- if (!request.maxPixels || request.maxPixels > 67108864 || request.tiles.length > 4096) throw new BrowserRenderError("render-failed", "Office capture exceeds its allocation limit.");
3284
- await this.command(".uno:ReportWhenIdle", { idleID: {
3285
- type: "string",
3286
- value: "capture"
3287
- } });
3288
- this.pump();
3289
- const generation = this.state.renderGeneration;
3290
- if (request.generation !== void 0 && request.generation !== generation) throw new BrowserRenderError("snapshot-changed", "The document changed before capture.");
3291
- const original = this.call("dsh_lok_document_get_view", [this.document]);
3292
- if (original < 0) throw new BrowserRenderError("render-failed", "The editor view is unavailable.");
3293
- this.phase = "capture";
3294
- let parts = this.state.parts;
3295
- const tiles = [];
3296
- const regions = [];
3297
- try {
3298
- if (this.renderView < 0) this.renderView = this.call("dsh_lok_document_create_view", [this.document]);
3299
- if (this.renderView < 0 || !this.call("dsh_lok_document_set_view", [this.document, this.renderView])) throw new BrowserRenderError("render-failed", "The capture view is unavailable.");
3300
- const pointer = this.call("malloc", [8]);
3301
- if (!pointer) throw new BrowserRenderError("render-failed", "Office capture geometry allocation failed.");
3302
- try {
3303
- parts = this.state.parts.map((part, index) => {
3304
- this.invoke("size", [
3305
- index,
3306
- pointer,
3307
- pointer + 4
3308
- ]);
3309
- const width = this.module.HEAPU32[pointer / 4] / 15;
3310
- const height = this.module.HEAPU32[pointer / 4 + 1] / 15;
3311
- if (!(width > 0 && height > 0)) throw new BrowserRenderError("invalid-document", "Office returned empty capture dimensions.");
3312
- return {
3313
- ...part,
3314
- width,
3315
- height
3316
- };
3317
- });
3318
- } finally {
3319
- this.call("free", [pointer]);
3320
- }
3321
- if (request.selection !== void 0 && this.state.documentType === "spreadsheet") {
3322
- const selection = request.selection;
3323
- for (let part = 0; part < parts.length; part++) {
3324
- const info = sheetPartInfo(this.text("dsh_lok_document_part_info", [this.document, part]));
3325
- if (selection.sheet !== void 0 ? selection.sheet !== info.name : !info.visible) continue;
3326
- this.invoke("part", [part]);
3327
- this.invoke("viewport", [
3328
- Math.max(1, Math.round(256 * selection.scale)),
3329
- 3840,
3330
- 0,
3331
- 0,
3332
- 1,
3333
- 1
3334
- ]);
3335
- const range = selection.range === void 0 ? dataArea(info) : parseCellRange(selection.range);
3336
- const rectangle = sheetRangeRectangle(JSON.parse(this.text("dsh_lok_document_command_values", [this.document, ".uno:SheetGeometryData"])), range, selection.scale);
3337
- this.text("dsh_lok_document_command_values", [this.document, `.uno:ViewRowColumnHeaders?x=${twips(rectangle.x)}&y=${twips(rectangle.y)}&width=${twips(rectangle.width)}&height=${twips(rectangle.height)}`]);
3338
- regions.push({
3339
- part,
3340
- sheet: info.name,
3341
- range: rangeName(range),
3342
- rectangle
3343
- });
3344
- parts = parts.map((entry, index) => index === part ? {
3345
- ...entry,
3346
- width: Math.max(entry.width, rectangle.x + rectangle.width),
3347
- height: Math.max(entry.height, rectangle.y + rectangle.height)
3348
- } : entry);
3349
- }
3350
- if (regions.length === 0) throw new BrowserRenderError("invalid-document", "No worksheet matches the export selection.");
3351
- } else if (this.state.documentType === "text") regions.push(...this.state.pages.map((rectangle) => ({
3352
- part: 0,
3353
- rectangle
3354
- })));
3355
- else if (this.state.documentType === "presentation") regions.push(...parts.map((part, index) => ({
3356
- part: index,
3357
- rectangle: {
3358
- x: 0,
3359
- y: 0,
3360
- width: part.width,
3361
- height: part.height
3362
- }
3363
- })));
3364
- let pixels = 0;
3365
- for (const entry of request.tiles) {
3366
- const page = {
3367
- ...parts[integer(entry.request.part, parts.length - 1)],
3368
- x: 0,
3369
- y: 0,
3370
- part: this.state.documentType === "text" ? -1 : entry.request.part
3371
- };
3372
- const region = {
3373
- ...entry.request,
3374
- pageIndex: 0
3375
- };
3376
- const size = tileDimensions(region, [page]);
3377
- pixels += size.width * size.height;
3378
- if (pixels > request.maxPixels) throw new BrowserRenderError("render-failed", "Office capture exceeds its pixel budget.");
3379
- if (entry.cached !== void 0) {
3380
- if (request.generation === void 0 || entry.cached.width !== size.width || entry.cached.height !== size.height || entry.cached.rgba.byteLength !== size.width * size.height * 4) throw new BrowserRenderError("render-failed", "Cached Office pixels do not match the capture.");
3381
- tiles.push(entry.cached);
3382
- } else {
3383
- this.invoke("part", [entry.request.part]);
3384
- tiles.push(renderRegion(this.module, this.document, region, [page], () => new BrowserRenderError("render-failed", "Office capture failed.")));
3385
- }
3386
- }
3387
- } finally {
3388
- try {
3389
- if (!this.call("dsh_lok_document_set_view", [this.document, original])) throw new BrowserRenderError("render-failed", "The editor view could not be restored after capture.");
3390
- this.pump();
3391
- } catch (error) {
3392
- this.stop();
3393
- this.failure(error);
3394
- throw error;
3395
- } finally {
3396
- this.phase = "idle";
3397
- }
3398
3237
  }
3399
- await this.command(".uno:ReportWhenIdle", { idleID: {
3400
- type: "string",
3401
- value: "capture-complete"
3402
- } });
3403
- this.pump();
3404
- if (this.state.renderGeneration !== generation) throw new BrowserRenderError("snapshot-changed", "The document changed during capture.");
3405
- return {
3406
- state: {
3407
- ...this.state,
3408
- parts
3409
- },
3410
- tiles,
3411
- regions
3412
- };
3413
3238
  }
3414
3239
  };
3415
3240
  //#endregion
@@ -3421,7 +3246,7 @@ ${XMLNS_NAMESPACE}.`);
3421
3246
  let document = 0;
3422
3247
  let pdf = 0;
3423
3248
  let pages = [];
3424
- let editor;
3249
+ let reader;
3425
3250
  let fatal = false;
3426
3251
  let fontFailure;
3427
3252
  let serial = Promise.resolve();
@@ -3443,7 +3268,7 @@ ${XMLNS_NAMESPACE}.`);
3443
3268
  call("free", [pointer]);
3444
3269
  }
3445
3270
  }
3446
- async function open(options, channel, editing = false) {
3271
+ async function open(options, channel, reading = false) {
3447
3272
  const { assets } = options;
3448
3273
  let metadata;
3449
3274
  try {
@@ -3454,6 +3279,22 @@ ${XMLNS_NAMESPACE}.`);
3454
3279
  } catch (failure) {
3455
3280
  throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3456
3281
  }
3282
+ const initialFont = {
3283
+ family: "sans-serif",
3284
+ style: "",
3285
+ weight: 5,
3286
+ italic: 0,
3287
+ width: 5,
3288
+ pitch: 0,
3289
+ language: "",
3290
+ codePoints: []
3291
+ };
3292
+ let initialFontPending = options.extension !== "pdf";
3293
+ if (initialFontPending) send({
3294
+ type: "font",
3295
+ request: initialFont,
3296
+ known: []
3297
+ });
3457
3298
  const response = await fetch(assets.dataUrl, {
3458
3299
  credentials: "same-origin",
3459
3300
  signal: lifetime.signal
@@ -3465,7 +3306,7 @@ ${XMLNS_NAMESPACE}.`);
3465
3306
  module = await scope.createLibreOfficeModule({
3466
3307
  noInitialRun: true,
3467
3308
  dshOnCallback(type, payload) {
3468
- editor?.callback(type, payload);
3309
+ reader?.callback(type, payload);
3469
3310
  },
3470
3311
  mainScriptUrlOrBlob: assets.loaderUrl,
3471
3312
  locateFile(name) {
@@ -3503,25 +3344,23 @@ ${XMLNS_NAMESPACE}.`);
3503
3344
  FONTCONFIG_FILE: "/dsh/fonts.conf",
3504
3345
  LOK_HOST_ALLOWLIST: "^$"
3505
3346
  });
3506
- resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families, (request) => send({
3507
- type: "font",
3508
- request
3509
- }), () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3347
+ resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families, (request, known) => {
3348
+ if (initialFontPending) initialFontPending = false;
3349
+ else send({
3350
+ type: "font",
3351
+ request,
3352
+ known
3353
+ });
3354
+ }, () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3510
3355
  type: "missing-fonts",
3511
3356
  families
3512
3357
  }));
3513
- const initialFamilies = options.extension === "pdf" ? new Set(options.fontFallbacks.flat()) : /* @__PURE__ */ new Set(["sans-serif"]);
3514
- for (const family of initialFamilies) resolveFonts({
3358
+ if (options.extension === "pdf") for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3359
+ ...initialFont,
3515
3360
  family,
3516
- style: "",
3517
- weight: 5,
3518
- italic: 0,
3519
- width: 5,
3520
- pitch: 0,
3521
- language: "",
3522
- codePoints: [],
3523
- ...options.extension === "pdf" ? { mode: "full" } : {}
3361
+ mode: "full"
3524
3362
  });
3363
+ else resolveFonts(initialFont);
3525
3364
  }],
3526
3365
  onAbort() {
3527
3366
  fatal = true;
@@ -3561,28 +3400,28 @@ ${XMLNS_NAMESPACE}.`);
3561
3400
  ], [
3562
3401
  office,
3563
3402
  `file://${input}`,
3564
- options.readOnly ? "ReadOnly=true,EnableMacrosExecution=false" : "EnableMacrosExecution=false"
3403
+ "ReadOnly=true,EnableMacrosExecution=false"
3565
3404
  ]);
3566
3405
  if (!document || !call("dsh_lok_document_initialize_rendering", [document])) throw error("invalid-document");
3567
3406
  const type = call("dsh_lok_document_type", [document]);
3568
3407
  if (type !== (options.extension === "docx" || options.extension === "doc" ? 0 : options.extension === "xlsx" || options.extension === "xls" ? 1 : 2)) throw new BrowserRenderError("invalid-document", "The document type does not match its extension.");
3569
- if (editing) {
3570
- editor = new EditorEngine(module, document, options.extension, options.maxUncompressedBytes, (event) => send({
3571
- type: "editor-event",
3408
+ if (reading) {
3409
+ reader = new OfficeEngine(module, document, options.extension, (event) => send({
3410
+ type: "office-event",
3572
3411
  event
3573
3412
  }), (failure) => {
3574
3413
  fatal ||= failure instanceof WebAssembly.RuntimeError;
3575
3414
  send({
3576
- type: "editor-event",
3415
+ type: "office-event",
3577
3416
  event: {
3578
3417
  type: "error",
3579
3418
  code: "render-failed",
3580
3419
  message: failure instanceof Error ? failure.message : String(failure)
3581
3420
  }
3582
3421
  });
3583
- }, options.readOnly);
3584
- await editor.start();
3585
- pages = editor.state.parts.map((part, index) => ({
3422
+ });
3423
+ await reader.start();
3424
+ pages = reader.state.parts.map((part, index) => ({
3586
3425
  ...part,
3587
3426
  x: 0,
3588
3427
  y: 0,
@@ -3598,8 +3437,8 @@ ${XMLNS_NAMESPACE}.`);
3598
3437
  return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3599
3438
  }
3600
3439
  function dispose() {
3601
- editor?.stop();
3602
- editor = void 0;
3440
+ reader?.stop();
3441
+ reader = void 0;
3603
3442
  try {
3604
3443
  if (module && !fatal) {
3605
3444
  if (pdf) {
@@ -3631,13 +3470,13 @@ ${XMLNS_NAMESPACE}.`);
3631
3470
  const message = event.data;
3632
3471
  if (message.type === "dispose") {
3633
3472
  lifetime.abort();
3634
- editor?.stop();
3473
+ reader?.stop();
3635
3474
  }
3636
3475
  serial = serial.then(async () => {
3637
3476
  try {
3638
3477
  switch (message.type) {
3639
3478
  case "open":
3640
- await open(message.options, message.channel, message.editing);
3479
+ await open(message.options, message.channel, message.office);
3641
3480
  send({
3642
3481
  type: "opened",
3643
3482
  id: message.id,
@@ -3645,7 +3484,7 @@ ${XMLNS_NAMESPACE}.`);
3645
3484
  width,
3646
3485
  height
3647
3486
  })),
3648
- ...editor ? { editor: editor.state } : {}
3487
+ ...reader ? { office: reader.state } : {}
3649
3488
  });
3650
3489
  break;
3651
3490
  case "tile": {
@@ -3657,9 +3496,9 @@ ${XMLNS_NAMESPACE}.`);
3657
3496
  }, [tile.rgba.buffer]);
3658
3497
  break;
3659
3498
  }
3660
- case "editor-tile": {
3661
- if (!editor) throw new BrowserRenderError("disposed", "Office editor is closed.");
3662
- const tile = editor.render(message.request);
3499
+ case "office-tile": {
3500
+ if (!reader) throw new BrowserRenderError("disposed", "Office reader is closed.");
3501
+ const tile = reader.render(message.request);
3663
3502
  send({
3664
3503
  type: "tile",
3665
3504
  id: message.id,
@@ -3667,24 +3506,14 @@ ${XMLNS_NAMESPACE}.`);
3667
3506
  }, [tile.rgba.buffer]);
3668
3507
  break;
3669
3508
  }
3670
- case "edit": {
3671
- if (!editor) throw new BrowserRenderError("disposed", "Office editor is closed.");
3672
- const result = await editor.operation(message.operation);
3509
+ case "office-operation": {
3510
+ if (!reader) throw new BrowserRenderError("disposed", "Office reader is closed.");
3511
+ const result = await reader.operation(message.operation);
3673
3512
  send({
3674
- type: "edited",
3513
+ type: "office-result",
3675
3514
  id: message.id,
3676
3515
  ...result
3677
- }, result.snapshot ? [result.snapshot.data.buffer] : []);
3678
- break;
3679
- }
3680
- case "capture": {
3681
- if (!editor) throw new BrowserRenderError("disposed", "Office editor is closed.");
3682
- const capture = await editor.capture(message.request);
3683
- send({
3684
- type: "captured",
3685
- id: message.id,
3686
- capture
3687
- }, capture.tiles.map((tile) => tile.rgba.buffer));
3516
+ });
3688
3517
  break;
3689
3518
  }
3690
3519
  case "dispose":
@@ -3694,6 +3523,8 @@ ${XMLNS_NAMESPACE}.`);
3694
3523
  id: message.id
3695
3524
  });
3696
3525
  scope.close();
3526
+ break;
3527
+ default: throw new BrowserRenderError("render-failed", "Unsupported Office Worker request.");
3697
3528
  }
3698
3529
  } catch (failure) {
3699
3530
  fatal ||= failure instanceof WebAssembly.RuntimeError;