LCOV - code coverage report
Current view: top level - src/renderer/extensions/painter/composables - usePainter.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 83.5 % 486 406
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { UploadImageResponse } from '@comfyorg/ingest-types'
       2              : import type { Ref } from 'vue'
       3              : import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
       4              : import { useElementSize } from '@vueuse/core'
       5              : import { useI18n } from 'vue-i18n'
       6              : 
       7              : import {
       8              :   getEffectiveBrushSize,
       9              :   getEffectiveHardness
      10              : } from '@comfyorg/mask-editor/brushUtils'
      11              : import { StrokeProcessor } from '@comfyorg/mask-editor/StrokeProcessor'
      12              : import { locateWidgetNode } from '@/composables/widgetHistoryScope'
      13              : import type { LocatedWidget } from '@/composables/widgetHistoryScope'
      14              : import {
      15              :   isWidgetInputConnected,
      16              :   resolveWidgetInputSource
      17              : } from '@/composables/widgetInputSource'
      18              : import {
      19              :   captureCanvasRegion,
      20              :   clampCanvasRect,
      21              :   usePainterHistory
      22              : } from '@/renderer/extensions/painter/composables/usePainterHistory'
      23              : import type { CanvasRect } from '@/renderer/extensions/painter/composables/usePainterHistory'
      24              : import { setNodeWidgetValue } from '@/core/graph/widgets/nodeWidgetValues'
      25              : import { hexToRgb } from '@comfyorg/shared-frontend-utils/colorUtil'
      26              : import type { Point2D as Point } from '@comfyorg/shared-frontend-utils/geometry'
      27              : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
      28              : import { useToast } from '@/components/ui/toast/toastStore'
      29              : import { useLiveGraphNode } from '@/composables/useLiveGraphNode'
      30              : import { api } from '@/scripts/api'
      31              : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
      32              : import type { WidgetHistoryScope } from '@/stores/widgetHistoryStore'
      33              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      34              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      35              : import { widgetId } from '@comfyorg/graph-model/widgetId'
      36              : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
      37              : 
      38              : type PainterTool = 'brush' | 'eraser'
      39              : 
      40           31 : export const PAINTER_TOOLS: Record<string, PainterTool> = {
      41              :   BRUSH: 'brush',
      42              :   ERASER: 'eraser'
      43              : } as const
      44              : 
      45              : interface UsePainterOptions {
      46              :   widget: LocatedWidget
      47              :   canvasEl: Ref<HTMLCanvasElement | null>
      48              :   cursorEl: Ref<HTMLElement | null>
      49              :   modelValue: Ref<string>
      50              :   historyScope?: () => WidgetHistoryScope | null
      51              : }
      52              : 
      53           16 : function capturePointerIfActive(e: PointerEvent): boolean {
      54           16 :   try {
      55           16 :     ;(e.target as HTMLElement).setPointerCapture(e.pointerId)
      56           16 :     return true
      57              :   } catch {
      58            0 :     return false
      59              :   }
      60              : }
      61              : 
      62           16 : function releasePointerIfCaptured(e: PointerEvent): boolean {
      63           16 :   try {
      64           16 :     ;(e.target as HTMLElement).releasePointerCapture(e.pointerId)
      65           16 :     return true
      66              :   } catch {
      67            0 :     return false
      68              :   }
      69              : }
      70              : 
      71           31 : export function usePainter(nodeId: NodeId, options: UsePainterOptions) {
      72           31 :   const {
      73              :     widget,
      74              :     canvasEl,
      75              :     cursorEl,
      76              :     modelValue,
      77              :     historyScope = () => null
      78              :   } = options
      79           31 :   const { t } = useI18n()
      80           31 :   const nodeOutputStore = useNodeOutputStore()
      81           31 :   const toast = useToast()
      82              : 
      83           31 :   const isDirty = ref(false)
      84           31 :   let canvasMask = ''
      85           31 :   let pendingMaskImage: HTMLImageElement | null = null
      86              : 
      87           31 :   const cursorVisible = ref(false)
      88              : 
      89           31 :   let isDrawing = false
      90           31 :   let strokeProcessor: StrokeProcessor | null = null
      91           31 :   let lastPoint: Point | null = null
      92              : 
      93           31 :   let cachedRect: DOMRect | null = null
      94              : 
      95           31 :   let mainCtx: CanvasRenderingContext2D | null = null
      96              : 
      97           31 :   let strokeCanvas: HTMLCanvasElement | null = null
      98           31 :   let strokeCtx: CanvasRenderingContext2D | null = null
      99              : 
     100           31 :   let baseCanvas: HTMLCanvasElement | null = null
     101           31 :   let baseCtx: CanvasRenderingContext2D | null = null
     102           31 :   let hasBaseSnapshot = false
     103              : 
     104           31 :   let dirtyX0 = 0
     105           31 :   let dirtyY0 = 0
     106           31 :   let dirtyX1 = 0
     107           31 :   let dirtyY1 = 0
     108           31 :   let hasDirtyRect = false
     109           31 :   let strokeBounds: CanvasRect | null = null
     110              : 
     111           31 :   let strokeBrush: {
     112              :     radius: number
     113              :     effectiveRadius: number
     114              :     effectiveHardness: number
     115              :     hardness: number
     116              :     r: number
     117              :     g: number
     118              :     b: number
     119              :   } | null = null
     120              : 
     121           31 :   const litegraphNode = useLiveGraphNode(() => {
     122           31 :     const location = locateWidgetNode(widget, nodeId)
     123           31 :     return location?.graph.getNodeById(location.nodeId)
     124              :   })
     125              : 
     126           31 :   const widgetValueStore = useWidgetValueStore()
     127              : 
     128           99 :   function storedWidgetValue(name: string): unknown {
     129           99 :     const node = litegraphNode.value
     130           99 :     if (!node) return undefined
     131           99 :     const graphId = node.graph?.rootGraph.id
     132           99 :     return graphId
     133              :       ? widgetValueStore.getWidget(widgetId(graphId, node.id, name))?.value
     134              :       : undefined
     135              :   }
     136              : 
     137            9 :   function writeWidgetValue(name: string, value: number | string): void {
     138            9 :     const node = litegraphNode.value
     139            9 :     const widget = node?.widgets?.find((w) => w.name === name)
     140            9 :     if (!node || !widget || widget.value === value) return
     141            9 :     setNodeWidgetValue(node, name, value)
     142              :   }
     143              : 
     144           62 :   function numberWidgetProjection(name: string, fallback: number) {
     145           62 :     return computed<number>({
     146              :       get: () => {
     147           70 :         const v = storedWidgetValue(name)
     148           70 :         return typeof v === 'number' && v > 0 ? v : fallback
     149              :       },
     150              :       set: (v) => writeWidgetValue(name, v)
     151              :     })
     152              :   }
     153              : 
     154           31 :   const canvasWidth = numberWidgetProjection('width', 512)
     155           31 :   const canvasHeight = numberWidgetProjection('height', 512)
     156           31 :   const backgroundColor = computed<string>({
     157              :     get: () => {
     158           29 :       const v = storedWidgetValue('bg_color')
     159           29 :       return typeof v === 'string' ? v : '#000000'
     160              :     },
     161              :     set: (v) => writeWidgetValue('bg_color', v)
     162              :   })
     163              : 
     164           31 :   const tool = ref<PainterTool>(PAINTER_TOOLS.BRUSH)
     165           31 :   const brushSize = ref(20)
     166           31 :   const brushColor = ref('#ffffff')
     167           31 :   const brushOpacity = ref(1)
     168           31 :   const brushHardness = ref(1)
     169              : 
     170           31 :   function restoreSettingsFromProperties() {
     171           31 :     const node = litegraphNode.value
     172           31 :     if (!node) return
     173              : 
     174           31 :     const props = node.properties
     175           31 :     if (props.painterTool != null) tool.value = props.painterTool as PainterTool
     176           31 :     if (props.painterBrushSize != null)
     177            0 :       brushSize.value = props.painterBrushSize as number
     178           31 :     if (props.painterBrushColor != null)
     179            0 :       brushColor.value = props.painterBrushColor as string
     180           31 :     if (props.painterBrushOpacity != null)
     181            0 :       brushOpacity.value = props.painterBrushOpacity as number
     182           31 :     if (props.painterBrushHardness != null)
     183            0 :       brushHardness.value = props.painterBrushHardness as number
     184              :   }
     185              : 
     186           38 :   function saveSettingsToProperties() {
     187           38 :     const node = litegraphNode.value
     188           38 :     if (!node) return
     189              : 
     190           38 :     node.properties.painterTool = tool.value
     191           38 :     node.properties.painterBrushSize = brushSize.value
     192           38 :     node.properties.painterBrushColor = brushColor.value
     193           38 :     node.properties.painterBrushOpacity = brushOpacity.value
     194           38 :     node.properties.painterBrushHardness = brushHardness.value
     195              :   }
     196              : 
     197           31 :   const imageInputSlot = computed(
     198              :     () => litegraphNode.value?.findInputSlot('image') ?? -1
     199              :   )
     200              : 
     201           31 :   const isImageInputConnected = computed(() => {
     202           31 :     const node = litegraphNode.value
     203           31 :     if (!node || imageInputSlot.value < 0) return false
     204           31 :     return isWidgetInputConnected(node, imageInputSlot.value, nodeId)
     205              :   })
     206              : 
     207           31 :   const inputImageUrl = computed<string | null>(() => {
     208           31 :     const node = litegraphNode.value
     209           31 :     if (!node || imageInputSlot.value < 0) return null
     210           31 :     const source = resolveWidgetInputSource(node, imageInputSlot.value, nodeId)
     211           31 :     return source
     212              :       ? (nodeOutputStore.getNodeImageUrls(source)?.[0] ?? null)
     213              :       : null
     214              :   })
     215              : 
     216           88 :   function activeHardness(): number {
     217           88 :     return tool.value === PAINTER_TOOLS.ERASER ? 1 : brushHardness.value
     218              :   }
     219              : 
     220           31 :   const { width: canvasDisplayWidth } = useElementSize(canvasEl)
     221              : 
     222           31 :   const displayBrushSize = computed(() => {
     223          134 :     if (!canvasDisplayWidth.value || !canvasWidth.value) return brushSize.value
     224              : 
     225           72 :     const radius = brushSize.value / 2
     226              :     const effectiveRadius = getEffectiveBrushSize(radius, activeHardness())
     227              :     const effectiveDiameter = effectiveRadius * 2
     228           72 :     return effectiveDiameter * (canvasDisplayWidth.value / canvasWidth.value)
     229              :   })
     230              : 
     231           31 :   const history = usePainterHistory({
     232              :     scope: historyScope,
     233              :     context: getCtx,
     234              :     canRestore: () => !isDrawing,
     235              :     onRestore: () => {
     236            0 :       isDirty.value = true
     237              :     }
     238              :   })
     239              : 
     240          227 :   function getCtx() {
     241          227 :     if (!mainCtx && canvasEl.value) {
     242           36 :       mainCtx = canvasEl.value.getContext('2d') ?? null
     243              :     }
     244          227 :     return mainCtx
     245              :   }
     246              : 
     247           16 :   function cacheCanvasRect() {
     248           16 :     const el = canvasEl.value
     249           16 :     if (el) cachedRect = el.getBoundingClientRect()
     250              :   }
     251              : 
     252          173 :   function getCanvasPoint(e: PointerEvent): Point | null {
     253          173 :     const el = canvasEl.value
     254          173 :     if (!el) return null
     255          173 :     const rect = cachedRect ?? el.getBoundingClientRect()
     256          173 :     return {
     257              :       x: ((e.clientX - rect.left) / rect.width) * el.width,
     258              :       y: ((e.clientY - rect.top) / rect.height) * el.height
     259              :     }
     260              :   }
     261              : 
     262         1474 :   function expandStrokeBounds(x0: number, y0: number, x1: number, y1: number) {
     263         1474 :     const bounds = strokeBounds
     264         1474 :     if (!bounds) {
     265           16 :       strokeBounds = { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
     266           16 :       return
     267              :     }
     268         1458 :     const left = Math.min(bounds.x, x0)
     269         1458 :     const top = Math.min(bounds.y, y0)
     270         1458 :     strokeBounds = {
     271              :       x: left,
     272              :       y: top,
     273              :       width: Math.max(bounds.x + bounds.width, x1) - left,
     274              :       height: Math.max(bounds.y + bounds.height, y1) - top
     275              :     }
     276              :   }
     277              : 
     278         1474 :   function expandDirtyRect(cx: number, cy: number, r: number) {
     279         1474 :     const x0 = cx - r
     280         1474 :     const y0 = cy - r
     281         1474 :     const x1 = cx + r
     282         1474 :     const y1 = cy + r
     283         1474 :     expandStrokeBounds(x0, y0, x1, y1)
     284         1474 :     if (!hasDirtyRect) {
     285          189 :       dirtyX0 = x0
     286          189 :       dirtyY0 = y0
     287          189 :       dirtyX1 = x1
     288          189 :       dirtyY1 = y1
     289          189 :       hasDirtyRect = true
     290              :     } else {
     291         1285 :       if (x0 < dirtyX0) dirtyX0 = x0
     292         1285 :       if (y0 < dirtyY0) dirtyY0 = y0
     293         1285 :       if (x1 > dirtyX1) dirtyX1 = x1
     294         1285 :       if (y1 > dirtyY1) dirtyY1 = y1
     295              :     }
     296              :   }
     297              : 
     298           16 :   function snapshotBrush() {
     299           16 :     const radius = brushSize.value / 2
     300           16 :     const hardness = activeHardness()
     301           16 :     const effectiveRadius = getEffectiveBrushSize(radius, hardness)
     302           16 :     strokeBrush = {
     303              :       radius,
     304              :       effectiveRadius,
     305              :       effectiveHardness: getEffectiveHardness(
     306              :         radius,
     307              :         hardness,
     308              :         effectiveRadius
     309              :       ),
     310              :       hardness,
     311              :       ...hexToRgb(brushColor.value)
     312              :     }
     313              :   }
     314              : 
     315          745 :   function drawCircle(ctx: CanvasRenderingContext2D, point: Point) {
     316          745 :     const b = strokeBrush!
     317              : 
     318          745 :     expandDirtyRect(point.x, point.y, b.effectiveRadius)
     319              : 
     320          745 :     ctx.beginPath()
     321          745 :     ctx.arc(point.x, point.y, b.effectiveRadius, 0, Math.PI * 2)
     322              : 
     323          745 :     if (b.hardness < 1) {
     324            0 :       const gradient = ctx.createRadialGradient(
     325              :         point.x,
     326              :         point.y,
     327              :         0,
     328              :         point.x,
     329              :         point.y,
     330              :         b.effectiveRadius
     331              :       )
     332            0 :       gradient.addColorStop(0, `rgba(${b.r}, ${b.g}, ${b.b}, 1)`)
     333            0 :       gradient.addColorStop(
     334              :         b.effectiveHardness,
     335              :         `rgba(${b.r}, ${b.g}, ${b.b}, 1)`
     336              :       )
     337            0 :       gradient.addColorStop(1, `rgba(${b.r}, ${b.g}, ${b.b}, 0)`)
     338            0 :       ctx.fillStyle = gradient
     339              :     }
     340              : 
     341          745 :     ctx.fill()
     342              :   }
     343              : 
     344          729 :   function drawSegment(ctx: CanvasRenderingContext2D, from: Point, to: Point) {
     345          729 :     const b = strokeBrush!
     346              : 
     347          729 :     if (b.hardness < 1) {
     348            0 :       const dx = to.x - from.x
     349            0 :       const dy = to.y - from.y
     350            0 :       const dist = Math.hypot(dx, dy)
     351            0 :       const step = Math.max(1, b.effectiveRadius / 2)
     352              : 
     353            0 :       if (dist > 0) {
     354            0 :         const steps = Math.ceil(dist / step)
     355            0 :         const dabPoint: Point = { x: 0, y: 0 }
     356            0 :         for (let i = 1; i <= steps; i++) {
     357            0 :           const t = i / steps
     358            0 :           dabPoint.x = from.x + dx * t
     359            0 :           dabPoint.y = from.y + dy * t
     360            0 :           drawCircle(ctx, dabPoint)
     361              :         }
     362              :       }
     363              :     } else {
     364          729 :       expandDirtyRect(from.x, from.y, b.effectiveRadius)
     365          729 :       ctx.beginPath()
     366          729 :       ctx.moveTo(from.x, from.y)
     367          729 :       ctx.lineTo(to.x, to.y)
     368          729 :       ctx.stroke()
     369          729 :       drawCircle(ctx, to)
     370              :     }
     371              :   }
     372              : 
     373          189 :   function applyBrushStyle(ctx: CanvasRenderingContext2D) {
     374          189 :     const b = strokeBrush!
     375          189 :     const color = `rgb(${b.r}, ${b.g}, ${b.b})`
     376              : 
     377          189 :     ctx.globalCompositeOperation = 'source-over'
     378          189 :     ctx.globalAlpha = 1
     379          189 :     ctx.fillStyle = color
     380          189 :     ctx.strokeStyle = color
     381          189 :     ctx.lineWidth = b.effectiveRadius * 2
     382          189 :     ctx.lineCap = 'round'
     383          189 :     ctx.lineJoin = 'round'
     384              :   }
     385              : 
     386           16 :   function ensureStrokeCanvas() {
     387           16 :     const el = canvasEl.value
     388           16 :     if (!el) return null
     389              : 
     390           16 :     if (
     391              :       !strokeCanvas ||
     392              :       strokeCanvas.width !== el.width ||
     393              :       strokeCanvas.height !== el.height
     394              :     ) {
     395           13 :       strokeCanvas = document.createElement('canvas')
     396           13 :       strokeCanvas.width = el.width
     397           13 :       strokeCanvas.height = el.height
     398           13 :       strokeCtx = strokeCanvas.getContext('2d')
     399              :     }
     400              : 
     401           16 :     strokeCtx?.clearRect(0, 0, strokeCanvas.width, strokeCanvas.height)
     402           16 :     return strokeCtx
     403              :   }
     404              : 
     405           16 :   function ensureBaseCanvas() {
     406           16 :     const el = canvasEl.value
     407           16 :     if (!el) return null
     408              : 
     409           16 :     if (
     410              :       !baseCanvas ||
     411              :       baseCanvas.width !== el.width ||
     412              :       baseCanvas.height !== el.height
     413              :     ) {
     414           13 :       baseCanvas = document.createElement('canvas')
     415           13 :       baseCanvas.width = el.width
     416           13 :       baseCanvas.height = el.height
     417           13 :       baseCtx = baseCanvas.getContext('2d')
     418              :     }
     419              : 
     420           16 :     return baseCtx
     421              :   }
     422              : 
     423          189 :   function compositeStrokeToMain(isPreview: boolean = false) {
     424          189 :     const el = canvasEl.value
     425          189 :     const ctx = getCtx()
     426          189 :     if (!el || !ctx || !strokeCanvas) return
     427              : 
     428          189 :     const useDirty = hasDirtyRect
     429          189 :     const sx = Math.max(0, Math.floor(dirtyX0))
     430          189 :     const sy = Math.max(0, Math.floor(dirtyY0))
     431          189 :     const sr = Math.min(el.width, Math.ceil(dirtyX1))
     432          189 :     const sb = Math.min(el.height, Math.ceil(dirtyY1))
     433          189 :     const sw = sr - sx
     434          189 :     const sh = sb - sy
     435          189 :     hasDirtyRect = false
     436              : 
     437          189 :     if (hasBaseSnapshot && baseCanvas) {
     438          189 :       if (useDirty && sw > 0 && sh > 0) {
     439          189 :         ctx.clearRect(sx, sy, sw, sh)
     440          189 :         ctx.drawImage(baseCanvas, sx, sy, sw, sh, sx, sy, sw, sh)
     441              :       } else {
     442            0 :         ctx.clearRect(0, 0, el.width, el.height)
     443            0 :         ctx.drawImage(baseCanvas, 0, 0)
     444              :       }
     445              :     }
     446              : 
     447          189 :     ctx.save()
     448          189 :     const isEraser = tool.value === PAINTER_TOOLS.ERASER
     449          189 :     ctx.globalAlpha = isEraser ? 1 : brushOpacity.value
     450          189 :     ctx.globalCompositeOperation = isEraser ? 'destination-out' : 'source-over'
     451          189 :     if (useDirty && sw > 0 && sh > 0) {
     452          189 :       ctx.drawImage(strokeCanvas, sx, sy, sw, sh, sx, sy, sw, sh)
     453              :     } else {
     454            0 :       ctx.drawImage(strokeCanvas, 0, 0)
     455              :     }
     456          189 :     ctx.restore()
     457              : 
     458          189 :     if (!isPreview) {
     459           16 :       hasBaseSnapshot = false
     460              :     }
     461              :   }
     462              : 
     463           16 :   function startStroke(e: PointerEvent) {
     464           16 :     const point = getCanvasPoint(e)
     465           16 :     if (!point || history.isRestoring()) return
     466              : 
     467           16 :     const el = canvasEl.value
     468           16 :     if (!el) return
     469              : 
     470           16 :     const bCtx = ensureBaseCanvas()
     471           16 :     if (bCtx) {
     472           16 :       bCtx.clearRect(0, 0, el.width, el.height)
     473           16 :       bCtx.drawImage(el, 0, 0)
     474           16 :       hasBaseSnapshot = true
     475              :     }
     476              : 
     477           16 :     isDrawing = true
     478           16 :     isDirty.value = true
     479           16 :     pendingMaskImage = null
     480           16 :     strokeBounds = null
     481           16 :     snapshotBrush()
     482           16 :     strokeProcessor = new StrokeProcessor(Math.max(1, strokeBrush!.radius / 2))
     483           16 :     strokeProcessor.addPoint(point)
     484           16 :     lastPoint = point
     485              : 
     486           16 :     const ctx = ensureStrokeCanvas()
     487           16 :     if (!ctx) return
     488           16 :     ctx.save()
     489           16 :     applyBrushStyle(ctx)
     490           16 :     drawCircle(ctx, point)
     491           16 :     ctx.restore()
     492              : 
     493           16 :     compositeStrokeToMain(true)
     494              :   }
     495              : 
     496          157 :   function continueStroke(e: PointerEvent) {
     497          157 :     if (!isDrawing || !strokeProcessor || !strokeCtx) return
     498              : 
     499          157 :     const point = getCanvasPoint(e)
     500          157 :     if (!point) return
     501              : 
     502          157 :     const points = strokeProcessor.addPoint(point)
     503          157 :     if (points.length === 0 && lastPoint) {
     504           16 :       points.push(point)
     505              :     }
     506              : 
     507          157 :     if (points.length === 0) return
     508              : 
     509          157 :     strokeCtx.save()
     510          157 :     applyBrushStyle(strokeCtx)
     511              : 
     512          157 :     let prev = lastPoint ?? points[0]
     513          157 :     for (const p of points) {
     514          625 :       drawSegment(strokeCtx, prev, p)
     515          625 :       prev = p
     516              :     }
     517          157 :     lastPoint = prev
     518              : 
     519          157 :     strokeCtx.restore()
     520              : 
     521          157 :     compositeStrokeToMain(true)
     522              :   }
     523              : 
     524           19 :   function endStroke() {
     525           19 :     if (!isDrawing || !strokeProcessor) return
     526              : 
     527           16 :     const points = strokeProcessor.endStroke()
     528           19 :     if (strokeCtx && points.length > 0) {
     529           16 :       strokeCtx.save()
     530           16 :       applyBrushStyle(strokeCtx)
     531           16 :       let prev = lastPoint ?? points[0]
     532           16 :       for (const p of points) {
     533          104 :         drawSegment(strokeCtx, prev, p)
     534          104 :         prev = p
     535              :       }
     536           16 :       strokeCtx.restore()
     537              :     }
     538              : 
     539           16 :     compositeStrokeToMain()
     540           16 :     recordStroke()
     541              : 
     542           16 :     isDrawing = false
     543           16 :     strokeProcessor = null
     544           16 :     strokeBrush = null
     545           16 :     lastPoint = null
     546              :   }
     547              : 
     548           16 :   function recordStroke() {
     549           16 :     const el = canvasEl.value
     550           16 :     const rect = el && strokeBounds && clampCanvasRect(strokeBounds, el)
     551           16 :     strokeBounds = null
     552           16 :     const before = baseCanvas
     553           16 :     if (!rect || !before) return
     554           16 :     history.record(() => captureCanvasRegion(before, rect))
     555              :   }
     556              : 
     557           36 :   function resizeCanvas() {
     558           36 :     const el = canvasEl.value
     559           36 :     if (!el) return
     560              : 
     561           36 :     let tmp: HTMLCanvasElement | null = null
     562           36 :     if (el.width > 0 && el.height > 0) {
     563           36 :       tmp = document.createElement('canvas')
     564           36 :       tmp.width = el.width
     565           36 :       tmp.height = el.height
     566           36 :       tmp.getContext('2d')!.drawImage(el, 0, 0)
     567              :     }
     568              : 
     569           36 :     el.width = canvasWidth.value
     570           36 :     el.height = canvasHeight.value
     571           36 :     mainCtx = null
     572              : 
     573           36 :     if (tmp) {
     574           36 :       getCtx()?.drawImage(tmp, 0, 0)
     575              :     }
     576              : 
     577           36 :     strokeCanvas = null
     578           36 :     strokeCtx = null
     579           36 :     baseCanvas = null
     580           36 :     baseCtx = null
     581           36 :     hasBaseSnapshot = false
     582              :   }
     583              : 
     584            2 :   function handleClear() {
     585            2 :     const el = canvasEl.value
     586            2 :     const ctx = getCtx()
     587            2 :     if (!el || !ctx) return
     588            2 :     const rect = clampCanvasRect(
     589              :       { x: 0, y: 0, width: el.width, height: el.height },
     590              :       el
     591              :     )
     592            2 :     if (rect) history.record(() => captureCanvasRegion(el, rect))
     593            2 :     ctx.clearRect(0, 0, el.width, el.height)
     594            2 :     isDirty.value = true
     595            2 :     pendingMaskImage = null
     596            2 :     canvasMask = ''
     597            2 :     modelValue.value = ''
     598              :   }
     599              : 
     600            0 :   function clearToEmptyMask() {
     601            0 :     const el = canvasEl.value
     602            0 :     const ctx = getCtx()
     603            0 :     if (!el || !ctx) return
     604            0 :     ctx.clearRect(0, 0, el.width, el.height)
     605            0 :     pendingMaskImage = null
     606            0 :     canvasMask = ''
     607              :   }
     608              : 
     609          194 :   function updateCursorPos(e: PointerEvent) {
     610          194 :     const el = cursorEl.value
     611          194 :     if (!el) return
     612          194 :     const size = displayBrushSize.value
     613          194 :     el.style.transform = `translate(${e.offsetX - size / 2}px, ${e.offsetY - size / 2}px)`
     614              :   }
     615              : 
     616           16 :   function handlePointerDown(e: PointerEvent) {
     617           16 :     if (e.button !== 0) return
     618           16 :     cacheCanvasRect()
     619           16 :     updateCursorPos(e)
     620           16 :     startStroke(e)
     621           16 :     capturePointerIfActive(e)
     622              :   }
     623              : 
     624           31 :   let pendingMoveEvent: PointerEvent | null = null
     625           31 :   let rafId: number | null = null
     626              : 
     627          157 :   function flushPendingStroke() {
     628          157 :     if (pendingMoveEvent) {
     629          157 :       continueStroke(pendingMoveEvent)
     630          157 :       pendingMoveEvent = null
     631              :     }
     632          157 :     rafId = null
     633              :   }
     634              : 
     635          178 :   function handlePointerMove(e: PointerEvent) {
     636          178 :     updateCursorPos(e)
     637          178 :     if (!isDrawing) return
     638              : 
     639          161 :     pendingMoveEvent = e
     640          161 :     if (!rafId) {
     641          157 :       rafId = requestAnimationFrame(flushPendingStroke)
     642              :     }
     643              :   }
     644              : 
     645           16 :   function handlePointerUp(e: PointerEvent) {
     646           16 :     if (e.button !== 0) return
     647           16 :     if (rafId) {
     648            1 :       cancelAnimationFrame(rafId)
     649            1 :       flushPendingStroke()
     650              :     }
     651           16 :     releasePointerIfCaptured(e)
     652           16 :     endStroke()
     653              :   }
     654              : 
     655            3 :   function handlePointerLeave() {
     656            3 :     cursorVisible.value = false
     657            3 :     if (rafId) {
     658            0 :       cancelAnimationFrame(rafId)
     659            0 :       flushPendingStroke()
     660              :     }
     661            3 :     endStroke()
     662              :   }
     663              : 
     664           14 :   function handlePointerEnter() {
     665           14 :     cursorVisible.value = true
     666              :   }
     667              : 
     668            3 :   function handleInputImageLoad(e: Event) {
     669            3 :     const img = e.target as HTMLImageElement
     670            3 :     canvasWidth.value = img.naturalWidth
     671            3 :     canvasHeight.value = img.naturalHeight
     672              :   }
     673              : 
     674           31 :   function parseMaskFilename(value: string): {
     675              :     filename: string
     676              :     subfolder: string
     677              :     type: string
     678              :   } | null {
     679           31 :     const trimmed = value.trim()
     680           31 :     if (!trimmed) return null
     681              : 
     682            0 :     const typeMatch = trimmed.match(/^(.+?) \[([^\]]+)\]$/)
     683           31 :     const pathPart = typeMatch ? typeMatch[1] : trimmed
     684           31 :     const type = typeMatch ? typeMatch[2] : 'input'
     685              : 
     686           31 :     const lastSlash = pathPart.lastIndexOf('/')
     687           31 :     const subfolder = lastSlash !== -1 ? pathPart.substring(0, lastSlash) : ''
     688              :     const filename =
     689              :       lastSlash !== -1 ? pathPart.substring(lastSlash + 1) : pathPart
     690              : 
     691           31 :     return { filename, subfolder, type }
     692              :   }
     693              : 
     694            6 :   async function serializeValue(): Promise<string> {
     695            6 :     const el = canvasEl.value
     696            6 :     if (!el) return modelValue.value
     697              : 
     698            6 :     if (!isDirty.value && modelValue.value) return modelValue.value
     699              : 
     700            5 :     const blob = await new Promise<Blob | null>((resolve) =>
     701              :       el.toBlob(resolve, 'image/png')
     702              :     )
     703            6 :     if (!blob) return modelValue.value
     704              : 
     705            5 :     const name = `painter-${nodeId}-${Date.now()}.png`
     706            5 :     const body = new FormData()
     707            5 :     body.append('image', blob, name)
     708            5 :     body.append('type', 'input')
     709              : 
     710            5 :     let resp: Response
     711            6 :     try {
     712            5 :       resp = await api.fetchApi('/upload/image', {
     713              :         method: 'POST',
     714              :         body
     715              :       })
     716              :     } catch (e) {
     717            0 :       const err = t('painter.uploadError', {
     718              :         status: 0,
     719              :         statusText: getErrorMessage(e) ?? t('g.unknownError')
     720              :       })
     721            0 :       toast.warning(err)
     722            0 :       throw new Error(err, { cause: e })
     723              :     }
     724              : 
     725            6 :     if (resp.status !== 200) {
     726            1 :       const bodyText = await resp.text().catch(() => '')
     727            1 :       const err = t('painter.uploadError', {
     728              :         status: resp.status,
     729              :         statusText: bodyText || resp.statusText || 'unknown error'
     730              :       })
     731            1 :       toast.warning(err)
     732            1 :       throw new Error(err)
     733              :     }
     734              : 
     735            4 :     let data: UploadImageResponse
     736            5 :     try {
     737            4 :       data = await resp.json()
     738              :     } catch (e) {
     739            0 :       const err = t('painter.uploadError', {
     740              :         status: resp.status,
     741              :         statusText: getErrorMessage(e) ?? t('g.unknownError')
     742              :       })
     743            0 :       toast.warning(err)
     744            0 :       throw new Error(err, { cause: e })
     745              :     }
     746              : 
     747            5 :     if (!data.name) {
     748            0 :       toast.warning(t('painter.uploadMissingName'))
     749            0 :       throw new Error(
     750              :         `Painter upload succeeded (${resp.status}) but response is missing 'name'`
     751              :       )
     752              :     }
     753              : 
     754            4 :     const result = `${data.name} [input]`
     755            4 :     canvasMask = result
     756            4 :     modelValue.value = result
     757            4 :     isDirty.value = false
     758            4 :     return result
     759              :   }
     760              : 
     761           31 :   function registerWidgetSerialization() {
     762           31 :     const node = litegraphNode.value
     763           31 :     if (!node?.widgets) return
     764           31 :     const targetWidget = node.widgets.find(
     765              :       (w: IBaseWidget) => w.name === 'mask'
     766              :     )
     767           31 :     if (targetWidget) {
     768           31 :       targetWidget.serializeValue = serializeValue
     769              :     }
     770              :   }
     771              : 
     772           31 :   function restoreCanvas() {
     773           31 :     const requestedMask = modelValue.value
     774           31 :     const parsed = parseMaskFilename(requestedMask)
     775           31 :     if (!parsed) return
     776              : 
     777            0 :     const params = new URLSearchParams()
     778            0 :     params.set('filename', parsed.filename)
     779            0 :     if (parsed.subfolder) params.set('subfolder', parsed.subfolder)
     780            0 :     params.set('type', parsed.type)
     781              : 
     782            0 :     const url = api.apiURL('/view?' + params.toString())
     783            0 :     const img = new Image()
     784            0 :     pendingMaskImage = img
     785            0 :     const isStillWanted = () =>
     786              :       pendingMaskImage === img && modelValue.value === requestedMask
     787            0 :     img.crossOrigin = 'anonymous'
     788            0 :     img.onload = () => {
     789            0 :       const el = canvasEl.value
     790            0 :       if (!el || !isStillWanted()) return
     791            0 :       pendingMaskImage = null
     792            0 :       canvasWidth.value = img.naturalWidth
     793            0 :       canvasHeight.value = img.naturalHeight
     794            0 :       el.width = img.naturalWidth
     795            0 :       el.height = img.naturalHeight
     796            0 :       mainCtx = null
     797            0 :       getCtx()?.drawImage(img, 0, 0)
     798            0 :       canvasMask = requestedMask
     799            0 :       isDirty.value = false
     800              :     }
     801            0 :     img.onerror = () => {
     802            0 :       if (!isStillWanted()) return
     803            0 :       pendingMaskImage = null
     804            0 :       modelValue.value = ''
     805              :     }
     806            0 :     img.src = url
     807              :   }
     808              : 
     809           31 :   watch(modelValue, (mask) => {
     810            4 :     if (mask === canvasMask) return
     811            0 :     history.discard()
     812            0 :     if (mask) restoreCanvas()
     813            0 :     else clearToEmptyMask()
     814              :   })
     815              : 
     816           31 :   watch(litegraphNode, () => {
     817            0 :     registerWidgetSerialization()
     818            0 :     restoreSettingsFromProperties()
     819              :   })
     820           31 :   watch([canvasWidth, canvasHeight], () => {
     821            5 :     resizeCanvas()
     822            5 :     history.discard()
     823              :   })
     824              : 
     825           31 :   watch(
     826              :     [tool, brushSize, brushColor, brushOpacity, brushHardness],
     827              :     saveSettingsToProperties
     828              :   )
     829              : 
     830           31 :   function initialize() {
     831           31 :     resizeCanvas()
     832           31 :     registerWidgetSerialization()
     833           31 :     restoreSettingsFromProperties()
     834           31 :     restoreCanvas()
     835              :   }
     836              : 
     837           31 :   onMounted(initialize)
     838              : 
     839           31 :   onUnmounted(() => {
     840            0 :     if (rafId) {
     841            0 :       cancelAnimationFrame(rafId)
     842            0 :       rafId = null
     843              :     }
     844            0 :     history.discard()
     845              :   })
     846              : 
     847           31 :   return {
     848              :     tool,
     849              :     brushSize,
     850              :     brushColor,
     851              :     brushOpacity,
     852              :     brushHardness,
     853              :     backgroundColor,
     854              : 
     855              :     canvasWidth,
     856              :     canvasHeight,
     857              : 
     858              :     cursorVisible,
     859              :     displayBrushSize,
     860              : 
     861              :     inputImageUrl,
     862              :     isImageInputConnected,
     863              : 
     864              :     handlePointerDown,
     865              :     handlePointerMove,
     866              :     handlePointerUp,
     867              :     handlePointerEnter,
     868              :     handlePointerLeave,
     869              : 
     870              :     handleInputImageLoad,
     871              :     handleClear,
     872              : 
     873              :     canUndo: history.canUndo,
     874              :     canRedo: history.canRedo,
     875              :     undo: history.undo,
     876              :     redo: history.redo
     877              :   }
     878              : }
        

Generated by: LCOV version 2.0-1