Privacy Cleaner: EXIF, GPS, Serial Numbers Removed
`
};
strip.innerHTML = configs[currentTool] || "";
}
function renderToolControls() {
const container = document.getElementById("inspector-tab-controls");
if (!container) return;
const cur = filesList[activeIndex];
const natW = cur ? cur.naturalW : 1920;
const natH = cur ? cur.naturalH : 1080;
const panels = {
crop: `
Visual Crop Coordinates
Drag to Frame
Drag directly on the image viewport or resize using the 8 boundary handles. When batch processing, the crop box is applied proportionally across all files.
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: `
Transcode Format
Crisp WebP Transcoding: Powered by Google's native cwebp engine with Sharp-YUV color preservation. Retains full resolution and fine texture without blur (quality 92–98 recommended, 100 for lossless).
`,
compress: `
Compression Engine
Original Size:--
Estimated Output:--
Reduction: --
`,
strip_metadata: `
EXIF Privacy Cleaner
Cleans All Hidden Metadata:
• GPS Geolocation Coordinates
• Camera Model, Serial Number & Lens
• Creation Date, Exposure & Shutter Speeds
• Embedded Thumbnails & Author Tags
`
};
container.innerHTML = panels[currentTool] || "";
}
// ═══════════════════════════════════════════════════════════════════
// STATE MUTATORS
// ═══════════════════════════════════════════════════════════════════
function updateResizeWidth(val) {
const w = parseInt(val, 10) || 0;
toolState.resize.width = w;
if (toolState.resize.maintain_aspect && filesList[activeIndex]) {
const cur = filesList[activeIndex];
const h = Math.round(w * (cur.naturalH / cur.naturalW));
toolState.resize.height = h;
const hIn = document.getElementById("param-height");
if (hIn) hIn.value = h;
}
}
window.updateResizeWidth = updateResizeWidth;
function updateResizeHeight(val) {
const h = parseInt(val, 10) || 0;
toolState.resize.height = h;
if (toolState.resize.maintain_aspect && filesList[activeIndex]) {
const cur = filesList[activeIndex];
const w = Math.round(h * (cur.naturalW / cur.naturalH));
toolState.resize.width = w;
const wIn = document.getElementById("param-width");
if (wIn) wIn.value = w;
}
}
window.updateResizeHeight = updateResizeHeight;
function scaleActiveImage(factor) {
const cur = filesList[activeIndex];
if (!cur) return;
const w = Math.round(cur.naturalW * factor);
const h = Math.round(cur.naturalH * factor);
toolState.resize.width = w;
toolState.resize.height = h;
const wIn = document.getElementById("param-width");
const hIn = document.getElementById("param-height");
if (wIn) wIn.value = w;
if (hIn) hIn.value = h;
showToast(`Scaled to ${Math.round(factor * 100)}% (${w}×${h} px)`, "info");
}
window.scaleActiveImage = scaleActiveImage;
function updateAdjustParam(key, val, labelId) {
toolState.adjust[key] = parseFloat(val);
const l = document.getElementById(labelId);
if (l) l.innerText = val;
}
window.updateAdjustParam = updateAdjustParam;
function applyColorPreset(bri, con, sat, gam) {
toolState.adjust.brightness = bri;
toolState.adjust.contrast = con;
toolState.adjust.saturation = sat;
toolState.adjust.gamma = gam;
const bIn = document.getElementById("param-brightness");
const cIn = document.getElementById("param-contrast");
const sIn = document.getElementById("param-saturation");
const gIn = document.getElementById("param-gamma");
if (bIn) { bIn.value = bri; document.getElementById("val-bri").innerText = bri; }
if (cIn) { cIn.value = con; document.getElementById("val-con").innerText = con; }
if (sIn) { sIn.value = sat; document.getElementById("val-sat").innerText = sat; }
if (gIn) { gIn.value = gam; document.getElementById("val-gam").innerText = gam; }
showToast("Preset applied", "info");
}
window.applyColorPreset = applyColorPreset;
function setFilterQuick(name) {
toolState.filter.filter = name;
const fSelect = document.getElementById("param-filter");
if (fSelect) fSelect.value = name;
renderToolOptions();
executeActiveImage();
}
window.setFilterQuick = setFilterQuick;
function setRotateQuick(op) {
toolState.rotate.operation = op;
const opSelect = document.getElementById("param-operation");
if (opSelect) opSelect.value = op;
executeActiveImage();
}
window.setRotateQuick = setRotateQuick;
function updateRotateAngle(val) {
toolState.rotate.angle = parseInt(val, 10);
toolState.rotate.operation = val;
const l = document.getElementById("val-angle");
if (l) l.innerText = `${val}°`;
const op = document.getElementById("param-operation");
if (op && val !== "0") op.value = val;
}
window.updateRotateAngle = updateRotateAngle;
function updateRoundRadius(val) {
const r = parseInt(val, 10);
toolState.round_corners.radius = r;
const l1 = document.getElementById("val-radius");
const l2 = document.getElementById("opt-round-val");
if (l1) l1.innerText = `${r}px`;
if (l2) l2.innerText = `${r}px`;
}
window.updateRoundRadius = updateRoundRadius;
function updateCircleAvatar(checked) {
toolState.round_corners.is_circle = checked;
const chk1 = document.getElementById("param-circle");
const chk2 = document.getElementById("opt-circle-check");
if (chk1) chk1.checked = checked;
if (chk2) chk2.checked = checked;
}
window.updateCircleAvatar = updateCircleAvatar;
function updateBorderWidth(val) {
const bw = parseInt(val, 10);
toolState.border.border_width = bw;
const l = document.getElementById("val-bwidth");
if (l) l.innerText = `${bw}px`;
}
window.updateBorderWidth = updateBorderWidth;
function setCustomBorderColor(hex) {
toolState.border.border_color = hex;
const cPicker = document.getElementById("param-border-color");
const cHex = document.getElementById("param-border-color-hex");
if (cPicker) cPicker.value = hex;
if (cHex) cHex.value = hex;
}
window.setCustomBorderColor = setCustomBorderColor;
function setAspectPad(pad) {
toolState.border.pad_aspect = pad;
const pSelect = document.getElementById("param-pad-aspect");
if (pSelect) pSelect.value = pad;
renderToolOptions();
}
window.setAspectPad = setAspectPad;
function triggerWatermarkPicker() {
const fileInput = document.getElementById("param-watermark-file");
if (fileInput) fileInput.click();
}
window.triggerWatermarkPicker = triggerWatermarkPicker;
function cacheWatermarkFile(input) {
if (input.files && input.files[0]) {
const file = input.files[0];
toolState.watermark.fileName = file.name;
const reader = new FileReader();
reader.onload = (e) => {
toolState.watermark.base64 = e.target.result;
const fLabel = document.getElementById("val-wm-file");
if (fLabel) fLabel.innerText = file.name;
renderToolOptions();
showToast(`Watermark selected: ${file.name}`, "success");
};
reader.readAsDataURL(file);
}
}
window.cacheWatermarkFile = cacheWatermarkFile;
function setWmPos(pos) {
toolState.watermark.position = pos;
const pSelect = document.getElementById("param-position");
if (pSelect) pSelect.value = pos;
renderToolOptions();
}
window.setWmPos = setWmPos;
function updateWatermarkOpacity(val) {
const op = parseInt(val, 10);
toolState.watermark.opacity = op;
const l = document.getElementById("val-wm-op");
if (l) l.innerText = `${op}%`;
}
window.updateWatermarkOpacity = updateWatermarkOpacity;
function setConvertFormat(fmt) {
toolState.convert.format = fmt;
const fSelect = document.getElementById("param-format");
if (fSelect) fSelect.value = fmt;
renderToolOptions();
}
window.setConvertFormat = setConvertFormat;
function updateConvertQuality(val) {
const q = parseInt(val, 10);
toolState.convert.quality = q;
const l = document.getElementById("val-conv-q");
if (l) l.innerText = `${q}%`;
const lOpt = document.getElementById("opt-conv-val");
if (lOpt) lOpt.innerText = `${q}%`;
const pQ = document.getElementById("param-quality");
if (pQ && pQ.value != q) pQ.value = q;
}
window.updateConvertQuality = updateConvertQuality;
function updateCompressFormat(fmt) {
toolState.compress.format = fmt;
simulateCompressionDebounced();
}
window.updateCompressFormat = updateCompressFormat;
function updateCompressQuality(val) {
const q = parseInt(val, 10);
toolState.compress.quality = q;
const l1 = document.getElementById("val-comp-q");
const l2 = document.getElementById("opt-comp-val");
if (l1) l1.innerText = `${q}%`;
if (l2) l2.innerText = `${q}%`;
simulateCompressionDebounced();
}
window.updateCompressQuality = updateCompressQuality;
// ═══════════════════════════════════════════════════════════════════
// COMPRESSION SIMULATION
// ═══════════════════════════════════════════════════════════════════
let simDebounceTimer;
function simulateCompressionDebounced() {
clearTimeout(simDebounceTimer);
simDebounceTimer = setTimeout(simulateCompression, 350);
}
async function simulateCompression() {
if (currentTool !== "compress" || filesList.length === 0) return;
const current = filesList[activeIndex];
if (!current) return;
const quality = toolState.compress.quality.toString();
const format = toolState.compress.format;
const statOrig = document.getElementById("stat-orig-sz");
const statNew = document.getElementById("stat-new-sz");
const statRed = document.getElementById("stat-red-pct");
const optSim = document.getElementById("opt-comp-sim");
if (statNew) statNew.textContent = "Calculating...";
if (optSim) optSim.textContent = "Calculating...";
try {
const formData = new FormData();
formData.append("image", current.file);
formData.append("quality", quality);
formData.append("format", format);
const res = await fetch(getApiUrl("/simulate-compression"), {
method: "POST",
body: formData
});
const data = await res.json();
if (data.original_size) {
const toMb = (b) => (b / (1024 * 1024)).toFixed(2) + " MB";
const toKb = (b) => (b / 1024).toFixed(0) + " KB";
const fmtSz = (s) => (s > 1024 * 1024 ? toMb(s) : toKb(s));
const origStr = fmtSz(data.original_size);
const newStr = fmtSz(data.new_size);
const redStr = `-${data.reduction.toFixed(1)}%`;
if (statOrig) statOrig.textContent = origStr;
if (statNew) statNew.textContent = newStr;
if (statRed) statRed.textContent = `Reduction: ${redStr}`;
if (optSim) optSim.textContent = `${origStr} → ${newStr} (${redStr})`;
}
} catch (err) {
if (statNew) statNew.textContent = "Error";
if (optSim) optSim.textContent = "Error";
}
}
// ═══════════════════════════════════════════════════════════════════
// EXECUTE ACTIVE IMAGE (Single Operation)
// ═══════════════════════════════════════════════════════════════════
async function executeActiveImage() {
if (!filesList || filesList.length === 0) {
showToast("Please open an image first", "error");
return;
}
const current = filesList[activeIndex];
if (!current) return;
// Masker Special Case
if (currentTool === "masker") {
const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH);
if (!maskDataUrl) {
showToast("Please paint a mask over the object first", "error");
return;
}
const maskBlob = await (await fetch(maskDataUrl)).blob();
const fData = new FormData();
fData.append("images", maskBlob, "mask.png");
await executeEndpointRequest("/mask", fData);
return;
}
const formData = new FormData();
formData.append("images", current.file);
if (currentTool === "crop") {
const img = document.getElementById("ps-active-img");
const imgW = img ? img.clientWidth : current.naturalW;
const imgH = img ? img.clientHeight : current.naturalH;
let { x, y, w, h } = toolState.crop;
if (!w || !h || w <= 0 || h <= 0) {
x = 0; y = 0; w = imgW; h = imgH;
}
const scaleX = current.naturalW / imgW;
const scaleY = current.naturalH / imgH;
const l = Math.max(0, Math.round(x * scaleX));
const t = Math.max(0, Math.round(y * scaleY));
const r = Math.min(current.naturalW, Math.round((x + w) * scaleX));
const b = Math.min(current.naturalH, Math.round((y + h) * scaleY));
const lPct = (x / imgW) * 100;
const tPct = (y / imgH) * 100;
const rPct = ((x + w) / imgW) * 100;
const bPct = ((y + h) / imgH) * 100;
formData.append("left", l.toString());
formData.append("top", t.toString());
formData.append("right", r.toString());
formData.append("bottom", b.toString());
formData.append("left_pct", lPct.toString());
formData.append("top_pct", tPct.toString());
formData.append("right_pct", rPct.toString());
formData.append("bottom_pct", bPct.toString());
} else if (currentTool === "resize") {
const w = toolState.resize.width || current.naturalW;
const h = toolState.resize.height || current.naturalH;
formData.append("width", w.toString());
formData.append("height", h.toString());
formData.append("maintain_aspect", toolState.resize.maintain_aspect ? "true" : "false");
} else if (currentTool === "adjust") {
formData.append("brightness", toolState.adjust.brightness.toString());
formData.append("contrast", toolState.adjust.contrast.toString());
formData.append("saturation", toolState.adjust.saturation.toString());
formData.append("gamma", toolState.adjust.gamma.toString());
} else if (currentTool === "filter") {
formData.append("filter", toolState.filter.filter);
} else if (currentTool === "rotate") {
formData.append("operation", toolState.rotate.operation);
} else if (currentTool === "round_corners") {
formData.append("radius", toolState.round_corners.radius.toString());
formData.append("is_circle", toolState.round_corners.is_circle ? "true" : "false");
} else if (currentTool === "border") {
formData.append("border_width", toolState.border.border_width.toString());
formData.append("border_color", toolState.border.border_color);
formData.append("pad_aspect", toolState.border.pad_aspect);
} else if (currentTool === "watermark") {
const wmFile = document.getElementById("param-watermark-file")?.files[0];
if (wmFile) {
formData.append("watermark", wmFile);
} else if (toolState.watermark.base64) {
formData.append("watermark_base64", toolState.watermark.base64);
} else {
showToast("Please choose a watermark image first", "error");
return;
}
formData.append("position", toolState.watermark.position);
formData.append("opacity", toolState.watermark.opacity.toString());
} else if (currentTool === "convert") {
formData.append("format", toolState.convert.format);
formData.append("quality", toolState.convert.quality.toString());
} else if (currentTool === "compress") {
formData.append("format", toolState.compress.format);
formData.append("quality", toolState.compress.quality.toString());
if (toolState.compress.target_size_mb > 0) {
formData.append("target_size_mb", toolState.compress.target_size_mb.toString());
}
} else if (currentTool === "strip_metadata") {
formData.append("format", toolState.strip_metadata.format);
formData.append("quality", "95");
}
const endpoint = currentTool === "round_corners" ? "/round-corners" :
currentTool === "strip_metadata" ? "/strip-metadata" :
`/${currentTool}`;
await executeEndpointRequest(endpoint, formData);
}
window.executeActiveImage = executeActiveImage;
async function executeEndpointRequest(endpoint, formData) {
showToast("Processing image...", "info");
try {
const res = await fetch(getApiUrl(endpoint), {
method: "POST",
body: formData
});
const data = await res.json();
if (res.ok && data.results && data.results.length > 0) {
const resItem = data.results[0];
const cur = filesList[activeIndex];
// Update current active image in place
cur.dataUrl = resItem.image;
if (resItem.info) {
cur.naturalW = resItem.info.width;
cur.naturalH = resItem.info.height;
}
// Re-convert data URI to Blob to update File reference
const blob = await (await fetch(resItem.image)).blob();
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");
}
} catch (err) {
showToast(`Network error: ${err.message}`, "error");
}
}
// ═══════════════════════════════════════════════════════════════════
// EXECUTE BATCH ALL (Universal Batch Across All Tools)
// ═══════════════════════════════════════════════════════════════════
async function executeBatchAll() {
if (!filesList || filesList.length === 0) {
showToast("No images to process", "error");
return;
}
// Open modal
openBatchModal();
logBatchConsole(`Starting batch execution for tool: [${currentTool.toUpperCase()}] across ${filesList.length} files...`);
// Build parameters object for batch
const params = {};
const current = filesList[activeIndex] || filesList[0];
if (currentTool === "crop") {
const img = document.getElementById("ps-active-img");
const imgW = img ? img.clientWidth : current.naturalW;
const imgH = img ? img.clientHeight : current.naturalH;
let { x, y, w, h } = toolState.crop;
if (!w || !h || w <= 0 || h <= 0) {
x = 0; y = 0; w = imgW; h = imgH;
}
params.left_pct = (x / imgW) * 100;
params.top_pct = (y / imgH) * 100;
params.right_pct = ((x + w) / imgW) * 100;
params.bottom_pct = ((y + h) / imgH) * 100;
} else if (currentTool === "resize") {
params.width = toolState.resize.width || current.naturalW;
params.height = toolState.resize.height || current.naturalH;
params.maintain_aspect = toolState.resize.maintain_aspect;
} else if (currentTool === "adjust") {
params.brightness = toolState.adjust.brightness;
params.contrast = toolState.adjust.contrast;
params.saturation = toolState.adjust.saturation;
params.gamma = toolState.adjust.gamma;
} else if (currentTool === "filter") {
params.filter = toolState.filter.filter;
} else if (currentTool === "rotate") {
params.operation = toolState.rotate.operation;
} else if (currentTool === "round_corners") {
params.radius = toolState.round_corners.radius;
params.is_circle = toolState.round_corners.is_circle;
} else if (currentTool === "border") {
params.border_width = toolState.border.border_width;
params.border_color = toolState.border.border_color;
params.pad_aspect = toolState.border.pad_aspect;
} else if (currentTool === "watermark") {
if (toolState.watermark.base64) {
params.watermark_base64 = toolState.watermark.base64;
}
params.position = toolState.watermark.position;
params.opacity = toolState.watermark.opacity;
} else if (currentTool === "masker") {
const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH);
if (maskDataUrl) {
params.mask_base64 = maskDataUrl;
}
} else if (currentTool === "convert") {
params.format = toolState.convert.format;
params.quality = toolState.convert.quality;
} else if (currentTool === "compress") {
params.format = toolState.compress.format;
params.quality = toolState.compress.quality;
if (toolState.compress.target_size_mb > 0) {
params.target_size_mb = toolState.compress.target_size_mb;
}
} else if (currentTool === "strip_metadata") {
params.format = toolState.strip_metadata.format;
params.quality = 95;
}
// Calculate total MB
const totalBytes = filesList.reduce((acc, f) => acc + f.size, 0);
const totalMb = totalBytes / (1024 * 1024);
params.current_size_mb = totalMb;
try {
// 1. Chunked Upload (Max 15 files or 8MB per chunk for proxy resilience)
const MAX_FILES = 15;
const MAX_BYTES = 8 * 1024 * 1024;
const chunks = [];
let curChunk = [];
let curChunkBytes = 0;
for (const item of filesList) {
if (curChunk.length >= MAX_FILES || (curChunkBytes + item.size > MAX_BYTES && curChunk.length > 0)) {
chunks.push(curChunk);
curChunk = [];
curChunkBytes = 0;
}
curChunk.push(item);
curChunkBytes += item.size;
}
if (curChunk.length > 0) chunks.push(curChunk);
logBatchConsole(`Packaging ${filesList.length} files into ${chunks.length} proxy-safe chunk(s)...`);
const uploadStartTime = performance.now();
let uploadedBytes = 0;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
const pct = Math.round((i / chunks.length) * 50);
updateBatchModalProgress(pct, `Uploading chunk ${i + 1} of ${chunks.length}...`);
const fData = new FormData();
fData.append("chunk_index", i.toString());
fData.append("total_chunks", chunks.length.toString());
fData.append("reset", (i === 0).toString());
if (activeSessionId) fData.append("session_id", activeSessionId);
chunk.forEach(item => {
fData.append("files", item.file);
fData.append("relative_paths", item.name);
});
// 3-Attempt Exponential Backoff
let chunkSuccess = false;
let lastErr = null;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const upRes = await fetch(getApiUrl("/upload-batch"), {
method: "POST",
headers: activeSessionId ? { "X-Session-ID": activeSessionId } : {},
body: fData
});
if (!upRes.ok) throw new Error(`HTTP ${upRes.status}`);
const upData = await upRes.json();
if (upData.session_id) activeSessionId = upData.session_id;
chunkSuccess = true;
break;
} catch (err) {
lastErr = err;
logBatchConsole(`⚠️ Chunk ${i + 1} attempt ${attempt} failed: ${err.message}. Retrying...`);
await new Promise(r => setTimeout(r, 1000 * attempt));
}
}
if (!chunkSuccess) {
throw new Error(`Upload failed on chunk ${i + 1}: ${lastErr?.message || "network error"}`);
}
uploadedBytes += chunk.reduce((acc, it) => acc + it.size, 0);
const elapsedSec = (performance.now() - uploadStartTime) / 1000;
const speedMb = (uploadedBytes / (1024 * 1024)) / (elapsedSec || 1);
const speedEl = document.getElementById("batch-modal-speed");
if (speedEl) speedEl.textContent = `${speedMb.toFixed(1)} MB/s`;
}
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",
headers: {
"Content-Type": "application/json",
...(activeSessionId ? { "X-Session-ID": activeSessionId } : {})
},
body: JSON.stringify({
operation: currentTool,
params: params,
session_id: activeSessionId
})
});
if (!procRes.ok) {
const errTxt = await procRes.text();
throw new Error(`Processing failed (${procRes.status}): ${errTxt}`);
}
const reader = procRes.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let lastResult = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith(":")) continue;
if (line.startsWith("data: ")) {
try {
const ev = JSON.parse(line.substring(6));
if (ev.type === "progress") {
const streamPct = 50 + Math.round((ev.current / ev.total) * 50);
updateBatchModalProgress(streamPct, `Processing image ${ev.current} of ${ev.total}: ${ev.filename}`);
logBatchConsole(`[${ev.current}/${ev.total}] ✓ ${ev.filename}`);
} else if (ev.type === "complete") {
lastResult = ev;
}
} catch (pe) {}
}
}
}
if (lastResult) {
updateBatchModalProgress(100, `Completed! Processed ${lastResult.processed_count} files`);
logBatchConsole(`✓ Batch complete: ${lastResult.processed_count} files processed successfully!`, "success");
// Auto Download ZIP
const dlSession = lastResult.session_id || activeSessionId;
const dlZip = lastResult.zip_name || "processed_images.zip";
const dlUrl = getApiUrl(`/download-batch?session_id=${encodeURIComponent(dlSession)}&zip_name=${encodeURIComponent(dlZip)}`);
logBatchConsole("Downloading processed ZIP archive...");
const dlRes = await fetch(dlUrl);
if (dlRes.ok) {
const blob = await dlRes.blob();
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = dlZip;
document.body.appendChild(a);
a.click();
a.remove();
showToast("Batch complete! ZIP downloaded", "success");
}
document.getElementById("btn-modal-close").style.display = "inline-flex";
} else {
throw new Error("No completion event received from server");
}
} catch (error) {
logBatchConsole(`❌ Error: ${error.message}`, "error");
updateBatchModalProgress(100, `Failed: ${error.message}`);
const fill = document.getElementById("batch-modal-fill");
if (fill) fill.style.background = "#ef4444";
document.getElementById("btn-modal-close").style.display = "inline-flex";
showToast(error.message, "error");
}
}
window.executeBatchAll = executeBatchAll;
// ═══════════════════════════════════════════════════════════════════
// MODAL & CONSOLE HELPERS
// ═══════════════════════════════════════════════════════════════════
function openBatchModal() {
const modal = document.getElementById("batch-modal");
const fill = document.getElementById("batch-modal-fill");
const closeBtn = document.getElementById("btn-modal-close");
const consoleBox = document.getElementById("batch-modal-console");
if (modal) modal.style.display = "flex";
if (fill) { fill.style.width = "0%"; fill.style.background = "linear-gradient(90deg, var(--primary) 0%, var(--accent-cyan) 100%)"; }
if (closeBtn) closeBtn.style.display = "none";
if (consoleBox) consoleBox.innerHTML = "";
updateBatchModalProgress(0, "Initializing...");
}
function closeBatchModal() {
const modal = document.getElementById("batch-modal");
if (modal) modal.style.display = "none";
}
window.closeBatchModal = closeBatchModal;
function updateBatchModalProgress(pct, statusText) {
const pctEl = document.getElementById("batch-modal-pct");
const fillEl = document.getElementById("batch-modal-fill");
const statEl = document.getElementById("batch-modal-status");
if (pctEl) pctEl.textContent = `${pct}%`;
if (fillEl) fillEl.style.width = `${pct}%`;
if (statEl) statEl.textContent = statusText;
}
function logBatchConsole(text, type = "normal") {
const box = document.getElementById("batch-modal-console");
if (!box) return;
const line = document.createElement("div");
line.className = `ps-console-line ${type}`;
line.textContent = `> ${text}`;
box.appendChild(line);
box.scrollTop = box.scrollHeight;
}
// ═══════════════════════════════════════════════════════════════════
// INSPECTOR TAB SWITCHING
// ═══════════════════════════════════════════════════════════════════
function switchInspectorTab(tabName, el) {
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;
// ═══════════════════════════════════════════════════════════════════
// VIEWPORT ZOOM & HUD CONTROLS
// ═══════════════════════════════════════════════════════════════════
function zoomViewport(delta) {
zoomFactor = Math.max(0.25, Math.min(3.5, zoomFactor + delta));
applyZoom();
}
window.zoomViewport = zoomViewport;
function resetZoom() {
zoomFactor = 1.0;
applyZoom();
}
window.resetZoom = resetZoom;
function actualSizeZoom() {
zoomFactor = 1.0;
applyZoom();
}
window.actualSizeZoom = actualSizeZoom;
function applyZoom() {
const stage = document.getElementById("ps-stage-container");
const val = document.getElementById("ps-zoom-val");
if (stage) stage.style.transform = `scale(${zoomFactor})`;
if (val) val.textContent = `${Math.round(zoomFactor * 100)}%`;
}
// ═══════════════════════════════════════════════════════════════════
// KEYBOARD SHORTCUTS (Photoshop Standard Ergonomics)
// ═══════════════════════════════════════════════════════════════════
function setupKeyboardShortcuts() {
document.addEventListener("keydown", (e) => {
if (["INPUT", "SELECT", "TEXTAREA"].includes(e.target.tagName)) {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
executeActiveImage();
}
return;
}
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "o") {
e.preventDefault();
document.getElementById("file-input-multi")?.click();
return;
}
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
executeActiveImage();
return;
}
if (e.key === "Escape") {
closeBatchModal();
return;
}
const key = e.key.toLowerCase();
const toolMap = {
"c": "crop",
"m": "resize",
"r": "rotate",
"a": "adjust",
"f": "filter",
"o": "round_corners",
"d": "border",
"t": "watermark",
"b": "masker",
"e": "convert",
"z": "compress",
"s": "strip_metadata"
};
if (toolMap[key]) {
e.preventDefault();
selectTool(toolMap[key]);
}
});
}
// ═══════════════════════════════════════════════════════════════════
// TOAST NOTIFICATIONS
// ═══════════════════════════════════════════════════════════════════
function showToast(msg, type = "info") {
const container = document.getElementById("toast-container");
if (!container) return;
const toast = document.createElement("div");
toast.className = `toast ${type}`;
const icon = type === "success" ? "fa-circle-check" :
type === "error" ? "fa-circle-exclamation" :
"fa-circle-info";
toast.innerHTML = ` ${msg}`;
container.appendChild(toast);
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.