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.
778 lines
29 KiB
JavaScript
778 lines
29 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
const { app, BrowserWindow, Menu, dialog, ipcMain, screen, shell, clipboard, net } = require('electron');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const childProcess = require('child_process');
|
|
const wslRuntime = require('./wsl-runtime');
|
|
const { RunDataDownloader } = require('./run-data-download');
|
|
const { LocalRuntime } = require('./local-runtime');
|
|
let runDataDownloader = null;
|
|
let runDataJob = null;
|
|
let localRuntime = null;
|
|
let localRuntimeJob = null;
|
|
|
|
// An SSH-forwarded X display belongs to the remote client, but pc13280 also
|
|
// exposes the user's persistent local desktop D-Bus session. Electron otherwise
|
|
// sends file choosers through that session's XDG portal, making them appear on
|
|
// the physical desktop instead of the forwarded display. Electron reads the
|
|
// portal environment before this script starts, so relaunch once without the
|
|
// mismatched session bus and let the new process use a native X11 file chooser.
|
|
const forwardedX11 = process.platform === "linux"
|
|
&& /^(?:localhost|127\.0\.0\.1):\d+(?:\.\d+)?$/.test(process.env.DISPLAY || "");
|
|
let relaunchingForForwardedX11 = false;
|
|
if (forwardedX11 && process.env.DBUS_SESSION_BUS_ADDRESS
|
|
&& process.env.MUSRFLOW_FORWARDED_X11 !== "1") {
|
|
const childEnvironment = Object.assign({}, process.env, {
|
|
MUSRFLOW_FORWARDED_X11: "1"
|
|
});
|
|
delete childEnvironment.DBUS_SESSION_BUS_ADDRESS;
|
|
|
|
// APPIMAGE points to the stable package path; process.execPath points into
|
|
// the temporary AppImage mount and would disappear when this process exits.
|
|
const executable = process.env.APPIMAGE || process.execPath;
|
|
const child = childProcess.spawn(executable, process.argv.slice(1), {
|
|
detached: true,
|
|
env: childEnvironment,
|
|
stdio: "ignore"
|
|
});
|
|
child.unref();
|
|
relaunchingForForwardedX11 = true;
|
|
}
|
|
|
|
|
|
// Parameter plots and help use the same native auxiliary-window shell. Keeping
|
|
// this in one place makes independent Electron windows behave consistently.
|
|
const parameterPlotWindows = new Set();
|
|
let quickStartWindow = null;
|
|
|
|
// The main window is tracked module-wide so deep links (a shared-configuration
|
|
// URL in the command line, a second invocation, or a macOS open-url event) can
|
|
// reach the already-created renderer.
|
|
let mainWindow = null;
|
|
let pendingSharedConfigurationURL = "";
|
|
|
|
// Packaged applications contain build-info.json, generated immediately before
|
|
// electron-builder runs. A development checkout instead reports its live Git
|
|
// revision and whether local edits make it differ from that commit.
|
|
let cachedApplicationBuildInfo = null;
|
|
function applicationBuildInfo(runtimeInfo) {
|
|
if (!cachedApplicationBuildInfo) {
|
|
let revision = "unrecorded";
|
|
let modified = false;
|
|
try {
|
|
const packaged = JSON.parse(fs.readFileSync(path.join(__dirname, "build-info.json"), "utf8"));
|
|
if (packaged && /^[0-9a-f]{40}$/i.test(packaged.revision || "")) {
|
|
revision = packaged.revision.slice(0, 12).toLowerCase();
|
|
modified = packaged.modified === true;
|
|
}
|
|
} catch (error) {
|
|
if (!app.isPackaged) {
|
|
try {
|
|
revision = childProcess.execFileSync("git", ["rev-parse", "--short=12", "HEAD"], {
|
|
cwd: __dirname, encoding: "utf8", timeout: 2000
|
|
}).trim();
|
|
modified = childProcess.execFileSync("git", ["status", "--porcelain"], {
|
|
cwd: __dirname, encoding: "utf8", timeout: 2000
|
|
}).trim() !== "";
|
|
} catch (gitError) {
|
|
revision = "development source";
|
|
}
|
|
}
|
|
}
|
|
const platformNames = { win32: "Windows", darwin: "macOS", linux: "Linux" };
|
|
cachedApplicationBuildInfo = {
|
|
version: app.getVersion(),
|
|
edition: "Electron/" + (platformNames[process.platform] || process.platform),
|
|
revision: revision,
|
|
modified: modified
|
|
};
|
|
}
|
|
return Object.assign({}, runtimeInfo || {}, cachedApplicationBuildInfo);
|
|
}
|
|
|
|
// Remember the last folder used by the Open/Save MSR dialogs, so a repeated
|
|
// open or save starts where the previous one finished instead of the process
|
|
// working directory. The remember is a tiny JSON file under userData; if it is
|
|
// missing or the directory no longer exists the dialogs fall back to ".".
|
|
function lastMSRDirectoryFile() {
|
|
return path.join(app.getPath("userData"), "last-msr-directory.json");
|
|
}
|
|
let rememberedMSRDirectory = "";
|
|
function rememberMSRDirectory(directory) {
|
|
if (!directory) {
|
|
return;
|
|
}
|
|
rememberedMSRDirectory = directory;
|
|
try {
|
|
fs.mkdirSync(app.getPath("userData"), { recursive: true });
|
|
fs.writeFileSync(lastMSRDirectoryFile(), JSON.stringify({ directory: directory }));
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
}
|
|
function msrDialogDirectory() {
|
|
return rememberedMSRDirectory || ".";
|
|
}
|
|
|
|
function createAuxiliaryWindow(options = {}) {
|
|
const auxiliaryWindow = new BrowserWindow({
|
|
title: options.title || "muSRFlow",
|
|
width: options.width || 760,
|
|
height: options.height || 600,
|
|
minWidth: options.minWidth || 480,
|
|
minHeight: options.minHeight || 360,
|
|
resizable: true,
|
|
autoHideMenuBar: true,
|
|
icon: path.join(__dirname, "assets", "musrflow-icon.png"),
|
|
webPreferences: {
|
|
preload: path.join(__dirname, "preload.js"),
|
|
contextIsolation: true,
|
|
nodeIntegration: false,
|
|
sandbox: false
|
|
}
|
|
});
|
|
|
|
// Auxiliary windows have no in-app navigation of their own. Send external
|
|
// links (the Quick Start references the online docs) to the system browser
|
|
// instead of spawning a new Electron window that would leave a dead frame.
|
|
auxiliaryWindow.webContents.setWindowOpenHandler(function (details) {
|
|
if (/^https?:\/\//i.test(details.url)) {
|
|
shell.openExternal(details.url);
|
|
}
|
|
return { action: "deny" };
|
|
});
|
|
|
|
if (options.dataChannel) {
|
|
auxiliaryWindow.webContents.once("did-finish-load", () => {
|
|
auxiliaryWindow.webContents.send(options.dataChannel, options.data || {});
|
|
});
|
|
}
|
|
auxiliaryWindow.loadFile(options.file);
|
|
return auxiliaryWindow;
|
|
}
|
|
|
|
function createParameterPlotWindow(options = {}) {
|
|
const plotWindow = createAuxiliaryWindow({
|
|
title: options.jobName ? `Parameters: ${options.jobName}` : "Parameter plot",
|
|
width: 760,
|
|
height: 600,
|
|
minWidth: 480,
|
|
minHeight: 360,
|
|
file: "parameter-plot.html",
|
|
dataChannel: "parameterPlotData",
|
|
data: options
|
|
});
|
|
|
|
parameterPlotWindows.add(plotWindow);
|
|
plotWindow.on("closed", () => parameterPlotWindows.delete(plotWindow));
|
|
}
|
|
|
|
// Create the Electron shell; fitting logic remains in the shared renderer.
|
|
// A configuration link is an http(s)://…/muSRFlow/#c=… (or #cfg=…) URL, or the
|
|
// desktop protocol form musrflow://open/#c=… that this app is registered to
|
|
// receive. A legacy web deep link carries run parameters in the query string
|
|
// instead (musrflow://…/muSRFlow?action=plot&YEAR=…&BeamLine=…&RunNumbers=…, or
|
|
// the equivalent http(s)://…/muSRFlow?… URL) and is forwarded the same way.
|
|
// Only such URLs are accepted from the command line, a second instance, or
|
|
// open-url; the HTTP target is never fetched, mirroring the web restore path.
|
|
function findSharedConfigurationURL(args) {
|
|
if (!Array.isArray(args)) return "";
|
|
for (const argument of args) {
|
|
const value = String(argument || "");
|
|
// Bare fragment (starting #c=/#cfg=) is the app's own restore form.
|
|
if (/^#(?:c|cfg)=/.test(value)) {
|
|
return value;
|
|
}
|
|
if (!/^(?:https?:\/\/|musrflow:\/\/)/i.test(value)) {
|
|
continue;
|
|
}
|
|
// Encoded configuration fragment on a full URL.
|
|
if (/#(?:c|cfg)=/.test(value)) {
|
|
return value;
|
|
}
|
|
// Legacy web deep link: query-string parameters instead of a fragment.
|
|
const queryAt = value.indexOf("?");
|
|
if (queryAt < 0) {
|
|
continue;
|
|
}
|
|
const path = value.slice(0, queryAt).replace(/\/+$/, "");
|
|
const ownProtocol = /^musrflow:\/\//i.test(value);
|
|
const muSRFlowPath = /\/muSRFlow$/i.test(path);
|
|
if (ownProtocol || muSRFlowPath) {
|
|
return value;
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function createWindow () {
|
|
const workArea = screen.getPrimaryDisplay().workAreaSize;
|
|
let defaultWidth = Math.floor(Math.min(980, workArea.width * 0.5));
|
|
let defaultHeight = Math.floor(Math.min(820, workArea.height * 0.75));
|
|
|
|
// Start with a compact desktop footprint, but do not impose maximum bounds:
|
|
// the renderer follows the window when the user resizes or maximizes it.
|
|
if (defaultWidth < 420) {
|
|
defaultWidth = Math.floor(workArea.width - 32);
|
|
}
|
|
if (defaultHeight < 420) {
|
|
defaultHeight = Math.floor(workArea.height - 32);
|
|
}
|
|
|
|
const win = new BrowserWindow({
|
|
title: "muSRFlow",
|
|
width: defaultWidth,
|
|
height: defaultHeight,
|
|
minWidth: Math.min(420, defaultWidth),
|
|
minHeight: Math.min(420, defaultHeight),
|
|
resizable: true,
|
|
icon: path.join(__dirname, "assets", "musrflow-icon.png"),
|
|
webPreferences: {
|
|
preload: path.join(__dirname, "preload.js"),
|
|
contextIsolation: true,
|
|
nodeIntegration: false,
|
|
sandbox: false
|
|
}
|
|
})
|
|
mainWindow = win;
|
|
win.on("closed", function () {
|
|
if (mainWindow === win) mainWindow = null;
|
|
});
|
|
|
|
try {
|
|
const __rememberedContent = fs.readFileSync(lastMSRDirectoryFile(), "utf8");
|
|
const __rememberedSaved = JSON.parse(__rememberedContent);
|
|
const directory = __rememberedSaved && __rememberedSaved.directory ? String(__rememberedSaved.directory) : "";
|
|
if (directory && fs.existsSync(directory) && fs.statSync(directory).isDirectory()) {
|
|
rememberedMSRDirectory = directory;
|
|
}
|
|
} catch (error) {
|
|
rememberedMSRDirectory = "";
|
|
}
|
|
|
|
|
|
const template = [
|
|
{
|
|
label: 'File',
|
|
submenu: [
|
|
{
|
|
label: 'Open MSR...',
|
|
accelerator: 'CmdOrCtrl+O',
|
|
click () {
|
|
dialog.showOpenDialog(win, {
|
|
title: "Open MSR file",
|
|
defaultPath: msrDialogDirectory(),
|
|
filters: [
|
|
{name: 'MSR files', extensions: ['msr']},
|
|
{name: 'All Files', extensions: ['*']}
|
|
],
|
|
properties: ['openFile']
|
|
}).then(result => {
|
|
if (!result.canceled && result.filePaths.length) {
|
|
rememberMSRDirectory(path.dirname(result.filePaths[0]));
|
|
console.log("[openMSR] dialog selected " + result.filePaths[0]);
|
|
win.webContents.send('openFile', result.filePaths);
|
|
} else {
|
|
console.log("[openMSR] dialog canceled or empty");
|
|
}
|
|
}).catch(err => {
|
|
console.log("[openMSR] dialog error: " + err);
|
|
});
|
|
}
|
|
},
|
|
{
|
|
label: 'Restore Configuration Link...',
|
|
accelerator: 'CmdOrCtrl+Shift+O',
|
|
click () {
|
|
// The renderer decodes the URL fragment locally; Electron never
|
|
// navigates to or fetches the web deployment.
|
|
win.webContents.send('openSharedConfiguration');
|
|
}
|
|
},
|
|
{
|
|
label: 'Save Session...',
|
|
click () {
|
|
win.webContents.send('saveSession');
|
|
}
|
|
},
|
|
{
|
|
label: 'Restore Session...',
|
|
click () {
|
|
win.webContents.send('openSessionHistory');
|
|
}
|
|
},
|
|
{
|
|
label: 'Save',
|
|
accelerator: 'CmdOrCtrl+S',
|
|
click () {
|
|
win.webContents.send('saveFile', '');
|
|
}
|
|
},
|
|
{
|
|
label: 'Save MSR As...',
|
|
accelerator: 'CmdOrCtrl+Shift+S',
|
|
click () {
|
|
dialog.showSaveDialog(win, {
|
|
title: "Save MSR file",
|
|
defaultPath: msrDialogDirectory(),
|
|
filters: [
|
|
{name: 'MSR files', extensions: ['msr']},
|
|
{name: 'All Files', extensions: ['*']}
|
|
],
|
|
properties: ['showOverwriteConfirmation']
|
|
}).then(result => {
|
|
if (!result.canceled && result.filePath) {
|
|
rememberMSRDirectory(path.dirname(result.filePath));
|
|
console.log("[saveMSR] dialog selected " + result.filePath);
|
|
win.webContents.send('saveFile', result.filePath);
|
|
} else {
|
|
console.log("[saveMSR] dialog canceled");
|
|
}
|
|
}).catch(err => {
|
|
console.log("[saveMSR] dialog error: " + err);
|
|
});
|
|
}
|
|
},
|
|
{ type: 'separator' },
|
|
{
|
|
label: 'Preferences...',
|
|
click () {
|
|
win.webContents.send('openPreferences');
|
|
}
|
|
},
|
|
{ type: 'separator' },
|
|
{
|
|
label: 'Print',
|
|
accelerator: 'CmdOrCtrl+P',
|
|
click () {
|
|
var focusedWindow = BrowserWindow.getFocusedWindow();
|
|
const options = {};
|
|
focusedWindow.webContents.print(options).catch(err => {
|
|
console.log(err);
|
|
})
|
|
}
|
|
},
|
|
{
|
|
role: 'quit'
|
|
}
|
|
]
|
|
},
|
|
{
|
|
role: 'editMenu'
|
|
},
|
|
{
|
|
role: 'viewMenu'
|
|
},
|
|
{
|
|
role: 'windowMenu'
|
|
},
|
|
{
|
|
role: 'help',
|
|
submenu: [
|
|
{
|
|
label: 'About muSRFlow',
|
|
click () {
|
|
const build = applicationBuildInfo();
|
|
dialog.showMessageBox(win, {
|
|
type: 'info',
|
|
title: 'About muSRFlow',
|
|
message: `muSRFlow ${app.getVersion()}`,
|
|
detail: build.edition + ' · build ' + build.revision
|
|
+ (build.modified ? ' (modified)' : '')
|
|
+ '\n\nDesktop and web workflow for musrfit\n\nAuthor: Zaher Salman\nCopyright (C) 2026 Zaher Salman\nGNU GPL version 3 or later',
|
|
icon: path.join(__dirname, 'assets', 'musrflow-icon.png')
|
|
});
|
|
}
|
|
}
|
|
]
|
|
}
|
|
]
|
|
const menu = Menu.buildFromTemplate(template)
|
|
Menu.setApplicationMenu(menu)
|
|
|
|
win.loadFile('index.html');
|
|
|
|
// Deep links captured before the window existed (macOS open-url during
|
|
// startup) and a startup URL from the command line are sent once the page
|
|
// is ready. The renderer decodes and restores them through the same path
|
|
// as the Restore Configuration Link menu, never by navigating the HTTP URL.
|
|
const startupURL = findSharedConfigurationURL(process.argv);
|
|
const deepLink = startupURL || pendingSharedConfigurationURL;
|
|
pendingSharedConfigurationURL = "";
|
|
if (deepLink) {
|
|
win.webContents.once('did-finish-load', function () {
|
|
win.webContents.send('openSharedConfiguration', deepLink);
|
|
});
|
|
}
|
|
}
|
|
|
|
if (relaunchingForForwardedX11) {
|
|
app.exit(0);
|
|
} else {
|
|
// One app instance owns the shared-configuration deep links. A second
|
|
// invocation that carries a configuration URL forwards it to the running
|
|
// window instead of starting a second copy.
|
|
if (!app.requestSingleInstanceLock()) {
|
|
app.quit();
|
|
} else {
|
|
app.on('second-instance', function (event, commandLine) {
|
|
const url = findSharedConfigurationURL(commandLine);
|
|
if (mainWindow) {
|
|
if (mainWindow.isMinimized()) mainWindow.restore();
|
|
mainWindow.focus();
|
|
if (url) mainWindow.webContents.send('openSharedConfiguration', url);
|
|
}
|
|
});
|
|
|
|
// macOS delivers URLs the app is registered to open through open-url, which
|
|
// may fire before the window exists.
|
|
app.on('open-url', function (event, url) {
|
|
event.preventDefault();
|
|
if (!url || !findSharedConfigurationURL([url])) {
|
|
return;
|
|
}
|
|
if (mainWindow) {
|
|
mainWindow.webContents.send('openSharedConfiguration', url);
|
|
} else {
|
|
pendingSharedConfigurationURL = url;
|
|
}
|
|
});
|
|
|
|
app.whenReady().then(function () {
|
|
// Register the desktop configuration-link protocol so a musrflow:// link
|
|
// (emitted by the web Share flow) launches this app. electron-builder adds
|
|
// the matching MimeType=x-scheme-handler/musrflow; desktop entry on Linux.
|
|
app.setAsDefaultProtocolClient("musrflow");
|
|
runDataDownloader = new RunDataDownloader({
|
|
directory: path.join(app.getPath('userData'), 'run-data'),
|
|
fetch: net.fetch.bind(net)
|
|
});
|
|
localRuntime = new LocalRuntime({ directory: path.join(app.getPath('userData'), 'runtimes') });
|
|
// The renderer only treats a configured tools directory inside this
|
|
// private tree as managed. Existing host tool selection is unchanged.
|
|
process.env.MUSRFLOW_MANAGED_RUNTIME_DIRECTORY = localRuntime.directory;
|
|
createWindow();
|
|
setupWslRuntime();
|
|
});
|
|
}
|
|
}
|
|
|
|
// Windows runs the bundled ROOT/musrfit tree inside a private WSL2
|
|
// distribution: the installer also ships the tree as a rootfs archive, and the
|
|
// first launch imports it. The check/import runs in the background so the
|
|
// window appears immediately; status is broadcast to the renderer and mirrored
|
|
// through IPC so a UI can surface progress or retry a failed import.
|
|
let wslRuntimeState = { status: process.platform === "win32" ? "pending" : "not-windows" };
|
|
let wslRuntimeSetup = null;
|
|
|
|
function broadcastWslRuntimeState(state) {
|
|
wslRuntimeState = state;
|
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
mainWindow.webContents.send("wslRuntimeStatus", state);
|
|
}
|
|
}
|
|
|
|
function setupWslRuntime() {
|
|
if (process.platform !== "win32") {
|
|
return Promise.resolve(wslRuntimeState);
|
|
}
|
|
if (wslRuntimeSetup) return wslRuntimeSetup;
|
|
broadcastWslRuntimeState({ status: "checking", distro: wslRuntime.DEFAULT_DISTRO });
|
|
wslRuntimeSetup = wslRuntime.ensureWSLRuntime({
|
|
resourcesPath: process.resourcesPath,
|
|
appDataPath: process.env.LOCALAPPDATA || app.getPath("userData"),
|
|
onProgress: function (progress) {
|
|
broadcastWslRuntimeState(Object.assign({ status: progress.phase }, progress));
|
|
}
|
|
}).then(function (result) {
|
|
broadcastWslRuntimeState(result);
|
|
if (!result.ok) {
|
|
wslRuntimeSetup = null;
|
|
console.log("[wsl-runtime] setup failed: " + result.status
|
|
+ (result.error ? " - " + result.error : ""));
|
|
} else {
|
|
console.log("[wsl-runtime] " + result.status);
|
|
}
|
|
return result;
|
|
}).catch(function (error) {
|
|
wslRuntimeSetup = null;
|
|
const result = { ok: false, status: "error", error: error.message || String(error) };
|
|
broadcastWslRuntimeState(result);
|
|
console.log("[wsl-runtime] error: " + result.error);
|
|
return result;
|
|
});
|
|
return wslRuntimeSetup;
|
|
}
|
|
|
|
ipcMain.handle("wslRuntimeStatus", function () {
|
|
return wslRuntimeState;
|
|
});
|
|
|
|
ipcMain.handle("ensureWslRuntime", function () {
|
|
return setupWslRuntime();
|
|
});
|
|
|
|
ipcMain.handle('checkLocalRuntime', async function(event, input) {
|
|
if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
|
|
return localRuntime.checkTools(input || {});
|
|
});
|
|
|
|
ipcMain.handle('installLocalRuntime', async function(event, token) {
|
|
if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
|
|
if (process.platform !== 'linux') return { ok: false, message: 'Offline runtime installation currently supports Linux only.' };
|
|
if (localRuntimeJob) return { ok: false, message: 'A runtime installation is already running.' };
|
|
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/.test(token)) {
|
|
return { ok: false, message: 'Invalid runtime installation request.' };
|
|
}
|
|
const controller = new AbortController();
|
|
localRuntimeJob = { token: token, controller: controller };
|
|
try {
|
|
const selection = await dialog.showOpenDialog(mainWindow, {
|
|
title: 'Select runtime-download.json', properties: ['openFile'],
|
|
filters: [{ name: 'Runtime download descriptor', extensions: ['json'] }]
|
|
});
|
|
if (selection.canceled || !selection.filePaths.length) return { ok: false, cancelled: true };
|
|
controller.signal.throwIfAborted();
|
|
const plan = await localRuntime.inspectBundle(selection.filePaths[0]);
|
|
controller.signal.throwIfAborted();
|
|
const confirmation = await dialog.showMessageBox(mainWindow, {
|
|
type: 'question', title: 'Install muSRFlow runtime',
|
|
message: 'Install this runtime and use it for future fits and plots?',
|
|
detail: 'Install only bundles from a trusted source: they contain executable programs.\n\n'
|
|
+ 'ROOT ' + plan.descriptor.runtime.root.version + ' / musrfit ' + plan.descriptor.runtime.musrfit.version
|
|
+ '\nArchive: ' + (plan.descriptor.artifact.size / 1000000).toFixed(1) + ' MB'
|
|
+ '\nSource: ' + selection.filePaths[0] + '\nInstall to: ' + plan.destination
|
|
+ '\n\nSystem installations and your startup XML files will not be changed.',
|
|
buttons: ['Install and use', 'Cancel'], defaultId: 1, cancelId: 1
|
|
});
|
|
if (confirmation.response !== 0) return { ok: false, cancelled: true };
|
|
return await localRuntime.install(plan, controller.signal, function(state) {
|
|
if (!event.sender.isDestroyed()) {
|
|
event.sender.send('localRuntimeProgress', Object.assign({ token: token }, state));
|
|
}
|
|
});
|
|
} catch (error) {
|
|
return { ok: false, cancelled: controller.signal.aborted, message: error.message || String(error) };
|
|
} finally {
|
|
localRuntimeJob = null;
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('cancelLocalRuntime', function(event, token) {
|
|
if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error('Invalid runtime window.');
|
|
if (!localRuntimeJob || localRuntimeJob.token !== token) return false;
|
|
localRuntimeJob.controller.abort();
|
|
return true;
|
|
});
|
|
|
|
ipcMain.handle('runDataConfiguration', async function(event) {
|
|
if (event.sender !== mainWindow.webContents) throw new Error('Invalid download window.');
|
|
return { directory: runDataDownloader.directory, files: await runDataDownloader.localFiles() };
|
|
});
|
|
|
|
ipcMain.handle('acquireRunData', async function(event, input) {
|
|
if (event.sender !== mainWindow.webContents) throw new Error('Invalid download window.');
|
|
if (runDataJob) return { ok: false, message: 'A data download is already running.' };
|
|
if (!input || !/^[A-Za-z0-9_-]{1,80}$/.test(input.token)) {
|
|
return { ok: false, message: 'Invalid download request.' };
|
|
}
|
|
const controller = new AbortController();
|
|
runDataJob = { token: input.token, controller: controller };
|
|
try {
|
|
const progress = function(state) {
|
|
if (!event.sender.isDestroyed()) {
|
|
event.sender.send('runDataProgress', Object.assign({ token: input.token }, state));
|
|
}
|
|
};
|
|
const plan = await runDataDownloader.prepare(input.requests, input.dataRoot, controller.signal, progress);
|
|
if (plan.downloads.length) {
|
|
const roots = Array.from(new Set(plan.downloads.map(function(file) { return file.storageRoot; })));
|
|
let detail = plan.downloads.slice(0, 12).map(function(file) {
|
|
return file.instrument + ' ' + file.year + ' / run ' + file.run;
|
|
}).join('\n');
|
|
if (plan.downloads.length > 12) detail += '\n...';
|
|
detail += '\n\nTotal: ' + (plan.totalBytes / 1000000).toFixed(1) + ' MB';
|
|
detail += '\nSave to:\n' + roots.join('\n');
|
|
if (roots.some(function(root) { return root !== path.resolve(input.dataRoot); })) {
|
|
detail += '\n\nThe Data directory is not writable. Downloads will use your personal muSRFlow data folder.';
|
|
}
|
|
if (plan.missing.length) {
|
|
detail += '\n\n' + plan.missing.length + ' other run file(s) are unavailable on the server.';
|
|
}
|
|
controller.signal.throwIfAborted();
|
|
const choice = await dialog.showMessageBox(mainWindow, {
|
|
type: 'question', title: 'Download run data',
|
|
message: 'Download ' + plan.downloads.length + ' missing run file(s) from musruser.psi.ch?',
|
|
detail: detail, buttons: ['Download and continue', 'Cancel'], defaultId: 0, cancelId: 1
|
|
});
|
|
if (choice.response !== 0) return { ok: false, cancelled: true, files: plan.files };
|
|
}
|
|
return await runDataDownloader.download(plan, controller.signal, progress);
|
|
} catch (error) {
|
|
return { ok: false, cancelled: controller.signal.aborted,
|
|
message: error.message, files: await runDataDownloader.localFiles() };
|
|
} finally {
|
|
runDataJob = null;
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('cancelRunData', function(event, token) {
|
|
if (event.sender !== mainWindow.webContents) throw new Error('Invalid download window.');
|
|
if (!runDataJob || runDataJob.token !== token) return false;
|
|
runDataJob.controller.abort();
|
|
return true;
|
|
});
|
|
|
|
app.on('window-all-closed', () => {
|
|
if (process.platform !== 'darwin') {
|
|
app.quit()
|
|
}
|
|
})
|
|
|
|
app.on('activate', () => {
|
|
if (BrowserWindow.getAllWindows().length === 0) {
|
|
createWindow()
|
|
}
|
|
})
|
|
|
|
// Let Preferences choose machine-local working and data directories.
|
|
ipcMain.on("selectWorkFolder", (event, currentPath) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
dialog.showOpenDialog(owner, {
|
|
title: "Select working directory",
|
|
defaultPath: currentPath || ".",
|
|
properties: ["openDirectory"]
|
|
}).then(result => {
|
|
if (!result.canceled) {
|
|
event.reply("workFolderSelected", result.filePaths);
|
|
}
|
|
}).catch(err => {
|
|
console.log(err);
|
|
});
|
|
});
|
|
|
|
ipcMain.on("selectDataRootFolder", (event, currentRoot) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
dialog.showOpenDialog(owner, {
|
|
title: "Select muSR data root",
|
|
defaultPath: currentRoot || "/psi.ch/group/lmu/public/data",
|
|
properties: ["openDirectory"]
|
|
}).then(result => {
|
|
if (!result.canceled) {
|
|
event.reply("dataRootSelected", result.filePaths);
|
|
}
|
|
}).catch(err => {
|
|
console.log(err);
|
|
});
|
|
});
|
|
|
|
ipcMain.on("selectStartupXmlFile", (event, currentPath) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
dialog.showOpenDialog(owner, {
|
|
title: "Select musrfit_startup.xml",
|
|
defaultPath: currentPath || "",
|
|
filters: [
|
|
{ name: "musrfit startup XML", extensions: ["xml"] },
|
|
{ name: "All Files", extensions: ["*"] }
|
|
],
|
|
properties: ["openFile"]
|
|
}).then(result => {
|
|
if (!result.canceled && result.filePaths.length) {
|
|
event.reply("startupXmlSelected", result.filePaths[0]);
|
|
}
|
|
}).catch(err => {
|
|
console.log(err);
|
|
});
|
|
});
|
|
|
|
ipcMain.on("selectBinFolder", (event, currentPath) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
dialog.showOpenDialog(owner, {
|
|
title: "Select musrfit binaries directory",
|
|
defaultPath: currentPath || "/usr/local/bin",
|
|
properties: ["openDirectory"]
|
|
}).then(result => {
|
|
if (!result.canceled) {
|
|
event.reply("binFolderSelected", result.filePaths);
|
|
}
|
|
}).catch(err => {
|
|
console.log(err);
|
|
});
|
|
});
|
|
|
|
// Open every parameter plot in its own native window. No parent is assigned,
|
|
// so closing or minimizing the main application does not manage the plot as an
|
|
// in-page child dialog.
|
|
ipcMain.on("openParameterPlotWindow", (event, options) => {
|
|
createParameterPlotWindow(options || {});
|
|
});
|
|
|
|
// Help is modeless and independent in Electron, using the same native window
|
|
// shell as parameter plots. Reopening Help focuses the existing window.
|
|
ipcMain.on("openQuickStartWindow", (event, options) => {
|
|
const sectionId = options && options.sectionId ? options.sectionId : "helpRuns";
|
|
const buildInfo = applicationBuildInfo(options && options.buildInfo);
|
|
if (quickStartWindow && !quickStartWindow.isDestroyed()) {
|
|
quickStartWindow.show();
|
|
quickStartWindow.focus();
|
|
quickStartWindow.webContents.send("quickStartSection", { sectionId: sectionId, buildInfo: buildInfo });
|
|
return;
|
|
}
|
|
|
|
quickStartWindow = createAuxiliaryWindow({
|
|
title: "muSRFlow Quick Start",
|
|
width: 720,
|
|
height: 680,
|
|
minWidth: 480,
|
|
minHeight: 360,
|
|
file: "quick-start.html",
|
|
dataChannel: "quickStartSection",
|
|
data: { sectionId: sectionId, buildInfo: buildInfo }
|
|
});
|
|
quickStartWindow.on("closed", () => {
|
|
quickStartWindow = null;
|
|
});
|
|
});
|
|
|
|
// Parameter plot windows can load additional msr2data tables into individual
|
|
// panels. Keep file-system access in the Electron main process.
|
|
ipcMain.handle("selectParameterDataFile", async (event, currentPath) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
const result = await dialog.showOpenDialog(owner, {
|
|
title: "Select parameter-data file",
|
|
defaultPath: currentPath || ".",
|
|
filters: [
|
|
{ name: "Parameter data", extensions: ["dat", "txt"] },
|
|
{ name: "All Files", extensions: ["*"] }
|
|
],
|
|
properties: ["openFile"]
|
|
});
|
|
return result.canceled || !result.filePaths.length ? "" : result.filePaths[0];
|
|
});
|
|
|
|
// Parameter plot windows can also overlay several additional msr2data tables
|
|
// into a panel; the multi-selection flavor stays in the main process too.
|
|
ipcMain.handle("selectParameterDataFiles", async (event, currentPath) => {
|
|
const owner = BrowserWindow.fromWebContents(event.sender);
|
|
const result = await dialog.showOpenDialog(owner, {
|
|
title: "Select parameter-data files to overlay",
|
|
defaultPath: currentPath || ".",
|
|
filters: [
|
|
{ name: "Parameter data", extensions: ["dat", "txt"] },
|
|
{ name: "All Files", extensions: ["*"] }
|
|
],
|
|
properties: ["openFile", "multiSelections"]
|
|
});
|
|
return result.canceled ? [] : (result.filePaths || []);
|
|
});
|
|
|
|
// The configuration-link share button writes to the system clipboard. The
|
|
// renderer cannot (no require, no clipboard module in the preload), so the
|
|
// main process performs the write on its behalf.
|
|
ipcMain.handle("write-clipboard", async (event, text) => {
|
|
clipboard.writeText(String(text == null ? "" : text));
|
|
return true;
|
|
});
|