@deepseek-ai/libreoffice-kit 0.0.2-rc6 → 0.0.2-rc9
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.
- package/README.md +2 -2
- package/README.zh.md +1 -1
- package/assets/font-subset.json +2 -2
- package/lib/browser/assets.json +2 -2
- package/lib/browser/index.js +333 -162
- package/lib/browser/types/connection.d.ts +28 -6
- package/lib/browser/types/font-channel.d.ts +16 -1
- package/lib/browser/types/index.d.ts +3 -2
- package/lib/browser/types/office-engine.d.ts +10 -2
- package/lib/browser/types/office-types.d.ts +60 -1
- package/lib/browser/types/office.d.ts +18 -3
- package/lib/browser/types/preparation.d.ts +13 -0
- package/lib/browser/types/protocol.d.ts +33 -10
- package/lib/browser/types/types.d.ts +31 -8
- package/lib/browser/worker.js +360 -106
- package/lib/browser-assets.js +1 -1
- package/lib/cli.js +2 -2
- package/lib/font-source.js +19 -1
- package/lib/font-worker.js +126 -29
- package/lib/index.js +2 -2
- package/lib/types/engine.d.ts +1 -1
- package/lib/types/font-source-types.d.ts +11 -0
- package/lib/types/font-subsets.d.ts +5 -1
- package/lib/types/fonts.d.ts +1 -0
- package/lib/types/office-fonts.d.ts +6 -0
- package/lib/worker.js +6 -5
- package/package.json +2 -2
- package/sources/browser/packages/browser/package.json +1 -1
- package/sources/browser/packages/browser/src/connection.ts +105 -34
- package/sources/browser/packages/browser/src/font-channel.ts +69 -9
- package/sources/browser/packages/browser/src/index.ts +3 -2
- package/sources/browser/packages/browser/src/office-engine.ts +80 -6
- package/sources/browser/packages/browser/src/office-types.ts +52 -1
- package/sources/browser/packages/browser/src/office.ts +118 -52
- package/sources/browser/packages/browser/src/preparation.ts +41 -0
- package/sources/browser/packages/browser/src/protocol.ts +19 -5
- package/sources/browser/packages/browser/src/types.ts +26 -2
- package/sources/browser/packages/browser/src/worker.ts +138 -53
- package/sources/browser/scripts/build-browser.mjs +6 -2
- package/sources/font-subset/scripts/verify-artifacts.mjs +1 -1
|
@@ -1,28 +1,43 @@
|
|
|
1
|
-
/** Browser
|
|
1
|
+
/** Browser Worker ownership, document lifetime, cancellation and asynchronous Host font delivery. */
|
|
2
2
|
import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
|
|
3
|
-
import type {
|
|
3
|
+
import type { OwnerRequest, WorkerDocumentOptions, WorkerMessage, WorkerOptions } from './protocol.ts'
|
|
4
4
|
import { fontFrames, fontViews } from './font-channel.ts'
|
|
5
5
|
import { BrowserRenderError } from './types.ts'
|
|
6
|
-
import
|
|
7
|
-
import type {
|
|
6
|
+
import { preparedBrowserModule } from './preparation.ts'
|
|
7
|
+
import type { BrowserDocumentOptions, BrowserRuntimeOptions } from './types.ts'
|
|
8
|
+
import type { OfficeDocumentEvent } from './office-types.ts'
|
|
8
9
|
|
|
9
10
|
interface Pending {
|
|
10
11
|
resolve(message: WorkerMessage): void
|
|
11
12
|
reject(error: unknown): void
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
/** One engine Worker that owns a LibreOffice instance and opens one document at a time. */
|
|
16
|
+
export interface BrowserWorker {
|
|
17
|
+
/** Load a document, replacing any document this Worker still holds. */
|
|
18
|
+
openDocument(options: WorkerDocumentOptions & Pick<BrowserDocumentOptions, 'resolveFonts' | 'onMissingFonts'>,
|
|
19
|
+
signal?: AbortSignal): Promise<Extract<WorkerMessage, { type: 'opened' }>>
|
|
20
|
+
/** Release the open document; the engine and its pthreads stay initialized. */
|
|
21
|
+
closeDocument(): Promise<void>
|
|
22
|
+
/** Send one typed request owned by the open document. */
|
|
23
|
+
request(message: OwnerRequest, operation?: AbortSignal, transfer?: Transferable[]): Promise<WorkerMessage>
|
|
24
|
+
/** Close the document and terminate the Worker. */
|
|
25
|
+
dispose(): Promise<void>
|
|
26
|
+
}
|
|
27
|
+
|
|
14
28
|
/**
|
|
15
|
-
*
|
|
16
|
-
* @param options -
|
|
17
|
-
* @param signal -
|
|
18
|
-
* @
|
|
29
|
+
* Start one LibreOffice Worker without loading a document.
|
|
30
|
+
* @param options - Engine resources, limits and asynchronous Host font provider.
|
|
31
|
+
* @param signal - Engine lifetime; abort closes its Worker and all pending work.
|
|
32
|
+
* @param onEvent - Reading notifications, including fatal Worker failures.
|
|
33
|
+
* @returns Document loading, Worker requests and joined disposal.
|
|
19
34
|
*/
|
|
20
|
-
export async function
|
|
21
|
-
|
|
35
|
+
export async function openBrowserWorker(options: BrowserRuntimeOptions, signal?: AbortSignal,
|
|
36
|
+
onEvent?: (event: OfficeDocumentEvent) => void): Promise<BrowserWorker> {
|
|
22
37
|
signal?.throwIfAborted()
|
|
23
38
|
if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer === 'undefined' || typeof Worker === 'undefined') throw new BrowserRenderError('unavailable', 'LibreOffice requires an isolated secure browser context with Worker and SharedArrayBuffer support.')
|
|
24
39
|
if (![options.timeoutMs, options.maxLoadedFontBytes, options.maxArchiveEntries, options.maxUncompressedBytes].every(value => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 0x7fffffff) throw new TypeError('Document limits must be positive integers and timeoutMs must fit a browser timer.')
|
|
25
|
-
if (
|
|
40
|
+
if (options.preparedEngine !== undefined) preparedBrowserModule(options.preparedEngine, options.assets)
|
|
26
41
|
const worker = new Worker(options.assets.workerUrl, { name: 'libreoffice-document' })
|
|
27
42
|
const channel = new SharedArrayBuffer(FONT_HEADER_BYTES + FONT_CHUNK_BYTES)
|
|
28
43
|
const { control, bytes } = fontViews(channel)
|
|
@@ -32,7 +47,8 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
|
|
|
32
47
|
let closed = false
|
|
33
48
|
let disposal: Promise<void> | undefined
|
|
34
49
|
let frames: ReturnType<typeof fontFrames> | undefined
|
|
35
|
-
let
|
|
50
|
+
let resolveFonts: BrowserDocumentOptions['resolveFonts'] | undefined
|
|
51
|
+
let onMissingFonts: BrowserDocumentOptions['onMissingFonts'] | undefined
|
|
36
52
|
|
|
37
53
|
function failPending(error: unknown): void {
|
|
38
54
|
for (const entry of pending.values()) entry.reject(error)
|
|
@@ -64,14 +80,15 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
|
|
|
64
80
|
case 'office-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
|
|
65
81
|
case 'font':
|
|
66
82
|
if (closed) return
|
|
67
|
-
|
|
83
|
+
if (!resolveFonts) { sendFontError(new BrowserRenderError('font-unavailable', 'No document font resolver is active.')); return }
|
|
84
|
+
void Promise.resolve().then(() => resolveFonts!(message.request, message.known, lifetime.signal)).then(result => {
|
|
68
85
|
if (closed) return
|
|
69
86
|
frames = fontFrames(result, message.known)
|
|
70
87
|
pumpFonts()
|
|
71
88
|
}, sendFontError)
|
|
72
89
|
return
|
|
73
90
|
case 'font-next': pumpFonts(); return
|
|
74
|
-
case 'missing-fonts': if (!closed)
|
|
91
|
+
case 'missing-fonts': if (!closed) onMissingFonts?.(message.families); return
|
|
75
92
|
default: {
|
|
76
93
|
const entry = pending.get(message.id)
|
|
77
94
|
if (!entry) return
|
|
@@ -99,7 +116,7 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
|
|
|
99
116
|
void dispose()
|
|
100
117
|
}
|
|
101
118
|
|
|
102
|
-
function post(message:
|
|
119
|
+
function post(message: { id: number } & Record<string, unknown>, transfer: Transferable[] = []): Promise<WorkerMessage> {
|
|
103
120
|
return new Promise((resolve, reject) => {
|
|
104
121
|
const timer = setTimeout(() => {
|
|
105
122
|
pending.delete(message.id)
|
|
@@ -121,6 +138,8 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
|
|
|
121
138
|
signal?.removeEventListener('abort', aborted)
|
|
122
139
|
lifetime.abort()
|
|
123
140
|
frames = undefined
|
|
141
|
+
resolveFonts = undefined
|
|
142
|
+
onMissingFonts = undefined
|
|
124
143
|
Atomics.store(control, 0, FontState.Cancelled)
|
|
125
144
|
Atomics.notify(control, 0)
|
|
126
145
|
failPending(new BrowserRenderError('disposed', 'The document is closed.'))
|
|
@@ -134,33 +153,85 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
|
|
|
134
153
|
function aborted(): void { void dispose() }
|
|
135
154
|
signal?.addEventListener('abort', aborted, { once: true })
|
|
136
155
|
|
|
156
|
+
function request(message: OwnerRequest, operation?: AbortSignal, transfer: Transferable[] = []): Promise<WorkerMessage> {
|
|
157
|
+
if (closed) return Promise.reject(new BrowserRenderError('disposed', 'The document is closed.'))
|
|
158
|
+
if (operation?.aborted) return Promise.reject(operation.reason)
|
|
159
|
+
const task = post({ ...message, id: ++sequence }, transfer)
|
|
160
|
+
if (!operation) return task
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const abort = (): void => { reject(operation.reason) }
|
|
163
|
+
operation.addEventListener('abort', abort, { once: true })
|
|
164
|
+
void task.then(resolve, reject).finally(() => operation.removeEventListener('abort', abort))
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const engineOptions: WorkerOptions = { assets: options.assets,
|
|
169
|
+
...(options.preparedEngine === undefined ? {} : { preparedEngine: options.preparedEngine }),
|
|
170
|
+
timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks,
|
|
171
|
+
maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
|
|
137
172
|
try {
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(office ? { office: true } : {}) }, [data.buffer])
|
|
141
|
-
if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
|
|
142
|
-
opened = result
|
|
143
|
-
if (opened.type !== 'opened' || opened.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
|
|
173
|
+
const started = await post({ type: 'start', id: ++sequence, options: engineOptions, channel })
|
|
174
|
+
if (started.type !== 'started') throw new BrowserRenderError('unavailable', 'LibreOffice returned an unexpected start response.')
|
|
144
175
|
signal?.throwIfAborted()
|
|
145
|
-
} catch (
|
|
176
|
+
} catch (failure) {
|
|
146
177
|
await dispose()
|
|
147
178
|
signal?.throwIfAborted()
|
|
148
|
-
throw
|
|
179
|
+
throw failure
|
|
149
180
|
}
|
|
150
181
|
|
|
151
182
|
return {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
183
|
+
async openDocument(documentOptions, documentSignal) {
|
|
184
|
+
if (closed) throw new BrowserRenderError('disposed', 'The document is closed.')
|
|
185
|
+
if (!['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(documentOptions.extension) || documentOptions.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
|
|
186
|
+
const data = new Uint8Array(documentOptions.data)
|
|
187
|
+
resolveFonts = documentOptions.resolveFonts
|
|
188
|
+
onMissingFonts = documentOptions.onMissingFonts
|
|
189
|
+
try {
|
|
190
|
+
const result = await request({ type: 'open', options: { data, extension: documentOptions.extension,
|
|
191
|
+
...(documentOptions.restore === undefined ? {} : { restore: documentOptions.restore }) } }, documentSignal, [data.buffer])
|
|
192
|
+
if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
|
|
193
|
+
if (result.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
|
|
194
|
+
documentSignal?.throwIfAborted()
|
|
195
|
+
return result
|
|
196
|
+
} catch (failure) {
|
|
197
|
+
await dispose()
|
|
198
|
+
documentSignal?.throwIfAborted()
|
|
199
|
+
throw failure
|
|
200
|
+
}
|
|
163
201
|
},
|
|
202
|
+
async closeDocument() {
|
|
203
|
+
if (closed) return
|
|
204
|
+
try {
|
|
205
|
+
const result = await request({ type: 'close-document' })
|
|
206
|
+
if (result.type !== 'closed-document') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected close response.')
|
|
207
|
+
} finally {
|
|
208
|
+
resolveFonts = undefined
|
|
209
|
+
onMissingFonts = undefined
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
request,
|
|
164
213
|
dispose,
|
|
165
214
|
}
|
|
166
215
|
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Load original PDF bytes in a dedicated Worker without Draw import.
|
|
219
|
+
* @param options - Resources, limits, source bytes and asynchronous Host font provider.
|
|
220
|
+
* @param signal - Document lifetime; abort closes its Worker and all pending work.
|
|
221
|
+
* @param onEvent - Reading notifications, including fatal Worker failures.
|
|
222
|
+
* @returns Initial geometry, ordered Worker requests and joined disposal.
|
|
223
|
+
*/
|
|
224
|
+
export async function openBrowserConnection(options: BrowserDocumentOptions, signal?: AbortSignal,
|
|
225
|
+
onEvent?: (event: OfficeDocumentEvent) => void) {
|
|
226
|
+
signal?.throwIfAborted()
|
|
227
|
+
if (options.extension !== 'pdf' || options.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
|
|
228
|
+
const connected = await openBrowserWorker(options, signal, onEvent)
|
|
229
|
+
try {
|
|
230
|
+
const opened = await connected.openDocument({ data: options.data, extension: options.extension,
|
|
231
|
+
resolveFonts: options.resolveFonts, ...(options.onMissingFonts === undefined ? {} : { onMissingFonts: options.onMissingFonts }) }, signal)
|
|
232
|
+
return { opened, request: connected.request, dispose: connected.dispose }
|
|
233
|
+
} catch (error) {
|
|
234
|
+
await connected.dispose()
|
|
235
|
+
throw error
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -14,9 +14,11 @@ export function fontViews(channel: SharedArrayBuffer): { control: Int32Array; by
|
|
|
14
14
|
export function* fontFrames(result: BrowserFontResult, known: readonly FontIdentity[] = []): Generator<{ state: FontState; bytes: Uint8Array }> {
|
|
15
15
|
const identities = new Map(known.map(font => [font.id, font]))
|
|
16
16
|
const header: FontHeader = { fonts: result.fonts.map(font => {
|
|
17
|
-
const
|
|
17
|
+
const size = font.data === undefined ? font.bytes : font.data.byteLength
|
|
18
|
+
const identity: FontIdentity = { id: font.id, bytes: size, ...(font.format ? { format: font.format } : {}) }
|
|
18
19
|
const prior = identities.get(font.id)
|
|
19
20
|
if (prior && (prior.bytes !== identity.bytes || prior.format !== identity.format)) throw new BrowserRenderError('font-unavailable', 'Font identity has conflicting bytes or formats.')
|
|
21
|
+
if (!prior && font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
|
|
20
22
|
identities.set(font.id, identity)
|
|
21
23
|
return { ...identity, family: font.family, alias: font.alias, ...(prior ? { reference: true as const } : {}) }
|
|
22
24
|
}), ...(result.missingFamily === undefined ? {} : { missingFamily: result.missingFamily }) }
|
|
@@ -25,6 +27,8 @@ export function* fontFrames(result: BrowserFontResult, known: readonly FontIdent
|
|
|
25
27
|
yield { state: FontState.Header, bytes: encoded }
|
|
26
28
|
for (const [index, font] of result.fonts.entries()) {
|
|
27
29
|
if (header.fonts[index]!.reference) continue
|
|
30
|
+
/* v8 ignore next -- header validation rejects an unknown data-less font before iteration. */
|
|
31
|
+
if (font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
|
|
28
32
|
for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) {
|
|
29
33
|
yield { state: FontState.Bytes, bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES) }
|
|
30
34
|
}
|
|
@@ -34,17 +38,50 @@ export function* fontFrames(result: BrowserFontResult, known: readonly FontIdent
|
|
|
34
38
|
|
|
35
39
|
/** One MEMFS font face registered under a document-local family alias. */
|
|
36
40
|
export interface EngineFontFace { readonly path: string; readonly family: string }
|
|
41
|
+
/** Fonts and internal aliases retained for the lifetime of one engine Worker. */
|
|
42
|
+
export interface EngineFontCache {
|
|
43
|
+
readonly installed: Map<string, { face: EngineFontFace; bytes: number; format: FontIdentity['format'] }>
|
|
44
|
+
readonly aliases: Map<string, { id: string; family: string }>
|
|
45
|
+
loadedBytes: number
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @returns Empty runtime-owned font state shared by successive documents. */
|
|
49
|
+
export function createEngineFontCache(): EngineFontCache {
|
|
50
|
+
return { installed: new Map(), aliases: new Map(), loadedBytes: 0 }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const SCRIPT_GROUPS = [
|
|
54
|
+
['arabic', /\p{Script_Extensions=Arabic}/u], ['cyrillic', /\p{Script_Extensions=Cyrillic}/u],
|
|
55
|
+
['devanagari', /\p{Script_Extensions=Devanagari}/u], ['greek', /\p{Script_Extensions=Greek}/u],
|
|
56
|
+
['han', /\p{Script_Extensions=Han}/u], ['hangul', /\p{Script_Extensions=Hangul}/u],
|
|
57
|
+
['hebrew', /\p{Script_Extensions=Hebrew}/u], ['hiragana', /\p{Script_Extensions=Hiragana}/u],
|
|
58
|
+
['katakana', /\p{Script_Extensions=Katakana}/u], ['latin', /\p{Script_Extensions=Latin}/u],
|
|
59
|
+
['thai', /\p{Script_Extensions=Thai}/u], ['common', /[\p{Script=Common}\p{Script=Inherited}]/u],
|
|
60
|
+
] as const
|
|
61
|
+
|
|
62
|
+
function scriptGroup(point: number): string {
|
|
63
|
+
const character = String.fromCodePoint(point)
|
|
64
|
+
return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`
|
|
65
|
+
}
|
|
37
66
|
|
|
38
67
|
/** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
|
|
39
68
|
export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number,
|
|
40
69
|
declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void,
|
|
41
|
-
install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void
|
|
70
|
+
install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void,
|
|
71
|
+
documentCodePoints: readonly number[] = [], cache: EngineFontCache = createEngineFontCache()): (request: BrowserFontRequest) => EngineFontFace[] {
|
|
42
72
|
const { control, bytes } = fontViews(channel)
|
|
43
|
-
const installed
|
|
44
|
-
const aliases = new Map<string, { id: string; family: string }>()
|
|
73
|
+
const { installed, aliases } = cache
|
|
45
74
|
const requests = new Map<string, EngineFontFace[]>()
|
|
75
|
+
const coverage = new Map<string, { readonly points: Set<number>; readonly faces: EngineFontFace[]; complete: boolean }>()
|
|
76
|
+
const expanded = new Map<string, Set<string>>()
|
|
77
|
+
const documentGroups = new Map<string, number[]>()
|
|
78
|
+
for (const point of [...new Set(documentCodePoints)].sort((left, right) => left - right)) {
|
|
79
|
+
const group = scriptGroup(point)
|
|
80
|
+
const points = documentGroups.get(group)
|
|
81
|
+
if (points) points.push(point)
|
|
82
|
+
else documentGroups.set(group, [point])
|
|
83
|
+
}
|
|
46
84
|
const families = new Set<string>()
|
|
47
|
-
let loadedBytes = 0
|
|
48
85
|
function read(): { state: FontState; data: Uint8Array } {
|
|
49
86
|
const started = performance.now()
|
|
50
87
|
while (Atomics.load(control, 0) === FontState.Waiting) {
|
|
@@ -63,11 +100,24 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
63
100
|
}
|
|
64
101
|
return (attributes) => {
|
|
65
102
|
const canonical = aliases.get(normalize(attributes.family))?.family
|
|
66
|
-
const
|
|
103
|
+
const codePoints = [...new Set(attributes.codePoints)].sort((left, right) => left - right)
|
|
104
|
+
const original = { ...attributes, codePoints, ...(canonical === undefined ? {} : { family: canonical }) }
|
|
67
105
|
const key = JSON.stringify(original)
|
|
68
106
|
const cached = requests.get(key)
|
|
69
107
|
if (cached) return cached
|
|
70
|
-
|
|
108
|
+
const { codePoints: _points, ...base } = original
|
|
109
|
+
const coverageKey = JSON.stringify(base)
|
|
110
|
+
const covered = coverage.get(coverageKey)
|
|
111
|
+
if (codePoints.length > 0 && covered && (covered.complete || codePoints.every(point => covered.points.has(point)))) {
|
|
112
|
+
requests.set(key, covered.faces)
|
|
113
|
+
return covered.faces
|
|
114
|
+
}
|
|
115
|
+
const groups = new Set(codePoints.map(scriptGroup))
|
|
116
|
+
const expandedGroups = expanded.get(coverageKey)
|
|
117
|
+
const newGroups = original.mode === 'full' ? [] : [...groups].filter(group => !expandedGroups?.has(group))
|
|
118
|
+
const requestedPoints = newGroups.length === 0 ? codePoints : [...new Set([...codePoints,
|
|
119
|
+
...newGroups.flatMap(group => documentGroups.get(group) ?? [])])].sort((left, right) => left - right)
|
|
120
|
+
request({ ...original, codePoints: requestedPoints }, [...installed].map(([id, font]) => ({ id, bytes: font.bytes, ...(font.format ? { format: font.format } : {}) })))
|
|
71
121
|
const first = read()
|
|
72
122
|
if (first.state !== FontState.Header) throw new BrowserRenderError('font-unavailable', 'Expected font transfer metadata.')
|
|
73
123
|
let header: FontHeader
|
|
@@ -84,7 +134,7 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
84
134
|
const alias = normalize(font.alias)
|
|
85
135
|
const previousAlias = aliases.get(alias)
|
|
86
136
|
if (previousAlias && (previousAlias.family !== font.family || (font.format === undefined && previousAlias.id !== font.id))) throw new BrowserRenderError('font-unavailable', 'Font alias identifies conflicting subsets.')
|
|
87
|
-
if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
|
|
137
|
+
if (!prior && cache.loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
|
|
88
138
|
const buffer = prior ? undefined : new Uint8Array(font.bytes)
|
|
89
139
|
let received = 0
|
|
90
140
|
while (!font.reference && received < font.bytes) {
|
|
@@ -96,7 +146,7 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
96
146
|
// A full TTC asset can expose multiple families from the same installed bytes.
|
|
97
147
|
// Its requested family must not inherit the first family's alias.
|
|
98
148
|
const face = { path: prior?.face.path ?? (font.format === undefined ? `/dsh-fonts/${installed.size}.font` : `/usr/share/fonts/dsh-pdfium/${installed.size}.${font.format}`), family: font.alias }
|
|
99
|
-
if (buffer) { install(face.path, buffer); installed.set(font.id, { face, bytes: buffer.length, format: font.format }); loadedBytes += buffer.length }
|
|
149
|
+
if (buffer) { install(face.path, buffer); installed.set(font.id, { face, bytes: buffer.length, format: font.format }); cache.loadedBytes += buffer.length }
|
|
100
150
|
aliases.set(alias, { id: font.id, family: font.family })
|
|
101
151
|
faces.push(face)
|
|
102
152
|
}
|
|
@@ -104,6 +154,16 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
|
|
|
104
154
|
const absentFamily = header.missingFamily === undefined ? undefined : declaredFamilies.get(normalize(header.missingFamily))
|
|
105
155
|
if (absentFamily !== undefined && !families.has(absentFamily)) { families.add(absentFamily); missing([...families]) }
|
|
106
156
|
requests.set(key, faces)
|
|
157
|
+
if (newGroups.length > 0) expanded.set(coverageKey, new Set([...(expandedGroups ?? []), ...newGroups]))
|
|
158
|
+
if (requestedPoints.length > 0) {
|
|
159
|
+
const group = { points: new Set(covered?.points), faces: [...(covered?.faces ?? [])], complete: covered?.complete ?? false }
|
|
160
|
+
for (const point of requestedPoints) group.points.add(point)
|
|
161
|
+
for (const face of faces) {
|
|
162
|
+
if (!group.faces.some(existing => existing.path === face.path && existing.family === face.family)) group.faces.push(face)
|
|
163
|
+
}
|
|
164
|
+
group.complete ||= header.fonts.every(font => font.format !== undefined)
|
|
165
|
+
coverage.set(coverageKey, group)
|
|
166
|
+
}
|
|
107
167
|
return faces
|
|
108
168
|
}
|
|
109
169
|
}
|
|
@@ -3,9 +3,10 @@ import { openBrowserConnection } from './connection.ts'
|
|
|
3
3
|
import { BrowserRenderError } from './types.ts'
|
|
4
4
|
import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
5
5
|
export { BrowserRenderError } from './types.ts'
|
|
6
|
-
export { openOfficeDocument } from './office.ts'
|
|
6
|
+
export { openOfficeDocument, openOfficeRuntime } from './office.ts'
|
|
7
|
+
export { prepareOfficeBrowser } from './preparation.ts'
|
|
7
8
|
export type * from './office-types.ts'
|
|
8
|
-
export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
9
|
+
export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserRuntimeOptions, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts'
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Open a read-only document; each call owns an independent Worker.
|
|
@@ -3,7 +3,7 @@ import { BrowserRenderError } from './types.ts'
|
|
|
3
3
|
import type { BrowserTile } from './types.ts'
|
|
4
4
|
import type { EmscriptenModule } from './engine-types.ts'
|
|
5
5
|
import type { OfficeOperation } from './protocol.ts'
|
|
6
|
-
import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
|
|
6
|
+
import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeReadingState } from './office-types.ts'
|
|
7
7
|
import { parseCellRange } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
|
|
8
8
|
import { renderRegion } from './engine-rendering.ts'
|
|
9
9
|
import { TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
|
|
@@ -41,7 +41,8 @@ export class OfficeEngine {
|
|
|
41
41
|
private geometryDirty = false
|
|
42
42
|
private stopped = false
|
|
43
43
|
private layoutWidth = 0
|
|
44
|
-
private
|
|
44
|
+
private viewportKey = ''
|
|
45
|
+
private viewportState: OfficeReadingState['viewport'] = null
|
|
45
46
|
private captureView: number | undefined
|
|
46
47
|
private readingView: number | undefined
|
|
47
48
|
private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
|
|
@@ -171,7 +172,7 @@ export class OfficeEngine {
|
|
|
171
172
|
case 14: {
|
|
172
173
|
const part = Number(payload)
|
|
173
174
|
if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
|
|
174
|
-
this.state = { ...this.state, part }; this.
|
|
175
|
+
this.state = { ...this.state, part }; this.viewportKey = ''; this.viewportState = null; this.geometryDirty = true; changed = true
|
|
175
176
|
}
|
|
176
177
|
break
|
|
177
178
|
}
|
|
@@ -239,7 +240,8 @@ export class OfficeEngine {
|
|
|
239
240
|
const part = integer(operation.part, this.state.parts.length - 1)
|
|
240
241
|
if (part === this.state.part) break
|
|
241
242
|
this.invoke('part', [part])
|
|
242
|
-
this.
|
|
243
|
+
this.viewportKey = ''
|
|
244
|
+
this.viewportState = null
|
|
243
245
|
this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
|
|
244
246
|
const geometry = this.refreshGeometry()
|
|
245
247
|
if (geometry !== undefined) this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1,
|
|
@@ -253,7 +255,11 @@ export class OfficeEngine {
|
|
|
253
255
|
if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
|
|
254
256
|
const args = [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)]
|
|
255
257
|
const key = args.join(',')
|
|
256
|
-
if (key !== this.
|
|
258
|
+
if (key !== this.viewportKey) {
|
|
259
|
+
this.invoke('viewport', args)
|
|
260
|
+
this.viewportKey = key
|
|
261
|
+
this.viewportState = { rectangle: { ...operation.rectangle }, scale: operation.scale }
|
|
262
|
+
}
|
|
257
263
|
break
|
|
258
264
|
}
|
|
259
265
|
case 'layout': {
|
|
@@ -267,7 +273,8 @@ export class OfficeEngine {
|
|
|
267
273
|
if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } }
|
|
268
274
|
const result = this.configure(request)
|
|
269
275
|
this.layoutWidth = width
|
|
270
|
-
this.
|
|
276
|
+
this.viewportKey = ''
|
|
277
|
+
this.viewportState = null
|
|
271
278
|
this.state = { ...this.state, layout: request.mode, layoutGeneration: this.state.layoutGeneration + 1,
|
|
272
279
|
renderGeneration: this.state.renderGeneration + 1 }
|
|
273
280
|
// Establish the requested layout before its acknowledgement pumps any
|
|
@@ -303,6 +310,73 @@ export class OfficeEngine {
|
|
|
303
310
|
try { this.invoke('command', [name, JSON.stringify(args)]); this.pump(); await result.promise }
|
|
304
311
|
finally { this.commandResult = undefined }
|
|
305
312
|
}
|
|
313
|
+
/** Read the part and selection the next open of these bytes must restore. */
|
|
314
|
+
capture(): OfficeReadingState {
|
|
315
|
+
this.requireOpen()
|
|
316
|
+
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
317
|
+
this.flush()
|
|
318
|
+
const raw = this.text('dsh_lok_document_capture_reading_selection', [this.document])
|
|
319
|
+
let text: OfficeReadingState['text'] = null
|
|
320
|
+
let cell: string | null = null
|
|
321
|
+
let object: OfficeReadingState['object'] = null
|
|
322
|
+
if (raw !== null && raw !== '') {
|
|
323
|
+
const selection = JSON.parse(raw) as { kind?: unknown; pointNode?: unknown; pointOffset?: unknown;
|
|
324
|
+
markNode?: unknown; markOffset?: unknown; range?: unknown; paths?: unknown }
|
|
325
|
+
if (selection.kind === 'text') {
|
|
326
|
+
text = { pointNode: integer(selection.pointNode as number), pointOffset: integer(selection.pointOffset as number),
|
|
327
|
+
markNode: integer(selection.markNode as number), markOffset: integer(selection.markOffset as number) }
|
|
328
|
+
} else if (selection.kind === 'cell' && typeof selection.range === 'string') {
|
|
329
|
+
parseCellRange(selection.range)
|
|
330
|
+
cell = selection.range
|
|
331
|
+
} else if (selection.kind === 'object' && typeof selection.paths === 'string') {
|
|
332
|
+
const paths = selection.paths.split(',')
|
|
333
|
+
if (paths.some(path => path === '' || path.split('/').some(value => value === '')))
|
|
334
|
+
throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid object selection.')
|
|
335
|
+
object = paths.map(path => path.split('/').map(value => integer(Number(value))))
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const layout: OfficeReadingState['layout'] = this.state.layout === 'continuous'
|
|
339
|
+
? { mode: 'continuous', width: this.layoutWidth / TWIPS_PER_CSS_PIXEL } : { mode: 'paginated' }
|
|
340
|
+
return { version: 1, documentType: this.state.documentType, part: this.state.part,
|
|
341
|
+
layout, viewport: this.viewportState, text, cell, object }
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Apply a reading position captured from the same bytes.
|
|
345
|
+
* @param state - Part and selection captured before this document closed.
|
|
346
|
+
*/
|
|
347
|
+
async restore(state: OfficeReadingState): Promise<void> {
|
|
348
|
+
this.requireOpen()
|
|
349
|
+
if (state.version !== 1 || state.documentType !== this.state.documentType)
|
|
350
|
+
throw new BrowserRenderError('render-failed', 'The captured reading state belongs to another document.')
|
|
351
|
+
if (this.state.documentType === 'text') {
|
|
352
|
+
if (state.layout.mode === 'continuous') {
|
|
353
|
+
const anchor = state.viewport === null ? undefined
|
|
354
|
+
: { x: state.viewport.rectangle.x, y: state.viewport.rectangle.y }
|
|
355
|
+
await this.operation({ type: 'layout', request: { mode: 'continuous', width: state.layout.width,
|
|
356
|
+
...(anchor === undefined ? {} : { anchor }) } })
|
|
357
|
+
} else if (state.layout.mode !== 'paginated') {
|
|
358
|
+
throw new BrowserRenderError('render-failed', 'The captured reading layout is invalid.')
|
|
359
|
+
}
|
|
360
|
+
} else if (state.layout.mode !== 'paginated') {
|
|
361
|
+
throw new BrowserRenderError('render-failed', 'The captured reading layout belongs to a Writer document.')
|
|
362
|
+
}
|
|
363
|
+
if (this.state.documentType !== 'text' && state.part !== this.state.part)
|
|
364
|
+
await this.operation({ type: 'part', part: state.part })
|
|
365
|
+
if (state.text && this.state.documentType === 'text') {
|
|
366
|
+
const { pointNode, pointOffset, markNode, markOffset } = state.text
|
|
367
|
+
this.invoke('restore_reading_text_selection', [integer(pointNode), integer(pointOffset),
|
|
368
|
+
integer(markNode), integer(markOffset)])
|
|
369
|
+
}
|
|
370
|
+
if (state.cell && this.state.documentType === 'spreadsheet')
|
|
371
|
+
await this.operation({ type: 'cell', address: state.cell })
|
|
372
|
+
if (state.object && this.state.documentType === 'presentation') {
|
|
373
|
+
const paths = state.object.map(path => path.map(value => integer(value)).join('/')).join(',')
|
|
374
|
+
if (!paths) throw new BrowserRenderError('render-failed', 'The captured object selection is invalid.')
|
|
375
|
+
this.invoke('restore_reading_object_selection', [paths])
|
|
376
|
+
}
|
|
377
|
+
if (state.viewport !== null) await this.operation({ type: 'viewport', ...state.viewport })
|
|
378
|
+
this.pump()
|
|
379
|
+
}
|
|
306
380
|
/** Direct tiles preserve the active view, navigation state and selection. */
|
|
307
381
|
render(request: OfficeDocumentTileRequest): BrowserTile {
|
|
308
382
|
this.requireOpen()
|
|
@@ -52,12 +52,51 @@ export interface OfficeDocumentNavigation {
|
|
|
52
52
|
}
|
|
53
53
|
/** One region of the current part. Pixel density does not change document layout. */
|
|
54
54
|
export interface OfficeDocumentTileRequest extends OfficeDocumentRectangle { readonly part: number; readonly scale: number }
|
|
55
|
+
/** Writer selection as document-model positions; one file always resolves to the same nodes. */
|
|
56
|
+
export interface OfficeTextSelection {
|
|
57
|
+
/** Document node holding the selection point. */
|
|
58
|
+
readonly pointNode: number
|
|
59
|
+
/** Character offset inside the point node's text. */
|
|
60
|
+
readonly pointOffset: number
|
|
61
|
+
/** Document node holding the selection mark. */
|
|
62
|
+
readonly markNode: number
|
|
63
|
+
/** Character offset inside the mark node's text. */
|
|
64
|
+
readonly markOffset: number
|
|
65
|
+
}
|
|
66
|
+
/** Reading position of one document; capturable before it closes and restorable when its bytes reopen. */
|
|
67
|
+
export interface OfficeReadingState {
|
|
68
|
+
readonly version: 1
|
|
69
|
+
readonly documentType: OfficeDocumentState['documentType']
|
|
70
|
+
/** Writer page, Calc worksheet, or Impress slide. */
|
|
71
|
+
readonly part: number
|
|
72
|
+
/** Writer layout parameters; non-Writer documents remain paginated. */
|
|
73
|
+
readonly layout: { readonly mode: 'paginated' } | { readonly mode: 'continuous'; readonly width: number }
|
|
74
|
+
/** Last document-coordinate viewport and raster scale, when one was configured. */
|
|
75
|
+
readonly viewport: { readonly rectangle: OfficeDocumentRectangle; readonly scale: number } | null
|
|
76
|
+
/** Writer text selection; null when the reader holds no text selection. */
|
|
77
|
+
readonly text: OfficeTextSelection | null
|
|
78
|
+
/** Calc selected range in A1 notation; null when the reader holds no cell range. */
|
|
79
|
+
readonly cell: string | null
|
|
80
|
+
/** Selected drawing objects as ordinal paths inside the current slide. */
|
|
81
|
+
readonly object: readonly (readonly number[])[] | null
|
|
82
|
+
}
|
|
83
|
+
/** Source bytes and reading position for one document of a shared runtime. */
|
|
84
|
+
export interface OfficeDocumentOpenOptions {
|
|
85
|
+
readonly data: Uint8Array
|
|
86
|
+
readonly extension: OfficeDocumentFormat
|
|
87
|
+
/** Match fonts for this document without blocking the browser's main thread. */
|
|
88
|
+
readonly resolveFonts: BrowserDocumentOptions['resolveFonts']
|
|
89
|
+
/** Called with unavailable declared families for this document. */
|
|
90
|
+
readonly onMissingFonts?: BrowserDocumentOptions['onMissingFonts']
|
|
91
|
+
/** Reading position captured from an earlier open of the same bytes. */
|
|
92
|
+
readonly restore?: OfficeReadingState
|
|
93
|
+
}
|
|
55
94
|
/** A null rectangle invalidates an entire part; negative part means every part. */
|
|
56
95
|
export type OfficeDocumentEvent =
|
|
57
96
|
| { readonly type: 'state'; readonly state: OfficeDocumentState }
|
|
58
97
|
| { readonly type: 'invalidate'; readonly part: number; readonly rectangle: OfficeDocumentRectangle | null; readonly generation: number }
|
|
59
98
|
| { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
|
|
60
|
-
/**
|
|
99
|
+
/** One open document of a runtime; closing it frees the parsed model without destroying the engine. */
|
|
61
100
|
export interface OfficeDocument {
|
|
62
101
|
readonly state: OfficeDocumentState
|
|
63
102
|
subscribe(listener: (event: OfficeDocumentEvent) => void): () => void
|
|
@@ -73,5 +112,17 @@ export interface OfficeDocument {
|
|
|
73
112
|
setLayout(request: OfficeDocumentLayoutRequest): Promise<OfficeDocumentLayoutResult>
|
|
74
113
|
/** Only the current part can be painted; queued requests for a former part reject with stale-part without changing selection. */
|
|
75
114
|
renderTile(request: OfficeDocumentTileRequest, signal?: AbortSignal): Promise<BrowserTile>
|
|
115
|
+
/** Read the position the next open of the same bytes must restore. */
|
|
116
|
+
captureReadingState(): Promise<OfficeReadingState>
|
|
117
|
+
/** Close this document and release its model; the owning runtime keeps its engine. */
|
|
118
|
+
close(): Promise<void>
|
|
119
|
+
/** Close this document and destroy the owning runtime. */
|
|
120
|
+
dispose(): Promise<void>
|
|
121
|
+
}
|
|
122
|
+
/** One engine Worker that opens documents one at a time without reinitializing LibreOffice. */
|
|
123
|
+
export interface OfficeRuntime {
|
|
124
|
+
/** Open a document, closing the document this runtime currently holds. */
|
|
125
|
+
open(options: OfficeDocumentOpenOptions, signal?: AbortSignal): Promise<OfficeDocument>
|
|
126
|
+
/** Close the open document and release the Worker, its WASM instance and its pthreads. */
|
|
76
127
|
dispose(): Promise<void>
|
|
77
128
|
}
|