editor.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. /*
  2. editor.js — UI controller for the Raw Editor WebApp.
  3. Wires the Camera-Raw style controls to the WebGL develop pipeline, handles
  4. file loading (ArozOS input files, file picker, drag & drop), the live
  5. histogram, LUT loading, auto white-balance / auto tone, and saving the
  6. developed image back to the user's storage as a JPEG.
  7. */
  8. (function () {
  9. "use strict";
  10. var renderer = null;
  11. var glOK = true;
  12. var decoded = null; // last decoded {data,width,height,meta,source}
  13. var sourceFile = null; // {filename, filepath} of the opened file
  14. var lut = null; // parsed LUT
  15. var renderQueued = false;
  16. var defaults = {
  17. temperature: 5500, tint: 0, exposure: 0, contrast: 0,
  18. highlights: 0, shadows: 0, whites: 0, blacks: 0,
  19. texture: 0, clarity: 0, dehaze: 0, vibrance: 0, saturation: 0,
  20. vignette: 0, grain: 0, lutAmount: 100
  21. };
  22. var state = Object.assign({}, defaults);
  23. state.baseTemp = 5500;
  24. state.treatment = "color";
  25. state.lutEnabled = true;
  26. state.lutLogInput = false;
  27. // Per-group bypass ("eye") toggles.
  28. state.groupOn = { light: true, color: true, effects: true, lut: true };
  29. // ---- init WebGL ------------------------------------------------------
  30. try {
  31. renderer = GLRender.create(document.getElementById("view"));
  32. } catch (e) {
  33. glOK = false;
  34. showFatal(e.message);
  35. }
  36. // =====================================================================
  37. // Slider wiring
  38. // =====================================================================
  39. function clampToRange(el, v) {
  40. var min = parseFloat(el.dataset.min), max = parseFloat(el.dataset.max);
  41. if (v < min) v = min;
  42. if (v > max) v = max;
  43. return v;
  44. }
  45. function initSliders() {
  46. document.querySelectorAll(".slider").forEach(function (row) {
  47. var key = row.dataset.key;
  48. var range = row.querySelector("input[type=range]");
  49. var num = row.querySelector(".s-val");
  50. var step = row.dataset.step || "1";
  51. range.min = row.dataset.min; range.max = row.dataset.max; range.step = step;
  52. num.min = row.dataset.min; num.max = row.dataset.max; num.step = step;
  53. var def = parseFloat(row.dataset.def);
  54. setSlider(row, def);
  55. range.addEventListener("input", function () {
  56. var v = parseFloat(range.value);
  57. num.value = fmt(v, step);
  58. state[key] = v;
  59. scheduleRender();
  60. });
  61. num.addEventListener("change", function () {
  62. var v = parseFloat(num.value);
  63. if (isNaN(v)) v = parseFloat(row.dataset.def);
  64. v = clampToRange(row, v);
  65. num.value = fmt(v, step);
  66. range.value = v;
  67. state[key] = v;
  68. scheduleRender();
  69. });
  70. // double click resets one slider to its default
  71. row.querySelector(".s-name").addEventListener("dblclick", function () {
  72. setSlider(row, parseFloat(row.dataset.def));
  73. state[key] = parseFloat(row.dataset.def);
  74. scheduleRender();
  75. });
  76. });
  77. }
  78. function fmt(v, step) {
  79. return (parseFloat(step) < 1) ? (Math.round(v * 100) / 100).toString() : Math.round(v).toString();
  80. }
  81. function setSlider(row, v) {
  82. var range = row.querySelector("input[type=range]");
  83. var num = row.querySelector(".s-val");
  84. range.value = v;
  85. num.value = fmt(v, row.dataset.step || "1");
  86. }
  87. function setSliderByKey(key, v) {
  88. var row = document.querySelector('.slider[data-key="' + key + '"]');
  89. if (row) setSlider(row, v);
  90. state[key] = v;
  91. }
  92. // =====================================================================
  93. // Render
  94. // =====================================================================
  95. function scheduleRender() {
  96. if (renderQueued || !renderer || !decoded) return;
  97. renderQueued = true;
  98. requestAnimationFrame(function () {
  99. renderQueued = false;
  100. doRender();
  101. });
  102. }
  103. function getParams() {
  104. var g = state.groupOn;
  105. var p = {
  106. baseTemp: state.baseTemp,
  107. // Color group
  108. temperature: g.color ? state.temperature : state.baseTemp,
  109. tint: g.color ? state.tint : 0,
  110. vibrance: g.color ? state.vibrance : 0,
  111. saturation: g.color ? state.saturation : 0,
  112. // Light group
  113. exposure: g.light ? state.exposure : 0,
  114. contrast: g.light ? state.contrast : 0,
  115. highlights: g.light ? state.highlights : 0,
  116. shadows: g.light ? state.shadows : 0,
  117. whites: g.light ? state.whites : 0,
  118. blacks: g.light ? state.blacks : 0,
  119. // Effects group
  120. texture: g.effects ? state.texture : 0,
  121. clarity: g.effects ? state.clarity : 0,
  122. dehaze: g.effects ? state.dehaze : 0,
  123. vignette: g.effects ? state.vignette : 0,
  124. grain: g.effects ? state.grain : 0,
  125. // LUT group
  126. lutEnabled: !!(lut && state.lutEnabled && g.lut),
  127. lutAmount: state.lutAmount / 100,
  128. lutLogInput: state.lutLogInput
  129. };
  130. if (state.treatment === "bw") { p.saturation = -100; p.vibrance = 0; }
  131. return p;
  132. }
  133. function doRender() {
  134. if (!renderer || !decoded) return;
  135. renderer.render(getParams());
  136. updateHistogram();
  137. updateFilmstrip();
  138. }
  139. // =====================================================================
  140. // Histogram
  141. // =====================================================================
  142. var histSmall = document.createElement("canvas");
  143. histSmall.width = 252; histSmall.height = 84;
  144. var histSmallCtx = histSmall.getContext("2d");
  145. function updateHistogram() {
  146. var view = document.getElementById("view");
  147. var hc = document.getElementById("histogram");
  148. var ctx = hc.getContext("2d");
  149. ctx.clearRect(0, 0, hc.width, hc.height);
  150. if (!decoded) return;
  151. try {
  152. histSmallCtx.drawImage(view, 0, 0, histSmall.width, histSmall.height);
  153. } catch (e) { return; }
  154. var img = histSmallCtx.getImageData(0, 0, histSmall.width, histSmall.height).data;
  155. var r = new Uint32Array(256), g = new Uint32Array(256), b = new Uint32Array(256);
  156. for (var i = 0; i < img.length; i += 4) {
  157. r[img[i]]++; g[img[i + 1]]++; b[img[i + 2]]++;
  158. }
  159. var max = 1;
  160. for (var k = 1; k < 255; k++) { // ignore pure black/white spikes for scaling
  161. if (r[k] > max) max = r[k];
  162. if (g[k] > max) max = g[k];
  163. if (b[k] > max) max = b[k];
  164. }
  165. drawChannel(ctx, r, max, "rgba(255,80,80,0.75)");
  166. drawChannel(ctx, g, max, "rgba(90,220,90,0.75)");
  167. drawChannel(ctx, b, max, "rgba(90,140,255,0.75)");
  168. // Clipping indicators (fraction of pixels pinned to 0 / 255).
  169. var totalPx = histSmall.width * histSmall.height;
  170. var hi = Math.max(r[255], g[255], b[255]);
  171. var lo = Math.max(r[0], g[0], b[0]);
  172. var ch = document.getElementById("clipHigh");
  173. var cs = document.getElementById("clipShadow");
  174. if (ch) ch.classList.toggle("active-high", hi / totalPx > 0.01);
  175. if (cs) cs.classList.toggle("active-shadow", lo / totalPx > 0.01);
  176. }
  177. // Small preview thumbnail in the bottom filmstrip.
  178. function updateFilmstrip() {
  179. var fs = document.getElementById("filmstrip");
  180. var v = document.getElementById("view");
  181. if (!fs || !v.width) return;
  182. var ctx = fs.getContext("2d");
  183. ctx.fillStyle = "#111"; ctx.fillRect(0, 0, fs.width, fs.height);
  184. var s = Math.min(fs.width / v.width, fs.height / v.height);
  185. var w = v.width * s, h = v.height * s;
  186. try { ctx.drawImage(v, (fs.width - w) / 2, (fs.height - h) / 2, w, h); } catch (e) { /* ignore */ }
  187. }
  188. function drawChannel(ctx, arr, max, color) {
  189. var w = ctx.canvas.width, h = ctx.canvas.height;
  190. ctx.globalCompositeOperation = "lighter";
  191. ctx.fillStyle = color;
  192. ctx.beginPath();
  193. ctx.moveTo(0, h);
  194. for (var x = 0; x < 256; x++) {
  195. var v = Math.min(1, arr[x] / max);
  196. var px = (x / 255) * w;
  197. var py = h - v * (h - 2);
  198. ctx.lineTo(px, py);
  199. }
  200. ctx.lineTo(w, h);
  201. ctx.closePath();
  202. ctx.fill();
  203. ctx.globalCompositeOperation = "source-over";
  204. }
  205. // =====================================================================
  206. // File loading
  207. // =====================================================================
  208. function showLoader(text) {
  209. document.getElementById("loaderText").textContent = text || "Working...";
  210. document.getElementById("loader").style.display = "flex";
  211. }
  212. function hideLoader() { document.getElementById("loader").style.display = "none"; }
  213. function showFatal(msg) {
  214. var dh = document.getElementById("dropHint");
  215. if (dh) dh.innerHTML = '<i class="warning circle icon huge"></i><p>' + escapeHtml(msg) + "</p>";
  216. }
  217. function escapeHtml(s) {
  218. return String(s).replace(/[&<>"]/g, function (c) {
  219. return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c];
  220. });
  221. }
  222. function loadFromPath(filepath, filename) {
  223. if (!glOK) return;
  224. sourceFile = { filepath: filepath, filename: filename };
  225. showLoader("Reading file...");
  226. document.getElementById("dropHint").style.display = "none";
  227. var url = "../media?file=" + encodeURIComponent(filepath);
  228. fetch(url).then(function (resp) {
  229. if (!resp.ok) throw new Error("Could not read file (HTTP " + resp.status + ")");
  230. return resp.arrayBuffer();
  231. }).then(function (buf) {
  232. showLoader("Decoding " + (filename || "image") + " ...");
  233. // Defer so the loader paints before the heavy decode.
  234. setTimeout(function () { decodeBuffer(buf, filename); }, 30);
  235. }).catch(function (err) {
  236. hideLoader();
  237. showFatal(err.message || String(err));
  238. });
  239. }
  240. function loadFromArrayBuffer(buf, filename) {
  241. showLoader("Decoding " + (filename || "image") + " ...");
  242. document.getElementById("dropHint").style.display = "none";
  243. setTimeout(function () { decodeBuffer(buf, filename); }, 30);
  244. }
  245. function decodeBuffer(buf, filename) {
  246. RawDecoder.decode(buf, filename).then(function (res) {
  247. decoded = res;
  248. renderer.setImage(res);
  249. document.getElementById("view").style.display = "block";
  250. applyMeta(res.meta, filename, res);
  251. resetAll(true);
  252. fitToWindow();
  253. hideLoader();
  254. }).catch(function (err) {
  255. hideLoader();
  256. showFatal(err.message || String(err));
  257. });
  258. }
  259. function applyMeta(meta, filename, res) {
  260. state.baseTemp = (meta && meta.temp) ? meta.temp : 5500;
  261. defaults.temperature = state.baseTemp;
  262. document.getElementById("fileTitle").textContent =
  263. (filename || "Untitled") + (meta && meta.camera ? " — " + meta.camera : "");
  264. // EXIF line (set before the title call so nothing can block it)
  265. setText("exifShutter", meta && meta.shutter ? formatShutter(meta.shutter) : "--");
  266. setText("exifAperture", meta && meta.aperture ? "f/" + round1(meta.aperture) : "--");
  267. setText("exifIso", meta && meta.iso ? "ISO " + meta.iso : "--");
  268. setText("exifFocal", meta && meta.focal ? Math.round(meta.focal) + " mm" : "--");
  269. try { ao_module_setWindowTitle("Raw Editor - " + (filename || "Untitled")); } catch (e) { /* ignore */ }
  270. // Status line
  271. var srcLabel = { "raw-demosaic": "RAW demosaiced", "embedded-preview": "Embedded preview", "image": "Image" }[res.source] || res.source;
  272. setText("statusInfo", srcLabel + " · " + res.width + " x " + res.height + " px");
  273. }
  274. function formatShutter(t) {
  275. if (t >= 1) return round1(t) + " s";
  276. return "1/" + Math.round(1 / t) + " s";
  277. }
  278. function round1(v) { return Math.round(v * 10) / 10; }
  279. function setText(id, t) { var e = document.getElementById(id); if (e) e.textContent = t; }
  280. // =====================================================================
  281. // White balance presets + auto
  282. // =====================================================================
  283. var wbPresets = { daylight: 5500, cloudy: 6500, shade: 7500, tungsten: 2850, fluorescent: 3800 };
  284. document.getElementById("wbPreset").addEventListener("change", function () {
  285. var v = this.value;
  286. if (v === "asshot") { setSliderByKey("temperature", state.baseTemp); setSliderByKey("tint", 0); }
  287. else if (v === "auto") { autoWhiteBalance(); }
  288. else if (wbPresets[v] != null) { setSliderByKey("temperature", wbPresets[v]); setSliderByKey("tint", 0); }
  289. scheduleRender();
  290. });
  291. // When temp/tint are edited manually flip the preset to Custom.
  292. ["temperature", "tint"].forEach(function (key) {
  293. var row = document.querySelector('.slider[data-key="' + key + '"]');
  294. row.querySelector("input[type=range]").addEventListener("input", function () {
  295. document.getElementById("wbPreset").value = "custom";
  296. });
  297. });
  298. function autoWhiteBalance() {
  299. if (!decoded) return;
  300. var d = decoded.data, n = d.length;
  301. var sr = 0, sg = 0, sb = 0, cnt = 0;
  302. var stride = Math.max(4, Math.floor(n / 4 / 40000) * 4);
  303. for (var i = 0; i < n; i += stride) { sr += d[i]; sg += d[i + 1]; sb += d[i + 2]; cnt++; }
  304. var ar = sr / cnt, ag = sg / cnt, ab = sb / cnt;
  305. if (ar <= 0 || ab <= 0) return;
  306. // Solve kelvinGain to equalise R and B: (1+0.9wr)/(1-0.9wr) = ab/ar.
  307. var ratio = ab / ar;
  308. var wr = (ratio - 1) / (0.9 * (ratio + 1));
  309. wr = Math.max(-1, Math.min(1, wr));
  310. var temp = state.baseTemp * Math.exp(wr * (Math.log(50000) - Math.log(2000)));
  311. temp = Math.max(2000, Math.min(50000, temp));
  312. // Tint: green vs magenta balance.
  313. var tint = ((ar + ab) / 2 - ag) / ((ar + ab) / 2 + ag) * 150;
  314. tint = Math.max(-150, Math.min(150, tint));
  315. setSliderByKey("temperature", Math.round(temp));
  316. setSliderByKey("tint", Math.round(tint));
  317. }
  318. // =====================================================================
  319. // Auto tone / reset
  320. // =====================================================================
  321. document.getElementById("btnAuto").addEventListener("click", function () { autoTone(); scheduleRender(); });
  322. document.getElementById("btnDefault").addEventListener("click", function () {
  323. ["exposure", "contrast", "highlights", "shadows", "whites", "blacks"].forEach(function (k) {
  324. setSliderByKey(k, defaults[k]);
  325. });
  326. scheduleRender();
  327. });
  328. function autoTone() {
  329. if (!decoded) return;
  330. var d = decoded.data, n = d.length;
  331. var sum = 0, cnt = 0, hiClip = 0, loClip = 0;
  332. var stride = Math.max(4, Math.floor(n / 4 / 40000) * 4);
  333. for (var i = 0; i < n; i += stride) {
  334. var lum = Math.pow(Math.max(0, 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]), 1 / 2.2);
  335. sum += lum; cnt++;
  336. if (lum > 0.96) hiClip++;
  337. if (lum < 0.03) loClip++;
  338. }
  339. var mean = sum / cnt;
  340. var exposure = Math.log(0.46 / Math.max(0.03, mean)) / Math.log(2);
  341. exposure = Math.max(-2.5, Math.min(2.5, exposure));
  342. setSliderByKey("exposure", Math.round(exposure * 100) / 100);
  343. setSliderByKey("contrast", 8);
  344. setSliderByKey("highlights", hiClip / cnt > 0.02 ? -35 : -10);
  345. setSliderByKey("shadows", loClip / cnt > 0.02 ? 35 : 12);
  346. setSliderByKey("whites", 8);
  347. setSliderByKey("blacks", -6);
  348. }
  349. function resetAll(keepImage) {
  350. Object.keys(defaults).forEach(function (k) {
  351. var def = (k === "temperature") ? state.baseTemp : defaults[k];
  352. setSliderByKey(k, def);
  353. });
  354. state.treatment = "color";
  355. document.getElementById("btnBW").classList.remove("active");
  356. document.getElementById("wbPreset").value = "asshot";
  357. if (keepImage) scheduleRender();
  358. }
  359. document.getElementById("btnReset").addEventListener("click", function () { resetAll(true); });
  360. // Treatment (B&W) toggle in the Edit header
  361. document.getElementById("btnBW").addEventListener("click", function () {
  362. state.treatment = (state.treatment === "bw") ? "color" : "bw";
  363. this.classList.toggle("active", state.treatment === "bw");
  364. scheduleRender();
  365. });
  366. // Auto white balance eyedropper
  367. document.getElementById("btnEyedrop").addEventListener("click", function () {
  368. autoWhiteBalance();
  369. document.getElementById("wbPreset").value = "auto";
  370. scheduleRender();
  371. });
  372. // =====================================================================
  373. // Collapsible groups (chevron) + per-group bypass (eye)
  374. // =====================================================================
  375. document.querySelectorAll(".group-head").forEach(function (head) {
  376. var group = head.parentElement;
  377. head.addEventListener("click", function (e) {
  378. if (e.target.classList.contains("eye-toggle")) return;
  379. group.classList.toggle("collapsed");
  380. });
  381. var eye = head.querySelector(".eye-toggle");
  382. if (eye) {
  383. eye.addEventListener("click", function (e) {
  384. e.stopPropagation();
  385. var key = group.dataset.group;
  386. state.groupOn[key] = !state.groupOn[key];
  387. group.classList.toggle("bypassed", !state.groupOn[key]);
  388. eye.className = state.groupOn[key] ? "eye icon eye-toggle" : "eye slash icon eye-toggle";
  389. scheduleRender();
  390. });
  391. }
  392. });
  393. // =====================================================================
  394. // LUT (library folder in the user's ArozOS storage + local import)
  395. // =====================================================================
  396. var LUT_ROOT = "user:/RawEditor"; // parent folder
  397. var LUT_DIR = "user:/RawEditor/LUTs"; // where .cube files live
  398. function inDesktop() {
  399. return (typeof ao_module_virtualDesktop !== "undefined" && ao_module_virtualDesktop) || window.parent !== window;
  400. }
  401. // --- minimal ArozOS file-system helpers ---
  402. function fsPost(url, body) {
  403. return fetch(url, {
  404. method: "POST",
  405. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  406. body: body
  407. });
  408. }
  409. function fsListDir(dir) {
  410. return fsPost("../system/file_system/listDir", "dir=" + encodeURIComponent(dir)).then(function (r) { return r.json(); });
  411. }
  412. function fsCSRF() {
  413. return fetch("../system/csrf/new").then(function (r) { return r.text(); });
  414. }
  415. function fsNewFolder(src, name) {
  416. return fsCSRF().then(function (token) {
  417. return fsPost("../system/file_system/newItem",
  418. "type=folder&src=" + encodeURIComponent(src) + "&filename=" + encodeURIComponent(name) + "&csrft=" + encodeURIComponent(token));
  419. });
  420. }
  421. function applyLut(parsed, displayName) {
  422. lut = parsed;
  423. renderer.setLUT(lut);
  424. state.lutEnabled = true;
  425. var g = document.querySelector('.group[data-group="lut"]');
  426. if (g) { g.classList.remove("bypassed"); }
  427. state.groupOn.lut = true;
  428. document.getElementById("lutEnabled").checked = true;
  429. // Auto-enable "Log input" for log->display conversion LUTs (F-Log, S-Log,
  430. // V-Log, Log-C, C-Log ...), which expect a flat log signal.
  431. var tag = ((parsed.title || "") + " " + (displayName || "")).toLowerCase();
  432. var isLog = /(^|[^a-z])(f-?log|s-?log|v-?log|log-?c|c-?log|n-?log|d-?log|z-?log|log3|rec709|to_rec|to709|_log|log_)/.test(tag) || tag.indexOf("log") >= 0;
  433. state.lutLogInput = isLog;
  434. document.getElementById("lutLogInput").checked = isLog;
  435. document.getElementById("lutInfo").style.display = "block";
  436. document.getElementById("lutName").textContent = (parsed.title ? parsed.title + " " : "") + displayName + " (" + parsed.size + "³)";
  437. scheduleRender();
  438. }
  439. // Load a LUT stored in the user's storage by virtual path.
  440. function loadLutFromPath(filepath, name) {
  441. fetch("../media?file=" + encodeURIComponent(filepath)).then(function (r) {
  442. if (!r.ok) throw new Error("Could not read file (HTTP " + r.status + ")");
  443. return r.text();
  444. }).then(function (text) {
  445. applyLut(LUTParser.parse(text), name);
  446. }).catch(function (e) { alert("Could not load LUT: " + e.message); });
  447. }
  448. // Populate the library dropdown from a listDir result.
  449. function populateLutLibrary(list) {
  450. var sel = document.getElementById("lutLibrary");
  451. var hint = document.getElementById("lutEmpty");
  452. var current = sel.value;
  453. sel.innerHTML = '<option value="">— Select a LUT —</option>';
  454. var cubes = (list || []).filter(function (f) { return !f.IsDir && /\.cube$/i.test(f.Filename); });
  455. cubes.sort(function (a, b) { return a.Filename.toLowerCase() < b.Filename.toLowerCase() ? -1 : 1; });
  456. cubes.forEach(function (f) {
  457. var o = document.createElement("option");
  458. o.value = f.Filepath;
  459. o.textContent = f.Filename.replace(/\.cube$/i, "");
  460. sel.appendChild(o);
  461. });
  462. if (current) sel.value = current;
  463. if (hint) {
  464. hint.textContent = cubes.length
  465. ? (cubes.length + " LUT" + (cubes.length > 1 ? "s" : "") + " in library")
  466. : "No LUTs yet — add .cube files to user:/RawEditor/LUTs or import one below.";
  467. }
  468. }
  469. // List the LUT folder, creating it (and its parent) on first use.
  470. function refreshLutLibrary() {
  471. if (!inDesktop()) {
  472. var hint = document.getElementById("lutEmpty");
  473. if (hint) hint.textContent = "Library needs the ArozOS desktop — use Import below.";
  474. return;
  475. }
  476. fsListDir(LUT_DIR).then(function (list) {
  477. if (list && list.error) {
  478. // Folder missing — create parent then LUT folder, then retry.
  479. return fsNewFolder("user:/", "RawEditor").catch(function () { }).then(function () {
  480. return fsNewFolder(LUT_ROOT + "/", "LUTs").catch(function () { });
  481. }).then(function () { return fsListDir(LUT_DIR); });
  482. }
  483. return list;
  484. }).then(function (list) {
  485. populateLutLibrary(Array.isArray(list) ? list : []);
  486. }).catch(function () {
  487. var hint = document.getElementById("lutEmpty");
  488. if (hint) hint.textContent = "Could not read the LUT folder.";
  489. });
  490. }
  491. document.getElementById("lutLibrary").addEventListener("change", function () {
  492. if (!this.value) return;
  493. loadLutFromPath(this.value, this.options[this.selectedIndex].text);
  494. });
  495. document.getElementById("btnLutRefresh").addEventListener("click", refreshLutLibrary);
  496. // Import: load a local .cube immediately and (in desktop) save it to the library.
  497. document.getElementById("btnLoadLut").addEventListener("click", function () {
  498. document.getElementById("lutFile").click();
  499. });
  500. document.getElementById("lutFile").addEventListener("change", function () {
  501. var f = this.files[0];
  502. this.value = "";
  503. if (!f) return;
  504. var reader = new FileReader();
  505. reader.onload = function () {
  506. var parsed;
  507. try { parsed = LUTParser.parse(reader.result); }
  508. catch (e) { alert("Could not load LUT: " + e.message); return; }
  509. applyLut(parsed, f.name.replace(/\.cube$/i, ""));
  510. // Persist into the library so it shows up next time.
  511. if (inDesktop() && typeof ao_module_uploadFile === "function") {
  512. fsNewFolder("user:/", "RawEditor").catch(function () { }).then(function () {
  513. return fsNewFolder(LUT_ROOT + "/", "LUTs").catch(function () { });
  514. }).then(function () {
  515. ao_module_uploadFile(f, LUT_DIR, function () { refreshLutLibrary(); });
  516. });
  517. }
  518. };
  519. reader.readAsText(f);
  520. });
  521. document.getElementById("lutEnabled").addEventListener("change", function () {
  522. state.lutEnabled = this.checked;
  523. scheduleRender();
  524. });
  525. document.getElementById("lutLogInput").addEventListener("change", function () {
  526. state.lutLogInput = this.checked;
  527. scheduleRender();
  528. });
  529. document.getElementById("btnClearLut").addEventListener("click", function () {
  530. lut = null;
  531. renderer.setLUT(null);
  532. document.getElementById("lutInfo").style.display = "none";
  533. document.getElementById("lutLibrary").value = "";
  534. scheduleRender();
  535. });
  536. // =====================================================================
  537. // Open / drag & drop
  538. // =====================================================================
  539. function openPicker() {
  540. if (typeof ao_module_openFileSelector === "function" && window.parent !== window) {
  541. ao_module_openFileSelector(function (files) {
  542. if (files && files.length) loadFromPath(files[0].filepath, files[0].filename);
  543. }, "user:/", "file", false);
  544. } else {
  545. var inp = document.createElement("input");
  546. inp.type = "file";
  547. inp.accept = ".arw,.dng,.nef,.cr2,.cr3,.orf,.raf,.rw2,.pef,.srw,.tif,.tiff,.jpg,.jpeg,.png,.webp";
  548. inp.onchange = function () {
  549. var f = inp.files[0];
  550. if (!f) return;
  551. sourceFile = null;
  552. f.arrayBuffer().then(function (buf) { loadFromArrayBuffer(buf, f.name); });
  553. };
  554. inp.click();
  555. }
  556. }
  557. document.getElementById("btnOpen").addEventListener("click", openPicker);
  558. document.getElementById("btnOpen2").addEventListener("click", openPicker);
  559. var stage = document.getElementById("stage");
  560. stage.addEventListener("dragover", function (e) { e.preventDefault(); stage.classList.add("dragover"); });
  561. stage.addEventListener("dragleave", function () { stage.classList.remove("dragover"); });
  562. stage.addEventListener("drop", function (e) {
  563. e.preventDefault();
  564. stage.classList.remove("dragover");
  565. // Local OS file drop.
  566. if (e.dataTransfer.files && e.dataTransfer.files.length) {
  567. var f = e.dataTransfer.files[0];
  568. sourceFile = null;
  569. f.arrayBuffer().then(function (buf) { loadFromArrayBuffer(buf, f.name); });
  570. return;
  571. }
  572. // ArozOS file-explorer drop.
  573. try {
  574. var info = ao_module_utils.getDropFileInfo(e);
  575. if (info && info.length) loadFromPath(info[0].filepath, info[0].filename);
  576. } catch (err) { /* ignore */ }
  577. });
  578. // =====================================================================
  579. // Zoom & pan (scroll to zoom at cursor, right/middle-drag to pan)
  580. // =====================================================================
  581. var vz = { zoom: 1, fit: 1, panX: 0, panY: 0 };
  582. function applyTransform() {
  583. var v = document.getElementById("view");
  584. v.style.transform = "translate(-50%,-50%) translate(" + vz.panX + "px," + vz.panY + "px) scale(" + vz.zoom + ")";
  585. }
  586. function updateZoomLabel() {
  587. var el = document.getElementById("zoomReadout");
  588. if (el) el.textContent = Math.round(vz.zoom * 100) + "%";
  589. }
  590. function computeFit() {
  591. var v = document.getElementById("view");
  592. if (!v.width) return 1;
  593. var pad = 32;
  594. return Math.min((stage.clientWidth - pad) / v.width, (stage.clientHeight - pad) / v.height);
  595. }
  596. function fitToWindow() {
  597. vz.fit = computeFit();
  598. vz.zoom = vz.fit; vz.panX = 0; vz.panY = 0;
  599. applyTransform(); updateZoomLabel();
  600. }
  601. function zoomActual() {
  602. vz.zoom = 1; vz.panX = 0; vz.panY = 0;
  603. applyTransform(); updateZoomLabel();
  604. }
  605. function setZoomAt(z2, cx, cy) {
  606. z2 = Math.max(vz.fit * 0.5, Math.min(16, z2));
  607. // Keep the image point under the cursor fixed while zooming.
  608. vz.panX = cx - (z2 / vz.zoom) * (cx - vz.panX);
  609. vz.panY = cy - (z2 / vz.zoom) * (cy - vz.panY);
  610. vz.zoom = z2;
  611. applyTransform(); updateZoomLabel();
  612. }
  613. document.getElementById("btnFit").addEventListener("click", fitToWindow);
  614. document.getElementById("btnZoomFit").addEventListener("click", fitToWindow);
  615. document.getElementById("btnZoom100").addEventListener("click", zoomActual);
  616. // Scroll to zoom, centred on the cursor.
  617. stage.addEventListener("wheel", function (e) {
  618. if (!decoded) return;
  619. e.preventDefault();
  620. var rect = stage.getBoundingClientRect();
  621. var cx = e.clientX - (rect.left + rect.width / 2);
  622. var cy = e.clientY - (rect.top + rect.height / 2);
  623. var factor = Math.pow(1.0016, -e.deltaY);
  624. setZoomAt(vz.zoom * factor, cx, cy);
  625. }, { passive: false });
  626. // Left (or middle) mouse button drag to pan.
  627. var panning = false, lastX = 0, lastY = 0;
  628. stage.addEventListener("mousedown", function (e) {
  629. if (!decoded || (e.button !== 0 && e.button !== 1)) return;
  630. panning = true; lastX = e.clientX; lastY = e.clientY;
  631. stage.classList.add("panning");
  632. e.preventDefault();
  633. });
  634. window.addEventListener("mousemove", function (e) {
  635. if (!panning) return;
  636. vz.panX += e.clientX - lastX; vz.panY += e.clientY - lastY;
  637. lastX = e.clientX; lastY = e.clientY;
  638. applyTransform();
  639. });
  640. window.addEventListener("mouseup", function () {
  641. if (panning) { panning = false; stage.classList.remove("panning"); }
  642. });
  643. // Re-fit on window resize while the view is at fit zoom.
  644. window.addEventListener("resize", function () {
  645. if (!decoded) return;
  646. if (Math.abs(vz.zoom - vz.fit) < 0.001 && vz.panX === 0 && vz.panY === 0) fitToWindow();
  647. else vz.fit = computeFit();
  648. });
  649. // =====================================================================
  650. // Save + Done
  651. // =====================================================================
  652. document.getElementById("btnSave").addEventListener("click", saveImage);
  653. document.getElementById("btnDone").addEventListener("click", openInPixelStudio);
  654. document.getElementById("btnCancel").addEventListener("click", function () {
  655. if (typeof ao_module_close === "function") ao_module_close();
  656. });
  657. // Hand the developed image off to Pixel Studio: write the current develop to
  658. // a temporary file (tmp:/ is cleared automatically) then launch Pixel Studio
  659. // as a float window with that file as its input.
  660. function openInPixelStudio() {
  661. var inDesktop = (typeof ao_module_virtualDesktop !== "undefined" && ao_module_virtualDesktop);
  662. if (!decoded || !renderer) {
  663. if (typeof ao_module_close === "function") ao_module_close();
  664. return;
  665. }
  666. if (!inDesktop || typeof ao_module_uploadFile !== "function") {
  667. // Outside the ArozOS desktop we cannot open another module — just save.
  668. saveImage();
  669. return;
  670. }
  671. doRender(); // ensure the canvas holds the latest develop
  672. var view = document.getElementById("view");
  673. view.toBlob(function (blob) {
  674. if (!blob) { alert("Failed to encode image."); return; }
  675. var base = (sourceFile && sourceFile.filename) ? stripExt(sourceFile.filename) : "Untitled";
  676. var fname = base + "_raw_" + Date.now() + ".jpg";
  677. var tmpDir = "tmp:/RawEditor";
  678. var file = ao_module_utils.blobToFile(blob, fname);
  679. showLoader("Opening in Pixel Studio...");
  680. ao_module_uploadFile(file, tmpDir, function () {
  681. hideLoader();
  682. launchPixelStudio(tmpDir + "/" + fname, fname);
  683. if (typeof ao_module_close === "function") ao_module_close();
  684. }, undefined, function () {
  685. hideLoader();
  686. alert("Could not hand the image to Pixel Studio. Try 'Save Image...' instead.");
  687. });
  688. }, "image/jpeg", 0.95);
  689. }
  690. function launchPixelStudio(filepath, filename) {
  691. var hash = encodeURIComponent(JSON.stringify([{ filename: filename, filepath: filepath }]));
  692. ao_module_newfw({
  693. url: "Pixel Studio/index.html#" + hash,
  694. width: 1280,
  695. height: 820,
  696. appicon: "Pixel Studio/img/module_icon.png",
  697. title: "Pixel Studio - " + filename
  698. });
  699. }
  700. function saveImage() {
  701. if (!decoded || !renderer) { alert("Nothing to save yet."); return; }
  702. doRender(); // make sure the canvas holds the latest develop
  703. var view = document.getElementById("view");
  704. view.toBlob(function (blob) {
  705. if (!blob) { alert("Failed to encode image."); return; }
  706. var baseName = (sourceFile && sourceFile.filename ? stripExt(sourceFile.filename) : "Untitled") + "_edited.jpg";
  707. if (window.parent !== window && typeof ao_module_openFileSelector === "function") {
  708. var defDir = "user:/Desktop";
  709. if (sourceFile && sourceFile.filepath) {
  710. var parts = sourceFile.filepath.split("/"); parts.pop(); defDir = parts.join("/");
  711. }
  712. ao_module_openFileSelector(function (files) {
  713. if (!files || !files.length) return;
  714. var fp = files[0].filepath.split("/"); var fn = fp.pop(); var dir = fp.join("/");
  715. if (!/\.jpe?g$/i.test(fn)) fn = stripExt(fn) + ".jpg";
  716. uploadBlob(blob, fn, dir);
  717. }, defDir, "new", false, { defaultName: baseName });
  718. } else {
  719. // Fallback: browser download.
  720. var a = document.createElement("a");
  721. a.href = URL.createObjectURL(blob);
  722. a.download = baseName;
  723. a.click();
  724. setTimeout(function () { URL.revokeObjectURL(a.href); }, 4000);
  725. }
  726. }, "image/jpeg", 0.92);
  727. }
  728. function uploadBlob(blob, filename, dir) {
  729. var file = ao_module_utils.blobToFile(blob, filename);
  730. showLoader("Saving " + filename + " ...");
  731. ao_module_uploadFile(file, dir, function () {
  732. hideLoader();
  733. setText("statusInfo", "Saved: " + dir + "/" + filename);
  734. }, undefined, function () {
  735. hideLoader();
  736. alert("Failed to save image to " + dir);
  737. });
  738. }
  739. function stripExt(name) { var i = name.lastIndexOf("."); return i < 0 ? name : name.substring(0, i); }
  740. // =====================================================================
  741. // Boot
  742. // =====================================================================
  743. initSliders();
  744. refreshLutLibrary();
  745. if (glOK) {
  746. var inputFiles = (typeof ao_module_loadInputFiles === "function") ? ao_module_loadInputFiles() : null;
  747. if (inputFiles && inputFiles.length) {
  748. loadFromPath(inputFiles[0].filepath, inputFiles[0].filename);
  749. }
  750. }
  751. })();