feat(image-manipulator): fix inpainting mask offset, add background job governance with time limit, split view and enterprise presets

This commit is contained in:
2026-10-27 15:45:26 +05:30
parent 29d755b645
commit 550d7e23c4
10 changed files with 3034 additions and 399 deletions
+752 -69
View File
@@ -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: `
<div class="ps-options-group">
<span class="ps-options-label">Brush:</span>
<input type="range" min="5" max="150" value="${toolState.masker.brush_size}" style="width: 120px;" oninput="setBrushSize(this.value)">
<span class="label-val" id="opt-brush-val">${toolState.masker.brush_size}px</span>
<span class="ps-options-label">Tool:</span>
<button class="seg-pill ${toolState.masker.mode === 'brush' ? 'active' : ''}" onclick="setMaskMode('brush')"><i class="fa-solid fa-paintbrush"></i> Brush</button>
<button class="seg-pill ${toolState.masker.mode === 'eraser' ? 'active' : ''}" onclick="setMaskMode('eraser')"><i class="fa-solid fa-eraser"></i> Eraser</button>
<button class="seg-pill ${toolState.masker.mode === 'rect' ? 'active' : ''}" onclick="setMaskMode('rect')"><i class="fa-regular fa-square"></i> Box</button>
</div>
<div class="ps-options-group">
<button class="btn btn-secondary btn-sm" onclick="undoMaskStroke()"><i class="fa-solid fa-rotate-left"></i> Undo</button>
<button class="btn btn-secondary btn-sm" onclick="clearMaskStrokes()"><i class="fa-solid fa-trash"></i> Clear</button>
<span class="ps-options-label">Size:</span>
<input type="range" min="4" max="250" value="${toolState.masker.brush_size}" style="width: 100px;" oninput="setBrushSize(this.value)">
<span class="label-val" id="opt-brush-val">${toolState.masker.brush_size}px</span>
<button class="seg-pill" onclick="setBrushSize(15)">15px</button>
<button class="seg-pill" onclick="setBrushSize(40)">40px</button>
<button class="seg-pill" onclick="setBrushSize(90)">90px</button>
</div>
<div class="ps-options-group">
<button class="btn btn-secondary btn-sm" onclick="undoMaskStroke()" title="Undo Stroke"><i class="fa-solid fa-rotate-left"></i> Undo</button>
<button class="btn btn-secondary btn-sm" onclick="redoMaskStroke()" title="Redo Stroke"><i class="fa-solid fa-rotate-right"></i> Redo</button>
<button class="btn btn-secondary btn-sm" onclick="invertMask()" title="Invert Mask"><i class="fa-solid fa-circle-half-stroke"></i> Invert</button>
<button class="btn btn-secondary btn-sm" onclick="fillMask()" title="Fill Whole Mask"><i class="fa-solid fa-fill-drip"></i> Fill</button>
<button class="btn btn-secondary btn-sm" onclick="clearMaskStrokes()" title="Clear Mask"><i class="fa-solid fa-trash"></i> Clear</button>
</div>
`,
convert: `
@@ -1142,13 +1422,43 @@ function renderToolControls() {
</div>
`,
masker: `
<div class="ps-section-title">Mask Generator & Brush</div>
<div class="ps-section-title">Inpainting Mask & Pro Brush</div>
<div class="input-group">
<label>Brush Mode</label>
<div class="seg-pills-row">
<button class="seg-pill ${toolState.masker.mode === 'brush' ? 'active' : ''}" onclick="setMaskMode('brush')"><i class="fa-solid fa-paintbrush"></i> Brush</button>
<button class="seg-pill ${toolState.masker.mode === 'eraser' ? 'active' : ''}" onclick="setMaskMode('eraser')"><i class="fa-solid fa-eraser"></i> Eraser</button>
<button class="seg-pill ${toolState.masker.mode === 'rect' ? 'active' : ''}" onclick="setMaskMode('rect')"><i class="fa-regular fa-square"></i> Box Marquee</button>
</div>
</div>
<div class="input-group">
<label>Brush Diameter <span class="label-val" id="val-brush-sz">${toolState.masker.brush_size}px</span></label>
<input type="range" min="5" max="150" value="${toolState.masker.brush_size}" oninput="setBrushSize(this.value)">
<input type="range" min="4" max="250" value="${toolState.masker.brush_size}" oninput="setBrushSize(this.value)">
</div>
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 12px; margin-top: 10px; font-size: 11.5px;">
<p style="color: var(--text-3); margin: 0;">Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.</p>
<div class="input-group">
<label>Mask Overlay Tint</label>
<div class="seg-pills-row">
<button class="seg-pill" style="border-color: rgba(244, 63, 94, 0.6); color: #f43f5e;" onclick="setMaskColor('rgba(244, 63, 94, 0.70)')">Ruby Red</button>
<button class="seg-pill" style="border-color: rgba(56, 189, 248, 0.6); color: #38bdf8;" onclick="setMaskColor('rgba(56, 189, 248, 0.70)')">Ice Cyan</button>
<button class="seg-pill" style="border-color: rgba(16, 185, 129, 0.6); color: #10b981;" onclick="setMaskColor('rgba(16, 185, 129, 0.70)')">Emerald</button>
</div>
</div>
<div class="input-group">
<label>Quick Actions</label>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 4px;">
<button class="btn btn-secondary btn-sm" onclick="invertMask()"><i class="fa-solid fa-circle-half-stroke"></i> Invert</button>
<button class="btn btn-secondary btn-sm" onclick="fillMask()"><i class="fa-solid fa-fill-drip"></i> Fill Image</button>
<button class="btn btn-secondary btn-sm" onclick="undoMaskStroke()"><i class="fa-solid fa-rotate-left"></i> Undo</button>
<button class="btn btn-secondary btn-sm" onclick="redoMaskStroke()"><i class="fa-solid fa-rotate-right"></i> Redo</button>
</div>
</div>
<div style="margin-top: 10px;">
<button class="btn btn-secondary btn-sm" style="width: 100%;" onclick="exportMaskOnly()">
<i class="fa-solid fa-download"></i> Download Binary Mask PNG
</button>
</div>
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 12px; margin-top: 10px; font-size: 11px;">
<p style="color: var(--text-3); margin: 0;"><i class="fa-solid fa-circle-info" style="color: var(--accent-cyan);"></i> Inpaint Masker paints a pixel-perfect rubylith mask directly over your image. Drawing generates a solid-white binary mask on a pitch-black canvas.</p>
</div>
`,
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 = `
<div style="text-align: center; color: var(--text-muted); font-size: 11.5px; padding: 24px 10px;">
<i class="fa-solid fa-clock-rotate-left" style="font-size: 24px; opacity: 0.4; margin-bottom: 8px; display: block;"></i>
No edit history recorded yet.<br>Apply operations to build snapshot timeline.
</div>`;
return;
}
let html = "";
historySnapshots.forEach((snap, idx) => {
const isLatest = idx === historySnapshots.length - 1;
html += `
<div class="ps-history-item ${isLatest ? 'active' : ''}" onclick="restoreHistoryState(${idx})" title="Click to restore this state">
<div class="ps-history-name">
<i class="fa-solid ${idx === 0 ? 'fa-image' : 'fa-wand-magic-sparkles'}" style="margin-right: 6px; color: ${isLatest ? 'var(--primary)' : 'var(--text-muted)'};"></i>
<span>${snap.label}</span>
</div>
<span class="ps-history-time">${snap.time}</span>
</div>`;
});
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 = `
<div style="text-align: center; color: var(--text-muted); font-size: 11.5px; padding: 24px 10px;">
<i class="fa-solid fa-server" style="font-size: 24px; opacity: 0.4; margin-bottom: 8px; display: block;"></i>
No background jobs found.<br>Dispatch heavy tasks using the "Run in Background" toggle.
</div>`;
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 += `
<div class="ps-job-card" id="job-card-${jId}">
<div class="ps-job-header">
<div style="display: flex; flex-direction: column; gap: 2px;">
<div style="font-weight: 700; font-size: 12px; color: #fff;">
<i class="fa-solid fa-gear" style="color: var(--primary); margin-right: 5px;"></i>
${(job.operation || "Batch").toUpperCase()} Task
</div>
<div style="font-size: 10px; font-family: var(--font-mono); color: var(--text-muted);">${jId}</div>
</div>
<span class="ps-job-badge ${badgeClass}">${job.status}</span>
</div>
<div class="ps-job-meta">
<div class="ps-job-stat">
<span class="ps-job-stat-label">Files</span>
<span class="ps-job-stat-val">${doneFiles} / ${job.total_files || 1}</span>
</div>
<div class="ps-job-stat">
<span class="ps-job-stat-label">Elapsed / Limit</span>
<span class="ps-job-stat-val">${elapsed} / ${limit}</span>
</div>
</div>
<div class="ps-progress-bar-bg" style="height: 5px; margin: 8px 0; background: rgba(255,255,255,0.06); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${job.progress_pct || 0}%; background: var(--primary); transition: width 0.3s ease;"></div>
</div>
<div class="ps-job-actions">
${(job.status === "PROCESSING" || job.status === "QUEUED") ? `
<button class="btn btn-secondary btn-sm" onclick="cancelJob('${jId}')" style="height: 24px; font-size: 10.5px; color: var(--accent-rose); border-color: rgba(244,63,94,0.3);">
<i class="fa-solid fa-stop"></i> Terminate
</button>
` : ''}
${dlUrl ? `
<a href="${dlUrl}" download class="btn btn-primary btn-sm" style="height: 24px; font-size: 10.5px; text-decoration: none; display: inline-flex; align-items: center; gap: 4px;">
<i class="fa-solid fa-download"></i> Download ZIP
</a>
` : ''}
</div>
</div>
`;
});
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;
+171 -229
View File
@@ -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)
}
+170 -12
View File
@@ -61,6 +61,12 @@
<div class="ps-counter-pill" id="ps-file-counter">
<i class="fa-regular fa-images"></i> <span>0 images</span>
</div>
<button class="btn btn-secondary btn-sm" onclick="openPresetsModal()" title="Social Media & E-Commerce Dimension Presets">
<i class="fa-solid fa-shapes"></i> Presets
</button>
<button class="btn btn-secondary btn-sm" id="btn-toggle-split" onclick="toggleSplitView()" title="Compare Before vs After in Split View">
<i class="fa-solid fa-code-compare"></i> Split View
</button>
<button class="btn btn-secondary btn-sm" id="btn-apply-active" onclick="executeActiveImage()" title="Execute on current image (Ctrl+Enter)">
<i class="fa-solid fa-bolt"></i> Apply Active
</button>
@@ -167,6 +173,20 @@
<div class="ps-stage-container" id="ps-stage-container" style="display: none;">
<img id="ps-active-img" class="ps-active-img" alt="Stage Image">
<!-- Split View Before/After Comparison Layer -->
<div class="ps-split-container" id="ps-split-container" style="display: none;">
<div class="ps-split-clip-wrap" id="ps-split-clip-wrap">
<img id="ps-split-before-img" class="ps-split-img" alt="Before">
</div>
<div class="ps-split-bar" id="ps-split-bar">
<div class="ps-split-knob">
<i class="fa-solid fa-arrows-left-right"></i>
</div>
</div>
<span class="ps-split-tag ps-split-tag-before">ORIGINAL</span>
<span class="ps-split-tag ps-split-tag-after">EDITED</span>
</div>
<!-- Visual Interactive Cropper Layer -->
<div class="ps-crop-overlay" id="ps-crop-overlay" style="display: none;">
<div class="crop-scrim crop-scrim-top" id="crop-scrim-t"></div>
@@ -226,14 +246,20 @@
<!-- Right Inspector Panel (Properties & Batch Hub) -->
<aside class="ps-inspector">
<div class="ps-inspector-tabs">
<div class="ps-inspector-tab active" data-tab="controls" onclick="switchInspectorTab('controls', this)">
<i class="fa-solid fa-sliders"></i> Tool Controls
<div class="ps-inspector-tab active" data-tab="controls" onclick="switchInspectorTab('controls', this)" title="Tool Controls">
<i class="fa-solid fa-sliders"></i> Tools
</div>
<div class="ps-inspector-tab" data-tab="info" onclick="switchInspectorTab('info', this)">
<i class="fa-solid fa-circle-info"></i> Image Info
<div class="ps-inspector-tab" data-tab="info" onclick="switchInspectorTab('info', this)" title="Image Info & Audit Telemetry">
<i class="fa-solid fa-circle-info"></i> Info
</div>
<div class="ps-inspector-tab" data-tab="batch" onclick="switchInspectorTab('batch', this)">
<i class="fa-solid fa-layer-group"></i> Batch Hub
<div class="ps-inspector-tab" data-tab="history" onclick="switchInspectorTab('history', this)" title="History Timeline Snapshots">
<i class="fa-solid fa-clock-rotate-left"></i> History
</div>
<div class="ps-inspector-tab" data-tab="batch" onclick="switchInspectorTab('batch', this)" title="Batch Hub & Proxy Pipeline">
<i class="fa-solid fa-layer-group"></i> Batch
</div>
<div class="ps-inspector-tab" data-tab="jobs" onclick="switchInspectorTab('jobs', this)" title="Enterprise Background Jobs & Governance">
<i class="fa-solid fa-server"></i> Jobs <span class="ps-job-counter" id="badge-jobs-count" style="display:none;">0</span>
</div>
</div>
@@ -246,7 +272,7 @@
<!-- Tab 2: Image Info -->
<div id="inspector-tab-info" style="display: none;">
<div class="ps-section-title">Active Image Specs</div>
<div style="display: flex; flex-direction: column; gap: 10px; font-size: 12px; margin-top: 10px;">
<div style="display: flex; flex-direction: column; gap: 8px; font-size: 12px; margin-top: 10px;">
<div style="display: flex; justify-content: space-between; padding: 6px 10px; background: var(--bg-input); border-radius: var(--r-sm);">
<span style="color: var(--text-3);">File Name</span>
<span id="info-filename" style="font-family: var(--font-mono); font-weight: 600; color: #fff; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">--</span>
@@ -267,12 +293,31 @@
<span style="color: var(--text-3);">MIME Type</span>
<span id="info-mimetype" style="font-family: var(--font-mono); font-weight: 600; color: #fff;">--</span>
</div>
<div style="display: flex; justify-content: space-between; padding: 6px 10px; background: var(--bg-input); border-radius: var(--r-sm);">
<span style="color: var(--text-3);">Megapixels</span>
<span id="info-megapixels" style="font-family: var(--font-mono); font-weight: 600; color: var(--accent-purple);">--</span>
</div>
<div style="display: flex; justify-content: space-between; padding: 6px 10px; background: var(--bg-input); border-radius: var(--r-sm);">
<span style="color: var(--text-3);">Audit SHA-256</span>
<span id="info-sha256" style="font-family: var(--font-mono); font-size: 10px; color: var(--text-muted); max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">Verified</span>
</div>
</div>
</div>
<!-- Tab 3: Batch Hub -->
<!-- Tab 3: History Timeline -->
<div id="inspector-tab-history" style="display: none;">
<div class="ps-section-title">
<span>History Snapshots</span>
<button class="btn btn-secondary btn-sm" style="height: 22px; font-size: 10px; padding: 0 6px;" onclick="revertToOriginal()" title="Revert to initial uploaded image">Reset to Original</button>
</div>
<div class="ps-history-list" id="ps-history-list" style="margin-top: 10px; display: flex; flex-direction: column; gap: 6px;">
<!-- Populated dynamically by app.js -->
</div>
</div>
<!-- Tab 4: Batch Hub -->
<div id="inspector-tab-batch" style="display: none;">
<div class="ps-section-title">Queue & Proxy Status</div>
<div class="ps-section-title">Queue & Governance</div>
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 14px; margin-top: 10px; font-size: 12px; display: flex; flex-direction: column; gap: 8px;">
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--text-3);">Queued Images:</span>
@@ -286,9 +331,27 @@
<span style="color: var(--text-3);">Proxy Chunk Size:</span>
<span style="font-weight: 600; font-family: var(--font-mono); color: var(--accent-cyan);">8 MB / 15 files</span>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--text-3);">Retry Strategy:</span>
<span style="font-weight: 600; color: var(--accent-emerald);">3-Attempt Backoff</span>
</div>
<!-- Enterprise Background & Time Limit Options -->
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 14px; margin-top: 12px; font-size: 12px; display: flex; flex-direction: column; gap: 10px;">
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--text-1);">
<input type="checkbox" id="batch-run-background" onchange="toggleBackgroundGovOptions(this.checked)">
<span>Run in Background (Async Worker)</span>
</label>
<p style="font-size: 11px; color: var(--text-muted); margin: 0;">Dispatches the batch job to the server background worker pool so your browser remains completely free.</p>
<div id="batch-gov-timeout-box" style="display: flex; flex-direction: column; gap: 4px;">
<label style="font-size: 11px; font-weight: 600; color: var(--text-2);">Governance Time Limit:</label>
<select id="batch-time-limit-sel" style="height: 32px; font-size: 11.5px;">
<option value="30">30 Seconds (Fast)</option>
<option value="60">1 Minute</option>
<option value="120" selected>2 Minutes (Recommended)</option>
<option value="300">5 Minutes (Heavy Folders)</option>
<option value="900">15 Minutes (Enterprise Bulk)</option>
<option value="1800">30 Minutes (Unlimited Archive)</option>
</select>
<span style="font-size: 10.5px; color: var(--text-muted);"><i class="fa-solid fa-shield-halved"></i> Auto-kills runaway batch tasks when time limit is reached.</span>
</div>
</div>
@@ -298,6 +361,20 @@
</button>
</div>
</div>
<!-- Tab 5: Enterprise Background Jobs -->
<div id="inspector-tab-jobs" style="display: none;">
<div class="ps-section-title">
<span>Background Jobs</span>
<button class="btn btn-secondary btn-sm" style="height: 22px; font-size: 10px; padding: 0 6px;" onclick="refreshBackgroundJobs()" title="Refresh job status list"><i class="fa-solid fa-rotate"></i> Refresh</button>
</div>
<div class="ps-jobs-container" id="ps-jobs-list" style="margin-top: 10px; display: flex; flex-direction: column; gap: 10px;">
<div style="text-align: center; color: var(--text-muted); font-size: 11.5px; padding: 24px 10px;">
<i class="fa-solid fa-server" style="font-size: 24px; opacity: 0.4; margin-bottom: 8px; display: block;"></i>
No active background jobs running.<br>Select "Run in Background" in the Batch tab to dispatch heavy jobs.
</div>
</div>
</div>
</div>
<!-- Inspector Action Footer -->
@@ -345,6 +422,87 @@
</div>
</div>
<!-- Enterprise Presets Modal Dialog -->
<div class="ps-modal-backdrop" id="presets-modal" style="display: none;">
<div class="ps-modal-card" style="max-width: 680px;">
<div class="ps-progress-header">
<h3><i class="fa-solid fa-shapes" style="color: var(--primary);"></i> Social & E-Commerce Presets</h3>
<button class="ps-hud-btn" onclick="closePresetsModal()"><i class="fa-solid fa-xmark"></i></button>
</div>
<p style="font-size: 12px; color: var(--text-3); margin-top: -6px;">Select an enterprise preset to instantly configure aspect ratio and native canvas target dimensions.</p>
<div class="ps-preset-sections">
<div class="ps-section-title" style="margin-top: 10px;">Social Media Formats</div>
<div class="ps-presets-grid">
<div class="ps-preset-card" onclick="applyEnterprisePreset('Instagram Portrait', 1080, 1350, '4:5')">
<div class="ps-preset-icon"><i class="fa-brands fa-instagram"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Instagram Portrait</span>
<span class="ps-preset-dims">1080 × 1350 px (4:5)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('Instagram Square', 1080, 1080, '1:1')">
<div class="ps-preset-icon"><i class="fa-brands fa-instagram"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Instagram Square</span>
<span class="ps-preset-dims">1080 × 1080 px (1:1)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('Story / Reels', 1080, 1920, '9:16')">
<div class="ps-preset-icon"><i class="fa-solid fa-mobile-screen"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Reels / Stories</span>
<span class="ps-preset-dims">1080 × 1920 px (9:16)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('YouTube Thumbnail', 1280, 720, '16:9')">
<div class="ps-preset-icon"><i class="fa-brands fa-youtube"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">YouTube Thumbnail</span>
<span class="ps-preset-dims">1280 × 720 px (16:9)</span>
</div>
</div>
</div>
<div class="ps-section-title" style="margin-top: 14px;">E-Commerce & Marketplaces</div>
<div class="ps-presets-grid">
<div class="ps-preset-card" onclick="applyEnterprisePreset('Shopify Product', 2048, 2048, '1:1')">
<div class="ps-preset-icon"><i class="fa-brands fa-shopify"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Shopify HD Product</span>
<span class="ps-preset-dims">2048 × 2048 px (1:1)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('Amazon Product', 2000, 2000, '1:1')">
<div class="ps-preset-icon"><i class="fa-brands fa-amazon"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Amazon High-Res</span>
<span class="ps-preset-dims">2000 × 2000 px (1:1)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('Profile Avatar', 512, 512, '1:1')">
<div class="ps-preset-icon"><i class="fa-solid fa-circle-user"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Profile Avatar</span>
<span class="ps-preset-dims">512 × 512 px (1:1)</span>
</div>
</div>
<div class="ps-preset-card" onclick="applyEnterprisePreset('Full HD 1080p', 1920, 1080, '16:9')">
<div class="ps-preset-icon"><i class="fa-solid fa-desktop"></i></div>
<div class="ps-preset-info">
<span class="ps-preset-title">Full HD 1080p</span>
<span class="ps-preset-dims">1920 × 1080 px (16:9)</span>
</div>
</div>
</div>
</div>
<div style="display: flex; justify-content: flex-end; margin-top: 14px;">
<button class="btn btn-secondary btn-sm" onclick="closePresetsModal()">Close</button>
</div>
</div>
</div>
<!-- Toast Notifications -->
<div class="toast-container" id="toast-container"></div>
+388
View File
@@ -0,0 +1,388 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"sort"
"sync"
"time"
"github.com/google/uuid"
)
type JobStatus string
const (
JobStatusQueued JobStatus = "QUEUED"
JobStatusProcessing JobStatus = "PROCESSING"
JobStatusCompleted JobStatus = "COMPLETED"
JobStatusFailed JobStatus = "FAILED"
JobStatusTimedOut JobStatus = "TIMED_OUT"
JobStatusCancelled JobStatus = "CANCELLED"
)
type BackgroundJob struct {
JobID string `json:"job_id"`
SessionID string `json:"session_id"`
Operation string `json:"operation"`
Params map[string]interface{} `json:"params"`
Status JobStatus `json:"status"`
TimeLimitSec int `json:"time_limit_sec"`
CreatedAt time.Time `json:"created_at"`
StartedAt time.Time `json:"started_at"`
FinishedAt time.Time `json:"finished_at"`
ElapsedSec float64 `json:"elapsed_sec"`
RemainingSec float64 `json:"remaining_sec"`
ProgressPct int `json:"progress_pct"`
TotalFiles int `json:"total_files"`
CompletedFiles int `json:"completed_files"`
ErrorCount int `json:"error_count"`
Errors []string `json:"errors"`
ZipName string `json:"zip_name"`
OriginalBytes int64 `json:"original_bytes"`
ProcessedBytes int64 `json:"processed_bytes"`
Message string `json:"message"`
cancelFunc context.CancelFunc `json:"-"`
}
type JobManager struct {
jobs map[string]*BackgroundJob
mu sync.RWMutex
}
var globalJobManager = &JobManager{
jobs: make(map[string]*BackgroundJob),
}
func (jm *JobManager) CreateJob(sessionID, operation string, params map[string]interface{}, timeLimitSec int) *BackgroundJob {
if timeLimitSec <= 0 {
timeLimitSec = 120 // Default 2 minutes governance timeout
}
if timeLimitSec > 3600 {
timeLimitSec = 3600 // Max 1 hour
}
jobID := "job_" + uuid.New().String()[:8]
job := &BackgroundJob{
JobID: jobID,
SessionID: sessionID,
Operation: operation,
Params: params,
Status: JobStatusQueued,
TimeLimitSec: timeLimitSec,
CreatedAt: time.Now(),
Errors: []string{},
Message: "Job queued in enterprise background engine",
}
jm.mu.Lock()
jm.jobs[jobID] = job
jm.mu.Unlock()
return job
}
func (jm *JobManager) GetJob(jobID string) *BackgroundJob {
jm.mu.RLock()
defer jm.mu.RUnlock()
job, exists := jm.jobs[jobID]
if !exists {
return nil
}
// Calculate live elapsed and remaining
now := time.Now()
if job.Status == JobStatusProcessing {
job.ElapsedSec = now.Sub(job.StartedAt).Seconds()
rem := float64(job.TimeLimitSec) - job.ElapsedSec
if rem < 0 {
rem = 0
}
job.RemainingSec = rem
} else if job.Status == JobStatusCompleted || job.Status == JobStatusTimedOut || job.Status == JobStatusCancelled || job.Status == JobStatusFailed {
job.ElapsedSec = job.FinishedAt.Sub(job.StartedAt).Seconds()
job.RemainingSec = 0
}
return job
}
func (jm *JobManager) ListJobs() []*BackgroundJob {
jm.mu.RLock()
defer jm.mu.RUnlock()
var list []*BackgroundJob
for _, j := range jm.jobs {
// Update elapsed
now := time.Now()
if j.Status == JobStatusProcessing {
j.ElapsedSec = now.Sub(j.StartedAt).Seconds()
rem := float64(j.TimeLimitSec) - j.ElapsedSec
if rem < 0 {
rem = 0
}
j.RemainingSec = rem
} else if j.FinishedAt.After(j.StartedAt) {
j.ElapsedSec = j.FinishedAt.Sub(j.StartedAt).Seconds()
j.RemainingSec = 0
}
list = append(list, j)
}
sort.Slice(list, func(i, j int) bool {
return list[i].CreatedAt.After(list[j].CreatedAt)
})
return list
}
func (jm *JobManager) CancelJob(jobID string) bool {
jm.mu.Lock()
defer jm.mu.Unlock()
job, exists := jm.jobs[jobID]
if !exists {
return false
}
if job.Status == JobStatusProcessing || job.Status == JobStatusQueued {
if job.cancelFunc != nil {
job.cancelFunc()
}
job.Status = JobStatusCancelled
job.FinishedAt = time.Now()
job.Message = "Job cancelled by enterprise user"
return true
}
return false
}
// StartJob executes the job in background goroutine with strict time-limit governance
func (jm *JobManager) StartJob(job *BackgroundJob) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(job.TimeLimitSec)*time.Second)
job.cancelFunc = cancel
defer cancel()
job.StartedAt = time.Now()
job.Status = JobStatusProcessing
job.Message = fmt.Sprintf("Processing started with %d-second governance time limit", job.TimeLimitSec)
uploadsDir := getSessionDir(job.SessionID, "uploads")
resultsDir := getSessionDir(job.SessionID, "results")
os.RemoveAll(resultsDir)
os.MkdirAll(resultsDir, 0755)
var allFiles []string
filepath.Walk(uploadsDir, func(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() {
allFiles = append(allFiles, path)
}
return nil
})
job.TotalFiles = len(allFiles)
if len(allFiles) == 0 {
job.Status = JobStatusFailed
job.FinishedAt = time.Now()
job.Message = "No files found in upload session"
return
}
zipName := fmt.Sprintf("batch_%s_%s.zip", job.Operation, job.JobID)
job.ZipName = zipName
for i, file := range allFiles {
// Check if context timed out or was cancelled
select {
case <-ctx.Done():
job.FinishedAt = time.Now()
if ctx.Err() == context.DeadlineExceeded {
job.Status = JobStatusTimedOut
job.Message = fmt.Sprintf("Enterprise Governance: Time limit of %d seconds exceeded. Auto-terminated.", job.TimeLimitSec)
slog.Warn("background job timed out", "job_id", job.JobID, "limit_sec", job.TimeLimitSec, "completed", job.CompletedFiles, "total", job.TotalFiles)
} else {
job.Status = JobStatusCancelled
job.Message = "Job cancelled"
}
// Package whatever files were completed before timeout
if job.CompletedFiles > 0 {
createZip(job.SessionID, "results", zipName, "manipulated_partial")
}
return
default:
}
origSize, newSize, err := processSingleBatchFile(file, job.Operation, job.Params, uploadsDir, resultsDir)
if err != nil {
job.ErrorCount++
job.Errors = append(job.Errors, fmt.Sprintf("%s: %v", filepath.Base(file), err))
} else {
job.OriginalBytes += origSize
job.ProcessedBytes += newSize
}
job.CompletedFiles = i + 1
job.ProgressPct = int((float64(job.CompletedFiles) / float64(job.TotalFiles)) * 100)
}
// Success completion
job.FinishedAt = time.Now()
job.Status = JobStatusCompleted
job.ProgressPct = 100
job.Message = fmt.Sprintf("Completed! Processed %d/%d files successfully.", job.CompletedFiles-job.ErrorCount, job.TotalFiles)
err := createZip(job.SessionID, "results", zipName, "manipulated_output")
if err != nil {
slog.Error("failed to create zip for background job", "job_id", job.JobID, "err", err)
job.Errors = append(job.Errors, fmt.Sprintf("Zip generation error: %v", err))
}
}()
}
// Clean old jobs periodically (older than 2 hours)
func cleanupOldJobs() {
globalJobManager.mu.Lock()
defer globalJobManager.mu.Unlock()
now := time.Now()
for id, job := range globalJobManager.jobs {
if now.Sub(job.CreatedAt) > 2*time.Hour {
delete(globalJobManager.jobs, id)
}
}
}
// ═══════════════════════════════════════════════════════════════════
// HTTP HANDLERS FOR BACKGROUND JOB GOVERNANCE
// ═══════════════════════════════════════════════════════════════════
func startBackgroundJobHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req struct {
SessionID string `json:"session_id"`
Operation string `json:"operation"`
TimeLimitSec int `json:"time_limit_sec"`
Params map[string]interface{} `json:"params"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"Invalid request payload"}`, http.StatusBadRequest)
return
}
if req.SessionID == "" || !validateSession(req.SessionID) {
http.Error(w, `{"error":"Invalid or missing session_id"}`, http.StatusBadRequest)
return
}
if req.Operation == "" {
http.Error(w, `{"error":"Operation must be specified"}`, http.StatusBadRequest)
return
}
if req.TimeLimitSec <= 0 {
req.TimeLimitSec = 120
}
job := globalJobManager.CreateJob(req.SessionID, req.Operation, req.Params, req.TimeLimitSec)
globalJobManager.StartJob(job)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "ok",
"job_id": job.JobID,
"time_limit_sec": job.TimeLimitSec,
"message": "Job dispatched to enterprise background worker pool",
})
}
func getJobStatusHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
jobID := r.URL.Query().Get("job_id")
if jobID == "" {
http.Error(w, `{"error":"job_id parameter required"}`, http.StatusBadRequest)
return
}
job := globalJobManager.GetJob(jobID)
if job == nil {
http.Error(w, `{"error":"Job not found"}`, http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(job)
}
func listJobsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
jobs := globalJobManager.ListJobs()
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "ok",
"count": len(jobs),
"jobs": jobs,
})
}
func cancelJobHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
jobID := r.URL.Query().Get("job_id")
if jobID == "" {
var req struct {
JobID string `json:"job_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err == nil {
jobID = req.JobID
}
}
if jobID == "" {
http.Error(w, `{"error":"job_id required"}`, http.StatusBadRequest)
return
}
success := globalJobManager.CancelJob(jobID)
if !success {
http.Error(w, `{"error":"Job could not be cancelled or already finished"}`, http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "ok",
"message": "Job cancelled successfully",
})
}
func downloadJobZipHandler(w http.ResponseWriter, r *http.Request) {
jobID := r.URL.Query().Get("job_id")
if jobID == "" {
http.Error(w, "job_id parameter required", http.StatusBadRequest)
return
}
job := globalJobManager.GetJob(jobID)
if job == nil {
http.Error(w, "Job not found", http.StatusNotFound)
return
}
zipPath := filepath.Join(getSessionDir(job.SessionID), job.ZipName)
if _, err := os.Stat(zipPath); os.IsNotExist(err) {
http.Error(w, "Processed ZIP archive not ready or expired", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", job.ZipName))
http.ServeFile(w, r, zipPath)
}
+8
View File
@@ -148,11 +148,19 @@ func main() {
r.Get("/download-batch", downloadBatchHandler)
r.Head("/download-batch", downloadBatchHandler)
// Enterprise Background Job Governance Routes
r.Post("/api/jobs/start", startBackgroundJobHandler)
r.Get("/api/jobs/status", getJobStatusHandler)
r.Get("/api/jobs/list", listJobsHandler)
r.Post("/api/jobs/cancel", cancelJobHandler)
r.Get("/api/jobs/download", downloadJobZipHandler)
// Start cleanup goroutine
go func() {
for {
time.Sleep(5 * time.Minute)
cleanupOldSessions()
cleanupOldJobs()
// Clean memory store
sessionMutex.Lock()
+306 -4
View File
@@ -759,19 +759,32 @@ html, body {
height: 100%;
cursor: crosshair;
z-index: 26;
opacity: 0.35;
opacity: 0.82;
touch-action: none;
}
#brush-cursor-ring {
position: fixed;
pointer-events: none;
border: 1.5px solid #ff3333;
border: 1.5px solid rgba(244, 63, 94, 0.95);
border-radius: 50%;
transform: translate(-50%, -50%);
display: none;
z-index: 1000;
box-shadow: 0 0 8px rgba(255, 51, 51, 0.6);
z-index: 9999;
box-shadow: 0 0 12px rgba(244, 63, 94, 0.55), inset 0 0 4px rgba(244, 63, 94, 0.35);
}
#brush-cursor-ring::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 3px;
height: 3px;
background: #ffffff;
border-radius: 50%;
transform: translate(-50%, -50%);
box-shadow: 0 0 4px #000;
}
/* ═══════════════════════════════════════════════════════════════════
@@ -1386,3 +1399,292 @@ input[type="range"]::-webkit-slider-thumb:hover {
.toast.error i {
color: #ef4444;
}
/* ═══════════════════════════════════════════════════════════════════
SPLIT VIEW BEFORE / AFTER COMPARISON SLIDER
═══════════════════════════════════════════════════════════════════ */
.ps-split-container {
position: absolute;
inset: 0;
pointer-events: auto;
z-index: 24;
overflow: hidden;
user-select: none;
border-radius: var(--r-md);
}
.ps-split-clip-wrap {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 50%;
overflow: hidden;
border-right: 2px solid var(--accent-cyan);
box-shadow: 2px 0 16px rgba(56, 189, 248, 0.45);
pointer-events: none;
}
.ps-split-img {
position: absolute;
top: 0;
left: 0;
max-width: none;
height: 100%;
display: block;
object-fit: contain;
}
.ps-split-bar {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 3px;
background: var(--accent-cyan);
cursor: ew-resize;
z-index: 28;
transform: translateX(-50%);
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 0 12px var(--accent-cyan-glow);
}
.ps-split-knob {
width: 28px;
height: 28px;
border-radius: 50%;
background: rgba(10, 12, 18, 0.95);
border: 1.5px solid var(--accent-cyan);
color: var(--accent-cyan);
display: flex;
align-items: center;
justify-content: center;
font-size: 11px;
box-shadow: 0 0 16px rgba(0, 0, 0, 0.8), 0 0 10px var(--accent-cyan-glow);
cursor: ew-resize;
pointer-events: none;
}
.ps-split-tag {
position: absolute;
top: 14px;
padding: 4px 10px;
border-radius: var(--r-full);
font-family: var(--font-mono);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
pointer-events: none;
backdrop-filter: blur(12px);
z-index: 27;
}
.ps-split-tag-before {
left: 14px;
background: rgba(139, 92, 246, 0.35);
border: 1px solid rgba(139, 92, 246, 0.55);
color: #ffffff;
box-shadow: 0 0 12px rgba(139, 92, 246, 0.4);
}
.ps-split-tag-after {
right: 14px;
background: rgba(56, 189, 248, 0.35);
border: 1px solid rgba(56, 189, 248, 0.55);
color: #ffffff;
box-shadow: 0 0 12px rgba(56, 189, 248, 0.4);
}
/* ═══════════════════════════════════════════════════════════════════
HISTORY TIMELINE PANEL
═══════════════════════════════════════════════════════════════════ */
.ps-history-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 9px 12px;
background: var(--bg-input);
border: 1px solid var(--border-1);
border-radius: var(--r-md);
cursor: pointer;
transition: all 0.18s ease;
}
.ps-history-item:hover {
background: var(--bg-card-hover);
border-color: var(--border-2);
transform: translateX(2px);
}
.ps-history-item.active {
background: linear-gradient(135deg, rgba(139, 92, 246, 0.25) 0%, rgba(139, 92, 246, 0.08) 100%);
border-color: var(--primary);
box-shadow: 0 0 12px var(--primary-alpha);
}
.ps-history-name {
font-size: 11.5px;
font-weight: 600;
color: var(--text-1);
display: flex;
align-items: center;
gap: 8px;
}
.ps-history-time {
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-muted);
}
/* ═══════════════════════════════════════════════════════════════════
ENTERPRISE BACKGROUND JOBS HUB
═══════════════════════════════════════════════════════════════════ */
.ps-job-counter {
font-size: 9px;
font-family: var(--font-mono);
background: var(--primary);
color: #fff;
padding: 1px 5px;
border-radius: var(--r-full);
margin-left: 4px;
}
.ps-job-card {
background: var(--bg-input);
border: 1px solid var(--border-2);
border-radius: var(--r-md);
padding: 12px 14px;
display: flex;
flex-direction: column;
gap: 8px;
transition: all 0.2s ease;
box-shadow: var(--sh-glass);
}
.ps-job-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.ps-job-id {
font-family: var(--font-mono);
font-size: 11px;
font-weight: 700;
color: #fff;
}
.ps-job-badge {
font-size: 9.5px;
font-family: var(--font-mono);
font-weight: 700;
padding: 2px 7px;
border-radius: 4px;
text-transform: uppercase;
}
.ps-job-badge.processing {
background: rgba(56, 189, 248, 0.20);
border: 1px solid rgba(56, 189, 248, 0.50);
color: #38bdf8;
animation: pulse 1.8s infinite;
}
.ps-job-badge.completed {
background: rgba(16, 185, 129, 0.20);
border: 1px solid rgba(16, 185, 129, 0.50);
color: #10b981;
}
.ps-job-badge.timed_out {
background: rgba(239, 68, 68, 0.20);
border: 1px solid rgba(239, 68, 68, 0.50);
color: #ef4444;
}
.ps-job-badge.cancelled {
background: rgba(148, 163, 184, 0.20);
border: 1px solid rgba(148, 163, 184, 0.40);
color: #94a3b8;
}
.ps-job-timer {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 10.5px;
font-family: var(--font-mono);
color: var(--text-3);
}
.ps-job-actions {
display: flex;
gap: 8px;
margin-top: 4px;
}
/* ═══════════════════════════════════════════════════════════════════
PRESETS MODAL
═══════════════════════════════════════════════════════════════════ */
.ps-presets-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 8px;
}
.ps-preset-card {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
background: var(--bg-card);
border: 1px solid var(--border-2);
border-radius: var(--r-md);
cursor: pointer;
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.ps-preset-card:hover {
background: var(--bg-card-hover);
border-color: var(--primary);
transform: translateY(-2px);
box-shadow: 0 8px 24px var(--primary-alpha);
}
.ps-preset-icon {
width: 34px;
height: 34px;
border-radius: var(--r-md);
background: rgba(139, 92, 246, 0.18);
border: 1px solid rgba(139, 92, 246, 0.35);
color: #c084fc;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
flex-shrink: 0;
}
.ps-preset-info {
display: flex;
flex-direction: column;
gap: 2px;
overflow: hidden;
}
.ps-preset-title {
font-size: 12px;
font-weight: 600;
color: #ffffff;
}
.ps-preset-dims {
font-family: var(--font-mono);
font-size: 10.5px;
color: var(--accent-cyan);
}