Compare commits

...
5 changed files with 214 additions and 1 deletions
+7
View File
@@ -4,6 +4,13 @@ All notable changes to ComfyUI-AusBoss are documented here.
## Unreleased
- **Copy a crop node's picture without its handles.** Right-click the picture
on Image Crop + Rotate + Pad and choose Copy image. By default it copies
the original picture. To include crop, rotation, padding and resize, turn
on Copy with crop, rotation and padding in the gear menu. Editing controls
and guides are never copied. Open image provides a clean
picture to copy with the browser on plain HTTP addresses too.
- **The "AusBoss was updated" message no longer asks for a reload by
mistake.** After the Manager switched the pack to another version, a
page reload before ComfyUI restarted brought up the message, telling you
@@ -24,6 +24,15 @@ pan. **Save & close** keeps your edits. **Cancel** or Escape puts everything
back, and asks first if anything changed. You do not need the editor: a run
uses what the node shows.
Right-click the picture and choose **Copy image** to copy the original picture,
without added padding, rotation, crop, resize, handles or guides. To include
your edits, open the gear and turn on **Copy with crop, rotation and padding**.
That also includes resize, and is remembered for this browser. **Open image**
follows the same choice. This works on the node and in the editor.
Direct copying needs localhost or HTTPS. On a plain HTTP address, choose
**Open image**, then right-click that
picture and use the browser's **Copy image**.
## On the node
From top to bottom:
+65 -1
View File
@@ -82,6 +82,7 @@ import {
} from "./transform_geometry.mjs";
import { clampFrame, clipInfo, frameTime } from "./timeline_math.mjs";
import { liftSocket } from "./widget_card.mjs";
import { COPY_EDITS_SETTING, copyPicture, transformPicture } from "./transform_picture.mjs";
const HIDDEN_WIDGETS = [
"image", "upload",
@@ -107,7 +108,7 @@ const RESIZE_METHODS = ["lanczos", "area", "bicubic", "bilinear", "nearest-exact
const TRANSFORM_DEFAULTS = resetTransformValues(false);
const CORE_IMAGE_PREVIEW_WIDGET = "$$canvas-image-preview";
// The gear on the image node's source card. Display choices only, kept for
// The gear on the image node's source card. Browser preferences, kept for
// every image node on this browser (settings_menu.mjs stores them).
const SETTINGS_SCOPE = "image_crop_rotate_pad";
const SETTINGS_SCHEMA = [
@@ -115,6 +116,7 @@ const SETTINGS_SCHEMA = [
key: "show_mask", label: "Show the mask on the picture", type: "toggle", default: true,
hint: "Teal over the parts of your picture the model paints: a mask drawn in the MaskEditor, or see-through parts of a PNG.",
},
COPY_EDITS_SETTING,
];
let transformSettings = null;
function settings() {
@@ -3106,6 +3108,68 @@ function drawRotateGlyph(context, x, y, radius, color) {
// node itself can still drag, and pointercancel plus mouseleave both end a
// gesture in case the capture was refused.
function attachStageHandlers(state, canvas, signal) {
if (state.kind === "image") {
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault(); event.stopPropagation();
if (!state.image) return;
const picture = async () => {
let source = state.image;
const sourceWidth = state.sourceWidth, sourceHeight = state.sourceHeight;
const current = values(state.node), resize = resizeRequest(state.node);
const includeEdits = settings().copy_edits;
if (includeEdits && maskLayer(state)) {
if (value(state.node, "painted_area", "fill") === "keep picture") {
// The browser loses colours under fully transparent pixels. Core's
// RGB view restores the stored picture under MaskEditor strokes.
source = new Image();
source.src = api.apiURL(`/view?${mediaViewQuery(value(state.node, "image", ""))}&channel=rgb`);
await source.decode();
} else {
// The stage's mask layer is capped at 2048px. Copy from the source
// at full size, using the same rule for which pixels stay picture.
const full = document.createElement("canvas");
full.width = sourceWidth; full.height = sourceHeight;
const context = full.getContext("2d");
context.drawImage(source, 0, 0);
const pixels = context.getImageData(0, 0, full.width, full.height);
const map = seeThroughMap(pixels.data);
if (map) for (let i = 0; i < map.length; i++) pixels.data[i * 4 + 3] = map[i] ? 0 : 255;
context.putImageData(pixels, 0, 0);
source = full;
}
}
return transformPicture({
sourceWidth, sourceHeight, values: current, resize, includeEdits,
fill: normalizeColor(current.fill_color),
drawSource: (context) => context.drawImage(source, -sourceWidth / 2, -sourceHeight / 2, sourceWidth, sourceHeight),
});
};
const report = (error) => showToast({ severity: "error", summary: "Copy image", detail: error?.message ?? String(error) });
new globalThis.LiteGraph.ContextMenu([
{ content: "Copy image", callback: () => {
try {
Promise.resolve(copyPicture(picture)).then(
() => showToast({ summary: "Copy image", severity: "success", detail: "The picture is on the clipboard." }), report,
);
} catch (error) { report(error); }
} },
{ content: "Open image", callback: async () => {
try {
// A real image retains the browser's native Copy image on plain
// HTTP too. A data URL stays usable for as long as the tab is open.
const tab = window.open("about:blank", "_blank");
if (!tab) throw new Error("Allow pop-ups to open the picture.");
tab.opener = null;
const image = tab.document.createElement("img");
image.src = (await picture()).toDataURL("image/png");
image.style.maxWidth = "100%";
tab.document.title = "Crop image — right-click to copy";
tab.document.body.append(image);
} catch (error) { report(error); }
} },
], { event });
}, { signal });
}
canvas.addEventListener("pointerdown", (event) => pointerDown(state, canvas, event), { signal });
canvas.addEventListener("pointermove", (event) => pointerMove(state, canvas, event), { signal });
canvas.addEventListener("pointerup", (event) => pointerUp(state, canvas, event), { signal });
+54
View File
@@ -0,0 +1,54 @@
import { keptCrop, resolveCrop, resolvePadding, rotatedSize, scaleToMegapixels } from "./transform_geometry.mjs";
export const COPY_EDITS_SETTING = Object.freeze({
key: "copy_edits", label: "Copy with crop, rotation and padding", type: "toggle", default: false,
hint: "Off: copy the original picture. On: include crop, rotation, padding and resize. Handles and guides are never copied.",
});
// Render picture pixels into a separate canvas. The editor's canvas contains
// handles, hatching and stage margins and must never be a clipboard source.
export function transformPicture({ sourceWidth, sourceHeight, values, resize, fill, drawSource, includeEdits = false, createCanvas = () => document.createElement("canvas") }) {
const canvas = createCanvas();
if (!includeEdits) {
canvas.width = sourceWidth; canvas.height = sourceHeight;
const context = canvas.getContext("2d");
if (!context) throw new Error("The browser could not make the picture.");
context.translate(sourceWidth / 2, sourceHeight / 2);
drawSource(context);
return canvas;
}
const source = rotatedSize(sourceWidth, sourceHeight, values.rotation_degrees);
const whole = resolveCrop(values, source);
const padding = resolvePadding(values, whole);
const crop = keptCrop(whole, padding);
const size = resize
? scaleToMegapixels(padding.outputWidth, padding.outputHeight, resize.megapixels, resize.steps)
: { width: padding.outputWidth, height: padding.outputHeight };
canvas.width = size.width; canvas.height = size.height;
const context = canvas.getContext("2d");
if (!context) throw new Error("The browser could not make the picture.");
context.fillStyle = fill;
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.scale(size.width / padding.outputWidth, size.height / padding.outputHeight);
context.beginPath();
context.rect(padding.left, padding.top, crop.width, crop.height);
context.clip();
context.translate(padding.left - crop.x + source.width / 2, padding.top - crop.y + source.height / 2);
context.rotate((Number(values.rotation_degrees) || 0) * Math.PI / 180);
drawSource(context);
context.restore();
return canvas;
}
// Start the clipboard write in the click's activation, including in browsers
// that require a promised PNG rather than a write after toBlob has finished.
export function copyPicture(picture, { clipboard = globalThis.navigator?.clipboard, ClipboardItem = globalThis.ClipboardItem } = {}) {
if (!clipboard?.write || !ClipboardItem) throw new Error("Open ComfyUI on localhost or HTTPS to copy directly. Choose Open image, then right-click the picture to copy it instead.");
const png = Promise.resolve().then(() => typeof picture === "function" ? picture() : picture).then((canvas) => new Promise((resolve, reject) => {
canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("The browser could not make the picture.")), "image/png");
}));
// Also observe encoding failure when write() is refused before it reads png.
png.catch(() => {});
return clipboard.write([new ClipboardItem({ "image/png": png })]);
}
+79
View File
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import { COPY_EDITS_SETTING, copyPicture, transformPicture } from "../js/shared/transform_picture.mjs";
import { mergeSettings } from "../js/shared/node_settings.mjs";
function render(values = {}, resize = null, includeEdits = false) {
const calls = [];
const context = new Proxy({}, { get: (target, name) => name in target ? target[name] : (...args) => calls.push([name, ...args]) });
const canvas = { getContext: () => context };
const result = transformPicture({
sourceWidth: 100, sourceHeight: 60,
values: { canvas_multiple: 1, ...values }, resize, includeEdits, fill: "#123456",
drawSource: (ctx) => ctx.drawImage("source", -50, -30, 100, 60),
createCanvas: () => canvas,
});
return { result, calls, context };
}
test("default copy uses the original picture, ignoring crop, rotation, padding and resize", () => {
const { result, calls } = render({ crop_x: 10, crop_width: 40, rotation_degrees: 90, pad_left: 80, pad_top: 20, canvas_multiple: 64 }, { megapixels: 1, steps: 8 });
assert.deepEqual([result.width, result.height], [100, 60]);
assert.deepEqual(calls, [
["translate", 50, 30], ["drawImage", "source", -50, -30, 100, 60],
]);
});
test("the gear preference defaults off for existing browsers and accepts an explicit opt-in", () => {
assert.equal(mergeSettings([COPY_EDITS_SETTING], {}).copy_edits, false);
assert.equal(mergeSettings([COPY_EDITS_SETTING], { show_mask: true }).copy_edits, false);
assert.equal(mergeSettings([COPY_EDITS_SETTING], { copy_edits: "true" }).copy_edits, false);
assert.equal(mergeSettings([COPY_EDITS_SETTING], { copy_edits: true }).copy_edits, true);
});
test("opting in includes crop, padding and alignment in the copied bounds and source offset", () => {
const { result, calls } = render({ crop_x: 10, crop_y: 5, crop_width: 40, crop_height: 30, pad_left: 8, pad_top: 4, pad_right: 8, pad_bottom: 6, canvas_multiple: 8 }, null, true);
assert.deepEqual([result.width, result.height], [56, 40]);
assert.ok(calls.some((c) => JSON.stringify(c) === JSON.stringify(["rect", 8, 4, 40, 30])));
assert.ok(calls.some((c) => JSON.stringify(c) === JSON.stringify(["translate", 48, 29])));
});
test("opting in applies rotation and resize without copying a screen-sized preview", () => {
const { result, calls } = render({ rotation_degrees: 90 }, { megapixels: 0.25, steps: 8 }, true);
assert.deepEqual([result.width, result.height], [400, 664]);
assert.ok(calls.some((c) => c[0] === "rotate" && c[1] === Math.PI / 2));
assert.ok(calls.some((c) => c[0] === "scale" && c[1] === 400 / 60 && c[2] === 664 / 100));
});
test("clipboard write starts before PNG encoding finishes and contains only the clean PNG", async () => {
let finish, item, written = false;
const canvas = { toBlob: (callback, type) => { assert.equal(type, "image/png"); finish = callback; } };
class ClipboardItem { constructor(data) { this.data = data; } }
const clipboard = { write: async (items) => { written = true; [item] = items; await item.data["image/png"]; } };
const pending = copyPicture(canvas, { clipboard, ClipboardItem });
assert.equal(written, true);
assert.deepEqual(Object.keys(item.data), ["image/png"]);
await Promise.resolve(); await Promise.resolve();
const png = new Blob(["picture"], { type: "image/png" });
finish(png);
await pending;
assert.equal(await item.data["image/png"], png);
});
test("clipboard and encoding failures are reported instead of false success", async () => {
assert.throws(() => copyPicture({}, { clipboard: null, ClipboardItem: null }), /Open image/);
class ClipboardItem { constructor(data) { this.data = data; } }
const canvas = { toBlob: (callback) => callback(null) };
const clipboard = { write: async ([item]) => await item.data["image/png"] };
await assert.rejects(copyPicture(canvas, { clipboard, ClipboardItem }), /could not make/);
await assert.rejects(copyPicture({ toBlob: () => {} }, { clipboard: { write: async () => { throw new Error("Denied"); } }, ClipboardItem }), /Denied/);
});
test("both image editing surfaces replace native canvas copying, video is unchanged", () => {
const source = readFileSync(new URL("../js/shared/transform_editor.mjs", import.meta.url), "utf8");
assert.match(source, /attachStageHandlers\(state, preview, state.panelAbort.signal\)/);
assert.match(source, /attachStageHandlers\(state, canvas, abort.signal\)/);
assert.match(source, /if \(state.kind === "image"\) \{\s*canvas.addEventListener\("contextmenu"/);
assert.match(source, /copyPicture\(picture\)/);
});