import * as common from "./common.js"; // // Snippet configuration. // // Each snippet defines a `generate(params)` function that returns the python // code for a set of parameter values, and a `parameters` list that describes // the form fields to render. `generate` is the single source of truth used for // both the live preview and the final submit. // // Parameter fields: name, id, type (number|text|select|checkbox|odb_browse| // loop_values), default, unit, options (for select, is either a list of value // + label or a function that generates the list), odbBase (for odb_browse), // forvar/from/step/to (name of loop variable, and default range). // // Parameter definitions shared by several snippets. Do not mutate! export const shared_args = { stats: { name: "Stats", id: "stats", type: "number", default: "30e6", unit: "Events", }, detector: { name: "Detector", id: "detectorVal", type: "select", optional: true, options: () => mjsonrpc_db_get_value("/Equipment/TDC/Histograms/Name").then((rpc) => rpc.result.data[0].map(item => ({ value: item, label: item }))), }, stable_for: { name: "Stable for", id: "stable_for", type: "number", optional: true, unit: "s", }, timeout: { name: "Timeout", id: "timeout", type: "number", optional: true, unit: "s", }, magnet: { name: "Magnet", id: "magnetVal", type: "select", optional: true, options: [{ value: "gossen", label: "GOSSEN" }, { value: "helm", label: "HELM" }, ], }, }; export function py_kw(name, value, quote = false) { if (value === undefined || value === null || value === "" || value === false) { return ""; } return `, ${name}=${quote ? `"${value}"` : value}`; } // // Python Formatting // const _original_mslDefs_groups = Object.getOwnPropertyDescriptor(mslDefs, 'groups').get; function add_extra_python_keywords(instrument) { const lower = instrument.toLowerCase(); const upper = instrument.toUpperCase(); Object.defineProperty(mslDefs, 'groups', { get() { const groups = _original_mslDefs_groups.call(this); groups.instrumentKeywords = { keywords: ["exp", upper, lower, "seq"], kwregex: ["\\b(", ")\\b", "g"], color: "#026875", // dark cyan mslclass: `msl_${lower}` }; return groups; } }); } function header_injector(instrument) { const instrument_lower = instrument.toLowerCase(); const instrument_upper = instrument.toUpperCase(); return (btn) => { const result = _sequencerjs_addETab(btn); // call original new tab // inject header: //get active tab: const tab = document.querySelectorAll(".edt_active")[0]; const tabID = tab.id.replace("-btn", ""); if (tabID === "etab1") { return result; //nothing to do } let textarea = document.getElementById(tabID).getElementsByClassName("edt_area")[0]; if (textarea.textContent.trim() === '') { const banner = ' ' + '#'.repeat(89) + '\n'; textarea.textContent = `from ${instrument_lower} import ${instrument_upper}\n` + `def sequence(seq):\n` + ` exp = ${instrument_upper}(seq)\n` + banner + ` #Do not modify above this line\n` + banner + ` `; let currText = textarea.innerText; let caretPos = textarea.innerText.length; // save current revision for undo saveState(currText, textarea); textarea.innerHTML = syntax_msl(currText).join(lc).slice(0, -1); setCurrentCursorPosition(textarea, caretPos); updateLineNumbers(textarea.previousElementSibling, textarea); } return result; }; } // // Snippet Lookup Table // const snippet_defs = {}; // Flatten the grouped config into a single id -> definition lookup. function build_snippet_def_lookup(pysequencer_config) { for (const _snippets of Object.values(pysequencer_config)) { for (const [id, def] of Object.entries(_snippets)) { if (id in snippet_defs) { console.error(`Duplicate key ${id} in Pysequencer Config`); } else { snippet_defs[id] = def; } } } } function get_snippet_def(id) { return snippet_defs[id]; } // // HTML Generators // function html_attr(v) { if (v === undefined || v === null) { return ""; } return String(v).replace(/&/g, "&").replace(/"/g, """); } function generate_snippets_dialogue(config) { const html = []; html.push(``); for (const [title, snippets] of Object.entries(config)) { html.push(``); for (const [id, props] of Object.entries(snippets)) { html.push(``); } } html.push(``); html.push(`
${title}
`); html.push(``); html.push(`
`); html.push(` Enable Pop-Up`); html.push(`
`); return html.join("\n"); } // Read the current values of every form control into a { id: value } map. function collect_form_params(container) { const params = {}; for (const el of container.querySelectorAll(".prompPar")) { params[el.id] = (el.type === "checkbox") ? el.checked : el.value; } return params; } // Default parameter map for a snippet function snippet_defaults(def) { const defaults = {}; for (const par of def.parameters) { if (par.type === "loop_values") { defaults[`${par.id}_from`] = par.from; defaults[`${par.id}_step`] = par.step; defaults[`${par.id}_to`] = par.to; defaults[`${par.id}_list`] = ""; } else { defaults[par.id] = (par.default !== undefined) ? par.default : ""; } } return defaults; } // Produce the correctly indented python text for a snippet. function snippet_text(def, params, indent = '') { return def.generate(params).split('\n').map(line => line.length ? indent + line : line).join('\n'); } function update_snippet_preview(def) { const container = document.getElementById("popHTML"); const preview = document.getElementById("textBlock"); if (!preview) { return; } preview.textContent = snippet_text(def, collect_form_params(container)); } // Expand "from:step:to" into a list of values, excluding the endpoint. function expand_range(from, step, to) { let adjustedStep = step; if ((from > to && step > 0) || (from < to && step < 0)) { adjustedStep = -step; } const values = [from]; if (adjustedStep == 0) { return values; } let current = from; while (1 + (current - to) / adjustedStep < 0) { current = Math.round((current + adjustedStep) * 100) / 100; values.push(current); } return values; } // Build the python list literal for a loop_values parameter: the explicit // comma-separated list wins over the from:step:to triple. export function loop_values_list(p, id_base) { const list = (p[`${id_base}_list`] || "").trim(); if (list) { const items = list.split(",").map(s => s.trim()).filter(s => s.length).map(Number); return `[${items.join(", ")}]`; } const from = parseFloat(p[`${id_base}_from`]); const step = parseFloat(p[`${id_base}_step`]); const to = parseFloat(p[`${id_base}_to`]); if (isNaN(from) && isNaN(step) && isNaN(to)) { return "[]"; } const values = expand_range(isNaN(from) ? 0 : from, isNaN(step) ? 1 : step, isNaN(to) ? 0 : to); return `[${values.join(", ")}]`; } // When the user types into one loop-values input, clear the other one so only // one of "from:step:to" / "list" is active at a time. function wire_loop_values(container) { const groups = {}; for (const el of container.querySelectorAll("[data-loopbase]")) { const base = el.dataset.loopbase; if (!groups[base]) { groups[base] = []; } groups[base].push(el); } for (const [base, els] of Object.entries(groups)) { for (const el of els) { el.addEventListener("input", () => { if (!el.value) { return; } const kind = el.dataset.loopkind; for (const other of els) { if (other.dataset.loopkind !== kind) { other.value = ""; } } }); } } } // For the input table and generated code boxes const card_style = 'width:95%;margin:0 auto;border:2px solid black;background-color:#fafafa;border-radius:8px;padding:10px;'; // Build the form rows for a snippet from its parameter list. async function build_snippet_form(def) { const rows = []; rows.push(`
`); for (const par of def.parameters) { const defv = html_attr(par.default); let control; let cellTail = ""; if (par.type === "select") { control = `"; } else if (par.type === "number") { const step = par.step ? ` step='${par.step}'` : ""; cellTail = par.unit ? ` ${par.unit}` : ""; control = ``; } else if (par.type === "checkbox") { const checked = par.default ? " checked" : ""; control = ``; } else if (par.type === "loop_values") { const base = html_attr(par.id); const unit = html_attr(par.unit); const triple = (id, value) => ``; rows.push(``); rows.push(``); rows.push(``); rows.push(``); continue; } else if (par.type === "odb_browse") { const base = html_attr(par.odbBase); const defval = html_attr(par.default); control = ``; } else { // text control = ``; rows.push(``); continue; } rows.push(``); } return rows.join(""); } // Insert block into autorun async function insert_seq_block(element, editor) { const def = get_snippet_def(element.id); if (!def) { return; } // determine current line's indentation const caretPos = getCurrentCursorPosition(editor); const textBefore = editor.innerText.substring(0, caretPos); const currentLine = textBefore.split('\n').pop(); const indent = currentLine.match(/^(\s*)/)[1]; const enablePop = document.getElementById("enablePop").checked; const defaults = snippet_defaults(def); const text = snippet_text(def, defaults); const newNode = document.createElement("pre"); newNode.id = "tmpID"; // Insert at the current cursor position, which must be inside the editor editor.focus(); const sel = document.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0) : null; if (!range || !editor.contains(range.startContainer)) { alert("Cursor must be in the editing area!"); return; } range.deleteContents(); range.insertNode(newNode); if (enablePop) { const modal_id = "pysequencer__popPrompt"; const d = common.populate_modal(modal_id); const popHTML = document.getElementById("popHTML"); // Let the modal grow with the form (instead of the fixed 35em) while // still keeping the preview visible via scrolling. Object.assign(popHTML.style, { height: "auto", maxHeight: "68vh", overflow: "auto" }); newNode.innerHTML = "
preparing ....
"; popHTML.innerHTML = await build_snippet_form(def) + `
${par.name} range${unit ? ` (${unit})` : ""}:
${triple("from", par.from)}${triple("step", par.step)}${triple("to", par.to)}
or raw list:
${par.name}:${control}
${par.name}:${control}${cellTail}

Generated Code:
` +
            text +
            "

"; for (const evt of ["input", "change"]) { popHTML.addEventListener(evt, () => update_snippet_preview(def)); } wire_loop_values(popHTML); // Write the block into the editor first, then close the modal and // re-highlight. const popButton = document.getElementById("popButton"); popButton.textContent = "Submit"; popButton.addEventListener("click", () => { const output = document.getElementById("tmpID"); output.innerHTML = snippet_text(def, collect_form_params(popHTML), indent); output.removeAttribute("id"); common.close_modal(modal_id); check_syntax(); }); const observer = new MutationObserver(() => { let preparing = document.getElementById("preparing"); if (preparing) preparing.remove(); }); observer.observe(d, { attributes: true }); } else { // TODO this function doesn't seem to exist // text = subLARDefaults(text); newNode.innerHTML = text; check_syntax(); } } async function insert_snippet(element) { const [lineNumbers, editor, label, btn] = editorElements(); if (btn.id === "etab1-btn") { // Not editor ignore dlgAlert("You are in the console, please switch to an editor tab."); } else { await insert_seq_block(element, editor); } } // // Snippet dialog // let seqSnippetsDlg; let seqSnippetsHTML; function ensure_seq_snip_dialog() { if (seqSnippetsDlg && document.body.contains(seqSnippetsDlg)) { return seqSnippetsDlg; } if (typeof dlgGeneral !== "function") { return null; } // Build the dialog lazily from the shared snippet HTML the first time it is needed. seqSnippetsDlg = dlgGeneral({ html: seqSnippetsHTML, iddiv: "pysequencer__snippets", width: 170, x: window.innerWidth - 260, y: 100, title: "Snippets" }); seqSnippetsDlg.shouldDestroy = false; // Keep the snippets window out of the standard dialog cascade so // file pickers and other transient dialogs are positioned normally. seqSnippetsDlg.classList.remove("dlgFrame"); seqSnippetsDlg.className = "dlgProgress"; // Add the click events for each button in the snippets form document.querySelectorAll('#pysequencer__snippets .mbutton').forEach( button => button.addEventListener("click", () => insert_snippet(button))); // This dialog is divorced from the shared dlgFrame lifecycle, so its close // button must hide it locally instead of going through dlgClose(). const closeBtnWrap = seqSnippetsDlg.querySelector("#cvsClose")?.parentElement; if (closeBtnWrap) { closeBtnWrap.removeAttribute("onclick"); closeBtnWrap.addEventListener("click", function(event) { event.preventDefault(); const checkbox = document.getElementById("pysequencer__show_seq_snip"); seqSnippetsDlg.style.display = "none"; if (checkbox) { checkbox.checked = false; } }); } return seqSnippetsDlg; } function is_seq_snip_host_visible() { const seqTable = document.getElementById("seqTable"); if (!seqTable) { return false; } const parentTab = seqTable.closest(".tabcontent"); if (!parentTab) { return true; } return parentTab.classList.contains("active"); } function sync_seq_snip_visibility() { const dlg = ensure_seq_snip_dialog(); if (!dlg) { return; } const checkbox = document.getElementById("pysequencer__show_seq_snip"); const visible = (checkbox ? checkbox.checked : true) && is_seq_snip_host_visible(); dlg.style.display = visible ? "block" : "none"; if (visible) { dlg.style.zIndex = "31"; } } function show_seq_snip() { sync_seq_snip_visibility(); } // Keep a single persistent snippets dialog for both standalone and embedded editors. let seqSnipOpenTabWrapped = false; function hook_seq_snip_tab_visibility() { // TODO can also maybe move if (seqSnipOpenTabWrapped || typeof openTab !== "function") { return; } const originalOpenTab = openTab; openTab = function(evt, tab) { const result = originalOpenTab.apply(this, arguments); sync_seq_snip_visibility(); return result; }; seqSnipOpenTabWrapped = true; } // // Sequencer // function check_syntax() { const [lineNumbers, editor] = editorElements(); const seqLines = editor.innerText; editor.innerHTML = syntax_msl(seqLines).join(lc); updateLineNumbers(editor.previousElementSibling, editor); } // Check the checkbox with the given id when a truthy value was saved for it. function restore_check(id) { const el = document.getElementById(id); if (el && localStorage.getItem(id)) { el.checked = true; } } const _sequencerjs_addETab = addETab; // Expects a checkbox element with the id "pysequencer__show_seq_snip" for // showing/hiding the snippets form. // // // // // export function initialise_sequencer(seq_base_path, instrument, pysequencer_config) { // This global currently needs to be overriden so that the many Pysequencer // functions work correctly window.SeqODB = seq_base_path; add_extra_python_keywords(instrument); // Inject header window.addETab = header_injector(instrument); build_snippet_def_lookup(pysequencer_config); seqSnippetsHTML = generate_snippets_dialogue(pysequencer_config); // Check whether the sequencer is running if (seq_base_path === "/PySequencer") { checkPyProgram(); } else { checkProgram(); } // Update CSS seqCSS(); //initialize snippets show_seq_snip(); // Check possible wrong path mjsonrpc_db_get_values([`${seq_base_path}/State/Path`]).then(function(rpc) { let path = rpc.result.data[0]; if (path && path.includes("userfiles/sequencer")) { dlgAlert(`The path in ${seq_base_path}/State/Path should be relative to (exp)/userfiles/sequencer.
Please make sure you set the correct path.
$SeqODB/State/Path = `); } }).catch(function(error) { mjsonrpc_error_alert(error); }); // Progress modal let progressDiv = `
`; const d = dlgGeneral({ html: progressDiv, iddiv: "Progress", width: 300, height: 80, x: document.documentElement.clientWidth - 320, y: document.documentElement.clientHeight - 100 }); dlgHide(d); d.shouldDestroy = false; // divorce fropm standard dialogs d.classList.remove("dlgFrame"); d.className = "dlgProgress"; // Check show progress bars const progressBars = document.getElementById("showProgressBars"); restore_check("showProgressBars"); let closeBtn = d.querySelector("#cvsClose").parentElement; closeBtn.removeEventListener("click", dlgClose); closeBtn.addEventListener("click", function() { localStorage.setItem("showProgressBars", false); progressBars.checked = false; dlgHide(d); }); // Check open in new tab restore_check("inNewTab"); // Check background color const lToDcheck = document.getElementById("darkMode"); restore_check("darkMode"); lightToDark(lToDcheck); // Check follow current line restore_check("scrollToCurr"); // seqState and updateBtns are defined in core MIDAS resources/sequencer.js seqState(updateBtns); window.addEventListener("resize", windowResize); // Check whether a sequence is running and adjust variables accordingly const showParTablecheck = document.getElementById("showParTable"); restore_check("showParTable"); mjsonrpc_db_get_values([`${seq_base_path}/State/Running`]).then(function(rpc) { if (rpc.result.data[0] && showParTablecheck.checked) { showParTable('varContainer'); } }).catch(function(error) { console.error(error); }); const [lineNumbers, editor] = editorElements(); const seqTable = document.getElementById("seqTable"); // Synchronize the scroll position of lineNumbers with editor in main tab editor.addEventListener('scroll', function() { lineNumbers.scrollTop = editor.scrollTop; }); editor.addEventListener("input", function() { updateLineNumbers(lineNumbers, editor); }); // adjust size when resizing editor (only main tab) const resizeObs = new ResizeObserver(() => { lineNumbers.style.height = editor.style.height; }); resizeObs.observe(editor); windowResize(); openETab(); // Short cuts have to be attached to window window.addEventListener("keydown", shortCutEvent); // maybe this should be on load instead of on DOMContentLoaded hook_seq_snip_tab_visibility(); document.getElementById("pysequencer__show_seq_snip").addEventListener("change", show_seq_snip); // This will be needed to refresh modb... document.title = `${instrument.toUpperCase()} PySequencer`; }