Line data Source code
1 : import { tryOnScopeDispose } from '@vueuse/core'
2 : import { computed } from 'vue'
3 :
4 : import {
5 : asHistoryReference,
6 : useWidgetHistoryStore
7 : } from '@/stores/widgetHistoryStore'
8 : import type {
9 : HistoryDirection,
10 : WidgetHistoryScope
11 : } from '@/stores/widgetHistoryStore'
12 :
13 31 : const PAINTER_HISTORY_BUDGET_BYTES = 512 * 1024 * 1024
14 31 : const PAINTER_HISTORY_COMPRESS_MIN_PIXELS = 1_000_000
15 :
16 : export interface CanvasRect {
17 : x: number
18 : y: number
19 : width: number
20 : height: number
21 : }
22 :
23 : interface RegionPixels {
24 : canvas?: HTMLCanvasElement
25 : png?: Blob
26 : }
27 :
28 : interface CanvasRegion extends CanvasRect {
29 : sequence: number
30 : pixels: RegionPixels
31 : }
32 :
33 31 : let nextSequence = 0
34 :
35 18 : export function clampCanvasRect(
36 : rect: CanvasRect,
37 : canvas: { width: number; height: number }
38 : ): CanvasRect | null {
39 18 : const x = Math.max(0, Math.floor(rect.x))
40 18 : const y = Math.max(0, Math.floor(rect.y))
41 18 : const right = Math.min(canvas.width, Math.ceil(rect.x + rect.width))
42 18 : const bottom = Math.min(canvas.height, Math.ceil(rect.y + rect.height))
43 18 : return right > x && bottom > y
44 : ? { x, y, width: right - x, height: bottom - y }
45 : : null
46 : }
47 :
48 18 : function blankCanvas(width: number, height: number) {
49 18 : const canvas = document.createElement('canvas')
50 18 : canvas.width = width
51 18 : canvas.height = height
52 18 : const ctx = canvas.getContext('2d')
53 18 : return ctx ? { canvas, ctx } : null
54 : }
55 :
56 18 : export function captureCanvasRegion(
57 : source: HTMLCanvasElement,
58 : { x, y, width, height }: CanvasRect
59 : ): CanvasRegion | null {
60 18 : const target = blankCanvas(width, height)
61 18 : if (!target) return null
62 18 : target.ctx.drawImage(source, x, y, width, height, 0, 0, width, height)
63 18 : return asHistoryReference({
64 : x,
65 : y,
66 : width,
67 : height,
68 : sequence: nextSequence++,
69 : pixels: { canvas: target.canvas }
70 : })
71 : }
72 :
73 147 : function isCanvasRegion(value: unknown): value is CanvasRegion {
74 147 : if (typeof value !== 'object' || value === null) return false
75 49 : const region = value as Record<string, unknown>
76 147 : return (
77 : typeof region.x === 'number' &&
78 : typeof region.y === 'number' &&
79 : typeof region.width === 'number' &&
80 : typeof region.height === 'number' &&
81 : typeof region.sequence === 'number' &&
82 : typeof region.pixels === 'object' &&
83 : region.pixels !== null
84 : )
85 : }
86 :
87 23 : function regionBytes({ width, height, pixels }: CanvasRegion): number {
88 23 : return pixels.canvas ? width * height * 4 : (pixels.png?.size ?? 0)
89 : }
90 :
91 1 : function releaseCanvas(canvas: HTMLCanvasElement) {
92 1 : canvas.width = 0
93 1 : canvas.height = 0
94 : }
95 :
96 1 : function releaseRegion({ pixels }: CanvasRegion) {
97 1 : if (pixels.canvas) releaseCanvas(pixels.canvas)
98 1 : pixels.canvas = undefined
99 1 : pixels.png = undefined
100 : }
101 :
102 0 : function paintCanvasRegion(
103 : ctx: CanvasRenderingContext2D,
104 : { x, y, width, height, pixels }: CanvasRegion
105 : ): boolean {
106 0 : if (!pixels.canvas) return false
107 0 : ctx.save()
108 0 : ctx.globalAlpha = 1
109 0 : ctx.globalCompositeOperation = 'source-over'
110 0 : ctx.clearRect(x, y, width, height)
111 0 : ctx.drawImage(pixels.canvas, x, y)
112 0 : ctx.restore()
113 0 : return true
114 : }
115 :
116 0 : async function decodeBitmap(png: Blob): Promise<ImageBitmap | null> {
117 0 : try {
118 0 : return await createImageBitmap(png)
119 : } catch {
120 0 : return null
121 : }
122 : }
123 :
124 0 : async function decodeRegion({
125 : width,
126 : height,
127 : pixels
128 : }: CanvasRegion): Promise<boolean> {
129 0 : const png = pixels.png
130 0 : const bitmap = png ? await decodeBitmap(png) : null
131 0 : if (!bitmap) return false
132 0 : const target = blankCanvas(width, height)
133 0 : if (target) target.ctx.drawImage(bitmap, 0, 0)
134 0 : bitmap.close()
135 0 : if (!target) return false
136 0 : if (pixels.png !== png) {
137 0 : releaseCanvas(target.canvas)
138 0 : return false
139 : }
140 0 : pixels.canvas = target.canvas
141 0 : pixels.png = undefined
142 0 : return true
143 : }
144 :
145 0 : function whenIdle(task: () => void) {
146 0 : if (typeof requestIdleCallback === 'function') requestIdleCallback(task)
147 0 : else setTimeout(task, 0)
148 : }
149 :
150 : interface UsePainterHistoryOptions {
151 : scope: () => WidgetHistoryScope | null
152 : context: () => CanvasRenderingContext2D | null
153 : onRestore: () => void
154 : canRestore?: () => boolean
155 : budgetBytes?: number
156 : compressMinPixels?: number
157 : }
158 :
159 31 : export function usePainterHistory({
160 : scope,
161 : context,
162 : onRestore,
163 : canRestore = () => true,
164 : budgetBytes = PAINTER_HISTORY_BUDGET_BYTES,
165 : compressMinPixels = PAINTER_HISTORY_COMPRESS_MIN_PIXELS
166 : }: UsePainterHistoryOptions) {
167 31 : const store = useWidgetHistoryStore()
168 31 : let pending = Promise.resolve()
169 31 : let pendingCount = 0
170 31 : const ownRegions = new WeakSet<CanvasRegion>()
171 :
172 41 : function storedRegions() {
173 41 : return store
174 : .storedSteps()
175 : .flatMap(({ scope, value }) =>
176 : isCanvasRegion(value) ? [{ scope, region: value }] : []
177 : )
178 : }
179 :
180 0 : function isStored(region: CanvasRegion) {
181 0 : return storedRegions().some((stored) => stored.region === region)
182 : }
183 :
184 18 : function enforceBudget() {
185 18 : const regions = storedRegions().sort(
186 : (a, b) => a.region.sequence - b.region.sequence
187 : )
188 18 : let total = regions.reduce(
189 : (sum, { region }) => sum + regionBytes(region),
190 : 0
191 : )
192 18 : for (const { scope, region } of regions) {
193 18 : if (total <= budgetBytes) return
194 0 : store.dropStep(scope, region)
195 0 : total -= regionBytes(region)
196 0 : releaseRegion(region)
197 : }
198 : }
199 :
200 18 : function compressLater(region: CanvasRegion) {
201 18 : if (region.width * region.height < compressMinPixels) return
202 0 : whenIdle(() => {
203 0 : const canvas = region.pixels.canvas
204 0 : if (!canvas || !isStored(region)) return
205 0 : canvas.toBlob((png) => {
206 0 : if (!png || region.pixels.canvas !== canvas) return
207 0 : region.pixels.png = png
208 0 : region.pixels.canvas = undefined
209 0 : releaseCanvas(canvas)
210 : }, 'image/png')
211 : })
212 : }
213 :
214 23 : function dropRegions(
215 : regions: { scope: WidgetHistoryScope; region: CanvasRegion }[]
216 : ) {
217 23 : for (const { scope, region } of regions) {
218 1 : store.dropStep(scope, region)
219 1 : releaseRegion(region)
220 : }
221 : }
222 :
223 18 : function dropOtherCanvasRegions({
224 : widgetId,
225 : rootGraphId
226 : }: WidgetHistoryScope) {
227 18 : dropRegions(
228 : storedRegions().filter(
229 : ({ scope, region }) =>
230 : scope.rootGraphId === rootGraphId &&
231 : scope.widgetId === widgetId &&
232 : !ownRegions.has(region)
233 : )
234 : )
235 : }
236 :
237 18 : function keep(region: CanvasRegion) {
238 18 : ownRegions.add(region)
239 18 : compressLater(region)
240 18 : enforceBudget()
241 : }
242 :
243 18 : function record(captureBefore: () => CanvasRegion | null) {
244 18 : const target = scope()
245 18 : const before = target && captureBefore()
246 18 : if (!target || !before) return
247 18 : dropOtherCanvasRegions(target)
248 18 : store.record(target, before)
249 18 : keep(before)
250 : }
251 :
252 0 : function swapRegion(
253 : target: WidgetHistoryScope,
254 : ctx: CanvasRenderingContext2D,
255 : next: CanvasRegion,
256 : direction: HistoryDirection
257 : ) {
258 0 : const current = captureCanvasRegion(ctx.canvas, next)
259 0 : if (!current) return
260 0 : const step =
261 : direction === 'undo'
262 : ? store.undo(target, current)
263 : : store.redo(target, current)
264 0 : if (!isCanvasRegion(step?.value) || !paintCanvasRegion(ctx, step.value))
265 0 : return
266 0 : releaseRegion(step.value)
267 0 : keep(current)
268 0 : onRestore()
269 : }
270 :
271 118 : function nextStep(target: WidgetHistoryScope, direction: HistoryDirection) {
272 118 : const next = store.peek(target, direction)?.value
273 118 : return isCanvasRegion(next) && ownRegions.has(next) ? next : undefined
274 : }
275 :
276 0 : async function travel(direction: HistoryDirection): Promise<void> {
277 0 : const target = scope()
278 0 : const ctx = context()
279 0 : const next = target && nextStep(target, direction)
280 0 : if (!target || !ctx || !next) return
281 0 : if (!next.pixels.canvas && !(await decodeRegion(next))) {
282 0 : store.dropStep(target, next)
283 0 : return
284 : }
285 0 : if (nextStep(target, direction) !== next || !canRestore()) return
286 0 : swapRegion(target, ctx, next, direction)
287 : }
288 :
289 0 : function enqueue(direction: HistoryDirection) {
290 0 : pendingCount++
291 0 : const run = pending
292 : .then(() => travel(direction))
293 : .finally(() => {
294 0 : pendingCount--
295 : })
296 0 : pending = run.catch(() => undefined)
297 0 : return run
298 : }
299 :
300 5 : function discard() {
301 5 : dropRegions(storedRegions().filter(({ region }) => ownRegions.has(region)))
302 : }
303 :
304 31 : const canUndo = computed(() => {
305 59 : const target = scope()
306 59 : return !!target && !!nextStep(target, 'undo')
307 : })
308 31 : const canRedo = computed(() => {
309 59 : const target = scope()
310 59 : return !!target && !!nextStep(target, 'redo')
311 : })
312 :
313 31 : tryOnScopeDispose(
314 : store.registerTraveler({
315 : scope,
316 : canTravel: (direction) =>
317 : direction === 'undo' ? canUndo.value : canRedo.value,
318 : travel: enqueue
319 : })
320 : )
321 :
322 31 : return {
323 : canUndo,
324 : canRedo,
325 : isRestoring: () => pendingCount > 0,
326 : record,
327 : discard,
328 : undo: () => enqueue('undo'),
329 : redo: () => enqueue('redo')
330 : }
331 : }
|