"""
The three partials of a Digital tone, worked on together.
Link partials: a change to the partial shown is set on the other partials that
are on. The oscillator's identity (waveform, variation, PCM wave and gain,
pitch, detune, Super Saw detune) stays each partial's own.
Copy, paste and swap a whole partial or one section of it. The clipboard is
shared by Digital 1 and Digital 2. Randomize a section, a partial or the whole
tone by a little, a medium amount or much. Each action is one Undo step.
"""
from __future__ import annotations
import random
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Optional
from jdxi_editor.midi.data.digital.partial import DigitalPartial
from jdxi_editor.midi.data.parameter.digital.common import DigitalCommonParam
from jdxi_editor.midi.data.parameter.digital.partial import DigitalPartialParam
from jdxi_editor.ui.editors.history import shown_value
[docs]
SECTIONS: dict[str, tuple[str, ...]] = {
"OSC": (
"OSC_WAVEFORM",
"OSC_WAVE_VARIATION",
"PCM_WAVE_NUMBER",
"PCM_WAVE_GAIN",
"OSC_PITCH_COARSE",
"OSC_PITCH_FINE",
"OSC_PULSE_WIDTH",
"OSC_PULSE_WIDTH_MOD_DEPTH",
"OSC_PULSE_WIDTH_SHIFT",
"SUPER_SAW_DETUNE",
"OSC_PITCH_ENV_ATTACK_TIME",
"OSC_PITCH_ENV_DECAY_TIME",
"OSC_PITCH_ENV_DEPTH",
),
"FILTER": (
"FILTER_MODE_SWITCH",
"FILTER_SLOPE",
"FILTER_CUTOFF",
"FILTER_RESONANCE",
"FILTER_CUTOFF_KEYFOLLOW",
"FILTER_ENV_VELOCITY_SENSITIVITY",
"HPF_CUTOFF",
"FILTER_ENV_ATTACK_TIME",
"FILTER_ENV_DECAY_TIME",
"FILTER_ENV_SUSTAIN_LEVEL",
"FILTER_ENV_RELEASE_TIME",
"FILTER_ENV_DEPTH",
),
"AMP": (
"AMP_LEVEL",
"AMP_VELOCITY",
"AMP_PAN",
"AMP_LEVEL_KEYFOLLOW",
"AMP_ENV_ATTACK_TIME",
"AMP_ENV_DECAY_TIME",
"AMP_ENV_SUSTAIN_LEVEL",
"AMP_ENV_RELEASE_TIME",
"CUTOFF_AFTERTOUCH",
"LEVEL_AFTERTOUCH",
),
"LFO": (
"LFO_SHAPE",
"LFO_RATE",
"LFO_TEMPO_SYNC_SWITCH",
"LFO_TEMPO_SYNC_NOTE",
"LFO_FADE_TIME",
"LFO_KEY_TRIGGER",
"LFO_PITCH_DEPTH",
"LFO_FILTER_DEPTH",
"LFO_AMP_DEPTH",
"LFO_PAN_DEPTH",
),
"MOD LFO": (
"MOD_LFO_SHAPE",
"MOD_LFO_RATE",
"MOD_LFO_TEMPO_SYNC_SWITCH",
"MOD_LFO_TEMPO_SYNC_NOTE",
"MOD_LFO_PITCH_DEPTH",
"MOD_LFO_FILTER_DEPTH",
"MOD_LFO_AMP_DEPTH",
"MOD_LFO_PAN",
"MOD_LFO_RATE_CTRL",
),
}
[docs]
SECTION_LABELS = {
"OSC": "Oscillator",
"FILTER": "Filter",
"AMP": "Amplifier",
"LFO": "LFO",
"MOD LFO": "Modulation LFO",
}
[docs]
PARTIAL_PARAMS: tuple[str, ...] = tuple(
name for names in SECTIONS.values() for name in names
)
# What makes each partial a different oscillator: not linked.
[docs]
OWN = frozenset(
{
"OSC_WAVEFORM",
"OSC_WAVE_VARIATION",
"PCM_WAVE_NUMBER",
"PCM_WAVE_GAIN",
"OSC_PITCH_COARSE",
"OSC_PITCH_FINE",
"SUPER_SAW_DETUNE",
}
)
[docs]
LINKED = frozenset(PARTIAL_PARAMS) - OWN
[docs]
AMOUNTS = {"little": 0.10, "medium": 0.30, "much": 1.0}
[docs]
COMMON_RANDOM = ("WAVE_SHAPE", "ANALOG_FEEL")
# Lists and switches change only with "much": a new waveform is a new sound.
[docs]
STEADY_BELOW_MUCH = frozenset(
{
"OSC_WAVEFORM",
"OSC_WAVE_VARIATION",
"PCM_WAVE_NUMBER",
"PCM_WAVE_GAIN",
"FILTER_MODE_SWITCH",
"FILTER_SLOPE",
"LFO_SHAPE",
"MOD_LFO_SHAPE",
"LFO_TEMPO_SYNC_SWITCH",
"MOD_LFO_TEMPO_SYNC_SWITCH",
"LFO_TEMPO_SYNC_NOTE",
"MOD_LFO_TEMPO_SYNC_NOTE",
"LFO_KEY_TRIGGER",
"OSC_PITCH_COARSE",
}
)
[docs]
MIN_LEVEL = 70 # a partial randomized stays audible
[docs]
def _names(section: str) -> tuple[str, ...]:
return SECTIONS[section] if section else PARTIAL_PARAMS
[docs]
def _by_name(panel) -> dict:
found = {}
for param, widget in panel.all_controls().items():
found[getattr(param, "name", param)] = (param, widget)
return found
[docs]
def param_of(editor, partial: int, name: str):
panel = editor.partial_editors.get(partial)
if panel is None:
return None
found = _by_name(panel).get(name)
return found[0] if found else None
[docs]
def _read(widget) -> int:
return shown_value(widget)
[docs]
def _bounds(param, widget) -> tuple[int, int]:
getter = getattr(param, "get_display_value", None)
if callable(getter):
lo, hi = getter()
return int(lo), int(hi)
return int(getattr(widget, "lo", 0)), int(getattr(widget, "hi", 127))
# ------------------------------------------------------------------- clipboard
@dataclass
[docs]
class Clip:
"""A partial (section "") or one section, with the values copied."""
[docs]
values: dict = field(default_factory=dict)
[docs]
def describe(self) -> str:
what = (
SECTION_LABELS.get(self.section, "Partial") if self.section else "Partial"
)
return f"{what} of {self.source}"
[docs]
_clip: Optional[Clip] = None
[docs]
def clip() -> Optional[Clip]:
return _clip
[docs]
def _source(editor, partial: int) -> str:
return f"Digital {getattr(editor, 'synth_number', 1)} ยท partial {partial}"
[docs]
def copy(editor, partial: int, section: str = "") -> Clip:
"""Copy partial *partial* (1-3), or one *section* of it."""
global _clip
values = {}
for name in _names(section):
widget = widget_of(editor, partial, name)
if widget is not None:
values[name] = _read(widget)
_clip = Clip(section, values, _source(editor, partial))
return _clip
@contextmanager
[docs]
def one_step(editor):
"""The changes made inside are one Undo step."""
history = getattr(editor, "history", None)
if history is not None:
history.begin_group()
try:
yield
finally:
if history is not None:
history.end_group()
@contextmanager
[docs]
def unlinked(editor):
"""Paste, swap and randomize set each partial as asked, not through the link."""
link = getattr(editor, "partial_link", None)
if link is not None:
link.suspended += 1
try:
yield
finally:
if link is not None:
link.suspended -= 1
[docs]
def set_values(editor, partial: int, values: dict) -> int:
"""Set these values on partial *partial*. How many changed."""
changed = 0
for name, value in values.items():
widget = widget_of(editor, partial, name)
if widget is None:
continue
current = _read(widget)
if current != int(value):
widget.setValue(int(value))
changed += 1
return changed
[docs]
def paste(editor, partial: int) -> int:
"""Paste the clipboard into partial *partial*."""
if _clip is None:
return 0
with one_step(editor), unlinked(editor):
return set_values(editor, partial, _clip.values)
[docs]
def swap(editor, first: int, second: int, section: str = "") -> int:
"""Swap two partials, or one section of them."""
if first == second:
return 0
names = _names(section)
a = {
name: _read(widget_of(editor, first, name))
for name in names
if widget_of(editor, first, name)
}
b = {
name: _read(widget_of(editor, second, name))
for name in names
if widget_of(editor, second, name)
}
with one_step(editor), unlinked(editor):
return set_values(editor, first, b) + set_values(editor, second, a)
# ------------------------------------------------------------------- linking
[docs]
class PartialLink:
"""A change on one partial is set on the other partials that are on, in the same Undo step."""
def __init__(self, editor):
for partial in PARTIALS:
for name in LINKED:
widget = widget_of(editor, partial, name)
if widget is None or not hasattr(widget, "valueChanged"):
continue
widget.valueChanged.connect(
lambda value, name=name, partial=partial: self._follow(
name, partial, value
)
)
[docs]
def _partial_on(self, partial: int) -> bool:
switches = (
getattr(getattr(self.editor, "partials_panel", None), "switches", {}) or {}
)
switch = switches.get(DigitalPartial(partial))
if switch is None:
return True
return bool(switch.enable_check.isChecked())
[docs]
def _follow(self, name: str, partial: int, value: int) -> None:
history = getattr(self.editor, "history", None)
if (
not self.enabled
or self._busy
or self.suspended
or (history is not None and history.replaying)
):
return
self._busy = True
try:
context = (
history.attached()
if history is not None and not history._group_depth
else _nothing()
)
with context:
for other in PARTIALS:
if other == partial or not self._partial_on(other):
continue
widget = widget_of(self.editor, other, name)
if widget is not None and _read(widget) != int(value):
widget.setValue(int(value))
finally:
self._busy = False
@contextmanager
# ------------------------------------------------------------------- randomize
[docs]
def _random_value(param, widget, amount: float, rng: random.Random) -> int:
lo, hi = _bounds(param, widget)
if hi - lo <= 3:
return rng.randint(lo, hi)
span = (hi - lo) * amount
value = _read(widget) + rng.uniform(-span, span)
return max(lo, min(hi, int(round(value))))
[docs]
def _common(editor, name: str):
section = getattr(editor, "common_section", None)
param = getattr(DigitalCommonParam, name, None)
if section is None or param is None:
return None, None
return param, section.controls.get(param)
[docs]
def randomize(
editor,
scope: str,
amount: str = "medium",
partial: int = 1,
section: str = "",
rng: Optional[random.Random] = None,
) -> int:
"""Randomize a section, a partial, or the whole tone. One Undo step. How many values changed."""
rng = rng or random.Random()
share = AMOUNTS[amount]
much = amount == "much"
if scope == "section":
targets = [(partial, name) for name in SECTIONS[section]]
elif scope == "partial":
targets = [(partial, name) for name in PARTIAL_PARAMS]
else:
targets = [(p, name) for p in PARTIALS for name in PARTIAL_PARAMS]
changed = 0
with one_step(editor), unlinked(editor):
for part, name in targets:
if name in STEADY_BELOW_MUCH and not much:
continue
widget = widget_of(editor, part, name)
param = param_of(editor, part, name)
if widget is None or param is None:
continue
value = _random_value(param, widget, share, rng)
if name == "AMP_LEVEL":
value = max(value, MIN_LEVEL)
elif name == "FILTER_CUTOFF":
value = max(value, NO_SILENT_FILTER)
elif name == "AMP_ENV_SUSTAIN_LEVEL" and much:
value = max(value, 40)
if _read(widget) != value:
widget.setValue(value)
changed += 1
if scope == "tone":
for name in COMMON_RANDOM:
param, widget = _common(editor, name)
if widget is None:
continue
value = _random_value(param, widget, share, rng)
if _read(widget) != value:
widget.setValue(value)
changed += 1
return changed