Files
muSRFlow/muSRFitelec.js
salman 3f9ecb4fd7 Report application and runtime build identity
Show version, edition, Git revision, runtime provider, musrfit, and ROOT in Quick Start across Electron and web deployments. Embed source provenance in Linux and Windows packages, repair the hardened help-window IPC path, and make Plotly controls toggle consistently by tap or click.
2026-11-04 16:27:07 +01:00

2662 lines
108 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
// Electron/Node.js-specific filesystem, process, and IPC helpers. Plotly is
// loaded lazily by muSRFitParameterPlot.js only when a parameter plot is opened.
// Use var-backed names because renderer scripts share one global lexical scope.
// In the hardened Electron build (contextIsolation:true) these come from the
// preload bridge; the window.* globals keep the vm-based test sandbox working
// unchanged, and require() is only a last-resort fallback.
var electronIpcRenderer = window.electronIpcRenderer
|| (window.electronAPI && window.electronAPI.ipc)
|| require('electron').ipcRenderer;
var nodeFs = window.nodeFs
|| (window.electronAPI && window.electronAPI.fs)
|| require('fs');
var nodePath = window.nodePath
|| (window.electronAPI && window.electronAPI.path)
|| require('path');
var nodeProcess = window.nodeProcess
|| (window.electronAPI && window.electronAPI.process)
|| process;
// The preload bridge cannot pass a live child_process module through
// contextBridge, so the bridge exposes normalized capture helpers and we
// rebuild the spawnSync/execSync/spawn shape call sites expect.
function bridgeChildProcess(api) {
var cp = {};
cp.execSync = function (command, options) {
var result = api.execSync(command, options || {});
if (!result.ok) {
var error = new Error(result.error || "Command failed");
error.status = result.status;
error.stdout = result.stdout;
error.stderr = result.stderr;
throw error;
}
return result.stdout;
};
cp.spawnSync = function (command, args, options) {
return api.spawnSync(command, args || [], options || {});
};
cp.spawnCapture = api.spawnCapture;
if (api.abortJob) {
cp.abortJob = function (token, signal) {
return api.abortJob(token, signal || "SIGTERM");
};
}
return cp;
}
var nodeChildProcess = window.nodeChildProcess
|| (window.electronAPI && bridgeChildProcess(window.electronAPI.childProcess))
|| require('child_process');
// The preload bridge exposes string-in/string-out gzip helpers that avoid
// passing Buffers across the contextBridge. The test sandbox keeps using
// require('zlib') and require('buffer') where Buffer is accessible natively.
var nodeZlib = (window.electronAPI && window.electronAPI.zlib) || null;
window.electronIpcRenderer = electronIpcRenderer;
window.nodeFs = nodeFs;
window.nodePath = nodePath;
window.nodeChildProcess = nodeChildProcess;
window.nodeProcess = nodeProcess;
// The shared action-button state is upgraded for Electron: while a job is
// running, the active Fit/Plot button becomes "Abort" and kills the last
// launched child process through the preload bridge. Web jobs run server-side,
// cannot be killed from the page, and keep the disabled button.
if (window.MusrfitAction) {
window.MusrfitAction.abortSupported = true;
}
// runLocalProcess() records the bridge token of the job it just launched so
// Abort targets exactly the last musrfit/musrview process, and only one.
var electronRunJobToken = "";
var electronRunJobLabel = "";
var electronRunJobLogFile = "";
var electronRunJobAborted = false;
var electronRunJobSeq = 0;
var electronRunDataFiles = [];
var electronRunDataReady = null;
var electronRunDataToken = '';
var electronRuntimeInstalling = false;
var electronRuntimeChecking = false;
var electronRuntimeToken = '';
function electronRequestAbort(action) {
if (electronRunDataToken && window.electronAPI && window.electronAPI.runData) {
window.electronAPI.runData.cancel(electronRunDataToken);
setFitStatus('Stopping the data download...');
return true;
}
if (electronRunJobToken === "" || typeof nodeChildProcess.abortJob !== "function") {
return false;
}
if (electronRunJobAborted) return true;
electronRunJobAborted = true;
if (electronRunJobLogFile) {
appendFitLog(electronRunJobLogFile, "\n# Abort requested by user\n");
}
nodeChildProcess.abortJob(electronRunJobToken, "SIGTERM");
if (typeof setFitStatus === "function") {
setFitStatus("Abort requested; stopping " + (electronRunJobLabel || "the job") + ".");
}
return true;
}
window.triggerMusrfitAbort = electronRequestAbort;
function seriesFilesystemError(code, filePath) {
let error = new Error(code + (filePath ? ": " + filePath : ""));
error.code = code;
return error;
}
function isSafeSeriesRegularFile(filePath) {
if (!filePath || !nodeFs.existsSync(filePath)) return false;
let stat = nodeFs.lstatSync(filePath);
return stat.isFile() && !stat.isSymbolicLink();
}
// Electron's independent-series transaction adapter. The shared coordinator
// decides when a whole batch may be promoted; this adapter supplies exclusive
// filesystem operations for one item at a time. The Fit action uses this same
// adapter, and it remains exposed for focused transaction tests.
function createSeriesMSRTransactionAdapter() {
return {
exists: function(filePath) {
return nodeFs.existsSync(filePath);
},
createExclusive: function(filePath, text) {
nodeFs.writeFileSync(filePath, text, { encoding: "utf8", flag: "wx" });
return true;
},
read: function(filePath) {
return nodeFs.readFileSync(filePath, "utf8");
},
// Only transaction-owned staging files are accepted here. The shared
// coordinator never asks this operation to remove a user MSR or backup.
discard: function(filePath) {
if (!/\.musrflow-stage-[A-Za-z0-9-]+\.msr$/.test(String(filePath || ""))) {
throw seriesFilesystemError("unsafe-stage-discard-path", filePath);
}
if (nodeFs.existsSync(filePath)) nodeFs.unlinkSync(filePath);
return true;
},
promote: function(item) {
if (!item || !item.stagePath || !item.targetPath
|| !nodeFs.existsSync(item.stagePath)) {
throw seriesFilesystemError("staged-file-not-found", item ? item.stagePath : "");
}
let stagedText = nodeFs.readFileSync(item.stagePath, "utf8");
if (stagedText !== item.expectedText) {
throw seriesFilesystemError("staged-content-changed", item.stagePath);
}
if (!item.replace) {
if (nodeFs.existsSync(item.targetPath)) {
throw seriesFilesystemError("new-target-already-exists", item.targetPath);
}
// A hard link publishes the already verified inode atomically and
// fails with EEXIST rather than replacing a file created by a race.
nodeFs.linkSync(item.stagePath, item.targetPath);
try {
nodeFs.unlinkSync(item.stagePath);
} catch (error) {
// Do not report a failed promotion while leaving a published
// target behind. Remove only the link created above.
if (nodeFs.existsSync(item.targetPath)
&& nodeFs.readFileSync(item.targetPath, "utf8") === stagedText) {
nodeFs.unlinkSync(item.targetPath);
}
throw error;
}
return {
run: item.run,
action: item.action,
targetPath: item.targetPath,
backupPath: "",
replaced: false,
promotedText: stagedText
};
}
if (!item.backupPath || !nodeFs.existsSync(item.targetPath)) {
throw seriesFilesystemError("replacement-target-not-found", item.targetPath);
}
if (nodeFs.existsSync(item.backupPath)) {
throw seriesFilesystemError("backup-already-exists", item.backupPath);
}
// Copy and verify the old file before the same-directory rename. On
// the supported Linux deployment renameSync atomically replaces the
// target; the exclusive backup remains available until the later
// runner either commits or rolls back the fit result.
nodeFs.copyFileSync(item.targetPath, item.backupPath, nodeFs.constants.COPYFILE_EXCL);
let backupText = nodeFs.readFileSync(item.backupPath, "utf8");
let originalText = nodeFs.readFileSync(item.targetPath, "utf8");
if (backupText !== originalText) {
nodeFs.unlinkSync(item.backupPath);
throw seriesFilesystemError("backup-content-mismatch", item.backupPath);
}
try {
nodeFs.renameSync(item.stagePath, item.targetPath);
} catch (error) {
// The original target was not removed by a failed rename. The
// transaction-owned backup is therefore safe to discard.
if (nodeFs.existsSync(item.backupPath)) nodeFs.unlinkSync(item.backupPath);
throw error;
}
return {
run: item.run,
action: item.action,
targetPath: item.targetPath,
backupPath: item.backupPath,
replaced: true,
promotedText: stagedText,
originalText: backupText
};
},
verifyFinalize: function(receipt, decision) {
if (!receipt || !receipt.targetPath || !isSafeSeriesRegularFile(receipt.targetPath)) {
throw seriesFilesystemError("promoted-target-not-found",
receipt ? receipt.targetPath : "");
}
let currentText = nodeFs.readFileSync(receipt.targetPath, "utf8");
if (decision == "retain" && receipt.replaced) {
throw seriesFilesystemError("cannot-retain-replacement-target", receipt.targetPath);
}
if (decision == "commit") {
if (!isValidGeneratedGlobalMSR(currentText)) {
throw seriesFilesystemError("committed-target-structure-invalid", receipt.targetPath);
}
if (parseMSRFitStatistic(currentText).converged !== true) {
throw seriesFilesystemError("committed-target-not-converged", receipt.targetPath);
}
if (seriesRunDirectiveIdentity(currentText)
!== seriesRunDirectiveIdentity(receipt.promotedText)) {
throw seriesFilesystemError("committed-target-run-identity-changed", receipt.targetPath);
}
}
if (receipt.replaced) {
if (!receipt.backupPath || !isSafeSeriesRegularFile(receipt.backupPath)) {
throw seriesFilesystemError("finalization-backup-not-found", receipt.backupPath || "");
}
let backupText = nodeFs.readFileSync(receipt.backupPath, "utf8");
if (backupText !== receipt.originalText) {
throw seriesFilesystemError("finalization-backup-changed", receipt.backupPath);
}
}
return true;
},
commit: function(receipt) {
this.verifyFinalize(receipt, "commit");
if (receipt.replaced && nodeFs.existsSync(receipt.backupPath)) {
nodeFs.unlinkSync(receipt.backupPath);
}
return true;
},
// A newly created failed result is still useful for inspection and as the
// input to a later retry. Retention never applies to replacements because
// their earlier user file must remain recoverable through rollback.
retain: function(receipt) {
this.verifyFinalize(receipt, "retain");
return true;
},
rollback: function(receipt, options = {}) {
if (!receipt || !receipt.targetPath || !isSafeSeriesRegularFile(receipt.targetPath)) {
throw seriesFilesystemError("promoted-target-not-found",
receipt ? receipt.targetPath : "");
}
let currentText = nodeFs.readFileSync(receipt.targetPath, "utf8");
if (!options.allowChangedTarget && currentText !== receipt.promotedText) {
throw seriesFilesystemError("promoted-target-changed", receipt.targetPath);
}
if (!receipt.replaced) {
nodeFs.unlinkSync(receipt.targetPath);
return true;
}
if (!receipt.backupPath || !isSafeSeriesRegularFile(receipt.backupPath)) {
throw seriesFilesystemError("rollback-backup-not-found", receipt.backupPath || "");
}
let backupText = nodeFs.readFileSync(receipt.backupPath, "utf8");
if (backupText !== receipt.originalText) {
throw seriesFilesystemError("rollback-backup-changed", receipt.backupPath);
}
nodeFs.renameSync(receipt.backupPath, receipt.targetPath);
return true;
}
};
}
window.createSeriesMSRTransactionAdapter = createSeriesMSRTransactionAdapter;
window.MusrfitSeriesTransactionAdapter = createSeriesMSRTransactionAdapter();
// Open renderer-requested auxiliary windows through one Electron IPC path.
// The web build never loads this file, so the presence of this helper is a
// reliable Electron check and avoids duplicating environment detection.
function openElectronAuxiliaryWindow(kind, options = {}) {
let channels = {
parameterPlot: "openParameterPlotWindow",
quickStart: "openQuickStartWindow"
};
let channel = channels[kind];
if (!channel || !electronIpcRenderer) return false;
electronIpcRenderer.send(channel, options || {});
return true;
}
window.openElectronAuxiliaryWindow = openElectronAuxiliaryWindow;
let cachedQuickStartRuntimeInfo = null;
function electronQuickStartRuntimeInfo() {
if (cachedQuickStartRuntimeInfo) return Object.assign({}, cachedQuickStartRuntimeInfo);
let configured = typeof getConfiguredBinDir === "function" ? getConfiguredBinDir() : "";
let provider = configured ? "configured tools" : "system tools";
if (!configured && isWslRuntimeHost()) {
provider = "bundled WSL runtime";
} else if (!configured && bundledRuntimeRoot()) {
provider = "bundled runtime";
} else if (!configured && systemRuntimeRoot()) {
provider = "system runtime";
}
let info = { runtimeProvider: provider, musrfit: "not reported", root: "not reported" };
let command = resolveLocalCommand("musrfit");
let launch = prepareLocalLaunch(command, ["--version"]);
let result = nodeChildProcess.spawnSync(launch.command, launch.args, {
env: buildToolEnvironment(),
encoding: "utf8",
shell: false,
timeout: 5000
});
if (!result.error && result.status === 0) {
let output = (result.stdout || "") + "\n" + (result.stderr || "");
let musrfit = output.match(/musrfit version:\s*([^,\s]+)/i);
let root = output.match(/ROOT version:\s*([^,\s]+)/i);
if (musrfit) info.musrfit = musrfit[1];
if (root) info.root = root[1].replace("/", ".");
}
cachedQuickStartRuntimeInfo = info;
return Object.assign({}, info);
}
window.getMuSRFlowBuildInfo = electronQuickStartRuntimeInfo;
// Parameter-plot opening is the only part of the plotting workflow owned by
// the main Electron renderer. The actual plot UI is rendered by the shared
// muSRFitParameterPlot.js inside the auxiliary BrowserWindow.
if (!window.MusrfitParameterPlotPlatform) window.MusrfitParameterPlotPlatform = {};
window.MusrfitParameterPlotPlatform.openPlot = function(options = {}) {
return openElectronAuxiliaryWindow("parameterPlot", options);
};
// Keep one mutable runner state on window. Only musrfit is serialized;
// musrview windows/processes are allowed to run in parallel.
if (!window.MusrfitRunner) {
window.MusrfitRunner = { fitActive: false, nextViewId: 1 };
} else {
if (typeof window.MusrfitRunner.fitActive === "undefined") {
window.MusrfitRunner.fitActive = false;
}
if (typeof window.MusrfitRunner.nextViewId === "undefined") {
window.MusrfitRunner.nextViewId = 1;
}
}
// Register this deployment's platform facts for the shared muSRFitlib.js
// before any action uses them: desktop mode, the real working directory, and
// the local musrfit/musrview runner. The browser build registers the same
// contract with its CGI-backed values. Both files load before muSRFitlib.js,
// so the shared code simply reads the contract when it is called.
window.MusRFlowPlatform = window.MusRFlowPlatform || {};
window.MusRFlowPlatform.webMode = false;
window.MusRFlowPlatform.currentDirectory = function() {
try {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd();
}
} catch (error) {
// Fall back to the launch directory.
}
return ".";
};
window.MusRFlowPlatform.msrFileRunner = function(fullPath, options) {
return runMSRFileLocal(fullPath, options);
};
window.MusRFlowPlatform.ensureRunData = ensureLocalRunData;
window.MusRFlowPlatform.resolveRunData = resolveLocalRunData;
window.MusRFlowPlatform.resolveDataFile = function(runName) {
for (let file of electronRunDataFiles) {
let resolved = resolveLocalRunData(file.run, file.year, file.instrument);
if (resolved && resolved.runName === runName) return resolved.filePath;
}
return '';
};
function rememberLocalRunData(files) {
for (let file of files || []) {
let index = electronRunDataFiles.findIndex(function(existing) {
return existing.instrument === file.instrument && existing.year === file.year
&& existing.run === file.run;
});
if (index !== -1) electronRunDataFiles.splice(index, 1);
electronRunDataFiles.push(file);
}
}
function initializeLocalRunData() {
if (electronRunDataReady) return electronRunDataReady;
let api = window.electronAPI && window.electronAPI.runData;
if (!api) return Promise.resolve();
electronRunDataReady = api.configuration().then(function(configuration) {
rememberLocalRunData(configuration.files);
let hint = document.getElementById('runDataDownloadHint');
if (hint) {
hint.textContent = 'Missing runs can be downloaded from musruser.psi.ch. '
+ 'Read-only data directories use: ' + configuration.directory;
}
}).catch(function(error) {
electronRunDataReady = null;
console.warn('Could not load downloaded runs: ' + error.message);
});
return electronRunDataReady;
}
function resolveLocalRunData(run, year, instrument) {
let file = electronRunDataFiles.find(function(record) {
return record.run === Number(run) && record.year === Number(year)
&& record.instrument === instrument;
});
if (!file) return null;
try {
let stat = nodeFs.statSync(file.filePath);
if (!stat.isFile() || stat.size !== file.size) return null;
} catch (error) {
return null;
}
// Keep spaces and Windows drive letters outside the MSR's whitespace-based
// grammar. MUSRFULLDATAPATH supplies the real storage roots to the tools.
let runName = file.relative_path.replace(/\.(root|bin|mdu)$/i, '');
if (file.format === 'PSI-MDU' && /\.bin$/i.test(file.filename)) runName = file.relative_path;
return { runName: runName, filePath: file.filePath, format: file.format };
}
function localRunDataSearchPath(viaWsl) {
let roots = [];
for (let file of electronRunDataFiles) {
roots.push(file.storageRoot);
roots.push(nodePath.join(file.storageRoot, file.instrument.toLowerCase(), 'his'));
}
roots = Array.from(new Set(roots));
if (viaWsl) roots = roots.map(windowsPathToWsl);
let inherited = nodeProcess.env.MUSRFULLDATAPATH || '';
if (viaWsl && /^[A-Za-z]:[\\/]/.test(inherited)) inherited = windowsPathToWsl(inherited);
if (inherited) roots.push(inherited);
return roots.join(':');
}
async function ensureLocalRunData(options) {
let api = window.electronAPI && window.electronAPI.runData;
if (!api || !options.all.instrName) return { ok: true };
await initializeLocalRunData();
let all = options.all;
let requests = [];
let seen = new Set();
for (let dataSet of options.runSelection) {
for (let run of seriesDataSetPhysicalRuns(dataSet)) {
if (seen.has(run)) continue;
seen.add(run);
let dataPath = seriesDataFilePath(run, all);
if (!fileExists(dataPath)) {
requests.push({ instrument: all.instrName, year: Number(all.selYear), run: run });
}
}
}
if (!requests.length) return { ok: true };
let action = options.action.toLowerCase();
let token = 'data-' + Date.now().toString(36) + '-' + (++electronRunJobSeq);
electronRunDataToken = token;
setMusrfitActionState(action, 'running');
let unsubscribe = api.onProgress(function(state) {
if (!state || state.token !== token) return;
let message = state.phase === 'checking'
? 'Checking server data for run ' + state.run + '...'
: 'Downloading ' + state.filename + ' ('
+ (100 * state.received / state.totalBytes).toFixed(0) + '%)...';
updateJobStatus({ state: 'Downloading data', message: message, noticeLevel: 'info' });
let activity = document.getElementById('musrfitActionActivityText');
if (activity) activity.textContent = message;
});
// Retry the automatic first-run guess only while its original parameter
// values remain untouched. Imported configurations and explicit models
// have already opted out of automatic model selection.
let parametersBefore = JSON.stringify(buildFitParameterSyncSpec({}));
let selectionBefore = all.runNumbers;
try {
let result = await api.acquire({ token: token, requests: requests, dataRoot: all.dataRoot });
rememberLocalRunData(result.files);
if (!result.ok) {
return { ok: false, outcome: result.cancelled ? 'aborted' : '',
message: result.cancelled ? 'Data download cancelled.' : 'Data download: ' + result.message };
}
for (let file of result.files || []) appendJobLog('Run data available: ' + file.filePath);
let runInput = document.getElementById('runNumbers');
if (runInput && runInput.value !== selectionBefore) {
return { ok: false, outcome: 'aborted', message: 'Runs changed during download. Start the action again.' };
}
let pendingGuess = initialParameterGuessState.pendingDownloadGuess;
if (automaticInitialFitModel && !initialParameterGuessState.metadata && pendingGuess
&& pendingGuess.generation === initialParameterGuessState.generation
&& pendingGuess.parameters === parametersBefore
&& parametersBefore === JSON.stringify(buildFitParameterSyncSpec({}))) {
initialParameterGuessState.appliedGeneration = 0;
await scheduleInitialParameterGuess();
prepCFG();
}
if (result.missing && result.missing.length) {
let message = result.missing.map(function(file) { return file.message; }).join('\n');
appendJobLog(message);
if (!options.series) return { ok: false, outcome: 'missing-data', message: message };
}
return { ok: true };
} catch (error) {
return { ok: false, message: 'Could not download run data: ' + error.message };
} finally {
if (typeof unsubscribe === 'function') unsubscribe();
electronRunDataToken = '';
setMusrfitActionState(action, 'preparing');
}
}
// Configuration links produced by Electron always target the canonical web
// deployment so they can be opened by another user without Electron installed.
var MUSRFLOW_CANONICAL_SHARE_URL = "http://musruser.psi.ch/muSRFlow/";
function electronGzipText(text) {
if (nodeZlib) {
return nodeZlib.gzipBase64URL(String(text));
}
// Test sandbox fallback that keeps require('zlib') accessible. Node's gzip
// output is directly compatible with the web-side DecompressionStream("gzip")
// decoder used for #c= links.
let zipped = require("zlib").gzipSync(require("buffer").Buffer.from(String(text), "utf8"));
return zipped.toString("base64")
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function encodeElectronSharedConfiguration(config) {
return encodeSharedConfigurationLink(config, electronGzipText);
}
function decodeElectronSharedConfiguration(value) {
return decodeSharedConfigurationFragment(value, function(payload) {
if (nodeZlib) {
return nodeZlib.gunzipBase64URL(payload);
}
let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/");
while (base64.length % 4) base64 += "=";
let zipped = require("buffer").Buffer.from(base64, "base64");
return require("zlib").gunzipSync(zipped).toString("utf8");
});
}
function electronWriteClipboard(url) {
let write = window.electronAPI && window.electronAPI.clipboard
&& typeof window.electronAPI.clipboard.writeText === "function"
? window.electronAPI.clipboard.writeText.bind(window.electronAPI.clipboard)
: null;
if (!write && typeof require === "function") {
// Test-sandbox fallback. The hardened renderer has no global require, so
// this branch is only reachable in the vm sandbox where require exists.
let electron = require("electron");
if (electron && electron.clipboard && typeof electron.clipboard.writeText === "function") {
write = electron.clipboard.writeText.bind(electron.clipboard);
}
}
if (typeof write !== "function") {
throw new Error("Electron clipboard is unavailable");
}
write(url);
return true;
}
async function copyWebConfigurationLink() {
return shareConfigurationLink({
baseURL: function() { return MUSRFLOW_CANONICAL_SHARE_URL; },
writeClipboard: electronWriteClipboard,
gzipText: electronGzipText
});
}
// Electron-only session persistence. A saved session records the same portable
// state fragment as a share link (so old apps still restore the fields they
// understand), appended as one timestamped line in a plain journal file inside
// the working directory. Preferences stay in the per-machine localStorage.
var MUSRFLOW_SESSION_FILENAME = "musrflow-sessions.txt";
function electronSessionFilename() {
let input = document.getElementById("workPath");
let workPath = normalizeWorkPath(input ? input.value : "");
try {
workPath = nodeFs.realpathSync(workPath);
} catch (error) {
// The working directory may not exist yet; write into the configured path.
}
return nodePath.join(workPath, MUSRFLOW_SESSION_FILENAME);
}
function readSessionHistoryFile(filename) {
// Missing journal files are normal on the first save, so failures stay
// silent here (readAsciiFile would raise an alert for them).
try {
return nodeFs.readFileSync(filename, "utf8");
} catch (error) {
return "";
}
}
function parseSessionHistoryFile(text) {
// One session per line: <ISO timestamp>\t<label>\t<#c=/#cfg= payload>.
// Blanks and # comments (hand-edited headers) are ignored, and a label may
// never contain a tab because writeElectronSession sanitizes it away.
let entries = [];
for (let rawLine of String(text || "").split(/\r?\n/)) {
let line = rawLine.trim();
if (!line || line[0] === "#") continue;
let parts = line.split("\t");
if (parts.length < 3) continue;
entries.push({
timestamp: parts[0].trim(),
label: parts[1].trim(),
fragment: parts.slice(2).join("\t")
});
}
return entries;
}
function saveElectronSession() {
let dialog = document.getElementById("saveSessionDialog");
let labelInput = document.getElementById("sessionLabel");
if (!dialog || !labelInput) return;
labelInput.value = "";
let errorText = document.getElementById("saveSessionError");
if (errorText) {
errorText.textContent = "";
errorText.hidden = true;
}
if (typeof dialog.showModal === "function") {
dialog.showModal();
} else {
dialog.setAttribute("open", "");
}
setTimeout(function() {
labelInput.focus();
}, 0);
}
async function encodeElectronSessionFragment() {
try {
let encoded = await buildEncodedSharedConfigurationLink(electronGzipText);
return encoded.prefix + encoded.payload;
} catch (error) {
if (typeof setFitStatus === "function") {
setFitStatus("Could not encode the session.", { level: "error" });
}
return "";
}
}
async function writeElectronSession() {
let dialog = document.getElementById("saveSessionDialog");
let labelInput = document.getElementById("sessionLabel");
let errorText = document.getElementById("saveSessionError");
let label = labelInput ? labelInput.value : "";
label = String(label || "").replace(/[\t\r\n]+/g, " ").trim();
if (!label) {
if (errorText) {
errorText.textContent = "Enter a label for the session.";
errorText.hidden = false;
}
return;
}
let fragment = await encodeElectronSessionFragment();
if (!fragment) return;
let filename = electronSessionFilename();
let existingText = readSessionHistoryFile(filename);
let entries = parseSessionHistoryFile(existingText);
if (entries.length > 0
&& entries[entries.length - 1].fragment === fragment) {
if (dialog) {
try { dialog.close(); } catch (error) {}
}
if (typeof setFitStatus === "function") {
setFitStatus("Session unchanged: \"" + entries[entries.length - 1].label
+ "\" already holds this analysis state.", { level: "success" });
}
return;
}
let line = [new Date().toISOString(), label, fragment].join("\t");
let joined = (existingText.trim() === "")
? line : existingText.replace(/\s+$/, "\n") + line;
let ok = writeAsciiFile(filename, joined + "\n");
if (dialog) {
try { dialog.close(); } catch (error) {}
}
if (typeof setFitStatus === "function") {
setFitStatus(ok ? "Session saved." : "Could not save the session.",
{ level: ok ? "success" : "error" });
}
if (typeof showTransientWarning === "function") {
showTransientWarning(
ok ? "Session saved into " + filename : "Could not save the session.",
document.getElementById("saveSessionButton"),
4000
);
}
}
var currentSessionHistory = [];
function openElectronSessionHistory() {
let dialog = document.getElementById("sessionHistoryDialog");
let list = document.getElementById("sessionHistoryList");
let errorText = document.getElementById("sessionHistoryError");
if (!dialog || !list) return;
let filename = electronSessionFilename();
currentSessionHistory = parseSessionHistoryFile(readSessionHistoryFile(filename));
list.innerHTML = "";
if (errorText) {
errorText.textContent = "";
errorText.hidden = true;
}
if (currentSessionHistory.length === 0) {
if (errorText) {
errorText.textContent = "No saved sessions in " + filename + ".";
errorText.hidden = false;
}
} else {
// Newest on top; the option value is the entry index in the ascending
// currentSessionHistory array.
for (let i = currentSessionHistory.length - 1; i >= 0; i--) {
let entry = currentSessionHistory[i];
let when = entry.timestamp;
try {
when = new Date(entry.timestamp).toLocaleString();
} catch (error) {}
let label = entry.label || "(untitled session)";
let option = document.createElement("option");
option.value = String(i);
option.textContent = when + " — " + label;
list.appendChild(option);
}
list.selectedIndex = list.options.length - 1;
}
if (typeof dialog.showModal === "function") {
dialog.showModal();
} else {
dialog.setAttribute("open", "");
}
}
async function restoreSelectedSession() {
let dialog = document.getElementById("sessionHistoryDialog");
let list = document.getElementById("sessionHistoryList");
if (!list || list.selectedIndex < 0
|| list.selectedIndex >= list.options.length) return;
let entry = currentSessionHistory[Number(list.value)];
if (!entry) return;
if (dialog) {
try { dialog.close(); } catch (error) {}
}
// The shared restore path shows its own editor-confirmation and status
// messages, so this stays a thin wrapper around the same decode/restore
// flow used by link paste and deep links.
await restoreSharedConfigurationFromSource(entry.fragment, null);
}
function openElectronSharedConfiguration() {
let dialog = document.getElementById("sharedConfigurationDialog");
let input = document.getElementById("sharedConfigurationURL");
let errorText = document.getElementById("sharedConfigurationError");
if (!dialog || !input) return;
// A copied share link is the common case. Unrelated clipboard text is not
// inserted so the dialog does not expose arbitrary clipboard contents.
let clipboardText = "";
try {
clipboardText = require("electron").clipboard.readText().trim();
} catch (error) {
clipboardText = "";
}
input.value = /#(?:c|cfg)=/.test(clipboardText) ? clipboardText : "";
if (errorText) {
errorText.textContent = "";
errorText.hidden = true;
}
if (typeof dialog.showModal === "function") {
dialog.showModal();
} else {
dialog.setAttribute("open", "");
}
setTimeout(function() {
input.focus();
input.select();
}, 0);
}
// A legacy (web-style) deep link carries run/beam-line/year selection in the
// query string (musrflow://…/muSRFlow?action=plot&YEAR=…&BeamLine=…&RunNumbers=…)
// instead of an encoded #c= configuration fragment. It reuses the web shell's
// parser to initialize the same GUI controls and, for action=plot, starts the
// established Plot flow once any initial-parameter guess is ready. Invalid
// values surface through the URL-parameter warning channel, same as on the web.
async function handleDesktopLegacyURL(sharedURL) {
let search = "";
try {
search = new URL(String(sharedURL)).search;
} catch (_error) {
return;
}
if (!search) {
return;
}
let result = (typeof applyWebURLParameters === "function")
? applyWebURLParameters(search)
: { applied: {}, errors: [], action: "" };
if (result.action === "plot" && typeof triggerWebURLAction === "function") {
await triggerWebURLAction(result);
}
}
async function restoreSharedConfigurationFromSource(sourceText, errorElement) {
let decoded = await decodeElectronSharedConfiguration(sourceText || "");
if (decoded.error) {
if (errorElement) {
errorElement.textContent = decoded.error;
errorElement.hidden = false;
}
if (typeof setFitStatus === "function") {
setFitStatus("Could not restore the shared configuration.", {
level: "error",
details: decoded.error
});
}
return false;
}
// A restored link intentionally makes the GUI authoritative. Preserve old
// editor text for reference, but ask before detaching user-owned changes.
let currentState = getMSRDocumentState("current");
let templateState = getMSRDocumentState("template");
let editorNeedsConfirmation = currentState.dirty || templateState.dirty
|| currentState.locked || templateState.locked;
if (editorNeedsConfirmation && typeof confirm === "function") {
let accepted = confirm(
"The MSR editor contains user-controlled changes. Restore the shared "
+ "GUI configuration and mark the existing editor documents as stale?"
);
if (!accepted) return false;
}
try {
await restoreSharedConfiguration(decoded.config);
// The shared helper keeps existing editor text visible but prevents it
// from silently overriding the newly imported GUI (see
// markMSREditorStaleAfterRestore in muSRFitlib.js). The next
// Generate/Fit/Plot creates a fresh MSR.
if (typeof openTab === "function") openTab(null, "Runs");
if (typeof setFitStatus === "function") {
setFitStatus("Shared configuration restored.", {
level: "success",
details: "Portable analysis settings were restored. Local paths were kept unchanged."
});
}
return true;
} catch (error) {
let message = "Could not restore shared configuration: "
+ (error && error.message ? error.message : String(error));
if (errorElement) {
errorElement.textContent = message;
errorElement.hidden = false;
}
if (typeof setFitStatus === "function") {
setFitStatus("Could not restore shared configuration.", {
level: "error",
details: message
});
}
return false;
}
}
async function restoreElectronSharedConfiguration() {
let dialog = document.getElementById("sharedConfigurationDialog");
let input = document.getElementById("sharedConfigurationURL");
let errorText = document.getElementById("sharedConfigurationError");
let restored = await restoreSharedConfigurationFromSource(
input ? input.value : "", errorText || null
);
if (restored && dialog) {
if (typeof dialog.close === "function") dialog.close();
else dialog.removeAttribute("open");
}
return restored;
}
function selectWorkFolder() {
let input = document.getElementById("workPath");
let currentPath = input ? input.value : ".";
electronIpcRenderer.send("selectWorkFolder", currentPath);
}
function selectDataRootFolder() {
let input = document.getElementById("dataRoot");
let currentRoot = input ? input.value : "";
electronIpcRenderer.send("selectDataRootFolder", currentRoot);
}
function selectStartupXmlFile() {
let input = document.getElementById("startupXml");
let currentPath = input ? input.value : "";
electronIpcRenderer.send("selectStartupXmlFile", currentPath);
}
function selectBinFolder() {
let input = document.getElementById("binDir");
let currentPath = input ? input.value : "";
electronIpcRenderer.send("selectBinFolder", currentPath);
}
function loadRunHeaderText(filePath, fileFormat) {
let dumpHeader = resolveLocalCommand("dump_header");
let env = buildToolEnvironment();
let args = ["-fn", filePath];
if (fileFormat) args.push("-ff", fileFormat);
let launch = prepareLocalLaunch(dumpHeader, args);
let result = nodeChildProcess.spawnSync(launch.command, launch.args, {
env: env,
encoding: "utf8",
shell: false
});
if (result.error || result.status !== 0) {
return {
ok: false,
text: result.stdout || "",
error: (result.stderr || (result.error ? result.error.message : "dump_header failed")).trim()
};
}
return { ok: true, text: result.stdout || "", error: "" };
}
function openElectronPreferences() {
let preferences = document.getElementById("preferencesDialog");
if (!preferences) return;
let workPath = document.getElementById("workPath");
let dataRoot = document.getElementById("dataRoot");
let startupXml = document.getElementById("startupXml");
let binDir = document.getElementById("binDir");
let musrfitThreads = document.getElementById("musrfitThreads");
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
preferences.dataset.originalWorkPath = workPath ? workPath.value : ".";
preferences.dataset.originalDataRoot = dataRoot ? dataRoot.value : "";
preferences.dataset.originalStartupXml = startupXml ? startupXml.value : "";
preferences.dataset.originalBinDir = binDir ? binDir.value : "";
preferences.dataset.originalMusrfitThreads = musrfitThreads ? musrfitThreads.value : "";
preferences.dataset.originalAsymmetrySuffix = asymmetrySuffix ? asymmetrySuffix.value : "_asy";
preferences.dataset.originalSingleHistSuffix = singleHistSuffix ? singleHistSuffix.value : "_singleHist";
preferences.dataset.originalGuessInitialParameters = guessInitialParameters && guessInitialParameters.checked ? "1" : "0";
preferences.dataset.originalEstimateT0FromPromptPeak = estimateT0FromPromptPeak && estimateT0FromPromptPeak.checked ? "1" : "0";
if (!preferences.dataset.cancelHandlerInstalled) {
preferences.addEventListener("cancel", function(event) {
event.preventDefault();
cancelElectronPreferences();
});
preferences.dataset.cancelHandlerInstalled = "1";
}
if (typeof preferences.showModal === "function") {
preferences.showModal();
} else {
preferences.setAttribute("open", "");
}
let runtimeControls = document.getElementById("localRuntimeControls");
if (runtimeControls) {
runtimeControls.hidden = nodeProcess.platform !== "linux" || !window.electronAPI || !window.electronAPI.localRuntime;
if (!runtimeControls.hidden && !electronRuntimeInstalling) checkElectronRuntime();
}
}
function showElectronRuntimeStatus(message) {
let status = document.getElementById("localRuntimeStatus");
if (status) status.textContent = message;
if (electronRuntimeInstalling && typeof setFitStatus === "function") setFitStatus(message);
let check = document.getElementById("runtimeCheck");
let install = document.getElementById("runtimeInstall");
let cancel = document.getElementById("runtimeCancel");
if (check) check.disabled = electronRuntimeInstalling || electronRuntimeChecking;
if (install) install.disabled = electronRuntimeInstalling || electronRuntimeChecking;
if (cancel) cancel.hidden = !electronRuntimeInstalling;
}
async function checkElectronRuntime() {
let api = window.electronAPI && window.electronAPI.localRuntime;
if (!api || electronRuntimeInstalling || electronRuntimeChecking) return;
electronRuntimeChecking = true;
showElectronRuntimeStatus("Checking the active musrfit tools...");
try {
let commands = {};
for (let name of ["musrfit", "musrview", "msr2data", "dump_header", "musrt0"]) {
commands[name] = resolveLocalCommand(name);
}
let result = await api.check({ commands: commands, env: buildToolEnvironment() });
let text = "Some active tools cannot start:";
if (result.ok) {
let first = result.tools[0];
let root = first.output && first.output.match(/ROOT version:\s*([^,\s]+)/);
text = "musrfit " + first.version + (root ? " / ROOT " + root[1] : "")
+ "; all five tools are available.\n" + nodePath.dirname(first.command);
} else {
for (let tool of result.tools) {
if (!tool.ok) text += "\n" + tool.name + ": " + tool.error;
}
}
showElectronRuntimeStatus(text);
} catch (error) {
showElectronRuntimeStatus("Could not check musrfit tools: " + error.message);
} finally {
electronRuntimeChecking = false;
let status = document.getElementById("localRuntimeStatus");
showElectronRuntimeStatus(status ? status.textContent : "");
}
}
async function installElectronRuntime() {
let api = window.electronAPI && window.electronAPI.localRuntime;
if (!api || electronRuntimeInstalling || electronRuntimeChecking) return;
if (window.MusrfitAction && window.MusrfitAction.busy) {
showElectronRuntimeStatus("Finish the current fit or plot before installing a runtime.");
return;
}
electronRuntimeInstalling = true;
electronRuntimeToken = "runtime-" + Date.now();
showElectronRuntimeStatus("Choose runtime-download.json from a downloaded runtime bundle.");
for (let id of ["FitMSR", "PlotMSR"]) {
let button = document.getElementById(id);
if (button) button.disabled = true;
}
let unsubscribe = api.onProgress(function(state) {
if (state.token !== electronRuntimeToken) return;
let message = state.phase + "...";
if (state.total) message += " " + (state.received / 1000000).toFixed(1) + " / " + (state.total / 1000000).toFixed(1) + " MB";
showElectronRuntimeStatus(message);
});
try {
let result = await api.install(electronRuntimeToken);
if (result.ok) {
let binDir = nodePath.join(result.root, "bin");
setConfiguredBinDir(binDir, true);
// Installation is a separate, explicitly confirmed action. Cancelling
// unrelated Preferences edits afterwards must not appear to undo it.
let preferences = document.getElementById("preferencesDialog");
let selected = getConfiguredBinDir() === binDir;
if (preferences && selected) preferences.dataset.originalBinDir = binDir;
if (selected && typeof reloadLocalPortableRunNaming === "function") reloadLocalPortableRunNaming();
showElectronRuntimeStatus(selected
? "Runtime installed and selected:\n" + result.root
: "Runtime installed, but the binaries preference could not be saved:\n" + result.root);
} else {
showElectronRuntimeStatus(result.cancelled ? "Runtime installation cancelled. Previous tools were kept."
: "Runtime installation failed: " + result.message);
}
} catch (error) {
showElectronRuntimeStatus("Runtime installation failed: " + error.message);
} finally {
unsubscribe();
electronRuntimeToken = "";
electronRuntimeInstalling = false;
wslRuntimeGateMessage = "";
let status = document.getElementById("localRuntimeStatus");
showElectronRuntimeStatus(status ? status.textContent : "");
if (typeof setMusrfitActionState === "function") setMusrfitActionState("", "idle");
}
}
function cancelElectronRuntimeInstall() {
let api = window.electronAPI && window.electronAPI.localRuntime;
if (api && electronRuntimeToken) {
api.cancel(electronRuntimeToken);
showElectronRuntimeStatus("Cancelling runtime installation...");
}
}
function closeElectronPreferences() {
let preferences = document.getElementById("preferencesDialog");
if (!preferences) return;
if (typeof preferences.close === "function") preferences.close();
else preferences.removeAttribute("open");
}
function saveElectronPreferences() {
let workPath = document.getElementById("workPath");
let dataRoot = document.getElementById("dataRoot");
let startupXml = document.getElementById("startupXml");
let binDir = document.getElementById("binDir");
let musrfitThreads = document.getElementById("musrfitThreads");
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
if (typeof setConfiguredWorkPath === "function" && workPath) {
setConfiguredWorkPath(workPath.value, true);
}
if (typeof setConfiguredDataRoot === "function" && dataRoot) {
setConfiguredDataRoot(dataRoot.value, true);
}
if (typeof setConfiguredStartupXml === "function" && startupXml) {
setConfiguredStartupXml(startupXml.value, true);
}
if (typeof setConfiguredBinDir === "function" && binDir) {
setConfiguredBinDir(binDir.value, true);
}
if (typeof setConfiguredMusrfitThreads === "function" && musrfitThreads) {
setConfiguredMusrfitThreads(musrfitThreads.value, true);
}
if (typeof reloadLocalPortableRunNaming === "function") {
reloadLocalPortableRunNaming();
}
if (typeof setConfiguredInitialParameterGuess === "function" && guessInitialParameters) {
setConfiguredInitialParameterGuess(guessInitialParameters.checked, true);
}
if (typeof setConfiguredT0FromPromptPeak === "function" && estimateT0FromPromptPeak) {
setConfiguredT0FromPromptPeak(estimateT0FromPromptPeak.checked, true);
}
if (typeof setConfiguredFileSuffix === "function") {
if (asymmetrySuffix) {
setConfiguredFileSuffix("asymmetrySuffix", asymmetrySuffixStorageKey,
asymmetrySuffix.value, defaultAsymmetrySuffix, true);
}
if (singleHistSuffix) {
setConfiguredFileSuffix("singleHistSuffix", singleHistSuffixStorageKey,
singleHistSuffix.value, defaultSingleHistSuffix, true);
}
}
closeElectronPreferences();
}
function cancelElectronPreferences() {
let preferences = document.getElementById("preferencesDialog");
if (!preferences) return;
let workPath = document.getElementById("workPath");
let dataRoot = document.getElementById("dataRoot");
let startupXml = document.getElementById("startupXml");
let binDir = document.getElementById("binDir");
let musrfitThreads = document.getElementById("musrfitThreads");
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
if (workPath) workPath.value = preferences.dataset.originalWorkPath || ".";
if (dataRoot) dataRoot.value = preferences.dataset.originalDataRoot || "";
if (startupXml) startupXml.value = preferences.dataset.originalStartupXml || "";
if (binDir) binDir.value = preferences.dataset.originalBinDir || "";
if (musrfitThreads) musrfitThreads.value = preferences.dataset.originalMusrfitThreads || "";
if (asymmetrySuffix) asymmetrySuffix.value = preferences.dataset.originalAsymmetrySuffix || "_asy";
if (singleHistSuffix) singleHistSuffix.value = preferences.dataset.originalSingleHistSuffix || "_singleHist";
if (guessInitialParameters) {
guessInitialParameters.checked = preferences.dataset.originalGuessInitialParameters !== "0";
}
if (estimateT0FromPromptPeak) {
estimateT0FromPromptPeak.checked = preferences.dataset.originalEstimateT0FromPromptPeak !== "0";
}
if (typeof updateResolvedDataPathPreview === "function") updateResolvedDataPathPreview();
if (typeof updateStartupNamingSourceIndicator === "function") updateStartupNamingSourceIndicator();
closeElectronPreferences();
}
// Synchronous command capture is kept for small utility commands such as
// msr2data template generation. Long-running fit/view execution uses spawn()
// below so the Electron renderer is not blocked.
function executeCapture(command, cwd = undefined, envOverrides = {}) {
command = prepareWslCommandString(command);
try {
const stdout = nodeChildProcess.execSync(command, {
cwd: cwd,
env: Object.assign(buildToolEnvironment(), envOverrides || {}),
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf8'
});
return { ok: 1, code: 0, stdout: stdout, stderr: "" };
} catch (err) {
return {
ok: 0,
code: err.status || 1,
stdout: err.stdout ? err.stdout.toString() : "",
stderr: err.stderr ? err.stderr.toString() : (err.message || "")
};
}
}
function checkDir(directory) {
let result = {
ok: 0,
path: typeof directory === "string" ? directory : "",
message: ""
};
if (result.path.trim() === "") {
result.message = "No Electron working folder is configured.";
return result;
}
try {
// Directory creation must finish before preparation starts writing files.
// The previous asynchronous mkdir returned success too early on first use.
if (!nodeFs.existsSync(result.path)) {
nodeFs.mkdirSync(result.path, { recursive: true });
}
let stats = nodeFs.statSync(result.path);
if (!stats || typeof stats.isDirectory !== "function" || !stats.isDirectory()) {
result.message = "The configured Electron working folder is not a directory:\n"
+ result.path;
return result;
}
// A directory can exist but still be unusable. Detect that before template
// generation so the user sees a folder error rather than a later save error.
let accessMode = nodeFs.constants.W_OK | nodeFs.constants.X_OK;
nodeFs.accessSync(result.path, accessMode);
} catch (error) {
result.message = "Cannot create or write to the Electron working folder:\n"
+ result.path;
if (error && error.message) {
result.message += "\n" + error.message;
}
return result;
}
result.ok = 1;
return result;
}
function writeAsciiFile(filename,content) {
// Write string content into ascii file filename
try { nodeFs.writeFileSync(filename, content, 'utf-8'); }
catch(e) {
alert('Failed to save '+filename);
return(0);
}
return(1);
}
function readAsciiFile(filename) {
// Read ascii file filename and return content in a string
var content;
// If an array of filenames was sent take the first one only
if (Array.isArray(filename)) {filename=filename[0];}
try {
content = nodeFs.readFileSync(filename, 'utf8');
} catch(e) {
alert('Failed to read '+filename);
return(0);
}
return(content);
}
function hasExplicitMSRTitle(filename) {
// Return true when the MSR carries an explicit first-line title that
// musrfit's `-t` (--title-from-data-file) would otherwise replace. The first
// non-blank, non-comment line of a real MSR is its run title; a GUI-generated
// MSR starts with the `# Run Numbers:` comment (or a blank line) and has no
// title to preserve.
try {
let content = nodeFs.readFileSync(filename, "utf8");
for (let rawLine of content.split(/\r?\n/)) {
let line = rawLine.trim();
if (line === "") continue;
return line[0] !== "#";
}
return false;
} catch (e) {
return false;
}
}
function deleteAsciiFile(filename) {
// Remove a generated text file when the caller needs to avoid stale artifacts.
// This is mainly used before msr2data, because its process status is not a
// reliable indicator of whether a fresh global MSR was produced.
try {
if (nodeFs.existsSync(filename)) {
nodeFs.unlinkSync(filename);
}
} catch(e) {
alert('Failed to delete '+filename);
return(0);
}
return(1);
}
function fileExists(filename) {
try {
if (nodeFs.existsSync(filename)) {
return 1;
}
}catch(err) {
console.log(err);
}
return 0;
}
// A relocatable ROOT + musrfit runtime can be shipped inside the packaged app
// (built by packaging/runtime and installed under <resources>/runtime). It is
// detected only when a musrfit executable is actually present, so development
// checkouts, web builds, and packages without the bundle fall back to the host
// installation unchanged.
function bundledRuntimeRoot() {
if (!nodeProcess || !nodeProcess.resourcesPath) return "";
let root = nodePath.join(nodeProcess.resourcesPath, "runtime");
if (fileExists(nodePath.join(root, "bin", "musrfit"))
|| fileExists(nodePath.join(root, "bin", "musrt0"))) {
return root;
}
return "";
}
function bundledRuntimeBinDir() {
let root = bundledRuntimeRoot();
return root === "" ? "" : nodePath.join(root, "bin");
}
// A separately packaged runtime (the musrflow-runtime rpm or the portable
// muSRFlow-runtime AppImage, both of which install here by default) is used
// when the app itself does not ship one. MUSRFLOW_RUNTIME_ROOT overrides the
// location for custom or user-local installs. Only Linux has a native runtime;
// Windows uses the bundled WSL2 distribution instead.
var MUSRFLOW_SYSTEM_RUNTIME_ROOT = "/opt/musrflow/runtime";
function systemRuntimeRoot() {
if (!nodeProcess || nodeProcess.platform === "win32") return "";
let root = (nodeProcess.env && nodeProcess.env.MUSRFLOW_RUNTIME_ROOT)
|| MUSRFLOW_SYSTEM_RUNTIME_ROOT;
if (root
&& (fileExists(nodePath.join(root, "bin", "musrfit"))
|| fileExists(nodePath.join(root, "bin", "musrt0")))) {
return root;
}
return "";
}
function systemRuntimeBinDir() {
let root = systemRuntimeRoot();
return root === "" ? "" : nodePath.join(root, "bin");
}
// The runtime prefix whose ROOTSYS/MUSRFITPATH/LD_LIBRARY_PATH should drive
// spawned tools: a runtime bundled inside the app wins, then a separately
// installed one.
function activeRuntimeRoot() {
// Only an explicitly selected private runtime changes the tool environment.
// Merely installing one must not shadow a working host installation.
let managed = nodeProcess.env && nodeProcess.env.MUSRFLOW_MANAGED_RUNTIME_DIRECTORY;
let configured = typeof getConfiguredBinDir === "function" ? getConfiguredBinDir() : "";
if (managed && configured && nodePath.basename(configured) === "bin") {
let root = nodePath.dirname(nodePath.resolve(configured));
if (root.startsWith(nodePath.resolve(managed) + "/")
&& fileExists(nodePath.join(root, "runtime-manifest.json"))
&& fileExists(nodePath.join(root, "lib", "libCore.so"))) return root;
}
let bundled = bundledRuntimeRoot();
if (bundled !== "") return bundled;
return systemRuntimeRoot();
}
// Environment for externally spawned musrfit tools. When a runtime (bundled or
// separately installed) is present, point ROOTSYS/MUSRFITPATH at it and prepend
// its lib directory so the binaries load the matching ROOT and musrfit shared
// libraries regardless of the host; otherwise the host environment is passed
// through with the usual PATH bias for the configured and PSI/local tool
// locations.
function buildToolEnvironment() {
let env = Object.assign({}, nodeProcess.env);
let root = activeRuntimeRoot();
// Windows runtime paths are supplied inside WSL by prepareLocalLaunch.
if (root !== "" && nodeProcess.platform !== "win32") {
let libDir = nodePath.join(root, "lib");
env.ROOTSYS = root;
env.MUSRFITPATH = root;
env.LD_LIBRARY_PATH = env.LD_LIBRARY_PATH
? libDir + ":" + env.LD_LIBRARY_PATH
: libDir;
}
if (nodeProcess.platform === "win32") {
// Plain bridge snapshots can contain Path and PATH. Node forwards only
// one case-insensitive match, so emit a single, canonical search path.
for (let key of Object.keys(env)) {
if (key.toUpperCase() === "PATH") delete env[key];
}
}
env.PATH = localCommandPathBias();
let dataSearchPath = localRunDataSearchPath(false);
if (dataSearchPath) env.MUSRFULLDATAPATH = dataSearchPath;
return env;
}
// --- Windows / WSL2 execution -------------------------------------------
// A packaged Windows build has no native ROOT + musrfit. Instead the same Linux
// runtime tree is imported into a bundled WSL2 distribution and the bundled
// tools run through wsl.exe. Host utilities (and a user-configured Windows tool
// directory) still launch directly.
var MUSRFLOW_WSL_DISTRO = "muSRFlow-runtime";
var MUSRFLOW_WSL_PREFIX = "/opt/musrfit-runtime";
function isWslRuntimeHost() {
return nodeProcess && nodeProcess.platform === "win32" && bundledRuntimeRoot() !== "";
}
// First-run runtime gate. The main process imports the bundled WSL2 distribution
// in the background at startup; until that finishes a Fit/Plot must wait rather
// than launch a tool inside a distribution that does not exist yet. The shared
// library calls window.MusrfitRuntimeGate.ready() before every Fit/Plot action.
var wslRuntimeReadyPromise = null;
var wslRuntimeGateMessage = "";
function refreshWslRuntimeGate() {
if (wslRuntimeReadyPromise) return wslRuntimeReadyPromise;
let api = window.electronAPI && window.electronAPI.wslRuntime;
if (!api || typeof api.ensure !== "function") {
// No bridge (development checkout or an older build): do not block.
wslRuntimeReadyPromise = Promise.resolve(true);
return wslRuntimeReadyPromise;
}
wslRuntimeReadyPromise = api.ensure().then(function (result) {
if (!result || result.ok) {
wslRuntimeGateMessage = "";
return true;
}
// Let a later action retry (for example after the user installs WSL2).
wslRuntimeReadyPromise = null;
wslRuntimeGateMessage = result.error || ("runtime setup failed: " + result.status);
return false;
}).catch(function (error) {
wslRuntimeReadyPromise = null;
wslRuntimeGateMessage = error && error.message ? error.message : String(error);
return false;
});
return wslRuntimeReadyPromise;
}
// A user-configured **musrfit binaries** directory holds Windows-native tools
// that can run without the bundled WSL2 runtime. If the import fails we fall
// back to those rather than blocking every Fit/Plot.
function hasConfiguredNativeTools() {
let configured = typeof getConfiguredBinDir === "function" ? getConfiguredBinDir() : "";
if (!configured) return false;
let names = ["musrfit", "musrfit.exe", "musrt0", "musrt0.exe"];
for (let i = 0; i < names.length; i++) {
try {
if (nodeFs.existsSync(nodePath.join(configured, names[i]))) return true;
} catch (error) {
// Treat an unreadable directory as "no native tools".
}
}
return false;
}
function wslRuntimeGateReady() {
if (electronRuntimeInstalling) {
wslRuntimeGateMessage = "Wait for the runtime installation to finish or cancel it.";
return Promise.resolve(false);
}
if (!isWslRuntimeHost()) return Promise.resolve(true);
let api = window.electronAPI && window.electronAPI.wslRuntime;
let unsubscribe = function () {};
if (api && typeof api.onStatus === "function") {
unsubscribe = api.onStatus(function (state) {
if (!state) return;
if (state.status === "checking") {
setFitStatus("Checking the bundled musrfit runtime...");
} else if (state.status === "importing") {
setFitStatus("Preparing the bundled musrfit runtime (first run only)...");
}
});
}
return refreshWslRuntimeGate().then(function (ready) {
unsubscribe();
if (!ready && hasConfiguredNativeTools()) {
setFitStatus("Bundled runtime unavailable; using the configured musrfit tools.",
{ level: "warning" });
return true;
}
return ready;
}, function (error) {
unsubscribe();
throw error;
});
}
// The shared library installs a no-op gate; the Electron shell replaces it with
// the WSL-aware one (a no-op on non-Windows hosts, where isWslRuntimeHost() is
// false).
if (window.MusrfitRuntimeGate) {
window.MusrfitRuntimeGate.ready = wslRuntimeGateReady;
window.MusrfitRuntimeGate.message = function () {
return wslRuntimeGateMessage
? wslRuntimeGateMessage
: "Check that WSL2 is installed, then try again.";
};
} else {
window.MusrfitRuntimeGate = {
ready: wslRuntimeGateReady,
message: function () {
return wslRuntimeGateMessage
? wslRuntimeGateMessage
: "Check that WSL2 is installed, then try again.";
}
};
}
// Translate an absolute Windows path (C:\dir\file or C:/dir/file) to the path
// its WSL mount exposes. Non-path arguments (flags, run lists) pass through.
function windowsPathToWsl(input) {
if (typeof input !== "string" || input === "") return input;
let match = /^([A-Za-z]):[\\/](.*)$/.exec(input);
if (!match) return input;
return "/mnt/" + match[1].toLowerCase() + "/" + match[2].replace(/\\/g, "/");
}
// Wrap a bundled Linux tool as a wsl.exe invocation, translating path
// arguments. Commands outside the runtime bin directory are unchanged so host
// tools and Windows-native binaries keep working.
function prepareLocalLaunch(command, args) {
args = args || [];
if (!isWslRuntimeHost()) return { command: command, args: args, viaWsl: false };
let binDir = bundledRuntimeBinDir();
if (!binDir || command.indexOf(binDir) !== 0) {
return { command: command, args: args, viaWsl: false };
}
let relative = command.slice(binDir.length).replace(/^[\\/]+/, "").replace(/\\/g, "/");
let inner = MUSRFLOW_WSL_PREFIX + "/bin/" + relative;
// Windows process.env is not the Linux tool environment. Set the runtime
// paths after `wsl -- env` so every bundled executable finds ROOT inside
// the imported distribution, without relying on shell startup files.
let wslArgs = ["-d", MUSRFLOW_WSL_DISTRO, "--", "env",
"ROOTSYS=" + MUSRFLOW_WSL_PREFIX,
"MUSRFITPATH=" + MUSRFLOW_WSL_PREFIX,
"LD_LIBRARY_PATH=" + MUSRFLOW_WSL_PREFIX + "/lib",
"PATH=" + MUSRFLOW_WSL_PREFIX + "/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"];
let dataSearchPath = localRunDataSearchPath(true);
if (dataSearchPath) wslArgs.push('MUSRFULLDATAPATH=' + dataSearchPath);
wslArgs.push(inner);
wslArgs = wslArgs
.concat(args.map(windowsPathToWsl));
return { command: "wsl.exe", args: wslArgs, viaWsl: true };
}
// Same translation for the one shell-string capture path (msr2data template
// generation), which builds a command such as
// "<binDir>/msr2data \"[1 2]\" _tmpl msr-1 global". Only the leading bundled
// executable is rewritten and Windows paths inside the quoted arguments are
// converted so msr2data sees /mnt/... paths.
function prepareWslCommandString(command) {
if (!isWslRuntimeHost() || typeof command !== "string") return command;
let binDir = bundledRuntimeBinDir();
if (!binDir || command.indexOf(binDir) !== 0) return command;
let remainder = command.slice(binDir.length).replace(/^[\\/]+/, "");
let spaceIndex = remainder.search(/\s/);
let exe = spaceIndex === -1 ? remainder : remainder.slice(0, spaceIndex);
let rest = spaceIndex === -1 ? "" : remainder.slice(spaceIndex);
rest = rest.replace(/[A-Za-z]:[\\/][^\s"']*/g, function(match) {
return windowsPathToWsl(match);
});
// Reuse the argv launcher so msr2data's shell capture receives exactly the
// same runtime and data paths as Fit/Plot. Double quotes work in cmd.exe
// and keep a downloaded-data path with spaces together as one argument.
let launch = prepareLocalLaunch(nodePath.join(binDir, exe), []);
let launchArguments = launch.args.map(function(argument) {
return '"' + argument.replace(/"/g, '\\"') + '"';
}).join(" ");
return launch.command + " " + launchArguments + rest;
}
function resolveLocalCommand(commandName) {
let candidates = [];
let configuredBinDir = typeof getConfiguredBinDir === "function"
? getConfiguredBinDir() : "";
if (configuredBinDir !== "") {
// A user-configured musrfit-tool directory wins over every built-in
// location, since auto-detection does not always find an installation.
candidates.push(nodePath.join(configuredBinDir, commandName));
}
let bundledBinDir = bundledRuntimeBinDir();
if (bundledBinDir !== "") {
// The bundled runtime outranks the host installation but still yields to
// an explicit user-configured tools directory.
candidates.push(nodePath.join(bundledBinDir, commandName));
}
let systemBinDir = systemRuntimeBinDir();
if (systemBinDir !== "") {
// A separately installed runtime (musrflow-runtime rpm / AppImage) ranks
// below the bundled one but still above the system installation.
candidates.push(nodePath.join(systemBinDir, commandName));
}
candidates = candidates.concat([
"/usr/local/bin/" + commandName,
"/usr/bin/" + commandName
]);
if (nodeProcess.resourcesPath) {
candidates.push(nodePath.join(nodeProcess.resourcesPath, "bin", commandName));
candidates.push(nodePath.join(nodeProcess.resourcesPath, commandName));
}
candidates.push(nodePath.join(nodeProcess.cwd(), commandName));
for (let candidate of candidates) {
if (fileExists(candidate)) return candidate;
}
return commandName;
}
// Path bias applied to externally spawned tools. The bundled runtime and the
// configured musrfit-tool directory, when present, are placed ahead of the
// usual PSI/local locations so children of musrfit that resolve their own
// helpers follow the preference.
function localCommandPathBias() {
let configuredBinDir = typeof getConfiguredBinDir === "function"
? getConfiguredBinDir() : "";
if (nodeProcess.platform === "win32") {
// Windows normally calls this variable Path. Preserve its directories
// and use semicolons; Linux prefixes can hide System32 and wsl.exe.
// Bundled Linux tools run inside WSL, not on the Windows host PATH.
let env = nodeProcess.env || {};
let pathKey = Object.keys(env).sort().find(function(key) {
return key.toUpperCase() === "PATH";
});
let dirs = configuredBinDir ? [configuredBinDir] : [];
if (pathKey && env[pathKey]) dirs.push(env[pathKey]);
return dirs.join(";");
}
let dirs = ["/usr/local/bin", "/usr/bin", "/bin"];
let systemBinDir = systemRuntimeBinDir();
if (systemBinDir !== "") {
dirs.unshift(systemBinDir);
}
let bundledBinDir = bundledRuntimeBinDir();
if (bundledBinDir !== "") {
dirs.unshift(bundledBinDir);
}
if (configuredBinDir !== "") {
dirs.unshift(configuredBinDir);
}
return dirs.concat(nodeProcess.env ? (nodeProcess.env.PATH || "") : "").join(":");
}
// Local runs mirror process output into a stable .out file. This gives the
// Electron workflow the same practical debugging hook as the old CGI workflow.
function appendFitLog(logFile, text) {
try {
nodeFs.appendFileSync(logFile, text, "utf-8");
} catch (err) {
console.log("Failed to append fit log:", err);
}
}
// Reading a msr2data parameter table, normalizing its column header via the
// shared pure-text transform, and writing the result back.
function cleanMusrfitParameterDataHeader(parameterPath, runNumbers = []) {
let contents = nodeFs.readFileSync(parameterPath, "utf8");
let newline = contents.includes("\r\n") ? "\r\n" : "\n";
let lines = contents.split(/\r?\n/);
lines = normalizeParameterDataHeaderLines(lines, runNumbers);
nodeFs.writeFileSync(parameterPath, lines.join(newline), "utf8");
}
// Stream output to both destinations: the on-screen status area for immediate
// feedback and the .out file for complete inspection after the process exits.
function appendProcessOutput(label, chunk, logFile) {
let text = chunk.toString();
appendFitLog(logFile, text);
let trimmed = text.trim();
if (trimmed !== "" && typeof appendJobLog === "function") {
appendJobLog(label + " output:\n" + trimmed);
}
}
// Run one external command and resolve when it exits. This is intentionally
// Promise-based rather than callback-only so runMSRFileLocal() can express the
// required sequence clearly and lets both executables share output classification.
function runLocalProcess(label, command, args, cwd, logFile, options = {}) {
let launch = prepareLocalLaunch(command, args);
let commandLine = displayCommand(launch.command, launch.args);
let reportStatus = options.reportStatus !== false;
if (reportStatus && typeof updateJobStatus === "function") {
updateJobStatus({
state: "Running " + label,
message: "Running " + label,
lastCommand: commandLine,
finishedAt: "",
exitCode: ""
});
}
if (typeof appendJobLog === "function") {
appendJobLog("Starting " + label + ": " + commandLine);
}
appendFitLog(logFile, "\n$ " + commandLine + "\n");
// Preserve the user's environment but bias PATH toward the bundled,
// configured, and PSI/local locations where musrfit installations live.
let env = buildToolEnvironment();
// In the hardened build child_process access lives behind the preload
// bridge, which buffers the streams and invokes onChunk per chunk so the
// live .out log and on-screen output behave exactly as before. The token
// lets the Abort action kill this job through the same bridge.
if (typeof nodeChildProcess.spawnCapture === "function") {
let jobToken = "";
if (typeof nodeChildProcess.abortJob === "function") {
jobToken = "musr" + (++electronRunJobSeq);
electronRunJobToken = jobToken;
electronRunJobLabel = label;
electronRunJobLogFile = logFile;
electronRunJobAborted = false;
}
return nodeChildProcess.spawnCapture(launch.command, launch.args, {
cwd: cwd,
env: env,
jobToken: jobToken
}, function(stream, chunk) {
appendProcessOutput(label, chunk, logFile);
}).then(function(result) {
if (electronRunJobToken === jobToken) {
electronRunJobToken = "";
electronRunJobLabel = "";
electronRunJobLogFile = "";
electronRunJobAborted = false;
}
if (result.error) {
let spawnMessage = label + " failed to start: " + result.error;
appendFitLog(logFile, label + " spawn failed: " + result.error + "\n");
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(0, 1, spawnMessage);
}
let err = new Error(result.error);
err.result = result;
return { ok: 0, code: 1, signal: null, error: err };
}
if (result.signal) {
// Terminated by the Abort action (or an external signal). Report it
// distinctly so the run is not mistaken for a failed fit.
let abortMessage = label + " was aborted.";
appendFitLog(logFile, label + " aborted (signal " + result.signal + ")\n");
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(0, 0, abortMessage, "aborted");
}
return { ok: 0, code: result.code, signal: result.signal,
stdout: result.stdout, stderr: result.stderr, outcome: "aborted" };
}
let ok = result.ok === 1;
let code = result.code;
let signal = result.signal || "";
let exitText = label + " exited with code " + code;
if (signal) exitText += " (signal " + signal + ")";
appendFitLog(logFile, exitText + "\n");
let missingData = typeof classifyMissingDataOutput === "function"
? classifyMissingDataOutput(result.stdout + "\n" + result.stderr) : { outcome: "" };
if (missingData.outcome == "missing-data") {
ok = false;
}
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(
ok ? 1 : 0,
code,
missingData.outcome == "missing-data" ? missingData.details : exitText,
missingData.outcome
);
}
return {
ok: ok ? 1 : 0,
code: code,
signal: signal,
stdout: result.stdout,
stderr: result.stderr,
outcome: missingData.outcome,
missingFiles: missingData.missingFiles || []
};
});
}
// Legacy streaming path kept for non-bridged environments (test sandboxes).
// No bridge token exists here, so Abort cannot reach this child.
electronRunJobToken = "";
return new Promise(function(resolve) {
let child;
let settled = false;
let stdoutText = "";
let stderrText = "";
try {
// shell:false keeps arguments such as file names and flags separate.
// It also avoids shell quoting bugs for work paths containing spaces.
child = nodeChildProcess.spawn(command, args, {
cwd: cwd,
env: env,
shell: false,
stdio: ["ignore", "pipe", "pipe"]
});
} catch (err) {
let spawnMessage = label + " failed to start: " + err.message;
appendFitLog(logFile, label + " spawn failed: " + err.message + "\n");
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(0, 1, spawnMessage);
}
resolve({ ok: 0, code: 1, signal: null, error: err });
return;
}
// musrfit/musrview can write useful diagnostics to either stream, so both
// are handled the same way and kept in chronological order as much as Node
// stream delivery allows.
child.stdout.on("data", function(chunk) {
stdoutText += chunk.toString();
appendProcessOutput(label, chunk, logFile);
});
child.stderr.on("data", function(chunk) {
stderrText += chunk.toString();
appendProcessOutput(label, chunk, logFile);
});
child.on("error", function(err) {
if (settled) return;
settled = true;
appendFitLog(logFile, label + " error: " + err.message + "\n");
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(0, 1, label + " error: " + err.message);
}
resolve({ ok: 0, code: 1, signal: null, error: err });
});
// close fires after stdio streams are closed, which makes it the right
// completion signal when logs are being collected from stdout/stderr.
child.on("close", function(code, signal) {
if (settled) return;
settled = true;
let ok = code === 0;
let exitText = label + " exited with code " + code;
if (signal) exitText += " (signal " + signal + ")";
appendFitLog(logFile, exitText + "\n");
let missingData = typeof classifyMissingDataOutput === "function"
? classifyMissingDataOutput(stdoutText + "\n" + stderrText) : { outcome: "" };
if (missingData.outcome == "missing-data") {
ok = false;
}
if (reportStatus && typeof finishJobStatus === "function") {
finishJobStatus(
ok ? 1 : 0,
code,
missingData.outcome == "missing-data" ? missingData.details : exitText,
missingData.outcome
);
}
resolve({
ok: ok ? 1 : 0,
code: code,
signal: signal,
stdout: stdoutText,
stderr: stderrText,
outcome: missingData.outcome,
missingFiles: missingData.missingFiles || []
});
});
});
}
// Execute exactly one already promoted independent-run MSR. Series collection,
// plotting, GUI synchronization, and transaction finalization belong to later
// layers; this adapter only invokes musrfit and returns its reliable process
// result to runPreparedSeriesFitSequence().
async function runSeriesMSRCandidateLocal(receipt, candidate, context = {}) {
let targetName = receipt && receipt.targetPath
? nodePath.basename(receipt.targetPath) : "";
let targetPattern = candidate && Number.isInteger(candidate.run)
? new RegExp("^" + candidate.run + "(?:[._+\\-][A-Za-z0-9._+\\-]*)?\\.msr$", "i")
: null;
if (!receipt || !candidate || receipt.run !== candidate.run
|| receipt.targetPath !== candidate.targetPath
|| !targetPattern || !targetPattern.test(targetName)
|| !isSafeSeriesRegularFile(receipt.targetPath)) {
return {
ok: 0,
code: 1,
outcome: "",
statusText: "Invalid local series candidate receipt."
};
}
if (window.MusrfitRunner.fitActive) {
return {
ok: 0,
code: 1,
outcome: "",
statusText: "Another local musrfit job is already running."
};
}
let resolvedPath = nodePath.resolve(receipt.targetPath);
let fitName = nodePath.basename(resolvedPath);
let fitDir = nodePath.dirname(resolvedPath);
let logFile = resolvedPath.replace(/\.msr$/i, ".out");
if (nodeFs.existsSync(logFile) && !isSafeSeriesRegularFile(logFile)) {
return {
ok: 0,
code: 1,
outcome: "",
statusText: "Series fit log is not a regular file."
};
}
let position = Number(context.position || 0);
let total = Number(context.total || 0);
let heading = "# muSRFlow independent series fit\n"
+ "# Run: " + candidate.run + "\n"
+ (position > 0 && total > 0 ? "# Position: " + position + "/" + total + "\n" : "")
+ "# Working directory: " + fitDir + "\n";
try {
nodeFs.writeFileSync(logFile, heading, { encoding: "utf8", flag: "w" });
} catch (error) {
return {
ok: 0,
code: 1,
outcome: "",
statusText: "Could not initialize the series fit log: " + error.message
};
}
window.MusrfitRunner.fitActive = true;
try {
let fitResult = await runLocalProcess(
"musrfit run " + candidate.run,
resolveLocalCommand("musrfit"),
["-e", "-t", fitName],
fitDir,
logFile,
{ reportStatus: false }
);
let validationReason = "";
if (fitResult.ok) {
let fittedText = isSafeSeriesRegularFile(resolvedPath)
? nodeFs.readFileSync(resolvedPath, "utf8") : "";
if (!isValidGeneratedGlobalMSR(fittedText)) {
validationReason = "series-candidate-structure-invalid";
} else if (parseMSRFitStatistic(fittedText).converged !== true) {
validationReason = "series-candidate-not-converged";
} else if (seriesRunDirectiveIdentity(fittedText)
!== seriesRunDirectiveIdentity(receipt.promotedText)) {
validationReason = "series-candidate-run-identity-changed";
}
}
let ok = fitResult.ok && validationReason === "";
return {
ok: ok ? 1 : 0,
code: fitResult.code,
signal: fitResult.signal,
outcome: fitResult.outcome || "",
missingFiles: fitResult.missingFiles || [],
stdout: fitResult.stdout || "",
stderr: fitResult.stderr || "",
targetPath: resolvedPath,
logPath: logFile,
reason: validationReason,
statusText: ok
? "Run " + candidate.run + " fitted."
: (fitResult.ok
? "Run " + candidate.run + " output failed validation: "
+ validationReason + "."
: "Run " + candidate.run + " fit failed.")
};
} finally {
window.MusrfitRunner.fitActive = false;
}
}
window.runSeriesMSRCandidateLocal = runSeriesMSRCandidateLocal;
// Collect independent fitted MSRs without fitting them again. The merged
// parameter table comes from msr2data, while the combined display MSR is
// assembled here from the per-run fitted files (msr2data only writes its
// +global file from a template). A non-empty requested .dat is registered
// immediately, and any structurally valid combined MSR is safe for musrview.
async function collectIndependentSeriesArtifactsLocal(spec) {
let prepared = prepareIndependentSeriesCollection(spec);
let result = normalizeIndependentSeriesCollectionResult({ reason: prepared.reason });
if (!prepared.ok) return result;
let workPath = nodePath.resolve(prepared.workPath);
let suffix = prepared.fileNameSuffix;
let baseRun = prepared.baseRun;
for (let index = 0; index < prepared.runs.length; index++) {
if (nodePath.resolve(prepared.msrPaths[index])
!== nodePath.join(workPath, prepared.runs[index] + suffix + ".msr")
|| !isSafeSeriesRegularFile(prepared.msrPaths[index])) {
result.reason = "series-artifact-source-invalid";
return result;
}
}
// The first fitted run's own MSR doubles as the per-run template shown by
// the Results "Template MSR" entry. All per-run files remain directly
// available in the local working directory.
result.templatePath = prepared.msrPaths[0];
// Independent-series artifacts use their own namespace. A genuine global
// fit can legitimately exist beside the same per-run files and must never
// be removed or replaced by display-only post-processing.
let combinedName = prepared.combinedName;
let combinedPath = nodePath.join(workPath, combinedName);
let parameterName = prepared.parameterName;
let parameterPath = nodePath.join(workPath, parameterName);
let logName = prepared.logName;
let logPath = nodePath.join(workPath, logName);
result.logPath = logPath;
try {
for (let stalePath of [combinedPath, parameterPath]) {
if (!nodeFs.existsSync(stalePath)) continue;
if (!isSafeSeriesRegularFile(stalePath)) {
result.reason = "series-artifact-output-invalid";
return result;
}
nodeFs.unlinkSync(stalePath);
}
nodeFs.writeFileSync(logPath,
"# muSRFlow independent series collection\n# Working directory: "
+ workPath + "\n", { encoding: "utf8", flag: "w" });
let runsArg = "[" + prepared.runs.join(" ") + "]";
let msr2data = resolveLocalCommand("msr2data");
let env = buildToolEnvironment();
let runMsr2data = function(label, args) {
let launch = prepareLocalLaunch(msr2data, args);
let commandLine = displayCommand(launch.command, launch.args);
appendFitLog(logPath, "\n$ " + commandLine + "\n");
if (typeof appendJobLog === "function") {
appendJobLog("Starting independent series " + label + ": " + commandLine);
}
let commandResult = nodeChildProcess.spawnSync(launch.command, launch.args, {
cwd: workPath,
env: env,
encoding: "utf8",
shell: false
});
if (commandResult.stdout) {
appendProcessOutput("independent series " + label, commandResult.stdout, logPath);
}
if (commandResult.stderr) {
appendProcessOutput("independent series " + label, commandResult.stderr, logPath);
}
let code = typeof commandResult.status === "number" ? commandResult.status : 1;
appendFitLog(logPath, "independent series " + label
+ " exited with code " + code + "\n");
return code;
};
// Parameter collection is the primary independent-series result. Use
// msr2data's ordinary per-run data mode—the same operation as the
// established rplcall/msr2data workflow—so an unsupported display merge
// can never prevent Plot parameters from receiving a usable table.
let parameterCode = runMsr2data("parameter msr2data",
[runsArg, suffix, "new", "data", "-o", parameterName]);
if (isSafeSeriesRegularFile(parameterPath)
&& nodeFs.statSync(parameterPath).size > 0) {
try {
cleanMusrfitParameterDataHeader(parameterPath, spec.runs);
} catch (error) {
result.warnings.push("Could not normalize the parameter-table header.");
}
result.parameterDataPath = parameterPath;
if (parameterCode !== 0) {
result.warnings.push("msr2data returned code " + parameterCode
+ " but produced the parameter table.");
}
} else {
result.warnings.push("msr2data did not produce parameter data.");
}
// Assemble the combined display MSR independently from the already
// fitted per-run files. No global re-fit takes place.
let msrTexts = [];
for (let index = 0; index < prepared.msrPaths.length; index++) {
if (!isSafeSeriesRegularFile(prepared.msrPaths[index])) {
result.warnings.push("Fitted MSR " + prepared.msrPaths[index]
+ " is missing for the combined display.");
break;
}
msrTexts.push(nodeFs.readFileSync(prepared.msrPaths[index], "utf8"));
}
if (msrTexts.length === prepared.msrPaths.length) {
let merged = buildSeriesGlobalMSR(msrTexts, prepared.runs);
if (merged.ok !== true) {
result.warnings.push("Could not assemble the combined display MSR ("
+ merged.reason + ").");
} else if (!isValidGeneratedGlobalMSR(merged.text)) {
result.warnings.push("Assembled combined display MSR failed validation.");
} else {
let combinedText = normalizeMSRPlotRuns(merged.text, {}, prepared.runs);
nodeFs.writeFileSync(combinedPath, combinedText, {
encoding: "utf8", flag: "wx"
});
result.combinedMSRPath = combinedPath;
}
} else {
result.warnings.push("Could not read all fitted per-run MSR files"
+ " for the combined display.");
}
if (result.combinedMSRPath) {
let musrviewArgs = [];
if (prepared.fftv == "y") musrviewArgs.push("-f");
musrviewArgs.push(combinedName);
let viewId = window.MusrfitRunner.nextViewId++;
runLocalProcess("musrview series #" + viewId,
resolveLocalCommand("musrview"), musrviewArgs, workPath, logPath,
{ reportStatus: false });
result.plotStarted = true;
}
return normalizeIndependentSeriesCollectionResult(result);
} catch (error) {
result.reason = "series-artifact-collection-failed";
result.warnings.push(error && error.message
? error.message : "Series post-processing failed.");
return normalizeIndependentSeriesCollectionResult(result);
}
}
window.collectIndependentSeriesArtifactsLocal = collectIndependentSeriesArtifactsLocal;
function exportLocalMusrfitParameterData(resolvedPath, options, logFile) {
let runs = String(options.runs || "").trim().split(/\s+/).filter(Boolean);
let baseRun = String(options.baseRun || (runs.length ? runs[0] : ""));
if (!runs.length || !baseRun) return "";
let fitDir = nodePath.dirname(resolvedPath);
let fitName = nodePath.basename(resolvedPath);
let parameterFile = fitName.replace(/\.msr$/i, "_par.dat");
let parameterPath = nodePath.join(fitDir, parameterFile);
let msr2data = resolveLocalCommand("msr2data");
let parameterRuns = runs.length > 1 ? "[" + runs.join(" ") + "]" : runs[0];
let args = [parameterRuns, "_tmpl", "new"];
if (runs.length > 1) args.push("global");
args.push("data", "-o", parameterFile);
// msr2data locates its input from the run number and suffix rather than a
// filename. Stage the fitted result under the legacy `_tmpl` name, then
// restore the user's real template afterwards.
let sourceName = runs.length > 1
? baseRun + "+global_tmpl.msr" : baseRun + "_tmpl.msr";
let sourcePath = nodePath.join(fitDir, sourceName);
let sourceExisted = fileExists(sourcePath) ? true : false;
let sourceBackup = sourceExisted ? nodeFs.readFileSync(sourcePath, "utf8") : "";
try {
nodeFs.rmSync(parameterPath, { force: true });
nodeFs.writeFileSync(sourcePath, nodeFs.readFileSync(resolvedPath, "utf8"), "utf8");
let launch = prepareLocalLaunch(msr2data, args);
let commandLine = displayCommand(launch.command, launch.args);
appendFitLog(logFile, "\n$ " + commandLine + "\n");
if (typeof appendJobLog === "function") {
appendJobLog("Starting msr2data parameter export: " + commandLine);
}
let env = buildToolEnvironment();
let result = nodeChildProcess.spawnSync(launch.command, launch.args, {
cwd: fitDir,
env: env,
encoding: "utf8",
shell: false
});
if (result.stdout) appendProcessOutput("msr2data parameter export", result.stdout, logFile);
if (result.stderr) appendProcessOutput("msr2data parameter export", result.stderr, logFile);
let code = typeof result.status === "number" ? result.status : 1;
appendFitLog(logFile, "msr2data parameter export exited with code " + code + "\n");
// Some msr2data versions return an unreliable status. As in the CGI,
// a non-empty requested output file is the authoritative success signal.
if (fileExists(parameterPath) && nodeFs.statSync(parameterPath).size > 0) {
cleanMusrfitParameterDataHeader(parameterPath);
if (typeof updateJobStatus === "function") {
updateJobStatus({ parameterDataPath: parameterPath });
}
return parameterPath;
}
if (typeof appendJobLog === "function") {
appendJobLog("msr2data did not produce parameter data.");
}
return "";
} catch (error) {
appendFitLog(logFile, "Parameter export failed: " + error.message + "\n");
if (typeof appendJobLog === "function") {
appendJobLog("Parameter export failed: " + error.message);
}
return "";
} finally {
try {
if (sourceExisted) {
nodeFs.writeFileSync(sourcePath, sourceBackup, "utf8");
} else {
nodeFs.rmSync(sourcePath, { force: true });
}
} catch (error) {
appendFitLog(logFile, "Failed to restore " + sourceName + ": " + error.message + "\n");
}
}
}
// Electron/local implementation of the shared runMSRFile() API. The web nodePath
// will keep using a CGI endpoint, while this nodePath can execute binaries directly.
// options.plotOnly selects the "Plot" button behavior: skip musrfit and open
// the generated MSR with musrview immediately.
async function runMSRFileLocal(fullPath, options = {}) {
let plotOnly = options.plotOnly ? true : false;
// Only block a new Fit while another musrfit process is active. Plot/musrview
// requests are intentionally not blocked, and musrview started after a fit
// must not keep the musrfit lock held.
if (!plotOnly && window.MusrfitRunner.fitActive) {
if (typeof setFitStatus === "function") {
setFitStatus("A local musrfit job is already running.", { level: "warning" });
}
return 0;
}
// Normalize to an absolute nodePath so the working directory and the MSR file
// name are unambiguous before spawning external commands.
let resolvedPath = nodePath.resolve(fullPath);
let fitName = nodePath.basename(resolvedPath);
let fitDir = nodePath.dirname(resolvedPath);
let outName = fitName.replace(/\.msr$/i, ".out");
let logFile = nodePath.join(fitDir, outName);
let musrfit = resolveLocalCommand("musrfit");
let musrview = resolveLocalCommand("musrview");
// Local fitting estimates N0 and derives the title from the data file. Keep
// the Electron path timeout-free; musrfit writes fitted values back to MSR.
//
// `-t` (--title-from-data-file) tells musrfit to overwrite the MSR run title
// with the title of the first run's data file. GUI-generated MSRs have no
// title (they start with the `# Run Numbers:` comment), so deriving one is
// desirable there. But an editor-owned MSR may carry an explicit title the
// user wants preserved, which `-t` would silently clobber. Only pass `-t`
// when the target MSR has no such explicit first-line title.
let musrfitArgs = ["-e"];
if (!hasExplicitMSRTitle(resolvedPath)) musrfitArgs.push("-t");
// Cap OpenMP threads when the user set a count in Preferences; a blank/auto
// setting (0) leaves `-u` out so musrfit uses all available cores.
let configuredThreads = (typeof getConfiguredMusrfitThreads === "function")
? getConfiguredMusrfitThreads() : 0;
if (configuredThreads > 0) {
musrfitArgs.push("-u");
musrfitArgs.push(String(configuredThreads));
}
musrfitArgs.push(fitName);
// musrview should inspect the resulting fitted MSR. Fourier plotting is
// controlled by the caller so the same function can serve normal and FFT UI.
let musrviewArgs = [];
if (options.fftv === "y") musrviewArgs.push("-f");
musrviewArgs.push(fitName);
// Mark only the fit phase busy. musrview is not part of this lock.
if (!plotOnly) window.MusrfitRunner.fitActive = true;
try {
// Start a fresh log for each run. Process output is appended below.
nodeFs.writeFileSync(logFile, "# muSRFlow local run\n# Working directory: " + fitDir + "\n", "utf-8");
} catch (err) {
console.log("Failed to initialize fit log:", err);
}
if (typeof appendJobLog === "function") {
appendJobLog("Local run directory: " + fitDir);
appendJobLog("Log file: " + logFile);
}
if (typeof updateJobStatus === "function") {
updateJobStatus({
resultMSR: resolvedPath,
logPath: logFile
});
}
if (plotOnly) {
// Plot mode intentionally leaves the generated MSR unchanged and only
// launches musrview. It is not serialized, so users can open multiple
// musrview windows/processes in parallel.
let viewId = window.MusrfitRunner.nextViewId++;
runLocalProcess("musrview #" + viewId, musrview, musrviewArgs, fitDir, logFile).then(function(plotResult) {
if (plotResult.ok && typeof setFitStatus === "function") {
setFitStatus("Plot #" + viewId + " completed.", {
level: "success",
details: "Local musrview plot #" + viewId + " completed."
});
}
});
return 1;
}
// The first phase performs the fit. Whether it succeeds or fails, we still
// open musrview on the resulting MSR so users can inspect why a fit did not
// converge. Parameter export and GUI synchronization only apply to a
// successful fit, whose MSR contains the fitted values.
// For eligible bulk instruments, force t0 to the prompt peak before fitting.
// LEM and HAL/HIFI must keep their existing t0. musrt0 writes explicit
// `t0` lines into the generated MSR, which musrfit then always honors. This is
// a best-effort pre-step: if musrt0 fails, musrfit still runs and reports the
// real problem.
let instrumentNameForT0 = (typeof activeInstrumentName === "function")
? activeInstrumentName() : ((typeof All !== "undefined" && All && All.instrName) ? All.instrName : "");
if (typeof shouldEstimateT0FromPromptPeak === "function" && shouldEstimateT0FromPromptPeak(instrumentNameForT0, resolvedPath)) {
let musrt0 = resolveLocalCommand("musrt0");
if (typeof appendJobLog === "function") {
appendJobLog("Estimating t0 from the prompt peak for bulk data (excluding LEM and HAL).");
}
try {
let t0Result = await runLocalProcess("musrt0", musrt0, [fitName, "-g"], fitDir, logFile, {
reportStatus: false
});
if (t0Result && t0Result.ok !== 1 && typeof appendJobLog === "function") {
appendJobLog("musrt0 prompt-peak estimation did not complete; continuing with the MSR as-is.");
}
} catch (err) {
if (typeof appendJobLog === "function") {
appendJobLog("musrt0 prompt-peak estimation failed: " + (err ? err.message : err) + "; continuing with the MSR as-is.");
}
}
}
let fitResult = await runLocalProcess("musrfit", musrfit, musrfitArgs, fitDir, logFile);
if (window.MusrfitRunner) window.MusrfitRunner.fitActive = false;
// A missing input is not a failed minimization and there is no useful result
// for musrview to inspect. The process runner has already reported the path.
if (fitResult.outcome == "missing-data") {
return 0;
}
if (fitResult.ok) {
// Generate the same `_par.dat` artifact as the web CGI before launching
// musrview. This gives the floating parameter viewer web/Electron parity.
exportLocalMusrfitParameterData(resolvedPath, options, logFile);
if (typeof setFitStatus === "function") {
setFitStatus("Fit completed; opening plot.", {
level: "success",
details: "Fit completed. Starting musrview on " + fitName + "."
});
}
let fittedMSR = readAsciiFile(resolvedPath);
if (fittedMSR && typeof applyFittedMSRToGUI === "function") {
let normalizedMSR = applyFittedMSRToGUI(fittedMSR, resolvedPath, options);
// Electron owns the local file, so persist the shared PLOT normalization
// before musrview reads it. Web normalization is persisted by the CGI.
if (normalizedMSR !== fittedMSR) {
try {
nodeFs.writeFileSync(resolvedPath, normalizedMSR, "utf-8");
} catch(e) {
console.log("Failed to update PLOT runs line in fitted MSR:", e);
}
}
}
} else {
if (typeof setFitStatus === "function") {
setFitStatus("Fit failed; opening plot to inspect the result.", {
level: "error",
details: "Fit failed; opening musrview on " + fitName + " to inspect why."
});
}
}
let fitSucceeded = fitResult.ok === 1;
let viewId = window.MusrfitRunner.nextViewId++;
// A diagnostic viewer must not replace the failed musrfit result with its
// own successful exit status. It still writes its command and output to the
// run log, but the failed fit remains the outcome shown to the user.
runLocalProcess("musrview #" + viewId, musrview, musrviewArgs, fitDir, logFile, {
reportStatus: fitSucceeded
}).then(function(viewResult) {
if (fitSucceeded && viewResult.ok && typeof setFitStatus === "function") {
setFitStatus("Plot #" + viewId + " completed.", {
level: "success",
details: "Local musrview #" + viewId + " completed."
});
}
if (!fitSucceeded && !viewResult.ok && typeof setFitStatus === "function") {
setFitStatus("Fit failed; the diagnostic plot could not be opened.", {
level: "error",
details: "musrfit failed and diagnostic musrview #" + viewId
+ " could not be opened. See the run log for both commands."
});
}
});
return fitSucceeded ? 1 : 0;
}
// Portable RUN naming for Electron: resolve candidate files on this machine and
// enable portable naming from a startup XML discovered/configured in
// Preferences. This is the filesystem companion to the server-backed web hook,
// keeping the library transport-neutral.
function portableRunResolver(subPath, dataPath) {
if (!subPath || !dataPath) return false;
if (subPath.charAt(0) === "/" || subPath.split(/[\\/]/).indexOf("..") !== -1) return false;
try {
return nodeFs.existsSync(nodePath.join(dataPath, subPath));
} catch (e) {
return false;
}
}
function loadLocalPortableRunNaming() {
if (typeof setPortableRunNaming !== "function"
|| typeof parseMusrfitStartupXML !== "function") {
return "";
}
// Follow the conventional musrfit startup-file locations for this machine. A
// path the user configured in Preferences takes precedence.
let configured = (typeof getConfiguredStartupXml === "function")
? getConfiguredStartupXml() : "";
let startupPath = (configured && nodeFs.existsSync(configured)) ? configured : "";
if (!startupPath) {
let candidates = [];
let home = nodeProcess.env.HOME || "";
if (home) candidates.push(nodePath.join(home, ".musrfit", "musrfit_startup.xml"));
candidates.push(nodePath.join(nodeProcess.cwd(), "musrfit_startup.xml"));
let runtimeRoots = Array.from(new Set([activeRuntimeRoot(), bundledRuntimeRoot(), systemRuntimeRoot()]));
for (let i = 0; i < runtimeRoots.length; i++) {
if (runtimeRoots[i] !== "") {
// Final fallbacks: the startup XML shipped with the bundled runtime
// or with a separately installed runtime.
candidates.push(nodePath.join(runtimeRoots[i], "musrfit_startup.xml"));
}
}
for (let i = 0; i < candidates.length; i++) {
if (nodeFs.existsSync(candidates[i])) {
startupPath = candidates[i];
break;
}
}
}
let startup = null;
if (startupPath) {
try {
startup = parseMusrfitStartupXML(nodeFs.readFileSync(startupPath, "utf8"));
} catch (e) {
startup = null;
}
}
// With no startup object, portable naming stays disabled and the library
// keeps the explicit absolute-path fallback in runFileNameAuto().
setPortableRunNaming(!!startup, startup, portableRunResolver);
if (typeof updateStartupNamingSourceIndicator === "function") {
updateStartupNamingSourceIndicator();
}
return startupPath;
}
function reloadLocalPortableRunNaming() {
return loadLocalPortableRunNaming();
}
// Register the renderer-side IPC handlers used by the Electron menu and the
// data-root chooser.
function firstLoad() {
if (!electronIpcRenderer) {
console.log("Electron ipcRenderer is not available; menu IPC handlers were not registered.");
return;
}
// Catch calls for open file
electronIpcRenderer.on('openFile', function(filename) {
const filePath = Array.isArray(filename) ? filename[0] : filename.toString();
console.log("[renderer.openFile] received path: " + filePath);
nodeFs.readFile(filePath, "utf8", function read(err, data) {
if (err) {
console.error("[renderer.openFile] read error: " + (err && err.message ? err.message : err));
throw err;
}
console.log("[renderer.openFile] read " + (data ? data.length : 0) + " bytes for " + filePath);
if (typeof loadMSRIntoEditor === "function") {
// A manually opened file is its own editor source. Clear any global-fit
// template tab that may have been left by the previous generated job.
if (window.MSREditor) {
window.MSREditor.hasTemplateTab = false;
window.MSREditor.templateContent = "";
window.MSREditor.templatePath = "";
// A manually opened standalone file starts a new editor document set;
// stale/template ownership from the previous global fit must not leak in.
if (window.MSREditor.documents) {
window.MSREditor.documents.template = {
sourceOfTruth: "gui", locked: false, dirty: false,
lastGeneratedHash: "", lastAcceptedHash: "", stale: false
};
window.MSREditor.documents.current = {
sourceOfTruth: "gui", locked: false, dirty: false,
lastGeneratedHash: "", lastAcceptedHash: "", stale: false
};
}
window.MSREditor.templateDirty = false;
}
try {
loadMSRIntoEditor(data.toString(), filePath, true, { editorOwned: true });
console.log("[renderer.openFile] loaded into editor: " + filePath);
} catch (error) {
console.error("[renderer.openFile] loadMSRIntoEditor failed: "
+ (error && error.stack ? error.stack : error));
}
openTab(null, "Editor");
console.log("[renderer.openFile] switched to Editor tab");
}
});
});
electronIpcRenderer.on('openPreferences', function() {
openElectronPreferences();
});
electronIpcRenderer.on('openSharedConfiguration', function(sharedURL) {
// A configuration deep link (http(s)://.../muSRFlow/#c=... or a bare #c=
// fragment) restores immediately, following exactly the same decode/restore
// path as the paste dialog minus the dialog itself. A legacy web deep link
// (musrflow://.../muSRFlow?action=plot&YEAR=...&BeamLine=...&RunNumbers=...)
// carries query-string run parameters and is applied through the shared web
// parser, which may also trigger a Plot. With no URL the Share menu paste
// dialog opens.
if (sharedURL && typeof sharedURL === "string") {
if (/#(?:c|cfg)=/.test(sharedURL)) {
return restoreSharedConfigurationFromSource(sharedURL, null);
}
return handleDesktopLegacyURL(sharedURL);
}
openElectronSharedConfiguration();
});
electronIpcRenderer.on('saveSession', function() {
saveElectronSession();
});
electronIpcRenderer.on('openSessionHistory', function() {
openElectronSessionHistory();
});
// Save and Save As share the same renderer handler.
electronIpcRenderer.on('saveFile', function(filename) {
// Prefer saving the editor content directly when available.
let content = "";
if (typeof getCurrentEditorText === "function") {
content = getCurrentEditorText();
}
if (!content || content.trim() === "") {
if (typeof prepCFG === "function") prepCFG();
// Saving a GUI-generated MSR must obey the same explicit RRF requirements
// as Generate/Fit/Plot; editor-authored text bypasses GUI-only validation.
if (typeof validateRRFSettings === "function" && !validateRRFSettings("Save", All)) {
return;
}
content = createMSR();
}
// If filename is empty, prefer current editor file or a default in cwd.
if (!filename || filename === "") {
if (window.MSREditor && window.MSREditor.currentPath) {
filename = window.MSREditor.currentPath;
} else {
filename = nodePath.join(nodeProcess.cwd(), "musrfit.msr");
}
}
try {
nodeFs.writeFileSync(filename, content, 'utf-8');
if (window.MSREditor) {
window.MSREditor.currentPath = filename;
}
}
catch(e) { alert('Failed to save the file !'); }
});
// The preload bridge removes Electron's internal event object and passes only
// serializable payloads. Folder choosers update the Preferences draft; Save
// persists those values after the user accepts the dialog.
electronIpcRenderer.on("workFolderSelected", function(foldername) {
let input = document.getElementById("workPath");
if (foldername.length != 0 && input) input.value = foldername[0];
});
electronIpcRenderer.on("dataRootSelected", function(foldername) {
let input = document.getElementById("dataRoot");
if (foldername.length != 0 && input) input.value = foldername[0];
});
electronIpcRenderer.on("startupXmlSelected", function(filePath) {
let input = document.getElementById("startupXml");
if (filePath && input) input.value = filePath;
});
electronIpcRenderer.on("binFolderSelected", function(foldername) {
let input = document.getElementById("binDir");
if (foldername && input) input.value = typeof foldername === "string"
? foldername : (foldername.length != 0 ? foldername[0] : "");
});
// Load the local startup XML after the Preferences field is initialized.
loadLocalPortableRunNaming();
initializeLocalRunData();
}
function activeInstrumentName() {
let element = document.getElementById("instrName");
if (element && typeof element.value === "string") {
return element.value.trim();
}
if (typeof All !== "undefined" && All && All.instrName) {
return String(All.instrName).trim();
}
return "";
}
function shouldEstimateT0FromPromptPeak(instrumentName, msrPath) {
if (typeof getConfiguredT0FromPromptPeak === "function" && !getConfiguredT0FromPromptPeak()) {
return false;
}
let name = String(instrumentName || "").trim().toUpperCase();
if (name === "LEM" || name === "HAL" || name === "HIFI") {
return false;
}
// An expert MSR can refer to a different instrument than the GUI selection.
// musrt0 changes the entire file, so exclude it if any RUN/ADDRUN is LEM or
// HAL, including portable filenames and older HIFI campaign names.
if (msrPath) {
let content;
try {
content = nodeFs.readFileSync(msrPath, 'utf8');
} catch (error) {
return false;
}
for (let line of content.split(/\r?\n/)) {
let run = /^\s*(?:RUN|ADDRUN)\s+(\S+)\s+(\S+)/i.exec(line);
if (!run) continue;
let identity = parseMSRRunFileToken(run[1]);
if (identity.instrument === 'LEM' || identity.instrument === 'HAL'
|| run[2].toUpperCase() === 'MUE4'
|| /(?:^|[\\/])(?:lem|hal|hifi)(?:[\\/]|$)/i.test(run[1])
|| /(?:^|_)hifi_/i.test(run[1].split(/[\\/]/).pop())) {
return false;
}
}
}
return true;
}