Line data Source code
1 : import { BaseWidget, LiteGraph } from '@/lib/litegraph/src/litegraph'
2 : import type { CanvasPointer, LGraphNode } from '@/lib/litegraph/src/litegraph'
3 : import type { IBaseWidget, IWidgetOptions } from '@comfyorg/graph-model/widgets'
4 : import type { DrawWidgetOptions } from '@/lib/litegraph/src/widgets/BaseWidget'
5 : import { useSettingStore } from '@/platform/settings/settingStore'
6 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
7 : import type { InputSpec } from '@comfyorg/object-info-parser/schemas/nodeDefSchemaV2'
8 : import { useApp } from '@/scripts/appInstance'
9 : import { calculateImageGrid } from '@/scripts/ui/imagePreview'
10 : import type { ComfyWidgetConstructorV2 } from '@/types/widgetConstructor'
11 : import { is_all_same_aspect_ratio } from '@/utils/imageUtil'
12 :
13 : /**
14 : * Workaround for Chrome GPU bug:
15 : * When Chrome is maximized with GPU acceleration and high DPR, calling
16 : * drawImage(canvas) + drawImage(img) in the same frame causes severe
17 : * performance degradation (FPS drops to 2-10, memory spikes ~18GB).
18 : *
19 : * Solution: Defer image rendering using queueMicrotask to separate
20 : * the two drawImage calls into different tasks.
21 : *
22 : * Note: As tested, requestAnimationFrame delays rendering to the next frame,
23 : * causing visible image flickering. queueMicrotask executes within the same
24 : * frame, avoiding flicker while still separating the drawImage calls.
25 : */
26 2356 : let deferredImageRenders: Array<() => void> = []
27 2356 : let deferredRenderScheduled = false
28 :
29 171 : function scheduleDeferredImageRender() {
30 171 : if (deferredRenderScheduled) return
31 108 : deferredRenderScheduled = true
32 :
33 108 : queueMicrotask(() => {
34 108 : const renders = deferredImageRenders
35 108 : deferredImageRenders = []
36 108 : deferredRenderScheduled = false
37 :
38 108 : for (const render of renders) {
39 175 : render()
40 : }
41 : })
42 : }
43 :
44 2356 : const TWO_PI = Math.PI * 2
45 2356 : const SPINNER_ARC_LENGTH = Math.PI * 1.5
46 :
47 13 : function renderUploadSpinner(
48 : ctx: CanvasRenderingContext2D,
49 : node: LGraphNode,
50 : shiftY: number,
51 : computedHeight: number | undefined
52 : ) {
53 13 : const dw = node.size[0]
54 13 : const dh = computedHeight ?? 220
55 13 : const centerX = dw / 2
56 13 : const centerY = shiftY + dh / 2
57 13 : const radius = 16
58 13 : const angle = ((Date.now() % 1000) / 1000) * TWO_PI
59 :
60 13 : ctx.save()
61 13 : ctx.strokeStyle = LiteGraph.NODE_TEXT_COLOR
62 13 : ctx.lineWidth = 3
63 13 : ctx.lineCap = 'round'
64 13 : ctx.beginPath()
65 13 : ctx.arc(centerX, centerY, radius, angle, angle + SPINNER_ARC_LENGTH)
66 13 : ctx.stroke()
67 13 : ctx.restore()
68 :
69 : // Schedule next frame to keep spinner animating continuously.
70 : // Only runs while node.isUploading is true (checked by caller).
71 13 : node.graph?.setDirtyCanvas(true)
72 : }
73 :
74 2356 : const renderPreview = (
75 : ctx: CanvasRenderingContext2D,
76 : node: LGraphNode,
77 : shiftY: number,
78 : computedHeight: number | undefined,
79 : imgs: HTMLImageElement[],
80 : width: number
81 : ) => {
82 190 : if (node.isUploading) {
83 13 : renderUploadSpinner(ctx, node, shiftY, computedHeight)
84 13 : return
85 : }
86 :
87 177 : const canvas = useCanvasStore().getCanvas()
88 177 : const mouse = canvas.graph_mouse
89 :
90 190 : if (!canvas.pointer_is_down && node.pointerDown) {
91 0 : if (
92 : mouse[0] === node.pointerDown.pos[0] &&
93 : mouse[1] === node.pointerDown.pos[1]
94 : ) {
95 0 : node.imageIndex = node.pointerDown.index
96 : }
97 0 : node.pointerDown = null
98 : }
99 :
100 186 : if (imgs.length === 0) return
101 :
102 171 : let { imageIndex } = node
103 171 : const numImages = imgs.length
104 190 : if (numImages === 1 && !imageIndex) {
105 : // This skips the thumbnail render section below
106 169 : node.imageIndex = imageIndex = 0
107 : }
108 :
109 : const settingStore = useSettingStore()
110 171 : const allowImageSizeDraw = settingStore.get('Comfy.Node.AllowImageSizeDraw')
111 190 : const IMAGE_TEXT_SIZE_TEXT_HEIGHT = allowImageSizeDraw ? 15 : 0
112 190 : const dw = width
113 190 : const dh = computedHeight ? computedHeight - IMAGE_TEXT_SIZE_TEXT_HEIGHT : 0
114 :
115 190 : if (imageIndex == null) {
116 : // No image selected; draw thumbnails of all
117 0 : let cellWidth: number
118 0 : let cellHeight: number
119 0 : let shiftX: number
120 0 : let cell_padding: number
121 0 : let cols: number
122 :
123 0 : const compact_mode = is_all_same_aspect_ratio(imgs)
124 0 : if (!compact_mode) {
125 : // use rectangle cell style and border line
126 0 : cell_padding = 2
127 : // Prevent infinite canvas2d scale-up
128 0 : const largestDimension = imgs.reduce(
129 : (acc, current) =>
130 : Math.max(acc, current.naturalWidth, current.naturalHeight),
131 : 0
132 : )
133 0 : const fakeImgs = []
134 0 : fakeImgs.length = imgs.length
135 0 : fakeImgs[0] = {
136 : naturalWidth: largestDimension,
137 : naturalHeight: largestDimension
138 : }
139 0 : ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(
140 : fakeImgs,
141 : dw,
142 : dh
143 : ))
144 : } else {
145 0 : cell_padding = 0
146 0 : ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(
147 : imgs,
148 : dw,
149 : dh
150 : ))
151 : }
152 :
153 0 : let anyHovered = false
154 0 : node.imageRects = []
155 0 : for (let i = 0; i < numImages; i++) {
156 0 : const img = imgs[i]
157 0 : const row = Math.floor(i / cols)
158 0 : const col = i % cols
159 0 : const x = col * cellWidth + shiftX
160 0 : const y = row * cellHeight + shiftY
161 0 : if (!anyHovered) {
162 0 : anyHovered = LiteGraph.isInsideRectangle(
163 : mouse[0],
164 : mouse[1],
165 : x + node.pos[0],
166 : y + node.pos[1],
167 : cellWidth,
168 : cellHeight
169 : )
170 0 : if (anyHovered) {
171 0 : node.overIndex = i
172 0 : let value = 110
173 0 : if (canvas.pointer_is_down) {
174 0 : if (!node.pointerDown || node.pointerDown.index !== i) {
175 0 : node.pointerDown = { index: i, pos: [...mouse] }
176 : }
177 0 : value = 125
178 : }
179 0 : ctx.filter = `contrast(${value}%) brightness(${value}%)`
180 0 : canvas.canvas.style.cursor = 'pointer'
181 : }
182 : }
183 0 : node.imageRects.push([x, y, cellWidth, cellHeight])
184 :
185 0 : const wratio = cellWidth / img.width
186 0 : const hratio = cellHeight / img.height
187 0 : const ratio = Math.min(wratio, hratio)
188 :
189 0 : const imgHeight = ratio * img.height
190 0 : const imgY = row * cellHeight + shiftY + (cellHeight - imgHeight) / 2
191 0 : const imgWidth = ratio * img.width
192 0 : const imgX = col * cellWidth + shiftX + (cellWidth - imgWidth) / 2
193 :
194 : // Defer image rendering to work around Chrome GPU bug
195 0 : const transform = ctx.getTransform()
196 0 : const filter = ctx.filter
197 0 : const drawParams = {
198 : img,
199 : x: imgX + cell_padding,
200 : y: imgY + cell_padding,
201 : w: imgWidth - cell_padding * 2,
202 : h: imgHeight - cell_padding * 2
203 : }
204 0 : deferredImageRenders.push(() => {
205 0 : if (!drawParams.img.naturalWidth || !drawParams.img.naturalHeight)
206 0 : return
207 0 : ctx.save()
208 0 : ctx.setTransform(transform)
209 0 : ctx.filter = filter
210 0 : ctx.drawImage(
211 : drawParams.img,
212 : drawParams.x,
213 : drawParams.y,
214 : drawParams.w,
215 : drawParams.h
216 : )
217 0 : ctx.restore()
218 : })
219 0 : scheduleDeferredImageRender()
220 :
221 0 : if (!compact_mode) {
222 : // rectangle cell and border line style
223 0 : ctx.strokeStyle = '#8F8F8F'
224 0 : ctx.lineWidth = 1
225 0 : ctx.strokeRect(
226 : x + cell_padding,
227 : y + cell_padding,
228 : cellWidth - cell_padding * 2,
229 : cellHeight - cell_padding * 2
230 : )
231 : }
232 :
233 0 : ctx.filter = 'none'
234 : }
235 :
236 0 : if (!anyHovered) {
237 0 : node.pointerDown = null
238 0 : node.overIndex = null
239 : }
240 :
241 0 : return
242 : }
243 : // Draw individual
244 171 : const img = imgs.at(imageIndex)
245 186 : if (!img) return
246 171 : let w = img.naturalWidth
247 171 : let h = img.naturalHeight
248 :
249 171 : const scaleX = dw / w
250 171 : const scaleY = dh / h
251 171 : const scale = Math.min(scaleX, scaleY, 1)
252 :
253 171 : w *= scale
254 171 : h *= scale
255 :
256 171 : const x = (dw - w) / 2
257 171 : const y = (dh - h) / 2 + shiftY
258 :
259 : // Defer image rendering to work around Chrome GPU bug
260 171 : const transform = ctx.getTransform()
261 171 : deferredImageRenders.push(() => {
262 171 : if (!img.naturalWidth || !img.naturalHeight) return
263 171 : ctx.save()
264 171 : ctx.setTransform(transform)
265 171 : ctx.drawImage(img, x, y, w, h)
266 171 : ctx.restore()
267 : })
268 171 : scheduleDeferredImageRender()
269 :
270 : // Draw image size text below the image
271 171 : if (allowImageSizeDraw) {
272 171 : ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR
273 171 : ctx.textAlign = 'center'
274 171 : ctx.font = '10px sans-serif'
275 171 : const sizeText = `${Math.round(img.naturalWidth)} × ${Math.round(img.naturalHeight)}`
276 171 : const textY = y + h + 10
277 171 : ctx.fillText(sizeText, x + w / 2, textY)
278 : }
279 :
280 171 : const drawButton = (
281 : x: number,
282 : y: number,
283 : sz: number,
284 : text: string
285 : ): boolean => {
286 4 : const hovered = LiteGraph.isInsideRectangle(
287 : mouse[0],
288 : mouse[1],
289 : x + node.pos[0],
290 : y + node.pos[1],
291 : sz,
292 : sz
293 : )
294 4 : let fill = '#333'
295 4 : let textFill = '#fff'
296 4 : let isClicking = false
297 4 : if (hovered) {
298 0 : canvas.canvas.style.cursor = 'pointer'
299 0 : if (canvas.pointer_is_down) {
300 0 : fill = '#1e90ff'
301 0 : isClicking = true
302 : } else {
303 0 : fill = '#eee'
304 0 : textFill = '#000'
305 : }
306 : }
307 :
308 4 : deferredImageRenders.push(() => {
309 4 : ctx.save()
310 4 : ctx.setTransform(transform)
311 4 : ctx.fillStyle = fill
312 4 : ctx.beginPath()
313 4 : ctx.roundRect(x, y, sz, sz, [4])
314 4 : ctx.fill()
315 4 : ctx.fillStyle = textFill
316 4 : ctx.font = '12px Inter, sans-serif'
317 4 : ctx.textAlign = 'center'
318 4 : ctx.fillText(text, x + 15, y + 20)
319 4 : ctx.restore()
320 : })
321 :
322 4 : return isClicking
323 : }
324 :
325 171 : if (!(numImages > 1)) return
326 :
327 190 : const imageNum = (node.imageIndex ?? 0) + 1
328 190 : if (drawButton(dw - 40, dh + shiftY - 40, 30, `${imageNum}/${numImages}`)) {
329 0 : const i = imageNum >= numImages ? 0 : imageNum
330 0 : if (!node.pointerDown || node.pointerDown.index !== i) {
331 0 : node.pointerDown = { index: i, pos: [...mouse] }
332 : }
333 : }
334 :
335 2 : if (drawButton(dw - 40, shiftY + 10, 30, `x`)) {
336 0 : if (!node.pointerDown || node.pointerDown.index !== null) {
337 0 : node.pointerDown = { index: null, pos: [...mouse] }
338 : }
339 : }
340 : }
341 :
342 2356 : class ImagePreviewWidget extends BaseWidget {
343 : constructor(
344 : node: LGraphNode,
345 : name: string,
346 : options: IWidgetOptions<string | object>
347 : ) {
348 : const widget: IBaseWidget = {
349 : name,
350 : options,
351 : type: 'custom',
352 : /** Dummy value to satisfy type requirements. */
353 : value: '',
354 : y: 0
355 : }
356 36 : super(widget, node)
357 :
358 : // Don't serialize the widget value
359 36 : this.serialize = false
360 : }
361 :
362 : override drawWidget(
363 : ctx: CanvasRenderingContext2D,
364 : options: DrawWidgetOptions
365 : ): void {
366 190 : const imgs = options.previewImages ?? this.node.imgs ?? []
367 190 : renderPreview(
368 : ctx,
369 : this.node,
370 : this.y,
371 : this.computedHeight,
372 : imgs,
373 : options.width
374 : )
375 : }
376 :
377 : override onPointerDown(pointer: CanvasPointer, node: LGraphNode): boolean {
378 0 : pointer.onDragStart = () => {
379 0 : const { canvas } = useApp()
380 0 : const { graph } = canvas
381 0 : canvas.emitBeforeChange()
382 0 : graph?.beforeChange()
383 : // Ensure that dragging is properly cleaned up, on success or failure.
384 0 : pointer.finally = () => {
385 0 : canvas.isDragging = false
386 0 : graph?.afterChange()
387 0 : canvas.emitAfterChange()
388 : }
389 :
390 0 : canvas.processSelect(node, pointer.eDown)
391 0 : canvas.isDragging = true
392 : }
393 :
394 0 : pointer.onDragEnd = (e) => {
395 0 : const { canvas } = useApp()
396 0 : if (e.shiftKey || LiteGraph.alwaysSnapToGrid)
397 0 : canvas.graph?.snapToGrid(canvas.selectedItems)
398 :
399 0 : canvas.setDirty(true, true)
400 : }
401 :
402 0 : return true
403 : }
404 :
405 : override onClick(): void {}
406 :
407 : override computeLayoutSize() {
408 193 : return {
409 : minHeight: 220,
410 : minWidth: 1
411 : }
412 : }
413 : }
414 :
415 2356 : export const useImagePreviewWidget = () => {
416 66916 : const widgetConstructor: ComfyWidgetConstructorV2 = (
417 : node: LGraphNode,
418 : inputSpec: InputSpec
419 : ) => {
420 36 : return node.addCustomWidget(
421 : new ImagePreviewWidget(node, inputSpec.name, {
422 : serialize: false,
423 : surfaces: { canvas: 'shown', vueNode: 'never', panel: 'never' }
424 : })
425 : )
426 : }
427 :
428 66916 : return widgetConstructor
429 : }
|