Source code for jdxi_editor.ui.preset.widget

"""Preset Widget to be used by All Editors"""

from typing import TYPE_CHECKING, Any, Optional

from decologr import Decologr as log
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QGroupBox, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QTabWidget, QVBoxLayout
import picomidi

from jdxi_editor.midi.channel.channel import MidiChannel
from jdxi_editor.ui.common import JDXi, QVBoxLayout, QWidget
from jdxi_editor.ui.editors.helpers.widgets import (
    create_jdxi_button,
    create_jdxi_row,
    create_round_button_with_label,
)
from jdxi_editor.ui.editors.pattern.preset_list_provider import (
    get_preset_list_for_synth_type,
    get_preset_signals,
)
from jdxi_editor.ui.preset.utils import convert_preset_dict_to_list
from jdxi_editor.ui.widgets.combo_box.searchable_filterable import (
    SearchableFilterableComboBox,
)
from jdxi_editor.ui.widgets.midi.selection_info_bar import (
    MidiSelectionInfoBar,
    bind_tone_midi_info,
)
from jdxi_editor.ui.widgets.digital.title import DigitalTitle
from jdxi_editor.ui.widgets.editor.helper import (
    create_layout_with_items,
    create_scroll_container,
    transfer_layout_items,
)
from picoui.helpers.layout import create_group
from picoui.specs.widgets import ComboBoxSpec
from picoui.widget.helper import create_combo_box, create_combo_row

if TYPE_CHECKING:
    from jdxi_editor.ui.editors.synth.editor import SynthEditor


[docs] class InstrumentPresetWidget(QWidget): """InstrumentPresetWidget""" def __init__( self, parent: "SynthEditor", # parent is not optional ): """ InstrumentPresetWidget :param parent: QWidget """ super().__init__(parent)
[docs] self.midi_channel_combo = None
[docs] self.midi_channel_combo_row = None
[docs] self.group: QGroupBox | None = None
[docs] self.layout: QVBoxLayout | None = None
[docs] self.instrument_presets: QWidget | None = None
[docs] self.widget: QWidget | None = None
[docs] self.hlayout: QHBoxLayout | None = None
[docs] self.parent = parent
[docs] self._synth_type: str = ""
[docs] self._preset_list: list = []
[docs] self.instrument_selection_combo: Optional["SearchableFilterableComboBox"] = None
[docs] self.tone_midi_info_bar: Optional[MidiSelectionInfoBar] = None
[docs] self.cheat_midi_info_bar: Optional[MidiSelectionInfoBar] = None
[docs] self.tone_midi_info = None # MidiSelectionInfoController for the preset combo
# Connect to preset list change signal for dynamic refresh get_preset_signals().soundfont_list_changed.connect(self._refresh_preset_list) log.info(scope="InstrumentPresetWidget", message="Connected to soundfont_list_changed signal")
[docs] def _refresh_preset_list(self) -> None: """Refresh the preset combo box when SoundFont list setting changes.""" log.info( scope="InstrumentPresetWidget", message=f"_refresh_preset_list called, synth_type={self._synth_type}" ) if not self._synth_type: log.info(scope="InstrumentPresetWidget", message="No synth_type set, skipping refresh") return if not hasattr(self, "instrument_selection_combo") or self.instrument_selection_combo is None: log.info(scope="InstrumentPresetWidget", message="No instrument_selection_combo, skipping refresh") return # Get updated preset list preset_list = get_preset_list_for_synth_type(self._synth_type) log.info( scope="InstrumentPresetWidget", message=f"Got {len(preset_list) if preset_list else 0} presets for {self._synth_type}" ) # Convert dictionary format to list format if needed converted_preset_list = convert_preset_dict_to_list(preset_list) # Update parent's preset list self.parent.preset_preset_list = converted_preset_list self._preset_list = converted_preset_list # Build new options and values preset_options = [ f"{preset['id']} - {preset['name']}" for preset in converted_preset_list ] preset_values = [int(preset["id"]) for preset in converted_preset_list] preset_categories = sorted( set(preset["category"] for preset in converted_preset_list) ) log.message(f"preset_options: {preset_options}") log.message(f"preset_values: {preset_values}") log.message(f"preset_categories: {preset_categories}") # Create new category filter function with the updated preset list def preset_category_filter(preset_display: str, category: str) -> bool: """Check if a preset matches a category.""" if not category: return True preset_id_str = ( preset_display.split(" - ")[0] if " - " in preset_display else None ) if preset_id_str: for preset in converted_preset_list: if preset["id"] == preset_id_str: return preset["category"] == category return False # Update the combo box with new options and filter function current_value = self.instrument_selection_combo.value() self.instrument_selection_combo.set_options( preset_options, preset_values, preset_categories, preset_category_filter ) log.info( scope="InstrumentPresetWidget", message=f"Updated combo with {len(preset_options)} options" ) # Try to restore the previous selection if current_value in preset_values: self.instrument_selection_combo.set_value(current_value)
[docs] def add_image_group(self, group: QGroupBox): """add the image beside the preset panel; the pair stays centred""" group.setMinimumWidth(JDXi.UI.Style.INSTRUMENT_IMAGE_WIDTH) self.hlayout.addWidget(group, 0, Qt.AlignmentFlag.AlignTop) self.hlayout.addStretch(1)
[docs] def add_preset_group(self, group: QGroupBox): """add groupbox for instruments (as tall as its contents)""" group.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) self.hlayout.addWidget(group, 0, Qt.AlignmentFlag.AlignTop)
[docs] def setup(self): """set up the widget - creates the main vertical layout""" if self.layout is None: self.layout = QVBoxLayout() # Set proper margins and spacing to match PresetWidget self.layout.setContentsMargins( *JDXi .UI.Style.PADDING_MARGINS ) self.layout.setSpacing(JDXi.UI.Style.SPACING) self.layout.setAlignment(Qt.AlignmentFlag.AlignTop) self.setLayout(self.layout)
[docs] def create_instrument_image_group(self) -> tuple[QGroupBox, Any, Any]: """Image group — frameless overview panel (no heavy inset card).""" self.instrument_image_label = QLabel() self.instrument_image_label.setAlignment( Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter ) instrument_group_layout = create_layout_with_items(items=[self.instrument_image_label], vertical=True, margins=JDXi.UI.Style.REDUCED_PADDING_MARGINS, spacing=JDXi.UI.Style.SPACING) instrument_image_group = create_group(layout=instrument_group_layout, style_sheet=JDXi.UI.Style.INSTRUMENT_IMAGE_LABEL, width=JDXi.UI.Style.INSTRUMENT_IMAGE_WIDTH, height=JDXi.UI.Style.INSTRUMENT_IMAGE_HEIGHT) return ( instrument_image_group, self.instrument_image_label, instrument_group_layout, )
[docs] def _add_round_action_button( self, icon_enum: Any, text: str, slot: Any, layout: QHBoxLayout, *, name: Optional[str] = None, checkable: bool = False, ) -> QPushButton: """Create a round button with icon + text label (same style as Transport).""" btn = create_jdxi_button("") btn.setCheckable(checkable) if slot is not None: btn.clicked.connect(slot) if name: setattr(self, f"{name}_button", btn) layout.addWidget(btn) pixmap = JDXi.UI.Icon.get_icon_pixmap( icon_enum, color=JDXi.UI.Style.FOREGROUND, size=20 ) label_row, _ = create_jdxi_row(text, icon_pixmap=pixmap) layout.addWidget(label_row) return btn
[docs] def _add_centered_round_button( self, icon_enum: Any, text: str, slot: Any, parent_layout: Any, name: Optional[str] = None, ) -> QPushButton: """Add a round button + label row centered in a QHBoxLayout (stretch on both sides).""" row = QHBoxLayout() row.addStretch() btn = self._add_round_action_button(icon_enum, text, slot, row, name=name) row.addStretch() parent_layout.addLayout(row) return btn
[docs] def create_instrument_preset_group(self, synth_type: str = "Analog") -> QGroupBox: """ Create the instrument preset group box with tabs for normal and cheat presets (Analog only). :param synth_type: str :return: QGroupBox """ self._synth_type = synth_type # Store for refresh instrument_preset_group = QGroupBox(f"{synth_type} Synth") instrument_title_group_layout = QVBoxLayout(instrument_preset_group) instrument_title_group_layout.setSpacing(3) # Reduced spacing instrument_title_group_layout.setContentsMargins(5, 5, 5, 5) # Reduced margins # Apply Analog color styling for Analog Synth group box if synth_type == "Analog": instrument_preset_group.setStyleSheet(JDXi.UI.Style.GROUP_BOX_ANALOG) # For Analog, create tabs; for others, create simple layout if synth_type == "Analog": # Create tabbed widget inside the group box preset_tabs = QTabWidget() instrument_title_group_layout.addWidget(preset_tabs) # === Tab 1: Normal Analog Presets === normal_preset_widget, normal_preset_layout = create_scroll_container() self._add_normal_preset_content(normal_preset_layout, synth_type) try: analog_presets_icon = JDXi.UI.Icon.get_icon( JDXi.UI.Icon.MUSIC_NOTE_MULTIPLE, color=JDXi.UI.Style.GREY ) if analog_presets_icon is None or analog_presets_icon.isNull(): raise ValueError("Icon is null") except Exception: analog_presets_icon = JDXi.UI.Icon.get_icon( JDXi.UI.Icon.MUSIC, color=JDXi.UI.Style.GREY ) preset_tabs.addTab( normal_preset_widget, analog_presets_icon, "Analog Presets" ) # === Tab 2: Cheat Presets (Digital Synth presets on Analog channel) === cheat_preset_widget, cheat_preset_layout = create_scroll_container() self._add_cheat_preset_content(cheat_preset_layout) cheat_presets_icon = JDXi.UI.Icon.get_icon( JDXi.UI.Icon.CODE_BRACES, color=JDXi.UI.Style.GREY ) preset_tabs.addTab(cheat_preset_widget, cheat_presets_icon, "Cheat Presets") else: # For Digital/Drums, create simple layout without tabs self._add_normal_preset_content(instrument_title_group_layout, synth_type) return instrument_preset_group
[docs] def _add_normal_preset_content(self, layout: Any, synth_type: str): """Add normal preset selection content to the layout.""" # No icon row here: the Digital and Drums editors show one above self.instrument_title_label = DigitalTitle() # Upper line names the part being edited, as the JD-Xi's display does part = { "Digital": f"DIGITAL SYNTH {getattr(self.parent, 'synth_number', 1)}", "Drums": "DRUMS", }.get(synth_type, synth_type.upper()) self.instrument_title_label.set_upper_display_text(part) layout.addWidget(self.instrument_title_label) # --- Edit Tone Name (round button + label, centered) self._add_centered_round_button( JDXi.UI.Icon.SETTINGS, "Edit Tone Name", self.parent.edit_tone_name, layout, name="edit_tone_name", ) # (Reading from the synth is the "Read from JD-Xi" button below) # Determine the correct preset list for this synth type. preset_list = get_preset_list_for_synth_type(synth_type) # Convert dictionary format (Digital/Analog) to list format if needed converted_preset_list = convert_preset_dict_to_list(preset_list) # Ensure parent uses this list for load_preset lookups self.parent.preset_preset_list = converted_preset_list # Build preset options, values, and categories from converted_preset_list preset_options = [ f"{preset['id']} - {preset['name']}" for preset in converted_preset_list ] # Convert preset IDs to integers for SearchableFilterableComboBox (e.g., "001" -> 1) preset_values = [int(preset["id"]) for preset in converted_preset_list] preset_categories = sorted( set(preset["category"] for preset in converted_preset_list) ) # Category filter function for presets def preset_category_filter(preset_display: str, category: str) -> bool: """Check if a preset matches a category.""" if not category: return True # Extract preset ID from digital string (format: "001 - Preset Name") preset_id_str = ( preset_display.split(" - ")[0] if " - " in preset_display else None ) if preset_id_str: # Find the preset in the list and check its category for preset in converted_preset_list: if preset["id"] == preset_id_str: return preset["category"] == category return False # Create SearchableFilterableComboBox for preset selection self.instrument_selection_combo = SearchableFilterableComboBox( label="", options=preset_options, values=preset_values, categories=preset_categories, category_filter_func=preset_category_filter, show_label=False, show_search=True, show_category=True, search_placeholder="Search presets...", use_analog_style=(synth_type == "Analog"), ) # Apply styling if synth_type == "Analog": # Apply Analog styling to the combo box and search line edit self.instrument_selection_combo.combo_box.setStyleSheet( JDXi.UI.Style.COMBO_BOX_ANALOG ) search_box = getattr(self.instrument_selection_combo, "search_box", None) if search_box is not None: search_box.setStyleSheet(JDXi.UI.Style.QLINEEDIT_ANALOG) else: self.instrument_selection_combo.combo_box.setStyleSheet( JDXi.UI.Style.COMBO_BOX ) # Connect signals - use combo_box for currentIndexChanged self.instrument_selection_combo.combo_box.currentIndexChanged.connect( self.parent.update_instrument_image ) self.instrument_selection_combo.combo_box.currentIndexChanged.connect( self.parent.update_instrument_title ) from jdxi_editor.ui.editors.helpers.edit_buffer_ops import ( create_part_syx_row, create_preset_nav_row, create_read_from_jdxi_row, ) nav_row, prev_btn, next_btn, load_button = create_preset_nav_row( self._on_prev_preset, self._on_next_preset, self._on_load_preset, ) self._preset_prev_button = prev_btn self._preset_next_button = next_btn selection_layout = create_layout_with_items( [self.instrument_selection_combo, nav_row], vertical=True ) self.tone_midi_info_bar = MidiSelectionInfoBar() selection_layout.addWidget(self.tone_midi_info_bar) channel = getattr(self.parent, "midi_channel", MidiChannel.DIGITAL_SYNTH_1) channel_label = str(MidiChannel.from_midi_channel(channel) or synth_type) self.tone_midi_info = bind_tone_midi_info( self.instrument_selection_combo, self.tone_midi_info_bar, converted_preset_list, channel=channel, channel_label=channel_label, parent=self, midi_helper=getattr(self.parent, "midi_helper", None), lcd_title=self.instrument_title_label, ) read_row, self._read_from_jdxi_button, self._preset_status_label = ( create_read_from_jdxi_row(self._on_read_from_jdxi) ) selection_layout.addWidget(read_row) selection_layout.addWidget( create_part_syx_row(self._on_import_part_syx, self._on_export_part_syx) ) if synth_type == "Analog": random_row = QHBoxLayout() random_widget, _ = create_round_button_with_label( "Random Patch", "mdi.dice-5-outline", self._on_random_analog_patch, "Randomize analog tone parameters (Manager rndVoice)", ) random_row.addWidget(random_widget) random_row.addStretch() selection_layout.addLayout(random_row) layout.addLayout(selection_layout) # Store reference to load button for compatibility self.instrument_selection_combo.load_button = load_button layout.addStretch()
[docs] def _add_cheat_preset_content(self, layout: QVBoxLayout): """Add cheat preset content to the layout (Analog only).""" # Add icon row at the top (centered with stretch on both sides, matching PresetWidget) icon_row_container = QHBoxLayout() icon_row_container.addStretch() icon_row = JDXi.UI.Icon.create_generic_musical_icon_row() transfer_layout_items(icon_row, icon_row_container) icon_row_container.addStretch() layout.addLayout(icon_row_container) layout.addSpacing(10) # Add spacing after icon row, matching PresetWidget # Build preset options, values, and categories # Support both "category" and "Category" (LIST has mixed formats) def _preset_category(p: dict) -> str: return p.get("category") or p.get("Category") or "" preset_options = [ f"{preset.get('id', '')} - {preset.get('name', preset.get('Name', ''))}" for preset in JDXi.UI.Preset.Digital.LIST ] # Convert preset IDs to integers for SearchableFilterableComboBox (e.g., "001" -> 1) preset_values = [int(p.get("id", "000")) for p in JDXi.UI.Preset.Digital.LIST] preset_categories = sorted( set( _preset_category(p) for p in JDXi.UI.Preset.Digital.LIST if _preset_category(p) ) ) # Category filter function for presets def cheat_preset_category_filter(preset_display: str, category: str) -> bool: """Check if a preset matches a category.""" if not category: return True # Extract preset ID from digital string (format: "001 - Preset Name") preset_id_str = ( preset_display.split(" - ")[0] if " - " in preset_display else None ) if preset_id_str: # Find the preset in the list and check its category for preset in JDXi.UI.Preset.Digital.LIST: if preset.get("id") == preset_id_str: return _preset_category(preset) == category return False # Create SearchableFilterableComboBox for cheat preset selection self.cheat_preset_combo_box = SearchableFilterableComboBox( label="Preset", options=preset_options, values=preset_values, categories=preset_categories, category_filter_func=cheat_preset_category_filter, show_label=True, show_search=True, show_category=True, search_placeholder="Search presets...", ) from picomidi.core.channel import Channel channels = [str(Channel.display_value(i)) for i in Channel.all_channels()] # channel_strings = [str(j) for j in channels] self.create_midi_combo_row(channels) self.midi_channel_combo.setCurrentIndex(MidiChannel.ANALOG_SYNTH) self._get_midi_channel_from_combo() self.cheat_midi_info_bar = MidiSelectionInfoBar() self._cheat_midi_info_controller = bind_tone_midi_info( self.cheat_preset_combo_box, self.cheat_midi_info_bar, JDXi.UI.Preset.Digital.LIST, channel=self.midi_channel, channel_label=self._channel_label_for(self.midi_channel), parent=self, midi_helper=getattr(self.parent, "midi_helper", None), ) layout.addWidget(self.cheat_preset_combo_box) layout.addLayout(self.midi_channel_combo_row) layout.addWidget(self.cheat_midi_info_bar) # Load Preset (round button + label, centered) self._add_centered_round_button( JDXi.UI.Icon.FOLDER_NOTCH_OPEN, "Load Preset", self._load_cheat_preset, layout, name="cheat_load", ) layout.addStretch()
[docs] def create_midi_combo_row(self, channels: list[str]) -> None: """ create_midi_combo_row :param channels: list :return: None """ self.midi_channel_combo_row, self.midi_channel_combo = create_combo_row(label="Midi Channel", items=channels, sort_items=False, slot=self._get_midi_channel_from_combo)
@staticmethod
[docs] def _channel_label_for(channel: int) -> Optional[str]: midi_ch = MidiChannel.from_midi_channel(channel) return str(midi_ch) if midi_ch is not None else None
[docs] def _get_midi_channel_from_combo(self, *_args) -> None: """Update cheat MIDI channel from combo and refresh the info bar.""" self.midi_channel = self.midi_channel_combo.currentIndex() log.info(f"midi channel = {self.midi_channel}") controller = getattr(self, "_cheat_midi_info_controller", None) if controller is not None: controller.set_channel( self.midi_channel, channel_label=self._channel_label_for(self.midi_channel), )
[docs] def _set_preset_status(self, text: str) -> None: label = getattr(self, "_preset_status_label", None) if label is not None: label.setText(text)
[docs] def _on_prev_preset(self) -> None: combo = self.instrument_selection_combo.combo_box idx = combo.currentIndex() if idx > 0: combo.setCurrentIndex(idx - 1)
[docs] def _on_next_preset(self) -> None: combo = self.instrument_selection_combo.combo_box idx = combo.currentIndex() if idx < combo.count() - 1: combo.setCurrentIndex(idx + 1)
[docs] def _on_read_from_jdxi(self) -> None: parent = self.parent if parent is None or not hasattr(parent, "read_from_jdxi"): if hasattr(parent, "data_request"): parent.data_request() self._set_preset_status("Requested data (F5 path)") return parent.read_from_jdxi(status_callback=self._set_preset_status)
[docs] def _on_import_part_syx(self) -> None: parent = self.parent if parent is not None and hasattr(parent, "import_part_syx"): parent.import_part_syx()
[docs] def _on_export_part_syx(self) -> None: parent = self.parent if parent is not None and hasattr(parent, "export_part_syx"): parent.export_part_syx()
[docs] def _on_random_analog_patch(self) -> None: parent = self.parent if parent is not None and hasattr(parent, "randomize_analog_patch"): parent.randomize_analog_patch() self._set_preset_status("Randomized analog patch")
[docs] def _on_load_preset(self): """Load factory preset on hardware, then read parameters into the editor.""" preset_id_int = self.instrument_selection_combo.value() self._set_preset_status(f"Loaded preset {preset_id_int} — reading…") if hasattr(self.parent, "read_from_jdxi"): self.parent.load_preset(int(preset_id_int), request_data=False) self.parent.read_from_jdxi(status_callback=self._set_preset_status) else: self.parent.load_preset(int(preset_id_int))
[docs] def _load_cheat_preset(self): """ Load a Digital Synth preset on the Analog Synth channel (Cheat Mode). """ if not hasattr(self.parent, "midi_helper") or not self.parent.midi_helper: log.warning("⚠️ MIDI helper not available for cheat preset loading") return preset_id_int = self.cheat_preset_combo_box.value() from jdxi_editor.ui.editors.helpers.preset import ( load_digital_cheat_preset_on_analog, ) load_digital_cheat_preset_on_analog( self.parent.midi_helper, preset_id_int, channel=self.midi_channel, ) if hasattr(self.parent, "read_from_jdxi"): self.parent.read_from_jdxi() elif hasattr(self.parent, "data_request"): self.parent.data_request()
[docs] def setup_header_layout(self) -> None: """Top layout with preset controls and instrument overview.""" # Ensure setup() has been called first if self.layout is None: self.setup() self.hlayout = QHBoxLayout() self.hlayout.setSpacing(JDXi.UI.Style.SPACING) self.hlayout.setAlignment(Qt.AlignmentFlag.AlignTop) self.hlayout.addStretch(1) # centre the preset panel and image (see add_image_group) # Add the horizontal layout to the vertical layout self.layout.addLayout(self.hlayout)
[docs] def add_stretch(self): """Gap between preset panel and instrument image (fixed: the image sits beside the panel).""" self.hlayout.addSpacing(24)