From 550d7e23c41240d1949e25caec8738ec5f4c362a Mon Sep 17 00:00:00 2001 From: vshnosngh Date: Tue, 27 Oct 2026 15:45:26 +0530 Subject: [PATCH] feat(image-manipulator): fix inpainting mask offset, add background job governance with time limit, split view and enterprise presets --- cmd/image-manipulator/app.js | 821 ++++++++++++++++++++++++++--- cmd/image-manipulator/handlers2.go | 400 ++++++-------- cmd/image-manipulator/index.html | 182 ++++++- cmd/image-manipulator/jobs.go | 388 ++++++++++++++ cmd/image-manipulator/main.go | 8 + cmd/image-manipulator/styles.css | 310 ++++++++++- internal/gateway/router.go | 11 + web/image-manipulator/app.js | 821 ++++++++++++++++++++++++++--- web/image-manipulator/index.html | 182 ++++++- web/image-manipulator/styles.css | 310 ++++++++++- 10 files changed, 3034 insertions(+), 399 deletions(-) create mode 100644 cmd/image-manipulator/jobs.go diff --git a/cmd/image-manipulator/app.js b/cmd/image-manipulator/app.js index a279c32..5ae58a7 100644 --- a/cmd/image-manipulator/app.js +++ b/cmd/image-manipulator/app.js @@ -52,7 +52,10 @@ const toolState = { fileName: "" }, masker: { - brush_size: 35 + brush_size: 40, + mode: "brush", + color: "rgba(244, 63, 94, 0.70)", + opacity: 70 }, convert: { format: "png", @@ -78,6 +81,10 @@ let maskCtx = null; let isDrawing = false; let maskStrokes = []; +window.toolState = toolState; +window.filesList = filesList; +window.maskStrokes = maskStrokes; + // ═══════════════════════════════════════════════════════════════════ // PROXY-SAFE API URL RESOLVER // ═══════════════════════════════════════════════════════════════════ @@ -99,6 +106,8 @@ document.addEventListener("DOMContentLoaded", () => { renderToolOptions(); renderToolControls(); updateQueueUI(); + refreshBackgroundJobs(); + startJobPolling(); }); // ═══════════════════════════════════════════════════════════════════ @@ -226,7 +235,18 @@ async function ingestFiles(newFileList) { if (filesList.length > 0) { if (activeIndex >= filesList.length) activeIndex = 0; + const cur = filesList[activeIndex]; + historySnapshots = [{ + id: "init_" + activeIndex, + label: "Original", + time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + dataUrl: cur.dataUrl, + w: cur.naturalW, + h: cur.naturalH + }]; renderActiveImage(); + updateSplitImages(); + renderHistoryTab(); } updateQueueUI(); @@ -360,7 +380,18 @@ function renderFilmstrip() { function selectActiveImage(index) { if (index >= 0 && index < filesList.length) { activeIndex = index; + const cur = filesList[index]; + historySnapshots = [{ + id: "init_" + index, + label: "Original", + time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + dataUrl: cur.dataUrl, + w: cur.naturalW, + h: cur.naturalH + }]; renderActiveImage(); + updateSplitImages(); + renderHistoryTab(); } } window.selectActiveImage = selectActiveImage; @@ -697,66 +728,178 @@ function setupCropDragEvents() { } // ═══════════════════════════════════════════════════════════════════ -// INPAINT MASK BRUSH ENGINE (Interactive Canvas Overlay) // ═══════════════════════════════════════════════════════════════════ +// INPAINT MASK BRUSH ENGINE (Enterprise Pixel-Perfect Canvas Overlay) +// ═══════════════════════════════════════════════════════════════════ +let maskRedoStack = []; + +function getMaskCanvasPoint(e) { + const canvas = document.getElementById("ps-mask-canvas"); + if (!canvas) return { x: 0, y: 0 }; + const rect = canvas.getBoundingClientRect(); + if (!rect.width || !rect.height) return { x: 0, y: 0 }; + + // EXACT transformation: screen viewport pixels -> native canvas buffer pixels + const scaleX = canvas.width / rect.width; + const scaleY = canvas.height / rect.height; + + const rawX = (e.clientX - rect.left) * scaleX; + const rawY = (e.clientY - rect.top) * scaleY; + + return { + x: Math.max(0, Math.min(canvas.width, rawX)), + y: Math.max(0, Math.min(canvas.height, rawY)) + }; +} + function initMaskCanvas() { const img = document.getElementById("ps-active-img"); const canvas = document.getElementById("ps-mask-canvas"); - if (!img || !canvas || !img.clientWidth) return; + if (!img || !canvas) return; + + const cur = filesList[activeIndex]; + if (!cur) return; + + // Set internal resolution to image native dimensions + const natW = cur.naturalW || img.naturalWidth || img.clientWidth || 800; + const natH = cur.naturalH || img.naturalHeight || img.clientHeight || 600; + + if (canvas.width !== natW || canvas.height !== natH) { + canvas.width = natW; + canvas.height = natH; + } - canvas.width = img.clientWidth; - canvas.height = img.clientHeight; maskCanvas = canvas; maskCtx = canvas.getContext("2d"); redrawMaskStrokes(); + setupMaskPointerEvents(); +} - canvas.onmousedown = (e) => { +function setupMaskPointerEvents() { + const canvas = document.getElementById("ps-mask-canvas"); + if (!canvas || canvas.dataset.pointerBound) return; + canvas.dataset.pointerBound = "true"; + + canvas.addEventListener("pointerdown", (e) => { + if (currentTool !== "masker") return; + e.preventDefault(); + canvas.setPointerCapture(e.pointerId); isDrawing = true; - const rect = canvas.getBoundingClientRect(); - const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top }; - const stroke = { size: toolState.masker.brush_size, points: [pt] }; + maskRedoStack = []; // clear redo on new action + + const pt = getMaskCanvasPoint(e); + const stroke = { + mode: toolState.masker.mode || "brush", + size: toolState.masker.brush_size, + points: [pt] + }; maskStrokes.push(stroke); - maskCtx.lineCap = "round"; - maskCtx.lineJoin = "round"; - maskCtx.strokeStyle = "#ff0000"; - maskCtx.lineWidth = toolState.masker.brush_size; - maskCtx.beginPath(); - maskCtx.moveTo(pt.x, pt.y); - maskCtx.lineTo(pt.x, pt.y); - maskCtx.stroke(); - }; + if (stroke.mode === "rect") { + stroke.startPt = pt; + } else { + renderSingleStrokeStep(stroke, pt, pt); + } + }); - canvas.onmousemove = (e) => { - updateBrushRing(e.clientX, e.clientY); + canvas.addEventListener("pointermove", (e) => { + updateBrushRing(e); if (!isDrawing) return; - const rect = canvas.getBoundingClientRect(); - const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top }; + + const pt = getMaskCanvasPoint(e); const curStroke = maskStrokes[maskStrokes.length - 1]; if (curStroke) { - const lastPt = curStroke.points[curStroke.points.length - 1]; - curStroke.points.push(pt); + if (curStroke.mode === "rect") { + curStroke.endPt = pt; + redrawMaskStrokes(); + if (maskCtx && curStroke.startPt) { + maskCtx.save(); + maskCtx.fillStyle = "rgba(244, 63, 94, 0.55)"; + maskCtx.strokeStyle = "#ffffff"; + maskCtx.lineWidth = 2; + const rx = Math.min(curStroke.startPt.x, pt.x); + const ry = Math.min(curStroke.startPt.y, pt.y); + const rw = Math.abs(pt.x - curStroke.startPt.x); + const rh = Math.abs(pt.y - curStroke.startPt.y); + maskCtx.fillRect(rx, ry, rw, rh); + maskCtx.strokeRect(rx, ry, rw, rh); + maskCtx.restore(); + } + } else if (curStroke.points.length > 0) { + const lastPt = curStroke.points[curStroke.points.length - 1]; + curStroke.points.push(pt); + renderSingleStrokeStep(curStroke, lastPt, pt); + } + } + }); - maskCtx.beginPath(); - maskCtx.moveTo(lastPt.x, lastPt.y); - maskCtx.lineTo(pt.x, pt.y); - maskCtx.stroke(); + const stopDrawing = (e) => { + if (isDrawing) { + isDrawing = false; + try { canvas.releasePointerCapture(e.pointerId); } catch (_) {} + redrawMaskStrokes(); } }; - canvas.onmouseup = () => { isDrawing = false; }; - canvas.onmouseleave = () => { isDrawing = false; }; + canvas.addEventListener("pointerup", stopDrawing); + canvas.addEventListener("pointercancel", stopDrawing); + canvas.addEventListener("pointerleave", (e) => { + if (!isDrawing) { + const ring = document.getElementById("brush-cursor-ring"); + if (ring) ring.style.display = "none"; + } + }); } -function updateBrushRing(x, y) { +function renderSingleStrokeStep(stroke, p1, p2) { + if (!maskCtx) return; + + maskCtx.save(); + if (stroke.mode === "eraser") { + maskCtx.globalCompositeOperation = "destination-out"; + maskCtx.lineWidth = stroke.size; + maskCtx.lineCap = "round"; + maskCtx.lineJoin = "round"; + maskCtx.beginPath(); + maskCtx.moveTo(p1.x, p1.y); + maskCtx.lineTo(p2.x, p2.y); + maskCtx.stroke(); + } else { + maskCtx.globalCompositeOperation = "source-over"; + maskCtx.lineCap = "round"; + maskCtx.lineJoin = "round"; + maskCtx.lineWidth = stroke.size; + maskCtx.strokeStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)"; + maskCtx.beginPath(); + maskCtx.moveTo(p1.x, p1.y); + maskCtx.lineTo(p2.x, p2.y); + maskCtx.stroke(); + } + maskCtx.restore(); +} + +function updateBrushRing(e) { const ring = document.getElementById("brush-cursor-ring"); - if (!ring) return; - const sz = toolState.masker.brush_size; - ring.style.left = `${x}px`; - ring.style.top = `${y}px`; - ring.style.width = `${sz}px`; - ring.style.height = `${sz}px`; + const canvas = document.getElementById("ps-mask-canvas"); + if (!ring || !canvas) return; + + if (currentTool !== "masker" || filesList.length === 0) { + ring.style.display = "none"; + return; + } + + const rect = canvas.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + + const screenScale = rect.width / (canvas.width || 1); + const visualSize = Math.max(6, toolState.masker.brush_size * screenScale); + + ring.style.width = `${visualSize}px`; + ring.style.height = `${visualSize}px`; + ring.style.left = `${e.clientX}px`; + ring.style.top = `${e.clientY}px`; + ring.style.display = "block"; } function setBrushSize(size) { @@ -768,7 +911,17 @@ function setBrushSize(size) { } window.setBrushSize = setBrushSize; +function setMaskMode(mode) { + toolState.masker.mode = mode; + renderToolOptions(); + renderToolControls(); +} +window.setMaskMode = setMaskMode; + function clearMaskStrokes() { + if (maskStrokes.length > 0) { + maskRedoStack.push([...maskStrokes]); + } maskStrokes = []; if (maskCtx && maskCanvas) { maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height); @@ -777,26 +930,94 @@ function clearMaskStrokes() { window.clearMaskStrokes = clearMaskStrokes; function undoMaskStroke() { - maskStrokes.pop(); - redrawMaskStrokes(); + if (maskStrokes.length > 0) { + const popped = maskStrokes.pop(); + maskRedoStack.push(popped); + redrawMaskStrokes(); + } } window.undoMaskStroke = undoMaskStroke; +function redoMaskStroke() { + if (maskRedoStack.length > 0) { + const item = maskRedoStack.pop(); + if (Array.isArray(item)) { + maskStrokes = item; + } else { + maskStrokes.push(item); + } + redrawMaskStrokes(); + } +} +window.redoMaskStroke = redoMaskStroke; + +function fillMask() { + if (!maskCanvas) return; + maskStrokes.push({ + mode: "fill", + size: 0, + points: [] + }); + redrawMaskStrokes(); +} +window.fillMask = fillMask; + +function invertMask() { + if (!maskCanvas) return; + maskStrokes.push({ + mode: "invert", + size: 0, + points: [] + }); + redrawMaskStrokes(); +} +window.invertMask = invertMask; + function redrawMaskStrokes() { if (!maskCtx || !maskCanvas) return; maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height); - maskCtx.lineCap = "round"; - maskCtx.lineJoin = "round"; - maskCtx.strokeStyle = "#ff0000"; maskStrokes.forEach(s => { - maskCtx.lineWidth = s.size; - maskCtx.beginPath(); - if (s.points.length > 0) { - maskCtx.moveTo(s.points[0].x, s.points[0].y); - s.points.forEach(p => maskCtx.lineTo(p.x, p.y)); + maskCtx.save(); + if (s.mode === "fill") { + maskCtx.fillStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)"; + maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height); + } else if (s.mode === "invert") { + maskCtx.globalCompositeOperation = "difference"; + maskCtx.fillStyle = "#ffffff"; + maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height); + } else if (s.mode === "rect" && s.startPt && s.endPt) { + maskCtx.fillStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)"; + const rx = Math.min(s.startPt.x, s.endPt.x); + const ry = Math.min(s.startPt.y, s.endPt.y); + const rw = Math.abs(s.endPt.x - s.startPt.x); + const rh = Math.abs(s.endPt.y - s.startPt.y); + maskCtx.fillRect(rx, ry, rw, rh); + } else if (s.mode === "eraser") { + maskCtx.globalCompositeOperation = "destination-out"; + maskCtx.lineWidth = s.size; + maskCtx.lineCap = "round"; + maskCtx.lineJoin = "round"; + maskCtx.beginPath(); + if (s.points.length > 0) { + maskCtx.moveTo(s.points[0].x, s.points[0].y); + s.points.forEach(p => maskCtx.lineTo(p.x, p.y)); + } + maskCtx.stroke(); + } else { + maskCtx.globalCompositeOperation = "source-over"; + maskCtx.lineCap = "round"; + maskCtx.lineJoin = "round"; + maskCtx.lineWidth = s.size; + maskCtx.strokeStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)"; + maskCtx.beginPath(); + if (s.points.length > 0) { + maskCtx.moveTo(s.points[0].x, s.points[0].y); + s.points.forEach(p => maskCtx.lineTo(p.x, p.y)); + } + maskCtx.stroke(); } - maskCtx.stroke(); + maskCtx.restore(); }); } @@ -807,29 +1028,76 @@ function generateMaskDataUrl(targetW, targetH) { outCanvas.height = targetH || maskCanvas.height; const ctx = outCanvas.getContext("2d"); + // Pure black background ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); const scaleX = outCanvas.width / maskCanvas.width; const scaleY = outCanvas.height / maskCanvas.height; - ctx.lineCap = "round"; - ctx.lineJoin = "round"; - ctx.strokeStyle = "#ffffff"; - maskStrokes.forEach(s => { - ctx.lineWidth = s.size * scaleX; - ctx.beginPath(); - if (s.points.length > 0) { - ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); - s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); + ctx.save(); + if (s.mode === "fill") { + ctx.fillStyle = "#ffffff"; + ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); + } else if (s.mode === "invert") { + ctx.globalCompositeOperation = "difference"; + ctx.fillStyle = "#ffffff"; + ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); + } else if (s.mode === "rect" && s.startPt && s.endPt) { + ctx.fillStyle = "#ffffff"; + const rx = Math.min(s.startPt.x * scaleX, s.endPt.x * scaleX); + const ry = Math.min(s.startPt.y * scaleY, s.endPt.y * scaleY); + const rw = Math.abs(s.endPt.x - s.startPt.x) * scaleX; + const rh = Math.abs(s.endPt.y - s.startPt.y) * scaleY; + ctx.fillRect(rx, ry, rw, rh); + } else if (s.mode === "eraser") { + ctx.globalCompositeOperation = "source-over"; + ctx.strokeStyle = "#000000"; // Eraser turns mask black + ctx.lineWidth = s.size * scaleX; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.beginPath(); + if (s.points.length > 0) { + ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); + s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); + } + ctx.stroke(); + } else { + ctx.globalCompositeOperation = "source-over"; + ctx.strokeStyle = "#ffffff"; // Mask is solid white + ctx.lineWidth = s.size * scaleX; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.beginPath(); + if (s.points.length > 0) { + ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); + s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); + } + ctx.stroke(); } - ctx.stroke(); + ctx.restore(); }); return outCanvas.toDataURL("image/png"); } +function exportMaskOnly() { + const cur = filesList[activeIndex]; + if (!cur) return; + const dataUrl = generateMaskDataUrl(cur.naturalW, cur.naturalH); + if (!dataUrl) return; + + const a = document.createElement("a"); + a.href = dataUrl; + a.download = (cur.name ? cur.name.replace(/\.[^/.]+$/, "") : "image") + "_mask.png"; + document.body.appendChild(a); + a.click(); + a.remove(); + showToast("Inpainting mask PNG downloaded", "success"); +} +window.exportMaskOnly = exportMaskOnly; + // ═══════════════════════════════════════════════════════════════════ // DYNAMIC CONTEXTUAL OPTIONS & INSPECTOR CONTROLS // ═══════════════════════════════════════════════════════════════════ @@ -932,13 +1200,25 @@ function renderToolOptions() { `, masker: `
- Brush: - - ${toolState.masker.brush_size}px + Tool: + + +
- - + Size: + + ${toolState.masker.brush_size}px + + + +
+
+ + + + +
`, convert: ` @@ -1142,13 +1422,43 @@ function renderToolControls() { `, masker: ` -
Mask Generator & Brush
+
Inpainting Mask & Pro Brush
+
+ +
+ + + +
+
- +
-
-

Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.

+
+ +
+ + + +
+
+
+ +
+ + + + +
+
+
+ +
+
+

Inpaint Masker paints a pixel-perfect rubylith mask directly over your image. Drawing generates a solid-white binary mask on a pitch-black canvas.

`, convert: ` @@ -1640,7 +1950,9 @@ async function executeEndpointRequest(endpoint, formData) { cur.file = new File([blob], resItem.filename || cur.name, { type: blob.type }); cur.size = blob.size; + pushHistorySnapshot(currentTool.toUpperCase() + " applied", resItem.image, cur.naturalW, cur.naturalH); renderActiveImage(); + updateSplitImages(); showToast("Transformation applied successfully!", "success"); } else { showToast(data.error || "Transformation failed", "error"); @@ -1807,6 +2119,37 @@ async function executeBatchAll() { updateBatchModalProgress(50, "Files uploaded! Starting server transformations..."); logBatchConsole(`✓ All chunks uploaded successfully. Starting stream processing...`, "success"); + // 2. Check if user selected Enterprise Background Execution + const isBackground = document.getElementById("batch-run-background")?.checked; + if (isBackground) { + const timeLimitSec = parseInt(document.getElementById("batch-time-limit-sel")?.value || "120", 10); + logBatchConsole(`Dispatching to enterprise background job with ${timeLimitSec}s governance time limit...`); + updateBatchModalProgress(70, `Dispatching to background worker (${timeLimitSec}s limit)...`); + + const jobRes = await fetch(getApiUrl("/api/jobs/start"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + session_id: activeSessionId, + operation: currentTool, + time_limit_sec: timeLimitSec, + params: params + }) + }); + const jobData = await jobRes.json(); + if (!jobRes.ok) throw new Error(jobData.error || "Failed to start background job"); + + logBatchConsole(`✓ Job [${jobData.job_id}] running in server background!`, "success"); + logBatchConsole(`✓ Governance: Auto-terminates if execution exceeds ${timeLimitSec} seconds.`); + updateBatchModalProgress(100, `Background job started: ${jobData.job_id}`); + document.getElementById("btn-modal-close").style.display = "inline-flex"; + + trackBackgroundJob(jobData.job_id); + switchInspectorTab("jobs"); + showToast(`Background job ${jobData.job_id} dispatched (${timeLimitSec}s limit)`, "success"); + return; + } + // 2. SSE Server-Side Batch Processing const procRes = await fetch(getApiUrl("/batch-process-session"), { method: "POST", @@ -1939,16 +2282,27 @@ function logBatchConsole(text, type = "normal") { // INSPECTOR TAB SWITCHING // ═══════════════════════════════════════════════════════════════════ function switchInspectorTab(tabName, el) { - document.querySelectorAll(".ps-inspector-tab").forEach(t => t.classList.remove("active")); - if (el) el.classList.add("active"); + document.querySelectorAll(".ps-inspector-tab").forEach(t => { + t.classList.toggle("active", t.getAttribute("data-tab") === tabName); + }); const tabControls = document.getElementById("inspector-tab-controls"); const tabInfo = document.getElementById("inspector-tab-info"); + const tabHistory = document.getElementById("inspector-tab-history"); const tabBatch = document.getElementById("inspector-tab-batch"); + const tabJobs = document.getElementById("inspector-tab-jobs"); if (tabControls) tabControls.style.display = (tabName === "controls") ? "block" : "none"; if (tabInfo) tabInfo.style.display = (tabName === "info") ? "block" : "none"; + if (tabHistory) { + tabHistory.style.display = (tabName === "history") ? "block" : "none"; + if (tabName === "history") renderHistoryTab(); + } if (tabBatch) tabBatch.style.display = (tabName === "batch") ? "block" : "none"; + if (tabJobs) { + tabJobs.style.display = (tabName === "jobs") ? "block" : "none"; + if (tabName === "jobs") refreshBackgroundJobs(); + } } window.switchInspectorTab = switchInspectorTab; @@ -2049,3 +2403,332 @@ function showToast(msg, type = "info") { setTimeout(() => toast.remove(), 4000); } window.showToast = showToast; + + +// ═══════════════════════════════════════════════════════════════════ +// HISTORY SNAPSHOTS TIMELINE +// ═══════════════════════════════════════════════════════════════════ +let historySnapshots = []; + +function pushHistorySnapshot(label, dataUrl, w, h) { + const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); + const snapshot = { + id: Date.now() + Math.random().toString(36).substring(2, 7), + label: label || "Edit", + time: time, + dataUrl: dataUrl, + w: w, + h: h + }; + historySnapshots.push(snapshot); + renderHistoryTab(); +} +window.pushHistorySnapshot = pushHistorySnapshot; + +function renderHistoryTab() { + const container = document.getElementById("ps-history-list"); + if (!container) return; + + if (historySnapshots.length === 0) { + container.innerHTML = ` +
+ + No edit history recorded yet.
Apply operations to build snapshot timeline. +
`; + return; + } + + let html = ""; + historySnapshots.forEach((snap, idx) => { + const isLatest = idx === historySnapshots.length - 1; + html += ` +
+
+ + ${snap.label} +
+ ${snap.time} +
`; + }); + container.innerHTML = html; +} +window.renderHistoryTab = renderHistoryTab; + +async function restoreHistoryState(index) { + if (index < 0 || index >= historySnapshots.length) return; + const snap = historySnapshots[index]; + const cur = filesList[activeIndex]; + if (!cur) return; + + cur.dataUrl = snap.dataUrl; + cur.naturalW = snap.w; + cur.naturalH = snap.h; + + try { + const blob = await (await fetch(snap.dataUrl)).blob(); + cur.file = new File([blob], cur.name, { type: blob.type }); + cur.size = blob.size; + } catch (_) {} + + renderActiveImage(); + updateSplitImages(); + renderHistoryTab(); + showToast(`Restored snapshot: ${snap.label}`, "info"); +} +window.restoreHistoryState = restoreHistoryState; + +function revertToOriginal() { + if (historySnapshots.length === 0) { + showToast("No original snapshot available", "info"); + return; + } + restoreHistoryState(0); +} +window.revertToOriginal = revertToOriginal; + +// ═══════════════════════════════════════════════════════════════════ +// BEFORE / AFTER SPLIT VIEW COMPARISON +// ═══════════════════════════════════════════════════════════════════ +let splitActive = false; +let isSplitDragging = false; + +function toggleSplitView() { + const splitContainer = document.getElementById("ps-split-container"); + const btn = document.getElementById("btn-toggle-split") || document.getElementById("btn-split-view"); + if (!splitContainer) return; + + splitActive = !splitActive; + if (splitActive) { + splitContainer.style.display = "block"; + if (btn) btn.classList.add("active"); + updateSplitImages(); + setupSplitDrag(); + showToast("Split View enabled (Drag divider to compare)", "info"); + } else { + splitContainer.style.display = "none"; + if (btn) btn.classList.remove("active"); + } +} +window.toggleSplitView = toggleSplitView; + +function updateSplitImages() { + const beforeImg = document.getElementById("ps-split-before-img"); + const activeImg = document.getElementById("ps-active-img"); + if (!beforeImg || !activeImg) return; + + const originalUrl = (historySnapshots.length > 0) ? historySnapshots[0].dataUrl : activeImg.src; + beforeImg.src = originalUrl; +} +window.updateSplitImages = updateSplitImages; + +function setupSplitDrag() { + const container = document.getElementById("ps-split-container"); + const bar = document.getElementById("ps-split-bar"); + const clipWrap = document.getElementById("ps-split-clip-wrap"); + if (!container || !bar || !clipWrap || container.dataset.dragBound) return; + container.dataset.dragBound = "true"; + + function setDividerPos(clientX) { + const rect = container.getBoundingClientRect(); + if (!rect.width) return; + let pct = ((clientX - rect.left) / rect.width) * 100; + pct = Math.max(0, Math.min(100, pct)); + bar.style.left = pct + "%"; + clipWrap.style.width = pct + "%"; + } + + bar.addEventListener("pointerdown", (e) => { + isSplitDragging = true; + bar.setPointerCapture(e.pointerId); + e.preventDefault(); + }); + + window.addEventListener("pointermove", (e) => { + if (!isSplitDragging) return; + setDividerPos(e.clientX); + }); + + window.addEventListener("pointerup", (e) => { + if (isSplitDragging) { + isSplitDragging = false; + try { bar.releasePointerCapture(e.pointerId); } catch (_) {} + } + }); +} + +// ═══════════════════════════════════════════════════════════════════ +// ENTERPRISE PRESETS MODAL +// ═══════════════════════════════════════════════════════════════════ +function openPresetsModal() { + const modal = document.getElementById("presets-modal"); + if (modal) modal.style.display = "flex"; +} +window.openPresetsModal = openPresetsModal; + +function closePresetsModal() { + const modal = document.getElementById("presets-modal"); + if (modal) modal.style.display = "none"; +} +window.closePresetsModal = closePresetsModal; + +function applyEnterprisePreset(name, targetW, targetH, aspect) { + selectTool("resize"); + toolState.resize.width = targetW; + toolState.resize.height = targetH; + toolState.resize.maintain_aspect = false; + + const wInput = document.getElementById("param-resize-w"); + const hInput = document.getElementById("param-resize-h"); + if (wInput) wInput.value = targetW; + if (hInput) hInput.value = targetH; + + closePresetsModal(); + showToast(`Applied preset: ${name} (${targetW}×${targetH})`, "success"); +} +window.applyEnterprisePreset = applyEnterprisePreset; + +// ═══════════════════════════════════════════════════════════════════ +// ENTERPRISE BACKGROUND JOBS & ASYNC WORKERS +// ═══════════════════════════════════════════════════════════════════ +let jobPollInterval = null; + +function toggleBackgroundGovOptions(checked) { + const box = document.getElementById("batch-gov-timeout-box"); + if (box) { + box.style.opacity = checked ? "1" : "0.5"; + } +} +window.toggleBackgroundGovOptions = toggleBackgroundGovOptions; + +function trackBackgroundJob(jobId) { + startJobPolling(); + refreshBackgroundJobs(); +} +window.trackBackgroundJob = trackBackgroundJob; + +function startJobPolling() { + if (jobPollInterval) return; + jobPollInterval = setInterval(refreshBackgroundJobs, 2500); +} +window.startJobPolling = startJobPolling; + +async function refreshBackgroundJobs() { + const listContainer = document.getElementById("ps-jobs-list"); + const badgePill = document.getElementById("jobs-badge-pill"); + if (!listContainer) return; + + try { + const res = await fetch(getApiUrl("/api/jobs/list")); + if (!res.ok) return; + const data = await res.json(); + const jobs = data.jobs || []; + + if (badgePill) { + const activeCount = jobs.filter(j => j.status === "QUEUED" || j.status === "PROCESSING").length; + badgePill.textContent = activeCount.toString(); + badgePill.style.display = activeCount > 0 ? "inline-block" : "none"; + } + + renderJobsList(jobs); + } catch (err) { + console.error("Failed to refresh background jobs:", err); + } +} +window.refreshBackgroundJobs = refreshBackgroundJobs; + +function renderJobsList(jobs) { + const container = document.getElementById("ps-jobs-list"); + if (!container) return; + + if (!jobs || jobs.length === 0) { + container.innerHTML = ` +
+ + No background jobs found.
Dispatch heavy tasks using the "Run in Background" toggle. +
`; + return; + } + + let html = ""; + jobs.forEach(job => { + const jId = job.job_id || job.id; + const badgeClass = + job.status === "COMPLETED" ? "badge-success" : + job.status === "PROCESSING" ? "badge-running" : + job.status === "TIMED_OUT" ? "badge-timeout" : + job.status === "CANCELLED" ? "badge-cancelled" : + "badge-queued"; + + const elapsed = `${Math.round(job.elapsed_sec || 0)}s`; + const limit = job.time_limit_sec ? `${job.time_limit_sec}s` : "none"; + const doneFiles = job.completed_files !== undefined ? job.completed_files : (job.processed_count || 0); + const dlUrl = (job.status === "COMPLETED" || job.status === "TIMED_OUT") ? getApiUrl("/api/jobs/download?job_id=" + encodeURIComponent(jId)) : null; + + html += ` +
+
+
+
+ + ${(job.operation || "Batch").toUpperCase()} Task +
+
${jId}
+
+ ${job.status} +
+ +
+
+ Files + ${doneFiles} / ${job.total_files || 1} +
+
+ Elapsed / Limit + ${elapsed} / ${limit} +
+
+ +
+
+
+ +
+ ${(job.status === "PROCESSING" || job.status === "QUEUED") ? ` + + ` : ''} + ${dlUrl ? ` + + Download ZIP + + ` : ''} +
+
+ `; + }); + + container.innerHTML = html; +} + +async function cancelJob(jobId) { + try { + const res = await fetch(getApiUrl(`/api/jobs/cancel?job_id=${encodeURIComponent(jobId)}`), { method: "POST" }); + const data = await res.json(); + if (res.ok) { + showToast("Job canceled successfully", "info"); + refreshBackgroundJobs(); + } else { + showToast(data.error || "Failed to cancel job", "error"); + } + } catch (err) { + showToast(`Error cancelling job: ${err.message}`, "error"); + } +} +window.cancelJob = cancelJob; + +function setMaskColor(colorHex) { + toolState.masker.color = colorHex; + redrawMaskStrokes(); +} +window.setMaskColor = setMaskColor; diff --git a/cmd/image-manipulator/handlers2.go b/cmd/image-manipulator/handlers2.go index a0373b7..ab23bf8 100644 --- a/cmd/image-manipulator/handlers2.go +++ b/cmd/image-manipulator/handlers2.go @@ -282,6 +282,169 @@ func getParamString(p map[string]interface{}, key string, def string) string { return def } +func processSingleBatchFile(file string, operation string, params map[string]interface{}, uploadsDir string, resultsDir string) (int64, int64, error) { + stat, err := os.Stat(file) + if err != nil { + return 0, 0, err + } + origSize := stat.Size() + + fileReader, err := os.Open(file) + if err != nil { + return 0, 0, err + } + img, format, err := image.Decode(fileReader) + fileReader.Close() + if err != nil { + return 0, 0, err + } + if format == "" { + format = "PNG" + } + + var buf []byte + var finalFmt = format + + switch operation { + case "resize": + width := getParamInt(params, "width", 0) + height := getParamInt(params, "height", 0) + maintain := getParamBool(params, "maintain_aspect", true) + if !maintain { + maintain = getParamBool(params, "maintain", false) + } + processed := resizeImage(img, width, height, maintain) + buf, finalFmt = compressLogic(processed, format, 95) + case "convert": + targetFmt := getParamString(params, "format", "png") + quality := getParamInt(params, "quality", 95) + buf, finalFmt = compressLogic(img, targetFmt, quality) + case "compress": + targetFmt := getParamString(params, "format", "original") + if targetFmt == "original" { + targetFmt = format + } + q := getParamInt(params, "quality", 80) + targetMB := getParamFloat(params, "target_size_mb", 0) + currentMB := getParamFloat(params, "current_size_mb", 0) + if targetMB > 0 && currentMB > targetMB { + ratio := targetMB / currentMB + calculatedQuality := int(float64(q) * ratio) + if calculatedQuality < 5 { + calculatedQuality = 5 + } + if calculatedQuality > 95 { + calculatedQuality = 95 + } + q = calculatedQuality + } + buf, finalFmt = compressLogic(img, targetFmt, q) + case "crop": + bounds := img.Bounds() + origW := bounds.Dx() + origH := bounds.Dy() + leftPct := getParamFloat(params, "left_pct", 0) + topPct := getParamFloat(params, "top_pct", 0) + rightPct := getParamFloat(params, "right_pct", 100) + bottomPct := getParamFloat(params, "bottom_pct", 100) + x := int(float64(origW) * leftPct / 100.0) + y := int(float64(origH) * topPct / 100.0) + w := int(float64(origW) * (rightPct - leftPct) / 100.0) + h := int(float64(origH) * (bottomPct - topPct) / 100.0) + processed := cropImage(img, x, y, w, h) + buf, finalFmt = compressLogic(processed, format, 95) + case "filter": + filterType := getParamString(params, "filter", "GRAYSCALE") + processed := filterImage(img, filterType) + buf, finalFmt = compressLogic(processed, format, 95) + case "rotate": + rotOp := getParamString(params, "operation", "90") + processed := rotateImage(img, rotOp) + buf, finalFmt = compressLogic(processed, format, 95) + case "round_corners": + radius := getParamInt(params, "radius", 20) + isCircle := getParamBool(params, "is_circle", false) + processed := roundCorners(img, radius, isCircle) + buf, finalFmt = compressLogic(processed, "PNG", 95) + case "border": + borderWidth := getParamInt(params, "border_width", 10) + borderColorHex := getParamString(params, "border_color", "#000000") + padAspect := getParamString(params, "pad_aspect", "none") + processed := addBorderCanvas(img, borderWidth, borderColorHex, padAspect) + buf, finalFmt = compressLogic(processed, format, 95) + case "strip_metadata": + targetFmt := getParamString(params, "format", "original") + if targetFmt == "original" { + targetFmt = format + } + quality := getParamInt(params, "quality", 95) + buf, finalFmt = compressLogic(img, targetFmt, quality) + case "adjust": + brightness := getParamFloat(params, "brightness", 0) + contrast := getParamFloat(params, "contrast", 0) + saturation := getParamFloat(params, "saturation", 0) + gamma := getParamFloat(params, "gamma", 1.0) + processed := adjustColor(img, brightness, contrast, saturation, gamma) + buf, finalFmt = compressLogic(processed, format, 95) + case "watermark": + var wmImg image.Image + wmBase64 := getParamString(params, "watermark_base64", "") + if wmBase64 != "" { + if commaIdx := strings.Index(wmBase64, ","); commaIdx != -1 { + wmBase64 = wmBase64[commaIdx+1:] + } + if decoded, err := base64.StdEncoding.DecodeString(wmBase64); err == nil { + wmImg, _, _ = image.Decode(bytes.NewReader(decoded)) + } + } + position := getParamString(params, "position", "bottom_right") + opacity := getParamFloat(params, "opacity", 0.7) + if wmImg != nil { + processed := watermarkImage(img, wmImg, position, int(opacity*100)) + buf, finalFmt = compressLogic(processed, format, 95) + } else { + buf, finalFmt = compressLogic(img, format, 95) + } + case "masker", "mask": + var maskImg image.Image + maskBase64 := getParamString(params, "mask_base64", "") + if maskBase64 != "" { + if commaIdx := strings.Index(maskBase64, ","); commaIdx != -1 { + maskBase64 = maskBase64[commaIdx+1:] + } + if decoded, err := base64.StdEncoding.DecodeString(maskBase64); err == nil { + maskImg, _, _ = image.Decode(bytes.NewReader(decoded)) + } + } + if maskImg != nil { + resizedMask := imaging.Resize(maskImg, img.Bounds().Dx(), img.Bounds().Dy(), imaging.Lanczos) + buf, finalFmt = compressLogic(resizedMask, "PNG", 95) + } else { + blackCanvas := imaging.New(img.Bounds().Dx(), img.Bounds().Dy(), color.Black) + buf, finalFmt = compressLogic(blackCanvas, "PNG", 95) + } + default: + buf, finalFmt = compressLogic(img, format, 95) + } + + relPath, _ := filepath.Rel(uploadsDir, file) + if operation == "convert" || operation == "round_corners" || (operation == "compress" && params["format"] != nil && params["format"] != "original" && params["format"] != "") { + ext := strings.ToLower(finalFmt) + if ext == "jpeg" { + ext = "jpg" + } + relPath = strings.TrimSuffix(relPath, filepath.Ext(relPath)) + "." + ext + } + + targetFilePath := filepath.Join(resultsDir, relPath) + os.MkdirAll(filepath.Dir(targetFilePath), 0755) + + if err := os.WriteFile(targetFilePath, buf, 0644); err != nil { + return origSize, 0, err + } + return origSize, int64(len(buf)), nil +} + func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { sessionData := getSessionData(r) @@ -405,8 +568,7 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { } completed++ - - stat, err := os.Stat(file) + origSize, newSize, err := processSingleBatchFile(file, data.Operation, data.Params, uploadsDir, resultsDir) if err != nil { errorCount++ errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err)) @@ -419,246 +581,26 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { }) continue } - origSize := stat.Size() + totalOriginalSize += origSize - - fileReader, err := os.Open(file) - if err != nil { - errorCount++ - errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err)) - emitSSE(map[string]interface{}{ - "type": "progress", - "current": completed, - "total": totalFiles, - "filename": filepath.Base(file), - "error": true, - }) - continue - } - - img, format, err := image.Decode(fileReader) - fileReader.Close() - - if err != nil { - errorCount++ - errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err)) - emitSSE(map[string]interface{}{ - "type": "progress", - "current": completed, - "total": totalFiles, - "filename": filepath.Base(file), - "error": true, - }) - continue - } - if format == "" { - format = "PNG" - } - - var buf []byte - var finalFmt = format - - switch data.Operation { - case "resize": - width := getParamInt(data.Params, "width", 0) - height := getParamInt(data.Params, "height", 0) - maintain := getParamBool(data.Params, "maintain_aspect", true) - if !maintain { - maintain = getParamBool(data.Params, "maintain", false) - } - processed := resizeImage(img, width, height, maintain) - buf, finalFmt = compressLogic(processed, format, 95) - case "convert": - targetFmt := getParamString(data.Params, "format", "png") - quality := getParamInt(data.Params, "quality", 95) - buf, finalFmt = compressLogic(img, targetFmt, quality) - case "compress": - targetFmt := getParamString(data.Params, "format", "original") - if targetFmt == "original" { - targetFmt = format - } - q := getParamInt(data.Params, "quality", 80) - - // Smart Target Size Compression - targetSizeMB := getParamFloat(data.Params, "target_size_mb", 0) - currentSizeMB := getParamFloat(data.Params, "current_size_mb", 0) - - if targetSizeMB > 0 && currentSizeMB > 0 { - ratio := targetSizeMB / currentSizeMB - if ratio >= 1.0 { - buf, finalFmt = compressLogic(img, targetFmt, 92) - } else { - perFileTarget := int64(float64(origSize) * ratio) - initQ := int(ratio * 90) - if initQ < 10 { initQ = 10 } - if initQ > 90 { initQ = 90 } - - trialBuf, trialFmt := compressLogic(img, targetFmt, initQ) - trialSize := int64(len(trialBuf)) - if trialSize <= perFileTarget && trialSize >= int64(float64(perFileTarget)*0.85) { - buf, finalFmt = trialBuf, trialFmt - } else { - lo, hi := 5, 95 - if trialSize <= perFileTarget { - lo = initQ - } else { - hi = initQ - } - bestBuf := trialBuf - bestFmt := trialFmt - // Fast bounded bisection (max 4 iterations) - for iter := 0; iter < 4; iter++ { - mid := (lo + hi) / 2 - tBuf, tFmt := compressLogic(img, targetFmt, mid) - tSize := int64(len(tBuf)) - if tSize <= perFileTarget { - bestBuf, bestFmt = tBuf, tFmt - lo = mid + 1 - } else { - hi = mid - 1 - } - } - buf, finalFmt = bestBuf, bestFmt - } - } - } else { - buf, finalFmt = compressLogic(img, targetFmt, q) - } - case "crop": - bounds := img.Bounds() - wDx, hDy := float64(bounds.Dx()), float64(bounds.Dy()) - l, t, r, b := 0, 0, bounds.Dx(), bounds.Dy() - lp := getParamFloat(data.Params, "left_pct", -1) - rp := getParamFloat(data.Params, "right_pct", -1) - tp := getParamFloat(data.Params, "top_pct", -1) - bp := getParamFloat(data.Params, "bottom_pct", -1) - - if lp >= 0 && rp > lp && tp >= 0 && bp > tp { - l = int(wDx * lp / 100.0) - r = int(wDx * rp / 100.0) - t = int(hDy * tp / 100.0) - b = int(hDy * bp / 100.0) - } else { - l = getParamInt(data.Params, "left", 0) - t = getParamInt(data.Params, "top", 0) - r = getParamInt(data.Params, "right", bounds.Dx()) - b = getParamInt(data.Params, "bottom", bounds.Dy()) - } - processed := cropImage(img, l, t, r, b) - buf, finalFmt = compressLogic(processed, format, 95) - case "filter": - f := getParamString(data.Params, "filter", "") - if f == "" { - f = getParamString(data.Params, "filter_type", "BLUR") - } - processed := filterImage(img, f) - buf, finalFmt = compressLogic(processed, format, 95) - case "rotate": - op := getParamString(data.Params, "operation", "90") - processed := rotateImage(img, op) - buf, finalFmt = compressLogic(processed, format, 95) - case "watermark": - wmPath := getParamString(data.Params, "watermark_path", "") - wmBase64 := getParamString(data.Params, "watermark_base64", "") - pos := getParamString(data.Params, "position", "bottom_right") - op := getParamInt(data.Params, "opacity", 60) - - var wmImg image.Image - if wmBase64 != "" { - if commaIdx := strings.Index(wmBase64, ","); commaIdx != -1 { - wmBase64 = wmBase64[commaIdx+1:] - } - if decoded, err := base64.StdEncoding.DecodeString(wmBase64); err == nil { - wmImg, _, _ = image.Decode(bytes.NewReader(decoded)) - } - } else if wmPath != "" { - if wmFile, err := os.Open(wmPath); err == nil { - wmImg, _, _ = image.Decode(wmFile) - wmFile.Close() - } - } - if wmImg != nil { - img = watermarkImage(img, wmImg, pos, op) - } - buf, finalFmt = compressLogic(img, format, 95) - case "adjust": - brightness := getParamFloat(data.Params, "brightness", 0.0) - contrast := getParamFloat(data.Params, "contrast", 0.0) - saturation := getParamFloat(data.Params, "saturation", 0.0) - gamma := getParamFloat(data.Params, "gamma", 1.0) - processed := adjustColor(img, brightness, contrast, saturation, gamma) - buf, finalFmt = compressLogic(processed, format, 95) - case "border": - borderWidth := getParamInt(data.Params, "border_width", 20) - borderColor := getParamString(data.Params, "border_color", "#ffffff") - padAspect := getParamString(data.Params, "pad_aspect", "none") - processed := addBorderCanvas(img, borderWidth, borderColor, padAspect) - buf, finalFmt = compressLogic(processed, format, 95) - case "round_corners": - radius := getParamInt(data.Params, "radius", 35) - isCircle := getParamBool(data.Params, "is_circle", false) - processed := roundCorners(img, radius, isCircle) - buf, finalFmt = compressLogic(processed, "PNG", 95) - case "strip_metadata": - targetFmt := getParamString(data.Params, "format", "original") - if targetFmt == "original" { - targetFmt = format - } - q := getParamInt(data.Params, "quality", 95) - buf, finalFmt = compressLogic(img, targetFmt, q) - case "masker", "mask": - var maskImg image.Image - maskBase64 := getParamString(data.Params, "mask_base64", "") - if maskBase64 != "" { - if commaIdx := strings.Index(maskBase64, ","); commaIdx != -1 { - maskBase64 = maskBase64[commaIdx+1:] - } - if decoded, err := base64.StdEncoding.DecodeString(maskBase64); err == nil { - maskImg, _, _ = image.Decode(bytes.NewReader(decoded)) - } - } - if maskImg != nil { - resizedMask := imaging.Resize(maskImg, img.Bounds().Dx(), img.Bounds().Dy(), imaging.Lanczos) - buf, finalFmt = compressLogic(resizedMask, "PNG", 95) - } else { - blackCanvas := imaging.New(img.Bounds().Dx(), img.Bounds().Dy(), color.Black) - buf, finalFmt = compressLogic(blackCanvas, "PNG", 95) - } - default: - buf, finalFmt = compressLogic(img, format, 95) - } - - relPath, _ := filepath.Rel(uploadsDir, file) - if data.Operation == "convert" || data.Operation == "round_corners" || (data.Operation == "compress" && data.Params["format"] != nil && data.Params["format"] != "original" && data.Params["format"] != "") { - ext := strings.ToLower(finalFmt) - if ext == "jpeg" { - ext = "jpg" - } - relPath = strings.TrimSuffix(relPath, filepath.Ext(relPath)) + "." + ext - } - - targetFilePath := filepath.Join(resultsDir, relPath) - os.MkdirAll(filepath.Dir(targetFilePath), 0755) - - os.WriteFile(targetFilePath, buf, 0644) - totalCompressedSize += int64(len(buf)) + totalCompressedSize += newSize processedCount++ - + pd := map[string]interface{}{ "type": "progress", "current": completed, "total": totalFiles, "filename": filepath.Base(file), } - + if data.Operation == "compress" { pd["original_kb"] = float64(origSize) / 1024 - pd["compressed_kb"] = float64(len(buf)) / 1024 + pd["compressed_kb"] = float64(newSize) / 1024 if origSize > 0 { - pd["reduction"] = (1.0 - float64(len(buf))/float64(origSize)) * 100.0 + pd["reduction"] = (1.0 - float64(newSize)/float64(origSize)) * 100.0 } } - + emitSSE(pd) } diff --git a/cmd/image-manipulator/index.html b/cmd/image-manipulator/index.html index 0b39037..b13ff95 100644 --- a/cmd/image-manipulator/index.html +++ b/cmd/image-manipulator/index.html @@ -61,6 +61,12 @@
0 images
+ + @@ -167,6 +173,20 @@