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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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/**
 * Give a badge on ControlNet Accordion indicating total number of active
 * units.
 * Make active unit's tab name green.
 * Append control type to tab name.
 * Disable resize mode selection when A1111 img2img input is used.
 */
(function () {
    const cnetAllAccordions = new Set();
    onUiUpdate(() => {
        const ImgChangeType = {
            NO_CHANGE: 0,
            REMOVE: 1,
            ADD: 2,
            SRC_CHANGE: 3,
        };

        function imgChangeObserved(mutationsList) {
            // Iterate over all mutations that just occured
            for (let mutation of mutationsList) {
                // Check if the mutation is an addition or removal of a node
                if (mutation.type === 'childList') {
                    // Check if nodes were added
                    if (mutation.addedNodes.length > 0) {
                        for (const node of mutation.addedNodes) {
                            if (node.tagName === 'IMG') {
                                return ImgChangeType.ADD;
                            }
                        }
                    }

                    // Check if nodes were removed
                    if (mutation.removedNodes.length > 0) {
                        for (const node of mutation.removedNodes) {
                            if (node.tagName === 'IMG') {
                                return ImgChangeType.REMOVE;
                            }
                        }
                    }
                }
                // Check if the mutation is a change of an attribute
                else if (mutation.type === 'attributes') {
                    if (mutation.target.tagName === 'IMG' && mutation.attributeName === 'src') {
                        return ImgChangeType.SRC_CHANGE;
                    }
                }
            }
            return ImgChangeType.NO_CHANGE;
        }

        function childIndex(element) {
            // Get all child nodes of the parent
            let children = Array.from(element.parentNode.childNodes);

            // Filter out non-element nodes (like text nodes and comments)
            children = children.filter(child => child.nodeType === Node.ELEMENT_NODE);

            return children.indexOf(element);
        }

        function imageInputDisabledAlert() {
            alert('Inpaint control type must use a1111 input in img2img mode.');
        }

        class ControlNetUnitTab {
            constructor(tab, accordion) {
                this.tab = tab;
                this.tabOpen = false; // Whether the tab is open.
                this.accordion = accordion;
                this.isImg2Img = tab.querySelector('.cnet-mask-upload').id.includes('img2img');

                this.enabledAccordionCheckbox = tab.querySelector('.input-accordion-checkbox');
                this.enabledCheckbox = tab.querySelector('.cnet-unit-enabled input');
                this.inputImage = tab.querySelector('.cnet-input-image-group .cnet-image input[type="file"]');
                this.inputImageContainer = tab.querySelector('.cnet-input-image-group .cnet-image');
                this.generatedImageGroup = tab.querySelector('.cnet-generated-image-group');
                this.maskImageGroup = tab.querySelector('.cnet-mask-image-group');
                this.inputImageGroup = tab.querySelector('.cnet-input-image-group');
                this.controlTypeRadios = tab.querySelectorAll('.controlnet_control_type_filter_group input[type="radio"]');
                this.resizeModeRadios = tab.querySelectorAll('.controlnet_resize_mode_radio input[type="radio"]');
                this.runPreprocessorButton = tab.querySelector('.cnet-run-preprocessor');

                this.tabs = tab.parentNode;
                this.tabIndex = childIndex(tab);

                // By default the InputAccordion checkbox is linked with the state
                // of accordion's open/close state. To disable this link, we can
                // simulate click to check the checkbox and uncheck it.
                this.enabledAccordionCheckbox.click();
                this.enabledAccordionCheckbox.click();

                this.sync_enabled_checkbox();
                this.attachEnabledButtonListener();
                this.attachControlTypeRadioListener();
                this.attachImageUploadListener();
                this.attachImageStateChangeObserver();
                this.attachA1111SendInfoObserver();
                this.attachPresetDropdownObserver();
                this.attachAccordionStateObserver();
            }

            /**
             * Sync the states of enabledCheckbox and enabledAccordionCheckbox.
             */
            sync_enabled_checkbox() {
                this.enabledCheckbox.addEventListener("change", () => {
                    if (this.enabledAccordionCheckbox.checked != this.enabledCheckbox.checked) {
                        this.enabledAccordionCheckbox.click();
                    }
                });
                this.enabledAccordionCheckbox.addEventListener("change", () => {
                    if (this.enabledCheckbox.checked != this.enabledAccordionCheckbox.checked) {
                        this.enabledCheckbox.click();
                    }
                });
            }
            /**
             * Get the span that has text "Unit {X}".
             */
            getUnitHeaderTextElement() {
                return this.tab.querySelector(
                    `:nth-child(${this.tabIndex + 1}) span.svelte-s1r2yt`
                );
            }

            getActiveControlType() {
                for (let radio of this.controlTypeRadios) {
                    if (radio.checked) {
                        return radio.value;
                    }
                }
                return undefined;
            }

            updateActiveState() {
                const unitHeader = this.getUnitHeaderTextElement();
                if (!unitHeader) return;

                if (this.enabledCheckbox.checked) {
                    unitHeader.classList.add('cnet-unit-active');
                } else {
                    unitHeader.classList.remove('cnet-unit-active');
                }
            }

            updateActiveUnitCount() {
                function getActiveUnitCount(checkboxes) {
                    let activeUnitCount = 0;
                    for (const checkbox of checkboxes) {
                        if (checkbox.checked)
                            activeUnitCount++;
                    }
                    return activeUnitCount;
                }

                const checkboxes = this.accordion.querySelectorAll('.cnet-unit-enabled input');
                const span = this.accordion.querySelector('.label-wrap span');

                // Remove existing badge.
                if (span.childNodes.length !== 1) {
                    span.removeChild(span.lastChild);
                }
                // Add new badge if necessary.
                const activeUnitCount = getActiveUnitCount(checkboxes);
                if (activeUnitCount > 0) {
                    const div = document.createElement('div');
                    div.classList.add('cnet-badge');
                    div.classList.add('primary');
                    div.innerHTML = `${activeUnitCount} unit${activeUnitCount > 1 ? 's' : ''}`;
                    span.appendChild(div);
                }
            }

            /**
             * Add the active control type to tab displayed text.
             */
            updateActiveControlType() {
                const unitHeader = this.getUnitHeaderTextElement();
                if (!unitHeader) return;

                // Remove the control if exists
                const controlTypeSuffix = unitHeader.querySelector('.control-type-suffix');
                if (controlTypeSuffix) controlTypeSuffix.remove();

                // Add new suffix.
                const controlType = this.getActiveControlType();
                if (controlType === 'All') return;

                const span = document.createElement('span');
                span.innerHTML = `[${controlType}]`;
                span.classList.add('control-type-suffix');
                unitHeader.appendChild(span);
            }
            getInputImageSrc() {
                const img = this.inputImageGroup.querySelector('.cnet-image img');
                return img ? img.src : null;
            }
            getPreprocessorPreviewImageSrc() {
                const img = this.generatedImageGroup.querySelector('.cnet-image img');
                return img ? img.src : null;
            }
            getMaskImageSrc() {
                function isEmptyCanvas(canvas) {
                    if (!canvas) return true;
                    const ctx = canvas.getContext('2d');
                    // Get the image data
                    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    const data = imageData.data; // This is a Uint8ClampedArray
                    // Check each pixel
                    let isPureBlack = true;
                    for (let i = 0; i < data.length; i += 4) {
                        if (data[i] !== 0 || data[i + 1] !== 0 || data[i + 2] !== 0) { // Check RGB values
                            isPureBlack = false;
                            break;
                        }
                    }
                    return isPureBlack;
                }
                const maskImg = this.maskImageGroup.querySelector('.cnet-mask-image img');
                // Hand-drawn mask on mask upload.
                const handDrawnMaskCanvas = this.maskImageGroup.querySelector('.cnet-mask-image canvas[key="mask"]');
                // Hand-drawn mask on input image upload.
                const inputImageHandDrawnMaskCanvas = this.inputImageGroup.querySelector('.cnet-image canvas[key="mask"]');
                if (!isEmptyCanvas(handDrawnMaskCanvas)) {
                    return handDrawnMaskCanvas.toDataURL();
                } else if (maskImg) {
                    return maskImg.src;
                } else if (!isEmptyCanvas(inputImageHandDrawnMaskCanvas)) {
                    return inputImageHandDrawnMaskCanvas.toDataURL();
                } else {
                    return null;
                }
            }
            setThumbnail(imgSrc, maskSrc) {
                if (!imgSrc) return;
                const unitHeader = this.getUnitHeaderTextElement();
                if (!unitHeader) return;
                const img = document.createElement('img');
                img.src = imgSrc;
                img.classList.add('cnet-thumbnail');
                unitHeader.appendChild(img);

                if (maskSrc) {
                    const mask = document.createElement('img');
                    mask.src = maskSrc;
                    mask.classList.add('cnet-thumbnail');
                    unitHeader.appendChild(mask);
                }
            }
            removeThumbnail() {
                const unitHeader = this.getUnitHeaderTextElement();
                if (!unitHeader) return;
                const imgs = unitHeader.querySelectorAll('.cnet-thumbnail');
                for (const img of imgs) {
                    img.remove();
                }
            }
            /**
             * When the accordion is folded, display a thumbnail of input image
             * and mask on the accordion header.
             */
            updateInputImageThumbnail() {
                if (!opts.controlnet_input_thumbnail) return;
                if (this.tabOpen) {
                    this.removeThumbnail();
                } else {
                    this.setThumbnail(this.getInputImageSrc(), this.getMaskImageSrc());
                }
            }

            attachEnabledButtonListener() {
                this.enabledCheckbox.addEventListener('change', () => {
                    this.updateActiveState();
                    this.updateActiveUnitCount();
                });
            }

            attachControlTypeRadioListener() {
                for (const radio of this.controlTypeRadios) {
                    radio.addEventListener('change', () => {
                        this.updateActiveControlType();
                    });
                }
            }

            attachImageUploadListener() {
                // Automatically check `enable` checkbox when image is uploaded.
                this.inputImage.addEventListener('change', (event) => {
                    if (!event.target.files) return;
                    if (!this.enabledCheckbox.checked)
                        this.enabledCheckbox.click();
                });

                // Automatically check `enable` checkbox when JSON pose file is uploaded.
                this.tab.querySelector('.cnet-upload-pose input').addEventListener('change', (event) => {
                    if (!event.target.files) return;
                    if (!this.enabledCheckbox.checked)
                        this.enabledCheckbox.click();
                });
            }

            attachImageStateChangeObserver() {
                new MutationObserver((mutationsList) => {
                    const changeObserved = imgChangeObserved(mutationsList);

                    if (changeObserved === ImgChangeType.ADD) {
                        // enabling the run preprocessor button
                        this.runPreprocessorButton.removeAttribute("disabled");
                        this.runPreprocessorButton.title = 'Run preprocessor';
                    }

                    if (changeObserved === ImgChangeType.REMOVE) {
                        // disabling the run preprocessor button
                        this.runPreprocessorButton.setAttribute("disabled", true);
                        this.runPreprocessorButton.title = "No ControlNet input image available";
                    }
                }).observe(this.inputImageContainer, {
                    childList: true,
                    subtree: true,
                });
            }

            /**
             * Observe send PNG info buttons in A1111, as they can also directly
             * set states of ControlNetUnit.
             */
            attachA1111SendInfoObserver() {
                const pasteButtons = gradioApp().querySelectorAll('#paste');
                const pngButtons = gradioApp().querySelectorAll(
                    this.isImg2Img ?
                        '#img2img_tab, #inpaint_tab' :
                        '#txt2img_tab'
                );

                for (const button of [...pasteButtons, ...pngButtons]) {
                    button.addEventListener('click', () => {
                        // The paste/send img generation info feature goes
                        // though gradio, which is pretty slow. Ideally we should
                        // observe the event when gradio has done the job, but
                        // that is not an easy task.
                        // Here we just do a 2 second delay until the refresh.
                        setTimeout(() => {
                            this.updateActiveState();
                            this.updateActiveUnitCount();
                        }, 2000);
                    });
                }
            }

            attachPresetDropdownObserver() {
                const presetDropDown = this.tab.querySelector('.cnet-preset-dropdown');

                new MutationObserver((mutationsList) => {
                    for (const mutation of mutationsList) {
                        if (mutation.removedNodes.length > 0) {
                            setTimeout(() => {
                                this.updateActiveState();
                                this.updateActiveUnitCount();
                                this.updateActiveControlType();
                            }, 1000);
                            return;
                        }
                    }
                }).observe(presetDropDown, {
                    childList: true,
                    subtree: true,
                });
            }
            /**
             * Observer that triggers when the ControlNetUnit's accordion(tab) closes.
             */
            attachAccordionStateObserver() {
                new MutationObserver((mutationsList) => {
                    for(const mutation of mutationsList) {
                        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                            const newState = mutation.target.classList.contains('open');
                            if (this.tabOpen != newState) {
                                this.tabOpen = newState;
                                if (newState) {
                                    this.onAccordionOpen();
                                } else {
                                    this.onAccordionClose();
                                }
                            }
                        }
                    }
                }).observe(this.tab.querySelector('.label-wrap'), { attributes: true, attributeFilter: ['class'] });
            }

            onAccordionOpen() {
                this.updateInputImageThumbnail();
            }

            onAccordionClose() {
                this.updateInputImageThumbnail();
            }
        }

        gradioApp().querySelectorAll('#controlnet').forEach(accordion => {
            if (cnetAllAccordions.has(accordion)) return;
            const tabs = [...accordion.querySelectorAll('.input-accordion')]
                .map(tab => new ControlNetUnitTab(tab, accordion));

            // On open of main extension accordion, if no unit is enabled,
            // open unit 0 for edit.
            const labelWrap = accordion.querySelector('.label-wrap');
            const observerAccordionOpen = new MutationObserver(function (mutations) {
                for (const mutation of mutations) {
                    if (mutation.target.classList.contains('open') &&
                        tabs.every(tab => !tab.enabledCheckbox.checked &&
                                          !tab.tab.querySelector('.label-wrap').classList.contains('open'))
                    ) {
                        tabs[0].tab.querySelector('.label-wrap').click();
                    }
                }
            });
            observerAccordionOpen.observe(labelWrap, { attributes: true, attributeFilter: ['class'] });

            cnetAllAccordions.add(accordion);
        });
    });
})();