Register the musrflow:// URL scheme at startup (electron-builder writes the matching MimeType=x-scheme-handler desktop entry for the packaged Linux builds), accept musrflow://open/#c= links on the launch path and macOS open-url alongside the existing http(s)/bare-fragment forms, and add a web Share button that emits the identical encoded fragment under musrflow://open/ so a browser can hand a configuration to the installed desktop app. Add a musrfit threads field to the Electron Preferences dialog. A set count is passed to local fits as `musrfit -u <n>`; blank keeps the previous all-cores behaviour and the web edition ignores it. Document both features (preferences, runs/fitting, configuration sharing, desktop deployment, CHANGELOG) and rebuild the Sphinx HTML and PDF.
1304 lines
50 KiB
JavaScript
1304 lines
50 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// This file contains functions that are web app specific.
|
|
|
|
if (typeof window.MusrfitWebRequestActive === "undefined") {
|
|
window.MusrfitWebRequestActive = false;
|
|
}
|
|
|
|
// Register this deployment's platform facts for the shared muSRFitlib.js:
|
|
// browser mode, a "." working directory (paths are server-owned), and the web
|
|
// runner that delegates each fit/plot to the CGI. Electron registers the same
|
|
// contract with its local values. Both files load before muSRFitlib.js, which
|
|
// reads this contract when an action runs.
|
|
window.MusRFlowPlatform = window.MusRFlowPlatform || {};
|
|
window.MusRFlowPlatform.webMode = true;
|
|
window.MusRFlowPlatform.currentDirectory = function() {
|
|
return ".";
|
|
};
|
|
window.MusRFlowPlatform.msrFileRunner = async function(fullPath, options) {
|
|
let webRes = await runMSRFileWeb(fullPath, options);
|
|
if (typeof finishJobStatus === "function") {
|
|
finishJobStatus(
|
|
webRes && webRes.ok,
|
|
webRes ? webRes.code : 1,
|
|
webRes ? webRes.statusText : "Web fit request failed.",
|
|
webRes ? webRes.outcome : ""
|
|
);
|
|
}
|
|
return webRes && webRes.ok ? 1 : 0;
|
|
};
|
|
|
|
// MSR generation is synchronous, while the browser must ask the CGI whether a
|
|
// portable data file exists. Resolve selected runs before generation and keep
|
|
// only server-confirmed path pairs in this short-lived per-action cache.
|
|
var webPortableRunResolution = {
|
|
confirmed: new Set(),
|
|
activeDataPath: ""
|
|
};
|
|
|
|
// Web-only shell and I/O adapters for the shared parameter-plot renderer.
|
|
// Plot construction, panel state, Plotly traces, error bars, and controls stay
|
|
// in muSRFitParameterPlot.js; this file owns only browser integration.
|
|
if (!window.MusrfitParameterPlotPlatform) window.MusrfitParameterPlotPlatform = {};
|
|
if (typeof window.MusrfitPlotlyURL === "undefined") {
|
|
window.MusrfitPlotlyURL = "https://cdn.plot.ly/plotly-3.5.1.min.js";
|
|
}
|
|
if (typeof window.MusrfitPlotlyPromise === "undefined") {
|
|
window.MusrfitPlotlyPromise = null;
|
|
}
|
|
function layoutWebMusrfitParameterWindows() {
|
|
if (typeof layoutMusrfitRootWindows === "function") {
|
|
layoutMusrfitRootWindows();
|
|
return;
|
|
}
|
|
let minimizedWindows = document.querySelectorAll('.web-plot-window[data-plot-state="minimized"]');
|
|
let top = 12;
|
|
let right = 12;
|
|
for (let minimizedWindow of minimizedWindows) {
|
|
minimizedWindow.style.left = "auto";
|
|
minimizedWindow.style.right = right + "px";
|
|
minimizedWindow.style.top = top + "px";
|
|
top += minimizedWindow.offsetHeight + 8;
|
|
}
|
|
}
|
|
|
|
function createWebMusrfitParameterPlotWindow(options = {}) {
|
|
let plotWindow = document.createElement("dialog");
|
|
let header = document.createElement("div");
|
|
let dragHandle = document.createElement("div");
|
|
let title = document.createElement("strong");
|
|
let windowControls = document.createElement("div");
|
|
let minimizeButton = document.createElement("button");
|
|
let maximizeButton = document.createElement("button");
|
|
let closeButton = document.createElement("button");
|
|
let content = document.createElement("div");
|
|
let closeHandlers = [];
|
|
let normalBounds = null;
|
|
let stateBeforeMinimize = "normal";
|
|
|
|
plotWindow.className = "web-plot-window parameter-plot-window";
|
|
plotWindow.dataset.plotState = "normal";
|
|
plotWindow.setAttribute("aria-modal", "false");
|
|
plotWindow.tabIndex = -1;
|
|
|
|
header.className = "web-plot-header parameter-plot-header";
|
|
dragHandle.className = "web-plot-drag-handle parameter-plot-drag-handle";
|
|
title.textContent = options.title || "Parameter plot";
|
|
dragHandle.appendChild(title);
|
|
windowControls.className = "web-plot-controls";
|
|
for (let item of [
|
|
[minimizeButton, "−", "Minimize plot"],
|
|
[maximizeButton, "□", "Maximize plot"],
|
|
[closeButton, "×", "Close plot"]
|
|
]) {
|
|
item[0].type = "button";
|
|
item[0].innerHTML = item[1];
|
|
item[0].title = item[2];
|
|
windowControls.appendChild(item[0]);
|
|
}
|
|
header.appendChild(dragHandle);
|
|
header.appendChild(windowControls);
|
|
|
|
content.className = "parameter-plot-content";
|
|
plotWindow.appendChild(header);
|
|
plotWindow.appendChild(content);
|
|
|
|
minimizeButton.addEventListener("click", function() {
|
|
if (plotWindow.dataset.plotState === "minimized") {
|
|
plotWindow.dataset.plotState = stateBeforeMinimize;
|
|
minimizeButton.innerHTML = "−";
|
|
if (stateBeforeMinimize === "maximized") {
|
|
plotWindow.style.left = "12px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = "12px";
|
|
plotWindow.style.width = "calc(100vw - 24px)";
|
|
plotWindow.style.height = "calc(100vh - var(--mu-status-height) - 36px)";
|
|
} else if (normalBounds) {
|
|
plotWindow.style.left = normalBounds.left + "px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = normalBounds.top + "px";
|
|
plotWindow.style.width = normalBounds.width + "px";
|
|
plotWindow.style.height = normalBounds.height + "px";
|
|
}
|
|
layoutWebMusrfitParameterWindows();
|
|
return;
|
|
}
|
|
if (plotWindow.dataset.plotState === "normal") {
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
normalBounds = { left: bounds.left, top: bounds.top, width: bounds.width, height: bounds.height };
|
|
}
|
|
stateBeforeMinimize = plotWindow.dataset.plotState;
|
|
plotWindow.dataset.plotState = "minimized";
|
|
minimizeButton.innerHTML = "⧉";
|
|
plotWindow.style.width = "";
|
|
plotWindow.style.height = "";
|
|
layoutWebMusrfitParameterWindows();
|
|
});
|
|
|
|
maximizeButton.addEventListener("click", function() {
|
|
if (plotWindow.dataset.plotState === "maximized") {
|
|
plotWindow.dataset.plotState = "normal";
|
|
maximizeButton.innerHTML = "□";
|
|
if (normalBounds) {
|
|
plotWindow.style.left = normalBounds.left + "px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = normalBounds.top + "px";
|
|
plotWindow.style.width = normalBounds.width + "px";
|
|
plotWindow.style.height = normalBounds.height + "px";
|
|
}
|
|
return;
|
|
}
|
|
if (plotWindow.dataset.plotState === "normal") {
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
normalBounds = { left: bounds.left, top: bounds.top, width: bounds.width, height: bounds.height };
|
|
}
|
|
plotWindow.dataset.plotState = "maximized";
|
|
minimizeButton.innerHTML = "−";
|
|
maximizeButton.innerHTML = "⧉";
|
|
plotWindow.style.left = "12px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = "12px";
|
|
plotWindow.style.width = "calc(100vw - 24px)";
|
|
plotWindow.style.height = "calc(100vh - var(--mu-status-height) - 36px)";
|
|
layoutWebMusrfitParameterWindows();
|
|
});
|
|
|
|
closeButton.addEventListener("click", function() { plotWindow.close(); });
|
|
plotWindow.addEventListener("close", function() {
|
|
for (let handler of closeHandlers) handler();
|
|
plotWindow.remove();
|
|
layoutWebMusrfitParameterWindows();
|
|
});
|
|
|
|
plotWindow.addEventListener("pointerdown", function() {
|
|
bringMusrfitFloatingWindowToFront(plotWindow);
|
|
try { plotWindow.focus({ preventScroll: true }); } catch (error) { plotWindow.focus(); }
|
|
});
|
|
|
|
let dragPosition = null;
|
|
header.addEventListener("pointerdown", function(event) {
|
|
if (plotWindow.dataset.plotState !== "normal" || windowControls.contains(event.target)) return;
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
dragPosition = {
|
|
pointerX: event.clientX, pointerY: event.clientY,
|
|
windowX: bounds.left, windowY: bounds.top
|
|
};
|
|
header.setPointerCapture(event.pointerId);
|
|
event.preventDefault();
|
|
});
|
|
header.addEventListener("pointermove", function(event) {
|
|
if (!dragPosition) return;
|
|
let maximumX = Math.max(0, window.innerWidth - plotWindow.offsetWidth);
|
|
let maximumY = Math.max(0, window.innerHeight - header.offsetHeight);
|
|
let nextX = dragPosition.windowX + event.clientX - dragPosition.pointerX;
|
|
let nextY = dragPosition.windowY + event.clientY - dragPosition.pointerY;
|
|
plotWindow.style.left = Math.min(maximumX, Math.max(0, nextX)) + "px";
|
|
plotWindow.style.top = Math.min(maximumY, Math.max(0, nextY)) + "px";
|
|
});
|
|
header.addEventListener("pointerup", function(event) {
|
|
dragPosition = null;
|
|
if (header.hasPointerCapture(event.pointerId)) header.releasePointerCapture(event.pointerId);
|
|
});
|
|
|
|
return {
|
|
root: plotWindow,
|
|
content: content,
|
|
keyTarget: plotWindow,
|
|
close: function() { plotWindow.close(); },
|
|
onClose: function(handler) { if (typeof handler === "function") closeHandlers.push(handler); },
|
|
show: function() {
|
|
document.body.appendChild(plotWindow);
|
|
plotWindow.show();
|
|
bringMusrfitFloatingWindowToFront(plotWindow);
|
|
try { plotWindow.focus({ preventScroll: true }); } catch (error) { plotWindow.focus(); }
|
|
let offset = ((Number(options.sequence) || 1) - 1) % 6 * 24;
|
|
let initialX = window.innerWidth - plotWindow.offsetWidth - 12 - offset;
|
|
plotWindow.style.left = Math.max(12, initialX) + "px";
|
|
plotWindow.style.top = 12 + offset + "px";
|
|
}
|
|
};
|
|
}
|
|
|
|
window.MusrfitParameterPlotPlatform.loadPlotly = function() {
|
|
if (window.Plotly) return Promise.resolve(window.Plotly);
|
|
if (!window.MusrfitPlotlyPromise) {
|
|
window.MusrfitPlotlyPromise = new Promise(function(resolve, reject) {
|
|
let script = document.createElement("script");
|
|
script.src = window.MusrfitPlotlyURL;
|
|
script.async = true;
|
|
script.onload = function() {
|
|
if (window.Plotly) resolve(window.Plotly);
|
|
else reject(new Error("Plotly loaded without exposing window.Plotly"));
|
|
};
|
|
script.onerror = function() {
|
|
reject(new Error("Could not load Plotly from " + window.MusrfitPlotlyURL));
|
|
};
|
|
document.head.appendChild(script);
|
|
});
|
|
}
|
|
return window.MusrfitPlotlyPromise;
|
|
};
|
|
|
|
window.MusrfitParameterPlotPlatform.readDataSource = async function(source) {
|
|
if (source && source.kind === "inline") return String(source.text || "");
|
|
if (source && source.kind === "file" && source.file) {
|
|
if (typeof source.file.text === "function") return await source.file.text();
|
|
throw new Error("This browser cannot read the selected parameter-data file");
|
|
}
|
|
let parameterPath = source && source.path ? source.path : String(source || "");
|
|
let response = await fetch(parameterPath, { cache: "no-store" });
|
|
if (!response.ok) throw new Error("Could not load parameter data (HTTP " + response.status + ")");
|
|
return await response.text();
|
|
};
|
|
|
|
window.MusrfitParameterPlotPlatform.chooseDataSource = async function() {
|
|
return await new Promise(function(resolve) {
|
|
let input = document.createElement("input");
|
|
input.type = "file";
|
|
input.accept = ".dat,.txt,text/plain";
|
|
input.addEventListener("change", function() {
|
|
let file = input.files && input.files[0];
|
|
resolve(file ? { kind: "file", file: file, label: file.name } : null);
|
|
}, { once: true });
|
|
input.click();
|
|
});
|
|
};
|
|
|
|
window.MusrfitParameterPlotPlatform.chooseDataSources = async function() {
|
|
return await new Promise(function(resolve) {
|
|
let input = document.createElement("input");
|
|
input.type = "file";
|
|
input.multiple = true;
|
|
input.accept = ".dat,.txt,text/plain";
|
|
input.addEventListener("change", function() {
|
|
let files = input.files ? Array.from(input.files) : [];
|
|
resolve(files.map(function(file) {
|
|
return { kind: "file", file: file, label: file.name };
|
|
}));
|
|
}, { once: true });
|
|
input.click();
|
|
});
|
|
};
|
|
|
|
window.MusrfitParameterPlotPlatform.createPlotWindow = createWebMusrfitParameterPlotWindow;
|
|
window.MusrfitParameterPlotPlatform.openPlot = function(options = {}) {
|
|
showMusrfitParameterPlotWindow(
|
|
options.parameterPath || "",
|
|
options.jobName || "",
|
|
Array.isArray(options.preferredParameters) ? options.preferredParameters : [],
|
|
options.preferredXColumn || "",
|
|
options.preferredTemplate || "",
|
|
options.preferredLayoutMode || "",
|
|
options.savedState || null
|
|
);
|
|
return true;
|
|
};
|
|
function findWebURLSelectValue(selectElement, requestedValue) {
|
|
// URL values come from links written by people and older CGI pages, so match
|
|
// instrument names case-insensitively while still returning the exact option
|
|
// value used by the current GUI. No arbitrary DOM ids or values are accepted.
|
|
if (!selectElement || requestedValue === undefined || requestedValue === null) {
|
|
return "";
|
|
}
|
|
|
|
let requested = String(requestedValue).trim().toLowerCase();
|
|
if (requested === "") {
|
|
return "";
|
|
}
|
|
|
|
let options = selectElement.options ? Array.from(selectElement.options) : [];
|
|
for (let option of options) {
|
|
if (String(option.value).toLowerCase() === requested) {
|
|
return option.value;
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
async function gzipWebSharedText(text) {
|
|
if (typeof CompressionStream !== "function") {
|
|
// Older browsers can still create a compatible, uncompressed link.
|
|
throw new Error("CompressionStream unavailable");
|
|
}
|
|
let bytes = new TextEncoder().encode(text);
|
|
let response = new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip")));
|
|
let zipped = new Uint8Array(await response.arrayBuffer());
|
|
let binary = "";
|
|
const chunkSize = 0x8000;
|
|
for (let i = 0; i < zipped.length; i += chunkSize) {
|
|
binary += String.fromCharCode.apply(null, zipped.subarray(i, i + chunkSize));
|
|
}
|
|
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
|
|
async function encodeWebSharedConfiguration(config) {
|
|
return encodeSharedConfigurationLink(config, gzipWebSharedText);
|
|
}
|
|
|
|
async function decodeWebSharedConfiguration(value) {
|
|
return decodeSharedConfigurationFragment(value, async function(payload) {
|
|
if (typeof DecompressionStream !== "function") {
|
|
throw new Error("this browser cannot decompress shared configurations");
|
|
}
|
|
let text = String(payload || "").replace(/-/g, "+").replace(/_/g, "/");
|
|
while (text.length % 4) text += "=";
|
|
let binary = atob(text);
|
|
let bytes = new Uint8Array(binary.length);
|
|
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
let response = new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")));
|
|
let out = new Uint8Array(await response.arrayBuffer());
|
|
return new TextDecoder().decode(out);
|
|
});
|
|
}
|
|
|
|
async function webWriteClipboard(url) {
|
|
if (typeof navigator !== "undefined" && navigator.clipboard
|
|
&& typeof navigator.clipboard.writeText === "function") {
|
|
await navigator.clipboard.writeText(url);
|
|
} else {
|
|
throw new Error("clipboard API unavailable");
|
|
}
|
|
}
|
|
|
|
async function copyWebConfigurationLink() {
|
|
if (typeof amIWeb === "function" && !amIWeb()) return false;
|
|
return shareConfigurationLink({
|
|
baseURL: function() {
|
|
let location = window.location || {};
|
|
let origin = location.origin && location.origin !== "null" ? location.origin : "";
|
|
return origin + (location.pathname || "/");
|
|
},
|
|
writeClipboard: webWriteClipboard,
|
|
gzipText: gzipWebSharedText
|
|
});
|
|
}
|
|
|
|
// The desktop build registers a custom musrflow:// protocol, which browsers
|
|
// hand to the installed app instead of navigating. Emit the same fragment under
|
|
// that protocol so a user on this page who installed the desktop muSRFlow can
|
|
// open the configuration directly in the app.
|
|
async function copyWebDesktopConfigurationLink() {
|
|
if (typeof amIWeb === "function" && !amIWeb()) return false;
|
|
return shareConfigurationLink({
|
|
baseURL: function() { return MUSRFLOW_DESKTOP_LINK_PREFIX; },
|
|
writeClipboard: webWriteClipboard,
|
|
gzipText: gzipWebSharedText
|
|
});
|
|
}
|
|
|
|
function applyWebURLParameters(search) {
|
|
// Deep links are deliberately a small whitelist. They initialize the same GUI
|
|
// controls a user would edit manually. The optional plot action is handled only
|
|
// after parameter initialization; server paths and other internal settings are
|
|
// never exposed through URL parameter names.
|
|
let result = {
|
|
applied: {},
|
|
errors: [],
|
|
action: ""
|
|
};
|
|
|
|
if (search === undefined || search === null) {
|
|
search = window.location && typeof window.location.search === "string"
|
|
? window.location.search : "";
|
|
}
|
|
if (!search) {
|
|
return result;
|
|
}
|
|
|
|
let params = new URLSearchParams(search);
|
|
let instrumentInput = document.getElementById("instrName");
|
|
let yearInput = document.getElementById("selYear");
|
|
let runInput = document.getElementById("runNumbers");
|
|
if (!instrumentInput || !yearInput || !runInput) {
|
|
result.errors.push("Run controls are not available.");
|
|
return result;
|
|
}
|
|
|
|
// Apply the instrument first because it determines the minimum valid year and
|
|
// the default histogram groups used by the rest of the Runs tab.
|
|
if (params.has("BeamLine")) {
|
|
let requestedBeamLine = params.get("BeamLine");
|
|
let instrumentValue = findWebURLSelectValue(instrumentInput, requestedBeamLine);
|
|
if (instrumentValue) {
|
|
instrumentInput.value = instrumentValue;
|
|
result.applied.BeamLine = instrumentValue;
|
|
} else {
|
|
result.errors.push("Unsupported BeamLine: " + requestedBeamLine);
|
|
}
|
|
}
|
|
|
|
if (params.has("YEAR")) {
|
|
let requestedYear = String(params.get("YEAR") || "").trim();
|
|
let yearNumber = Number(requestedYear);
|
|
let currentMax = Number(yearInput.max) || new Date().getFullYear();
|
|
let instrument = (typeof instPars !== "undefined")
|
|
? instPars[instrumentInput.value] : null;
|
|
let minimumYear = instrument && instrument.minYear
|
|
? Number(instrument.minYear) : Number(yearInput.min || 0);
|
|
let validYear = /^\d{4}$/.test(requestedYear)
|
|
&& Number.isInteger(yearNumber)
|
|
&& yearNumber >= minimumYear
|
|
&& yearNumber <= currentMax;
|
|
|
|
if (validYear) {
|
|
yearInput.value = requestedYear;
|
|
result.applied.YEAR = requestedYear;
|
|
} else {
|
|
let rangeText = minimumYear > 0
|
|
? minimumYear + "-" + currentMax : "a supported four-digit year";
|
|
result.errors.push("Invalid YEAR " + requestedYear + " (expected " + rangeText + ").");
|
|
}
|
|
}
|
|
|
|
if (params.has("RunNumbers")) {
|
|
let requestedRuns = String(params.get("RunNumbers") || "").trim();
|
|
let expandedRuns = (typeof arrayRunNumbers === "function")
|
|
? arrayRunNumbers(requestedRuns) : [];
|
|
if (requestedRuns !== "" && expandedRuns.length > 0) {
|
|
// Preserve the compact text exactly as supplied so bookmarked links keep
|
|
// ranges such as 520-525 instead of expanding them into a long list.
|
|
runInput.value = requestedRuns;
|
|
result.applied.RunNumbers = requestedRuns;
|
|
} else {
|
|
result.errors.push("Invalid RunNumbers: " + (requestedRuns || "(empty)"));
|
|
}
|
|
}
|
|
|
|
if (params.has("action")) {
|
|
let requestedAction = String(params.get("action") || "").trim().toLowerCase();
|
|
if (requestedAction === "plot") {
|
|
// Automatic plotting is intentionally allowed only for a fully specified
|
|
// run deep link. YEAR may be omitted and then keeps the GUI's current year.
|
|
if (result.applied.BeamLine && result.applied.RunNumbers) {
|
|
result.action = "plot";
|
|
} else {
|
|
result.errors.push("action=plot requires BeamLine and RunNumbers.");
|
|
}
|
|
} else if (requestedAction !== "") {
|
|
result.errors.push("Unsupported action: " + requestedAction);
|
|
}
|
|
}
|
|
|
|
if (Object.keys(result.applied).length > 0) {
|
|
// Reuse the normal GUI update path so deep-link initialization cannot drift
|
|
// from manual editing behavior. This keeps histogram defaults, RUN-path
|
|
// validation, and the shared All object synchronized without generating MSR.
|
|
if (typeof defaultHistograms === "function") {
|
|
defaultHistograms(1);
|
|
}
|
|
if (typeof updateResolvedDataPathPreview === "function") {
|
|
updateResolvedDataPathPreview();
|
|
}
|
|
if (typeof prepCFG === "function") {
|
|
prepCFG();
|
|
}
|
|
}
|
|
|
|
if (result.errors.length > 0) {
|
|
let message = result.errors.join(" ");
|
|
if (typeof setRunInputWarning === "function") {
|
|
setRunInputWarning(message, "URL parameters");
|
|
}
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Some URL parameters were ignored.", {
|
|
level: "warning",
|
|
details: "URL parameters: " + message
|
|
});
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async function triggerWebURLAction(result) {
|
|
if (!result || result.action !== "plot") return 0;
|
|
|
|
// Build the parameter table first. cfgParams() returns the pending initial-
|
|
// parameter guess, so a header-based Frq guess is guaranteed to finish before
|
|
// the URL-triggered Plot starts. If guessing is disabled, this resolves at once.
|
|
if (typeof cfgParams === "function") {
|
|
let guess = cfgParams();
|
|
if (guess && typeof guess.then === "function") {
|
|
await guess;
|
|
}
|
|
}
|
|
|
|
if (typeof startPlot !== "function") {
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Plot is not available for this URL.", {
|
|
level: "error",
|
|
details: "URL action: Plot is not available."
|
|
});
|
|
}
|
|
return 0;
|
|
}
|
|
return await startPlot();
|
|
}
|
|
|
|
async function initializeWebURLParameters() {
|
|
// Capture one-shot startup input, then clean the address bar immediately.
|
|
// Shared configuration decoding can continue asynchronously afterwards.
|
|
let result = applyWebURLParameters();
|
|
let hash = window.location && typeof window.location.hash === "string"
|
|
? window.location.hash : "";
|
|
let hasSharedConfiguration = hash.startsWith("#c=") || hash.startsWith("#cfg=");
|
|
|
|
if (window.location && (window.location.search || hasSharedConfiguration)) {
|
|
// Query parameters and shared-configuration fragments are one-shot startup
|
|
// input. Once copied into GUI state, remove both without reloading.
|
|
if (typeof window !== "undefined" && window.location && window.history
|
|
&& typeof window.history.replaceState === "function") {
|
|
let cleanURL = window.location.pathname || "";
|
|
window.history.replaceState({}, "", cleanURL || "/");
|
|
}
|
|
}
|
|
|
|
// Only recognized configuration fragments are decoded. Any other hash is
|
|
// preserved silently so a plain page load never reports an error.
|
|
let shared = hasSharedConfiguration
|
|
? await decodeWebSharedConfiguration(hash)
|
|
: { config: null, error: "", consumed: false };
|
|
result.sharedConfiguration = shared.config;
|
|
if (shared.error) result.errors.push(shared.error);
|
|
|
|
if (shared.config) await restoreSharedConfiguration(shared.config);
|
|
|
|
// When a self-contained parameter-plot stanza was restored, open the plot
|
|
// directly so the web recipient sees the sender's exact plot -- fitted
|
|
// values, scan variable, and error bars -- without needing a local fit or
|
|
// a server copy of the data.
|
|
if (shared.config && typeof openPendingSharedParameterPlot === "function") {
|
|
openPendingSharedParameterPlot();
|
|
}
|
|
|
|
if (result.action === "plot") {
|
|
// Shared-state restoration already rebuilt parameters and waited for the
|
|
// first-run guess. Plain deep links use the established action path.
|
|
if (shared.config && typeof startPlot === "function") await startPlot();
|
|
else await triggerWebURLAction(result);
|
|
}
|
|
|
|
if (shared.error && typeof setFitStatus === "function") {
|
|
setFitStatus("Could not restore the shared configuration.", {
|
|
level: "error",
|
|
details: shared.error
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function postToMusrfitCGI(payload) {
|
|
let pairs = [];
|
|
for (let key in payload) {
|
|
if (!Object.prototype.hasOwnProperty.call(payload, key)) {
|
|
continue;
|
|
}
|
|
if (payload[key] === undefined || payload[key] === null) {
|
|
continue;
|
|
}
|
|
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(payload[key]));
|
|
}
|
|
let request = "/cgi-bin/single_musrfit.cgi";
|
|
try {
|
|
let response = await fetch(request, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded"
|
|
},
|
|
body: pairs.join("&"),
|
|
cache: "no-store"
|
|
});
|
|
let responseText = await response.text();
|
|
let responsePayload = null;
|
|
let parseError = "";
|
|
try {
|
|
responsePayload = JSON.parse(responseText);
|
|
} catch (error) {
|
|
parseError = "Invalid JSON response from " + request;
|
|
let responsePreview = responseText.trim().replace(/\s+/g, " ").substring(0, 240);
|
|
if (responsePreview !== "") {
|
|
parseError += ": " + responsePreview;
|
|
}
|
|
}
|
|
|
|
return {
|
|
ok: response.ok && parseError === "",
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
payload: responsePayload,
|
|
raw: responseText,
|
|
error: parseError
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
ok: false,
|
|
status: 0,
|
|
statusText: "Network error",
|
|
payload: null,
|
|
raw: "",
|
|
error: error && error.message ? error.message : "CGI request failed"
|
|
};
|
|
}
|
|
}
|
|
|
|
function createSeriesMSRWebTransactionAdapter() {
|
|
return {
|
|
transactBatch: async function(batch) {
|
|
if (!batch || !Array.isArray(batch.candidates) || batch.candidates.length === 0) {
|
|
throw new Error("No series candidates were supplied.");
|
|
}
|
|
let jobDirectory = "";
|
|
let candidates = batch.candidates.map(function(candidate) {
|
|
let targetPath = String(candidate.targetPath || "");
|
|
let slash = targetPath.lastIndexOf("/");
|
|
if (slash <= 0 || slash == targetPath.length - 1) {
|
|
throw new Error("Invalid web series target path.");
|
|
}
|
|
let directory = targetPath.substring(0, slash);
|
|
let targetName = targetPath.substring(slash + 1);
|
|
if (jobDirectory === "") jobDirectory = directory;
|
|
if (directory !== jobDirectory
|
|
|| (candidate.targetName && candidate.targetName !== targetName)) {
|
|
throw new Error("Series targets must belong to one web job directory.");
|
|
}
|
|
return {
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
target_name: targetName,
|
|
expected_text: candidate.expectedTargetText || "",
|
|
text: candidate.text
|
|
};
|
|
});
|
|
let request = await postToMusrfitCGI({
|
|
action: "series_transaction",
|
|
// fn is only a validated job-directory anchor. The server derives
|
|
// every target, stage, and backup filename from the JSON batch.
|
|
fn: batch.candidates[0].targetPath,
|
|
transaction: JSON.stringify({
|
|
id: batch.transactionId,
|
|
candidates: candidates
|
|
})
|
|
});
|
|
if (!request.ok || !request.payload) {
|
|
throw new Error(request.error || request.statusText
|
|
|| "Web series transaction failed.");
|
|
}
|
|
return request.payload;
|
|
},
|
|
|
|
finalizeBatch: async function(transaction, decision) {
|
|
if (!transaction || !transaction.transactionId
|
|
|| !Array.isArray(transaction.receipts) || transaction.receipts.length === 0
|
|
|| !["commit", "rollback", "retain"].includes(decision)) {
|
|
throw new Error("Invalid web series finalization request.");
|
|
}
|
|
let targetPath = String(transaction.receipts[0].targetPath || "");
|
|
if (targetPath.lastIndexOf("/") <= 0) {
|
|
throw new Error("Invalid web series transaction target.");
|
|
}
|
|
let request = await postToMusrfitCGI({
|
|
action: "series_transaction_finalize",
|
|
fn: targetPath,
|
|
finalization: JSON.stringify({
|
|
id: transaction.transactionId,
|
|
decision: decision
|
|
})
|
|
});
|
|
if (!request.ok || !request.payload) {
|
|
throw new Error(request.error || request.statusText
|
|
|| "Web series finalization failed.");
|
|
}
|
|
return request.payload;
|
|
}
|
|
};
|
|
}
|
|
|
|
window.createSeriesMSRWebTransactionAdapter = createSeriesMSRWebTransactionAdapter;
|
|
window.MusrfitSeriesTransactionAdapter = createSeriesMSRWebTransactionAdapter();
|
|
|
|
// Execute one target that is already protected by a server-side series
|
|
// transaction. The CGI verifies the private manifest before launching musrfit;
|
|
// no msr2data export, musrview process, GUI synchronization, or finalization is
|
|
// performed by this adapter.
|
|
async function runSeriesMSRCandidateWeb(receipt, candidate, context = {}) {
|
|
if (!receipt || !candidate || receipt.run !== candidate.run
|
|
|| receipt.targetPath !== candidate.targetPath
|
|
|| !context.transactionId) {
|
|
return {
|
|
ok: 0,
|
|
code: 1,
|
|
outcome: "",
|
|
statusText: "Invalid web series candidate receipt."
|
|
};
|
|
}
|
|
let request = await postToMusrfitCGI({
|
|
action: "series_run_candidate",
|
|
fn: receipt.targetPath,
|
|
transaction_id: context.transactionId
|
|
});
|
|
if (!request.ok || !request.payload) {
|
|
return {
|
|
ok: 0,
|
|
code: request.status || 1,
|
|
outcome: "",
|
|
statusText: request.error || request.statusText
|
|
|| "Web series fit request failed."
|
|
};
|
|
}
|
|
let response = request.payload;
|
|
return {
|
|
ok: response.ok ? 1 : 0,
|
|
code: response.code !== undefined ? response.code : (response.ok ? 0 : 1),
|
|
outcome: response.outcome || "",
|
|
missingFiles: Array.isArray(response.missing_files) ? response.missing_files : [],
|
|
targetPath: response.msr_url || receipt.targetPath,
|
|
logPath: response.out_url || "",
|
|
statusText: response.message || "Web series fit request completed.",
|
|
reason: response.reason || ""
|
|
};
|
|
}
|
|
|
|
window.runSeriesMSRCandidateWeb = runSeriesMSRCandidateWeb;
|
|
|
|
// Ask the server to collect already fitted independent-run MSRs. This endpoint
|
|
// never invokes musrfit; it only creates the parameter table, a combined display
|
|
// MSR, and the ROOT canvas used by the browser viewer.
|
|
async function collectIndependentSeriesArtifactsWeb(spec) {
|
|
let prepared = prepareIndependentSeriesCollection(spec);
|
|
let result = normalizeIndependentSeriesCollectionResult({ reason: prepared.reason });
|
|
if (!prepared.ok) return result;
|
|
let workUrl = prepared.workPath.replace(/\/+$/, "");
|
|
for (let index = 0; index < prepared.runs.length; index++) {
|
|
if (prepared.msrPaths[index]
|
|
!== workUrl + "/" + prepared.runs[index] + prepared.fileNameSuffix + ".msr") {
|
|
result.reason = "series-artifact-source-invalid";
|
|
return result;
|
|
}
|
|
}
|
|
|
|
// Generated job files are HTTP-visible, so the browser can perform the
|
|
// pure merge itself using the same implementation as Electron. Failure to
|
|
// build a display file does not block the server-side parameter collection.
|
|
let clientWarnings = [];
|
|
let combinedMSR = "";
|
|
let sourceTexts = await Promise.all(prepared.msrPaths.map(function(path) {
|
|
return readAsciiFile(path);
|
|
}));
|
|
if (sourceTexts.every(function(text) {
|
|
return typeof text === "string" && text !== "";
|
|
})) {
|
|
let merged = buildSeriesGlobalMSR(sourceTexts, prepared.runs);
|
|
if (merged.ok && isValidGeneratedGlobalMSR(merged.text)) {
|
|
combinedMSR = normalizeMSRPlotRuns(merged.text, {}, prepared.runs);
|
|
} else {
|
|
clientWarnings.push("Could not assemble the combined display MSR ("
|
|
+ (merged.reason || "series-merge-invalid") + ").");
|
|
}
|
|
} else {
|
|
clientWarnings.push("Could not fetch all fitted per-run MSR files"
|
|
+ " for the combined display.");
|
|
}
|
|
let collectionRequest = buildIndependentSeriesCollectionRequest(
|
|
prepared, combinedMSR
|
|
);
|
|
|
|
let request = await postToMusrfitCGI({
|
|
action: "series_collect",
|
|
fn: prepared.msrPaths[0],
|
|
collection: JSON.stringify(collectionRequest)
|
|
});
|
|
if (!request.ok || !request.payload) {
|
|
result.reason = "web-series-artifact-request-failed";
|
|
result.warnings.push(request.error || request.statusText
|
|
|| "Series collection request failed.");
|
|
return result;
|
|
}
|
|
|
|
let response = request.payload;
|
|
result.ok = response.ok === true || response.ok === 1;
|
|
result.reason = response.reason || (result.ok
|
|
? "series-artifacts-collected" : "series-artifacts-not-produced");
|
|
result.parameterDataPath = response.parameter_url || "";
|
|
result.combinedMSRPath = response.msr_url || "";
|
|
result.logPath = response.out_url || "";
|
|
result.packagePath = response.package_url || "";
|
|
result.templatePath = response.template_url || "";
|
|
result.warnings = clientWarnings.concat(Array.isArray(response.warnings)
|
|
? response.warnings.filter(Boolean) : []);
|
|
if (response.command_log && typeof appendJobLog === "function") {
|
|
appendJobLog(response.command_log.trim());
|
|
}
|
|
let rootUrls = typeof musrfitRootUrlsFromResponse === "function"
|
|
? musrfitRootUrlsFromResponse(response)
|
|
: (Array.isArray(response.root_urls) ? response.root_urls.filter(Boolean) : []);
|
|
if (rootUrls.length > 0) {
|
|
result.plotPath = rootUrls[0];
|
|
if (typeof showWebRootPlotWindow === "function") {
|
|
showWebRootPlotWindow(rootUrls, response.job_name || "", {
|
|
msrPath: result.combinedMSRPath,
|
|
runs: prepared.runs.join(" "),
|
|
rootItems: Array.isArray(response.root_items) ? response.root_items : []
|
|
});
|
|
result.plotStarted = true;
|
|
}
|
|
}
|
|
return normalizeIndependentSeriesCollectionResult(result);
|
|
}
|
|
|
|
window.collectIndependentSeriesArtifactsWeb = collectIndependentSeriesArtifactsWeb;
|
|
|
|
function webSeriesInventoryFailure(config, execution, reason, message) {
|
|
let all = config.all || {};
|
|
return {
|
|
ok: false,
|
|
mode: execution.mode,
|
|
reason: reason,
|
|
message: message || "",
|
|
execution: execution,
|
|
workPath: normalizeWorkPath(config.workPath || all.workPath || defaultWorkPath),
|
|
fileNameSuffix: config.fileNameSuffix || "",
|
|
availableDataRuns: [],
|
|
entries: [],
|
|
summary: summarizeSeriesFitEntries([])
|
|
};
|
|
}
|
|
|
|
async function resolveWebPortableRunSelection(runSelection, all) {
|
|
let result = { ok: true, resolvedRuns: [], unresolvedRuns: [] };
|
|
if (!portableRunNamingEnabled || !portableRunNamingStartup
|
|
|| typeof portableMusrfitRunCandidates !== "function") {
|
|
return result;
|
|
}
|
|
|
|
let physicalRuns = Array.from(new Set((runSelection || []).reduce(function(runs, dataSet) {
|
|
return runs.concat(seriesDataSetPhysicalRuns(dataSet));
|
|
}, []))).sort(function(a, b) { return a - b; });
|
|
let configuredPaths = Array.isArray(portableRunNamingStartup.dataPaths)
|
|
? portableRunNamingStartup.dataPaths.slice() : [];
|
|
|
|
// pc13280 exposes both unavailable PSI paths and its mounted NEMU path. Try
|
|
// the CGI-selected MUSRFULLDATAPATH first, while retaining every configured
|
|
// root as a fallback for installations with several accessible data trees.
|
|
let activePath = webPortableRunResolution.activeDataPath;
|
|
if (activePath && configuredPaths.includes(activePath)) {
|
|
configuredPaths = [activePath].concat(configuredPaths.filter(function(dataPath) {
|
|
return dataPath !== activePath;
|
|
}));
|
|
}
|
|
|
|
await Promise.all(physicalRuns.map(async function(run) {
|
|
let candidates = portableMusrfitRunCandidates(
|
|
run, all.selYear, all.instrName, portableRunNamingStartup
|
|
);
|
|
for (let candidate of candidates) {
|
|
for (let dataPath of configuredPaths) {
|
|
let cacheKey = dataPath + "\n" + candidate.subPath;
|
|
if (webPortableRunResolution.confirmed.has(cacheKey)) {
|
|
result.resolvedRuns.push(run);
|
|
return;
|
|
}
|
|
|
|
let request = await postToMusrfitCGI({
|
|
action: "resolve_run_name",
|
|
sub_path: candidate.subPath,
|
|
data_path: dataPath
|
|
});
|
|
if (request.ok && request.payload && request.payload.ok === true
|
|
&& request.payload.sub_path === candidate.subPath
|
|
&& request.payload.data_path === dataPath) {
|
|
webPortableRunResolution.confirmed.add(cacheKey);
|
|
result.resolvedRuns.push(run);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
result.ok = false;
|
|
result.unresolvedRuns.push(run);
|
|
}));
|
|
result.resolvedRuns.sort(function(a, b) { return a - b; });
|
|
result.unresolvedRuns.sort(function(a, b) { return a - b; });
|
|
return result;
|
|
}
|
|
|
|
// Ask the server for one immutable read-only snapshot, then run the normal
|
|
// transport-independent classifier against in-memory maps. No browser HEAD
|
|
// request is made for server filesystem paths, and a malformed/incomplete CGI
|
|
// response fails closed before any candidate can be prepared.
|
|
async function inspectSeriesFitPlanWeb(config = {}) {
|
|
let all = config.all || {};
|
|
let runSelection = Array.isArray(config.runSelection)
|
|
? config.runSelection : parseRunSelection(all.runNumbers || config.runNumbers || "");
|
|
let execution = planFitExecution(
|
|
runSelection,
|
|
config.sharedFlags || {},
|
|
{ crossRunCoupling: config.crossRunCoupling === true }
|
|
);
|
|
let webConfig = Object.assign({}, config, {
|
|
all: all,
|
|
runSelection: runSelection,
|
|
webMode: true
|
|
});
|
|
if (execution.mode != "series") {
|
|
return inspectSeriesFitPlan(webConfig, {});
|
|
}
|
|
|
|
let workPath = normalizeWorkPath(config.workPath || all.workPath || defaultWorkPath);
|
|
let fileNameSuffix = config.fileNameSuffix || fitFileSuffix(all, true);
|
|
webConfig.workPath = workPath;
|
|
webConfig.fileNameSuffix = fileNameSuffix;
|
|
|
|
let seenMSR = new Set();
|
|
let msrRequests = [];
|
|
for (let dataSet of runSelection) {
|
|
let name = dataSet.main + fileNameSuffix + ".msr";
|
|
if (seenMSR.has(name)) {
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
"duplicate-series-target", "The run selection resolves to duplicate MSR targets.");
|
|
}
|
|
seenMSR.add(name);
|
|
msrRequests.push({
|
|
run: dataSet.main,
|
|
name: name,
|
|
path: joinSeriesWorkPath(workPath, name)
|
|
});
|
|
}
|
|
|
|
let physicalRuns = Array.from(new Set(runSelection.reduce(function(runs, dataSet) {
|
|
return runs.concat(seriesDataSetPhysicalRuns(dataSet));
|
|
}, []))).sort(function(a, b) { return a - b; });
|
|
await resolveWebPortableRunSelection(runSelection, all);
|
|
let dataRequests = [];
|
|
try {
|
|
dataRequests = physicalRuns.map(function(run) {
|
|
return { run: run, path: seriesDataFilePath(run, all) };
|
|
});
|
|
} catch (error) {
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
"could-not-resolve-data-path", error && error.message ? error.message : "");
|
|
}
|
|
|
|
let request = await postToMusrfitCGI({
|
|
action: "series_inventory",
|
|
fn: msrRequests[0].path,
|
|
inventory: JSON.stringify({
|
|
msr_files: msrRequests.map(function(item) {
|
|
return { run: item.run, name: item.name };
|
|
}),
|
|
data_files: dataRequests.map(function(item) {
|
|
return { run: item.run, path: item.path };
|
|
})
|
|
})
|
|
});
|
|
if (!request.ok || !request.payload || request.payload.ok !== true) {
|
|
let payload = request.payload || {};
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
payload.reason || "web-series-inventory-failed",
|
|
request.error || payload.message || request.statusText || "Web inventory request failed.");
|
|
}
|
|
|
|
let responseMSR = request.payload.msr_files;
|
|
let responseData = request.payload.data_files;
|
|
if (!Array.isArray(responseMSR) || !Array.isArray(responseData)
|
|
|| responseMSR.length !== msrRequests.length
|
|
|| responseData.length !== dataRequests.length) {
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
"web-series-inventory-incomplete", "The server returned an incomplete inventory.");
|
|
}
|
|
|
|
let msrByPath = Object.create(null);
|
|
let requestedMSR = new Map(msrRequests.map(function(item) {
|
|
return [item.name, item];
|
|
}));
|
|
for (let record of responseMSR) {
|
|
let expected = record && requestedMSR.get(record.name);
|
|
if (!expected || record.run !== expected.run || record.path !== expected.path
|
|
|| Object.prototype.hasOwnProperty.call(msrByPath, expected.path)
|
|
|| typeof record.exists !== "boolean" || typeof record.readable !== "boolean"
|
|
|| typeof record.text !== "string") {
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
"web-series-inventory-invalid", "The server returned an invalid MSR inventory.");
|
|
}
|
|
msrByPath[expected.path] = record;
|
|
}
|
|
|
|
let dataByPath = Object.create(null);
|
|
let requestedData = new Map(dataRequests.map(function(item) {
|
|
return [item.path, item];
|
|
}));
|
|
for (let record of responseData) {
|
|
let expected = record && requestedData.get(record.path);
|
|
if (!expected || record.run !== expected.run
|
|
|| Object.prototype.hasOwnProperty.call(dataByPath, expected.path)
|
|
|| typeof record.exists !== "boolean") {
|
|
return webSeriesInventoryFailure(webConfig, execution,
|
|
"web-series-inventory-invalid", "The server returned an invalid data-file inventory.");
|
|
}
|
|
dataByPath[expected.path] = record;
|
|
}
|
|
|
|
let access = {
|
|
msrFileExists: async function(filePath) {
|
|
return Boolean(msrByPath[filePath] && msrByPath[filePath].exists);
|
|
},
|
|
readAsciiFile: async function(filePath) {
|
|
let record = msrByPath[filePath];
|
|
return record && record.exists && record.readable ? record.text : "";
|
|
},
|
|
dataFileExists: async function(filePath) {
|
|
return Boolean(dataByPath[filePath] && dataByPath[filePath].exists);
|
|
}
|
|
};
|
|
let plan = await inspectSeriesFitPlan(webConfig, access);
|
|
plan.webInventory = {
|
|
jobExists: request.payload.job_exists === true,
|
|
msrFiles: responseMSR.length,
|
|
dataFiles: responseData.length
|
|
};
|
|
return plan;
|
|
}
|
|
|
|
window.inspectSeriesFitPlanWeb = inspectSeriesFitPlanWeb;
|
|
|
|
async function loadRunHeaderText(filePath, fileFormat) {
|
|
let request = await postToMusrfitCGI({
|
|
action: "dump_header",
|
|
fn: filePath,
|
|
file_format: fileFormat || ""
|
|
});
|
|
if (!request.ok || !request.payload || !request.payload.ok) {
|
|
return {
|
|
ok: false,
|
|
text: request.payload && request.payload.header ? request.payload.header : "",
|
|
error: request.error || (request.payload ? request.payload.message : "dump_header failed")
|
|
};
|
|
}
|
|
return { ok: true, text: request.payload.header || "", error: "" };
|
|
}
|
|
|
|
async function loadWebDataRoot() {
|
|
let request = await postToMusrfitCGI({ action: "health" });
|
|
let modeText = document.getElementById("dataRootModeText");
|
|
|
|
// A health response may report missing executables while still carrying a
|
|
// valid server path. Only transport/JSON validity matters for this setting.
|
|
if (request.ok && request.payload && request.payload.environment
|
|
&& request.payload.environment.data_root) {
|
|
setConfiguredDataRoot(request.payload.environment.data_root, false);
|
|
if (modeText) {
|
|
modeText.textContent = "Managed by web server";
|
|
}
|
|
|
|
// Register a server-backed portable-naming resolver when the admin has
|
|
// installed a parsed startup XML. This is opt-in: without a validated
|
|
// startup XML the resolver is absent and absolute RUN paths remain the
|
|
// default. The resolver asks the CGI to confirm an exact candidate file
|
|
// under an admin-configured data path, so it is scoped and not a general
|
|
// server file-existence API.
|
|
let startup = request.payload.environment.startup_xml;
|
|
webPortableRunResolution.confirmed.clear();
|
|
webPortableRunResolution.activeDataPath =
|
|
request.payload.environment.musr_full_data_path || "";
|
|
if (startup && startup.ok && startup.templates
|
|
&& typeof setPortableRunNaming === "function") {
|
|
setPortableRunNaming(
|
|
true,
|
|
{ dataPaths: startup.data_paths || [], templates: startup.templates },
|
|
function resolveRunFile(subPath, dataPath) {
|
|
return webPortableRunResolution.confirmed.has(
|
|
dataPath + "\n" + subPath
|
|
);
|
|
}
|
|
);
|
|
} else if (typeof setPortableRunNaming === "function") {
|
|
setPortableRunNaming(false, null, null);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
if (modeText) {
|
|
modeText.textContent = "Server setting unavailable";
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
async function writeAsciiFile(filename, content) {
|
|
// Write string content into ascii file filename via CGI.
|
|
let payload = {
|
|
action: "write",
|
|
fn: filename
|
|
};
|
|
let lines = content.split(/\n/);
|
|
for (let i = 0; i < lines.length; i++) {
|
|
payload["line" + i] = lines[i];
|
|
}
|
|
|
|
let request = await postToMusrfitCGI(payload);
|
|
if (!request.ok || !request.payload || !request.payload.ok) {
|
|
let message = request.error || (request.payload ? request.payload.message : "File upload failed");
|
|
console.log(message);
|
|
return (0);
|
|
}
|
|
|
|
return (1);
|
|
}
|
|
|
|
async function runMSRFileWeb(fullPath, options = {}) {
|
|
let workUrl = fullPath.substring(0, fullPath.lastIndexOf("/"));
|
|
let payload = {
|
|
action: "run",
|
|
fn: fullPath,
|
|
use_msr2data: options.useM2D ? 1 : 0,
|
|
runs: options.runs || "",
|
|
template_name: options.templateName || "",
|
|
base_run: options.baseRun || "",
|
|
// Multi-data-set ADDRUN directives are applied server-side only after
|
|
// msr2data has expanded the template. The spec is already resolved and
|
|
// JSON encoded by prepareMSRRunFiles().
|
|
addrun_spec: options.addRunSpec || "",
|
|
fit_parameter_spec: options.fitParameterSpec || "",
|
|
fftv: options.fftv || "n",
|
|
plot_only: options.plotOnly ? 1 : 0
|
|
};
|
|
|
|
// Clear the previous artifact paths before the CGI starts. The Results tab
|
|
// renders these fields directly, so stale links cannot survive a failed run.
|
|
if (typeof updateJobStatus === "function") {
|
|
updateJobStatus({
|
|
directory: workUrl,
|
|
resultMSR: fullPath,
|
|
logPath: "",
|
|
plotPath: "",
|
|
parameterDataPath: "",
|
|
packagePath: ""
|
|
});
|
|
}
|
|
|
|
let request = await postToMusrfitCGI(payload);
|
|
if (!request.ok || !request.payload) {
|
|
return {
|
|
ok: 0,
|
|
code: request.status || 1,
|
|
statusText: "Web runner request failed: " + (request.error || request.statusText)
|
|
};
|
|
}
|
|
|
|
let response = request.payload;
|
|
if (response.work_url) {
|
|
workUrl = response.work_url;
|
|
}
|
|
// The web runner now treats ROOT files as the primary plot artifact. Keep the
|
|
// extraction here small so the rest of the job/status code stays format-free.
|
|
let rootUrls = [];
|
|
if (typeof musrfitRootUrlsFromResponse === "function") {
|
|
rootUrls = musrfitRootUrlsFromResponse(response);
|
|
} else if (Array.isArray(response.root_urls)) {
|
|
rootUrls = response.root_urls.filter(function(rootUrl) {
|
|
return typeof rootUrl === "string" && rootUrl !== "";
|
|
});
|
|
} else if (response.root_url) {
|
|
rootUrls = [response.root_url];
|
|
}
|
|
|
|
if (typeof updateJobStatus === "function") {
|
|
let artifacts = { directory: workUrl };
|
|
if (response.msr_url) {
|
|
artifacts.resultMSR = response.msr_url;
|
|
}
|
|
if (response.out_url) {
|
|
artifacts.logPath = response.out_url;
|
|
}
|
|
if (rootUrls.length > 0) {
|
|
artifacts.plotPath = rootUrls[0];
|
|
}
|
|
if (response.parameter_url) {
|
|
// The Results tab opens this artifact in the integrated floating Plotly
|
|
// viewer; no separate parameter-plotter application is required.
|
|
artifacts.parameterDataPath = response.parameter_url;
|
|
}
|
|
if (response.tgz_url) {
|
|
artifacts.packagePath = response.tgz_url;
|
|
}
|
|
updateJobStatus(artifacts);
|
|
}
|
|
if (response.out_url && typeof appendJobLog === "function") {
|
|
// The CGI log contains each executable command, its combined output, and
|
|
// exit status. Loading it here gives web users the same diagnostics as the
|
|
// streaming Electron runner without duplicating the text in the JSON body.
|
|
let commandLog = await readAsciiFile(response.out_url);
|
|
if (commandLog && commandLog.trim() !== "") {
|
|
appendJobLog(commandLog.trim());
|
|
}
|
|
}
|
|
// Open the JSROOT window only after the server has produced at least one ROOT
|
|
// canvas. root_items tells JSROOT which serialized TCanvas to draw.
|
|
if (rootUrls.length > 0 && typeof showWebRootPlotWindow === "function") {
|
|
showWebRootPlotWindow(rootUrls, response.job_name || "", {
|
|
msrPath: response.msr_url || fullPath,
|
|
runs: options.runs || "",
|
|
rootItems: Array.isArray(response.root_items) ? response.root_items : []
|
|
});
|
|
}
|
|
if (response.msr_url) {
|
|
let fittedMSR = await readAsciiFile(response.msr_url);
|
|
if (fittedMSR && typeof applyFittedMSRToGUI === "function") {
|
|
applyFittedMSRToGUI(fittedMSR, response.msr_url, options);
|
|
}
|
|
}
|
|
|
|
let outcome = response.outcome || "";
|
|
let status = response.message ? response.message : "Web fit request completed.";
|
|
if (outcome == "missing-data" && typeof classifyMissingDataOutput === "function") {
|
|
let missingData = classifyMissingDataOutput(response.stderr || "", {
|
|
outcome: outcome,
|
|
missingFiles: response.missing_files || []
|
|
});
|
|
status = missingData.details;
|
|
} else {
|
|
status += "\nWeb artifacts are available via the generated links (ROOT plot/tgz/log/msr).";
|
|
if (response.stderr && response.stderr !== "") {
|
|
status += "\n" + response.stderr;
|
|
}
|
|
}
|
|
return {
|
|
ok: response.ok ? 1 : 0,
|
|
code: response.code !== undefined ? response.code : (response.ok ? 0 : 1),
|
|
statusText: status,
|
|
outcome: outcome,
|
|
missingFiles: Array.isArray(response.missing_files) ? response.missing_files : []
|
|
};
|
|
}
|
|
|
|
async function readAsciiFile(filename) {
|
|
// Browser file access goes through HTTP and must not block the UI thread.
|
|
if (filename == "" || filename == undefined || filename == null) {
|
|
return 0;
|
|
}
|
|
|
|
try {
|
|
let response = await fetch(filename, { cache: "no-store" });
|
|
if (!response.ok) {
|
|
console.log("File " + filename + " could not be read: " + response.status + " " + response.statusText);
|
|
return(0);
|
|
}
|
|
return await response.text();
|
|
} catch (error) {
|
|
console.log("File " + filename + " could not be read: " + error.message);
|
|
return(0);
|
|
}
|
|
}
|
|
|
|
async function fileExists(filename) {
|
|
try {
|
|
let response = await fetch(filename, {
|
|
method: "HEAD",
|
|
cache: "no-store"
|
|
});
|
|
return response.ok ? 1 : 0;
|
|
} catch (error) {
|
|
console.log("File check failed for " + filename + ": " + error.message);
|
|
return 0;
|
|
}
|
|
}
|