Files
muSRFlow/main.js
salman 184c5b9eb1 Add musrflow:// configuration links and musrfit thread preference
Register the musrflow:// URL scheme at startup (electron-builder writes the
matching MimeType=x-scheme-handler desktop entry for the packaged Linux
builds), accept musrflow://open/#c= links on the launch path and macOS
open-url alongside the existing http(s)/bare-fragment forms, and add a web
Share button that emits the identical encoded fragment under musrflow://open/
so a browser can hand a configuration to the installed desktop app.

Add a musrfit threads field to the Electron Preferences dialog. A set count
is passed to local fits as `musrfit -u <n>`; blank keeps the previous
all-cores behaviour and the web edition ignores it.

Document both features (preferences, runs/fitting, configuration sharing,
desktop deployment, CHANGELOG) and rebuild the Sphinx HTML and PDF.
2026-10-10 10:40:41 +02:00

535 lines
18 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
const { app, BrowserWindow, Menu, dialog, ipcMain, screen, shell, clipboard } = require('electron');
const path = require('path');
const fs = require('fs');
const childProcess = require('child_process');
// 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 = "";
// 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. 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, and musrflow:// links only carry the fragment (no content).
function findSharedConfigurationURL(args) {
if (!Array.isArray(args)) return "";
for (const argument of args) {
const value = String(argument || "");
if (/^(?:https?:\/\/|musrflow:\/\/)/i.test(value) && /#(?:c|cfg)=/.test(value)) {
return value;
}
if (/^#(?:c|cfg)=/.test(value)) {
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 () {
dialog.showMessageBox(win, {
type: 'info',
title: 'About muSRFlow',
message: `muSRFlow ${app.getVersion()}`,
detail: 'Desktop 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 || !/^(?:https?:\/\/|musrflow:\/\/)/i.test(url) || !/#(?:c|cfg)=/.test(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");
createWindow();
});
}
}
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";
if (quickStartWindow && !quickStartWindow.isDestroyed()) {
quickStartWindow.show();
quickStartWindow.focus();
quickStartWindow.webContents.send("quickStartSection", { sectionId: sectionId });
return;
}
quickStartWindow = createAuxiliaryWindow({
title: "muSRFlow Quick Start",
width: 720,
height: 680,
minWidth: 480,
minHeight: 360,
file: "quick-start.html",
dataChannel: "quickStartSection",
data: { sectionId: sectionId, version: app.getVersion() }
});
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;
});