Source code for jdxi_editor.ui.editors.ab_compare

"""
Two photos of one part's tone, to switch between while playing.

On the Digital and Analog editors, after Undo / Redo / Reload: A, B, Capture
and Switch. A photo is the editor's own parameter values, not a SysEx dump.
Capture stores the tone in the chosen slot. A and B recall that photo, and
Switch recalls the other one. A recall is one Undo step. The photos are kept
per part in ~/.jdxi_editor/ab_compare and come back at start; nothing is sent
until a slot is pressed. After a program change, or when a photo was stored
in another session, a recall asks first.

Editing after a recall marks that photo as edited. The other photo stays as
it was stored.
"""

from __future__ import annotations

import json
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Optional

from decologr import Decologr as log
from PySide6.QtGui import QKeySequence, QShortcut
from PySide6.QtWidgets import (
    QButtonGroup,
    QHBoxLayout,
    QLabel,
    QMessageBox,
    QPushButton,
    QWidget,
)

from jdxi_editor.ui.editors.digital.partial_tools import one_step, unlinked
from jdxi_editor.ui.editors.history import history_of, shown_value

[docs] SLOTS = ("A", "B")
[docs] SCHEMA_VERSION = 1
[docs] PARTS = { "DIGITAL_SYNTH_1": "digital_1", "DIGITAL_SYNTH_2": "digital_2", "ANALOG_SYNTH": "analog", }
[docs] def store_dir() -> Path: """Where the photos are kept. Tests point this somewhere else.""" return Path.home() / ".jdxi_editor" / "ab_compare"
[docs] def part_of(editor) -> Optional[str]: """digital_1, digital_2 or analog, or None for an editor without A/B.""" preset = getattr(editor, "preset_type", None) name = str( getattr(preset, "name", None) or getattr(preset, "value", None) or preset or "" ) return PARTS.get(name)
@dataclass
[docs] class Photo:
[docs] values: dict
[docs] taken_at: str
[docs] epoch: Optional[int] = None # program context; None once reloaded from disk
[docs] def _store_file(part: str) -> Path: return store_dir() / f"{part}.json"
[docs] def load_slots(part: str) -> dict: """The photos kept for *part*. An unreadable file gives none.""" slots = {slot: None for slot in SLOTS} try: data = json.loads(_store_file(part).read_text(encoding="utf-8")) except FileNotFoundError: return slots except (OSError, ValueError) as ex: log.warning(f"A/B photos of {part} not read: {ex}", scope="ABCompare") return slots if not isinstance(data, dict): return slots for slot in SLOTS: item = data.get(slot) if not isinstance(item, dict) or not isinstance(item.get("values"), dict): continue try: values = {str(key): int(value) for key, value in item["values"].items()} except (TypeError, ValueError) as ex: log.warning(f"A/B photo {slot} of {part} not read: {ex}", scope="ABCompare") continue slots[slot] = Photo( values=values, taken_at=str(item.get("taken_at") or ""), epoch=None, # another session: the next recall asks first ) return slots
[docs] def save_slots(part: str, slots: dict) -> bool: """Keep *part*'s photos. False if they could not be written.""" path = _store_file(part) try: path.parent.mkdir(parents=True, exist_ok=True) data = {"schema": SCHEMA_VERSION} for slot, photo in slots.items(): if photo is None: data[slot] = None else: data[slot] = { "values": photo.values, "taken_at": photo.taken_at, "epoch": photo.epoch, } tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=1), encoding="utf-8") tmp.replace(path) return True except (OSError, TypeError, ValueError) as ex: log.warning(f"A/B photos of {part} not kept: {ex}", scope="ABCompare") return False
[docs] def widgets_of(editor) -> list: """(key, widget) for every tone control. Keys stay stable across sessions.""" found = [] seen: set[int] = set() def add(key: str, widget) -> None: if widget is None or id(widget) in seen: return seen.add(id(widget)) found.append((key, widget)) panels = getattr(editor, "partial_editors", None) or {} for number in sorted(panels): panel = panels[number] controls = panel.all_controls() if hasattr(panel, "all_controls") else {} for param, widget in controls.items(): name = getattr(param, "name", None) if name: add(f"p{int(number)}:{name}", widget) switches = getattr(getattr(editor, "partials_panel", None), "switches", None) or {} for partial, switch in switches.items(): number = getattr(partial, "value", None) box = getattr(switch, "enable_check", None) if isinstance(number, int) and box is not None: add(f"on:{number}", box) if hasattr(editor, "all_controls"): for param, widget in editor.all_controls().items(): name = getattr(param, "name", None) if name: add(f"c:{name}", widget) return found
[docs] def _read(widget) -> Optional[int]: if callable(getattr(widget, "set_mode", None)): try: return int(widget.value()) except (TypeError, ValueError): return None checker = getattr(widget, "isChecked", None) if callable(checker) and not callable(getattr(widget, "value", None)): return 1 if checker() else 0 try: return shown_value(widget) except (TypeError, ValueError, AttributeError): return None
[docs] def _bind_check(widget) -> None: """A checkbox gains value/setValue so a recall of it is an Undo step.""" if callable(getattr(widget, "setValue", None)): return def value(box=widget) -> int: return 1 if box.isChecked() else 0 def set_value(new, box=widget) -> None: target = 1 if int(new) else 0 current = 1 if box.isChecked() else 0 if current == target: return history = history_of(box) box.setChecked(bool(target)) if history is not None and not history.replaying: history.record(box, current, target) widget.value = value widget.setValue = set_value
[docs] def _bind_mode(widget) -> None: """A mode row gains setValue so a recall of it is an Undo step.""" if getattr(widget, "_ab_bound", False): return def set_value(new, group=widget) -> None: target = int(new) try: current = int(group.value()) except (TypeError, ValueError): current = None if current == target: return for mode in group.buttons: if getattr(mode, "value", None) == target: history = history_of(group) group.set_mode(mode, send_midi=True) if ( history is not None and not history.replaying and current is not None ): history.record(group, current, target) return widget.setValue = set_value widget._ab_bound = True
[docs] def _write(widget, value: int) -> None: if callable(getattr(widget, "set_mode", None)): _bind_mode(widget) widget.setValue(int(value)) return if callable(getattr(widget, "setChecked", None)) and not callable( getattr(widget, "setValue", None) ): _bind_check(widget) if callable(getattr(widget, "setValue", None)): widget.setValue(int(value))
[docs] def tone_values(editor) -> dict: """The tone the editor shows now, keyed like a photo.""" values = {} for key, widget in widgets_of(editor): reading = _read(widget) if reading is not None: values[key] = reading return values
[docs] def apply_values(editor, values: dict) -> int: """Set the editor to *values*. One Undo step. How many controls changed.""" changed = 0 with unlinked(editor), one_step(editor): for key, widget in widgets_of(editor): if key not in values: continue target = int(values[key]) current = _read(widget) if current is None or current == target: continue _write(widget, target) if _read(widget) == target: changed += 1 return changed
[docs] class ABSession: """The two photos of one editor, and which one was recalled last.""" def __init__(self, editor, part: str):
[docs] self.editor = editor
[docs] self.part = part
[docs] self.slots = load_slots(part)
[docs] self.selected = SLOTS[0]
[docs] self.active: Optional[str] = None
[docs] self.modified = False
[docs] self.notice = ""
[docs] self.epoch = 0 # program changes seen while this editor is open
[docs] self._accepted_epoch: Optional[int] = None
[docs] self._updating = False
[docs] self._on_changed = []
history = getattr(editor, "history", None) if history is not None: history.on_state(self._after_edit) helper = getattr(editor, "midi_helper", None) signal = getattr(helper, "midi_program_changed", None) if signal is not None and hasattr(signal, "connect"): signal.connect(lambda *_args: self.note_program_change())
[docs] def on_changed(self, callback) -> None: self._on_changed.append(callback)
[docs] def _emit(self) -> None: for callback in self._on_changed: callback()
[docs] def note_program_change(self) -> None: """Another program: the next recall asks first.""" self.epoch += 1
[docs] def can_switch(self) -> bool: return all(self.slots.get(slot) is not None for slot in SLOTS)
[docs] def other(self) -> str: slot = self.active or self.selected return SLOTS[1] if slot == SLOTS[0] else SLOTS[0]
[docs] def capture(self, slot: str, confirm_overwrite=lambda _photo: True) -> bool: """Store the tone in *slot*. False if the old photo was kept.""" if slot not in SLOTS: return False existing = self.slots.get(slot) if existing is not None and not confirm_overwrite(existing): return False photo = Photo( values=dict(tone_values(self.editor)), taken_at=datetime.now().isoformat(timespec="seconds"), epoch=self.epoch, ) self.slots[slot] = photo self.selected = slot kept = save_slots(self.part, self.slots) if self.active == slot: self.modified = False self.notice = ( f"{slot} stored" if kept else f"{slot} stored, but it could not be written to disk" ) self._emit() return True
[docs] def recall(self, slot: str, confirm_context=lambda _photo: True) -> bool: """Show *slot*'s photo. False if it was not recalled.""" photo = self.slots.get(slot) if photo is None: self.notice = f"{slot} is empty" self._emit() return False if photo.epoch != self.epoch and self._accepted_epoch != self.epoch: if not confirm_context(photo): self.notice = f"{slot} not recalled" self._emit() return False self._accepted_epoch = self.epoch apply_values(self.editor, photo.values) self.active = slot self.selected = slot self.modified = False self.notice = f"{slot} recalled" self._emit() return True
[docs] def switch(self, confirm_context=lambda _photo: True) -> bool: """Recall the other photo.""" slot = self.other() if self.slots.get(slot) is None: self.notice = f"{slot} is empty" self._emit() return False self.selected = slot return self.recall(slot, confirm_context=confirm_context)
[docs] def _after_edit(self) -> None: photo = self.slots.get(self.active) if self.active else None modified = False if photo is not None: current = tone_values(self.editor) modified = any( current.get(key) != value for key, value in photo.values.items() if key in current ) if modified != self.modified: self.modified = modified self._emit()
[docs] def button_text(self, slot: str) -> str: if self.slots.get(slot) is None: return slot if self.active == slot and self.modified: return f"{slot} *" if self.active == slot: return f"{slot} ●" return f"{slot} ·"
[docs] def _ask_overwrite(editor, slot: str) -> bool: answer = QMessageBox.question( editor, "A/B compare", f"Replace the tone stored in {slot}?", ) return answer == QMessageBox.StandardButton.Yes
[docs] def _ask_context(editor, photo: Photo, slot: str) -> bool: if photo.epoch is None: text = f"{slot} was stored in another session. Recall it into this program?" else: text = f"The program has changed since {slot} was stored. Recall {slot} anyway?" answer = QMessageBox.question(editor, "A/B compare", text) return answer == QMessageBox.StandardButton.Yes
[docs] def _history_row(editor): layout = editor.layout() if layout is None: return None for index in range(layout.count()): item = layout.itemAt(index) nested = item.layout() if item is not None else None if nested is None: continue for child in range(nested.count()): widget = nested.itemAt(child).widget() if widget is not None and widget.objectName() == "editUndo": return nested return None
[docs] def install_ab_compare(editor: QWidget) -> Optional[ABSession]: """A, B, Capture and Switch on a Digital or Analog editor. None otherwise.""" part = part_of(editor) if part is None: return None session = ABSession(editor, part) editor.ab = session buttons = {} group = QButtonGroup(editor) group.setExclusive(True) for slot in SLOTS: button = QPushButton(slot) button.setObjectName(f"ab{slot}") button.setCheckable(True) group.addButton(button) buttons[slot] = button capture = QPushButton("Capture") switch = QPushButton("Switch") notice = QLabel("") capture.setObjectName("abCapture") switch.setObjectName("abSwitch") notice.setObjectName("abNotice") capture.setToolTip("Store the tone in the chosen slot, A or B") switch.setToolTip("Recall the other slot (Ctrl+Shift+A)") notice.setMinimumWidth(140) def refresh() -> None: session._updating = True try: for slot, button in buttons.items(): button.setText(session.button_text(slot)) button.setChecked(session.selected == slot) photo = session.slots.get(slot) if photo is None: button.setToolTip(f"{slot} is empty. Capture stores the tone here.") elif session.active == slot and session.modified: button.setToolTip( f"{slot} was recalled, and the tone has been edited since" ) elif session.active == slot: button.setToolTip(f"{slot} is the tone recalled last") else: button.setToolTip( f"{slot} stored {photo.taken_at}. Click to recall it." ) switch.setEnabled(session.can_switch()) notice.setText(session.notice) finally: session._updating = False def choose(slot: str) -> None: if session._updating: return session.selected = slot if session.slots.get(slot) is None: session.notice = f"{slot} is empty" session._emit() return session.recall( slot, confirm_context=lambda photo: _ask_context(editor, photo, slot) ) def do_capture() -> None: slot = session.selected session.capture( slot, confirm_overwrite=lambda _photo: _ask_overwrite(editor, slot), ) def do_switch() -> None: session.switch( confirm_context=lambda photo: _ask_context(editor, photo, session.other()) ) for slot, button in buttons.items(): button.clicked.connect(lambda _checked=False, slot=slot: choose(slot)) capture.clicked.connect(lambda: do_capture()) switch.clicked.connect(lambda: do_switch()) shortcut = QShortcut(QKeySequence("Ctrl+Shift+A"), editor) shortcut.activated.connect(do_switch) editor.ab_shortcut = shortcut session.on_changed(refresh) refresh() row = _history_row(editor) if row is None: row = QHBoxLayout() layout = editor.layout() if layout is not None: layout.insertLayout(0, row) row.addWidget(buttons["A"]) row.addWidget(buttons["B"]) row.addWidget(capture) row.addWidget(switch) row.addWidget(notice) return session