@deepseek-ai/libreoffice-kit 0.0.2-rc4 → 0.0.2-rc5
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 +238 -0
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/lib/browser/assets.json +2 -2
- package/lib/browser/index.js +65 -58
- package/lib/browser/types/connection.d.ts +3 -3
- package/lib/browser/types/index.d.ts +2 -2
- package/lib/browser/types/office-engine.d.ts +46 -0
- package/lib/browser/types/office-types.d.ts +107 -0
- package/lib/browser/types/office.d.ts +4 -0
- package/lib/browser/types/protocol.d.ts +24 -32
- package/lib/browser/types/types.d.ts +3 -1
- package/lib/browser/worker.js +276 -489
- package/lib/browser-assets.js +1 -1
- package/lib/cli.js +91 -58
- package/lib/font-source.js +89 -56
- package/lib/font-worker.js +710 -39
- package/lib/index.js +91 -58
- package/lib/types/default-fonts.d.ts +3 -0
- package/lib/types/engine.d.ts +1 -1
- package/lib/types/font-preferences-data.d.ts +16 -0
- package/lib/types/font-preferences.d.ts +29 -0
- package/lib/types/font-source-types.d.ts +2 -0
- package/lib/types/fonts.d.ts +11 -8
- package/lib/types/options.d.ts +1 -1
- package/lib/worker.js +707 -37
- package/package.json +3 -3
- package/sources/browser/packages/browser/package.json +2 -2
- package/sources/browser/packages/browser/src/connection.ts +7 -9
- package/sources/browser/packages/browser/src/index.ts +3 -3
- package/sources/browser/packages/browser/src/office-engine.ts +299 -0
- package/sources/browser/packages/browser/src/office-types.ts +77 -0
- package/sources/browser/packages/browser/src/office.ts +62 -0
- package/sources/browser/packages/browser/src/protocol.ts +15 -16
- package/sources/browser/packages/browser/src/types.ts +3 -1
- package/sources/browser/packages/browser/src/worker.ts +25 -30
- package/sources/browser/scripts/build-browser.mjs +9 -1
- package/lib/browser/types/editor-engine.d.ts +0 -50
- package/lib/browser/types/editor-types.d.ts +0 -141
- package/lib/browser/types/editor.d.ts +0 -9
- package/sources/browser/packages/browser/src/editor-engine.ts +0 -382
- package/sources/browser/packages/browser/src/editor-types.ts +0 -106
- package/sources/browser/packages/browser/src/editor.ts +0 -55
|
@@ -1,382 +0,0 @@
|
|
|
1
|
-
/** Worker-owned editing, VCL event slices and immutable editing 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 { EditorOperation } from './protocol.ts'
|
|
6
|
-
import type { BrowserEditorCapture, BrowserEditorCaptureRegion, BrowserEditorCaptureRequest, BrowserEditorEvent, BrowserEditorFormat, BrowserEditorSnapshot, BrowserEditorState, BrowserEditorTileRequest, BrowserRectangle } from './editor-types.ts'
|
|
7
|
-
import { dataArea, parseCellRange, rangeName, sheetPartInfo, sheetRangeRectangle, type SheetGeometry } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
|
|
8
|
-
import { renderRegion } from './engine-rendering.ts'
|
|
9
|
-
import { tileDimensions, TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
|
|
10
|
-
|
|
11
|
-
function rectangle(payload: string): BrowserRectangle | 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
|
-
/** One editor, driven exclusively by its owning Worker's messages and timer. */
|
|
35
|
-
export class EditorEngine {
|
|
36
|
-
state: BrowserEditorState
|
|
37
|
-
private timer: ReturnType<typeof setTimeout> | undefined
|
|
38
|
-
private readonly callbacks: { type: number; payload: string; phase: string }[] = []
|
|
39
|
-
private phase = 'view'
|
|
40
|
-
private modified = false
|
|
41
|
-
private geometryDirty = false
|
|
42
|
-
private stopped = false
|
|
43
|
-
private renderView = -1
|
|
44
|
-
private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
|
|
45
|
-
|
|
46
|
-
constructor(private readonly module: EmscriptenModule, private readonly document: number,
|
|
47
|
-
private readonly format: BrowserEditorFormat, private readonly maxBytes: number,
|
|
48
|
-
private readonly emit: (event: BrowserEditorEvent) => void, private readonly failure: (error: unknown) => void,
|
|
49
|
-
private readonly readOnly = false) {
|
|
50
|
-
this.state = { documentType: format === 'docx' || format === 'doc' ? 'text' : format === 'xlsx' || format === 'xls' ? 'spreadsheet' : 'presentation', revision: 0, renderGeneration: 0,
|
|
51
|
-
part: 0, parts: [], pages: [], cursor: null, cursorVisible: false, selection: [], graphicSelection: null,
|
|
52
|
-
cellAddress: '', cellFormula: '', commands: {} }
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
private call(name: string, args: (number | string)[] = []): number {
|
|
56
|
-
return this.module.ccall(name, 'number', args.map(value => typeof value), args)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
private text(name: string, args: (number | string)[]): string {
|
|
60
|
-
const pointer = this.call(name, args)
|
|
61
|
-
if (!pointer) return ''
|
|
62
|
-
try { return this.module.UTF8ToString(pointer) } finally { this.call('free', [pointer]) }
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
private invoke(name: string, args: (number | string)[] = []): void {
|
|
66
|
-
if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError('render-failed', `LibreOffice could not complete ${name}.`)
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
private requireOpen(): void {
|
|
70
|
-
if (this.stopped) throw new BrowserRenderError('disposed', 'Office editor is closed.')
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Collect callbacks without reentering LibreOffice from inside its own callback. */
|
|
74
|
-
callback(type: number, payload: string): void { if (!this.stopped) this.callbacks.push({ type, payload, phase: this.phase }) }
|
|
75
|
-
|
|
76
|
-
/** Register callbacks after document initialization, then begin bounded event slices. */
|
|
77
|
-
async start(): Promise<void> {
|
|
78
|
-
this.requireOpen()
|
|
79
|
-
this.invoke('listen')
|
|
80
|
-
this.refreshGeometry()
|
|
81
|
-
this.pump()
|
|
82
|
-
this.schedule()
|
|
83
|
-
await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'editor-open' } })
|
|
84
|
-
this.state = { ...this.state, revision: 0 }
|
|
85
|
-
this.phase = 'idle'
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
private schedule(): void {
|
|
89
|
-
this.timer = setTimeout(() => {
|
|
90
|
-
if (this.stopped) return
|
|
91
|
-
try { this.pump(); this.schedule() } catch (error) { this.stop(); this.failure(error) }
|
|
92
|
-
}, 16)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Cancel the owned timer before the document or office is destroyed. */
|
|
96
|
-
stop(): void {
|
|
97
|
-
this.stopped = true
|
|
98
|
-
clearTimeout(this.timer)
|
|
99
|
-
this.callbacks.length = 0
|
|
100
|
-
this.commandResult?.reject(new BrowserRenderError('disposed', 'Office editor is closed.'))
|
|
101
|
-
this.commandResult = undefined
|
|
102
|
-
if (this.renderView >= 0) {
|
|
103
|
-
this.call('dsh_lok_document_destroy_view', [this.document, this.renderView])
|
|
104
|
-
this.renderView = -1
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
private refreshGeometry(): void {
|
|
109
|
-
const phase = this.phase
|
|
110
|
-
this.phase = 'view'
|
|
111
|
-
const count = this.state.documentType === 'text' ? 1 : this.call('dsh_lok_document_parts', [this.document])
|
|
112
|
-
if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError('invalid-document', 'Office document has no editable parts.')
|
|
113
|
-
const pointer = this.call('malloc', [8])
|
|
114
|
-
if (!pointer) throw new BrowserRenderError('render-failed', 'Office geometry allocation failed.')
|
|
115
|
-
try {
|
|
116
|
-
const part = Math.min(this.state.part, count - 1)
|
|
117
|
-
this.invoke('size', [part, pointer, pointer + 4])
|
|
118
|
-
const width = this.module.HEAPU32[pointer / 4]! / TWIPS_PER_CSS_PIXEL
|
|
119
|
-
const height = this.module.HEAPU32[pointer / 4 + 1]! / TWIPS_PER_CSS_PIXEL
|
|
120
|
-
if (!(width > 0 && height > 0)) throw new BrowserRenderError('invalid-document', 'Office returned empty document dimensions.')
|
|
121
|
-
// Switching worksheets to measure them can commit an in-progress cell or IME edit.
|
|
122
|
-
// Inactive parts retain their last observed dimensions until selected.
|
|
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'
|
|
129
|
-
? writerPages(this.text('dsh_lok_document_page_rectangles', [this.document])).map(page => ({ x: page.x / TWIPS_PER_CSS_PIXEL,
|
|
130
|
-
y: page.y / TWIPS_PER_CSS_PIXEL, width: page.width, height: page.height })) : []
|
|
131
|
-
this.state = { ...this.state, part, parts, pages }
|
|
132
|
-
} finally { this.call('free', [pointer]); this.phase = phase }
|
|
133
|
-
this.geometryDirty = false
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
private pump(): void {
|
|
137
|
-
const deadline = performance.now() + 8
|
|
138
|
-
// A newly created capture window can activate itself through deferred VCL
|
|
139
|
-
// events. Preserve the caller's view so subsequent commands retain their
|
|
140
|
-
// callback channel and never target the read-only capture window.
|
|
141
|
-
const view = this.renderView >= 0 ? this.call('dsh_lok_document_get_view', [this.document]) : -1
|
|
142
|
-
try {
|
|
143
|
-
for (let pass = 0; pass < 8; pass++) {
|
|
144
|
-
const result = this.call('dsh_lok_pump')
|
|
145
|
-
if (result < 0) throw new BrowserRenderError('render-failed', 'LibreOffice event processing failed.')
|
|
146
|
-
if (!result || performance.now() >= deadline) break
|
|
147
|
-
}
|
|
148
|
-
} finally {
|
|
149
|
-
if (view >= 0 && !this.call('dsh_lok_document_set_view', [this.document, view])) {
|
|
150
|
-
throw new BrowserRenderError('render-failed', 'The editor view could not be restored after event processing.')
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
this.flush()
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
private flush(): void {
|
|
157
|
-
if (this.callbacks.length === 0) return
|
|
158
|
-
let changed = false
|
|
159
|
-
let edited = false
|
|
160
|
-
const invalidations: { part: number; rectangle: BrowserRectangle | null }[] = []
|
|
161
|
-
for (const { type, payload, phase } of this.callbacks.splice(0)) {
|
|
162
|
-
switch (type) {
|
|
163
|
-
case 0: {
|
|
164
|
-
const fields = payload.split(',')
|
|
165
|
-
const index = fields[0]?.trim() === 'EMPTY' ? fields[1] : fields[4]
|
|
166
|
-
const part = index !== undefined && /^\s*-?\d+\s*$/.test(index) ? Number(index) : this.state.part
|
|
167
|
-
invalidations.push({ part, rectangle: rectangle(payload) })
|
|
168
|
-
edited ||= !['paint', 'view', 'save', 'capture'].includes(phase)
|
|
169
|
-
break
|
|
170
|
-
}
|
|
171
|
-
case 1: this.state = { ...this.state, cursor: rectangle(payload) }; changed = true; break
|
|
172
|
-
case 2: this.state = { ...this.state, selection: payload.split(';').map(rectangle).filter((value): value is BrowserRectangle => value !== null) }; changed = true; break
|
|
173
|
-
case 5: this.state = { ...this.state, cursorVisible: payload === 'true' }; changed = true; break
|
|
174
|
-
case 6: this.state = { ...this.state, graphicSelection: rectangle(payload) }; changed = true; break
|
|
175
|
-
case 8: {
|
|
176
|
-
const separator = payload.indexOf('=')
|
|
177
|
-
if (separator < 0) break
|
|
178
|
-
const command = payload.slice(0, separator), value = payload.slice(separator + 1)
|
|
179
|
-
if (command === '.uno:ModifiedStatus') { this.modified = value === 'true'; edited ||= this.modified }
|
|
180
|
-
this.state = { ...this.state, commands: { ...this.state.commands, [command]: value } }
|
|
181
|
-
changed = true
|
|
182
|
-
break
|
|
183
|
-
}
|
|
184
|
-
case 13: this.geometryDirty = true; changed = true; break
|
|
185
|
-
case 14: {
|
|
186
|
-
const part = Number(payload)
|
|
187
|
-
if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) this.state = { ...this.state, part }
|
|
188
|
-
changed = true
|
|
189
|
-
break
|
|
190
|
-
}
|
|
191
|
-
case 16: {
|
|
192
|
-
const result: unknown = JSON.parse(payload)
|
|
193
|
-
if (typeof result !== 'object' || result === null || !('commandName' in result)
|
|
194
|
-
|| result.commandName !== this.commandResult?.name) break
|
|
195
|
-
// Writer's Undo executes without setting SfxRequest::Done or a return value,
|
|
196
|
-
// so its dispatch notification reports success=false even after the edit.
|
|
197
|
-
// This notification acknowledges completion; state callbacks report effects.
|
|
198
|
-
this.commandResult!.resolve()
|
|
199
|
-
break
|
|
200
|
-
}
|
|
201
|
-
case 17: this.state = { ...this.state, cursor: rectangle(payload), cursorVisible: true }; changed = true; break
|
|
202
|
-
case 19: this.state = { ...this.state, cellFormula: payload }; changed = true; break
|
|
203
|
-
case 34: this.state = { ...this.state, cellAddress: payload }; changed = true; break
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
if (edited && this.modified) { this.state = { ...this.state, revision: this.state.revision + 1 }; changed = true }
|
|
207
|
-
if (invalidations.length > 0 || this.geometryDirty) {
|
|
208
|
-
this.state = { ...this.state, renderGeneration: this.state.renderGeneration + 1 }
|
|
209
|
-
changed = true
|
|
210
|
-
}
|
|
211
|
-
if (this.geometryDirty) this.refreshGeometry()
|
|
212
|
-
if (changed) this.emit({ type: 'state', state: this.state })
|
|
213
|
-
for (const invalidation of invalidations) this.emit({ type: 'invalidate', ...invalidation, revision: this.state.revision })
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** Apply one ordered command and collect the resulting notifications before acknowledgement. */
|
|
217
|
-
async operation(operation: EditorOperation): Promise<{ text?: string; snapshot?: BrowserEditorSnapshot }> {
|
|
218
|
-
this.requireOpen()
|
|
219
|
-
if (this.readOnly && ['input', 'command', 'paste', 'save'].includes(operation.type)) throw new BrowserRenderError('render-failed', 'This Office document is read-only.')
|
|
220
|
-
this.phase = operation.type === 'part' || operation.type === 'viewport' ? 'view' : operation.type === 'save' ? 'save' : 'edit'
|
|
221
|
-
try {
|
|
222
|
-
switch (operation.type) {
|
|
223
|
-
case 'input': {
|
|
224
|
-
const event = operation.event
|
|
225
|
-
if (event.type === 'key') this.invoke('key', [event.action === 'down' ? 0 : 1, integer(event.character, 0x10ffff), integer(event.key, 0xffff)])
|
|
226
|
-
else if (event.type === 'pointer') this.invoke('mouse', [event.action === 'down' ? 0 : event.action === 'up' ? 1 : 2,
|
|
227
|
-
twips(event.x), twips(event.y), integer(event.clicks, 3), integer(event.buttons, 7), integer(event.modifiers, 0xffff)])
|
|
228
|
-
else { this.checkText(event.text); this.invoke('composition', [event.action === 'update' ? 0 : 2, event.text]) }
|
|
229
|
-
break
|
|
230
|
-
}
|
|
231
|
-
case 'command':
|
|
232
|
-
if (!/^\.uno:[A-Za-z][A-Za-z0-9]*$/.test(operation.command)) throw new BrowserRenderError('render-failed', 'Office command must name a UNO command.')
|
|
233
|
-
await this.command(operation.command, operation.arguments ?? {})
|
|
234
|
-
break
|
|
235
|
-
case 'paste': {
|
|
236
|
-
this.checkText(operation.text)
|
|
237
|
-
this.invoke('paste', ['text/plain;charset=utf-8', operation.text, new TextEncoder().encode(operation.text).byteLength])
|
|
238
|
-
break
|
|
239
|
-
}
|
|
240
|
-
case 'copy': return { text: this.text('dsh_lok_document_selection', [this.document]) }
|
|
241
|
-
case 'part': {
|
|
242
|
-
const part = integer(operation.part, this.state.parts.length - 1)
|
|
243
|
-
this.invoke('part', [part])
|
|
244
|
-
this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null }
|
|
245
|
-
this.refreshGeometry()
|
|
246
|
-
this.emit({ type: 'state', state: this.state })
|
|
247
|
-
break
|
|
248
|
-
}
|
|
249
|
-
case 'viewport': {
|
|
250
|
-
const { x, y, width, height } = operation.rectangle
|
|
251
|
-
if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
|
|
252
|
-
this.invoke('viewport', [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)])
|
|
253
|
-
break
|
|
254
|
-
}
|
|
255
|
-
case 'save': {
|
|
256
|
-
this.pump()
|
|
257
|
-
const path = `/dsh/export.${this.format}`
|
|
258
|
-
this.invoke('save', [`file://${path}`, this.format])
|
|
259
|
-
const data = this.module.FS.readFile(path)
|
|
260
|
-
this.module.FS.unlink(path)
|
|
261
|
-
if (data.length === 0 || data.length > this.maxBytes) throw new BrowserRenderError('render-failed', 'Office export exceeds the configured byte limit.')
|
|
262
|
-
this.pump()
|
|
263
|
-
return { snapshot: { data, revision: this.state.revision, extension: this.format } }
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
this.pump()
|
|
267
|
-
return {}
|
|
268
|
-
} finally { this.phase = 'idle' }
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private checkText(text: string): void {
|
|
272
|
-
if (typeof text !== 'string' || text.includes('\0') || new TextEncoder().encode(text).length > this.maxBytes) throw new BrowserRenderError('render-failed', 'Office input exceeds the text limit or contains NUL.')
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
private async command(name: string, args: unknown): Promise<void> {
|
|
276
|
-
const result = Promise.withResolvers<void>()
|
|
277
|
-
this.commandResult = { name, resolve: () => result.resolve(), reject: result.reject }
|
|
278
|
-
try {
|
|
279
|
-
this.invoke('command', [name, JSON.stringify(args)])
|
|
280
|
-
this.pump()
|
|
281
|
-
await result.promise
|
|
282
|
-
} finally { this.commandResult = undefined }
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/** Painting preserves the active selection and cannot itself mark the document edited. */
|
|
286
|
-
render(request: BrowserEditorTileRequest): BrowserTile {
|
|
287
|
-
this.requireOpen()
|
|
288
|
-
const part = this.state.parts[integer(request.part, this.state.parts.length - 1)]!
|
|
289
|
-
this.phase = 'paint'
|
|
290
|
-
try {
|
|
291
|
-
return renderRegion(this.module, this.document, { ...request, pageIndex: 0 }, [{ ...part, x: 0, y: 0,
|
|
292
|
-
part: this.state.documentType === 'text' ? -1 : request.part }], () => new BrowserRenderError('render-failed', 'Office tile rendering failed.'))
|
|
293
|
-
} finally { this.flush(); this.phase = 'idle' }
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
/** Capture one bounded batch with no input interleaving; cached tiles are checked at the same generation. */
|
|
297
|
-
async capture(request: BrowserEditorCaptureRequest): Promise<BrowserEditorCapture> {
|
|
298
|
-
this.requireOpen()
|
|
299
|
-
integer(request.maxPixels)
|
|
300
|
-
if (!request.maxPixels || request.maxPixels > 67_108_864 || request.tiles.length > 4096) {
|
|
301
|
-
throw new BrowserRenderError('render-failed', 'Office capture exceeds its allocation limit.')
|
|
302
|
-
}
|
|
303
|
-
await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'capture' } })
|
|
304
|
-
this.pump()
|
|
305
|
-
const generation = this.state.renderGeneration
|
|
306
|
-
if (request.generation !== undefined && request.generation !== generation) throw new BrowserRenderError('snapshot-changed', 'The document changed before capture.')
|
|
307
|
-
const original = this.call('dsh_lok_document_get_view', [this.document])
|
|
308
|
-
if (original < 0) throw new BrowserRenderError('render-failed', 'The editor view is unavailable.')
|
|
309
|
-
this.phase = 'capture'
|
|
310
|
-
let parts = this.state.parts
|
|
311
|
-
const tiles: BrowserTile[] = []
|
|
312
|
-
const regions: BrowserEditorCaptureRegion[] = []
|
|
313
|
-
try {
|
|
314
|
-
if (this.renderView < 0) this.renderView = this.call('dsh_lok_document_create_view', [this.document])
|
|
315
|
-
if (this.renderView < 0 || !this.call('dsh_lok_document_set_view', [this.document, this.renderView])) throw new BrowserRenderError('render-failed', 'The capture view is unavailable.')
|
|
316
|
-
const pointer = this.call('malloc', [8])
|
|
317
|
-
if (!pointer) throw new BrowserRenderError('render-failed', 'Office capture geometry allocation failed.')
|
|
318
|
-
try {
|
|
319
|
-
parts = this.state.parts.map((part, index) => {
|
|
320
|
-
this.invoke('size', [index, pointer, pointer + 4])
|
|
321
|
-
const width = this.module.HEAPU32[pointer / 4]! / TWIPS_PER_CSS_PIXEL
|
|
322
|
-
const height = this.module.HEAPU32[pointer / 4 + 1]! / TWIPS_PER_CSS_PIXEL
|
|
323
|
-
if (!(width > 0 && height > 0)) throw new BrowserRenderError('invalid-document', 'Office returned empty capture dimensions.')
|
|
324
|
-
return { ...part, width, height }
|
|
325
|
-
})
|
|
326
|
-
} finally { this.call('free', [pointer]) }
|
|
327
|
-
if (request.selection !== undefined && this.state.documentType === 'spreadsheet') {
|
|
328
|
-
const selection = request.selection
|
|
329
|
-
for (let part = 0; part < parts.length; part++) {
|
|
330
|
-
const info = sheetPartInfo(this.text('dsh_lok_document_part_info', [this.document, part]))
|
|
331
|
-
if (selection.sheet !== undefined ? selection.sheet !== info.name : !info.visible) continue
|
|
332
|
-
this.invoke('part', [part])
|
|
333
|
-
this.invoke('viewport', [Math.max(1, Math.round(256 * selection.scale)), 256 * TWIPS_PER_CSS_PIXEL, 0, 0, 1, 1])
|
|
334
|
-
const range = selection.range === undefined ? dataArea(info) : parseCellRange(selection.range)
|
|
335
|
-
const geometry = JSON.parse(this.text('dsh_lok_document_command_values', [this.document, '.uno:SheetGeometryData'])) as SheetGeometry
|
|
336
|
-
const rectangle = sheetRangeRectangle(geometry, range, selection.scale)
|
|
337
|
-
this.text('dsh_lok_document_command_values', [this.document, `.uno:ViewRowColumnHeaders?x=${twips(rectangle.x)}&y=${twips(rectangle.y)}&width=${twips(rectangle.width)}&height=${twips(rectangle.height)}`])
|
|
338
|
-
regions.push({ part, sheet: info.name, range: rangeName(range), rectangle })
|
|
339
|
-
parts = parts.map((entry, index) => index === part ? { ...entry, width: Math.max(entry.width, rectangle.x + rectangle.width), height: Math.max(entry.height, rectangle.y + rectangle.height) } : entry)
|
|
340
|
-
}
|
|
341
|
-
if (regions.length === 0) throw new BrowserRenderError('invalid-document', 'No worksheet matches the export selection.')
|
|
342
|
-
} else if (this.state.documentType === 'text') {
|
|
343
|
-
regions.push(...this.state.pages.map(rectangle => ({ part: 0, rectangle })))
|
|
344
|
-
} else if (this.state.documentType === 'presentation') {
|
|
345
|
-
regions.push(...parts.map((part, index) => ({ part: index, rectangle: { x: 0, y: 0, width: part.width, height: part.height } })))
|
|
346
|
-
}
|
|
347
|
-
let pixels = 0
|
|
348
|
-
for (const entry of request.tiles) {
|
|
349
|
-
const part = parts[integer(entry.request.part, parts.length - 1)]!
|
|
350
|
-
const page = { ...part, x: 0, y: 0, part: this.state.documentType === 'text' ? -1 : entry.request.part }
|
|
351
|
-
const region = { ...entry.request, pageIndex: 0 }
|
|
352
|
-
const size = tileDimensions(region, [page])
|
|
353
|
-
pixels += size.width * size.height
|
|
354
|
-
if (pixels > request.maxPixels) throw new BrowserRenderError('render-failed', 'Office capture exceeds its pixel budget.')
|
|
355
|
-
if (entry.cached !== undefined) {
|
|
356
|
-
if (request.generation === undefined || entry.cached.width !== size.width || entry.cached.height !== size.height
|
|
357
|
-
|| entry.cached.rgba.byteLength !== size.width * size.height * 4) throw new BrowserRenderError('render-failed', 'Cached Office pixels do not match the capture.')
|
|
358
|
-
tiles.push(entry.cached)
|
|
359
|
-
} else {
|
|
360
|
-
this.invoke('part', [entry.request.part])
|
|
361
|
-
tiles.push(renderRegion(this.module, this.document, region, [page], () => new BrowserRenderError('render-failed', 'Office capture failed.')))
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
} finally {
|
|
365
|
-
try {
|
|
366
|
-
if (!this.call('dsh_lok_document_set_view', [this.document, original])) {
|
|
367
|
-
throw new BrowserRenderError('render-failed', 'The editor view could not be restored after capture.')
|
|
368
|
-
}
|
|
369
|
-
this.pump()
|
|
370
|
-
} catch (error) {
|
|
371
|
-
// Further commands must never run against the read-only capture view.
|
|
372
|
-
this.stop()
|
|
373
|
-
this.failure(error)
|
|
374
|
-
throw error
|
|
375
|
-
} finally { this.phase = 'idle' }
|
|
376
|
-
}
|
|
377
|
-
await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'capture-complete' } })
|
|
378
|
-
this.pump()
|
|
379
|
-
if (this.state.renderGeneration !== generation) throw new BrowserRenderError('snapshot-changed', 'The document changed during capture.')
|
|
380
|
-
return { state: { ...this.state, parts }, tiles, regions }
|
|
381
|
-
}
|
|
382
|
-
}
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
/** Persistent, single-user Office editing in one browser Worker. */
|
|
2
|
-
import type { BrowserDocumentOptions, BrowserPage, BrowserRenderErrorCode, BrowserTile } from './types.ts'
|
|
3
|
-
|
|
4
|
-
/** Formats qualified for editing and saving in their original container. */
|
|
5
|
-
export type BrowserEditorFormat = 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx'
|
|
6
|
-
|
|
7
|
-
/** Editor source, engine resources and Host font service. */
|
|
8
|
-
export type BrowserEditorOptions = Omit<BrowserDocumentOptions, 'extension'> & { readonly extension: BrowserEditorFormat; readonly readOnly?: boolean }
|
|
9
|
-
|
|
10
|
-
/** Document coordinates in CSS pixels at 96 DPI, independent of zoom. */
|
|
11
|
-
export interface BrowserRectangle extends BrowserPage { readonly x: number; readonly y: number }
|
|
12
|
-
|
|
13
|
-
/** A Writer document, Calc worksheet or Impress slide, measured when selected. */
|
|
14
|
-
export interface BrowserEditorPart extends BrowserPage { readonly name: string }
|
|
15
|
-
|
|
16
|
-
/** Geometry and current editing state; snapshots are immutable to consumers. */
|
|
17
|
-
export interface BrowserEditorState {
|
|
18
|
-
readonly documentType: 'text' | 'spreadsheet' | 'presentation'
|
|
19
|
-
readonly revision: number
|
|
20
|
-
/** Changes whenever document pixels or geometry are invalidated, independently of saved edits. */
|
|
21
|
-
readonly renderGeneration: number
|
|
22
|
-
readonly part: number
|
|
23
|
-
readonly parts: readonly BrowserEditorPart[]
|
|
24
|
-
/** Writer's visible page rectangles within its continuous document. */
|
|
25
|
-
readonly pages: readonly BrowserRectangle[]
|
|
26
|
-
readonly cursor: BrowserRectangle | null
|
|
27
|
-
readonly cursorVisible: boolean
|
|
28
|
-
readonly selection: readonly BrowserRectangle[]
|
|
29
|
-
readonly graphicSelection: BrowserRectangle | null
|
|
30
|
-
readonly cellAddress: string
|
|
31
|
-
readonly cellFormula: string
|
|
32
|
-
/** UNO command names to their current values, including undo and formatting state. */
|
|
33
|
-
readonly commands: Readonly<Record<string, string>>
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Input codes follow LibreOfficeKit; pointer coordinates use CSS pixels at 96 DPI. */
|
|
37
|
-
export type BrowserEditorInput =
|
|
38
|
-
| { readonly type: 'key'; readonly action: 'down' | 'up'; readonly character: number; readonly key: number }
|
|
39
|
-
| { readonly type: 'pointer'; readonly action: 'down' | 'up' | 'move'; readonly x: number; readonly y: number; readonly buttons: number; readonly modifiers: number; readonly clicks: number }
|
|
40
|
-
| { readonly type: 'composition'; readonly action: 'update' | 'end'; readonly text: string }
|
|
41
|
-
|
|
42
|
-
/** Typed UNO property values, serialized inside the Worker. */
|
|
43
|
-
export type BrowserCommandArguments = Readonly<Record<string, { readonly type: 'string' | 'boolean' | 'long' | 'short' | 'float'; readonly value: string | boolean | number }>>
|
|
44
|
-
|
|
45
|
-
/** One view-relative render request. */
|
|
46
|
-
export interface BrowserEditorTileRequest extends BrowserRectangle { readonly part: number; readonly scale: number }
|
|
47
|
-
|
|
48
|
-
/** One bounded, serialized capture; cached pixels must be current at generation. */
|
|
49
|
-
export interface BrowserEditorCaptureRequest {
|
|
50
|
-
readonly generation?: number
|
|
51
|
-
readonly maxPixels: number
|
|
52
|
-
readonly selection?: { readonly sheet?: string; readonly range?: string; readonly scale: number }
|
|
53
|
-
readonly tiles: readonly { readonly request: BrowserEditorTileRequest; readonly cached?: BrowserTile }[]
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Immutable pixels and geometry observed before a later input can run. */
|
|
57
|
-
export interface BrowserEditorCapture {
|
|
58
|
-
readonly state: BrowserEditorState
|
|
59
|
-
readonly tiles: readonly BrowserTile[]
|
|
60
|
-
readonly regions: readonly BrowserEditorCaptureRegion[]
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** A Writer page, slide, or bounded worksheet data area ready for raster export. */
|
|
64
|
-
export interface BrowserEditorCaptureRegion {
|
|
65
|
-
readonly part: number
|
|
66
|
-
readonly rectangle: BrowserRectangle
|
|
67
|
-
readonly sheet?: string
|
|
68
|
-
readonly range?: string
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** A complete Office export, associated with the edits it includes. */
|
|
72
|
-
export interface BrowserEditorSnapshot { readonly data: Uint8Array<ArrayBuffer>; readonly revision: number; readonly extension: BrowserEditorFormat }
|
|
73
|
-
|
|
74
|
-
/** State and tile events are delivered in engine order. A null region invalidates the entire part. */
|
|
75
|
-
export type BrowserEditorEvent =
|
|
76
|
-
| { readonly type: 'state'; readonly state: BrowserEditorState }
|
|
77
|
-
| { readonly type: 'invalidate'; readonly part: number; readonly rectangle: BrowserRectangle | null; readonly revision: number }
|
|
78
|
-
| { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
|
|
79
|
-
|
|
80
|
-
/** A retained editable document; hiding a view does not dispose its session. */
|
|
81
|
-
export interface BrowserEditor {
|
|
82
|
-
/** Latest engine snapshot; subscribe for later changes. */
|
|
83
|
-
readonly state: BrowserEditorState
|
|
84
|
-
/** Observe state and invalidation events; one throwing observer cannot interrupt others. */
|
|
85
|
-
subscribe(listener: (event: BrowserEditorEvent) => void): () => void
|
|
86
|
-
/** Apply one keyboard, pointer or IME event in order. */
|
|
87
|
-
input(event: BrowserEditorInput): Promise<void>
|
|
88
|
-
/** Execute a LibreOffice editing command, such as .uno:Bold or .uno:Undo. */
|
|
89
|
-
dispatch(command: string, args?: BrowserCommandArguments): Promise<void>
|
|
90
|
-
/** Insert plain UTF-8 text at the current selection, with engine-owned undo. */
|
|
91
|
-
paste(text: string): Promise<void>
|
|
92
|
-
/** Read the current selection as plain text. */
|
|
93
|
-
copy(): Promise<string>
|
|
94
|
-
/** Activate one worksheet or slide. Writer has a single part. */
|
|
95
|
-
setPart(part: number): Promise<void>
|
|
96
|
-
/** Inform the engine of visible document coordinates and zoom. */
|
|
97
|
-
setViewport(rectangle: BrowserRectangle, scale: number): Promise<void>
|
|
98
|
-
/** Render without changing the document; callers own caching and invalidation. */
|
|
99
|
-
renderTile(request: BrowserEditorTileRequest, signal?: AbortSignal): Promise<BrowserTile>
|
|
100
|
-
/** Capture bounded tiles under one render generation; an empty list is an idle barrier. */
|
|
101
|
-
capture(request: BrowserEditorCaptureRequest, signal?: AbortSignal): Promise<BrowserEditorCapture>
|
|
102
|
-
/** Export the current revision. Only a successful Host write confirms it saved. */
|
|
103
|
-
save(): Promise<BrowserEditorSnapshot>
|
|
104
|
-
/** Await engine and Worker disposal; repeated calls share completion. */
|
|
105
|
-
dispose(): Promise<void>
|
|
106
|
-
}
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/** Browser owner for an editable document and its ordered engine notifications. */
|
|
2
|
-
import { openBrowserConnection } from './connection.ts'
|
|
3
|
-
import { BrowserRenderError } from './types.ts'
|
|
4
|
-
import type { BrowserEditor, BrowserEditorEvent, BrowserEditorOptions, BrowserEditorState } from './editor-types.ts'
|
|
5
|
-
import type { EditorOperation } from './protocol.ts'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Import an Office document once and retain its editable model until disposal.
|
|
9
|
-
* @param options - OOXML bytes, version-matched engine resources and Host fonts.
|
|
10
|
-
* @param signal - Document lifetime; visibility changes must not abort it.
|
|
11
|
-
* @returns An editor whose exports remain unsaved until the caller writes them.
|
|
12
|
-
*/
|
|
13
|
-
export async function openEditor(options: BrowserEditorOptions, signal?: AbortSignal): Promise<BrowserEditor> {
|
|
14
|
-
const listeners = new Set<(event: BrowserEditorEvent) => void>()
|
|
15
|
-
let state: BrowserEditorState | undefined
|
|
16
|
-
const connection = await openBrowserConnection(options, signal, true, (event) => {
|
|
17
|
-
if (event.type === 'state') state = event.state
|
|
18
|
-
for (const listener of listeners) {
|
|
19
|
-
try { listener(event) } catch (error) { console.error('Office editor observer failed', error) }
|
|
20
|
-
}
|
|
21
|
-
})
|
|
22
|
-
state = connection.opened.editor
|
|
23
|
-
if (!state) { await connection.dispose(); throw new BrowserRenderError('invalid-document', 'LibreOffice returned no editing state.') }
|
|
24
|
-
async function edit(operation: EditorOperation) {
|
|
25
|
-
const response = await connection.request({ type: 'edit', operation })
|
|
26
|
-
if (response.type !== 'edited') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected editing response.')
|
|
27
|
-
return response
|
|
28
|
-
}
|
|
29
|
-
return {
|
|
30
|
-
get state() { return state! },
|
|
31
|
-
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener) } },
|
|
32
|
-
async input(event) { await edit({ type: 'input', event }) },
|
|
33
|
-
async dispatch(command, args) { await edit({ type: 'command', command, ...(args ? { arguments: args } : {}) }) },
|
|
34
|
-
async paste(text) { await edit({ type: 'paste', text }) },
|
|
35
|
-
async copy() { return (await edit({ type: 'copy' })).text ?? '' },
|
|
36
|
-
async setPart(part) { await edit({ type: 'part', part }) },
|
|
37
|
-
async setViewport(rectangle, scale) { await edit({ type: 'viewport', rectangle, scale }) },
|
|
38
|
-
async renderTile(request, tileSignal) {
|
|
39
|
-
const response = await connection.request({ type: 'editor-tile', request }, tileSignal)
|
|
40
|
-
if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
|
|
41
|
-
return response.tile
|
|
42
|
-
},
|
|
43
|
-
async capture(request, captureSignal) {
|
|
44
|
-
const response = await connection.request({ type: 'capture', request }, captureSignal)
|
|
45
|
-
if (response.type !== 'captured') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected capture response.')
|
|
46
|
-
return response.capture
|
|
47
|
-
},
|
|
48
|
-
async save() {
|
|
49
|
-
const response = await edit({ type: 'save' })
|
|
50
|
-
if (!response.snapshot) throw new BrowserRenderError('render-failed', 'LibreOffice returned no saved document bytes.')
|
|
51
|
-
return response.snapshot
|
|
52
|
-
},
|
|
53
|
-
dispose() { listeners.clear(); return connection.dispose() },
|
|
54
|
-
}
|
|
55
|
-
}
|