diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 763b098..3c46699 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -45,6 +45,7 @@ QuantUI/ │ ├── app_structure_edit.py ← Edit Structure tools (set bond/angle/dihedral, delete atoms…) │ ├── app_measurement.py ← click-to-measure distances/angles in the viewer │ ├── app_pes_pick.py ← pick PES-scan atoms in the viewer +│ ├── app_pick_mode.py ← workspace viewer pick mode (measure / edit structure / pick scan atoms) │ ├── app_xyz_input.py ← XYZ Input tab handlers │ ├── app_visualization.py ← Trajectory / vib / IR / orbital / PES rendering │ ├── app_history.py ← History tab loaders, replay context diff --git a/CHANGELOG.md b/CHANGELOG.md index 103324d..3a2fec5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,28 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +## [0.13.2] - 2026-12-05 + +### Changed + +- **One molecule viewer with the two-pane workspace.** The Calculate tab no + longer shows a second copy of the molecule: Edit Structure and atom + picking for PES scans now use the workspace pane's viewer. Opening Edit + Structure or choosing PES Scan switches the pane into a pick mode with a + banner ("Clicking picks atoms for … [Done]"); the atom list, highlights + and the status footer follow it, and Done returns to measuring. With the + workspace turned off, the Calculate tab keeps its own viewer as before. + +### Fixed + +- **PyFock geometry optimizations:** every step energy except the final one + was too high by 2.3 × 10⁻⁶ of the total energy (0.11 kcal/mol for water, + about 1.4 kcal/mol for a molecule near −1000 Eh). PyFock reports energies + in eV with its own Hartree→eV constant; QuantUI now converts them back + with the same constant. The final energy was already right (it comes from + the required single point). The backend cross-check now also compares the + first optimization step's energy. + ## [0.13.1] - 2026-12-05 ### Fixed @@ -1723,7 +1745,8 @@ Initial public scaffolding of the QuantUI package: `quantui` package with `calculator.py`, basic notebook launcher, Apptainer container definition, MIT license, and project metadata. -[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.1...HEAD +[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.2...HEAD +[0.13.2]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.1...v0.13.2 [0.13.1]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.0...v0.13.1 [0.13.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.12.0...v0.13.0 [0.12.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.11.1...v0.12.0 diff --git a/pyproject.toml b/pyproject.toml index e079e66..eaff0fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ build-backend = "setuptools.build_meta" [project] name = "quantui" -version = "0.13.1" +version = "0.13.2" description = "An open-source frontend for DFT and post-HF quantum chemistry with PySCF" readme = "README.md" requires-python = ">=3.9" diff --git a/quantui/__init__.py b/quantui/__init__.py index e3a6b39..d6dbd03 100644 --- a/quantui/__init__.py +++ b/quantui/__init__.py @@ -7,7 +7,7 @@ PySCF requires Linux/macOS/WSL. Windows users should use the Apptainer container. """ -__version__ = "0.13.1" +__version__ = "0.13.2" import logging from typing import Any diff --git a/quantui/app.py b/quantui/app.py index 60f5a83..88f2b63 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -268,6 +268,8 @@ from quantui.app_menubar import build_menubar as _mb_build_menubar from quantui.app_menubar import menubar_js as _mb_menubar_js from quantui.app_pes2d import scan2d_enabled as _scan2d_enabled +from quantui.app_pick_mode import pick_mode_active as _pm_active +from quantui.app_pick_mode import sync_pick_mode as _pm_sync from quantui.app_runflow import ( apply_scan_range_around_current as _run_apply_scan_range_around_current, ) @@ -639,8 +641,10 @@ from quantui.app_workspace import build_workspace as _ws_build_workspace from quantui.app_workspace import finalize_viewer_html as _ws_finalize_viewer_html from quantui.app_workspace import labels_enabled as _ws_labels_enabled +from quantui.app_workspace import render_viewer as _ws_render_viewer from quantui.app_workspace import show_input_preview as _ws_show_input_preview from quantui.app_workspace import viewer_render_kwargs as _ws_viewer_render_kwargs +from quantui.app_workspace import workspace_enabled as _ws_workspace_on from quantui.app_xyz_input import ( on_load_xyz as _xyz_on_load_xyz, ) @@ -2006,6 +2010,13 @@ class QuantUIApp: _analysis_empty_html: Any _analysis_mol_output: Any _ws_shell: Any + _ws_pick_mode: str + _ws_pick_paused: bool + _ws_pick_snapshot: Any + _ws_pick_backend: str + _ws_pick_banner: Any + _ws_pick_banner_html: Any + _ws_pick_btn: Any _mb_host: Any _mb_row: Any _mb_js_bridge: Any @@ -2539,6 +2550,9 @@ def _on_root_tab_changed(self, change) -> None: new = change.get("new") if self._is_tab(new, "analysis"): _ana_scroll_analysis_tab_to_top(self) + # The Calculate tab's click tools own the workspace viewer only while + # that tab is selected (app_pick_mode). + _pm_sync(self) if _slurm_jobs_tab_visible(self) and self._is_tab(new, "slurm_jobs"): _slurm_refresh_jobs_tab(self) # Runs save new result folders while Files is out of view; re-list on @@ -4349,6 +4363,11 @@ def _refresh_calc_mol_viewer(self, *, backend: Optional[str] = None) -> None: """ if self._molecule is None or _render_molecule_html is None: return + if _ws_workspace_on(self): + # Two-pane workspace: no Calculate viewer; Edit Structure and PES + # scan picking use the pane's viewer through a pick mode. + _pm_sync(self) + return # Reserve the viewer's height only once there is a viewer, so the # empty Calculate tab has no blank block. self.viz_output.layout.min_height = _CALC_VIEWER_MIN_HEIGHT @@ -4564,7 +4583,10 @@ def _rerender_3d_views(self, *, keep_picks: bool = False) -> None: self._refresh_calc_mol_viewer(backend=str(chosen)) # Analysis-tab molecule viewer (ANALYSIS_STRUCTURE_VIEW task). - if self._analysis_displayed_molecule is not None: + if self._analysis_displayed_molecule is not None and _pm_active(self): + # A Calculate tool owns the workspace viewer: its click wiring. + _ws_render_viewer(self, keep_picks=True) + elif self._analysis_displayed_molecule is not None: chosen = self._resolve_backend(VizTask.ANALYSIS_STRUCTURE_VIEW) if chosen is not None: # Same render path as the first draw (app_visualization. @@ -4903,7 +4925,11 @@ def _on_viz_style_changed(self, change) -> None: def _on_viz_lighting_changed(self, change) -> None: self._viz_lighting = change["new"] - self._refresh_calc_mol_viewer() + if _ws_workspace_on(self): + # The workspace viewer is the only one on screen. + self._rerender_3d_views(keep_picks=True) + else: + self._refresh_calc_mol_viewer() # ── Molecule input ──────────────────────────────────────────────────── diff --git a/quantui/app_builders.py b/quantui/app_builders.py index baedd7f..36f3490 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -1591,7 +1591,7 @@ def build_shared_widgets( app._scan_pick_readout = widgets.HTML( value=( f'' - "Click atoms in the viewer above (py3Dmol) to fill the fields." + "Click atoms in the 3D viewer (py3Dmol) to fill the fields." ) ) app._scan_pick_clear_btn = widgets.Button( diff --git a/quantui/app_measurement.py b/quantui/app_measurement.py index 7d9b3de..0d31503 100644 --- a/quantui/app_measurement.py +++ b/quantui/app_measurement.py @@ -414,8 +414,14 @@ def _clear_inbox() -> None: def on_measure_clear(app: Any, btn: Any = None) -> None: """Clear button: empty the pick chain and its highlights.""" _ = btn + from .app_pick_mode import measuring_off_text, pick_mode_active + app._measure_picks = [] - _set_readout(app, _PLACEHOLDER_TEXT) + # While a Calculate tool owns the workspace viewer's clicks, the readout + # keeps saying so (the Clear button is still on screen). + _set_readout( + app, measuring_off_text(app) if pick_mode_active(app) else _PLACEHOLDER_TEXT + ) push_highlight(app, []) _notify_selection(app) diff --git a/quantui/app_pes_pick.py b/quantui/app_pes_pick.py index 66aec19..b517a3d 100644 --- a/quantui/app_pes_pick.py +++ b/quantui/app_pes_pick.py @@ -1,8 +1,10 @@ -"""Click-to-pick atom selection for PES Scan setup (Calculate-tab viewer). +"""Click-to-pick atom selection for PES Scan setup. Reuses the py3Dmol click transport and highlight overlay from :mod:`quantui.app_measurement`, but fills the PES scan atom dropdowns instead -of the measure readout. +of the measure readout. The viewer clicked is the Calculate tab's own one, or +— with the two-pane workspace on — the pane's viewer in its "pick scan atoms" +mode (``app_pick_mode``). """ from __future__ import annotations @@ -34,7 +36,10 @@ def _scan_pick_indices(app: Any) -> List[int]: def push_scan_highlight(app: Any, indices: Sequence[int]) -> None: - """Highlight scan atoms on the live Calculate-tab viewer.""" + """Highlight scan atoms on the live viewer that takes the scan clicks.""" + from .app_pick_mode import notify_pick_views + + notify_pick_views(app) # workspace atom list / footer, in the scan mode bridge = getattr(app, "_scan_pick_bridge", None) if bridge is None: return @@ -124,6 +129,6 @@ def clear_pes_pick(app: Any) -> None: if readout is not None: readout.value = ( '' - "Click atoms in the viewer above (py3Dmol) to fill the fields." + "Click atoms in the 3D viewer (py3Dmol) to fill the fields." ) push_scan_highlight(app, _scan_pick_indices(app)) diff --git a/quantui/app_pick_mode.py b/quantui/app_pick_mode.py new file mode 100644 index 0000000..2164d5d --- /dev/null +++ b/quantui/app_pick_mode.py @@ -0,0 +1,455 @@ +"""Pick modes for the workspace viewer: what a click on the 3D structure does. + +With the two-pane workspace on (``app_workspace``), the Calculate tab has no +3D viewer of its own; the pane's viewer is the only one. Three tools pick +atoms by clicking it, so that viewer has an explicit pick mode, exactly one +at a time: + +- ``measure`` (normal) — click-to-measure and atom-list selection + (``app_measurement``); +- ``edit`` — the Edit Structure panel's atom picks (``app_structure_edit``), + while that panel is open; +- ``scan`` — the PES scan coordinate atoms (``app_pes_pick``), while + Calc. Type is PES Scan. + +Both tools live on the Calculate tab, so a pick mode is entered only while +that tab is selected; on every other tab the viewer measures. A pick mode +shows the Calculate-tab molecule (the input) with atom numbers, and wires the +tool's own click inbox and highlight slot into the viewer — the same click +transport and overlay the tools used on the Calculate tab's viewer, so their +Python handlers are unchanged. A banner at the top of the pane says what a +click does, with a Done button. Leaving the mode puts back what the viewer +showed before (a result stays a result) and clicks measure again. + +Done closes Edit Structure, or pauses scan picking; a result arriving while a +pick mode is on also pauses it, so the new result shows normally. While +paused the banner offers a button to pick again; reopening Edit Structure or +choosing PES Scan again also ends the pause. + +With the workspace off nothing here applies: the Calculate tab keeps its own +viewer and both tools wire into it as before (``app._refresh_calc_mol_viewer``). +""" + +from __future__ import annotations + +import html as _html +import logging +from typing import Any, List, Optional + +import ipywidgets as widgets + +from quantui import theme as _theme +from quantui.app_measurement import ( + MEASURE_INBOX_CLASS, + _set_readout, + inject_click_js, + on_measure_clear, + reset_picks, + update_panel_for_backend, +) +from quantui.app_pes_pick import PES_PICK_INBOX_CLASS +from quantui.app_structure_edit import EDIT_PICK_INBOX_CLASS, editing_active + +logger = logging.getLogger(__name__) + +MODE_MEASURE = "measure" +MODE_EDIT = "edit" +MODE_SCAN = "scan" + +BANNER_CLASS = "quantui-ws-pickbar" + +_INBOX = { + MODE_MEASURE: MEASURE_INBOX_CLASS, + MODE_EDIT: EDIT_PICK_INBOX_CLASS, + MODE_SCAN: PES_PICK_INBOX_CLASS, +} + +_TOOL_NAME = {MODE_EDIT: "Edit Structure", MODE_SCAN: "the PES scan"} + +PICK_BANNER_CSS = f""" +/* Pick-mode banner at the top of the workspace pane (app_pick_mode) ----- */ +.{BANNER_CLASS} {{ + background: var(--q-surface-info-bg); + border: 1px solid var(--q-accent-info); + border-radius: 6px; + padding: 4px 6px 4px 10px; + margin: 0 0 4px; +}} +.{BANNER_CLASS}.is-paused {{ + background: var(--q-bg-panel); + border-color: var(--q-border); +}} +""" + + +# --------------------------------------------------------------------------- +# State +# --------------------------------------------------------------------------- + + +def _ws_on(app: Any) -> bool: + return bool(getattr(app, "_ws_enabled", False)) + + +def pick_mode(app: Any) -> str: + """The viewer's current pick mode (``measure`` unless a tool owns it).""" + mode = getattr(app, "_ws_pick_mode", MODE_MEASURE) + return mode if mode in _INBOX else MODE_MEASURE + + +def pick_mode_active(app: Any) -> bool: + """True while a Calculate-tab tool owns the workspace viewer's clicks.""" + return _ws_on(app) and pick_mode(app) != MODE_MEASURE + + +def inbox_class(mode: str) -> str: + """Hidden inbox a click (viewer or atom-list row) writes to in *mode*.""" + return _INBOX.get(mode, MEASURE_INBOX_CLASS) + + +def _on_calculate_tab(app: Any) -> bool: + tab = getattr(app, "root_tab", None) + is_tab = getattr(app, "_is_tab", None) + if tab is None or is_tab is None: + return False + return bool(is_tab(tab.selected_index, "calculate")) + + +def available_tool(app: Any) -> str: + """The pick tool the Calculate tab offers right now, ignoring a pause. + + Edit Structure wins over a PES scan setup (as on the Calculate viewer). + """ + if not _ws_on(app) or getattr(app, "_molecule", None) is None: + return MODE_MEASURE + if not _on_calculate_tab(app): + return MODE_MEASURE + if editing_active(app): + return MODE_EDIT + if getattr(getattr(app, "calc_type_dd", None), "value", None) == "PES Scan": + return MODE_SCAN + return MODE_MEASURE + + +def desired_mode(app: Any) -> str: + if getattr(app, "_ws_pick_paused", False): + return MODE_MEASURE + return available_tool(app) + + +def mode_picks(app: Any, mode: Optional[str] = None) -> List[int]: + """0-based atoms the *mode*'s tool has picked, in pick order.""" + mode = mode or pick_mode(app) + if mode == MODE_MEASURE: + raw = getattr(app, "_measure_picks", None) + return list(raw) if isinstance(raw, (list, tuple)) else [] + mol = getattr(app, "_molecule", None) + n = len(getattr(mol, "atoms", []) or []) if mol is not None else 0 + picks: List[int] = [] + try: + if mode == MODE_EDIT: + from quantui.app_structure_edit import current_picks + + picks = current_picks(app) + else: + from quantui.app_pes_pick import _scan_pick_indices + + picks = list(getattr(app, "_scan_pick_buffer", None) or []) + if not picks: + picks = _scan_pick_indices(app) + except (AttributeError, TypeError, ValueError) as exc: + logger.debug("pick-mode picks unavailable: %s", exc) + return [] + return [int(p) for p in picks if 0 <= int(p) < n] + + +def measuring_off_text(app: Any) -> str: + """The measurement readout while a tool owns the clicks.""" + tool = _TOOL_NAME.get(pick_mode(app), "a Calculate tool") + return ( + f"Measuring is off while clicks pick atoms for {tool}. " + "Press Done above the viewer to measure again." + ) + + +# --------------------------------------------------------------------------- +# Rendering hook (called by app_workspace.render_viewer) +# --------------------------------------------------------------------------- + + +def finalize_pick_html(app: Any, html: str, backend: Any) -> str: + """Wire the active tool's click inbox into the workspace viewer HTML. + + The pick-mode counterpart of ``app_measurement.finalize_analysis_html``: + the tool's picks are drawn as soon as the viewer exists, and its own + highlight slot is registered, so the tool's existing highlight pushes + (``push_scan_highlight`` / Edit Structure's) reach this viewer. + """ + mode = pick_mode(app) + app._ws_pick_backend = str(backend) + app._measure_picks = [] + update_panel_for_backend(app, backend) + _set_readout(app, measuring_off_text(app)) + if str(backend) == "py3dmol": + html = inject_click_js( + html, inbox_class=inbox_class(mode), initial_picks=mode_picks(app, mode) + ) + refresh_banner(app) # its text depends on the backend + return html + + +# --------------------------------------------------------------------------- +# Switching +# --------------------------------------------------------------------------- + + +def sync_pick_mode(app: Any) -> None: + """Enter or leave a pick mode to match the Calculate tab's tools. + + Called whenever one of the inputs changes: Edit Structure opened/closed, + Calc. Type changed, the root tab changed, a molecule loaded (all reach + here through ``app._refresh_calc_mol_viewer`` or the tab observer), the + banner's button, and the workspace setting. + """ + if not isinstance(getattr(app, "_ws_pick_banner", None), widgets.Widget): + return + new = desired_mode(app) + old = pick_mode(app) + if new != old: + _switch(app, old, new) + refresh_banner(app) + + +def _switch(app: Any, old: str, new: str) -> None: + from quantui.app_workspace import refresh_workspace, render_viewer + + if old == MODE_MEASURE: + app._ws_pick_snapshot = ( + getattr(app, "_analysis_displayed_molecule", None), + getattr(app, "_ws_source", None), + str(getattr(app, "_ws_result_label", "") or ""), + ) + app._ws_pick_mode = new + _log("pick_mode_changed", f"{old}->{new}") + if new == MODE_MEASURE: + _restore_view(app, render=True) + else: + mol = app._molecule + app._ws_source = "input" + if not render_viewer(app, mol, keep_picks=False): + app._analysis_displayed_molecule = mol + refresh_workspace(app) + + +def _restore_view(app: Any, *, render: bool) -> None: + """Put back what the viewer showed before the pick mode began.""" + snap = getattr(app, "_ws_pick_snapshot", None) + app._ws_pick_snapshot = None + mol, source, label = snap if snap else (None, None, "") + if source == "result" and mol is not None: + app._ws_source = "result" + app._ws_result_label = label + target = mol + else: + target = getattr(app, "_molecule", None) + app._ws_source = "input" if target is not None else None + reset_picks(app) + if render and target is not None: + from quantui.app_workspace import render_viewer + + if render_viewer(app, target, keep_picks=False): + return + app._analysis_displayed_molecule = target + + +def leave_pick_mode(app: Any, *, render: bool = True) -> None: + """Back to normal (measure) mode now; used when the layout is switched off.""" + if pick_mode(app) == MODE_MEASURE: + return + app._ws_pick_mode = MODE_MEASURE + _log("pick_mode_changed", "left") + _restore_view(app, render=render) + refresh_banner(app) + + +def pause_for_result(app: Any) -> None: + """A result is about to be drawn: stop picking so it shows normally. + + Called by ``app_visualization.show_result_3d`` before it renders into the + workspace viewer. The pre-pick view is dropped (the result replaces it). + """ + if not pick_mode_active(app): + return + app._ws_pick_mode = MODE_MEASURE + app._ws_pick_snapshot = None + app._ws_pick_paused = True + _log("pick_mode_changed", "paused for a result") + refresh_banner(app) + + +def forget_view(app: Any) -> None: + """A run started: leaving the pick mode later shows the input, not the + previous result (which the run replaces).""" + if pick_mode_active(app): + app._ws_pick_snapshot = None + + +def tool_entered(app: Any) -> None: + """Edit Structure opened or PES Scan chosen: a pause no longer applies.""" + app._ws_pick_paused = False + + +def on_banner_button(app: Any) -> None: + """Done (leave the pick mode) or Pick atoms (resume after a pause).""" + if pick_mode_active(app): + if pick_mode(app) == MODE_EDIT: + # Leaving Edit Structure: close its panel (its observer syncs). + app._edit_accordion.selected_index = None + sync_pick_mode(app) + return + app._ws_pick_paused = True + else: + app._ws_pick_paused = False + sync_pick_mode(app) + + +def on_clear_selection(app: Any) -> None: + """The atom list's Clear selection button, for whichever mode is on.""" + mode = pick_mode(app) if pick_mode_active(app) else MODE_MEASURE + if mode == MODE_EDIT: + from quantui.app_structure_edit import on_clear_picks + + on_clear_picks(app) + elif mode == MODE_SCAN: + from quantui.app_pes_pick import clear_pes_pick + + clear_pes_pick(app) + else: + on_measure_clear(app) + + +def notify_pick_views(app: Any) -> None: + """A tool's picks changed: redraw the atom list, footer and banner.""" + if not pick_mode_active(app): + return + from quantui.app_workspace import sync_selection_views + + sync_selection_views(app) + refresh_banner(app) + + +# --------------------------------------------------------------------------- +# Banner +# --------------------------------------------------------------------------- + + +def build_pick_banner(app: Any, *, layout_fn: Any) -> None: + """The "Clicking picks atoms for … [Done]" strip (hidden in measure mode).""" + app._ws_pick_mode = MODE_MEASURE + app._ws_pick_paused = False + app._ws_pick_snapshot = None + app._ws_pick_backend = "py3dmol" + app._ws_pick_banner_html = widgets.HTML( + value="", layout=layout_fn(flex="1 1 auto", min_width="0") + ) + app._ws_pick_btn = widgets.Button( + description="Done", + icon="check", + tooltip="Stop picking atoms; clicks measure again", + layout=layout_fn( + width="auto", min_width="84px", height="28px", flex="0 0 auto" + ), + ) + app._ws_pick_banner = widgets.HBox( + [app._ws_pick_banner_html, app._ws_pick_btn], + layout=layout_fn(align_items="center", gap="8px", display="none"), + ) + app._ws_pick_banner.add_class(BANNER_CLASS) + app._ws_pick_btn.on_click(lambda _b: on_banner_button(app)) + + +def banner_text(app: Any) -> tuple: + """(state, html, button label) — state is ``active``, ``paused`` or ``""``.""" + body = f"font-size:12px;color:{_theme.css.TEXT_BODY};line-height:1.35" + if pick_mode_active(app): + mode = pick_mode(app) + tool = _TOOL_NAME[mode] + if mode == MODE_EDIT: + how = "up to 4; click a picked atom again to drop it" + else: + kind = str(getattr(getattr(app, "_scan_type_dd", None), "value", "Bond")) + need = {"bond": 2, "angle": 3, "dihedral": 4}.get(kind.lower(), 2) + what = _html.escape(kind.lower()) + how = f"{need} atoms for {'an' if what[:1] in 'aeiou' else 'a'} {what}" + if getattr(app, "_ws_pick_backend", "py3dmol") != "py3dmol": + text = ( + f"Atom numbers are shown for {tool}. Picking by clicking " + "needs the py3Dmol viewer; type the atom numbers instead." + ) + else: + text = f"Clicking picks atoms for {tool} ({how})." + return "active", f'
{text}
', "Done" + tool_mode = available_tool(app) + if tool_mode != MODE_MEASURE: + tool = _TOOL_NAME[tool_mode] + text = f"Clicks measure. To pick atoms for {tool} by clicking:" + return "paused", f'
{text}
', "Pick atoms" + return "", "", "Done" + + +def refresh_banner(app: Any) -> None: + banner = getattr(app, "_ws_pick_banner", None) + if not isinstance(banner, widgets.Widget): + return + state, text, label = banner_text(app) + banner.layout.display = "" if state else "none" + if state == "paused": + banner.add_class("is-paused") + else: + banner.remove_class("is-paused") + app._ws_pick_banner_html.value = text + btn = app._ws_pick_btn + btn.description = label + btn.icon = "check" if state == "active" else "mouse-pointer" + btn.tooltip = ( + "Stop picking atoms; clicks measure again" + if state == "active" + else "Clicks in the viewer pick atoms for this tool again" + ) + + +def _log(event: str, detail: str = "") -> None: + try: + from quantui import calc_log as _clog + + _clog.log_event(event, detail) + except OSError as exc: + logger.debug("pick-mode log failed: %s", exc) + + +__all__ = [ + "BANNER_CLASS", + "MODE_EDIT", + "MODE_MEASURE", + "MODE_SCAN", + "PICK_BANNER_CSS", + "available_tool", + "banner_text", + "build_pick_banner", + "desired_mode", + "finalize_pick_html", + "forget_view", + "inbox_class", + "leave_pick_mode", + "measuring_off_text", + "mode_picks", + "notify_pick_views", + "on_banner_button", + "on_clear_selection", + "pause_for_result", + "pick_mode", + "pick_mode_active", + "refresh_banner", + "sync_pick_mode", + "tool_entered", +] diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index 18e04b8..a3e97f6 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -792,8 +792,13 @@ def on_calc_type_changed(app: Any, change: Any, *, layout_fn: Any) -> None: except Exception: # noqa: BLE001 — a stale hint must not break the tab pass - # PES Scan overlays 1-based atom indices on the Calculate-tab viewer. + # PES Scan overlays 1-based atom indices on the Calculate-tab viewer (or + # puts the workspace viewer in its scan pick mode, app_pick_mode). old_ct = change.get("old") + if ct == "PES Scan" and old_ct != "PES Scan": + from quantui.app_pick_mode import tool_entered + + tool_entered(app) if ct == "PES Scan" or old_ct == "PES Scan": try: app._refresh_calc_mol_viewer() diff --git a/quantui/app_structure_edit.py b/quantui/app_structure_edit.py index 9f37394..f38f1bc 100644 --- a/quantui/app_structure_edit.py +++ b/quantui/app_structure_edit.py @@ -1,10 +1,14 @@ """Edit Structure panel on the Calculate tab. -Pick atoms by clicking the Calculate-tab viewer (py3Dmol; same click bridge -as click-to-measure and PES picking) or by typing their numbers, then set a +Pick atoms by clicking the 3D viewer (py3Dmol; same click bridge as +click-to-measure and PES picking) or by typing their numbers, then set a bond length / angle / dihedral, delete atoms, add a hydrogen, change an element, or mark atoms frozen for a Geometry Opt. Every edit replaces the working molecule (charge and multiplicity unchanged) and can be undone. + +The viewer clicked is the Calculate tab's own one, or — with the two-pane +workspace on — the pane's viewer in its "edit structure" pick mode +(``app_pick_mode``), entered while this panel is open. """ from __future__ import annotations @@ -136,7 +140,7 @@ def wire_edit_widgets(app: Any) -> None: ) app._edit_pick_inbox.observe(safe(lambda c: on_edit_pick(app, c)), names="value") app._edit_accordion.observe( - safe(lambda c: app._refresh_calc_mol_viewer()), names="selected_index" + safe(lambda c: on_edit_panel_toggled(app, c)), names="selected_index" ) for btn, fn in ( (app._edit_bond_btn, on_set_bond), @@ -152,6 +156,15 @@ def wire_edit_widgets(app: Any) -> None: btn.on_click(safe(lambda _b, _fn=fn: _fn(app))) +def on_edit_panel_toggled(app: Any, change: Any = None) -> None: + """Panel opened or closed: redraw the viewer that takes the clicks.""" + if (change or {}).get("new") == 0: + from .app_pick_mode import tool_entered + + tool_entered(app) + app._refresh_calc_mol_viewer() + + def editing_active(app: Any) -> bool: acc = getattr(app, "_edit_accordion", None) return acc is not None and acc.selected_index == 0 @@ -167,6 +180,9 @@ def finalize_edit_calc_html(app: Any, html: str, backend: Any) -> str: def _push_edit_highlight(app: Any, indices: Sequence[int]) -> None: + from .app_pick_mode import notify_pick_views + + notify_pick_views(app) # workspace atom list / footer, in the edit mode bridge = getattr(app, "_edit_pick_bridge", None) if bridge is None: return diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index f268ed9..0737c1c 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -170,6 +170,13 @@ def show_result_3d( ) app._set_html_output(app.result_viz_output, html) + # A result replaces whatever a Calculate tool was picking on in the + # workspace viewer; it shows normally (click-to-measure). + if is_analysis_output: + from quantui.app_pick_mode import pause_for_result + + pause_for_result(app) + # Optional second viewer (typically the Analysis tab). if extra_output is not None: task = ( diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 1cdab72..840f99f 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -24,9 +24,15 @@ and the footer. The 3D highlight is the measurement overlay (``push_highlight``), py3Dmol only. +With the layout on, this viewer is the only 3D structure viewer: the +Calculate tab's own viewer is hidden, and its two click tools (Edit Structure, +PES scan atom picking) pick on this viewer through an explicit pick mode +(``app_pick_mode``) with a banner at the top of the pane. + The layout can be switched off (System Settings → Workspace layout, ``ui.workspace_layout``); the viewer block then sits at the top of the -Analysis tab as before, still with the toolbar and atom list. +Analysis tab as before, still with the toolbar and atom list, and the +Calculate tab gets its own viewer back. """ from __future__ import annotations @@ -38,7 +44,19 @@ import ipywidgets as widgets from quantui import theme as _theme -from quantui.app_measurement import MEASURE_INBOX_CLASS, on_measure_clear +from quantui.app_measurement import MEASURE_INBOX_CLASS +from quantui.app_pick_mode import ( + PICK_BANNER_CSS, + build_pick_banner, + inbox_class, + leave_pick_mode, + mode_picks, + on_clear_selection, + pick_mode, + pick_mode_active, + refresh_banner, + sync_pick_mode, +) from quantui.config import ( WORKSPACE_ATOM_LIST_MAX_HEIGHT, WORKSPACE_STACK_BELOW_PX, @@ -221,19 +239,25 @@ border-top: 1px solid var(--q-border); margin-top: 6px; }} -""" +""" + PICK_BANNER_CSS -# Row click → the measure inbox (the same transport as a viewer click; see -# app_measurement.inject_click_js). Event delegation on the table, so one -# handler serves every row; single quotes only — it sits in a "-quoted -# attribute. widgets.HTML assigns innerHTML, which keeps inline handlers. -_ROW_CLICK_JS = ( - "var r=event.target.closest('tr[data-atom]');if(!r){return;}" - f"var b=document.querySelector('.{MEASURE_INBOX_CLASS} textarea');" - "if(!b){return;}" - "b.value=r.getAttribute('data-atom');" - "b.dispatchEvent(new Event('input',{bubbles:true}));" -) + +# Row click → the active pick mode's inbox (the measure inbox normally; the +# same transport as a viewer click, see app_measurement.inject_click_js). +# Event delegation on the table, so one handler serves every row; single +# quotes only — it sits in a "-quoted attribute. widgets.HTML assigns +# innerHTML, which keeps inline handlers. +def _row_click_js(inbox: str) -> str: + return ( + "var r=event.target.closest('tr[data-atom]');if(!r){return;}" + f"var b=document.querySelector('.{inbox} textarea');" + "if(!b){return;}" + "b.value=r.getAttribute('data-atom');" + "b.dispatchEvent(new Event('input',{bubbles:true}));" + ) + + +_ROW_CLICK_JS = _row_click_js(MEASURE_INBOX_CLASS) # Remember the freshly rendered viewer's camera so "Reset view" can return # to it without a Python re-render (which would rebuild the viewer). @@ -259,10 +283,18 @@ "if(f){f();}else if(n<40){setTimeout(go,50);}}go();})();" ) +# Scrolls only the atom list's own box: scrollIntoView would also scroll the +# pane body (and the page), moving the 3D viewer away while atoms are being +# clicked in it. _SCROLL_PUSH_JS = ( "(function(){var n=0;function go(){n++;" - "var r=document.querySelector('.%s tr[data-atom=\"%d\"]');" - "if(r){r.scrollIntoView({block:'nearest'});}" + "var c=document.querySelector('.%s');" + "var r=c&&c.querySelector('tr[data-atom=\"%d\"]');" + "if(r){var h=c.querySelector('thead');" + "var top=c.getBoundingClientRect().top+(h?h.getBoundingClientRect().height:0);" + "var bot=c.getBoundingClientRect().bottom,b=r.getBoundingClientRect();" + "if(b.topbot){c.scrollTop+=b.bottom-bot;}}" "else if(n<20){setTimeout(go,50);}}go();})();" ) @@ -287,9 +319,12 @@ def viewer_render_kwargs(app: Any) -> Dict[str, Any]: """Extra ``render_molecule_html`` kwargs for the Analysis/workspace viewer. The pane is narrower than a tab, so the viewer renders smaller there; the - single-column fallback keeps the original 600×500 size. + single-column fallback keeps the original 600×500 size. A pick mode + shows atom numbers, as the Calculate viewer did for its tools. """ - kwargs: Dict[str, Any] = {"show_atom_indices": labels_enabled(app)} + kwargs: Dict[str, Any] = { + "show_atom_indices": labels_enabled(app) or pick_mode_active(app) + } if workspace_enabled(app): kwargs["width"] = WORKSPACE_VIEWER_WIDTH kwargs["height"] = WORKSPACE_VIEWER_HEIGHT @@ -301,6 +336,10 @@ def _viewed_molecule(app: Any) -> Any: def _picks(app: Any) -> list: + """The selection the list and footer show: the active tool's picks in a + pick mode, the measurement chain otherwise.""" + if pick_mode_active(app): + return mode_picks(app) raw = getattr(app, "_measure_picks", None) return list(raw) if isinstance(raw, (list, tuple)) else [] @@ -323,12 +362,14 @@ def atom_list_html( *, mulliken: Optional[Sequence[float]] = None, npa: Optional[Sequence[float]] = None, + inbox: str = MEASURE_INBOX_CLASS, ) -> str: """Read-only atom table: 1-based index, element, x/y/z (Å), charges. Picked atoms (0-based ``picks``) are highlighted and carry their pick order, matching the numbered chain the measurement readout describes. - Charge columns appear only when given and the right length. + Charge columns appear only when given and the right length. A row click + writes to *inbox* (the active pick mode's). """ if molecule is None: return ( @@ -370,7 +411,7 @@ def atom_list_html( f'' + "".join(f"{c}" for c in cells) ) return ( - f'' + f'
' f"{head}{''.join(rows)}
" ) @@ -442,6 +483,12 @@ def footer_html(app: Any) -> str: ) + "" ) + if pick_mode_active(app): + tool = "Edit Structure" if pick_mode(app) == "edit" else "PES scan" + parts.append( + f'' + f"Picking for {tool}" + ) parts.append(f"{_html.escape(selection_text(mol, _picks(app)))}") else: parts.append( @@ -462,6 +509,11 @@ def caption_html(app: Any) -> str: style = f"font-size:12px;color:{_theme.css.TEXT_SECONDARY};margin:2px 0 4px" if mol is None: text = "No structure yet — load a molecule on the Calculate tab." + elif pick_mode_active(app): + text = ( + f"Input structure {_html.escape(mol.get_formula())}, as set up " + "on the Calculate tab." + ) elif source == "input": text = ( f"Input structure {_html.escape(mol.get_formula())} — run a " @@ -575,7 +627,8 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: # The block that moves between the pane and the Analysis tab. # Head (toolbar + caption) stays put in the pane; the body scrolls. - app._ws_head = widgets.VBox([app._ws_toolbar, app._ws_caption]) + build_pick_banner(app, layout_fn=layout_fn) + app._ws_head = widgets.VBox([app._ws_toolbar, app._ws_caption, app._ws_pick_banner]) app._ws_head.add_class(HEAD_CLASS) app._ws_body = widgets.VBox([app._ana_viewer_row, app._ws_atom_box]) app._ws_body.add_class(BODY_CLASS) @@ -601,7 +654,7 @@ def build_workspace(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: safe(lambda ch: on_labels_toggled(app, ch)), names="value" ) app._ws_reset_btn.on_click(lambda _b: on_reset_view(app)) - app._ws_atom_clear_btn.on_click(lambda _b: on_measure_clear(app)) + app._ws_atom_clear_btn.on_click(lambda _b: on_clear_selection(app)) layout_cb = getattr(app, "workspace_layout_cb", None) if layout_cb is not None: layout_cb.observe( @@ -639,7 +692,15 @@ def _drop_child(box: Any, child: Any) -> None: def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> None: - """Place the viewer block in the side pane (on) or the Analysis tab (off).""" + """Place the viewer block in the side pane (on) or the Analysis tab (off). + + On: the Calculate tab's own viewer is hidden (the pane's is the one + viewer). Off: it comes back and the Calculate tools pick on it again. + """ + if not enabled: + # Leave any pick mode first; the single-column code below then + # handles the restored view like any other. + leave_pick_mode(app, render=False) block = app._ws_viewer_block panel = app.analysis_tab_panel row = getattr(app, "_ana_viewer_row", None) @@ -657,6 +718,8 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> panel.children = tuple(kids) app._ws_enabled = bool(enabled) app._ws_caption.layout.display = "" if enabled else "none" + _show_calc_viewer(app, not enabled) + refresh_banner(app) if not rerender: return if not enabled and getattr(app, "_ws_source", None) == "input": @@ -673,6 +736,32 @@ def apply_workspace_layout(app: Any, enabled: bool, *, rerender: bool = True) -> # The viewer changes size with the layout. render_viewer(app, keep_picks=True) refresh_workspace(app) + if enabled: + sync_pick_mode(app) + elif getattr(app, "_molecule", None) is not None: + # The Calculate tab's viewer is back (with its tools' click wiring). + app._refresh_calc_mol_viewer() + + +def _show_calc_viewer(app: Any, shown: bool) -> None: + """Show or hide the Calculate tab's own 3D viewer and its controls. + + Hidden (workspace on) it is also emptied, so no second live viewer holds + a tool's click wiring; the style dropdown is hidden too (the pane's + toolbar is linked to it). Lighting stays: it is not in the toolbar. + """ + display = "" if shown else "none" + for name in ("viz_output", "_mol_calc_png_status", "viz_backend_toggle"): + w = getattr(app, name, None) + if isinstance(w, widgets.Widget): + w.layout.display = display + style_dd = getattr(app, "viz_style_dd", None) + if isinstance(style_dd, widgets.Widget): + style_dd.layout.display = display + out = getattr(app, "viz_output", None) + if not shown and isinstance(out, widgets.Output): + app._clear_output_widget(out) + out.layout.min_height = "0px" def on_workspace_layout_changed(app: Any, change: dict) -> None: @@ -712,7 +801,8 @@ def render_viewer(app: Any, molecule: Any = None, *, keep_picks: bool) -> bool: """(Re)draw the Analysis/workspace viewer through the router. Same task, render function, PNG-capture slot and click-to-measure wiring - as ``app_visualization.show_result_3d``'s Analysis branch. Returns True + as ``app_visualization.show_result_3d``'s Analysis branch; in a pick mode + the active tool's click wiring instead (``app_pick_mode``). Returns True when something was rendered. """ import quantui.app as _app_mod @@ -740,7 +830,12 @@ def render_viewer(app: Any, molecule: Any = None, *, keep_picks: bool) -> bool: show_info=False, **viewer_render_kwargs(app), ) - html = finalize_analysis_html(app, html, chosen, keep_picks=keep_picks) + if pick_mode_active(app): + from quantui.app_pick_mode import finalize_pick_html + + html = finalize_pick_html(app, html, chosen) + else: + html = finalize_analysis_html(app, html, chosen, keep_picks=keep_picks) html = finalize_viewer_html(app, html, chosen) app._set_html_output(out, html) app._analysis_displayed_molecule = mol @@ -763,6 +858,10 @@ def show_input_preview(app: Any, *, force: bool = False) -> None: if getattr(app, "_ws_source", None) == "result" and not force: refresh_footer(app) return + if force: + from quantui.app_pick_mode import forget_view + + forget_view(app) app._ws_source = "input" app._ws_result_label = "" if not render_viewer(app, mol, keep_picks=False): @@ -809,7 +908,14 @@ def _refresh_atom_list(app: Any) -> None: if getattr(app, "_ws_source", None) == "result": mull = getattr(app, "_last_mulliken_charges", None) npa = getattr(app, "_last_npa_charges", None) - app._ws_atom_html.value = atom_list_html(mol, _picks(app), mulliken=mull, npa=npa) + inbox = inbox_class(pick_mode(app)) if pick_mode_active(app) else None + app._ws_atom_html.value = atom_list_html( + mol, + _picks(app), + mulliken=mull, + npa=npa, + inbox=inbox or MEASURE_INBOX_CLASS, + ) n = len(getattr(mol, "atoms", []) or []) if mol is not None else 0 hint = " · click a row or an atom in the viewer" if n else "" app._ws_atom_count.value = ( diff --git a/quantui/help_content.py b/quantui/help_content.py index c67ea87..480e62b 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -549,7 +549,10 @@ "Pre-optimize starting geometry — scans are most meaningful " "from a good starting structure." "
  • Pick atoms via the dropdowns or by clicking in the viewer " - "(py3Dmol only).
  • " + "(py3Dmol only). With the two-pane workspace on, that is the side " + "viewer: while PES Scan is chosen on the Calculate tab, a banner " + "there says clicks pick scan atoms; Done makes clicks " + "measure again." "
  • Use Suggest range or ± around current to fill " "Start/Stop from the current geometry.
  • " "
  • Each scan point runs a constrained QM optimization + " @@ -811,8 +814,9 @@ "measure": { "title": "Click-to-measure (bond / angle / dihedral)", "body": ( - "

    Click atoms directly in the Analysis tab's molecule viewer to " - "read off geometry:

    " + "

    Click atoms directly in the Analysis tab's molecule viewer (the " + "side viewer, with the two-pane workspace on) to read off " + "geometry:

    " "" f"" " " @@ -832,6 +836,10 @@ "atom already in the chain is ignored — repeating an atom makes " "the geometry undefined. Picked atoms are highlighted in the " "viewer; Clear resets the selection.

    " + "

    While Edit Structure is open or PES Scan is chosen on the " + "Calculate tab, clicks in the side viewer pick atoms for that tool " + "instead; a banner above the viewer says so, and its Done " + "button makes clicks measure again.

    " "

    Note: this needs the py3Dmol viewer — if the " "panel shows a message instead of the picker, switch backends " "with the toggle above the viewer (or in Settings). Whenever the " @@ -846,9 +854,12 @@ "editing": { "title": "Editing a structure", "body": ( - "

    Open Edit Structure under the molecule viewer on the " - "Calculate tab. Atom numbers appear in the viewer; click atoms " - "(py3Dmol) or type their numbers.

    " + "

    Open Edit Structure under the molecule on the " + "Calculate tab. Atom numbers appear in the 3D viewer; click atoms " + "(py3Dmol) or type their numbers. With the two-pane workspace on, " + "the viewer is the side one: a banner there says clicks pick atoms " + "for Edit Structure, and Done (or closing the panel) makes " + "clicks measure again.

    " "
    Clicks