diff --git a/main.js b/main.js index c160c1d..2787fed 100644 --- a/main.js +++ b/main.js @@ -54,19 +54,6 @@ function lastMSRDirectoryFile() { return path.join(app.getPath("userData"), "last-msr-directory.json"); } let rememberedMSRDirectory = ""; -function loadRememberedMSRDirectory() { - try { - const content = fs.readFileSync(lastMSRDirectoryFile(), "utf8"); - const saved = JSON.parse(content); - const directory = saved && saved.directory ? String(saved.directory) : ""; - if (directory && fs.existsSync(directory) && fs.statSync(directory).isDirectory()) { - rememberedMSRDirectory = directory; - } - } catch (error) { - rememberedMSRDirectory = ""; - } - return rememberedMSRDirectory; -} function rememberMSRDirectory(directory) { if (!directory) { return; @@ -136,29 +123,6 @@ function createParameterPlotWindow(options = {}) { plotWindow.on("closed", () => parameterPlotWindows.delete(plotWindow)); } -function showQuickStartWindow(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; - }); -} - // Create the Electron shell; fitting logic remains in the shared renderer. // A configuration link is an http(s)://…/muSRFlow/#c=… (or #cfg=…) URL. Only // such URLs are accepted from the command line, a second instance, or @@ -211,7 +175,16 @@ function createWindow () { if (mainWindow === win) mainWindow = null; }); - loadRememberedMSRDirectory(); + 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 = [ @@ -462,7 +435,27 @@ ipcMain.on("openParameterPlotWindow", (event, 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) => { - showQuickStartWindow(options && options.sectionId ? options.sectionId : "helpRuns"); + 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 diff --git a/muSRFitParameterPlot.js b/muSRFitParameterPlot.js index 489b385..df3fe6b 100644 --- a/muSRFitParameterPlot.js +++ b/muSRFitParameterPlot.js @@ -14,19 +14,6 @@ function musrfitParameterPlotPlatform() { return platform; } -function loadMusrfitPlotly() { - if (window.Plotly) return Promise.resolve(window.Plotly); - let platform = musrfitParameterPlotPlatform(); - if (typeof platform.loadPlotly !== "function") { - return Promise.reject(new Error("No Plotly loader is available for this platform")); - } - return Promise.resolve(platform.loadPlotly()).then(function(plotly) { - if (!plotly) throw new Error("The platform Plotly loader returned no Plotly instance"); - window.Plotly = plotly; - return plotly; - }); -} - function parseMusrfitParameterData(contents) { // Preserve msr2data column names exactly. Only the leading '%' comment // marker used by some versions is removed from the header line. @@ -115,47 +102,6 @@ function defaultMusrfitParameterXColumn(dataset) { const musrfitScanCandidateOrder = ["dataT", "dataB", "dataE", "dataSpinRot", "RUN"]; -function musrfitFiniteValues(dataset, columnIndex) { - return musrfitParameterColumnValues(dataset, columnIndex) - .filter(function(value) { return Number.isFinite(value); }); -} - -// Per-variable tolerance floor: changes smaller than this are treated as -// drift or noise rather than a genuine scan variable. This keeps a small -// secondary-parameter drift from overriding the real scan variable. -function musrfitScanFloor(name) { - let floors = { dataT: 1, dataB: 10, dataE: 1, dataSpinRot: 1, RUN: 0 }; - return floors[name] !== undefined ? floors[name] : 0; -} - -function detectiveScoreCursor(column, dataset, scan) { - if (column < 0) { - scan.ranged = 0; - scan.distinct = 0; - scan.coverage = 0; - scan.score = 0; - return; - } - let finite = musrfitFiniteValues(dataset, column); - scan.coverage = dataset.rows.length ? finite.length / dataset.rows.length : 0; - let distinct = new Set(finite); - scan.distinct = distinct.size; - if (distinct.size === 0) { - scan.ranged = 0; - scan.score = 0; - return; - } - let min = Infinity; - let max = -Infinity; - for (let value of distinct) { - if (value < min) min = value; - if (value > max) max = value; - } - scan.ranged = max - min; - scan.score = scan.coverage === 1 && distinct.size > 1 - && scan.ranged > musrfitScanFloor(scan.name) ? 1 : 0; -} - // Determine the scan variable for a finished multi-run parameter table. A scan // description reports the selected column plus its coverage, distinct-value // count, numeric range, confidence, and any alternative varying metadata. The @@ -168,7 +114,34 @@ function detectMusrfitScanVariable(dataset) { for (let name of musrfitScanCandidateOrder) { let column = musrfitParameterColumnIndex(dataset, name); let scan = { name: name, column: column, label: musrfitParameterAxisLabel(name) }; - detectiveScoreCursor(column, dataset, scan); + if (column < 0) { + scan.ranged = 0; + scan.distinct = 0; + scan.coverage = 0; + scan.score = 0; + } else { + let finite = musrfitParameterColumnValues(dataset, column) + .filter(function(value) { return Number.isFinite(value); }); + scan.coverage = dataset.rows.length ? finite.length / dataset.rows.length : 0; + let distinct = new Set(finite); + scan.distinct = distinct.size; + if (distinct.size === 0) { + scan.ranged = 0; + scan.score = 0; + } else { + let min = Infinity; + let max = -Infinity; + for (let value of distinct) { + if (value < min) min = value; + if (value > max) max = value; + } + scan.ranged = max - min; + let floors = { dataT: 1, dataB: 10, dataE: 1, dataSpinRot: 1, RUN: 0 }; + let floor = floors[scan.name] !== undefined ? floors[scan.name] : 0; + scan.score = scan.coverage === 1 && distinct.size > 1 + && scan.ranged > floor ? 1 : 0; + } + } registry[name] = scan; } @@ -238,13 +211,6 @@ function detectMusrfitScanVariable(dataset) { }; } -function isMusrfitParameterMetadataColumn(name) { - let normalized = String(name || "").toLowerCase(); - return normalized === "run" || normalized === "datat" - || normalized === "datab" || normalized === "datae" - || normalized === "dataspinrot"; -} - // Built-in parameter-plot templates are declarative data: a stable identifier, // a human name, the compatible X-variable names, the panel layout, shared-X // behavior, and per-panel semantic parameter roles. Templates are applied by @@ -546,13 +512,9 @@ const MUSRFIT_PARAMETER_PLOT_PALETTES = { "#333333", "#555555", "#888888", "#bbbbbb", "#dddddd"] }; -function musrfitParameterPalette(paletteId) { - let palette = MUSRFIT_PARAMETER_PLOT_PALETTES[paletteId || "default"]; - return palette || MUSRFIT_PARAMETER_PLOT_PALETTES.default; -} - function musrfitParameterPaletteColor(paletteId, index) { - let palette = musrfitParameterPalette(paletteId); + let palette = MUSRFIT_PARAMETER_PLOT_PALETTES[paletteId || "default"]; + if (!palette) palette = MUSRFIT_PARAMETER_PLOT_PALETTES.default; return palette[Math.max(0, Number(index) || 0) % palette.length]; } @@ -696,10 +658,6 @@ function parameterPlotConfigurationLabel(snapshotConfig) { return panelCount ? panelCount + " panel" + (panelCount > 1 ? "s" : "") : "Saved configuration"; } -function isRememberedParameterPlotStateList(value) { - return Array.isArray(value) && value.some(validateParameterPlotState); -} - // Each data source keeps a list of remembered configurations, most recent // first, with at most one entry per parameter-Y-set. Values written by older // versions (a single snapshot per source) are upgraded on read. @@ -712,7 +670,7 @@ function readRememberedParameterPlotStates(storage) { let parsed = JSON.parse(raw); for (let key of Object.keys(parsed || {})) { let value = parsed[key]; - let list = isRememberedParameterPlotStateList(value) + let list = Array.isArray(value) && value.some(validateParameterPlotState) ? value.filter(validateParameterPlotState) : (validateParameterPlotState(value) ? [value] : []); if (list.length) states[key] = list; @@ -812,7 +770,9 @@ async function hydratedParameterPlotSnapshot(snapshot) { if (!text) return snapshot; let pathValue = mainSource.path || ""; - let label = mainSource.label || firstParameterPlotPathSegment(pathValue) || "Parameter data"; + let pathClean = String(pathValue).split(/[?#]/)[0]; + let pathPieces = pathClean.split(/[\\/]/); + let label = mainSource.label || pathPieces[pathPieces.length - 1] || "Parameter data"; let inlineSource = { kind: "inline", text: String(text), label: label }; let inlineKey = parameterDataSetKey(inlineSource); let hydrated = JSON.parse(JSON.stringify(snapshot)); @@ -852,12 +812,6 @@ if (Array.isArray(hydrated.registeredDataSets)) { return hydrated; } -function firstParameterPlotPathSegment(pathValue) { - let clean = String(pathValue || "").split(/[?#]/)[0]; - let pieces = clean.split(/[\\/]/); - return pieces[pieces.length - 1] || ""; -} - // The most recent shared configuration's parameter-plot stanza. It is consumed // once: the first time a parameter plot is opened after a restore, the shared // window state (with its embedded data) is used instead of the source-keyed @@ -876,7 +830,8 @@ function consumePendingSharedParameterPlot() { } // The parameters a snapshot plotted, as a flat name list (used to pre-select -// the parameter-plot chips after a shared-configuration restore). +// the parameter-plot chips after a shared-configuration restore, both from +// muSRFitlib.js and when a pending shared plot opens here). function parameterPlotNamesFromSnapshot(snapshot) { let names = []; for (let panel of Array.isArray(snapshot && snapshot.panelStates) ? snapshot.panelStates : []) { @@ -1124,7 +1079,11 @@ function buildMusrfitParameterOverlayTraces(dataSets, xName, yNames, mode, optio function musrfitParameterYCandidates(dataset, xIndex) { let candidates = []; for (let i = 0; i < dataset.columns.length; i++) { - if (i === xIndex || isMusrfitParameterMetadataColumn(dataset.columns[i])) continue; + let name = dataset.columns[i]; + let normalized = String(name || "").toLowerCase(); + if (i === xIndex || normalized === "run" || normalized === "datat" + || normalized === "datab" || normalized === "datae" + || normalized === "dataspinrot") continue; if (isMusrfitParameterErrorColumn(dataset, i)) continue; candidates.push(i); } @@ -1230,13 +1189,6 @@ function fillMusrfitParameterSelect(select, dataset, indices, selectedIndex, non select.value = String(selectedIndex); } -function musrfitParameterIsEditableTarget(target) { - if (!target || !target.tagName) return false; - let tagName = target.tagName.toLowerCase(); - return tagName === "input" || tagName === "select" || tagName === "textarea" - || target.isContentEditable; -} - function showMusrfitParameterAxisDialog(parameterPath, jobName = "", preferredParameters = []) { if (!parameterPath || !preferredParameters.length) return; parameterPath = normalizeParameterSource(parameterPath); @@ -1777,10 +1729,6 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa return pieces[pieces.length - 1] || "Parameter data"; } - function makePathSource(pathValue, labelValue) { - return { kind: "path", path: pathValue, label: labelValue || sourceLabelFromPath(pathValue) }; - } - async function readPanelSource(source) { if (!source) throw new Error("No parameter-data source is selected"); let platform = musrfitParameterPlotPlatform(); @@ -1912,7 +1860,14 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa name.className = "parameter-plot-data-set-name"; name.textContent = entry.label; checkbox.addEventListener("change", function() { - togglePanelOverlay(panel, entry.key, checkbox.checked); + if (checkbox.checked) { + if (!panel.overlays.includes(entry.key)) panel.overlays.push(entry.key); + } else { + panel.overlays = panel.overlays.filter(function(existing) { return existing !== entry.key; }); + } + redrawPanel(activePanelIndex); + syncToolbarFromActivePanel(); + scheduleParameterPlotStateSave(); }); row.appendChild(checkbox); row.appendChild(swatch); @@ -1921,17 +1876,6 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa } } - function togglePanelOverlay(panel, key, checked) { - if (checked) { - if (!panel.overlays.includes(key)) panel.overlays.push(key); - } else { - panel.overlays = panel.overlays.filter(function(existing) { return existing !== key; }); - } - redrawPanel(activePanelIndex); - syncToolbarFromActivePanel(); - scheduleParameterPlotStateSave(); - } - async function loadDataSetEntry(entry) { let contents = await readPanelSource(entry.source); let nextDataset = parseMusrfitParameterData(contents); @@ -2127,23 +2071,21 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa }); if (!panel.clickAttached && typeof panel.chart.on === "function") { panel.clickAttached = true; - panel.chart.on("plotly_click", function(event) { handleParameterPlotClick(panel, event); }); + // Map a click on a plotted marker back to its (data set, parameter) + // series and offer style editing in a small popover near the pointer. + panel.chart.on("plotly_click", function(clickEvent) { + let points = clickEvent && clickEvent.points; + if (!points || !points.length) return; + let clicked = points[0]; + if (!clicked) return; + let yName = (clicked.curveNumber >= 0 && clicked.curveNumber < panel.yNames.length) + ? panel.yNames[clicked.curveNumber] : panel.yNames[0]; + if (!yName) return; + openParameterStylePicker(panel, yName, clicked.event); + }); } } - // Map a click on a plotted marker back to its (data set, parameter) series - // and offer style editing in a small popover near the pointer. - function handleParameterPlotClick(panel, event) { - let points = event && event.points; - if (!points || !points.length) return; - let clicked = points[0]; - if (!clicked) return; - let yName = (clicked.curveNumber >= 0 && clicked.curveNumber < panel.yNames.length) - ? panel.yNames[clicked.curveNumber] : panel.yNames[0]; - if (!yName) return; - openParameterStylePicker(panel, yName, clicked.event); - } - function closeParameterStylePicker() { if (stylePicker) { if (stylePicker.remove) stylePicker.remove(); @@ -2405,16 +2347,14 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa // One-shot outside click / focus elsewhere closes the picker. setTimeout(function() { - document.addEventListener("pointerdown", stylePickerDismiss, { once: true, capture: true }); + document.addEventListener("pointerdown", function(event) { + if (!stylePicker || !stylePicker.parentNode) return; + if (stylePicker.contains(event.target)) return; + closeParameterStylePicker(); + }, { once: true, capture: true }); }, 0); } - function stylePickerDismiss(event) { - if (!stylePicker || !stylePicker.parentNode) return; - if (stylePicker.contains(event.target)) return; - closeParameterStylePicker(); - } - function redrawParameterStyleTargets(panel, scope) { if (scope === "dataset") { redrawVisiblePanels(); @@ -2487,7 +2427,19 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa message.className = "web-root-message parameter-plot-message"; message.textContent = initialLoad ? "Loading parameter data..." : "Refreshing parameter data..."; try { - if (!plotly) plotly = await loadMusrfitPlotly(); + if (!plotly) { + if (window.Plotly) { + plotly = window.Plotly; + } else { + let platform = musrfitParameterPlotPlatform(); + if (typeof platform.loadPlotly !== "function") { + throw new Error("No Plotly loader is available for this platform"); + } + plotly = await platform.loadPlotly(); + if (!plotly) throw new Error("The platform Plotly loader returned no Plotly instance"); + window.Plotly = plotly; + } + } let tasks = []; for (let i = 0; i < visiblePanelCount; i++) { if (panelStates[i] && panelStates[i].source) tasks.push(refreshPanel(i, initialLoad)); @@ -2742,7 +2694,11 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa let source = parameterPath; if (source.kind === "path" && !source.label) { - source = makePathSource(source.path, jobName || sourceLabelFromPath(source.path)); + source = { + kind: "path", + path: source.path, + label: jobName || sourceLabelFromPath(source.path) + }; } // The axis dialog can pass a validated snapshot to reopen a remembered plot // directly, skipping the "Choose X axis" dialog. Panel sources are resolved @@ -2767,7 +2723,13 @@ function showMusrfitParameterPlotWindow(parameterPath, jobName = "", preferredPa } function handleParameterPlotKeydown(event) { - if (event.altKey || event.ctrlKey || event.metaKey || musrfitParameterIsEditableTarget(event.target)) return; + let target = event.target; + let editableTarget = target && target.tagName + && (target.tagName.toLowerCase() === "input" + || target.tagName.toLowerCase() === "select" + || target.tagName.toLowerCase() === "textarea" + || target.isContentEditable); + if (event.altKey || event.ctrlKey || event.metaKey || editableTarget) return; let shortcut = event.key.length === 1 ? event.key.toLowerCase() : event.key; if (shortcut === "u" && plotly) { event.preventDefault(); diff --git a/muSRFitRoot.js b/muSRFitRoot.js index 77d9a12..a263206 100644 --- a/muSRFitRoot.js +++ b/muSRFitRoot.js @@ -23,25 +23,8 @@ function loadMusrfitJSRoot() { return window.MusrfitRootModulePromise; } -// musrview reuses predictable filenames inside the same job directory. Add a -// harmless query parameter so redraw/reset requests never show a stale canvas. -function musrfitRootCacheBustUrl(rootUrl, version) { - let separator = rootUrl.indexOf("?") === -1 ? "?" : "&"; - return rootUrl + separator + "musrflow_root=" + encodeURIComponent(version); -} - // musrview names each serialized ROOT canvas fMainCanvas;1, where // follows the numbered output filename, e.g. run_0.root -> fMainCanvas0;1. -function musrfitRootDefaultItemForUrl(rootUrl) { - let cleanUrl = String(rootUrl || "").split("?")[0]; - let fileName = cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1); - let match = fileName.match(/_(\d+)(?:_F)?\.root$/); - if (match) { - return "fMainCanvas" + match[1] + ";1"; - } - return "fMainCanvas0;1"; -} - // Convert the CGI response into explicit {url, item} pairs. If the CGI did not // return an item name, derive the usual musrview canvas name from the filename. function normalizeMusrfitRootPlotSpecs(rootUrls, rootItems) { @@ -50,15 +33,21 @@ function normalizeMusrfitRootPlotSpecs(rootUrls, rootItems) { return urls.filter(function(rootUrl) { return typeof rootUrl === "string" && rootUrl !== ""; }).map(function(rootUrl, index) { + let cleanUrl = String(rootUrl || "").split("?")[0]; + let fileName = cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1); + let match = fileName.match(/_(\d+)(?:_F)?\.root$/); + let defaultItem = match ? "fMainCanvas" + match[1] + ";1" : "fMainCanvas0;1"; return { url: rootUrl, - item: items[index] || musrfitRootDefaultItemForUrl(rootUrl) + item: items[index] || defaultItem }; }); } // Accept both the current multi-plot response and the older single-url shape. -// This keeps the browser side tolerant while CGI deployments are upgraded. +// This keeps the browser side tolerant while CGI deployments are upgraded. The +// web platform adapter also consults this helper after rt_alias / msr2data +// requests, so it stays a shared top-level function. function musrfitRootUrlsFromResponse(response) { if (!response) { return []; @@ -121,23 +110,19 @@ function musrfitRootTimeoutMs() { return Number.isFinite(configured) && configured > 0 ? configured : 60000; } -function musrfitRootTimeoutError(step, url) { - let error = new Error(step + " timed out after " - + Math.round(musrfitRootTimeoutMs() / 1000) + "s: " + url); - error.name = "TimeoutError"; - return error; -} - function withMusrfitRootTimeout(promise, step, url) { return new Promise(function(resolve, reject) { let settled = false; let timer = setTimeout(function() { - if (settled) { - return; - } - settled = true; - reject(musrfitRootTimeoutError(step, url)); - }, musrfitRootTimeoutMs()); + if (settled) { + return; + } + settled = true; + let timeoutError = new Error(step + " timed out after " + + Math.round(musrfitRootTimeoutMs() / 1000) + "s: " + url); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, musrfitRootTimeoutMs()); Promise.resolve(promise).then(function(value) { if (settled) { return; @@ -156,17 +141,6 @@ function withMusrfitRootTimeout(promise, step, url) { }); } -// Plot shortcuts should not steal keystrokes from inputs, selects, or editable -// regions that may appear in future plot controls. -function musrfitRootIsEditableTarget(target) { - if (!target) { - return false; - } - let tagName = target.tagName ? target.tagName.toLowerCase() : ""; - return target.isContentEditable || tagName === "input" - || tagName === "textarea" || tagName === "select"; -} - // JSROOT may expose a ROOT TList either directly as an array or via .arr. function musrfitRootCollectionArray(collection) { if (Array.isArray(collection)) { @@ -224,20 +198,6 @@ const MUSRFIT_ROOT_LEGEND_MAX_HEIGHT = 0.80; // the transformation independent of JSROOT painter internals. const MUSRFIT_ROOT_CENTER_TITLE_BIT = 1 << 12; -// Apply the clean-view axis typography. Keep the axis titles slightly larger -// than the tick labels while retaining a compact publication-like scale. -function styleMusrfitRootAxis(axis) { - if (!axis || typeof axis !== "object") { - return; - } - axis.fLabelFont = MUSRFIT_ROOT_LATEX_FONT; - axis.fTitleFont = MUSRFIT_ROOT_LATEX_FONT; - axis.fLabelSize = MUSRFIT_ROOT_SCALE_FONT_SIZE; - axis.fTitleSize = MUSRFIT_ROOT_AXIS_LABEL_FONT_SIZE; - axis.fBits = (Number.isFinite(axis.fBits) ? axis.fBits : 0) - | MUSRFIT_ROOT_CENTER_TITLE_BIT; -} - // Axis-bearing ROOT objects can be nested inside pads or a multigraph frame. // Walk only the small set of container fields used by musrview/JSROOT rather // than traversing graph data arrays. @@ -248,9 +208,16 @@ function styleMusrfitRootAxes(object, visited = new WeakSet()) { visited.add(object); ["fXaxis", "fYaxis"].forEach(function(axisName) { - if (object[axisName]) { - styleMusrfitRootAxis(object[axisName]); + let axis = object[axisName]; + if (!axis || typeof axis !== "object") { + return; } + axis.fLabelFont = MUSRFIT_ROOT_LATEX_FONT; + axis.fTitleFont = MUSRFIT_ROOT_LATEX_FONT; + axis.fLabelSize = MUSRFIT_ROOT_SCALE_FONT_SIZE; + axis.fTitleSize = MUSRFIT_ROOT_AXIS_LABEL_FONT_SIZE; + axis.fBits = (Number.isFinite(axis.fBits) ? axis.fBits : 0) + | MUSRFIT_ROOT_CENTER_TITLE_BIT; }); if (object.fHistogram) { @@ -292,42 +259,6 @@ function musrfitRootCoordinate(object, ndcName, fallbackName) { return null; } -// Identify musrview's parameter/theory boxes by type and right-column geometry. -function musrfitRootIsRightTextPanel(object) { - if (!object || object._typename !== "TPaveText") { - return false; - } - let x1 = musrfitRootCoordinate(object, "fX1NDC", "fX1"); - let x2 = musrfitRootCoordinate(object, "fX2NDC", "fX2"); - let y1 = musrfitRootCoordinate(object, "fY1NDC", "fY1"); - let y2 = musrfitRootCoordinate(object, "fY2NDC", "fY2"); - return x1 !== null && x2 !== null && y1 !== null && y2 !== null - && x1 >= 0.6 && x2 >= 0.95 && y1 >= 0.05 && y2 <= 0.96; -} - -// Identify the full-width information legend at the bottom of a musrview canvas. -function musrfitRootIsInfoLegend(object) { - if (!object || object._typename !== "TLegend") { - return false; - } - let x1 = musrfitRootCoordinate(object, "fX1NDC", "fX1"); - let x2 = musrfitRootCoordinate(object, "fX2NDC", "fX2"); - let y1 = musrfitRootCoordinate(object, "fY1NDC", "fY1"); - let y2 = musrfitRootCoordinate(object, "fY2NDC", "fY2"); - return x1 !== null && x2 !== null && y1 !== null && y2 !== null - && x1 <= 0.05 && x2 >= 0.95 && y1 <= 0.05 && y2 <= 0.2; -} - -// Add a readable space between a numeric value and its physical unit. -function musrfitRootFormatMetadataValue(value) { - let trimmed = String(value || "").trim(); - let match = trimmed.match(/^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(K|G|T|keV|meV|eV)$/i); - if (!match) { - return trimmed; - } - return match[1] + " " + match[2]; -} - // musrview writes labels as run,histograms,T=...,B=...,E=...,setup. Keep only // physical metadata in the clean view. If none are available, retain the run // identifier so multiple curves do not become anonymous. @@ -345,7 +276,12 @@ function cleanMusrfitRootLegendLabels(label) { if (!value || value === "??") { continue; } - metadata.push(match[1] + "=" + musrfitRootFormatMetadataValue(value)); + // Add a readable space between a numeric value and its physical unit. + let trimmedValue = String(value || "").trim(); + let unitMatch = trimmedValue.match( + /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(K|G|T|keV|meV|eV)$/i); + metadata.push(match[1] + "=" + + (unitMatch ? unitMatch[1] + " " + unitMatch[2] : trimmedValue)); } if (metadata.length) { return metadata; @@ -487,24 +423,6 @@ function positionMusrfitRootInfoLegend(legend) { * Math.min(heightScale, widthScale); } -// The bottom information strip is removed in clean mode, so use that space for -// the data pad. Preserve its right edge and top edge: only the vertical extent -// changes and the compact T/B/E legend remains in the original right column. -function stretchMusrfitRootDataPadVertically(dataPad) { - if (!dataPad) { - return; - } - - if (Number.isFinite(dataPad.fYlowNDC) && Number.isFinite(dataPad.fHNDC)) { - dataPad.fHNDC += dataPad.fYlowNDC; - dataPad.fYlowNDC = 0.0; - } - if (Number.isFinite(dataPad.fAbsYlowNDC) && Number.isFinite(dataPad.fAbsHNDC)) { - dataPad.fAbsHNDC += dataPad.fAbsYlowNDC; - dataPad.fAbsYlowNDC = 0.0; - } -} - // Apply a presentation-only cleanup to the deserialized musrview canvas. The // ROOT file itself is never modified; toggling back simply rereads it. function cleanMusrfitRootCanvas(canvasObject) { @@ -520,13 +438,43 @@ function cleanMusrfitRootCanvas(canvasObject) { return canvasObject; } - let infoLegend = primitives.find(musrfitRootIsInfoLegend); + // Identify the full-width information legend at the bottom of the canvas. + let infoLegend = primitives.find(function(object) { + if (!object || object._typename !== "TLegend") { + return false; + } + let lx1 = musrfitRootCoordinate(object, "fX1NDC", "fX1"); + let lx2 = musrfitRootCoordinate(object, "fX2NDC", "fX2"); + let ly1 = musrfitRootCoordinate(object, "fY1NDC", "fY1"); + let ly2 = musrfitRootCoordinate(object, "fY2NDC", "fY2"); + return lx1 !== null && lx2 !== null && ly1 !== null && ly2 !== null + && lx1 <= 0.05 && lx2 >= 0.95 && ly1 <= 0.05 && ly2 <= 0.2; + }); + // Remove musrview's parameter/theory boxes: TPaveText objects in the right + // column of the canvas. filterMusrfitRootCollection(canvasObject.fPrimitives, function(object) { - return !musrfitRootIsRightTextPanel(object); + if (!object || object._typename !== "TPaveText") { + return true; + } + let rx1 = musrfitRootCoordinate(object, "fX1NDC", "fX1"); + let rx2 = musrfitRootCoordinate(object, "fX2NDC", "fX2"); + let ry1 = musrfitRootCoordinate(object, "fY1NDC", "fY1"); + let ry2 = musrfitRootCoordinate(object, "fY2NDC", "fY2"); + return !(rx1 !== null && rx2 !== null && ry1 !== null && ry2 !== null + && rx1 >= 0.6 && rx2 >= 0.95 && ry1 >= 0.05 && ry2 <= 0.96); }); cleanMusrfitRootInfoLegend(infoLegend); positionMusrfitRootInfoLegend(infoLegend); - stretchMusrfitRootDataPadVertically(dataPad); + // The bottom information strip is removed in clean mode, so use that space + // for the data pad. Preserve its right edge and top edge. + if (Number.isFinite(dataPad.fYlowNDC) && Number.isFinite(dataPad.fHNDC)) { + dataPad.fHNDC += dataPad.fYlowNDC; + dataPad.fYlowNDC = 0.0; + } + if (Number.isFinite(dataPad.fAbsYlowNDC) && Number.isFinite(dataPad.fAbsHNDC)) { + dataPad.fAbsHNDC += dataPad.fAbsYlowNDC; + dataPad.fAbsYlowNDC = 0.0; + } styleMusrfitRootAxes(dataPad); styleMusrfitRootTextFonts(canvasObject); return canvasObject; @@ -688,8 +636,13 @@ async function renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewM container.appendChild(pane); try { + // musrview reuses predictable filenames inside the same job directory; + // add a harmless query parameter so redraw/reset requests never show a + // stale canvas. let file = await withMusrfitRootTimeout( - jsroot.openFile(musrfitRootCacheBustUrl(plotSpec.url, renderVersion)), + jsroot.openFile(plotSpec.url + + (plotSpec.url.indexOf("?") === -1 ? "?" : "&") + + "musrflow_root=" + encodeURIComponent(renderVersion)), "Opening ROOT file", plotSpec.url); if (musrfitRootRenderIsStale(container, renderToken, canvas)) { return; @@ -1006,8 +959,14 @@ function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) { // Minimal musrview-like shortcuts for the focused ROOT plot window. plotWindow.addEventListener("keydown", function(event) { - if (event.altKey || event.ctrlKey || event.metaKey - || musrfitRootIsEditableTarget(event.target)) { + // Plot shortcuts should not steal keystrokes from inputs, selects, or + // editable regions that may appear in future plot controls. + let target = event.target; + let targetTagName = target && target.tagName ? target.tagName.toLowerCase() : ""; + let editableTarget = target && (target.isContentEditable + || targetTagName === "input" || targetTagName === "textarea" + || targetTagName === "select"); + if (event.altKey || event.ctrlKey || event.metaKey || editableTarget) { return; } diff --git a/muSRFitelec.js b/muSRFitelec.js index c4f9b62..b7c8adb 100644 --- a/muSRFitelec.js +++ b/muSRFitelec.js @@ -363,26 +363,20 @@ function electronGzipText(text) { .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } -function electronGunzipText(payload) { - if (nodeZlib) { - return nodeZlib.gunzipBase64URL(payload); - } - let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/"); - while (base64.length % 4) base64 += "="; - let zipped = require("buffer").Buffer.from(base64, "base64"); - return require("zlib").gunzipSync(zipped).toString("utf8"); -} - function encodeElectronSharedConfiguration(config) { return encodeSharedConfigurationLink(config, electronGzipText); } function decodeElectronSharedConfiguration(value) { - return decodeSharedConfigurationFragment(value, electronGunzipText); -} - -function electronShareBaseURL() { - return MUSRFLOW_CANONICAL_SHARE_URL; + return decodeSharedConfigurationFragment(value, function(payload) { + if (nodeZlib) { + return nodeZlib.gunzipBase64URL(payload); + } + let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/"); + while (base64.length % 4) base64 += "="; + let zipped = require("buffer").Buffer.from(base64, "base64"); + return require("zlib").gunzipSync(zipped).toString("utf8"); + }); } function electronWriteClipboard(url) { @@ -407,7 +401,7 @@ function electronWriteClipboard(url) { async function copyWebConfigurationLink() { return shareConfigurationLink({ - baseURL: electronShareBaseURL, + baseURL: function() { return MUSRFLOW_CANONICAL_SHARE_URL; }, writeClipboard: electronWriteClipboard, gzipText: electronGzipText }); @@ -521,13 +515,6 @@ async function restoreElectronSharedConfiguration() { return restored; } -// A deep link arriving through the main process follows exactly the same -// decode/restore path as the paste dialog, minus the dialog itself. -async function restoreElectronSharedURL(url) { - if (!url || typeof url !== "string") return false; - return restoreSharedConfigurationFromSource(url, null); -} - function selectWorkFolder() { let input = document.getElementById("workPath"); let currentPath = input ? input.value : "."; @@ -1536,29 +1523,28 @@ function portableRunResolver(subPath, dataPath) { } } -// Follow the conventional musrfit startup-file locations for this machine. A -// path the user configured in Preferences takes precedence. -function discoverLocalStartupXml() { - let configured = (typeof getConfiguredStartupXml === "function") - ? getConfiguredStartupXml() : ""; - if (configured && nodeFs.existsSync(configured)) return configured; - - let candidates = []; - let home = nodeProcess.env.HOME || ""; - if (home) candidates.push(nodePath.join(home, ".musrfit", "musrfit_startup.xml")); - candidates.push(nodePath.join(nodeProcess.cwd(), "musrfit_startup.xml")); - for (let i = 0; i < candidates.length; i++) { - if (nodeFs.existsSync(candidates[i])) return candidates[i]; - } - return ""; -} - function loadLocalPortableRunNaming() { if (typeof setPortableRunNaming !== "function" || typeof parseMusrfitStartupXML !== "function") { return ""; } - let startupPath = discoverLocalStartupXml(); + // Follow the conventional musrfit startup-file locations for this machine. A + // path the user configured in Preferences takes precedence. + let configured = (typeof getConfiguredStartupXml === "function") + ? getConfiguredStartupXml() : ""; + let startupPath = (configured && nodeFs.existsSync(configured)) ? configured : ""; + if (!startupPath) { + let candidates = []; + let home = nodeProcess.env.HOME || ""; + if (home) candidates.push(nodePath.join(home, ".musrfit", "musrfit_startup.xml")); + candidates.push(nodePath.join(nodeProcess.cwd(), "musrfit_startup.xml")); + for (let i = 0; i < candidates.length; i++) { + if (nodeFs.existsSync(candidates[i])) { + startupPath = candidates[i]; + break; + } + } + } let startup = null; if (startupPath) { try { @@ -1638,9 +1624,11 @@ function firstLoad() { electronIpcRenderer.on('openSharedConfiguration', function(sharedURL) { // A deep link (http(s)://.../muSRFlow/#c=... or a bare #c= fragment) - // restores immediately. With no URL the Share menu paste dialog opens. + // restores immediately, following exactly the same decode/restore path as + // the paste dialog minus the dialog itself. With no URL the Share menu + // paste dialog opens. if (sharedURL && typeof sharedURL === "string") { - return restoreElectronSharedURL(sharedURL); + return restoreSharedConfigurationFromSource(sharedURL, null); } openElectronSharedConfiguration(); }); diff --git a/muSRFitlib.js b/muSRFitlib.js index 808f549..907840c 100644 --- a/muSRFitlib.js +++ b/muSRFitlib.js @@ -66,17 +66,6 @@ function readSharedControlValue(element) { return element.value !== undefined ? String(element.value) : ""; } -function collectSharedControls(root) { - let values = {}; - if (!root || !root.querySelectorAll) return values; - for (let element of root.querySelectorAll("input[id], select[id]")) { - // Components are stored separately as an ordered theory-model list. - if (/^fitFunc\d+$/.test(element.id) || element.id === "numComps") continue; - values[element.id] = readSharedControlValue(element); - } - return values; -} - function collectSharedParameterControls() { let values = {}; let table = document.getElementById("Params"); @@ -130,7 +119,16 @@ function buildSharedConfiguration() { return { v: MUSRFLOW_SHARE_CONFIG_VERSION, - controls: collectSharedControls(document.getElementById("Runs")), + controls: (function(root) { + let values = {}; + if (!root || !root.querySelectorAll) return values; + for (let element of root.querySelectorAll("input[id], select[id]")) { + // Components are stored separately as an ordered theory-model list. + if (/^fitFunc\d+$/.test(element.id) || element.id === "numComps") continue; + values[element.id] = readSharedControlValue(element); + } + return values; + })(document.getElementById("Runs")), components: typeof getFitComponentValues === "function" ? getFitComponentValues() : [], parameters: collectSharedParameterControls(), customParameters: typeof customParams !== "undefined" ? customParams.slice() : [], @@ -206,23 +204,6 @@ function validateSharedConfiguration(config) { // inject only a gzip/gunzip text primitive (Node zlib through the preload bridge // in Electron, CompressionStream/DecompressionStream in the browser), so the // protocol itself is identical in both runtimes. -function bytesToBase64URL(bytes) { - let binary = ""; - const chunkSize = 0x8000; - for (let i = 0; i < bytes.length; i += chunkSize) { - binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize)); - } - return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - -function base64URLToBytes(text) { - text = String(text || "").replace(/-/g, "+").replace(/_/g, "/"); - while (text.length % 4) text += "="; - let binary = atob(text); - let bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); - return bytes; -} function parseSharedConfigurationFragment(value) { let input = String(value || "").trim(); @@ -2127,22 +2108,6 @@ async function discardSeriesTransactionStages(adapter, staged, errors) { } } -async function rollbackSeriesTransaction(adapter, receipts, errors) { - for (let index = receipts.length - 1; index >= 0; index--) { - let receipt = receipts[index]; - try { - await adapter.rollback(receipt); - } catch (error) { - errors.push({ - run: receipt.run || 0, - operation: "rollback", - path: receipt.targetPath || "", - message: seriesTransactionError(error, "could-not-rollback-promotion") - }); - } - } -} - // Persist an already validated batch as one filesystem transaction. Every // candidate is first written exclusively under a transaction-owned name and // read back byte-for-byte. Promotion starts only after the entire batch passes. @@ -2359,7 +2324,19 @@ async function stageAndPromoteSeriesMSRCandidates(prepared, adapter, options = { path: item.candidate.targetPath, message: seriesTransactionError(error, "could-not-promote-candidate") }); - await rollbackSeriesTransaction(adapter, receipts, result.rollbackErrors); + for (let index = receipts.length - 1; index >= 0; index--) { + let receipt = receipts[index]; + try { + await adapter.rollback(receipt); + } catch (rollbackError) { + result.rollbackErrors.push({ + run: receipt.run || 0, + operation: "rollback", + path: receipt.targetPath || "", + message: seriesTransactionError(rollbackError, "could-not-rollback-promotion") + }); + } + } await discardSeriesTransactionStages(adapter, staged, result.rollbackErrors); if (result.rollbackErrors.length > 0) result.reason = "promotion-rollback-failed"; return result; @@ -2487,26 +2464,6 @@ async function finalizeSeriesMSRTransaction(transaction, adapter, decision) { return result; } -function seriesRunResultSucceeded(runResult) { - if (!runResult || typeof runResult !== "object" - || (runResult.ok !== true && runResult.ok !== 1)) { - return false; - } - if (runResult.code !== undefined && runResult.code !== null - && Number(runResult.code) !== 0) { - return false; - } - if (runResult.signal) return false; - return !runResult.outcome || runResult.outcome == "success"; -} - -function seriesSequenceTransactionId(sequenceId, candidate, index) { - let suffix = "-" + (index + 1) + "-" + candidate.run; - return normalizeSeriesTransactionId( - sequenceId.substring(0, Math.max(1, 64 - suffix.length)) + suffix - ); -} - // Run prepared independent fits in strict sequence. Each candidate gets its // own transaction so a successfully committed prefix survives a later failure. // The injected runner is the only operation that may execute musrfit; this @@ -2560,10 +2517,14 @@ async function runPreparedSeriesFitSequence( for (let index = 0; index < prepared.candidates.length; index++) { let candidate = prepared.candidates[index]; + let suffix = "-" + (index + 1) + "-" + candidate.run; + let transactionId = normalizeSeriesTransactionId( + sequenceId.substring(0, Math.max(1, 64 - suffix.length)) + suffix + ); let transaction = await stageAndPromoteSeriesMSRCandidates( { ok: true, candidates: [candidate] }, transactionAdapter, - { transactionId: seriesSequenceTransactionId(sequenceId, candidate, index) } + { transactionId: transactionId } ); if (!transaction.ok) { result.reason = "series-candidate-staging-failed"; @@ -2609,7 +2570,15 @@ async function runPreparedSeriesFitSequence( }; } - if (!seriesRunResultSucceeded(runResult)) { + // A successful run must report ok and a zero exit code, with no signal and + // no explicit failure outcome. + let runSucceeded = runResult && typeof runResult === "object" + && (runResult.ok === true || runResult.ok === 1) + && (runResult.code === undefined || runResult.code === null + || Number(runResult.code) === 0) + && !runResult.signal + && (!runResult.outcome || runResult.outcome == "success"); + if (!runSucceeded) { let finalizationDecision = candidate.action == "fit" ? "retain" : "rollback"; let finalization = await finalizeSeriesMSRTransaction( transaction, transactionAdapter, finalizationDecision @@ -3558,13 +3527,6 @@ function isMSREditorSourceAuthoritative(source = window.MSREditor.activeSource) return state.sourceOfTruth == "editor" && state.locked; } -function isCurrentMSREditorAuthoritative() { - // The runnable/global document is authoritative only while it is the selected - // editor document. A selected template has its own independent lock state. - return window.MSREditor.activeSource == "current" - && isMSREditorSourceAuthoritative("current"); -} - function isActiveMSREditorAuthoritative() { return isMSREditorSourceAuthoritative(window.MSREditor.activeSource); } @@ -3585,13 +3547,6 @@ function setGlobalMSRStale(isStale) { updateMSREditorSourceTabs(); } -function lockMSREditorSource(source = window.MSREditor.activeSource) { - setMSREditorSourceOfTruth("editor", true, source); - if (source == "template" && window.MSREditor.hasTemplateTab) { - setGlobalMSRStale(true); - } -} - function unlockMSREditorSource() { let source = window.MSREditor.activeSource; setMSREditorSourceOfTruth("gui", false, source); @@ -3677,7 +3632,10 @@ function handleMSREditorInput() { && editorHash !== state.lastAcceptedHash) { // Manual editing transfers ownership only for the document being edited. // Editing a template also marks the downstream global file as stale. - lockMSREditorSource(source); + setMSREditorSourceOfTruth("editor", true, source); + if (source == "template" && window.MSREditor.hasTemplateTab) { + setGlobalMSRStale(true); + } } updateMSREditorSourceTabs(); } @@ -4392,10 +4350,6 @@ function applyImportedMSRParameterOrder(funSel) { for (let option of ordered) funSel.appendChild(option); } -function indexedTheoryParameterName(parameterName, componentIndex, componentCount) { - return componentCount > 1 ? parameterName + componentIndex : parameterName; -} - function theorySignature(theoryLines) { return theoryLines.map(function(line) { let parts = line.trim().split(/\s+/); @@ -4528,9 +4482,9 @@ function parseMSRTheoryModel(msrText) { let sourceParts = sourceLines[lineIndex].trim().split(/\s+/); let templateParts = match.lines[lineIndex].trim().split(/\s+/); for (let argumentIndex = 1; argumentIndex < sourceParts.length; argumentIndex++) { - let targetName = indexedTheoryParameterName( - templateParts[argumentIndex], componentIndex + 1, theoryComponents.length - ); + let targetName = theoryComponents.length > 1 + ? templateParts[argumentIndex] + (componentIndex + 1) + : templateParts[argumentIndex]; let reference = sourceParts[argumentIndex]; let referenceMatch = reference.match(/^(\d+|map(\d+)|fun(\d+))$/i); if (!referenceMatch) { @@ -4709,21 +4663,6 @@ function parseMSRTheoryModel(msrText) { return parsed; } -function appendCustomParameterOptions() { - let funSel = document.getElementById("funSel"); - if (!funSel) return; - let existing = new Set(); - for (let option of funSel.options) existing.add(option.value); - for (let parameterName of customParams) { - if (existing.has(parameterName)) continue; - let option = document.createElement("option"); - option.textContent = parameterName; - option.value = parameterName; - option.id = "fn" + parameterName; - funSel.appendChild(option); - } -} - function applyMSRTheoryModel(parsed, all = All) { if (!parsed || !parsed.ok || parsed.components.length === 0 || !all) return(0); markFitModelExplicit(); @@ -4753,7 +4692,18 @@ function applyMSRTheoryModel(parsed, all = All) { customParams = parsed.customParameters.slice(); funBlock.innerHTML = ""; updateTheoryBlock(); - appendCustomParameterOptions(); + { + let existing = new Set(); + for (let option of funSel.options) existing.add(option.value); + for (let parameterName of customParams) { + if (existing.has(parameterName)) continue; + let option = document.createElement("option"); + option.textContent = parameterName; + option.value = parameterName; + option.id = "fn" + parameterName; + funSel.appendChild(option); + } + } suppressSeriesGUIEditCapture = true; try { @@ -5332,35 +5282,30 @@ function normalizeMSRPlotRuns(msrText, all, runs) { const SERIES_MSR_RUN_PARAM_DIRECTIVES = { alpha: 1, norm: 1, "backgr.fit": 1, beta: 1 }; const SERIES_MSR_MAX_MAP_SLOTS = 10; -// Recognize a block header line. The FOURIER block uses a lowercase -// `plot ` directive that would otherwise look like a PLOT header, so a -// genuine PLOT header must carry a numeric plot id ("PLOT 2"); non-numeric -// `plot` lines stay inside FOURIER. -function seriesMSRBlockHeaderName(line) { - let match = line.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)(?:[ \t]|$)/i); - if (!match) return null; - let name = match[1].toUpperCase(); - if (name === "PLOT") { - let arg = line.slice(match[0].length).trim(); - if (!/^\d/.test(arg)) return null; - } - return name; -} - function splitSeriesMSRBlocks(msrText) { let sections = []; let current = null; let lines = String(msrText || "").split(/\r?\n/); - for (let line of lines) { - let name = seriesMSRBlockHeaderName(line.trim()); - if (name) { - current = { - name: name, - header: line.trim(), - lines: [] - }; - sections.push(current); - } else if (current) { +for (let line of lines) { + // Recognize a block header line. The FOURIER block uses a lowercase + // `plot ` directive that would otherwise look like a PLOT header, so + // a genuine PLOT header must carry a numeric plot id ("PLOT 2"); + // non-numeric `plot` lines stay inside FOURIER. + let trimmedLine = line.trim(); + let match = trimmedLine.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)(?:[ \t]|$)/i); + let name = match ? match[1].toUpperCase() : null; + if (name === "PLOT") { + let arg = trimmedLine.slice(match[0].length).trim(); + if (!/^\d/.test(arg)) name = null; + } + if (name) { + current = { + name: name, + header: trimmedLine, + lines: [] + }; + sections.push(current); + } else if (current) { current.lines.push(line); } else { if (!sections.length) { @@ -5373,36 +5318,6 @@ function splitSeriesMSRBlocks(msrText) { return sections; } -function parseSeriesMSRParameters(lines) { - let params = []; - for (let line of lines) { - let trimmed = String(line).trim(); - if (!trimmed || trimmed.charAt(0) === "#") continue; - let match = trimmed.match(/^(\d+)\s+(\S+)\s*(.*)$/); - if (!match) continue; - params.push({ - no: parseInt(match[1], 10), - name: match[2], - rest: match[3].trim().split(/\s+/).join(" ") - }); - } - return params; -} - -function parseSeriesMSRRunBlocks(lines) { - let blocks = []; - let current = null; - for (let line of lines) { - if (/^RUN\b/i.test(String(line).trim())) { - current = { header: line, lines: [] }; - blocks.push(current); - } else if (current) { - current.lines.push(line); - } - } - return blocks; -} - // Detach every THEORY/FUNCTIONS integer that refers to a fit parameter. Falls // back to carrying the current per-run text through for anything that is not a // simple parameter reference. Returns { ok, lines } and a lookup for the merged @@ -5503,13 +5418,33 @@ function buildSeriesGlobalMSR(msrTexts, runs) { if (!byName.FITPARAMETER || !byName.THEORY || !byName.RUN) { return fail("series-merge-source-incomplete"); } - let params = parseSeriesMSRParameters(byName.FITPARAMETER.lines); + let params = []; + for (let line of byName.FITPARAMETER.lines) { + let trimmed = String(line).trim(); + if (!trimmed || trimmed.charAt(0) === "#") continue; + let match = trimmed.match(/^(\d+)\s+(\S+)\s*(.*)$/); + if (!match) continue; + params.push({ + no: parseInt(match[1], 10), + name: match[2], + rest: match[3].trim().split(/\s+/).join(" ") + }); + } if (params.length === 0) { return fail("series-merge-parameters-incomplete"); } - let runBlocks = parseSeriesMSRRunBlocks( - [byName.RUN.header].concat(byName.RUN.lines) - ); + let runBlocks = []; + { + let current = null; + for (let line of [byName.RUN.header].concat(byName.RUN.lines)) { + if (/^RUN\b/i.test(String(line).trim())) { + current = { header: line, lines: [] }; + runBlocks.push(current); + } else if (current) { + current.lines.push(line); + } + } + } if (runBlocks.length === 0) { return fail("series-merge-run-blocks-incomplete"); } @@ -6627,7 +6562,19 @@ function renderFitComponents(values) remove.title = "Remove component " + componentNo; remove.setAttribute("aria-label", remove.title); remove.addEventListener("click", function() { - removeFitComponent(componentNo); + let countInput = document.getElementById("numComps"); + if (!countInput) return; + + // Preserve the remaining model choices when removing a middle component, + // then renumber them densely so downstream code can continue using + // fitFunc1..N. + let fitFuncs = getFitComponentValues(); + if (fitFuncs.length <= 1 || componentNo < 2 || componentNo > fitFuncs.length) return; + markFitModelExplicit(); + fitFuncs.splice(componentNo - 1, 1); + countInput.value = String(fitFuncs.length); + renderFitComponents(fitFuncs); + clearTabs(true); }); row.appendChild(remove); } @@ -6668,22 +6615,6 @@ function addFitComponent() clearTabs(true); } -function removeFitComponent(componentNo) -{ - let countInput = document.getElementById("numComps"); - if (!countInput) return; - - // Preserve the remaining model choices when removing a middle component, then - // renumber them densely so downstream code can continue using fitFunc1..N. - let fitFuncs = getFitComponentValues(); - if (fitFuncs.length <= 1 || componentNo < 2 || componentNo > fitFuncs.length) return; - markFitModelExplicit(); - fitFuncs.splice(componentNo - 1, 1); - countInput.value = String(fitFuncs.length); - renderFitComponents(fitFuncs); - clearTabs(true); -} - // Deployment mode is a platform fact registered by muSRFitelec.js / // muSRFitweb.js at load time, not a property to sniff from the user agent or // module globals. The heuristic below only covers embedded or test contexts @@ -6730,22 +6661,17 @@ function platformCurrentDirectory() { return "."; } -// Quick Start is one guide for the whole application. The active tab only -// determines which section is brought into view when the user opens it. -function quickStartSectionForTab(tabName) { - let sections = { +function showQuickStartHelp() { + // Quick Start is one guide for the whole application. The active tab only + // determines which section is brought into view when the user opens it. + let sectionId = ({ Runs: "helpRuns", Params: "helpParams", Functions: "helpConstraints", t0Bg: "helpT0Bg", Editor: "helpEditor", Jobs: "helpResults" - }; - return sections[tabName] || "helpRuns"; -} - -function showQuickStartHelp() { - let sectionId = quickStartSectionForTab(window.muSRFlowActiveTab || "Runs"); + })[window.muSRFlowActiveTab || "Runs"] || "helpRuns"; // Electron uses the same auxiliary-window request path as parameter plots. // This helper exists only in the Electron renderer, so do not rely on the @@ -8369,12 +8295,6 @@ function formatInitialParameterGuess(value) { return Number(Number(value).toPrecision(9)).toString(); } -function initialParameterGuessEnabled() { - let input = typeof document !== "undefined" - ? document.getElementById("guessInitialParameters") : null; - return input ? input.checked : true; -} - function setConfiguredInitialParameterGuess(enabled, persist) { let value = Boolean(enabled); let input = typeof document !== "undefined" @@ -8736,18 +8656,6 @@ function collectSeriesActionOverrides() { // These helpers mark edited data sets and force the next plan to rebuild them // from the GUI. The marker clears once a refit successfully rebuilds the run. -function seriesEditedRunNumbers() { - let source = ""; - if (typeof document !== "undefined" && document.getElementById) { - let input = document.getElementById("runNumbers"); - if (input && input.value) source = input.value; - } - if (source === "") source = All.runNumbers || ""; - let runs = []; - for (let dataSet of parseRunSelection(source)) runs.push(dataSet.main); - return Array.from(new Set(runs)); -} - function setSeriesActionChipAction(run, action) { if (typeof document === "undefined") return; if (action != "reuse" && action != "refit" && action != "skip") return; @@ -8772,7 +8680,17 @@ function markSeriesRunParametersEdited(run) { } function markAllCurrentSeriesRunsEdited() { - for (let run of seriesEditedRunNumbers()) markSeriesRunParametersEdited(run); + // Read the currently selected run numbers so every edited data set is forced + // to rebuild on the next series plan. + let source = ""; + if (typeof document !== "undefined" && document.getElementById) { + let input = document.getElementById("runNumbers"); + if (input && input.value) source = input.value; + } + if (source === "") source = All.runNumbers || ""; + let runs = []; + for (let dataSet of parseRunSelection(source)) runs.push(dataSet.main); + for (let run of Array.from(new Set(runs))) markSeriesRunParametersEdited(run); } // The chip row mirrors the last committed selection: each chip carries its data @@ -8948,7 +8866,9 @@ function scheduleInitialParameterGuess() { let components = getFitComponentValues(); let canSelectAutomaticModel = automaticInitialFitModel && components.length == 1 && ["Exponential", "ExponentialCos"].includes(components[0]); - if (!initialParameterGuessEnabled() + let guessInput = typeof document !== "undefined" + ? document.getElementById("guessInitialParameters") : null; + if ((guessInput ? guessInput.checked : true) === false || (targets.length == 0 && !canSelectAutomaticModel)) { return Promise.resolve(false); } @@ -9688,24 +9608,6 @@ function replaceWord(str, word, replacement) { return str.replace(regex, replacement); } -function isSingleHistTheoryPhaseParameter(parName) { - // GUI component indexing turns Phi into Phi1, Phi2, ... for multi-component - // models. Histogram-specific copies add H and therefore deliberately do - // not match here; only the phase placeholder that appears in THEORY gets a - // map slot. - return /^Phi(?:\d+)?$/.test(parName); -} - -function singleHistPhaseParameterForHistogram(baseName, histogramIndex) { - // The first histogram keeps the normal model parameter name. Additional - // detector groups get explicit phase copies that are selected through RUN - // maps. This mirrors the native musrfit single-histogram mapping mechanism. - if (histogramIndex <= 1) { - return baseName; - } - return baseName + "H" + histogramIndex; -} - function buildModelBlocks(config, fitType) { let all = config.all || {}; let funOptions = config.funOptions || []; @@ -9810,7 +9712,7 @@ function buildModelBlocks(config, fitType) { let shPar = runs.length > 1 && !!sharedFlags[parName]; let singleHistPhase = all.fitAsyType == "SingleHist" - && isSingleHistTheoryPhaseParameter(parName) + && /^Phi(?:\d+)?$/.test(parName) && new RegExp("\\b" + parName + "\\b").test(theoryBlk); if (singleHistPhase) { // THEORY/FUNCTIONS must not point directly at the first detector's phase. @@ -9881,7 +9783,10 @@ function buildModelBlocks(config, fitType) { let mapValues = []; if (singleHistPhaseMaps.length > 0) { for (let phaseMap of singleHistPhaseMaps) { - let phaseName = singleHistPhaseParameterForHistogram(phaseMap.baseName, iHist); + // The first histogram keeps the normal model parameter name; additional + // detector groups get explicit phase copies selected through RUN maps. + let phaseName = iHist <= 1 ? phaseMap.baseName + : phaseMap.baseName + "H" + iHist; // Older/incomplete GUI state may not yet contain the extra detector // phase. Reusing the first phase keeps the generated MSR valid; a normal // constraints refresh creates the explicit PhiH parameter. @@ -10984,9 +10889,13 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { : runs[0] + fileNameSuffix + ".msr"; let finalPath = workPath + "/" + finalMSR; - if (isCurrentMSREditorAuthoritative()) { - // A manually edited runnable/global MSR is used verbatim. Keep any template - // document beside it; editing the global file must not erase template work. + // The runnable/global document is authoritative only while it is the + // selected editor document. A selected template has its own independent + // lock state, so check both. A manually edited runnable/global MSR is then + // used verbatim; keep any template document beside it, since editing the + // global file must not erase template work. + if (window.MSREditor.activeSource == "current" + && isMSREditorSourceAuthoritative("current")) { let editorMSR = getCurrentEditorText(); if (!editorMSR || editorMSR.trim() === "") { setFitStatus("The active editor is empty.", { diff --git a/muSRFitweb.js b/muSRFitweb.js index 5e9e9db..62a5928 100644 --- a/muSRFitweb.js +++ b/muSRFitweb.js @@ -325,17 +325,12 @@ async function gzipWebSharedText(text) { let bytes = new TextEncoder().encode(text); let response = new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip"))); let zipped = new Uint8Array(await response.arrayBuffer()); - return bytesToBase64URL(zipped); -} - -async function gunzipWebSharedText(payload) { - if (typeof DecompressionStream !== "function") { - throw new Error("this browser cannot decompress shared configurations"); + let binary = ""; + const chunkSize = 0x8000; + for (let i = 0; i < zipped.length; i += chunkSize) { + binary += String.fromCharCode.apply(null, zipped.subarray(i, i + chunkSize)); } - let bytes = base64URLToBytes(payload); - let response = new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"))); - let out = new Uint8Array(await response.arrayBuffer()); - return new TextDecoder().decode(out); + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } async function encodeWebSharedConfiguration(config) { @@ -343,29 +338,37 @@ async function encodeWebSharedConfiguration(config) { } async function decodeWebSharedConfiguration(value) { - return decodeSharedConfigurationFragment(value, gunzipWebSharedText); -} - -function webShareBaseURL() { - let location = window.location || {}; - let origin = location.origin && location.origin !== "null" ? location.origin : ""; - return origin + (location.pathname || "/"); -} - -async function webWriteClipboard(url) { - if (typeof navigator !== "undefined" && navigator.clipboard - && typeof navigator.clipboard.writeText === "function") { - await navigator.clipboard.writeText(url); - } else { - throw new Error("clipboard API unavailable"); - } + return decodeSharedConfigurationFragment(value, async function(payload) { + if (typeof DecompressionStream !== "function") { + throw new Error("this browser cannot decompress shared configurations"); + } + let text = String(payload || "").replace(/-/g, "+").replace(/_/g, "/"); + while (text.length % 4) text += "="; + let binary = atob(text); + let bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + let response = new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"))); + let out = new Uint8Array(await response.arrayBuffer()); + return new TextDecoder().decode(out); + }); } async function copyWebConfigurationLink() { if (typeof amIWeb === "function" && !amIWeb()) return false; return shareConfigurationLink({ - baseURL: webShareBaseURL, - writeClipboard: webWriteClipboard, + baseURL: function() { + let location = window.location || {}; + let origin = location.origin && location.origin !== "null" ? location.origin : ""; + return origin + (location.pathname || "/"); + }, + writeClipboard: async function(url) { + if (typeof navigator !== "undefined" && navigator.clipboard + && typeof navigator.clipboard.writeText === "function") { + await navigator.clipboard.writeText(url); + } else { + throw new Error("clipboard API unavailable"); + } + }, gzipText: gzipWebSharedText }); } @@ -519,18 +522,6 @@ async function triggerWebURLAction(result) { return await startPlot(); } -function clearWebStartupURLParameters() { - // Query parameters and shared-configuration fragments are one-shot startup - // input. Once copied into GUI state, remove both without reloading. - if (typeof window === "undefined" || !window.location || !window.history - || typeof window.history.replaceState !== "function") { - return; - } - - let cleanURL = window.location.pathname || ""; - window.history.replaceState({}, "", cleanURL || "/"); -} - async function initializeWebURLParameters() { // Capture one-shot startup input, then clean the address bar immediately. // Shared configuration decoding can continue asynchronously afterwards. @@ -540,7 +531,13 @@ async function initializeWebURLParameters() { let hasSharedConfiguration = hash.startsWith("#c=") || hash.startsWith("#cfg="); if (window.location && (window.location.search || hasSharedConfiguration)) { - clearWebStartupURLParameters(); + // Query parameters and shared-configuration fragments are one-shot startup + // input. Once copied into GUI state, remove both without reloading. + if (typeof window !== "undefined" && window.location && window.history + && typeof window.history.replaceState === "function") { + let cleanURL = window.location.pathname || ""; + window.history.replaceState({}, "", cleanURL || "/"); + } } // Only recognized configuration fragments are decoded. Any other hash is diff --git a/parameter-plot-window.js b/parameter-plot-window.js index 272d29f..1741e11 100644 --- a/parameter-plot-window.js +++ b/parameter-plot-window.js @@ -19,12 +19,11 @@ window.MusrfitParameterPlotPlatform.createPlotWindow = function() { const closeHandlers = []; let closed = false; - function runCloseHandlers() { + window.addEventListener("beforeunload", function() { if (closed) return; closed = true; for (const handler of closeHandlers) handler(); - } - window.addEventListener("beforeunload", runCloseHandlers, { once: true }); + }, { once: true }); return { root: document.body, @@ -41,7 +40,7 @@ window.MusrfitParameterPlotPlatform.createPlotWindow = function() { // The bridge delivers only the payload (no event wrapper); legacy ipcRenderer // passes the event first. Normalize so both call shapes hand options to the // shared renderer unchanged. -function onParameterPlotData() { +ipcRenderer.on("parameterPlotData", function() { let options = (arguments.length > 0 && arguments[0] && arguments[0].sender) ? arguments[1] : arguments[0]; options = options || {}; @@ -55,5 +54,4 @@ function onParameterPlotData() { options.preferredLayoutMode || "", options.savedState || null ); -} -ipcRenderer.on("parameterPlotData", onParameterPlotData); +}); diff --git a/preload.js b/preload.js index 08aef58..2dd335f 100644 --- a/preload.js +++ b/preload.js @@ -55,19 +55,6 @@ function toText(value) { return Buffer.isBuffer(value) ? value.toString() : (value == null ? "" : String(value)); } -// Normalize a synchronous child-process result into a plain object that the -// renderer shim turns back into the familiar spawnSync shape. -function normalizeSyncResult(result) { - return { - pid: result && typeof result.pid === "number" ? result.pid : null, - status: result && typeof result.status === "number" ? result.status : null, - signal: result ? (result.signal || null) : null, - stdout: result ? toText(result.stdout) : "", - stderr: result ? toText(result.stderr) : "", - error: result && result.error ? (result.error.message || String(result.error)) : null - }; -} - // Handles for running child processes, keyed by a caller-supplied job token. // The renderer keeps the token for the last launched job, so an Abort action // can target exactly that job without ever exposing PIDs into the page. @@ -207,7 +194,16 @@ readFile: function (p, encoding, callback) { } catch (err) { return { pid: null, status: null, signal: null, stdout: "", stderr: "", error: err.message || String(err) }; } - return normalizeSyncResult(result); + // Normalize the synchronous child-process result into a plain object + // that the renderer shim turns back into the familiar spawnSync shape. + return { + pid: result && typeof result.pid === "number" ? result.pid : null, + status: result && typeof result.status === "number" ? result.status : null, + signal: result ? (result.signal || null) : null, + stdout: result ? toText(result.stdout) : "", + stderr: result ? toText(result.stderr) : "", + error: result && result.error ? (result.error.message || String(result.error)) : null + }; }, spawnCapture: function (command, args, options, onChunk) { return new Promise(function (resolve) {