Line data Source code
1 : import { useThrottleFn } from '@vueuse/core'
2 : import { ref } from 'vue'
3 : import type { Ref } from 'vue'
4 :
5 : import { useChainCallback } from '@/composables/functional/useChainCallback'
6 : import type { LGraphEventMap } from '@comfyorg/graph-model/LGraphEventMap'
7 : import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
8 : import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
9 : import { api } from '@/scripts/api'
10 : import { useExecutionStore } from '@/stores/executionStore'
11 :
12 : import type { UpdateFlags } from '@/renderer/extensions/minimap/types'
13 :
14 : interface GraphCallbacks {
15 : onConnectionChange?: (node: LGraphNode) => void
16 : }
17 :
18 : /**
19 : * Fixed-point quantisation for digest input, at eighth-pixel precision.
20 : * Mixing raw values would truncate at each `| 0`, so a drag or resize that
21 : * only changes the fractional part would leave the digest unchanged.
22 : */
23 571132 : function quantise(value: number): number {
24 571132 : return Math.round(value * 8)
25 : }
26 :
27 : /**
28 : * Mixes one term into a rolling digest.
29 : *
30 : * The coercion is on the term, not the sum: `(digest + NaN) | 0` is 0, which
31 : * would discard every node mixed in so far and make an unrelated change
32 : * invisible for as long as the non-finite value stays in the graph.
33 : */
34 1785085 : function mixIn(digest: number, value: number): number {
35 1785085 : return (Math.imul(digest, 31) + (Number.isFinite(value) ? value : 0)) | 0
36 : }
37 :
38 : /**
39 : * Cheap string hash for digest input (colors, execution states).
40 : */
41 1207 : function hashString(value: string): number {
42 1207 : let hash = value.length
43 1207 : for (let i = 0; i < value.length; i++) {
44 6402 : hash = (Math.imul(hash, 31) + value.charCodeAt(i)) | 0
45 : }
46 1207 : return hash
47 : }
48 :
49 : interface GraphDigests {
50 : /** Node placement: drives bounds recomputation as well as repaint. */
51 : geometry: number
52 : /** Everything else the renderer draws: repaint only, bounds untouched. */
53 : visual: number
54 : }
55 :
56 : /**
57 : * Rolling digests over everything the minimap renders, in one allocation-free
58 : * pass. The digests are the single authority on "did the picture change":
59 : * event hooks and the poll are only signals to compare them, so any input the
60 : * renderer reads has to be mixed in here or changes to it stop repainting.
61 : *
62 : * Digests can in principle collide, which would drop a single refresh -
63 : * acceptable for an approximate overview, and the next change re-syncs it.
64 : */
65 27260 : function computeGraphDigests(graph: LGraph): GraphDigests {
66 : // Store-side geometry: the renderer reads layoutStore whenever it holds
67 : // nodes, so a write whose write-back to the litegraph node has not landed
68 : // must still count. Geometry version, not layoutVersion - that counts
69 : // operations, and zIndex alone fires one per widget pointerdown.
70 27260 : let geometry = mixIn(layoutStore.nodeGeometryVersion, graph._nodes.length)
71 27260 : let visual = 0
72 :
73 27260 : for (const node of graph._nodes) {
74 142292 : const [x, y] = node.pos
75 142292 : const [width, height] = node.renderingSize
76 142292 : geometry = mixIn(geometry, quantise(x))
77 142292 : geometry = mixIn(geometry, quantise(y))
78 142292 : geometry = mixIn(geometry, quantise(width))
79 142292 : geometry = mixIn(geometry, quantise(height))
80 142292 : visual = mixIn(visual, node.mode)
81 142292 : visual = mixIn(visual, node.has_errors ? 1 : 0)
82 142292 : visual = mixIn(visual, node.bgcolor ? hashString(node.bgcolor) : 0)
83 : }
84 :
85 27260 : for (const group of graph._groups) {
86 491 : visual = mixIn(visual, quantise(group.pos[0]))
87 491 : visual = mixIn(visual, quantise(group.pos[1]))
88 491 : visual = mixIn(visual, quantise(group.size[0]))
89 491 : visual = mixIn(visual, quantise(group.size[1]))
90 491 : visual = mixIn(visual, group.color ? hashString(group.color) : 0)
91 : }
92 :
93 : // Execution state is drawn as discrete outline colors, so mixing the state
94 : // strings repaints exactly on transitions. Progress percentages are not
95 : // rendered, which is what lets the per-progress-message watcher go: the
96 : // poll picks up each transition within one tick at no per-message cost.
97 27260 : const progressStates = useExecutionStore().nodeProgressStates
98 27260 : for (const nodeId in progressStates) {
99 181 : const state = Object.hasOwn(progressStates, nodeId)
100 : ? progressStates[nodeId].state
101 : : undefined
102 181 : if (!state) continue
103 181 : visual = mixIn(visual, hashString(nodeId))
104 181 : visual = mixIn(visual, hashString(state))
105 : }
106 :
107 27260 : return { geometry, visual }
108 : }
109 :
110 : /**
111 : * Rolling digest of link endpoints and slots. Counting links alone would miss
112 : * a rewire that keeps the total unchanged, and endpoints alone would miss a
113 : * link moved to a different slot on the same pair of nodes.
114 : */
115 27260 : function computeLinkDigest(graph: LGraph): number {
116 27260 : let digest = 0
117 27260 : for (const link of graph.links.values()) {
118 : // Node ids are branded strings and need not be numeric; non-numeric ones
119 : // contribute 0 here and are caught instead by the onConnectionChange hook.
120 189741 : digest = mixIn(digest, Number(link.origin_id))
121 189741 : digest = mixIn(digest, Number(link.target_id))
122 189741 : digest = mixIn(digest, link.origin_slot)
123 189741 : digest = mixIn(digest, link.target_slot)
124 : }
125 :
126 27260 : return digest
127 : }
128 :
129 2102 : export function useMinimapGraph(
130 : graph: Ref<LGraph | null>,
131 : onGraphChanged: () => void
132 : ) {
133 : // Null rather than a numeric sentinel: 0 is a digest these functions produce
134 : // for an empty graph, so a numeric "no baseline" would be indistinguishable
135 : // from a real first reading.
136 2102 : let geometryDigest: number | null = null
137 2102 : let visualDigest: number | null = null
138 2102 : let linkDigest: number | null = null
139 2102 : const updateFlags = ref<UpdateFlags>({
140 : bounds: false,
141 : nodes: false,
142 : connections: false,
143 : viewport: false
144 : })
145 :
146 : // Cleanup restores originals only when our wrapper is still on top, and
147 : // marks any buried wrapper inert via `entry.live` so it can't fire dead work.
148 : interface InstalledHooks {
149 : originals: GraphCallbacks
150 : wrappers: GraphCallbacks
151 : live: boolean
152 : disposeListeners: () => void
153 : }
154 2102 : const hooksMap = new Map<string, InstalledHooks>()
155 :
156 2102 : const handleGraphChangedThrottled = useThrottleFn(() => {
157 3729 : onGraphChanged()
158 : }, 500)
159 :
160 2102 : const setupEventListeners = () => {
161 2272 : const g = graph.value
162 2272 : if (!g || hooksMap.has(g.id)) return
163 :
164 2272 : const originals: GraphCallbacks = {
165 : onConnectionChange: g.onConnectionChange
166 : }
167 2272 : const wrappers: GraphCallbacks = {}
168 :
169 2272 : const onNodeAdded = () => void handleGraphChangedThrottled()
170 :
171 2272 : const onNodeRemoved = () => {
172 177 : void handleGraphChangedThrottled()
173 : }
174 :
175 : // A reload of the same workflow leaves the node count and every geometry
176 : // string identical, so change detection alone cannot tell that `bounds` was
177 : // last derived mid-configure, from a partially built graph.
178 2272 : const onConfigured = () => {
179 3407 : clearCache()
180 3407 : void handleGraphChangedThrottled()
181 : }
182 :
183 2272 : const onPropertyChanged = (
184 : e: CustomEvent<LGraphEventMap['node:property:changed']>
185 : ) => {
186 18675 : const { property } = e.detail
187 18675 : if (
188 : property === 'mode' ||
189 : property === 'bgcolor' ||
190 : property === 'color'
191 : ) {
192 132 : void handleGraphChangedThrottled()
193 : }
194 : }
195 :
196 2272 : const entry: InstalledHooks = {
197 : originals,
198 : wrappers,
199 : live: true,
200 : disposeListeners: () => {
201 95 : g.events.removeEventListener('node:added', onNodeAdded)
202 95 : g.events.removeEventListener('node:removed', onNodeRemoved)
203 95 : g.events.removeEventListener('configured', onConfigured)
204 95 : g.events.removeEventListener('node:property:changed', onPropertyChanged)
205 : }
206 : }
207 2272 : hooksMap.set(g.id, entry)
208 :
209 2272 : wrappers.onConnectionChange = useChainCallback(
210 : originals.onConnectionChange,
211 : function () {
212 0 : if (!entry.live) return
213 0 : void handleGraphChangedThrottled()
214 : }
215 : )
216 2272 : g.onConnectionChange = wrappers.onConnectionChange
217 :
218 2272 : g.events.addEventListener('node:added', onNodeAdded)
219 2272 : g.events.addEventListener('node:removed', onNodeRemoved)
220 2272 : g.events.addEventListener('configured', onConfigured)
221 2272 : g.events.addEventListener('node:property:changed', onPropertyChanged)
222 : }
223 :
224 2102 : const cleanupEventListeners = (oldGraph?: LGraph) => {
225 238 : const g = oldGraph || graph.value
226 238 : if (!g) return
227 238 : const entry = hooksMap.get(g.id)
228 238 : if (!entry) return
229 95 : const { originals, wrappers } = entry
230 :
231 98 : if (g.onConnectionChange === wrappers.onConnectionChange)
232 92 : g.onConnectionChange = originals.onConnectionChange
233 95 : entry.disposeListeners()
234 :
235 95 : entry.live = false
236 95 : hooksMap.delete(g.id)
237 : }
238 :
239 2102 : const checkForChangesInternal = () => {
240 27260 : const g = graph.value
241 27260 : if (!g) return false
242 :
243 27260 : const { geometry, visual } = computeGraphDigests(g)
244 27260 : const links = computeLinkDigest(g)
245 :
246 27260 : const geometryChanged = geometry !== geometryDigest
247 27260 : const visualChanged = visual !== visualDigest
248 27260 : const connectionChanged = links !== linkDigest
249 :
250 27260 : geometryDigest = geometry
251 27260 : visualDigest = visual
252 27260 : linkDigest = links
253 :
254 : // Only geometry moves the graph's extent; a recolour, group drag or
255 : // execution transition repaints without recomputing bounds.
256 27260 : if (geometryChanged) {
257 7876 : updateFlags.value.bounds = true
258 : }
259 27260 : if (geometryChanged || visualChanged) {
260 8019 : updateFlags.value.nodes = true
261 : }
262 27260 : if (connectionChanged) {
263 6315 : updateFlags.value.connections = true
264 : }
265 :
266 27260 : return geometryChanged || visualChanged || connectionChanged
267 : }
268 :
269 2102 : const init = () => {
270 2102 : setupEventListeners()
271 2102 : api.addEventListener('graphChanged', handleGraphChangedThrottled)
272 : }
273 :
274 2102 : const destroy = () => {
275 68 : cleanupEventListeners()
276 68 : api.removeEventListener('graphChanged', handleGraphChangedThrottled)
277 68 : clearCache()
278 : }
279 :
280 2102 : const clearCache = () => {
281 3475 : geometryDigest = null
282 3475 : visualDigest = null
283 3475 : linkDigest = null
284 : }
285 :
286 2102 : return {
287 : updateFlags,
288 : setupEventListeners,
289 : cleanupEventListeners,
290 : checkForChanges: checkForChangesInternal,
291 : init,
292 : destroy,
293 : clearCache
294 : }
295 : }
|