Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

presentation.worker.ts

428 lines14.3 KB

1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import {
3 initWasm,
4 needsElementDecode,
5 openPresentation,
6 paintSlide,
7 presentationImageBlob,
8 type PresentationHandle,
9 type SlideDisplayList,
10 type SlidePrimitive,
11} from "@betteroffice/pptx";
12import { slideFonts } from "./slide-fonts";
13import {
14 maxImageSide,
15 type SlideMethods,
16 type SlidePainted,
17 type SlideSummary,
18 type VectorBitmap,
19 type VectorRequest,
20} from "./slide-protocol";
21import { deckText } from "./slide-text";
22import { officeImageBitmap } from "./image-bitmap";
23import { serveWorker, Transfer } from "./worker-rpc";
24​
25// One worker holds one open PowerPoint deck: its engine, fonts, laid-out slides, decoded pictures and painting. The
26// window terminates the worker when the deck closes, which is the only way the engine's memory is given back.
27​
28/** English Metric Units per CSS pixel. */
29const emuPerPixel = 9525;
30​
31/** The most device pixels one slide's bitmap holds, about a 4K screen: a zoomed slide stays sharp up to it. */
32const maxBitmapPixels = 3840 * 2160;
33​
34/** The longest side a canvas takes in every browser. */
35const maxBitmapSide = 16384;
36​
37/**
38 * Shadow pixels a slide may blur, per pixel of its bitmap: sixteen slide-sized shadows before they are dropped. Past
39 * it a slide gives up its shadows within about half a second, rather than painting for many seconds.
40 */
41const shadowPixelsPerPixel = 16;
42​
43/**
44 * How many bytes of decoded pictures stay for repaints; the least recently drawn go first past it. A deck of camera
45 * photos holds about 17 MB per picture, even scaled down to `maxImageSide`.
46 */
47const pictureBudget = 128 * 1024 * 1024;
48​
49type Size = { readonly width: number; readonly height: number };
50​
51/**
52 * A picture as the painter draws it: a bitmap, an SVG that the window rasterizes (a worker has no SVG decoder) with
53 * the bitmap it last returned, or nothing when the browser cannot decode it.
54 */
55type Picture =
56 | { readonly kind: "bitmap"; readonly bitmap: ImageBitmap; readonly size: Size }
57 | {
58 readonly kind: "vector";
59 readonly blob: Blob;
60 bitmap: ImageBitmap | undefined;
61 failed: boolean;
62 }
63 | { readonly kind: "missing" };
64​
65type Deck = ReturnType<typeof createDeck>;
66​
67/** The deck this worker opened, once it has. */
68type WorkerState = { deck: Deck | undefined };
69​
70const state: WorkerState = { deck: undefined };
71​
72serveWorker<SlideMethods>({
73 open: async (input) => {
74 if (state.deck) throw new Error("The worker already holds a deck");
75​
76 await initWasm();
77​
78 const bytes = new Uint8Array(input.bytes);
79 const handle = openPresentation(bytes);
80 const snapshot = handle.snapshot();
81 const text = deckText(bytes, snapshot);
82 const fonts = slideFonts(handle, workerFonts());
83​
84 await fonts.load(text);
85​
86 state.deck = createDeck(handle, fonts.layout);
87​
88 const size = {
89 width: snapshot.widthEmu / emuPerPixel,
90 height: snapshot.heightEmu / emuPerPixel,
91 };
92​
93 return snapshot.slides.map((slide, index): SlideSummary => ({
94 ...size,
95 hidden: text.hidden[index] ?? false,
96 notes: slide.notes?.trim() || undefined,
97 }));
98 },
99 paint: async (input, signal) => {
100 const deck = required();
101 const painted = await deck.paint(input.index, input.density, signal).finally(deck.trim);
102​
103 return painted.kind === "painted" ? new Transfer(painted, [painted.bitmap]) : painted;
104 },
105 vectors: (input) => required().vectors(input),
106});
107​
108function required() {
109 if (!state.deck) throw new Error("The worker holds no deck");
110​
111 return state.deck;
113​
114/** The worker's own font set, which its canvases draw text with. */
115function workerFonts() {
116 if (!("fonts" in self)) throw new Error("This browser has no fonts in workers");
117​
118 // SAFETY: a worker's global scope is a FontFaceSource, whose `fonts` is a FontFaceSet (CSS Font Loading, exposed to
119 // workers). The window's types declare it on documents only, and workers expose no FontFaceSet to check against.
120 return self.fonts as FontFaceSet;
122​
123function createDeck(
124 handle: PresentationHandle,
125 layout: (index: number) => Promise<SlideDisplayList>,
126) {
127 // A frame depends on the slide alone, so a new scale or pixel ratio paints the frame laid out before.
128 const frames = new Map<number, Promise<SlideDisplayList | undefined>>();
129 const pictures = new Map<string, Promise<Picture>>();
130 // The decoded bitmaps, least recently drawn first, which `trim` keeps within `pictureBudget`.
131 const drawn = new Map<string, ImageBitmap>();
132 const surface = new OffscreenCanvas(1, 1);
133​
134 const frame = (index: number) => {
135 const cached = frames.get(index);
136​
137 if (cached) return cached;
138​
139 const laid = layout(index).catch(() => undefined);
140​
141 frames.set(index, laid);
142​
143 return laid;
144 };
145​
146 const decode = async (asset: string): Promise<Picture> => {
147 const blob = presentationImageBlob(handle.mediaBytes(asset));
148​
149 // SVG decodes through an image element, which a worker lacks.
150 if (needsElementDecode(blob)) return { kind: "vector", blob, bitmap: undefined, failed: false };
151​
152 const source = await officeImageBitmap(blob).catch(() => undefined);
153​
154 if (!source) return { kind: "missing" };
155 const size = { width: source.width, height: source.height };
156 return { kind: "bitmap", bitmap: await bounded(source), size };
157 };
158​
159 const picture = (asset: string) => {
160 const cached = pictures.get(asset);
161​
162 if (cached) return cached;
163​
164 const decoded = decode(asset).catch((): Picture => ({ kind: "missing" }));
165​
166 pictures.set(asset, decoded);
167​
168 return decoded;
169 };
170​
171 const tileScale = async (primitive: SlidePrimitive): Promise<SlidePrimitive> => {
172 if (primitive.kind === "table" || primitive.kind === "chart") {
173 const primitives: SlidePrimitive[] = [];
174 for (const child of primitive.primitives) primitives.push(await tileScale(child));
175 return { ...primitive, primitives };
176 }
177 if (primitive.kind !== "image" || !primitive.tile || !primitive.assetId) return primitive;
178 const found = await picture(primitive.assetId);
179 if (found.kind !== "bitmap") return primitive;
180 return {
181 ...primitive,
182 tile: {
183 ...primitive.tile,
184 scaleX: primitive.tile.scaleX * (found.size.width / found.bitmap.width),
185 scaleY: primitive.tile.scaleY * (found.size.height / found.bitmap.height),
186 },
187 };
188 };
189​
190 return {
191 paint: async (index: number, density: number, signal: AbortSignal): Promise<SlidePainted> => {
192 const laid = await frame(index);
193​
194 if (!laid) return { kind: "failed" };
195​
196 if (signal.aborted) return { kind: "cancelled" };
197​
198 const scale = Math.min(
199 density,
200 Math.sqrt(maxBitmapPixels / (laid.width * laid.height)),
201 maxBitmapSide / Math.max(laid.width, laid.height),
202 );
203​
204 // One canvas paints every slide: a paint that was withdrawn leaves its pixels for the next to clear, rather than a
205 // slide-sized canvas each until the worker collects garbage. A reset context starts as a new canvas's does.
206 const canvas = surface;
207 const width = Math.max(1, Math.round(laid.width * scale));
208 const height = Math.max(1, Math.round(laid.height * scale));
209​
210 if (canvas.width !== width) canvas.width = width;
211​
212 if (canvas.height !== height) canvas.height = height;
213​
214 const context = canvas.getContext("2d");
215​
216 if (!context) return { kind: "failed" };
217​
218 context.reset();
219​
220 const needs = vectorSizes(laid.primitives, scale);
221 const wanted = new Map<string, VectorRequest>();
222​
223 const resolveImage = async (asset: string) => {
224 // A paint that was withdrawn finishes without pictures, and its reply is dropped.
225 if (signal.aborted) return null;
226​
227 const found = await picture(asset);
228​
229 if (found.kind === "bitmap") {
230 drawn.delete(asset);
231 drawn.set(asset, found.bitmap);
232​
233 return found.bitmap;
234 }
235​
236 if (found.kind === "missing" || found.failed) return null;
237​
238 const need = needs.get(asset);
239​
240 if (!covers(found.bitmap, need)) wanted.set(asset, { asset, blob: found.blob, size: need });
241​
242 if (found.bitmap) {
243 drawn.delete(asset);
244 drawn.set(asset, found.bitmap);
245 }
246​
247 return found.bitmap ?? null;
248 };
249​
250 const options = {
251 resolveImage,
252 maxShadowPixels: canvas.width * canvas.height * shadowPixelsPerPixel,
253 };
254​
255 const attempt = (list: SlideDisplayList) =>
256 // SAFETY: the painter draws through the members a worker's 2D context shares with the window's, and makes its
257 // scratch canvases with OffscreenCanvas wherever it exists, as it does in a worker. Only the window's context
258 // type is declared, and it has two focus and attribute members the worker's lacks, hence the double cast.
259 paintSlide(context as unknown as CanvasRenderingContext2D, list, scale, 1, options).then(
260 () => true,
261 () => false,
262 );
263​
264 const primitives: SlidePrimitive[] = [];
265 for (const primitive of laid.primitives) primitives.push(await tileScale(primitive));
266 const scaled = { ...laid, primitives };
267 const shadowed = await attempt(scaled);
268​
269 // Past its shadow budget a slide throws, and paints again without shadows rather than not at all. It first lets
270 // through a cancellation that arrived meanwhile, such as a scroll that moved the slide away.
271 if (!shadowed) await new Promise((resolve) => setTimeout(resolve));
272​
273 if (signal.aborted) return { kind: "cancelled" };
274​
275 const done = shadowed || (await attempt(withoutShadows(scaled)));
276​
277 if (!done) return { kind: "failed" };
278​
279 if (signal.aborted) return { kind: "cancelled" };
280​
281 return {
282 kind: "painted",
283 bitmap: canvas.transferToImageBitmap(),
284 vectors: [...wanted.values()],
285 };
286 },
287​
288 /** Closes the least recently drawn pictures past the budget; they decode again when drawn. Call it between paints. */
289 trim: () => {
290 [...drawn].reduce(
291 (total, [asset, bitmap]) => {
292 if (total <= pictureBudget) return total;
293​
294 const freed = pixelBytes(bitmap);
295​
296 bitmap.close();
297 drawn.delete(asset);
298 pictures.delete(asset);
299​
300 return total - freed;
301 },
302 [...drawn.values()].reduce((total, bitmap) => total + pixelBytes(bitmap), 0),
303 );
304 },
305​
306 /**
307 * Keeps the window's rasterized SVG pictures in place of coarser ones. A finer one that a paint at a larger scale
308 * returned stays, and so does any one when the window could not rasterize the picture again.
309 */
310 vectors: (bitmaps: readonly VectorBitmap[]) =>
311 Promise.all(
312 bitmaps.map(async (entry) => {
313 const found = await picture(entry.asset);
314​
315 if (found.kind !== "vector") return entry.bitmap?.close();
316​
317 if (found.bitmap && (!entry.bitmap || covers(found.bitmap, entry.bitmap)))
318 return entry.bitmap?.close();
319​
320 found.bitmap?.close();
321 drawn.delete(entry.asset);
322 found.bitmap = entry.bitmap;
323 found.failed = !entry.bitmap;
324 if (entry.bitmap) drawn.set(entry.asset, entry.bitmap);
325 }),
326 ).then(() => undefined),
327 };
329​
330/**
331 * The bitmap size each SVG picture on a slide needs at `scale`: its drawn size in device pixels, before cropping and
332 * up to `maxImageSide`. A tiled picture repeats at its own size, so it needs exactly that (undefined).
333 */
334function vectorSizes(primitives: readonly SlidePrimitive[], scale: number) {
335 const sizes = new Map<string, Size | undefined>();
336​
337 const visit = (primitive: SlidePrimitive): void => {
338 if (primitive.kind === "table" || primitive.kind === "chart")
339 return primitive.primitives.forEach(visit);
340​
341 if (primitive.kind !== "image" || !primitive.assetId) return;
342​
343 const asset = primitive.assetId;
344 const previous = sizes.get(asset);
345​
346 if (primitive.tile || (sizes.has(asset) && !previous)) return void sizes.set(asset, undefined);
347​
348 const visibleX = 1 - fraction(primitive.crop?.left) - fraction(primitive.crop?.right);
349 const visibleY = 1 - fraction(primitive.crop?.top) - fraction(primitive.crop?.bottom);
350​
351 if (visibleX <= 0 || visibleY <= 0) return;
352​
353 const width = Math.max(previous?.width ?? 0, (primitive.w * scale) / visibleX);
354 const height = Math.max(previous?.height ?? 0, (primitive.h * scale) / visibleY);
355 const shrink = Math.min(1, maxImageSide / Math.max(width, height));
356​
357 sizes.set(asset, {
358 width: Math.max(1, Math.ceil(width * shrink)),
359 height: Math.max(1, Math.ceil(height * shrink)),
360 });
361 };
362​
363 primitives.forEach(visit);
364​
365 return sizes;
367​
368function pixelBytes(bitmap: ImageBitmap) {
369 return bitmap.width * bitmap.height * 4;
371​
372/** Whether a rasterized SVG picture is as fine as `need`; undefined needs the picture's own size, rasterized once. */
373function covers(bitmap: ImageBitmap | undefined, need: Size | undefined) {
374 if (!bitmap) return false;
375​
376 if (!need) return true;
377​
378 return bitmap.width >= need.width && bitmap.height >= need.height;
380​
381/** A crop fraction as the painter reads it. */
382function fraction(value: number | undefined) {
383 return value === undefined || !Number.isFinite(value) ? 0 : Math.min(Math.max(value, 0), 1);
385​
386function withoutShadows(frame: SlideDisplayList): SlideDisplayList {
387 const strip = (primitive: SlidePrimitive): SlidePrimitive => {
388 if (primitive.kind === "shape" || primitive.kind === "image") {
389 const { shadow: _shadow, ...rest } = primitive;
390 return rest;
391 }
392​
393 if (primitive.kind === "textBox") {
394 const { textShadow: _shadow, ...rest } = primitive;
395 return rest;
396 }
397​
398 if (primitive.kind === "table" || primitive.kind === "chart")
399 return { ...primitive, primitives: primitive.primitives.map(strip) };
400​
401 return primitive;
402 };
403​
404 return { ...frame, primitives: frame.primitives.map(strip) };
406​
407/**
408 * The picture scaled down to `maxImageSide` when it is larger. Decks of camera photos would otherwise hold about 100 MB
409 * per decoded picture for as long as the deck is open.
410 */
411async function bounded(source: ImageBitmap) {
412 const shrink = maxImageSide / Math.max(source.width, source.height);
413​
414 if (shrink >= 1) return source;
415​
416 return createImageBitmap(source, {
417 resizeWidth: Math.max(1, Math.round(source.width * shrink)),
418 resizeHeight: Math.max(1, Math.round(source.height * shrink)),
419 resizeQuality: "high",
420 }).then(
421 (resized) => {
422 source.close();
423​
424 return resized;
425 },
426 () => source,
427 );