@deepseek-ai/libreoffice-kit 0.0.2-rc9 → 0.0.3
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/NOTICE +0 -240
- package/README.md +53 -43
- package/README.zh.md +58 -35
- package/lib/cli.js +725 -132
- package/lib/index.js +757 -133
- package/lib/types/engine.d.ts +5 -5
- package/lib/types/font-loader.d.ts +18 -16
- package/lib/types/fonts.d.ts +38 -21
- package/lib/types/image-operations.d.ts +1 -1
- package/lib/types/index.d.ts +13 -7
- package/lib/types/native-image-renderer.d.ts +19 -0
- package/lib/types/native.d.ts +1 -1
- package/lib/types/options.d.ts +3 -1
- package/lib/types/wasm.d.ts +4 -1
- package/lib/types/worker.d.ts +2 -0
- package/lib/worker.js +420 -942
- package/package.json +13 -55
- package/assets/font-subset.json +0 -70
- package/assets/font-subset.wasm +0 -0
- package/lib/browser/assets.json +0 -10
- package/lib/browser/index.js +0 -626
- package/lib/browser/types/connection.d.ts +0 -42
- package/lib/browser/types/engine-rendering.d.ts +0 -3
- package/lib/browser/types/engine-types.d.ts +0 -17
- package/lib/browser/types/font-channel.d.ts +0 -36
- package/lib/browser/types/index.d.ts +0 -14
- package/lib/browser/types/office-engine.d.ts +0 -56
- package/lib/browser/types/office-types.d.ts +0 -166
- package/lib/browser/types/office.d.ts +0 -19
- package/lib/browser/types/preparation.d.ts +0 -13
- package/lib/browser/types/protocol.d.ts +0 -137
- package/lib/browser/types/rendering.d.ts +0 -4
- package/lib/browser/types/types.d.ts +0 -115
- package/lib/browser/types/worker.d.ts +0 -2
- package/lib/browser/worker.js +0 -3796
- package/lib/browser-assets.js +0 -119
- package/lib/document.js +0 -178
- package/lib/engine-rendering.js +0 -120
- package/lib/font-config.js +0 -46
- package/lib/font-source.js +0 -395
- package/lib/font-worker.js +0 -1481
- package/lib/rendering.js +0 -99
- package/lib/sheet-geometry.js +0 -111
- package/lib/types/browser-assets.d.ts +0 -15
- package/lib/types/default-fonts.d.ts +0 -3
- package/lib/types/font-config.d.ts +0 -24
- package/lib/types/font-preferences-data.d.ts +0 -16
- package/lib/types/font-preferences.d.ts +0 -29
- package/lib/types/font-request.d.ts +0 -12
- package/lib/types/font-source-types.d.ts +0 -95
- package/lib/types/font-source.d.ts +0 -10
- package/lib/types/font-subsets.d.ts +0 -39
- package/lib/types/font-worker.d.ts +0 -2
- package/lib/types/harfbuzz-subset.d.ts +0 -11
- package/lib/types/unicode-scripts.d.ts +0 -18
- package/licenses/font-subset/harfbuzz-COPYING +0 -42
- package/licenses/font-subset/harfbuzzjs-LICENSE +0 -19
- package/licenses/javascript/fflate-LICENSE +0 -21
- package/licenses/javascript/saxes-LICENSE +0 -64
- package/licenses/javascript/xmlchars-LICENSE +0 -18
- package/sources/browser/packages/browser/package.json +0 -22
- package/sources/browser/packages/browser/src/connection.ts +0 -237
- package/sources/browser/packages/browser/src/engine-rendering.ts +0 -2
- package/sources/browser/packages/browser/src/engine-types.ts +0 -14
- package/sources/browser/packages/browser/src/font-channel.ts +0 -169
- package/sources/browser/packages/browser/src/index.ts +0 -40
- package/sources/browser/packages/browser/src/office-engine.ts +0 -397
- package/sources/browser/packages/browser/src/office-types.ts +0 -128
- package/sources/browser/packages/browser/src/office.ts +0 -128
- package/sources/browser/packages/browser/src/preparation.ts +0 -41
- package/sources/browser/packages/browser/src/protocol.ts +0 -55
- package/sources/browser/packages/browser/src/rendering.ts +0 -3
- package/sources/browser/packages/browser/src/types.ts +0 -118
- package/sources/browser/packages/browser/src/worker.ts +0 -260
- package/sources/browser/packages/browser/tsconfig.json +0 -5
- package/sources/browser/packages/browser/tsdown.config.ts +0 -7
- package/sources/browser/scripts/build-browser.mjs +0 -86
- package/sources/font-subset/engine/font-subset/README.md +0 -23
- package/sources/font-subset/engine/font-subset/README.zh.md +0 -23
- package/sources/font-subset/engine/font-subset/source.json +0 -16
- package/sources/font-subset/harfbuzzjs/config-override-subset.h +0 -7
- package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +0 -34
- package/sources/font-subset/scripts/build-font-subset.mjs +0 -64
- package/sources/font-subset/scripts/pack-utils.mjs +0 -69
- package/sources/font-subset/scripts/platform-matrix.mjs +0 -100
- package/sources/font-subset/scripts/verify-artifacts.mjs +0 -260
|
@@ -1,397 +0,0 @@
|
|
|
1
|
-
/** Worker-owned reading, bounded VCL event slices and immutable notifications. */
|
|
2
|
-
import { BrowserRenderError } from './types.ts'
|
|
3
|
-
import type { BrowserTile } from './types.ts'
|
|
4
|
-
import type { EmscriptenModule } from './engine-types.ts'
|
|
5
|
-
import type { OfficeOperation } from './protocol.ts'
|
|
6
|
-
import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeReadingState } from './office-types.ts'
|
|
7
|
-
import { parseCellRange } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
|
|
8
|
-
import { renderRegion } from './engine-rendering.ts'
|
|
9
|
-
import { TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
|
|
10
|
-
|
|
11
|
-
function rectangle(payload: string): OfficeDocumentRectangle | null {
|
|
12
|
-
if (payload.startsWith('{')) {
|
|
13
|
-
const value: unknown = JSON.parse(payload)
|
|
14
|
-
if (typeof value !== 'object' || value === null || !('rectangle' in value) || typeof value.rectangle !== 'string') return null
|
|
15
|
-
payload = value.rectangle
|
|
16
|
-
}
|
|
17
|
-
if (!payload || payload.startsWith('EMPTY') || payload === 'INPLACE') return null
|
|
18
|
-
const values = payload.split(',').slice(0, 4).map(Number)
|
|
19
|
-
if (values.length !== 4 || values.some(value => !Number.isFinite(value))) return null
|
|
20
|
-
const [x, y, width, height] = values.map(value => value / TWIPS_PER_CSS_PIXEL) as [number, number, number, number]
|
|
21
|
-
return width >= 0 && height >= 0 ? { x, y, width, height } : null
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function integer(value: number, max = 0x7fffffff): number {
|
|
25
|
-
if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new BrowserRenderError('render-failed', 'Office input contains an invalid integer.')
|
|
26
|
-
return value
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function twips(value: number): number {
|
|
30
|
-
if (!Number.isFinite(value) || Math.abs(value * TWIPS_PER_CSS_PIXEL) > 0x7fffffff) throw new BrowserRenderError('render-failed', 'Office input lies outside document coordinates.')
|
|
31
|
-
return Math.round(value * TWIPS_PER_CSS_PIXEL)
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const navigationKeys = { down: 0x400, up: 0x401, left: 0x402, right: 0x403, home: 0x404, end: 0x405, pageUp: 0x406, pageDown: 0x407 } as const
|
|
35
|
-
|
|
36
|
-
/** One read-only document, driven exclusively by its Worker's messages and timer. */
|
|
37
|
-
export class OfficeEngine {
|
|
38
|
-
state: OfficeDocumentState
|
|
39
|
-
private timer: ReturnType<typeof setTimeout> | undefined
|
|
40
|
-
private readonly callbacks: { type: number; payload: string }[] = []
|
|
41
|
-
private geometryDirty = false
|
|
42
|
-
private stopped = false
|
|
43
|
-
private layoutWidth = 0
|
|
44
|
-
private viewportKey = ''
|
|
45
|
-
private viewportState: OfficeReadingState['viewport'] = null
|
|
46
|
-
private captureView: number | undefined
|
|
47
|
-
private readingView: number | undefined
|
|
48
|
-
private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
|
|
49
|
-
|
|
50
|
-
constructor(private readonly module: EmscriptenModule, private readonly document: number,
|
|
51
|
-
format: OfficeDocumentFormat, private readonly emit: (event: OfficeDocumentEvent) => void,
|
|
52
|
-
private readonly failure: (error: unknown) => void) {
|
|
53
|
-
this.state = { documentType: format === 'docx' || format === 'doc' ? 'text' : format === 'xlsx' || format === 'xls' ? 'spreadsheet' : 'presentation',
|
|
54
|
-
renderGeneration: 0, layoutGeneration: 0, layout: 'paginated', part: 0, parts: [], pages: [], cursor: null,
|
|
55
|
-
selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
private call(name: string, args: (number | string)[] = []): number {
|
|
59
|
-
return this.module.ccall(name, 'number', args.map(value => typeof value), args)
|
|
60
|
-
}
|
|
61
|
-
private text(name: string, args: (number | string)[]): string {
|
|
62
|
-
const pointer = this.call(name, args)
|
|
63
|
-
if (!pointer) return ''
|
|
64
|
-
try { return this.module.UTF8ToString(pointer) } finally { this.call('free', [pointer]) }
|
|
65
|
-
}
|
|
66
|
-
private invoke(name: string, args: (number | string)[] = []): void {
|
|
67
|
-
if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError('render-failed', `LibreOffice could not complete ${name}.`)
|
|
68
|
-
}
|
|
69
|
-
private requireOpen(): void {
|
|
70
|
-
if (this.stopped) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
71
|
-
}
|
|
72
|
-
/** Collect callbacks without reentering LibreOffice inside its callback. */
|
|
73
|
-
callback(type: number, payload: string): void { if (!this.stopped) this.callbacks.push({ type, payload }) }
|
|
74
|
-
/** Enforce the native read-only view before accepting any input. */
|
|
75
|
-
async start(): Promise<void> {
|
|
76
|
-
this.requireOpen()
|
|
77
|
-
if (this.state.documentType === 'presentation') {
|
|
78
|
-
const view = this.call('dsh_lok_document_get_view', [this.document])
|
|
79
|
-
try {
|
|
80
|
-
const created = this.call('dsh_lok_document_create_view', [this.document])
|
|
81
|
-
if (created < 0) throw new BrowserRenderError('render-failed', 'LibreOffice could not create a slide capture view.')
|
|
82
|
-
this.captureView = created
|
|
83
|
-
this.invoke('initialize_rendering')
|
|
84
|
-
this.configure({ mode: 'paginated' })
|
|
85
|
-
this.pump()
|
|
86
|
-
} finally { this.invoke('set_view', [view]) }
|
|
87
|
-
this.readingView = view
|
|
88
|
-
}
|
|
89
|
-
this.configure({ mode: 'paginated' })
|
|
90
|
-
this.invoke('listen')
|
|
91
|
-
this.refreshGeometry()
|
|
92
|
-
this.pump()
|
|
93
|
-
this.schedule()
|
|
94
|
-
await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-open' } })
|
|
95
|
-
}
|
|
96
|
-
private schedule(): void {
|
|
97
|
-
this.timer = setTimeout(() => {
|
|
98
|
-
if (this.stopped) return
|
|
99
|
-
try { this.pump(); this.schedule() } catch (error) { this.stop(); this.failure(error) }
|
|
100
|
-
}, 16)
|
|
101
|
-
}
|
|
102
|
-
/** Stop event processing before destroying the document. */
|
|
103
|
-
stop(): void {
|
|
104
|
-
this.stopped = true
|
|
105
|
-
clearTimeout(this.timer)
|
|
106
|
-
this.callbacks.length = 0
|
|
107
|
-
this.commandResult?.reject(new BrowserRenderError('disposed', 'Office document is closed.'))
|
|
108
|
-
this.commandResult = undefined
|
|
109
|
-
}
|
|
110
|
-
/** Return the part whose cached coordinates changed, or -1 when part identities changed. */
|
|
111
|
-
private refreshGeometry(): number | undefined {
|
|
112
|
-
const count = this.state.documentType === 'text' ? 1 : this.call('dsh_lok_document_parts', [this.document])
|
|
113
|
-
if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError('invalid-document', 'Office document has no parts.')
|
|
114
|
-
const pointer = this.call('malloc', [8])
|
|
115
|
-
if (!pointer) throw new BrowserRenderError('render-failed', 'Office geometry allocation failed.')
|
|
116
|
-
try {
|
|
117
|
-
const part = Math.min(this.state.part, count - 1)
|
|
118
|
-
this.invoke('size', [part, pointer, pointer + 4])
|
|
119
|
-
const width = this.module.HEAPU32[pointer / 4]! / TWIPS_PER_CSS_PIXEL
|
|
120
|
-
const height = this.module.HEAPU32[pointer / 4 + 1]! / TWIPS_PER_CSS_PIXEL
|
|
121
|
-
if (!(width > 0 && height > 0)) throw new BrowserRenderError('invalid-document', 'Office returned empty document dimensions.')
|
|
122
|
-
// Measure the selected part only, preserving navigation and selection.
|
|
123
|
-
const parts = Array.from({ length: count }, (_, index) => ({
|
|
124
|
-
name: this.state.documentType === 'text' ? '' : this.text('dsh_lok_document_part_name', [this.document, index]),
|
|
125
|
-
width: index === part ? width : this.state.parts[index]?.width ?? width,
|
|
126
|
-
height: index === part ? height : this.state.parts[index]?.height ?? height,
|
|
127
|
-
}))
|
|
128
|
-
const pages = this.state.documentType !== 'text' ? [] : this.state.layout === 'continuous'
|
|
129
|
-
? [{ x: 0, y: 0, width, height }]
|
|
130
|
-
: writerPages(this.text('dsh_lok_document_page_rectangles', [this.document])).map(page => ({ x: page.x / TWIPS_PER_CSS_PIXEL,
|
|
131
|
-
y: page.y / TWIPS_PER_CSS_PIXEL, width: page.width, height: page.height }))
|
|
132
|
-
const previous = this.state
|
|
133
|
-
const identitiesChanged = previous.parts.length > 0 && (previous.parts.length !== parts.length
|
|
134
|
-
|| parts.some((value, index) => value.name !== previous.parts[index]!.name))
|
|
135
|
-
const measured = previous.parts[part]
|
|
136
|
-
const geometryChanged = measured !== undefined && (measured.width !== width || measured.height !== height
|
|
137
|
-
|| JSON.stringify(previous.pages) !== JSON.stringify(pages))
|
|
138
|
-
this.state = { ...previous, part, parts, pages }
|
|
139
|
-
this.geometryDirty = false
|
|
140
|
-
return identitiesChanged ? -1 : geometryChanged ? part : undefined
|
|
141
|
-
} finally { this.call('free', [pointer]) }
|
|
142
|
-
}
|
|
143
|
-
private pump(): void {
|
|
144
|
-
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
145
|
-
const deadline = performance.now() + 8
|
|
146
|
-
for (let pass = 0; pass < 8; pass++) {
|
|
147
|
-
const result = this.call('dsh_lok_pump')
|
|
148
|
-
if (result < 0) throw new BrowserRenderError('render-failed', 'LibreOffice event processing failed.')
|
|
149
|
-
if (!result || performance.now() >= deadline) break
|
|
150
|
-
}
|
|
151
|
-
// Deferred native focus events can activate the capture view while pumping.
|
|
152
|
-
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
153
|
-
this.flush()
|
|
154
|
-
}
|
|
155
|
-
private flush(): void {
|
|
156
|
-
if (this.callbacks.length === 0) return
|
|
157
|
-
let changed = false
|
|
158
|
-
const invalidations: { part: number; rectangle: OfficeDocumentRectangle | null }[] = []
|
|
159
|
-
for (const { type, payload } of this.callbacks.splice(0)) {
|
|
160
|
-
switch (type) {
|
|
161
|
-
case 0: {
|
|
162
|
-
const fields = payload.split(',')
|
|
163
|
-
const index = fields[0]?.trim() === 'EMPTY' ? fields[1] : fields[4]
|
|
164
|
-
const part = index !== undefined && /^\s*-?\d+\s*$/.test(index) ? Number(index) : this.state.part
|
|
165
|
-
invalidations.push({ part, rectangle: rectangle(payload) })
|
|
166
|
-
break
|
|
167
|
-
}
|
|
168
|
-
case 1: case 17: this.state = { ...this.state, cursor: rectangle(payload) }; changed = true; break
|
|
169
|
-
case 2: this.state = { ...this.state, selection: payload.split(';').map(rectangle).filter((value): value is OfficeDocumentRectangle => value !== null) }; changed = true; break
|
|
170
|
-
case 6: this.state = { ...this.state, graphicSelection: rectangle(payload) }; changed = true; break
|
|
171
|
-
case 13: this.geometryDirty = true; break
|
|
172
|
-
case 14: {
|
|
173
|
-
const part = Number(payload)
|
|
174
|
-
if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
|
|
175
|
-
this.state = { ...this.state, part }; this.viewportKey = ''; this.viewportState = null; this.geometryDirty = true; changed = true
|
|
176
|
-
}
|
|
177
|
-
break
|
|
178
|
-
}
|
|
179
|
-
case 16: {
|
|
180
|
-
const result: unknown = JSON.parse(payload)
|
|
181
|
-
if (typeof result === 'object' && result !== null && 'commandName' in result && result.commandName === this.commandResult?.name) this.commandResult?.resolve()
|
|
182
|
-
break
|
|
183
|
-
}
|
|
184
|
-
case 19: this.state = { ...this.state, cellFormula: payload }; changed = true; break
|
|
185
|
-
case 34: this.state = { ...this.state, cellAddress: payload }; changed = true; break
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
const geometry = this.geometryDirty ? this.refreshGeometry() : undefined
|
|
189
|
-
if (geometry !== undefined) {
|
|
190
|
-
this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1 }
|
|
191
|
-
// A size notification need not be accompanied by LOK tile invalidation.
|
|
192
|
-
// Keep other sheets' pixels, but never reuse coordinates from an old layout.
|
|
193
|
-
if (!invalidations.some(value => value.rectangle === null && (value.part === -1 || value.part === geometry))) {
|
|
194
|
-
for (let index = invalidations.length - 1; index >= 0; index--) {
|
|
195
|
-
if (geometry === -1 || invalidations[index]!.part === geometry) invalidations.splice(index, 1)
|
|
196
|
-
}
|
|
197
|
-
invalidations.push({ part: geometry, rectangle: null })
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
if (invalidations.length > 0) {
|
|
201
|
-
this.state = { ...this.state, renderGeneration: this.state.renderGeneration + 1 }
|
|
202
|
-
changed = true
|
|
203
|
-
}
|
|
204
|
-
if (changed) this.emit({ type: 'state', state: this.state })
|
|
205
|
-
for (const invalidation of invalidations) this.emit({ type: 'invalidate', ...invalidation, generation: this.state.renderGeneration })
|
|
206
|
-
}
|
|
207
|
-
/** The Worker permits only these typed reading operations, including at runtime. */
|
|
208
|
-
async operation(operation: OfficeOperation): Promise<{ text?: string; layout?: OfficeDocumentLayoutResult }> {
|
|
209
|
-
this.requireOpen()
|
|
210
|
-
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
211
|
-
if (!operation || typeof operation !== 'object') throw new BrowserRenderError('render-failed', 'Invalid Office reading operation.')
|
|
212
|
-
switch (operation.type) {
|
|
213
|
-
case 'pointer': {
|
|
214
|
-
const event = operation.event
|
|
215
|
-
if (!event || !['down', 'up', 'move'].includes(event.action) || ![0, 1].includes(event.buttons)
|
|
216
|
-
|| ![0, 0x1000, 0x2000, 0x3000].includes(event.modifiers)) throw new BrowserRenderError('render-failed', 'Invalid Office selection pointer.')
|
|
217
|
-
this.invoke('mouse', [event.action === 'down' ? 0 : event.action === 'up' ? 1 : 2,
|
|
218
|
-
twips(event.x), twips(event.y), integer(event.clicks, 3), event.buttons, event.modifiers])
|
|
219
|
-
break
|
|
220
|
-
}
|
|
221
|
-
case 'navigate': {
|
|
222
|
-
const event = operation.event
|
|
223
|
-
if (!event || !Object.hasOwn(navigationKeys, event.key)
|
|
224
|
-
|| (event.extend !== undefined && typeof event.extend !== 'boolean') || (event.word !== undefined && typeof event.word !== 'boolean')) {
|
|
225
|
-
throw new BrowserRenderError('render-failed', 'Invalid Office navigation key.')
|
|
226
|
-
}
|
|
227
|
-
const key = navigationKeys[event.key] | (event.extend ? 0x1000 : 0) | (event.word ? 0x2000 : 0)
|
|
228
|
-
this.invoke('key', [0, 0, key]); this.invoke('key', [1, 0, key])
|
|
229
|
-
break
|
|
230
|
-
}
|
|
231
|
-
case 'select-all': await this.command('.uno:SelectAll', {}); break
|
|
232
|
-
case 'cell': {
|
|
233
|
-
if (this.state.documentType !== 'spreadsheet' || typeof operation.address !== 'string') throw new BrowserRenderError('render-failed', 'Cell navigation requires a spreadsheet address.')
|
|
234
|
-
try { parseCellRange(operation.address) } catch { throw new BrowserRenderError('render-failed', 'Cell navigation requires a bounded A1 cell or range.') }
|
|
235
|
-
await this.command('.uno:GoToCell', { ToPoint: { type: 'string', value: operation.address } })
|
|
236
|
-
break
|
|
237
|
-
}
|
|
238
|
-
case 'copy': this.pump(); return { text: this.text('dsh_lok_document_selection', [this.document]) }
|
|
239
|
-
case 'part': {
|
|
240
|
-
const part = integer(operation.part, this.state.parts.length - 1)
|
|
241
|
-
if (part === this.state.part) break
|
|
242
|
-
this.invoke('part', [part])
|
|
243
|
-
this.viewportKey = ''
|
|
244
|
-
this.viewportState = null
|
|
245
|
-
this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
|
|
246
|
-
const geometry = this.refreshGeometry()
|
|
247
|
-
if (geometry !== undefined) this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1,
|
|
248
|
-
renderGeneration: this.state.renderGeneration + 1 }
|
|
249
|
-
this.emit({ type: 'state', state: this.state })
|
|
250
|
-
if (geometry !== undefined) this.emit({ type: 'invalidate', part: geometry, rectangle: null, generation: this.state.renderGeneration })
|
|
251
|
-
break
|
|
252
|
-
}
|
|
253
|
-
case 'viewport': {
|
|
254
|
-
const { x, y, width, height } = operation.rectangle
|
|
255
|
-
if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
|
|
256
|
-
const args = [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)]
|
|
257
|
-
const key = args.join(',')
|
|
258
|
-
if (key !== this.viewportKey) {
|
|
259
|
-
this.invoke('viewport', args)
|
|
260
|
-
this.viewportKey = key
|
|
261
|
-
this.viewportState = { rectangle: { ...operation.rectangle }, scale: operation.scale }
|
|
262
|
-
}
|
|
263
|
-
break
|
|
264
|
-
}
|
|
265
|
-
case 'layout': {
|
|
266
|
-
const request = operation.request
|
|
267
|
-
if (!request || !['paginated', 'continuous'].includes(request.mode) || (request.mode === 'continuous' && this.state.documentType !== 'text')) {
|
|
268
|
-
throw new BrowserRenderError('render-failed', 'Continuous layout is only available for Writer documents.')
|
|
269
|
-
}
|
|
270
|
-
const width = request.mode === 'continuous' ? twips(request.width) : 0
|
|
271
|
-
if (request.mode === 'continuous' && width <= 0) throw new BrowserRenderError('render-failed', 'Continuous layout requires a positive width.')
|
|
272
|
-
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.')
|
|
273
|
-
if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } }
|
|
274
|
-
const result = this.configure(request)
|
|
275
|
-
this.layoutWidth = width
|
|
276
|
-
this.viewportKey = ''
|
|
277
|
-
this.viewportState = null
|
|
278
|
-
this.state = { ...this.state, layout: request.mode, layoutGeneration: this.state.layoutGeneration + 1,
|
|
279
|
-
renderGeneration: this.state.renderGeneration + 1 }
|
|
280
|
-
// Establish the requested layout before its acknowledgement pumps any
|
|
281
|
-
// matching size callback; that callback must not invalidate it twice.
|
|
282
|
-
this.refreshGeometry()
|
|
283
|
-
await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-layout' } })
|
|
284
|
-
this.refreshGeometry()
|
|
285
|
-
this.emit({ type: 'state', state: this.state })
|
|
286
|
-
this.emit({ type: 'invalidate', part: -1, rectangle: null, generation: this.state.renderGeneration })
|
|
287
|
-
return { layout: result }
|
|
288
|
-
}
|
|
289
|
-
default: throw new BrowserRenderError('render-failed', 'Unsupported Office reading operation.')
|
|
290
|
-
}
|
|
291
|
-
this.pump()
|
|
292
|
-
return {}
|
|
293
|
-
}
|
|
294
|
-
private configure(request: OfficeDocumentLayoutRequest): OfficeDocumentLayoutResult {
|
|
295
|
-
const raw = this.text('dsh_lok_document_configure_view', [this.document, 1, request.mode === 'continuous' ? 1 : 0,
|
|
296
|
-
request.mode === 'continuous' ? twips(request.width) : 0, request.anchor ? twips(request.anchor.x) : -1, request.anchor ? twips(request.anchor.y) : -1])
|
|
297
|
-
if (!raw) throw new BrowserRenderError('render-failed', 'LibreOffice could not configure its read-only view.')
|
|
298
|
-
const result = JSON.parse(raw) as { changed: boolean; width: number; height: number; anchor?: OfficeDocumentRectangle }
|
|
299
|
-
if (typeof result.changed !== 'boolean' || !(result.width > 0 && result.height > 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading layout.')
|
|
300
|
-
if (result.anchor === undefined) return { changed: result.changed }
|
|
301
|
-
const { x, y, width, height } = result.anchor
|
|
302
|
-
if (![x, y, width, height].every(value => Number.isFinite(value) && value >= 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading anchor.')
|
|
303
|
-
return { changed: result.changed, anchor: { x: x / TWIPS_PER_CSS_PIXEL, y: y / TWIPS_PER_CSS_PIXEL,
|
|
304
|
-
width: width / TWIPS_PER_CSS_PIXEL, height: height / TWIPS_PER_CSS_PIXEL } }
|
|
305
|
-
}
|
|
306
|
-
/** Internal whitelist commands only; no arbitrary command crosses the public API. */
|
|
307
|
-
private async command(name: '.uno:ReportWhenIdle' | '.uno:SelectAll' | '.uno:GoToCell', args: unknown): Promise<void> {
|
|
308
|
-
const result = Promise.withResolvers<void>()
|
|
309
|
-
this.commandResult = { name, resolve: () => result.resolve(), reject: result.reject }
|
|
310
|
-
try { this.invoke('command', [name, JSON.stringify(args)]); this.pump(); await result.promise }
|
|
311
|
-
finally { this.commandResult = undefined }
|
|
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
|
-
}
|
|
380
|
-
/** Direct tiles preserve the active view, navigation state and selection. */
|
|
381
|
-
render(request: OfficeDocumentTileRequest): BrowserTile {
|
|
382
|
-
this.requireOpen()
|
|
383
|
-
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
384
|
-
this.flush()
|
|
385
|
-
const part = this.state.parts[integer(request.part, this.state.parts.length - 1)]!
|
|
386
|
-
const capture = request.part !== this.state.part
|
|
387
|
-
if (capture && this.state.documentType !== 'presentation') throw new BrowserRenderError('stale-part', 'The Office tile belongs to an inactive worksheet.')
|
|
388
|
-
try {
|
|
389
|
-
if (capture) this.invoke('set_view', [this.captureView!])
|
|
390
|
-
return renderRegion(this.module, this.document, { ...request, pageIndex: 0 }, [{ ...part, x: 0, y: 0,
|
|
391
|
-
part: this.state.documentType === 'text' ? -1 : request.part }], () => new BrowserRenderError('render-failed', 'Office tile rendering failed.'))
|
|
392
|
-
} finally {
|
|
393
|
-
if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
|
|
394
|
-
this.flush()
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
}
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
/** Retained Office reading sessions; this API never exposes document mutation. */
|
|
2
|
-
import type { BrowserDocumentOptions, BrowserPage, BrowserRenderErrorCode, BrowserTile } from './types.ts'
|
|
3
|
-
|
|
4
|
-
/** Office containers supported by the reading engine. */
|
|
5
|
-
export type OfficeDocumentFormat = 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx'
|
|
6
|
-
/** Source bytes, engine resources and Host fonts; all sessions are read-only. */
|
|
7
|
-
export type OfficeDocumentOptions = Omit<BrowserDocumentOptions, 'extension'> & { readonly extension: OfficeDocumentFormat }
|
|
8
|
-
/** Document coordinates in CSS pixels at 96 DPI, independent of zoom. */
|
|
9
|
-
export interface OfficeDocumentRectangle extends BrowserPage { readonly x: number; readonly y: number }
|
|
10
|
-
/** One Writer document, Calc worksheet or Impress slide. */
|
|
11
|
-
export interface OfficeDocumentPart extends BrowserPage { readonly name: string }
|
|
12
|
-
/** Writer layout; other document types always remain paginated. */
|
|
13
|
-
export type OfficeDocumentLayout = 'paginated' | 'continuous'
|
|
14
|
-
/** A point in the previous layout, normally the upper visible line of body text. */
|
|
15
|
-
export interface OfficeDocumentAnchor { readonly x: number; readonly y: number }
|
|
16
|
-
/** Continuous width is the available content width in document CSS pixels. */
|
|
17
|
-
export type OfficeDocumentLayoutRequest =
|
|
18
|
-
| { readonly mode: 'paginated'; readonly anchor?: OfficeDocumentAnchor }
|
|
19
|
-
| { readonly mode: 'continuous'; readonly width: number; readonly anchor?: OfficeDocumentAnchor }
|
|
20
|
-
/** An optional body-text rectangle in the new layout for restoring reading position. */
|
|
21
|
-
export interface OfficeDocumentLayoutResult { readonly changed: boolean; readonly anchor?: OfficeDocumentRectangle }
|
|
22
|
-
/** Geometry and selection; cursor is a navigation/cell rectangle, never an editing caret. */
|
|
23
|
-
export interface OfficeDocumentState {
|
|
24
|
-
readonly documentType: 'text' | 'spreadsheet' | 'presentation'
|
|
25
|
-
readonly renderGeneration: number
|
|
26
|
-
readonly layoutGeneration: number
|
|
27
|
-
readonly layout: OfficeDocumentLayout
|
|
28
|
-
readonly part: number
|
|
29
|
-
readonly parts: readonly OfficeDocumentPart[]
|
|
30
|
-
/** Writer page rectangles in paginated mode; one continuous rectangle otherwise. */
|
|
31
|
-
readonly pages: readonly OfficeDocumentRectangle[]
|
|
32
|
-
readonly cursor: OfficeDocumentRectangle | null
|
|
33
|
-
readonly selection: readonly OfficeDocumentRectangle[]
|
|
34
|
-
readonly graphicSelection: OfficeDocumentRectangle | null
|
|
35
|
-
readonly cellAddress: string
|
|
36
|
-
readonly cellFormula: string
|
|
37
|
-
}
|
|
38
|
-
/** Primary-button selection; modifiers use LOK Shift (0x1000) / Control (0x2000). */
|
|
39
|
-
export interface OfficeDocumentPointer {
|
|
40
|
-
readonly action: 'down' | 'up' | 'move'
|
|
41
|
-
readonly x: number
|
|
42
|
-
readonly y: number
|
|
43
|
-
readonly buttons: number
|
|
44
|
-
readonly modifiers: number
|
|
45
|
-
readonly clicks: number
|
|
46
|
-
}
|
|
47
|
-
/** Only navigation keys are accepted; no arbitrary character or key injection. */
|
|
48
|
-
export interface OfficeDocumentNavigation {
|
|
49
|
-
readonly key: 'left' | 'right' | 'up' | 'down' | 'home' | 'end' | 'pageUp' | 'pageDown'
|
|
50
|
-
readonly extend?: boolean
|
|
51
|
-
readonly word?: boolean
|
|
52
|
-
}
|
|
53
|
-
/** One region of the current part. Pixel density does not change document layout. */
|
|
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
|
-
}
|
|
94
|
-
/** A null rectangle invalidates an entire part; negative part means every part. */
|
|
95
|
-
export type OfficeDocumentEvent =
|
|
96
|
-
| { readonly type: 'state'; readonly state: OfficeDocumentState }
|
|
97
|
-
| { readonly type: 'invalidate'; readonly part: number; readonly rectangle: OfficeDocumentRectangle | null; readonly generation: number }
|
|
98
|
-
| { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
|
|
99
|
-
/** One open document of a runtime; closing it frees the parsed model without destroying the engine. */
|
|
100
|
-
export interface OfficeDocument {
|
|
101
|
-
readonly state: OfficeDocumentState
|
|
102
|
-
subscribe(listener: (event: OfficeDocumentEvent) => void): () => void
|
|
103
|
-
pointer(event: OfficeDocumentPointer): Promise<void>
|
|
104
|
-
navigate(event: OfficeDocumentNavigation): Promise<void>
|
|
105
|
-
selectAll(): Promise<void>
|
|
106
|
-
copy(): Promise<string>
|
|
107
|
-
/** Select a bounded A1 cell or range on the current worksheet. */
|
|
108
|
-
goToCell(address: string): Promise<void>
|
|
109
|
-
setPart(part: number): Promise<void>
|
|
110
|
-
setViewport(rectangle: OfficeDocumentRectangle, scale: number): Promise<void>
|
|
111
|
-
/** Coalesces pending widths; superseded callers observe the newest applied layout. */
|
|
112
|
-
setLayout(request: OfficeDocumentLayoutRequest): Promise<OfficeDocumentLayoutResult>
|
|
113
|
-
/** Only the current part can be painted; queued requests for a former part reject with stale-part without changing selection. */
|
|
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. */
|
|
127
|
-
dispose(): Promise<void>
|
|
128
|
-
}
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
/** Browser owner for one shared engine Worker and its read-only Office documents. */
|
|
2
|
-
import { openBrowserWorker } from './connection.ts'
|
|
3
|
-
import { BrowserRenderError } from './types.ts'
|
|
4
|
-
import type { BrowserRuntimeOptions } from './types.ts'
|
|
5
|
-
import type { OfficeDocument, OfficeDocumentEvent, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult,
|
|
6
|
-
OfficeDocumentOpenOptions, OfficeDocumentState, OfficeReadingState, OfficeRuntime } from './office-types.ts'
|
|
7
|
-
import type { OfficeOperation } from './protocol.ts'
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Start one read-only Office engine that opens documents one at a time.
|
|
11
|
-
* @param options - Engine resources and limits shared by every document.
|
|
12
|
-
* @param signal - Runtime lifetime; abort closes the Worker and its pthreads.
|
|
13
|
-
* @returns Sequential document loading and joined disposal.
|
|
14
|
-
*/
|
|
15
|
-
export async function openOfficeRuntime(options: BrowserRuntimeOptions, signal?: AbortSignal): Promise<OfficeRuntime> {
|
|
16
|
-
let current: { closed: boolean; readonly listeners: Set<(event: OfficeDocumentEvent) => void>;
|
|
17
|
-
update(state: OfficeDocumentState): void } | undefined
|
|
18
|
-
let disposed = false
|
|
19
|
-
const worker = await openBrowserWorker(options, signal, (event) => {
|
|
20
|
-
if (event.type === 'state') current?.update(event.state)
|
|
21
|
-
for (const listener of current?.listeners ?? []) {
|
|
22
|
-
try { listener(event) } catch (error) { console.error('Office document observer failed', error) }
|
|
23
|
-
}
|
|
24
|
-
})
|
|
25
|
-
const open = async (openOptions: OfficeDocumentOpenOptions, documentSignal?: AbortSignal): Promise<OfficeDocument> => {
|
|
26
|
-
if (disposed) throw new BrowserRenderError('disposed', 'The Office runtime is closed.')
|
|
27
|
-
if (current && !current.closed) current.closed = true
|
|
28
|
-
current?.listeners.clear()
|
|
29
|
-
current = undefined
|
|
30
|
-
await worker.closeDocument()
|
|
31
|
-
const opened = await worker.openDocument({ data: openOptions.data, extension: openOptions.extension,
|
|
32
|
-
resolveFonts: openOptions.resolveFonts,
|
|
33
|
-
...(openOptions.onMissingFonts === undefined ? {} : { onMissingFonts: openOptions.onMissingFonts }),
|
|
34
|
-
...(openOptions.restore === undefined ? {} : { restore: openOptions.restore }) }, documentSignal)
|
|
35
|
-
if (!opened.office) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no reading state.')
|
|
36
|
-
let reading = opened.office
|
|
37
|
-
const record = { closed: false, listeners: new Set<(event: OfficeDocumentEvent) => void>(),
|
|
38
|
-
update(state: OfficeDocumentState): void { reading = state } }
|
|
39
|
-
current = record
|
|
40
|
-
async function operate(operation: OfficeOperation) {
|
|
41
|
-
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
42
|
-
const response = await worker.request({ type: 'office-operation', operation })
|
|
43
|
-
if (response.type !== 'office-result') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading response.')
|
|
44
|
-
return response
|
|
45
|
-
}
|
|
46
|
-
let layoutRunning = false
|
|
47
|
-
let pendingLayout: { request: OfficeDocumentLayoutRequest; waiters: ReturnType<typeof Promise.withResolvers<OfficeDocumentLayoutResult>>[] } | undefined
|
|
48
|
-
async function applyLayouts(): Promise<void> {
|
|
49
|
-
layoutRunning = true
|
|
50
|
-
while (pendingLayout) {
|
|
51
|
-
const next = pendingLayout
|
|
52
|
-
pendingLayout = undefined
|
|
53
|
-
try {
|
|
54
|
-
const response = await operate({ type: 'layout', request: next.request })
|
|
55
|
-
if (!response.layout) throw new BrowserRenderError('render-failed', 'LibreOffice returned no layout result.')
|
|
56
|
-
for (const waiter of next.waiters) waiter.resolve(response.layout)
|
|
57
|
-
} catch (error) { for (const waiter of next.waiters) waiter.reject(error) }
|
|
58
|
-
}
|
|
59
|
-
layoutRunning = false
|
|
60
|
-
}
|
|
61
|
-
const close = async (): Promise<void> => {
|
|
62
|
-
if (record.closed) return
|
|
63
|
-
record.closed = true
|
|
64
|
-
record.listeners.clear()
|
|
65
|
-
current = undefined
|
|
66
|
-
await worker.closeDocument()
|
|
67
|
-
}
|
|
68
|
-
let disposal: Promise<void> | undefined
|
|
69
|
-
return {
|
|
70
|
-
get state() { return reading },
|
|
71
|
-
subscribe(listener) { if (record.closed) return () => {}; record.listeners.add(listener); return () => { record.listeners.delete(listener) } },
|
|
72
|
-
async pointer(event) { await operate({ type: 'pointer', event }) },
|
|
73
|
-
async navigate(event) { await operate({ type: 'navigate', event }) },
|
|
74
|
-
async selectAll() { await operate({ type: 'select-all' }) },
|
|
75
|
-
async copy() { return (await operate({ type: 'copy' })).text ?? '' },
|
|
76
|
-
async goToCell(address) { await operate({ type: 'cell', address }) },
|
|
77
|
-
async setPart(part) { await operate({ type: 'part', part }) },
|
|
78
|
-
async setViewport(rectangle, scale) { await operate({ type: 'viewport', rectangle, scale }) },
|
|
79
|
-
setLayout(request) {
|
|
80
|
-
const waiter = Promise.withResolvers<OfficeDocumentLayoutResult>()
|
|
81
|
-
pendingLayout = { request, waiters: [...(pendingLayout?.waiters ?? []), waiter] }
|
|
82
|
-
if (!layoutRunning) void applyLayouts()
|
|
83
|
-
return waiter.promise
|
|
84
|
-
},
|
|
85
|
-
async renderTile(request, tileSignal) {
|
|
86
|
-
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
87
|
-
const response = await worker.request({ type: 'office-tile', request }, tileSignal)
|
|
88
|
-
if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
|
|
89
|
-
return response.tile
|
|
90
|
-
},
|
|
91
|
-
async captureReadingState(): Promise<OfficeReadingState> {
|
|
92
|
-
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
93
|
-
const response = await worker.request({ type: 'reading-state' })
|
|
94
|
-
if (response.type !== 'reading-state') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading state.')
|
|
95
|
-
return response.state
|
|
96
|
-
},
|
|
97
|
-
close,
|
|
98
|
-
dispose() { return disposal ??= close().then(disposeRuntime) },
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
const disposeRuntime = async (): Promise<void> => {
|
|
102
|
-
if (disposed) return
|
|
103
|
-
disposed = true
|
|
104
|
-
current?.listeners.clear()
|
|
105
|
-
if (current && !current.closed) current.closed = true
|
|
106
|
-
await worker.dispose()
|
|
107
|
-
}
|
|
108
|
-
return { open, dispose: disposeRuntime }
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Open one read-only Office document in its own engine; the runtime ends with the document.
|
|
113
|
-
* @param options - Source bytes, engine resources and Host fonts.
|
|
114
|
-
* @param signal - Document lifetime; abort closes its Worker and pthreads.
|
|
115
|
-
* @returns Immutable reading state and disposal.
|
|
116
|
-
*/
|
|
117
|
-
export async function openOfficeDocument(options: BrowserRuntimeOptions & { readonly data: Uint8Array }
|
|
118
|
-
& Pick<OfficeDocumentOpenOptions, 'extension' | 'resolveFonts' | 'onMissingFonts'>, signal?: AbortSignal): Promise<OfficeDocument> {
|
|
119
|
-
const { data, extension, resolveFonts, onMissingFonts, ...runtime } = options
|
|
120
|
-
const office = await openOfficeRuntime(runtime, signal)
|
|
121
|
-
try {
|
|
122
|
-
return await office.open({ data, extension, resolveFonts,
|
|
123
|
-
...(onMissingFonts === undefined ? {} : { onMissingFonts }) }, signal)
|
|
124
|
-
} catch (error) {
|
|
125
|
-
await office.dispose()
|
|
126
|
-
throw error
|
|
127
|
-
}
|
|
128
|
-
}
|