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.
1142 lines
50 KiB
JavaScript
1142 lines
50 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
const assert = require("assert");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const vm = require("vm");
|
|
|
|
const repoRoot = path.resolve(__dirname, "..");
|
|
const commonCode = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8");
|
|
const electronCode = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8");
|
|
const plotCode = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
|
|
|
|
function loadSharedConfigurationHelpers() {
|
|
const ipcListeners = {};
|
|
let clipboardText = "";
|
|
const electron = {
|
|
clipboard: {
|
|
readText: function() { return clipboardText; },
|
|
writeText: function(value) { clipboardText = value; }
|
|
},
|
|
ipcRenderer: {
|
|
on: function(channel, handler) { ipcListeners[channel] = handler; },
|
|
send: function() {}
|
|
}
|
|
};
|
|
const elements = {};
|
|
const sandbox = {
|
|
URL: URL,
|
|
console: { log: function() {} },
|
|
confirm: function() { return true; },
|
|
process: process,
|
|
setTimeout: function(callback) { callback(); },
|
|
window: { MSREditor: {} },
|
|
document: {
|
|
getElementById: function(id) { return elements[id] || null; },
|
|
querySelectorAll: function() { return []; },
|
|
createElement: function() { return {}; }
|
|
},
|
|
require: function(name) {
|
|
if (name === "electron") return electron;
|
|
return require(name);
|
|
}
|
|
};
|
|
sandbox.global = sandbox;
|
|
sandbox.window.window = sandbox.window;
|
|
vm.runInNewContext(commonCode, sandbox, { filename: "muSRFitlib.js" });
|
|
vm.runInNewContext(electronCode, sandbox, { filename: "muSRFitelec.js" });
|
|
return {
|
|
electron: electron,
|
|
elements: elements,
|
|
ipcListeners: ipcListeners,
|
|
sandbox: sandbox,
|
|
setClipboardText: function(value) { clipboardText = value; }
|
|
};
|
|
}
|
|
|
|
function loadSharedConfigurationWithPlotHelpers() {
|
|
const ipcListeners = {};
|
|
let clipboardText = "";
|
|
const electron = {
|
|
clipboard: {
|
|
readText: function() { return clipboardText; },
|
|
writeText: function(value) { clipboardText = value; }
|
|
},
|
|
ipcRenderer: {
|
|
on: function(channel, handler) { ipcListeners[channel] = handler; },
|
|
send: function() {}
|
|
}
|
|
};
|
|
const elements = {};
|
|
let storageMap = {};
|
|
const localStorage = {
|
|
getItem: function(key) { return storageMap[key] || null; },
|
|
setItem: function(key, value) { storageMap[key] = String(value); }
|
|
};
|
|
const sandbox = {
|
|
URL: URL,
|
|
console: { log: function() {} },
|
|
confirm: function() { return true; },
|
|
process: process,
|
|
setTimeout: function(callback) { callback(); },
|
|
globalThis: {},
|
|
window: { MSREditor: {}, localStorage: localStorage },
|
|
document: {
|
|
getElementById: function(id) { return elements[id] || null; },
|
|
querySelectorAll: function() { return []; },
|
|
getElementsByTagName: function() { return []; },
|
|
createElement: function() { return {}; }
|
|
},
|
|
require: function(name) {
|
|
if (name === "electron") return electron;
|
|
return require(name);
|
|
}
|
|
};
|
|
sandbox.globalThis.globalThis = sandbox.globalThis;
|
|
sandbox.window.window = sandbox.window;
|
|
vm.runInNewContext(plotCode, sandbox, { filename: "muSRFitParameterPlot.js" });
|
|
vm.runInNewContext(commonCode, sandbox, { filename: "muSRFitlib.js" });
|
|
vm.runInNewContext(electronCode, sandbox, { filename: "muSRFitelec.js" });
|
|
return {
|
|
electron: electron,
|
|
elements: elements,
|
|
ipcListeners: ipcListeners,
|
|
sandbox: sandbox,
|
|
setClipboardText: function(value) { clipboardText = value; }
|
|
};
|
|
}
|
|
|
|
async function testElectronCodecReadsWebCompatibleLinks() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const config = {
|
|
v: 1,
|
|
controls: { instrName: "LEM", runNumbers: "514-516" },
|
|
components: ["ExponentialCos"],
|
|
parameters: { valFrq_514: "1.2" },
|
|
functionMaps: {
|
|
1: { target: "Phi", parameters: ["RelPh_L", "RelPh_R"] }
|
|
}
|
|
};
|
|
const encoded = await lib.encodeElectronSharedConfiguration(config);
|
|
const fullURL = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload;
|
|
const decoded = await lib.decodeElectronSharedConfiguration(fullURL);
|
|
|
|
assert.strictEqual(decoded.error, "");
|
|
assert.strictEqual(decoded.consumed, true);
|
|
assert.strictEqual(JSON.stringify(decoded.config), JSON.stringify(config));
|
|
|
|
const legacyURL = "https://example.invalid/#cfg="
|
|
+ encodeURIComponent(JSON.stringify(config));
|
|
const legacy = await lib.decodeElectronSharedConfiguration(legacyURL);
|
|
assert.strictEqual(JSON.stringify(legacy.config), JSON.stringify(config));
|
|
|
|
const missing = await lib.decodeElectronSharedConfiguration("https://example.invalid/no-state");
|
|
assert.match(missing.error, /does not contain/);
|
|
const corrupt = await lib.decodeElectronSharedConfiguration("#c=not-gzip");
|
|
assert.match(corrupt.error, /Could not read/);
|
|
|
|
// The desktop protocol link wraps the identical fragment, so decoding a
|
|
// musrflow:// link (delivered when the registered scheme launches the app)
|
|
// is unchanged from the web form; only the base URL differs.
|
|
assert.strictEqual(lib.MUSRFLOW_DESKTOP_LINK_PREFIX, "musrflow://open/");
|
|
const defaultDesktopURL = lib.desktopConfigurationLink(encoded);
|
|
assert.strictEqual(defaultDesktopURL,
|
|
"musrflow://open/" + encoded.prefix + encoded.payload);
|
|
const desktopDecoded = await lib.decodeElectronSharedConfiguration(defaultDesktopURL);
|
|
assert.strictEqual(desktopDecoded.error, "");
|
|
assert.strictEqual(JSON.stringify(desktopDecoded.config), JSON.stringify(config));
|
|
const authorityDesktopURL = "musrflow://open/restore" + encoded.prefix + encoded.payload;
|
|
const authorityDecoded = await lib.decodeElectronSharedConfiguration(authorityDesktopURL);
|
|
assert.strictEqual(authorityDecoded.error, "");
|
|
assert.strictEqual(authorityDecoded.consumed, true);
|
|
|
|
const incompleteConfig = {
|
|
v: 1,
|
|
controls: {},
|
|
constraints: ["Phi = Ph + map1"]
|
|
};
|
|
const incomplete = await lib.encodeElectronSharedConfiguration(incompleteConfig);
|
|
const incompleteResult = await lib.decodeElectronSharedConfiguration(
|
|
incomplete.prefix + incomplete.payload
|
|
);
|
|
assert.match(incompleteResult.error, /missing the detector definition for map1/);
|
|
|
|
// Share links written by earlier builds carry parameterPlot:null when no
|
|
// parameter plot was open. The decode must treat that as "no plot" instead
|
|
// of rejecting the whole link.
|
|
const legacyNullPlot = {
|
|
v: 1,
|
|
controls: { runNumbers: "514" },
|
|
component: "",
|
|
parameterPlot: null
|
|
};
|
|
const nullPlot = await lib.encodeElectronSharedConfiguration(legacyNullPlot);
|
|
const nullPlotResult = await lib.decodeElectronSharedConfiguration(
|
|
nullPlot.prefix + nullPlot.payload
|
|
);
|
|
assert.strictEqual(nullPlotResult.error, "");
|
|
assert.strictEqual(nullPlotResult.consumed, true);
|
|
assert.strictEqual(nullPlotResult.config.parameterPlot, null);
|
|
|
|
// New links omit the stanza entirely when there is no plot.
|
|
const noPlot = await lib.encodeElectronSharedConfiguration({ v: 1, controls: {} });
|
|
assert.strictEqual(noPlot.prefix, "#c=");
|
|
assert.ok(!noPlot.payload.includes("parameterPlot"));
|
|
}
|
|
|
|
function testSharedConfigurationIncludesDetectorMaps() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
env.elements.Runs = { querySelectorAll: function() { return []; } };
|
|
env.elements.Params = { querySelectorAll: function() { return []; } };
|
|
lib.prepCFG = function() {};
|
|
lib.getFitComponentValues = function() { return ["GaussianCos"]; };
|
|
lib.All.msrFunctionMaps = {
|
|
1: {
|
|
target: "Phi",
|
|
parameters: ["RelPh_L", "RelPh_T", "RelPh_R", "RelPh_B"]
|
|
}
|
|
};
|
|
|
|
const shared = lib.buildSharedConfiguration();
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(shared.functionMaps)), {
|
|
1: {
|
|
target: "Phi",
|
|
parameters: ["RelPh_L", "RelPh_T", "RelPh_R", "RelPh_B"]
|
|
}
|
|
});
|
|
|
|
shared.functionMaps[1].parameters[0] = "changed";
|
|
assert.strictEqual(lib.All.msrFunctionMaps[1].parameters[0], "RelPh_L");
|
|
}
|
|
|
|
function testElectronMenuAndRendererAreConnected() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
|
|
const html = fs.readFileSync(path.join(repoRoot, "index.html"), "utf8");
|
|
|
|
assert.match(main, /label: 'Restore Configuration Link\.\.\.'/);
|
|
assert.match(main, /webContents\.send\('openSharedConfiguration'\)/);
|
|
assert.match(html, /id="sharedConfigurationDialog"/);
|
|
assert.match(html, /restoreElectronSharedConfiguration\(\)/);
|
|
|
|
// The Electron main process accepts a configuration URL from the command
|
|
// line, a second invocation, or a macOS open-url event, and delivers it to
|
|
// the renderer through the same restore channel as the menu item. The app
|
|
// never fetches the web deployment for these links.
|
|
assert.match(main, /requestSingleInstanceLock\(\)/);
|
|
assert.match(main, /'second-instance'/);
|
|
assert.match(main, /'open-url'/);
|
|
assert.match(main, /findSharedConfigurationURL\(/);
|
|
assert.match(main, /send\('openSharedConfiguration', deepLink\)/);
|
|
|
|
// The desktop app registers the musrflow:// protocol and treats its links
|
|
// like the command-line/open-url forms. electron-builder carries the scheme
|
|
// so packaged Linux builds get the MimeType=x-scheme-handler/musrflow;
|
|
// desktop entry that lets browsers and the OS hand links to the app.
|
|
assert.match(main, /setAsDefaultProtocolClient\("musrflow"\)/);
|
|
assert.match(main, /\^\(\?:https\?:\\\/\\\/\|musrflow:\\\/\\\/\)/);
|
|
const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
|
|
const packagedSchemes = [];
|
|
for (const entry of pkg.build.protocols || []) {
|
|
for (const scheme of entry.schemes || []) packagedSchemes.push(scheme);
|
|
}
|
|
assert.ok(packagedSchemes.includes("musrflow"));
|
|
|
|
env.sandbox.firstLoad();
|
|
assert.strictEqual(typeof env.ipcListeners.openSharedConfiguration, "function");
|
|
}
|
|
|
|
function testTransientWarningIsPositionedAndTimed() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const classes = new Set();
|
|
const warningElement = {
|
|
classList: {
|
|
add: function(name) { classes.add(name); },
|
|
remove: function(name) { classes.delete(name); }
|
|
},
|
|
offsetHeight: 34,
|
|
offsetWidth: 180,
|
|
style: {}
|
|
};
|
|
env.elements.transientWarning = null;
|
|
lib.document.createElement = function() { return warningElement; };
|
|
lib.document.body = {
|
|
appendChild: function(element) { env.elements.transientWarning = element; }
|
|
};
|
|
lib.window.innerWidth = 600;
|
|
lib.window.innerHeight = 400;
|
|
let timeoutDuration = 0;
|
|
lib.setTimeout = function(callback, duration) {
|
|
timeoutDuration = duration;
|
|
return 1;
|
|
};
|
|
const target = {
|
|
getBoundingClientRect: function() {
|
|
return { left: 500, right: 530, top: 20, bottom: 50 };
|
|
}
|
|
};
|
|
|
|
lib.showTransientWarning("Configuration link copied.", target, 3500);
|
|
|
|
assert.strictEqual(warningElement.textContent, "Configuration link copied.");
|
|
assert.strictEqual(warningElement.style.left, "408px");
|
|
assert.strictEqual(warningElement.style.top, "58px");
|
|
assert.strictEqual(classes.has("visible"), true);
|
|
assert.strictEqual(timeoutDuration, 3500);
|
|
}
|
|
|
|
async function testElectronShareProvidesVisibleConfirmation() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
env.elements.Runs = { querySelectorAll: function() { return []; } };
|
|
env.elements.Params = { querySelectorAll: function() { return []; } };
|
|
lib.prepCFG = function() {};
|
|
lib.getFitComponentValues = function() { return ["Exponential"]; };
|
|
env.elements.shareConfigButton = { id: "shareConfigButton" };
|
|
let warning = null;
|
|
let status = "";
|
|
lib.showTransientWarning = function(message, target, duration) {
|
|
warning = { message: message, target: target, duration: duration };
|
|
};
|
|
lib.setFitStatus = function(message) { status = message; };
|
|
|
|
const copied = await lib.copyWebConfigurationLink();
|
|
|
|
assert.strictEqual(copied, true);
|
|
assert.strictEqual(warning.message, "Configuration link copied.");
|
|
assert.strictEqual(warning.target, env.elements.shareConfigButton);
|
|
assert.strictEqual(warning.duration, 3500);
|
|
assert.match(
|
|
env.electron.clipboard.readText(),
|
|
/^http:\/\/musruser\.psi\.ch\/muSRFlow\/#c=/
|
|
);
|
|
assert.strictEqual(status, "Configuration link copied.");
|
|
}
|
|
|
|
async function testSharedRestoreCannotChangeLocalPreferences() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const runsRoot = {
|
|
contains: function(element) { return element === env.elements.runNumbers; }
|
|
};
|
|
const paramsRoot = {
|
|
innerHTML: "existing",
|
|
contains: function(element) { return element === env.elements.valLam_514; }
|
|
};
|
|
env.elements.Runs = runsRoot;
|
|
env.elements.runNumbers = { value: "1" };
|
|
env.elements.workPath = { value: "/local/work" };
|
|
env.elements.dataRoot = { value: "/local/data" };
|
|
env.elements.Params = paramsRoot;
|
|
env.elements.valLam_514 = { value: "0.1" };
|
|
env.elements.funBlock = { innerHTML: "" };
|
|
env.elements.t0Bg = { innerHTML: "" };
|
|
env.elements.funSel = { value: "", appendChild: function() {} };
|
|
env.elements.funLine = { value: "" };
|
|
env.elements.fnPhi = { disabled: false };
|
|
|
|
lib.adjustComps = function() {};
|
|
lib.updateTheoryBlock = function() {};
|
|
lib.clearStoredT0BgValues = function() {};
|
|
lib.cfgParams = async function() {};
|
|
lib.prepCFG = function() {};
|
|
let restoredConstraint = "";
|
|
lib.addFunLine = function() {
|
|
assert.strictEqual(lib.All.msrFunctionMaps[1].target, "Phi");
|
|
restoredConstraint = env.elements.funSel.value + " = " + env.elements.funLine.value;
|
|
};
|
|
|
|
await lib.restoreSharedConfiguration({
|
|
v: 1,
|
|
controls: {
|
|
runNumbers: "514-516",
|
|
workPath: "/remote/work",
|
|
dataRoot: "/remote/data"
|
|
},
|
|
parameters: { valLam_514: "0.25", dataRoot: "/remote/data" },
|
|
customParameters: [],
|
|
constraints: ["Phi = Ph + map1"],
|
|
functionMaps: {
|
|
1: { target: "Phi", parameters: ["RelPh_L", "RelPh_R"] }
|
|
}
|
|
});
|
|
|
|
assert.strictEqual(env.elements.runNumbers.value, "514-516");
|
|
assert.strictEqual(env.elements.workPath.value, "/local/work");
|
|
assert.strictEqual(env.elements.dataRoot.value, "/local/data");
|
|
assert.strictEqual(env.elements.valLam_514.value, "0.25");
|
|
assert.strictEqual(restoredConstraint, "Phi = Ph + map1");
|
|
}
|
|
|
|
async function testElectronDialogRestoresStateAndMarksEditorStale() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const config = { v: 1, controls: { runNumbers: "514" } };
|
|
const encoded = await lib.encodeElectronSharedConfiguration(config);
|
|
const link = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload;
|
|
const dialog = {
|
|
open: false,
|
|
showModal: function() { this.open = true; },
|
|
close: function() { this.open = false; }
|
|
};
|
|
const input = {
|
|
value: "",
|
|
focus: function() { this.focused = true; },
|
|
select: function() { this.selected = true; }
|
|
};
|
|
const errorText = { textContent: "", hidden: true };
|
|
const runsRoot = {
|
|
contains: function(element) { return element === env.elements.runNumbers; }
|
|
};
|
|
env.elements.sharedConfigurationDialog = dialog;
|
|
env.elements.sharedConfigurationURL = input;
|
|
env.elements.sharedConfigurationError = errorText;
|
|
env.elements.Runs = runsRoot;
|
|
env.elements.runNumbers = { value: "1" };
|
|
env.setClipboardText(link);
|
|
|
|
lib.openElectronSharedConfiguration();
|
|
assert.strictEqual(input.value, link);
|
|
assert.strictEqual(dialog.open, true);
|
|
assert.strictEqual(input.focused, true);
|
|
|
|
// The real restore runs against this minimal DOM mock. It rebuilds the GUI
|
|
// controls and, at the end, marks the existing editor documents stale so
|
|
// they cannot silently override the imported configuration.
|
|
lib.adjustComps = function() {};
|
|
lib.updateTheoryBlock = function() {};
|
|
lib.clearStoredT0BgValues = function() {};
|
|
lib.cfgParams = async function() {};
|
|
lib.prepCFG = function() {};
|
|
lib.getCurrentEditorText = function() { return "old MSR text"; };
|
|
lib.updateMSREditorSourceTabs = function() {};
|
|
lib.openTab = function(event, name) { assert.strictEqual(name, "Runs"); };
|
|
lib.setFitStatus = function(message, options) { status = { message, options }; };
|
|
let status = null;
|
|
lib.window.MSREditor.currentPath = "/tmp/old.msr";
|
|
|
|
const result = await lib.restoreElectronSharedConfiguration();
|
|
assert.strictEqual(result, true);
|
|
assert.strictEqual(env.elements.runNumbers.value, "514");
|
|
assert.strictEqual(dialog.open, false);
|
|
assert.strictEqual(lib.getMSRDocumentState("current").sourceOfTruth, "gui");
|
|
assert.strictEqual(lib.getMSRDocumentState("current").stale, true);
|
|
assert.strictEqual(lib.window.MSREditor.currentPath, "");
|
|
assert.strictEqual(lib.window.MSREditor.templatePath, "");
|
|
assert.strictEqual(status.message, "Shared configuration restored.");
|
|
}
|
|
|
|
async function testUserCanCancelOverwritingEditorOwnership() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const config = { v: 1, controls: {} };
|
|
const encoded = await lib.encodeElectronSharedConfiguration(config);
|
|
env.elements.sharedConfigurationURL = { value: encoded.prefix + encoded.payload };
|
|
env.elements.sharedConfigurationError = { textContent: "", hidden: true };
|
|
lib.getMSRDocumentState("current").dirty = true;
|
|
lib.confirm = function() { return false; };
|
|
lib.restoreSharedConfiguration = async function() {
|
|
throw new Error("restore must not run after cancellation");
|
|
};
|
|
|
|
const result = await lib.restoreElectronSharedConfiguration();
|
|
assert.strictEqual(result, false);
|
|
assert.strictEqual(lib.getMSRDocumentState("current").dirty, true);
|
|
}
|
|
|
|
async function testElectronSharedURLRestoresThroughListener() {
|
|
// A configuration link delivered by the main process (command line, a
|
|
// second instance, or macOS open-url) must restore through the same
|
|
// decode/restore path as the menu dialog, without opening the dialog.
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
const config = { v: 1, controls: { runNumbers: "514" } };
|
|
const encoded = await lib.encodeElectronSharedConfiguration(config);
|
|
const link = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload;
|
|
const dialog = {
|
|
open: false,
|
|
showModal: function() { this.open = true; },
|
|
close: function() { this.open = false; }
|
|
};
|
|
const runsRoot = {
|
|
contains: function(element) { return element === env.elements.runNumbers; }
|
|
};
|
|
env.elements.sharedConfigurationDialog = dialog;
|
|
env.elements.Runs = runsRoot;
|
|
env.elements.runNumbers = { value: "1" };
|
|
|
|
lib.adjustComps = function() {};
|
|
lib.updateTheoryBlock = function() {};
|
|
lib.clearStoredT0BgValues = function() {};
|
|
lib.cfgParams = async function() {};
|
|
lib.prepCFG = function() {};
|
|
lib.getCurrentEditorText = function() { return "old MSR text"; };
|
|
lib.updateMSREditorSourceTabs = function() {};
|
|
lib.openTab = function(event, name) { assert.strictEqual(name, "Runs"); };
|
|
let status = null;
|
|
lib.setFitStatus = function(message, options) { status = { message, options }; };
|
|
lib.window.MSREditor.currentPath = "/tmp/old.msr";
|
|
|
|
lib.firstLoad();
|
|
const result = await env.ipcListeners.openSharedConfiguration(link);
|
|
assert.strictEqual(result, true);
|
|
assert.strictEqual(env.elements.runNumbers.value, "514");
|
|
assert.strictEqual(dialog.open, false);
|
|
assert.strictEqual(status.message, "Shared configuration restored.");
|
|
|
|
// The same listener still opens the paste dialog when no URL is provided.
|
|
const menuEnv = loadSharedConfigurationHelpers();
|
|
const menuLib = menuEnv.sandbox;
|
|
const menuDialog = {
|
|
open: false,
|
|
showModal: function() { this.open = true; },
|
|
close: function() { this.open = false; }
|
|
};
|
|
menuEnv.elements.sharedConfigurationDialog = menuDialog;
|
|
menuEnv.elements.sharedConfigurationURL = {
|
|
value: "", focus: function() {}, select: function() {}
|
|
};
|
|
menuLib.firstLoad();
|
|
menuEnv.ipcListeners.openSharedConfiguration();
|
|
assert.strictEqual(menuDialog.open, true);
|
|
}
|
|
|
|
// A sandbox that simulates the hardened Electron renderer: require throws for
|
|
// Node builtins, only window.electronAPI is available. extraAPI merges into
|
|
// window.electronAPI so each test can expose the bridge surface it targets.
|
|
function buildHardenedSandbox(bridgeZlib, extraAPI) {
|
|
const hardenedElements = {};
|
|
const hardenedSandbox = {
|
|
URL: URL,
|
|
console: { log: function() {} },
|
|
confirm: function() { return true; },
|
|
process: process,
|
|
setTimeout: function(callback) { callback(); },
|
|
window: {
|
|
MSREditor: {},
|
|
electronAPI: Object.assign({
|
|
zlib: bridgeZlib,
|
|
ipc: { on: function() {}, send: function() {}, invoke: function() { return Promise.resolve(null); } },
|
|
fs: {
|
|
existsSync: function() { return false; },
|
|
lstatSync: function() { return { isFile: function() { return false; }, isSymbolicLink: function() { return false; } }; },
|
|
statSync: function() { return { isFile: function() { return false; } }; },
|
|
readdirSync: function() { return []; },
|
|
readFileSync: function() { return ""; },
|
|
writeFileSync: function() {},
|
|
appendFileSync: function() {},
|
|
copyFileSync: function() {},
|
|
unlinkSync: function() {},
|
|
rmSync: function() {},
|
|
mkdirSync: function() {},
|
|
renameSync: function() {},
|
|
linkSync: function() {},
|
|
mkdir: function(p, o, cb) { if (typeof cb === "function") cb(null); },
|
|
readFile: function(p, e, cb) { if (typeof cb === "function") cb(null, ""); },
|
|
constants: { O_WRONLY: 0o1, COPYFILE_EXCL: 1 }
|
|
},
|
|
path: {
|
|
join: function(...parts) { return parts.join("/"); },
|
|
resolve: function(...parts) { return parts.join("/"); },
|
|
basename: function(p) { return (p || "").split("/").pop(); },
|
|
dirname: function(p) { return (p || "").split("/").slice(0, -1).join("/"); }
|
|
},
|
|
process: { cwd: function() { return "/tmp"; }, resourcesPath: "/tmp", plotlyURL: "", env: {} },
|
|
childProcess: {
|
|
execSync: function() { return { ok: true, stdout: "", error: null }; },
|
|
spawnSync: function() { return { pid: null, status: 0, signal: null, stdout: "", stderr: "", error: null }; },
|
|
spawnCapture: function() { return Promise.resolve({ ok: 1, code: 0, signal: null, stdout: "", stderr: "", error: null }); }
|
|
}
|
|
}, extraAPI || {})
|
|
},
|
|
document: {
|
|
getElementById: function(id) { return hardenedElements[id] || null; },
|
|
querySelectorAll: function() { return []; },
|
|
createElement: function() { return {}; }
|
|
},
|
|
require: function(name) {
|
|
// The hardened renderer never reaches require; this guard catches bugs.
|
|
throw new Error("require is not defined in hardened renderer");
|
|
}
|
|
};
|
|
hardenedSandbox.global = hardenedSandbox;
|
|
hardenedSandbox.window.window = hardenedSandbox.window;
|
|
|
|
vm.runInNewContext(commonCode, hardenedSandbox, { filename: "muSRFitlib.js" });
|
|
vm.runInNewContext(electronCode, hardenedSandbox, { filename: "muSRFitelec.js" });
|
|
return { sandbox: hardenedSandbox, elements: hardenedElements };
|
|
}
|
|
|
|
async function testElectronBridgeDecodeHardenedRenderer() {
|
|
// In the hardened Electron renderer (contextIsolation:true, sandbox:false),
|
|
// require('zlib') and require('buffer') are not available. This test loads
|
|
// muSRFitelec.js in a sandbox where require throws for Node builtins and only
|
|
// window.electronAPI.zlib is available, confirming the bridge-based path works.
|
|
const realZlib = require("zlib");
|
|
const realBuffer = require("buffer");
|
|
|
|
function gzipBase64URL(text) {
|
|
const zipped = realZlib.gzipSync(realBuffer.Buffer.from(text, "utf8"));
|
|
return zipped.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
function gunzipBase64URL(payload) {
|
|
let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/");
|
|
while (base64.length % 4) base64 += "=";
|
|
const zipped = realBuffer.Buffer.from(base64, "base64");
|
|
return realZlib.gunzipSync(zipped).toString("utf8");
|
|
}
|
|
const bridgeZlib = { gzipBase64URL: gzipBase64URL, gunzipBase64URL: gunzipBase64URL };
|
|
|
|
// First encode in a normal environment to get a valid #c= payload.
|
|
const normalEnv = loadSharedConfigurationHelpers();
|
|
const config = {
|
|
v: 1,
|
|
controls: { instrName: "LEM", runNumbers: "514-516" },
|
|
components: ["ExponentialCos"],
|
|
parameters: { valFrq_514: "1.2" },
|
|
functionMaps: { 1: { target: "Phi", parameters: ["RelPh_L", "RelPh_R"] } }
|
|
};
|
|
const encoded = await normalEnv.sandbox.encodeElectronSharedConfiguration(config);
|
|
const url = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload;
|
|
|
|
// Only window.electronAPI.zlib is available (no clipboard, no require).
|
|
const hardened = buildHardenedSandbox(bridgeZlib);
|
|
const hardenedSandbox = hardened.sandbox;
|
|
|
|
// Decode must succeed using only the bridge, without require('zlib').
|
|
const decoded = await hardenedSandbox.decodeElectronSharedConfiguration(url);
|
|
assert.strictEqual(decoded.error, "", "decode should succeed without require");
|
|
assert.strictEqual(decoded.consumed, true);
|
|
assert.strictEqual(JSON.stringify(decoded.config), JSON.stringify(config));
|
|
|
|
// Encode in the hardened sandbox must also work via the bridge.
|
|
const reEncoded = await hardenedSandbox.encodeElectronSharedConfiguration(config);
|
|
assert.strictEqual(reEncoded.prefix, "#c=");
|
|
const reDecoded = await hardenedSandbox.decodeElectronSharedConfiguration(
|
|
"#c=" + reEncoded.payload
|
|
);
|
|
assert.strictEqual(JSON.stringify(reDecoded.config), JSON.stringify(config));
|
|
}
|
|
|
|
async function testElectronBridgeCopyUsesBridgeClipboard() {
|
|
// Regression for "share link not working" in the packaged app: the hardened
|
|
// renderer has no require() and window.prompt() throws, so the working path
|
|
// must be bridge clipboard (window.electronAPI.clipboard.writeText). Prove
|
|
// copyWebConfigurationLink() completes and reaches the clipboard without
|
|
// ever touching require or prompt.
|
|
const realZlib = require("zlib");
|
|
const realBuffer = require("buffer");
|
|
function gzipBase64URL(text) {
|
|
const zipped = realZlib.gzipSync(realBuffer.Buffer.from(text, "utf8"));
|
|
return zipped.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
function gunzipBase64URL(payload) {
|
|
let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/");
|
|
while (base64.length % 4) base64 += "=";
|
|
const zipped = realBuffer.Buffer.from(base64, "base64");
|
|
return realZlib.gunzipSync(zipped).toString("utf8");
|
|
}
|
|
let bridgeClipboardText = "";
|
|
const hardened = buildHardenedSandbox(
|
|
{ gzipBase64URL: gzipBase64URL, gunzipBase64URL: gunzipBase64URL },
|
|
{
|
|
clipboard: {
|
|
writeText: function(value) { bridgeClipboardText = value; return true; }
|
|
}
|
|
}
|
|
);
|
|
const lib = hardened.sandbox;
|
|
hardened.elements.Runs = { querySelectorAll: function() { return []; } };
|
|
hardened.elements.Params = { querySelectorAll: function() { return []; } };
|
|
lib.prepCFG = function() {};
|
|
lib.getFitComponentValues = function() { return ["Exponential"]; };
|
|
lib.showTransientWarning = function() {};
|
|
lib.setFitStatus = function() {};
|
|
|
|
const copied = await lib.copyWebConfigurationLink();
|
|
|
|
assert.strictEqual(copied, true);
|
|
assert.match(bridgeClipboardText, /^http:\/\/musruser\.psi\.ch\/muSRFlow\/#c=/);
|
|
}
|
|
|
|
async function testSharedConfigurationEmbedsParameterPlotState() {
|
|
const env = loadSharedConfigurationWithPlotHelpers();
|
|
const lib = env.sandbox;
|
|
const storage = lib.parameterPlotStateStorage();
|
|
|
|
// No remembered state for the current source => the stanza is absent, so
|
|
// JSON.stringify drops it from the link instead of carrying a null value.
|
|
lib.window.MusrfitJob = { parameterDataPath: "/work/514_par.dat" };
|
|
let shared = lib.buildSharedConfiguration();
|
|
assert.strictEqual(shared.parameterPlot, undefined);
|
|
|
|
// A remembered snapshot for the current source rides along in the link.
|
|
const snapshot = {
|
|
v: 1,
|
|
mainSourceKey: "path:/work/514_par.dat",
|
|
jobName: "514_par.dat",
|
|
windowPaletteId: "bold",
|
|
panelSequence: 2,
|
|
dataSetColorCounter: 1,
|
|
templateId: "",
|
|
templatePanels: [],
|
|
templateSharedX: false,
|
|
layout: "2x1",
|
|
activePanelIndex: 0,
|
|
panelStates: [{
|
|
stableId: "pp1",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
yNames: ["Alpha"],
|
|
xName: "dataT",
|
|
xAuto: false,
|
|
mode: "markers",
|
|
dataSetKey: "path:/work/514_par.dat",
|
|
overlays: [],
|
|
paletteId: "bold",
|
|
xTitle: "",
|
|
yTitle: ""
|
|
}],
|
|
registeredDataSets: [{
|
|
key: "path:/work/514_par.dat",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
label: "514_par.dat",
|
|
colorIndex: 0
|
|
}],
|
|
styleRegistry: { "data!path:/work/514_par.dat": { color: "#d62728", symbol: "star", size: 12, opacity: 0.8, cap: true } }
|
|
};
|
|
lib.rememberParameterPlotState(storage, snapshot);
|
|
shared = lib.buildSharedConfiguration();
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(shared.parameterPlot)), snapshot);
|
|
|
|
// The shared stanza is a fresh copy: mutating it never touches the map.
|
|
shared.parameterPlot.panelStates[0].yNames[0] = "mutated";
|
|
shared.parameterPlot.styleRegistry["data!path:/work/514_par.dat"].color = "#000000";
|
|
const after = lib.readRememberedParameterPlotState(storage, "path:/work/514_par.dat");
|
|
assert.strictEqual(after.panelStates[0].yNames[0], "Alpha");
|
|
assert.strictEqual(after.styleRegistry["data!path:/work/514_par.dat"].color, "#d62728");
|
|
|
|
// Inline parameter-table sources embed the state the plot would restore.
|
|
const inlineText = "RUN dataT Alpha\n514 5 0.1\n";
|
|
const inlineSource = { kind: "inline", text: inlineText, label: "Parameter table" };
|
|
const inlineKey = lib.parameterDataSetKey(lib.normalizeParameterSource(inlineSource));
|
|
const inlineSnapshot = Object.assign({}, snapshot, {
|
|
mainSourceKey: inlineKey,
|
|
registeredDataSets: [{ key: inlineKey, source: inlineSource, label: "Parameter table", colorIndex: 0 }],
|
|
panelStates: [Object.assign({}, snapshot.panelStates[0], {
|
|
source: inlineSource,
|
|
dataSetKey: inlineKey
|
|
})]
|
|
});
|
|
lib.window.MusrfitJob = {};
|
|
lib.buildParameterDataFromTable = function() { return inlineText; };
|
|
lib.rememberParameterPlotState(storage, inlineSnapshot);
|
|
shared = lib.buildSharedConfiguration();
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(shared.parameterPlot)), inlineSnapshot);
|
|
|
|
// Order-preserving codec round-trip keeps the stanza intact.
|
|
const encoded = await lib.encodeElectronSharedConfiguration(shared);
|
|
const decoded = await lib.decodeElectronSharedConfiguration(
|
|
encoded.prefix + encoded.payload);
|
|
assert.strictEqual(decoded.error, "");
|
|
assert.deepStrictEqual(
|
|
JSON.parse(JSON.stringify(decoded.config.parameterPlot)),
|
|
JSON.parse(JSON.stringify(shared.parameterPlot)));
|
|
}
|
|
|
|
function testSharedConfigurationValidatesParameterPlotStanza() {
|
|
const env = loadSharedConfigurationWithPlotHelpers();
|
|
const lib = env.sandbox;
|
|
const valid = {
|
|
v: 1,
|
|
mainSourceKey: "path:/work/514_par.dat",
|
|
panelStates: [],
|
|
registeredDataSets: [],
|
|
styleRegistry: {}
|
|
};
|
|
assert.strictEqual(lib.validateSharedConfiguration({ v: 1, controls: {} }).v, 1);
|
|
assert.strictEqual(lib.validateSharedConfiguration(
|
|
{ v: 1, controls: {}, parameterPlot: valid }).parameterPlot.mainSourceKey,
|
|
"path:/work/514_par.dat");
|
|
assert.strictEqual(lib.validateSharedConfiguration(
|
|
{ v: 1, controls: {}, parameterPlot: null }).v, 1);
|
|
|
|
assert.throws(function() {
|
|
lib.validateSharedConfiguration({ v: 1, controls: {}, parameterPlot: [] });
|
|
}, /invalid parameter-plot configuration/);
|
|
assert.throws(function() {
|
|
lib.validateSharedConfiguration({ v: 1, controls: {}, parameterPlot: "text" });
|
|
}, /invalid parameter-plot configuration/);
|
|
// A stanza written by a future application version cannot be restored here,
|
|
// so it is silently dropped rather than failing the whole link.
|
|
assert.strictEqual(lib.validateSharedConfiguration({
|
|
v: 1, controls: {},
|
|
parameterPlot: { v: 99, mainSourceKey: "k", panelStates: [], registeredDataSets: [], styleRegistry: {} }
|
|
}).parameterPlot, null);
|
|
// A structurally invalid stanza of the current version is still rejected
|
|
// outright: crafted or unknown shapes are never trusted.
|
|
assert.throws(function() {
|
|
lib.validateSharedConfiguration({
|
|
v: 1, controls: {},
|
|
parameterPlot: { v: 1, mainSourceKey: "k", panelStates: "not-array", registeredDataSets: [], styleRegistry: {} }
|
|
});
|
|
}, /invalid parameter-plot configuration/);
|
|
|
|
// The shared-configuration version stays 1: the stanza is optional, so old
|
|
// links (without `parameterPlot`) and new links must decode identically.
|
|
assert.strictEqual(lib.MUSRFLOW_SHARE_CONFIG_VERSION, 1);
|
|
}
|
|
|
|
async function testSharedConfigurationIsVersionForwardCompatible() {
|
|
const env = loadSharedConfigurationHelpers();
|
|
const lib = env.sandbox;
|
|
|
|
// A link written by a newer build must still validate and decode here. The
|
|
// extra top-level fields are unknown to this application, so they are kept
|
|
// in the decoded object but never read by the restore step.
|
|
const future = { v: 2, controls: { runNumbers: "514" }, newField: { anything: true } };
|
|
assert.strictEqual(lib.validateSharedConfiguration(future).v, 2);
|
|
const encoded = await lib.encodeElectronSharedConfiguration(future);
|
|
const decoded = await lib.decodeElectronSharedConfiguration(
|
|
"http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload);
|
|
assert.strictEqual(decoded.error, "");
|
|
assert.strictEqual(decoded.config.v, 2);
|
|
assert.strictEqual(decoded.config.controls.runNumbers, "514");
|
|
assert.strictEqual(decoded.config.newField.anything, true);
|
|
|
|
// Older links (v:1) keep decoding in a v1-capable application.
|
|
const current = await lib.decodeElectronSharedConfiguration(
|
|
(await lib.encodeElectronSharedConfiguration({ v: 1, controls: {} })).prefix
|
|
+ (await lib.encodeElectronSharedConfiguration({ v: 1, controls: {} })).payload);
|
|
assert.strictEqual(current.error, "");
|
|
assert.strictEqual(current.config.v, 1);
|
|
|
|
// Only a missing/unknown version or a missing controls map is unusable.
|
|
assert.throws(function() { lib.validateSharedConfiguration(null); }, /unsupported configuration format/);
|
|
assert.throws(function() { lib.validateSharedConfiguration({}); }, /unsupported configuration format/);
|
|
assert.throws(function() { lib.validateSharedConfiguration({ v: 0, controls: {} }); }, /unsupported configuration format/);
|
|
assert.throws(function() { lib.validateSharedConfiguration({ v: -1, controls: {} }); }, /unsupported configuration format/);
|
|
assert.throws(function() { lib.validateSharedConfiguration({ v: "1", controls: {} }); }, /unsupported configuration format/);
|
|
assert.throws(function() { lib.validateSharedConfiguration({ v: 1 }); }, /unsupported configuration format/);
|
|
}
|
|
|
|
async function testSharedRestoreWritesParameterPlotStanza() {
|
|
const env = loadSharedConfigurationWithPlotHelpers();
|
|
const lib = env.sandbox;
|
|
const runsRoot = {
|
|
contains: function(element) { return element === env.elements.runNumbers; }
|
|
};
|
|
const paramsRoot = {
|
|
innerHTML: "existing",
|
|
contains: function(element) { return element === env.elements.valLam_514; }
|
|
};
|
|
env.elements.Runs = runsRoot;
|
|
env.elements.runNumbers = { value: "1" };
|
|
env.elements.columns = ["run", "dataT", "Alpha"];
|
|
env.elements.Params = paramsRoot;
|
|
env.elements.valLam_514 = { value: "0.1" };
|
|
env.elements.funBlock = { innerHTML: "" };
|
|
env.elements.t0Bg = { innerHTML: "" };
|
|
env.elements.funSel = { value: "", appendChild: function() {} };
|
|
env.elements.funLine = { value: "" };
|
|
env.elements.fnPhi = { disabled: false };
|
|
lib.adjustComps = function() {};
|
|
lib.updateTheoryBlock = function() {};
|
|
lib.clearStoredT0BgValues = function() {};
|
|
lib.cfgParams = async function() {};
|
|
lib.prepCFG = function() {};
|
|
lib.addFunLine = function() {};
|
|
lib.updateSeriesActionVisibility = function() {};
|
|
|
|
const stanza = {
|
|
v: 1,
|
|
mainSourceKey: "path:/work/514_par.dat",
|
|
jobName: "514_par.dat",
|
|
windowPaletteId: "bold",
|
|
panelSequence: 1,
|
|
dataSetColorCounter: 0,
|
|
templateId: "",
|
|
templatePanels: [],
|
|
templateSharedX: false,
|
|
layout: "1x1",
|
|
activePanelIndex: 0,
|
|
panelStates: [{
|
|
stableId: "pp1",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
yNames: ["Alpha"],
|
|
xName: "dataT",
|
|
xAuto: true,
|
|
mode: "markers",
|
|
dataSetKey: "path:/work/514_par.dat",
|
|
overlays: [],
|
|
paletteId: "bold",
|
|
xTitle: "",
|
|
yTitle: ""
|
|
}],
|
|
registeredDataSets: [{
|
|
key: "path:/work/514_par.dat",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
label: "514_par.dat",
|
|
colorIndex: 0
|
|
}],
|
|
styleRegistry: {}
|
|
};
|
|
|
|
const restored = await lib.restoreSharedConfiguration({
|
|
v: 1,
|
|
controls: { runNumbers: "514-516" },
|
|
parameters: { valLam_514: "0.25" },
|
|
customParameters: [],
|
|
constraints: [],
|
|
parameterPlot: stanza
|
|
});
|
|
assert.strictEqual(restored, true);
|
|
|
|
const stored = lib.readRememberedParameterPlotState(
|
|
lib.parameterPlotStateStorage(), "path:/work/514_par.dat");
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(stored)), stanza);
|
|
}
|
|
|
|
async function testSharedShareEmbedsParameterDataAndRestoresPlot() {
|
|
const env = loadSharedConfigurationWithPlotHelpers();
|
|
const lib = env.sandbox;
|
|
let capturedOpen = null;
|
|
lib.window.MusrfitParameterPlotPlatform = {
|
|
readDataSource: async function() { return "RUN dataT Alpha\n514 5 0.1\n"; },
|
|
openPlot: function(options) { capturedOpen = options; }
|
|
};
|
|
env.elements.Runs = { querySelectorAll: function() { return []; } };
|
|
env.elements.Params = { querySelectorAll: function() { return []; } };
|
|
env.elements.shareConfigButton = {};
|
|
lib.prepCFG = function() {};
|
|
lib.getFitComponentValues = function() { return []; };
|
|
lib.showTransientWarning = function() {};
|
|
lib.setFitStatus = function() {};
|
|
|
|
// Seed a remembered plot state for the current on-disk source.
|
|
const pathSnapshot = {
|
|
v: 1,
|
|
mainSourceKey: "path:/work/514_par.dat",
|
|
jobName: "514_par.dat",
|
|
windowPaletteId: "bold",
|
|
panelSequence: 1,
|
|
dataSetColorCounter: 0,
|
|
templateId: "",
|
|
templatePanels: [],
|
|
templateSharedX: false,
|
|
layout: "1x1",
|
|
activePanelIndex: 0,
|
|
panelStates: [{
|
|
stableId: "pp1",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
yNames: ["Alpha", "Lambda"],
|
|
xName: "dataT",
|
|
xAuto: true,
|
|
mode: "markers",
|
|
dataSetKey: "path:/work/514_par.dat",
|
|
overlays: [],
|
|
paletteId: "bold",
|
|
xTitle: "",
|
|
yTitle: ""
|
|
}],
|
|
registeredDataSets: [{
|
|
key: "path:/work/514_par.dat",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
label: "514_par.dat",
|
|
colorIndex: 0
|
|
}],
|
|
styleRegistry: {}
|
|
};
|
|
lib.rememberParameterPlotState(lib.parameterPlotStateStorage(), pathSnapshot);
|
|
lib.window.MusrfitJob = { parameterDataPath: "/work/514_par.dat" };
|
|
|
|
// Sharing embeds the actual parameter-data rows as an inline source so the
|
|
// receiving machine can draw the identical plot without its own *_par.dat.
|
|
const copied = await lib.copyWebConfigurationLink();
|
|
assert.strictEqual(copied, true);
|
|
const link = env.electron.clipboard.readText();
|
|
const decoded = await lib.decodeElectronSharedConfiguration(link);
|
|
assert.strictEqual(decoded.error, "");
|
|
const stanza = decoded.config.parameterPlot;
|
|
assert.strictEqual(stanza.panelStates[0].source.kind, "inline");
|
|
assert.strictEqual(stanza.panelStates[0].source.text, "RUN dataT Alpha\n514 5 0.1\n");
|
|
assert.ok(stanza.mainSourceKey.indexOf("inline:") === 0);
|
|
assert.strictEqual(stanza.panelStates[0].dataSetKey, stanza.mainSourceKey);
|
|
|
|
// Restore re-arms the "Plot parameters..." action with the shared selection
|
|
// and the pending self-contained snapshot.
|
|
env.elements.runNumbers = { value: "1" };
|
|
env.elements.funBlock = { innerHTML: "" };
|
|
env.elements.t0Bg = { innerHTML: "" };
|
|
env.elements.funSel = { value: "", appendChild: function() {} };
|
|
env.elements.funLine = { value: "" };
|
|
env.elements.valLam_514 = { value: "0.1" };
|
|
lib.adjustComps = function() {};
|
|
lib.updateTheoryBlock = function() {};
|
|
lib.clearStoredT0BgValues = function() {};
|
|
lib.cfgParams = async function() {};
|
|
lib.addFunLine = function() {};
|
|
lib.getCurrentEditorText = function() { return ""; };
|
|
lib.updateMSREditorSourceTabs = function() {};
|
|
|
|
const restored = await lib.restoreSharedConfiguration(decoded.config);
|
|
assert.strictEqual(restored, true);
|
|
assert.deepStrictEqual(Array.from(lib.selectedParameterPlotNames), ["Alpha", "Lambda"]);
|
|
|
|
const opened = lib.openPendingSharedParameterPlot();
|
|
assert.strictEqual(opened, true);
|
|
assert.ok(capturedOpen, "shared plot open must be dispatched");
|
|
assert.strictEqual(capturedOpen.savedState.mainSourceKey, stanza.mainSourceKey);
|
|
assert.strictEqual(capturedOpen.savedState.panelStates[0].source.text, "RUN dataT Alpha\n514 5 0.1\n");
|
|
assert.deepStrictEqual(Array.from(capturedOpen.preferredParameters), ["Alpha", "Lambda"]);
|
|
|
|
// The pending snapshot is consumed once: without a new restore the shared
|
|
// plot is not re-offered, so the user's own session takes over.
|
|
capturedOpen = null;
|
|
assert.strictEqual(lib.openPendingSharedParameterPlot(), false);
|
|
assert.strictEqual(capturedOpen, null);
|
|
}
|
|
|
|
async function testSharedShareHydratesAllPanelSources() {
|
|
const env = loadSharedConfigurationWithPlotHelpers();
|
|
const lib = env.sandbox;
|
|
lib.window.MusrfitParameterPlotPlatform = {
|
|
readDataSource: async function() { return "RUN dataT Alpha\n514 5 0.1\n"; }
|
|
};
|
|
|
|
// A two-panel snapshot where both panels reference the same path source.
|
|
const twoPanelSnapshot = {
|
|
v: 1,
|
|
mainSourceKey: "path:/work/514_par.dat",
|
|
jobName: "514_par.dat",
|
|
windowPaletteId: "bold",
|
|
panelSequence: 2,
|
|
dataSetColorCounter: 0,
|
|
templateId: "2x1",
|
|
templatePanels: [{ role: "relax", title: "Relaxation", params: ["Alpha"] }, { role: "relax", title: "Relaxation", params: ["Lambda"] }],
|
|
templateSharedX: true,
|
|
layout: "2x1",
|
|
activePanelIndex: 0,
|
|
panelStates: [
|
|
{
|
|
stableId: "pp1",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
yNames: ["Alpha"],
|
|
xName: "dataT",
|
|
xAuto: true,
|
|
mode: "markers",
|
|
dataSetKey: "path:/work/514_par.dat",
|
|
overlays: [],
|
|
paletteId: "bold",
|
|
xTitle: "",
|
|
yTitle: ""
|
|
},
|
|
{
|
|
stableId: "pp2",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
yNames: ["Lambda"],
|
|
xName: "dataT",
|
|
xAuto: true,
|
|
mode: "markers",
|
|
dataSetKey: "path:/work/514_par.dat",
|
|
overlays: [],
|
|
paletteId: "bold",
|
|
xTitle: "",
|
|
yTitle: ""
|
|
}
|
|
],
|
|
registeredDataSets: [{
|
|
key: "path:/work/514_par.dat",
|
|
source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" },
|
|
label: "514_par.dat",
|
|
colorIndex: 0
|
|
}],
|
|
styleRegistry: {
|
|
"trace!path:/work/514_par.dat!pp1!Alpha": { color: "#FF0000", symbol: "square", size: 8, opacity: 1, cap: false },
|
|
"trace!path:/work/514_par.dat!pp2!Lambda": { color: "#00FF00", symbol: "diamond", size: 6, opacity: 0.8, cap: true },
|
|
"data!path:/work/514_par.dat": { color: "#0000FF", symbol: "circle", size: 5, opacity: 1, cap: false },
|
|
"data!path:/work/other_par.dat": { color: "#123456" }
|
|
}
|
|
};
|
|
|
|
lib.rememberParameterPlotState(lib.parameterPlotStateStorage(), twoPanelSnapshot);
|
|
lib.window.MusrfitJob = { parameterDataPath: "/work/514_par.dat" };
|
|
|
|
// Hydrate and verify both panels become inline.
|
|
const hydrated = await lib.hydratedParameterPlotSnapshot(twoPanelSnapshot);
|
|
assert.strictEqual(hydrated.panelStates[0].source.kind, "inline");
|
|
assert.strictEqual(hydrated.panelStates[0].source.text, "RUN dataT Alpha\n514 5 0.1\n");
|
|
assert.strictEqual(hydrated.panelStates[1].source.kind, "inline");
|
|
assert.strictEqual(hydrated.panelStates[1].source.text, "RUN dataT Alpha\n514 5 0.1\n");
|
|
assert.strictEqual(hydrated.registeredDataSets[0].source.kind, "inline");
|
|
// Style-registry entries for the hydrated source are re-keyed to the inline
|
|
// identity so colors and markers survive the path-to-inline remap; entries
|
|
// for other data sets are left untouched.
|
|
const inlineKey = "inline:514_par.dat:26";
|
|
assert.deepStrictEqual(
|
|
JSON.parse(JSON.stringify(hydrated.styleRegistry["trace!" + inlineKey + "!pp1!Alpha"])),
|
|
{ color: "#FF0000", symbol: "square", size: 8, opacity: 1, cap: false });
|
|
assert.deepStrictEqual(
|
|
JSON.parse(JSON.stringify(hydrated.styleRegistry["trace!" + inlineKey + "!pp2!Lambda"])),
|
|
{ color: "#00FF00", symbol: "diamond", size: 6, opacity: 0.8, cap: true });
|
|
assert.deepStrictEqual(
|
|
JSON.parse(JSON.stringify(hydrated.styleRegistry["data!" + inlineKey])),
|
|
{ color: "#0000FF", symbol: "circle", size: 5, opacity: 1, cap: false });
|
|
assert.deepStrictEqual(
|
|
JSON.parse(JSON.stringify(hydrated.styleRegistry["data!path:/work/other_par.dat"])),
|
|
{ color: "#123456" });
|
|
assert.strictEqual(hydrated.styleRegistry["data!path:/work/514_par.dat"], undefined);
|
|
assert.strictEqual(hydrated.styleRegistry["trace!path:/work/514_par.dat!pp1!Alpha"], undefined);
|
|
}
|
|
|
|
// The web page exposes the desktop protocol link next to the normal Share
|
|
// button: browsers keep http(s) navigation for themselves, so handing a config
|
|
// to the installed desktop app requires a musrflow:// link (electron-builder
|
|
// registers x-scheme-handler/musrflow for the desktop build).
|
|
function testWebDesktopLinkButton() {
|
|
const web = fs.readFileSync(path.join(repoRoot, "muSRFitweb.js"), "utf8");
|
|
const lib = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8");
|
|
const html = fs.readFileSync(path.join(repoRoot, "index.html"), "utf8");
|
|
|
|
assert.match(lib, /var MUSRFLOW_DESKTOP_LINK_PREFIX = "musrflow:\/\/open\/"/);
|
|
assert.match(lib, /function desktopConfigurationLink\(encoded\)/);
|
|
assert.match(web, /async function copyWebDesktopConfigurationLink/);
|
|
assert.match(web, /baseURL: function\(\) { return MUSRFLOW_DESKTOP_LINK_PREFIX; }/);
|
|
|
|
assert.match(html, /id="desktopLinkButton"/);
|
|
assert.match(html, /copyWebDesktopConfigurationLink/);
|
|
// Hidden in markup, revealed only by the web shell (Electron keeps its own
|
|
// native Share flow and hides the web-only button).
|
|
assert.match(html, /desktopLinkButton\) desktopLinkButton\.hidden = false;/);
|
|
}
|
|
|
|
async function main() {
|
|
await testElectronCodecReadsWebCompatibleLinks();
|
|
testSharedConfigurationIncludesDetectorMaps();
|
|
testElectronMenuAndRendererAreConnected();
|
|
testWebDesktopLinkButton();
|
|
testTransientWarningIsPositionedAndTimed();
|
|
await testElectronShareProvidesVisibleConfirmation();
|
|
await testSharedRestoreCannotChangeLocalPreferences();
|
|
await testElectronDialogRestoresStateAndMarksEditorStale();
|
|
await testUserCanCancelOverwritingEditorOwnership();
|
|
await testElectronSharedURLRestoresThroughListener();
|
|
await testElectronBridgeDecodeHardenedRenderer();
|
|
await testElectronBridgeCopyUsesBridgeClipboard();
|
|
await testSharedConfigurationEmbedsParameterPlotState();
|
|
testSharedConfigurationValidatesParameterPlotStanza();
|
|
await testSharedConfigurationIsVersionForwardCompatible();
|
|
await testSharedRestoreWritesParameterPlotStanza();
|
|
await testSharedShareEmbedsParameterDataAndRestoresPlot();
|
|
await testSharedShareHydratesAllPanelSources();
|
|
console.log("shared configuration tests passed");
|
|
}
|
|
|
|
main().catch(function(error) {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|