-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathCanvasEntityBufferObjectRenderer.ts
More file actions
338 lines (287 loc) · 12.6 KB
/
CanvasEntityBufferObjectRenderer.ts
File metadata and controls
338 lines (287 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { deepClone } from 'common/util/deepClone';
import type { CanvasEntityAdapter } from 'features/controlLayers/konva/CanvasEntity/types';
import type { CanvasManager } from 'features/controlLayers/konva/CanvasManager';
import { CanvasModuleBase } from 'features/controlLayers/konva/CanvasModuleBase';
import { CanvasObjectBrushLine } from 'features/controlLayers/konva/CanvasObject/CanvasObjectBrushLine';
import { CanvasObjectBrushLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectBrushLineWithPressure';
import { CanvasObjectEraserLine } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLine';
import { CanvasObjectEraserLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLineWithPressure';
import { CanvasObjectGradient } from 'features/controlLayers/konva/CanvasObject/CanvasObjectGradient';
import { CanvasObjectImage } from 'features/controlLayers/konva/CanvasObject/CanvasObjectImage';
import { CanvasObjectLasso } from 'features/controlLayers/konva/CanvasObject/CanvasObjectLasso';
import { CanvasObjectOval } from 'features/controlLayers/konva/CanvasObject/CanvasObjectOval';
import { CanvasObjectPolygon } from 'features/controlLayers/konva/CanvasObject/CanvasObjectPolygon';
import { CanvasObjectRect } from 'features/controlLayers/konva/CanvasObject/CanvasObjectRect';
import type { AnyObjectRenderer, AnyObjectState } from 'features/controlLayers/konva/CanvasObject/types';
import { getPrefixedId } from 'features/controlLayers/konva/util';
import Konva from 'konva';
import type { Logger } from 'roarr';
import { assert } from 'tsafe';
/**
* Handles rendering of objects for a canvas entity.
*/
export class CanvasEntityBufferObjectRenderer extends CanvasModuleBase {
readonly type = 'buffer_renderer';
readonly id: string;
readonly path: string[];
readonly parent: CanvasEntityAdapter;
readonly manager: CanvasManager;
readonly log: Logger;
/**
* A set of subscriptions that should be cleaned up when the transformer is destroyed.
*/
subscriptions: Set<() => void> = new Set();
/**
* A buffer object state that is rendered separately from the other objects. This is used for objects that are being
* drawn in real-time, such as brush lines. The buffer object state only exists in this renderer and is not part of
* the application state until it is committed.
*/
state: AnyObjectState | null = null;
/**
* The object renderer for the buffer object state. It is created when the buffer object state is set and destroyed
* when the buffer object state is cleared. This is separate from the other object renderers to allow the buffer to
* be rendered separately.
*/
renderer: AnyObjectRenderer | null = null;
/**
* A object containing singleton Konva nodes.
*/
konva: {
/**
* A Konva Group that holds the buffer object renderer.
*/
group: Konva.Group;
};
constructor(parent: CanvasEntityAdapter) {
super();
this.id = getPrefixedId(this.type);
this.parent = parent;
this.manager = parent.manager;
this.path = this.manager.buildPath(this);
this.log = this.manager.buildLogger(this);
this.log.debug('Creating module');
this.konva = {
group: new Konva.Group({ name: `${this.type}:buffer_group`, listening: false }),
};
this.parent.konva.layer.add(this.konva.group);
/**
* When switching tool, commit the buffer. This is necessary to prevent the buffer from being lost when the
* user switches tool mid-drawing, for example by pressing space to pan the stage. It's easy to press space
* to pan _before_ releasing the mouse button, which would cause the buffer to be lost if we didn't commit it.
*
* But! We should only do this if we are not "busy". "Busy" means the canvas may be filtering or transforming
* a layer, and may be using the buffer object! So, we should not commit the buffer in that case, and let the
* filter or transformer handle it.
*/
this.subscriptions.add(
this.manager.tool.$tool.listen(() => {
if (this.hasBuffer() && !this.manager.$isBusy.get()) {
const isTemporaryShapesViewSwitch =
this.manager.tool.tools.rect.hasSuspendableSession() &&
((this.manager.tool.$tool.get() === 'view' && this.manager.tool.$toolBuffer.get() === 'rect') ||
this.manager.tool.$tool.get() === 'rect');
if (isTemporaryShapesViewSwitch) {
return;
}
if (this.state?.type === 'polygon' && this.state.previewPoint) {
this.clearBuffer();
return;
}
this.commitBuffer();
}
})
);
}
/**
* Renders the buffer object. If the buffer renderer does not exist, it will be created and its Konva group added to the
* parent entity's buffer object group.
* @returns A promise that resolves to a boolean, indicating if the object was rendered.
*/
renderBufferObject = async (): Promise<boolean> => {
let didRender = false;
if (!this.state) {
return false;
}
// If we are creating a new renderer, we need to destroy the old one. But, to prevent a flicker, we only destroy
// it after the new renderer has been created and rendered.
let rendererToDestroy: AnyObjectRenderer | null = null;
if (this.renderer && this.renderer.id !== this.state.id) {
rendererToDestroy = this.renderer;
this.renderer = null;
}
if (this.state.type === 'brush_line') {
assert(this.renderer instanceof CanvasObjectBrushLine || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectBrushLine(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'brush_line_with_pressure') {
assert(this.renderer instanceof CanvasObjectBrushLineWithPressure || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectBrushLineWithPressure(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'eraser_line') {
assert(this.renderer instanceof CanvasObjectEraserLine || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectEraserLine(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'eraser_line_with_pressure') {
assert(this.renderer instanceof CanvasObjectEraserLineWithPressure || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectEraserLineWithPressure(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'rect') {
assert(this.renderer instanceof CanvasObjectRect || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectRect(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'oval') {
assert(this.renderer instanceof CanvasObjectOval || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectOval(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'polygon') {
assert(this.renderer instanceof CanvasObjectPolygon || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectPolygon(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'lasso') {
assert(this.renderer instanceof CanvasObjectLasso || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectLasso(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'gradient') {
assert(this.renderer instanceof CanvasObjectGradient || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectGradient(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = this.renderer.update(this.state, true);
} else if (this.state.type === 'image') {
assert(this.renderer instanceof CanvasObjectImage || !this.renderer);
if (!this.renderer) {
this.renderer = new CanvasObjectImage(this.state, this);
this.konva.group.add(this.renderer.konva.group);
}
didRender = await this.renderer.update(this.state, true);
}
if (rendererToDestroy) {
rendererToDestroy.destroy();
}
return didRender;
};
/**
* Determines if the renderer has a buffer object to render.
* @returns Whether the renderer has a buffer object to render.
*/
hasBuffer = (): boolean => {
return this.state !== null || this.renderer !== null;
};
/**
* Sets the buffer object state to render.
* @param objectState The object state to set as the buffer.
* @param resetBufferOffset Whether to reset the buffer's offset to 0,0. This is necessary when previewing filters.
* When previewing a filter, the buffer object is an image of the same size as the entity, so it should be rendered
* at the top-left corner of the entity.
* @returns A promise that resolves to a boolean, indicating if the object was rendered.
*/
setBuffer = async (objectState: AnyObjectState, resetBufferOffset: boolean = false): Promise<boolean> => {
this.log.trace('Setting buffer');
this.state = objectState;
if (resetBufferOffset) {
this.konva.group.offset({ x: 0, y: 0 });
}
return await this.renderBufferObject();
};
/**
* Clears the buffer object state.
*/
clearBuffer = () => {
if (this.state || this.renderer) {
this.log.trace('Clearing buffer');
this.renderer?.destroy();
this.renderer = null;
this.state = null;
}
};
/**
* Commits the current buffer object, pushing the buffer object state back to the application state.
*/
commitBuffer = (options?: { pushToState?: boolean }) => {
const { pushToState } = { ...options, pushToState: true };
if (!this.state || !this.renderer) {
this.log.trace('No buffer to commit');
return;
}
this.log.trace({ buffer: this.renderer.repr() }, 'Committing buffer');
let committedState = this.state;
// Polygon previews render an outline while they are still live in the buffer.
// Clear that preview state before adopting the renderer into the persistent object group.
if (committedState.type === 'polygon' && this.renderer instanceof CanvasObjectPolygon) {
committedState = { ...committedState, previewPoint: undefined };
this.state = null;
this.renderer.update(committedState, true);
}
// Move the buffer to the persistent objects group/renderers
this.parent.renderer.adoptObjectRenderer(this.renderer);
if (pushToState) {
const entityIdentifier = this.parent.entityIdentifier;
switch (committedState.type) {
case 'brush_line':
case 'brush_line_with_pressure':
this.manager.stateApi.addBrushLine({ entityIdentifier, brushLine: committedState });
break;
case 'eraser_line':
case 'eraser_line_with_pressure':
this.manager.stateApi.addEraserLine({ entityIdentifier, eraserLine: committedState });
break;
case 'rect':
case 'oval':
case 'polygon':
this.manager.stateApi.addShape({ entityIdentifier, shape: committedState });
break;
case 'lasso':
this.manager.stateApi.addLasso({ entityIdentifier, lasso: committedState });
break;
case 'gradient':
this.manager.stateApi.addGradient({ entityIdentifier, gradient: committedState });
break;
}
}
this.renderer = null;
this.state = null;
};
destroy = () => {
this.log.debug('Destroying module');
this.subscriptions.forEach((unsubscribe) => unsubscribe());
this.subscriptions.clear();
if (this.renderer) {
this.renderer.destroy();
}
};
repr = () => {
return {
id: this.id,
type: this.type,
path: this.path,
parent: this.parent.id,
bufferState: deepClone(this.state),
bufferRenderer: this.renderer?.repr() ?? null,
};
};
}