Open History to see the last commit
1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import * as Schema from "effect/Schema";
3import {
4 buildResidentRegionLayoutRequest,
5 getLayoutKernelInputs,
6 workerLayoutComputation,
7} from "@betteroffice/docx/editor";
8import { createRustMeasureSource } from "@betteroffice/docx/layout";
9import {
10 applyFrameDelta,
11 decodeFrameDelta,
12 encodeDisplayListFrameExtras,
13 GlyphCache,
14 rasterizeDisplayPageToBackBuffer,
15 type DisplayPage,
16 type RetainedFrame,
17} from "@betteroffice/docx/layout/render";
18import {
19 createYrsPositionProjection,
20 createYrsSession,
21 type YrsPositionProjection,
22} from "@betteroffice/docx/yrs";
23import { wordFonts } from "./fonts";
24import { createBitmapImageResolver } from "./word-images";
25import { layerFont, type WordMethods, type WordPageSize, type WordSpan } from "./word-protocol";
26import { pageText, positionTarget, type TextMeasure } from "./word-text";
27import { serveWorker, Transfer } from "./worker-rpc";
28
29// One worker holds one open Word document: its engine session, fonts, layout, built pages and painting. The window
30// terminates the worker when the document closes, which is the only way the engine's memory is given back.
31
32const FontRequirements = Schema.fromJsonString(
33 Schema.Array(
34 Schema.Struct({
35 key: Schema.String,
36 family: Schema.String,
37 bold: Schema.Boolean,
38 italic: Schema.Boolean,
39 scripts: Schema.optional(
40 Schema.Array(Schema.Literals(["cjk-sc", "cjk-tc", "cjk-jp", "cjk-kr", "arabic", "hebrew"])),
41 ),
42 }),
43 ),
44);
45
46const decodeFontRequirements = Schema.decodeUnknownSync(FontRequirements);
47
48/** A prefix layout's reply marks itself provisional when the document goes on past it. */
49const decodeLayoutReply = Schema.decodeUnknownSync(
50 Schema.fromJsonString(Schema.Struct({ provisional: Schema.optional(Schema.Boolean) })),
51);
52
53/** Pages laid out and built before the first paint; later pages are built as they near the viewport. */
54const firstPages = 3;
55
56/** How long one layout step may hold back a paint that waits behind it, in milliseconds. */
57const stepBudget = 24;
58
59/**
60 * How many pages either side of the page painted last stay built. A built page holds about 5 MB in the engine and
61 * builds again in about 100 ms. This keeps every page near the viewport, which paints a viewport ahead in both
62 * directions, and lets a reader scroll back a few screens without waiting, while a long read holds at most 21 pages.
63 */
64const keptAround = 10;
65
66type Opened = Awaited<ReturnType<typeof open>>;
67
68/** A value built on first use. */
69type Lazy<T> = { value: T | undefined };
70
71/** The document this worker opened, once it has. */
72const opened: Lazy<Opened> = { value: undefined };
73
74serveWorker<WordMethods>({
75 open: async (input) => {
76 if (opened.value) throw new Error("The worker already holds a document");
77
78 const loaded = await open(new Uint8Array(input.bytes));
79
80 opened.value = loaded;
81
82 return { pages: loaded.pages().map(pageSize), loading: loaded.loading() };
83 },
84 layout: () => required().step(),
85 paint: async (input, signal) => {
86 const bitmap = await required().paint(input.index, input.scale, input.ratio, signal);
87
88 return bitmap ? new Transfer(bitmap, [bitmap]) : undefined;
89 },
90 build: (input) => {
91 required().built(input.index);
92
93 return undefined;
94 },
95 text: (input) => required().text(input.index),
96 bookmark: (input) => required().target(input.name),
97});
98
99function required() {
100 if (!opened.value) throw new Error("The worker holds no document");
101
102 return opened.value;
103}
104
105/** Opens the document and lays out its first pages; the rest lay out a `step` at a time. */
106async function open(bytes: Uint8Array) {
107 const session = await createYrsSession();
108 const document = session.openDocx(bytes, true, { mediaTokens: true }).document;
109 const settings = document.package.settings;
110
111 const measure = createRustMeasureSource({
112 engine: {
113 registerFont: (font) => session.registerFont(font),
114 registerSubstituteFont: (id, family) => session.registerSubstituteFont(id, family),
115 clearFonts: () => session.clearFonts(),
116 },
117 bundled: wordFonts(),
118 });
119
120 measure.setCompat(settings?.compatibilityFlags);
121
122 const request = buildResidentRegionLayoutRequest(document, 0, {
123 themeColors: Object.fromEntries(
124 Object.entries(document.package.theme?.colorScheme ?? {}).filter(
125 (entry): entry is [string, string] => entry[1] !== undefined,
126 ),
127 ),
128 defaultTabStopTwips: settings?.defaultTabStop ?? null,
129 numericIds: {},
130 mediaTokens: true,
131 });
132
133 const requirements = decodeFontRequirements(
134 session.layoutFontRequirementsJson(JSON.stringify(request)),
135 ).map(({ scripts, ...requirement }) => ({
136 ...requirement,
137 ...(scripts ? { scripts: [...scripts] } : {}),
138 }));
139
140 await measure.prepareFontRequirements(requirements);
141
142 const measurement = measure.measurementConfigForRequirements(requirements);
143
144 if (!measurement) throw new Error("The document's fonts could not be prepared");
145
146 const input = JSON.stringify({ ...request, measurement });
147
148 // Word shows resolved comments without the active highlight.
149 const resolvedCommentIds = (document.package.document.comments ?? [])
150 .filter(
151 (comment) =>
152 (comment.done || comment.status === "resolved") && comment.parentId === undefined,
153 )
154 .map((comment) => comment.id);
155
156 // The session keeps the layout it last ran and builds display frames from it: only the display extras go in, and a
157 // binary frame comes back with the window's pages built and every other page a placeholder carrying its geometry.
158 const display = (previous: RetainedFrame | null, reply: string) => {
159 const layout = workerLayoutComputation(reply).layout;
160
161 session.setDisplayWindow(0, firstPages);
162
163 const extras = encodeDisplayListFrameExtras({
164 measured: [],
165 options: {},
166 layout,
167 fontChains: measurement.fontChains,
168 ...(getLayoutKernelInputs(layout)?.headersFooters
169 ? { headersFooters: getLayoutKernelInputs(layout)!.headersFooters! }
170 : {}),
171 resolvedCommentIds,
172 });
173
174 return applyFrameDelta(
175 previous,
176 decodeFrameDelta(session.buildDisplayListFrame(extras, previous?.frameEpoch ?? 0)),
177 );
178 };
179
180 // Only as much of the body as fills the first pages; a long document goes on past it.
181 const prefix = session.layoutDocumentWithRegionsPrefixRetainedJson(input, firstPages);
182 const retained = { frame: display(null, prefix) };
183
184 if (retained.frame.displayList.pages.length === 0)
185 throw new Error("The document produced no pages");
186
187 // The region layout that finishes the document: begun on the first step, `cost` the running average milliseconds a
188 // body block takes.
189 const layout = { loading: decodeLayoutReply(prefix).provisional ?? false, begun: false, cost: 3 };
190
191 // Builds a page's content when it is needed and not built, the first time or again after `release`.
192 const built = (index: number) => {
193 const page = retained.frame.displayList.pages[index];
194
195 if (!page?.unbuilt) return page;
196
197 retained.frame = applyFrameDelta(
198 retained.frame,
199 decodeFrameDelta(session.buildDisplayPagesFrame([index], retained.frame.frameEpoch)),
200 );
201
202 return retained.frame.displayList.pages[index];
203 };
204
205 // Gives back the built pages far from the page about to paint, so a long read keeps only the pages around the
206 // viewport. A released page keeps its geometry and document positions, which bookmarks search, and builds again
207 // when it is needed.
208 const release = (painted: number) => {
209 // The engine releases pages of the whole document's layout only, and few pages show before it.
210 if (layout.loading) return;
211
212 const far = retained.frame.displayList.pages.flatMap((page, index) =>
213 !page.unbuilt && Math.abs(painted - index) > keptAround ? [index] : [],
214 );
215
216 if (far.length === 0) return;
217
218 const frame = session.releaseDisplayPagesFrame(far, retained.frame.frameEpoch);
219
220 // A superseded release changes nothing; the next one tries again.
221 if (frame) retained.frame = applyFrameDelta(retained.frame, decodeFrameDelta(frame));
222 };
223
224 // The whole document's layout replaces the prefix's frame.
225 const complete = (reply: string) => {
226 const before = retained.frame.displayList.pages;
227
228 retained.frame = display(retained.frame, reply);
229 layout.loading = false;
230
231 const pages = retained.frame.displayList.pages;
232
233 return {
234 done: true as const,
235 pages: pages.map(pageSize),
236 kept: pages.map((page, index) => {
237 const was = before[index];
238
239 return was === page || (!!was?.unbuilt && !!page.unbuilt);
240 }),
241 };
242 };
243
244 const glyphCache = new GlyphCache({
245 provider: (font, glyph) => session.outlineGlyphJson(font, glyph),
246 });
247 const images = createBitmapImageResolver((token) => session.mediaSource(token));
248 const surface = new OffscreenCanvas(1, 1);
249 const textMeasure = layerMeasure();
250 const texts = new WeakMap<DisplayPage, readonly WordSpan[]>();
251 // Built on the first followed bookmark: most documents are read without one.
252 const projection: Lazy<YrsPositionProjection | null> = { value: undefined };
253
254 return {
255 pages: () => retained.frame.displayList.pages,
256 loading: () => layout.loading,
257 built,
258 /**
259 * Lays out about `stepBudget` milliseconds more of the body. Blocks vary widely, and sizing a step by the last one
260 * alone overshoots after a run of cheap blocks.
261 */
262 step: () => {
263 if (!layout.loading) {
264 const pages = retained.frame.displayList.pages;
265
266 return { done: true as const, pages: pages.map(pageSize), kept: pages.map(() => true) };
267 }
268
269 if (!layout.begun) {
270 layout.begun = true;
271
272 const begun = session.beginRegionLayout(input);
273
274 return begun.layoutJson === undefined
275 ? { done: false as const }
276 : complete(begun.layoutJson);
277 }
278
279 const blocks = Math.min(8192, Math.max(1, Math.round(stepBudget / layout.cost)));
280 const started = performance.now();
281 const progress = session.resumeRegionLayout(blocks);
282
283 layout.cost = layout.cost * 0.7 + ((performance.now() - started) / blocks) * 0.3;
284
285 return progress.layoutJson === undefined
286 ? { done: false as const }
287 : complete(progress.layoutJson);
288 },
289 paint: async (index: number, scale: number, ratio: number, signal: AbortSignal) => {
290 // A page that scrolled away before its paint began, or while it rasterized, needs no bitmap.
291 if (signal.aborted) return undefined;
292
293 // Released first, so the page builds in the memory they free.
294 release(index);
295
296 const page = built(index);
297
298 if (!page) return undefined;
299
300 // The window drew image elements, which shrink smoothly at the default quality; a bitmap needs medium quality to
301 // look the same. Sizing the surface first keeps the setting: the painter resizes it, which resets the context,
302 // only when its size differs.
303 const context = surface.getContext("2d");
304 const width = Math.ceil(page.width * ratio * scale);
305 const height = Math.ceil(page.height * ratio * scale);
306
307 if (surface.width !== width) surface.width = width;
308
309 if (surface.height !== height) surface.height = height;
310
311 if (context) context.imageSmoothingQuality = "medium";
312
313 await rasterizeDisplayPageToBackBuffer(
314 surface,
315 page,
316 { glyphCache, resolveImage: images.resolve },
317 ratio,
318 scale,
319 );
320 images.trim();
321
322 if (signal.aborted) return undefined;
323
324 return surface.transferToImageBitmap();
325 },
326 text: (index: number) => {
327 const page = built(index);
328
329 if (!page || !textMeasure) return [];
330
331 const cached = texts.get(page);
332
333 if (cached) return cached;
334
335 const spans = pageText(page, textMeasure);
336
337 texts.set(page, spans);
338
339 return spans;
340 },
341 target: (name: string) => {
342 projection.value ??= createYrsPositionProjection(session, "body");
343
344 const position = projection.value?.bookmarkPosition(name) ?? undefined;
345
346 if (position !== undefined)
347 return positionTarget(retained.frame.displayList.pages, position, built);
348
349 // Word's reserved bookmark for the start of the document.
350 return name === "_top" ? { index: 0, y: 0 } : undefined;
351 },
352 };
353}
354
355function pageSize(page: DisplayPage): WordPageSize {
356 return { width: page.width, height: page.height, background: page.background };
357}
358
359/** Measures the text layer's font with a detached canvas; undefined where the worker offers no 2D context. */
360function layerMeasure(): TextMeasure | undefined {
361 const context = new OffscreenCanvas(1, 1).getContext("2d");
362
363 if (!context) return undefined;
364
365 // Measured large and scaled down, so rounding stays well below a pixel at any zoom.
366 const size = 100;
367
368 context.font = `${size}px ${layerFont}`;
369
370 const metrics = context.measureText("Hg");
371
372 return {
373 width: (text) => context.measureText(text).width / size,
374 ascent: metrics.fontBoundingBoxAscent / size,
375 descent: metrics.fontBoundingBoxDescent / size,
376 };
377}