diff --git a/composer-lab/README.md b/composer-lab/README.md
index 1757388..1e9ad49 100644
--- a/composer-lab/README.md
+++ b/composer-lab/README.md
@@ -105,6 +105,8 @@ python -m studio.summary out_studio
«Кульм.», «Конц.»), полное имя видно во всплывающей подсказке. «Скачать MIDI» и
«Скачать табы (MusicXML)» сохраняют готовый трек для DAW и Guitar Pro.
+«Тональность» в параметрах пьесы переводит все ноты в выбранную тональность и лад по ступеням: ритм, форма и состав нот остаются прежними, а аппликатура и приёмы (легато, слайды, тэппинг) заново выводятся для новых нот по секциям (легато на первую ноту секции не переносится) и могут отличаться от исходных; аккорды перестраиваются так, чтобы их можно было сыграть и в них не было полутонов. Октава меняется целиком для участка гитары в секции, если он не помещается в гриф; «Как в пьесе» возвращает исходную тональность.
+
Стек «Вернуть» хранится в `redo.json` рядом с `undo.json` в папке пьесы и
доступен как `POST /api/piece/{id}/redo`; в журнал `history.jsonl` пишется
действие `redo`. Оба стека ограничены 50 шагами.
@@ -139,6 +141,6 @@ nix shell nixpkgs#fluidsynth nixpkgs#sox nixpkgs#ffmpeg -c bash build_samples.sh
### Как пользоваться в браузере (для владельца)
-Откройте страницу на компьютере или телефоне: при первом запуске браузер загрузит Pyodide и сэмплы гитары (далее они берутся из кеша браузера). Нажмите «Новая пьеса» (при желании задайте `seed`), запускайте воспроизведение кнопкой «Играть» или кликом по блокам секций на таймлайне. Перегенерируйте отдельные слои, закрепляйте удачные кнопкой «Закрепить» (параметры снизу всё равно действуют и на закреплённые секции), отменяйте и возвращайте шаги кнопками «Отменить: …» и «Вернуть», сразу меняйте глухие ноты ритм-гитары, долю октавных тактов, длину вступления, повтор квадрата в куплетах и прочие параметры снизу (дозы перегенерации скрыты в «Дополнительно») и скачивайте готовый результат в MIDI, MusicXML или ASCII-табах. Стек «Вернуть» хранится в состоянии пьесы рядом со стеком «Отменить» (до 50 шагов, команда `redo` в `web_api`). Все пьесы и журнал действий сохраняются локально в браузере; в боковой панели доступны «Скачать журнал» (`history.jsonl`), «Экспорт пьес» и «Импорт пьес» для переноса между устройствами.
+Откройте страницу на компьютере или телефоне: при первом запуске браузер загрузит Pyodide и сэмплы гитары (далее они берутся из кеша браузера). Нажмите «Новая пьеса» (при желании задайте `seed`), запускайте воспроизведение кнопкой «Играть» или кликом по блокам секций на таймлайне. Перегенерируйте отдельные слои, закрепляйте удачные кнопкой «Закрепить» (параметры снизу всё равно действуют и на закреплённые секции), отменяйте и возвращайте шаги кнопками «Отменить: …» и «Вернуть», сразу меняйте глухие ноты ритм-гитары, долю октавных тактов, длину вступления, повтор квадрата в куплетах, тональность и прочие параметры снизу (дозы перегенерации скрыты в «Дополнительно») и скачивайте готовый результат в MIDI, MusicXML или ASCII-табах. Стек «Вернуть» хранится в состоянии пьесы рядом со стеком «Отменить» (до 50 шагов, команда `redo` в `web_api`). Все пьесы и журнал действий сохраняются локально в браузере; в боковой панели доступны «Скачать журнал» (`history.jsonl`), «Экспорт пьес» и «Импорт пьес» для переноса между устройствами.
diff --git a/composer-lab/STUDIO-KEY-SPEC.md b/composer-lab/STUDIO-KEY-SPEC.md
new file mode 100644
index 0000000..b4579ab
--- /dev/null
+++ b/composer-lab/STUDIO-KEY-SPEC.md
@@ -0,0 +1,61 @@
+# Studio: change the key of a piece (specification)
+
+Base: `main` at 552831d (after #222 and #223). Both front ends
+(`studio/index.html`, Studio Web) share `studio/engine.py`, `studio/web_api.py`
+and `composer.py`.
+
+## Problem (from the owner)
+
+The owner wants to move a finished piece to another key and mode, e.g. from A major
+to D minor, keeping everything else: the same notes in the same places, each
+note moved to the same scale degree of the new scale.
+
+Today a recipe can be recomposed with another `intent.tonic` / `intent.mode`,
+but that is not "everything else unchanged". On seed 802000, A aeolian to
+E aeolian keeps the onsets but changes durations (4 -> 2, 8 -> 2) and legato,
+and the register jumps unevenly (77 -> 84 but 76 -> 71) because octave choice
+and fingering are re-derived per note. In 19 of 24 probes the note set
+changed by 0-12 notes per piece.
+
+## Required behaviour
+
+New whole-piece option `key`, stored in `studio.options`, default unset
+(today's output byte for byte). Value: `{"tonic": one of TONICS,
+"mode": one of ionian, dorian, phrygian, lydian, mixolydian, aeolian,
+locrian}`. It applies at once, is undoable/redoable and logged like other
+options; locks are unaffected (same rule as the other piece parameters).
+
+1. Every note keeps its onset, duration, guitar, velocity and articulation
+ intent (dead, palm mute, accent). Its pitch moves to the same scale degree
+ in the new scale. Chromatic notes (not in the old scale) keep their
+ offset from the nearest lower scale degree.
+2. Register: the whole piece shifts by one common octave offset chosen so that
+ all pitches fit the guitar range (40-88); within a phrase the melodic
+ contour (up/down/same between consecutive notes of one guitar) is
+ preserved. No per-note octave folding.
+3. Fingering is recomputed for the new pitches with the existing fretboard
+ pass; legato/slide/tap are kept where they remain playable under the
+ existing rules (same string, slide_max, taps above the fretting hand) and
+ dropped otherwise.
+4. After mapping, the existing minor-ninth rule between the guitars holds; if
+ a mapped note creates a minor ninth, apply the existing resolution and
+ report how often that happens in the tests.
+5. UI: "Тональность" in "Параметры пьесы" — a tonic choice (E, F#, G, A, B,
+ C#, D, as available in TONICS; add C and F only if trivially supported)
+ and a mode choice with Russian names (мажор, натуральный минор,
+ дорийский, фригийский, лидийский, миксолидийский, локрийский), plus
+ "Как в пьесе" to reset. Hint: "Переводит все ноты в выбранную тональность
+ по ступеням; ритм и форма не меняются. Применяется сразу." The piece header
+ shows the current key in Russian.
+
+## Tests (write first)
+
+- Unset key: byte-identical MIDI for the frozen seeds and 20 random seeds.
+- For 30 seeds and several target keys: onsets, durations, guitar assignment
+ identical to the source; each pitch is the mapped scale degree; contour
+ preserved per guitar; all pitches in 40-88; ComposerInvariants hold;
+ MusicXML measures fill their meter.
+- Mapping to the piece's own key is the identity.
+- A -> D minor -> back to the original key restores the original pitches
+ (round trip), when no note was clipped by range.
+- Undo/redo and web_api parity as for the other options.
diff --git a/composer-lab/composer.py b/composer-lab/composer.py
index 0a0c845..b3e5fbd 100644
--- a/composer-lab/composer.py
+++ b/composer-lab/composer.py
@@ -25,7 +25,10 @@
"mixolydian": [0, 2, 4, 5, 7, 9, 10],
"dorian": [0, 2, 3, 5, 7, 9, 10],
"aeolian": [0, 2, 3, 5, 7, 8, 10],
+ "phrygian": [0, 1, 3, 5, 7, 8, 10],
+ "locrian": [0, 1, 3, 5, 6, 8, 10],
}
+KEY_MODES = ("ionian", "dorian", "phrygian", "lydian", "mixolydian", "aeolian", "locrian")
TONICS = {"E": 4, "F#": 6, "A": 9, "B": 11, "D": 2, "G": 7, "C#": 1}
METERS = { # name: (sixteenths per bar, numerator, denominator, groupings)
"4/4": (16, 4, 4, [[3, 3, 3, 3, 4], [3, 3, 2, 3, 3, 2], [4, 4, 4, 4], [3, 3, 4, 3, 3]]),
@@ -710,7 +713,7 @@ def minor_ninth(a, b):
return abs(a - b) % 12 == 1 and a != b
-def resolve_minor_ninths(parts, lead, other):
+def resolve_minor_ninths(parts, lead, other, keyed=False):
"""The corpus has many major sevenths between the guitars but almost no
minor ninths. An accompaniment note sounding a minor ninth or semitone
against a lead note is cut short before it, or dropped when struck together
@@ -718,6 +721,9 @@ def resolve_minor_ninths(parts, lead, other):
resolved = []
keep = []
for m in sorted(parts[other], key=lambda n: n["start"]):
+ if keyed and "dead" in m["tech"]:
+ keep.append(m)
+ continue
end = m["start"] + m["dur"]
hits = [n for n in parts[lead] if m["start"] <= n["start"] < end and minor_ninth(n["pitch"], m["pitch"])]
under = [n for n in parts[lead] if n["start"] < m["start"] < n["start"] + n["dur"]
@@ -742,6 +748,8 @@ def resolve_minor_ninths(parts, lead, other):
p = by_string.get(n["string"]) if n.get("dyad") else prev
legato = {"hammer", "pull", "slide"} & set(n["tech"])
if legato and (p is None or p["string"] != n["string"] or p["fret"] == n["fret"]
+ or (keyed and "slide" not in legato
+ and (p["start"] + p["dur"] < n["start"] - 0.01 or n["start"] - p["start"] > 2))
or ("hammer" in legato and n["fret"] < p["fret"])
or ("pull" in legato and n["fret"] > p["fret"])):
n["tech"] = [x for x in n["tech"] if x not in legato]
@@ -751,6 +759,206 @@ def resolve_minor_ninths(parts, lead, other):
return resolved
+def map_degree(pitch, old, new):
+ """Pitch of the same scale degree in another scale; a chromatic note keeps
+ its offset above the lower degree, squeezed to stay below the next one.
+ Returns (pitch, merged) with merged set when it had to land on the degree."""
+ octave, rel = divmod(pitch - old.base, 12)
+ i = max(j for j in range(7) if old.scale[j] <= rel)
+ off = rel - old.scale[i]
+ gap = (new.scale[i + 1] if i < 6 else 12) - new.scale[i]
+ merged = off >= gap == 1
+ return new.base + 12 * octave + new.scale[i] + min(off, gap - 1), merged
+
+
+def _place(pitch, near_string, near_fret):
+ cands = [(s, pitch - o) for s, o in enumerate(fretboard.OPEN) if 0 <= pitch - o <= fretboard.MAX_FRET]
+ return min(cands, key=lambda c: (c[0] != near_string, abs(c[1] - near_fret), c[0]))
+
+
+def _place_group(group):
+ options = [[(s, n["pitch"] - o) for s, o in enumerate(fretboard.OPEN) if 0 <= n["pitch"] - o <= fretboard.MAX_FRET]
+ for n in group]
+ best = []
+
+ def walk(i, used, picks, cost):
+ if best and cost >= best[0]:
+ return
+ if i == len(group):
+ fretted = [f for _, f in picks if f]
+ if fretted and max(fretted) - min(fretted) > fretboard.SPAN:
+ return
+ total = cost + 0.5 * (max(fretted) - min(fretted) if fretted else 0)
+ if not best or total < best[0]:
+ best[:] = [total, list(picks)]
+ return
+ near_s, near_f = group[i]["fixed"]
+ for s, f in options[i]:
+ if s not in used:
+ walk(i + 1, used | {s}, picks + [(s, f)], cost + 3 * (s != near_s) + 0.1 * abs(f - near_f))
+
+ walk(0, frozenset(), [], 0.0)
+ return best[1] if best else None
+
+
+def _tidy_chords(parts, g, new, report, lo, hi):
+ """Within one guitar's chord, collapse doubled pitches and move or drop tones
+ that sit a semitone or a minor ninth from another tone or that form a low
+ cluster. The lowest tone and notes that are not fixed chord shapes stay."""
+ scale_pcs = {(new.tonic_pc + x) % 12 for x in new.scale}
+ by_start = {}
+ for n in parts[g]:
+ if "dead" not in n.get("preset_tech", ()):
+ by_start.setdefault(n["start"], []).append(n)
+ gone = set()
+ for group in by_start.values():
+ movable = {id(n) for n in group if n.get("fixed") and not n.get("dyad") and "preset_tech" not in n}
+ if not movable or len(group) < 2:
+ continue
+ live = lambda skip: [m for m in group if id(m) not in gone and m is not skip]
+ seen = set()
+ for n in sorted(group, key=lambda n: id(n) in movable):
+ if n["pitch"] in seen and id(n) in movable:
+ gone.add(id(n))
+ report["chord_collapsed"] += 1
+ seen.add(n["pitch"])
+ lowest = min((n for n in group if id(n) not in gone), key=lambda n: n["pitch"])
+ for n in sorted((n for n in group if id(n) in movable and id(n) not in gone), key=lambda n: -n["pitch"]):
+ if n is lowest or not any(abs(n["pitch"] - m["pitch"]) % 12 == 1 for m in live(n)):
+ continue
+ cands = sorted((p for p in range(n["pitch"] - 7, n["pitch"] + 8)
+ if lo <= p <= hi and p % 12 in scale_pcs and p != n["pitch"]),
+ key=lambda p: (abs(p - n["pitch"]), p))
+ fit = next((p for p in cands if all(abs(p - m["pitch"]) % 12 != 1 and p != m["pitch"] for m in live(n))), None)
+ if fit is None:
+ gone.add(id(n))
+ report["chord_dropped"] += 1
+ else:
+ n["pitch"] = fit
+ report["chord_moved"] += 1
+ for _ in range(len(group)):
+ low = sorted((n for n in live(None) if n["pitch"] < 66), key=lambda n: n["pitch"])
+ trio = next((t for t in zip(low, low[1:], low[2:]) if t[2]["pitch"] - t[0]["pitch"] <= 4), None)
+ if trio is None:
+ break
+ mid = trio[1]
+ if id(mid) not in movable:
+ break
+ if mid["pitch"] + 12 <= hi and all(m["pitch"] != mid["pitch"] + 12 for m in live(mid)):
+ mid["pitch"] += 12
+ report["chord_moved"] += 1
+ else:
+ gone.add(id(mid))
+ report["chord_dropped"] += 1
+ parts[g] = [n for n in parts[g] if id(n) not in gone]
+
+
+def _key_octave(old, new, ref):
+ d = new.tonic_pc - old.tonic_pc
+ near = (d + 6) % 12 - 6
+ options = [near] if near != -6 else [-6, 6]
+ mean = sum(ref) / len(ref)
+
+ def drift(x):
+ shifted = sum(map_degree(p, old, new)[0] + x - d for p in ref) / len(ref)
+ return round(abs(shifted - mean), 6), abs(shifted - 63)
+
+ return min(options, key=drift) - d
+
+
+def apply_key_to_parts(parts, chords, total16, old, new, ref):
+ """Map the pitches of an unfingered piece into another key before fingering.
+ One tonic shift of at most a tritone for the whole piece; a run of one guitar
+ inside a section leaving the fretboard moves by an octave as a whole, and only
+ when no octave fits the run are single chords or dyads folded."""
+ report = {"runs_moved": 0, "folded": 0, "merged": 0, "revoiced": 0,
+ "chord_moved": 0, "chord_dropped": 0, "chord_collapsed": 0}
+ shift = _key_octave(old, new, ref)
+ for g in ("g1", "g2"):
+ for n in parts[g]:
+ n["pitch"], merged = map_degree(n["pitch"], old, new)
+ n["pitch"] += shift
+ report["merged"] += merged
+ lo, hi = fretboard.OPEN[0], fretboard.OPEN[5] + fretboard.MAX_FRET
+ bar_starts = [c["start"] for c in chords]
+
+ def bar_of(n):
+ return max(s for s in bar_starts if s <= n["start"])
+
+ def tap_triad(n):
+ return n.get("fixed") and not n.get("dyad") and "preset_tech" in n
+
+ def fits(group, k):
+ return all(lo <= n["pitch"] + 12 * k <= hi for n in group)
+
+ def move(group, k):
+ for n in group:
+ n["pitch"] += 12 * k
+
+ for g in ("g1", "g2"):
+ for _sec, _occ, s0, s1 in _section_runs(chords, total16):
+ run = [n for n in parts[g] if s0 <= n["start"] < s1]
+ if fits(run, 0):
+ continue
+ high = max(n["pitch"] for n in run) > hi
+ order = (-1, 1, -2, 2) if high else (1, -1, 2, -2)
+ k = next((k for k in order if fits(run, k)), None)
+ if k is not None:
+ move(run, k)
+ report["runs_moved"] += 1
+ continue
+ groups = {}
+ for n in run:
+ groups.setdefault(("tap", bar_of(n), n["fixed"][0]) if tap_triad(n) else n["start"], []).append(n)
+ for group in groups.values():
+ if not fits(group, 0):
+ k = next((k for k in order if fits(group, k)), 0)
+ move(group, k)
+ report["folded"] += len(group)
+ for g in ("g1", "g2"):
+ _tidy_chords(parts, g, new, report, lo, hi)
+ by_start = {}
+ for n in parts[g]:
+ if n.get("fixed"):
+ by_start.setdefault(n["start"], []).append(n)
+ gone = set()
+ for group in by_start.values():
+ pos = _place_group(group)
+ for n in sorted(group, key=lambda n: n["pitch"]):
+ if pos is not None or n["pitch"] + 12 > hi:
+ continue
+ n["pitch"] += 12
+ ps = sorted(m["pitch"] for m in group)
+ if fretboard.low_cluster(ps) or any(b - a < 2 or (b - a) % 12 == 1 for a, b in zip(ps, ps[1:])):
+ n["pitch"] -= 12
+ continue
+ report["revoiced"] += 1
+ pos = _place_group(group)
+ while pos is None and len(group) > 1:
+ top = max(group, key=lambda n: n["pitch"])
+ group.remove(top)
+ gone.add(id(top))
+ report["chord_dropped"] += 1
+ pos = _place_group(group)
+ for n, p in zip(group, pos or [_place(n["pitch"], *n["fixed"]) for n in group]):
+ n["fixed"] = p
+ parts[g] = [n for n in parts[g] if id(n) not in gone]
+ triads = sorted((n for n in parts[g] if tap_triad(n)), key=lambda n: n["start"])
+ for prev, n in zip([None] + triads, triads):
+ leg = {"hammer", "pull"} & set(n["preset_tech"])
+ if leg and (prev is None or prev["fixed"][0] != n["fixed"][0] or n["start"] - prev["start"] > 2
+ or ("hammer" in leg and n["fixed"][1] <= prev["fixed"][1])
+ or ("pull" in leg and n["fixed"][1] >= prev["fixed"][1])):
+ n["preset_tech"] = [t for t in n["preset_tech"] if t not in leg]
+ for n in triads:
+ if "tap" in n["preset_tech"]:
+ nxt = next((m for m in triads if n["start"] < m["start"] <= n["start"] + 2
+ and m["fixed"][0] == n["fixed"][0] and "pull" in m["preset_tech"]), None)
+ if nxt is not None and nxt["fixed"][1] >= n["fixed"][1]:
+ n["preset_tech"] = [t for t in n["preset_tech"] if t != "tap"]
+ return report
+
+
def apply_rests_and_pushes(parts, lead, other, form, spans, plan):
"""Rests at square boundaries and rhythm-guitar anticipations (the last
hits of a bar an eighth early), as listed in plan."""
@@ -1512,6 +1720,7 @@ def _prepare_studio(recipe, arp, v8):
mute_share = max(0.0, min(1.0, float(opts.get("mute_share", 0.0))))
square_repeat = int(opts.get("square_repeat", 1))
+ key = opts.get("key")
return {
"hook": hook,
@@ -1526,6 +1735,7 @@ def _prepare_studio(recipe, arp, v8):
"end_riff": end_riff,
"mute_share": mute_share,
"square_repeat": square_repeat,
+ "key": key,
}
@@ -1849,6 +2059,13 @@ def phrase_anchor(sec, root, lift, tone=None):
opts = [p for p in range(n["pitch"] - 9, n["pitch"] + 10)
if (p - th.tonic_pc) % 12 in th.scale and 40 <= p <= 86]
n["pitch"] = crng.choice(opts)
+ key_report = None
+ if st_cfg is not None and st_cfg["key"]:
+ new_th = Theory(TONICS[st_cfg["key"]["tonic"]], st_cfg["key"]["mode"])
+ if (new_th.tonic_pc, new_th.scale) != (th.tonic_pc, th.scale):
+ ref = [n["pitch"] for g in ("g1", "g2") for n in st_cfg["base"]["pre"][g]]
+ key_report = apply_key_to_parts(parts, chords, t, th, new_th, ref)
+ th = new_th
for g in ("g1", "g2"):
for n in parts[g]:
while n["pitch"] > 86:
@@ -1920,10 +2137,15 @@ def phrase_anchor(sec, root, lift, tone=None):
for g in ("g1", "g2"):
out_parts[g].extend(sec_parts[g])
parts = out_parts
- if fix:
- report["m9_resolved"] = resolve_minor_ninths(parts, lead, other)
+ keyed = key_report is not None
+ if keyed and st_cfg["mute_share"] > 0.0:
+ _apply_mute_share(parts, other, chords, t, recipe["seed"], st_cfg["mute_share"])
+ if fix or keyed:
+ report["m9_resolved"] = resolve_minor_ninths(parts, lead, other, keyed=keyed)
+ if keyed:
+ _strip_legato_from_dead(parts[other])
_validate_octave_slides(parts)
- if st_cfg["mute_share"] > 0.0:
+ if not keyed and st_cfg["mute_share"] > 0.0:
_apply_mute_share(parts, other, chords, t, recipe["seed"], st_cfg["mute_share"])
if st_cfg["square_repeat"] > 1:
t = _apply_square_repeat(
@@ -1960,6 +2182,8 @@ def phrase_anchor(sec, root, lift, tone=None):
_trace["spans"] = [
[sec, st0, starts[k + 1][1] if k + 1 < len(starts) else t] for k, (sec, st0) in enumerate(starts)
]
+ if key_report is not None:
+ report["key"] = key_report
return {"tempo": tempo, "meters": meters, "parts": parts,
"chords": chords,
"total16": t, "report": report, "theory": th}
diff --git a/composer-lab/studio/engine.py b/composer-lab/studio/engine.py
index d796515..463febe 100644
--- a/composer-lab/studio/engine.py
+++ b/composer-lab/studio/engine.py
@@ -58,6 +58,17 @@
"octave_sixteenths": "октавы шестнадцатыми",
"dead_notes": "глухие удары перед акцентами",
"slide_max": "макс. слайд октав",
+ "key": "тональность",
+}
+
+KEY_MODE_LABELS = {
+ "ionian": "мажор",
+ "dorian": "дорийский",
+ "phrygian": "фригийский",
+ "lydian": "лидийский",
+ "mixolydian": "миксолидийский",
+ "aeolian": "натуральный минор",
+ "locrian": "локрийский",
}
B_LEAD_LABELS = {"augmented": "медленнее", "same_speed": "в темпе рифа", "rest": "без соло"}
@@ -82,6 +93,7 @@ def default_options():
"octave_sixteenths": float(composer.V8["octave_sixteenths"]),
"dead_notes": float(composer.V8["dead_notes"]),
"slide_max": int(composer.V8["slide_max"]),
+ "key": None,
}
@@ -144,6 +156,8 @@ def _option_text(name, value):
label = OPTION_LABELS.get(name, name)
if name == "b_lead":
return f"{label}: {B_LEAD_LABELS.get(value, value)}"
+ if name == "key":
+ return f"{label}: {value['tonic']} {KEY_MODE_LABELS[value['mode']]}" if value else f"{label}: как в пьесе"
if value is None or value == "auto":
return f"{label}: авто"
return f"{label} {value:g}" if isinstance(value, float) else f"{label} {value}"
@@ -245,7 +259,9 @@ def set_lock(recipe, layer, section, locked):
riffs.pop(key, None)
elif key not in riffs:
trace = {}
- composer.compose(rec, _trace=trace)
+ unkeyed = copy.deepcopy(rec)
+ unkeyed["studio"]["options"]["key"] = None
+ composer.compose(unkeyed, _trace=trace)
riffs[key] = json.loads(json.dumps(trace["riff"].get("A3") or trace["riff"].get("A") or []))
return rec
@@ -256,6 +272,28 @@ def _number(value, what):
return value
+def parse_key(value):
+ if value is None:
+ return None
+ if (
+ not isinstance(value, dict)
+ or set(value) != {"tonic", "mode"}
+ or not isinstance(value["tonic"], str)
+ or not isinstance(value["mode"], str)
+ or value["tonic"] not in composer.TONICS
+ or value["mode"] not in composer.KEY_MODES
+ ):
+ raise ValueError(f"invalid key: {value}")
+ return {"tonic": value["tonic"], "mode": value["mode"]}
+
+
+def _parse_key(value, intent):
+ key = parse_key(value)
+ if key == {"tonic": intent["tonic"], "mode": intent["mode"]}:
+ return None
+ return key
+
+
def set_option(recipe, name, value):
_require_text(name, "name")
rec = _ensure_studio(recipe)
@@ -303,6 +341,8 @@ def set_option(recipe, name, value):
if opts[name] != clamped:
_backfill_comp_doses(st)
opts[name] = clamped
+ elif name == "key":
+ opts["key"] = _parse_key(value, rec["intent"])
else:
raise ValueError(f"unknown option: {name}")
return rec
@@ -361,8 +401,9 @@ def layer_info(layer, section):
"id": piece_id,
"seed": rec["seed"],
"meter": rec["intent"]["meter"],
- "mode": rec["intent"]["mode"],
- "key": rec["intent"]["tonic"],
+ "mode": (st["options"]["key"] or rec["intent"])["mode"],
+ "key": (st["options"]["key"] or rec["intent"])["tonic"],
+ "own_key": {"tonic": rec["intent"]["tonic"], "mode": rec["intent"]["mode"]},
"tempo": piece["tempo"],
"length": round(piece["total16"] * 15.0 / piece["tempo"], 2),
"sections": sections,
diff --git a/composer-lab/studio/index.html b/composer-lab/studio/index.html
index e9e1b6f..55e206e 100644
--- a/composer-lab/studio/index.html
+++ b/composer-lab/studio/index.html
@@ -286,6 +286,16 @@
Griff Studio
locrian: "локрийский",
};
const modeLabel = (mode) => MODE_LABELS[mode] || mode;
+const KEY_TONICS = ["E", "F#", "G", "A", "B", "C#", "D"];
+const KEY_MODES = [
+ ["ionian", "мажор"],
+ ["dorian", "дорийский"],
+ ["phrygian", "фригийский"],
+ ["lydian", "лидийский"],
+ ["mixolydian", "миксолидийский"],
+ ["aeolian", "натуральный минор"],
+ ["locrian", "локрийский"],
+];
const state = { pieces: [], current: null, currentId: null, busyCount: 0, chipCount: 0, error: "", navSeq: 0, editSeq: 0, pendingSliders: [] };
function setChip(delta) {
@@ -599,16 +609,11 @@ Параметры пьесы
grid.appendChild(wrap);
}
- function addChoiceGroup(grid, title, name, choices, current, hint) {
- const box = document.createElement("div");
- const titleEl = document.createElement("div");
- titleEl.className = "piece-meta";
- titleEl.style.marginBottom = "6px";
- titleEl.textContent = title;
+ function makeChoiceRow(label, name, choices, current, pick, force) {
const row = document.createElement("div");
row.className = "row";
row.setAttribute("role", "group");
- row.setAttribute("aria-label", title);
+ row.setAttribute("aria-label", label);
for (const [val, txt] of choices) {
const selected = current === val;
const b = document.createElement("button");
@@ -618,16 +623,72 @@ Параметры пьесы
b.textContent = txt;
b.setAttribute("aria-pressed", selected ? "true" : "false");
b.onclick = () => {
- if (!selected) sendOption(name, val, b);
+ if (!selected || (force && force())) pick(val, b);
};
row.appendChild(b);
}
+ return row;
+ }
+
+ function addChoiceGroup(grid, title, name, choices, current, hint) {
+ const box = document.createElement("div");
+ const titleEl = document.createElement("div");
+ titleEl.className = "piece-meta";
+ titleEl.style.marginBottom = "6px";
+ titleEl.textContent = title;
box.appendChild(titleEl);
- box.appendChild(row);
+ box.appendChild(makeChoiceRow(title, name, choices, current, (val, b) => sendOption(name, val, b)));
if (hint) addOptionHint(box, hint);
grid.appendChild(box);
}
+ function pendingKey() {
+ return state.keyPending && state.keyPending.id === d.id ? state.keyPending.value : null;
+ }
+
+ function trackKey(value, request) {
+ state.keyPending = { id: d.id, value };
+ state.keyBusy = (state.keyBusy || 0) + 1;
+ return Promise.resolve(request()).finally(() => {
+ if (--state.keyBusy === 0) state.keyPending = null;
+ });
+ }
+
+ function sendKey(patch, ctl) {
+ const pending = pendingKey();
+ const next = Object.assign({}, pending || { tonic: d.key, mode: d.mode }, patch);
+ return trackKey(next, () => sendOption("key", next, ctl));
+ }
+
+ function resetKey(ctl) {
+ return trackKey(d.own_key || { tonic: d.key, mode: d.mode }, () => sendOption("key", null, ctl));
+ }
+
+ function addKeyControl(grid) {
+ const title = "Тональность";
+ const box = document.createElement("div");
+ const titleEl = document.createElement("div");
+ titleEl.className = "piece-meta";
+ titleEl.style.marginBottom = "6px";
+ titleEl.textContent = title;
+ box.appendChild(titleEl);
+ box.appendChild(
+ makeChoiceRow(`${title}: основной тон`, "key_tonic", KEY_TONICS.map((t) => [t, t]), d.key, (t, b) =>
+ sendKey({ tonic: t }, b)
+ )
+ );
+ box.appendChild(
+ makeChoiceRow(`${title}: лад`, "key_mode", KEY_MODES, d.mode, (m, b) => sendKey({ mode: m }, b))
+ );
+ box.appendChild(
+ makeChoiceRow(`${title}: как в пьесе`, "key", [["auto", "Как в пьесе"]], opts.key ? null : "auto", (v, b) =>
+ resetKey(b), pendingKey
+ )
+ );
+ addOptionHint(box, "Переводит все ноты в выбранную тональность по ступеням; ритм и форма не меняются. Применяется сразу.");
+ grid.appendChild(box);
+ }
+
addSliderControl(
oGrid,
"mute_share",
@@ -720,6 +781,7 @@ Параметры пьесы
opts.square_repeat ?? 1,
"Повторяет 4-тактовый квадрат куплетов A и A2 дважды подряд; применяется сразу."
);
+ addKeyControl(oGrid);
addChoiceGroup(
oGrid,
"Соло в середине B",
diff --git a/composer-lab/studio/web_api.py b/composer-lab/studio/web_api.py
index 58e5032..68769de 100644
--- a/composer-lab/studio/web_api.py
+++ b/composer-lab/studio/web_api.py
@@ -85,11 +85,20 @@ def _validate_recipe(rec):
v = opts[k]
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0.0 <= float(v) <= 1.0:
raise ValueError(f"invalid studio.options.{k}")
+ if "key" in opts:
+ try:
+ engine.parse_key(opts["key"])
+ except ValueError:
+ raise ValueError("invalid studio.options.key") from None
if "slide_max" in opts:
sm = opts["slide_max"]
if not _is_int(sm) or not 0 <= sm <= 12:
raise ValueError("invalid studio.options.slide_max")
- return copy.deepcopy(rec)
+ rec = copy.deepcopy(rec)
+ opts = (rec.get("studio") or {}).get("options") or {}
+ if opts.get("key") == {"tonic": intent["tonic"], "mode": intent["mode"]}:
+ opts["key"] = None
+ return rec
def _validate_history(state, key):
diff --git a/composer-lab/test_studio.py b/composer-lab/test_studio.py
index cce0242..81d2569 100644
--- a/composer-lab/test_studio.py
+++ b/composer-lab/test_studio.py
@@ -1,4 +1,5 @@
import argparse
+import collections
import copy
import hashlib
import json
@@ -2712,5 +2713,566 @@ def test_composer_invariants_with_random_control_combinations(self):
self.assertLess(bad_clash / max(1, shared_clash), 0.03, (bad_clash, shared_clash))
+KEY_TARGETS = (
+ ("D", "aeolian"), ("E", "ionian"), ("G", "dorian"), ("F#", "locrian"),
+ ("B", "phrygian"), ("C#", "mixolydian"), ("D", "lydian"),
+)
+KEY_SEEDS = [s * 1000 for s in range(801, 831)]
+KEY_STATS = collections.Counter()
+
+ORACLE_SCALES = {
+ "ionian": (0, 2, 4, 5, 7, 9, 11), "dorian": (0, 2, 3, 5, 7, 9, 10), "phrygian": (0, 1, 3, 5, 7, 8, 10),
+ "lydian": (0, 2, 4, 6, 7, 9, 11), "mixolydian": (0, 2, 4, 5, 7, 9, 10), "aeolian": (0, 2, 3, 5, 7, 8, 10),
+ "locrian": (0, 1, 3, 5, 6, 8, 10),
+}
+ORACLE_PC = {"E": 4, "F#": 6, "A": 9, "B": 11, "D": 2, "G": 7, "C#": 1}
+
+
+def oracle_pitch(p, old, new, shift):
+ t_old = 48 + ORACLE_PC[old[0]]
+ octave, r = divmod(p - t_old, 12)
+ scale = ORACLE_SCALES[old[1]]
+ idx = max(i for i, x in enumerate(scale) if x <= r)
+ new_scale = ORACLE_SCALES[new[1]]
+ gap = (new_scale[idx + 1] if idx < 6 else 12) - new_scale[idx]
+ return t_old + shift + 12 * octave + new_scale[idx] + min(r - scale[idx], gap - 1)
+
+
+def oracle_shift(old, new, ref):
+ diff = (ORACLE_PC[new[0]] - ORACLE_PC[old[0]]) % 12
+ if diff != 6:
+ return diff if diff < 6 else diff - 12
+ mean = sum(ref) / len(ref)
+ return min((-6, 6), key=lambda s: (round(abs(sum(oracle_pitch(p, old, new, s) for p in ref) / len(ref) - mean), 6),
+ abs(sum(oracle_pitch(p, old, new, s) for p in ref) / len(ref) - 63)))
+
+
+def map_notes(pitches, old, new, ref=None):
+ parts = {"g1": [{"pitch": p, "start": i, "dur": 1} for i, p in enumerate(pitches)], "g2": []}
+ chords = [{"start": 0, "sec": "A"}]
+ rep = composer.apply_key_to_parts(
+ parts, chords, len(pitches), composer.Theory(composer.TONICS[old[0]], old[1]),
+ composer.Theory(composer.TONICS[new[0]], new[1]), ref or pitches)
+ return [n["pitch"] for n in parts["g1"]], rep
+
+
+def sign(x):
+ return (x > 0) - (x < 0)
+
+
+def keyed(seed, tonic, mode, **opts):
+ rec = studio_engine.new_recipe(seed)
+ for name, val in opts.items():
+ rec = studio_engine.set_option(rec, name, val)
+ return rec, studio_engine.set_option(rec, "key", {"tonic": tonic, "mode": mode})
+
+
+def notes_at(piece, g, start):
+ return [n for n in piece["parts"][g] if n["start"] == start]
+
+
+class TestStudioKey(unittest.TestCase):
+ @classmethod
+ def tearDownClass(cls):
+ if KEY_STATS["pieces"]:
+ print(f"\nkey change: {dict(KEY_STATS)}", file=sys.stderr)
+
+ def assert_playable(self, p, ctx):
+ for g, notes in p["parts"].items():
+ for n in notes:
+ self.assertTrue(40 <= n["pitch"] <= 88, (ctx, g, n))
+ self.assertTrue(0 <= n["fret"] <= fretboard.MAX_FRET, (ctx, g, n))
+ self.assertEqual(fretboard.OPEN[n["string"]] + n["fret"], n["pitch"], (ctx, g, n))
+ seen = {}
+ for n in notes:
+ self.assertNotIn((n["start"], n["string"]), seen, (ctx, g, n))
+ seen[(n["start"], n["string"])] = n
+ chords = {}
+ for n in notes:
+ if "dead" not in n["tech"]:
+ chords.setdefault(n["start"], []).append(n)
+ for start, group in chords.items():
+ if len(group) < 2:
+ continue
+ fretted = [n["fret"] for n in group if n["fret"]]
+ self.assertLessEqual(max(fretted) - min(fretted) if fretted else 0, fretboard.SPAN, (ctx, g, start))
+ pitches = sorted(n["pitch"] for n in group)
+ self.assertEqual(len(set(pitches)), len(pitches), (ctx, g, start, pitches))
+ self.assertFalse(any((b - a) % 12 == 1 for a, b in zip(pitches, pitches[1:])), (ctx, g, start, pitches))
+ self.assertFalse(fretboard.low_cluster(pitches), (ctx, g, start, pitches))
+ line = [n for n in notes if not n.get("chordtone") and not n.get("dyad")
+ and not (n.get("fixed") and "preset_tech" not in n)]
+ for prev, n in zip(line, line[1:]):
+ if {"hammer", "pull", "slide"} & set(n["tech"]):
+ self.assertEqual(prev["string"], n["string"], (ctx, g, n))
+ if {"hammer", "pull"} & set(n["tech"]):
+ self.assertGreaterEqual(prev["start"] + prev["dur"], n["start"] - 0.01, (ctx, g, prev, n))
+ if "hammer" in n["tech"]:
+ self.assertGreater(n["fret"], prev["fret"], (ctx, g, n))
+ if "tap" in n["tech"] and not n.get("fixed"):
+ self.assertTrue(n["fret"] > 0, (ctx, g, n))
+ for prev, n in zip(notes, notes[1:]):
+ if "tap" in prev["tech"] and n["string"] == prev["string"] and n["fret"] > 0 and not n.get("fixed"):
+ self.assertGreater(prev["fret"], n["fret"], (ctx, g, prev, n))
+ last = {}
+ for n in sorted((x for x in notes if x.get("dyad")), key=lambda x: x["start"]):
+ if "slide" in n["tech"]:
+ q = last.get(n["string"])
+ self.assertTrue(q is not None and q["fret"] != n["fret"], (ctx, g, n))
+ last[n["string"]] = n
+ for n in notes:
+ if "tap" in n.get("tech", []) and n.get("fixed"):
+ nxt = [m for m in notes if n["start"] < m["start"] <= n["start"] + 2
+ and m["string"] == n["string"] and "pull" in m.get("tech", [])][:1]
+ for m in nxt:
+ self.assertGreater(n["fret"], m["fret"], (ctx, g, n))
+ with tempfile.TemporaryDirectory() as d:
+ composer.export(p, Path(d) / "x")
+ root = ET.parse(Path(d) / "x.musicxml").getroot()
+ for part in root.iter("part"):
+ num = den = None
+ for m in part.iter("measure"):
+ t = m.find("attributes/time")
+ if t is not None:
+ num, den = int(t.findtext("beats")), int(t.findtext("beat-type"))
+ total = sum(int(n.findtext("duration")) for n in m.iter("note") if n.find("chord") is None)
+ self.assertEqual(total, num * 16 // den, (ctx, part.get("id"), m.get("number")))
+
+ def assert_no_minor_ninth(self, p, ctx):
+ for x, y in (("g1", "g2"), ("g2", "g1")):
+ for n in p["parts"][x]:
+ if "dead" in n["tech"]:
+ continue
+ for m in p["parts"][y]:
+ if "dead" not in m["tech"] and m["start"] <= n["start"] < m["start"] + m["dur"]:
+ self.assertFalse(composer.minor_ninth(n["pitch"], m["pitch"]), (ctx, n, m))
+
+ def test_unset_key_is_byte_identical_and_own_key_is_unset(self):
+ rng = random.Random(20261123)
+ rand_seeds = rng.sample(range(1000, 999999), 20)
+ for seed in [s * 1000 for s in (801, 802, 805, 807, 809, 810)] + rand_seeds:
+ rec = studio_engine.new_recipe(seed)
+ self.assertIsNone(rec["studio"]["options"]["key"])
+ plain = {k: v for k, v in rec.items() if k != "studio"}
+ base = midi_sha256(composer.compose(plain))
+ self.assertEqual(midi_sha256(composer.compose(rec)), base, seed)
+ legacy = copy.deepcopy(rec)
+ del legacy["studio"]["options"]["key"]
+ self.assertEqual(midi_sha256(composer.compose(legacy)), base, seed)
+ own = {"tonic": rec["intent"]["tonic"], "mode": rec["intent"]["mode"]}
+ self.assertEqual(studio_engine.set_option(rec, "key", own), rec, seed)
+ there = studio_engine.set_option(rec, "key", {"tonic": "D", "mode": "locrian"})
+ self.assertEqual(midi_sha256(composer.compose(studio_engine.set_option(there, "key", None))), base, seed)
+
+ def test_hand_checked_degree_mapping(self):
+ cases = (
+ ((("E", "ionian"), ("E", "phrygian")), (64, 68, 71, 66, 65), (64, 67, 71, 65, 64)),
+ ((("A", "aeolian"), ("D", "aeolian")), (69, 72), (74, 77)),
+ ((("E", "ionian"), ("E", "locrian")), (71,), (70,)),
+ ((("D", "locrian"), ("D", "ionian")), (56,), (57,)),
+ ((("A", "phrygian"), ("A", "aeolian")), (58,), (59,)),
+ ((("G", "mixolydian"), ("C#", "ionian")), (77,), (72,)),
+ ((("G", "mixolydian"), ("C#", "phrygian")), (59,), (64,)),
+ )
+ for (old, new), src, expected in cases:
+ for p, e in zip(src, expected):
+ got, _ = map_notes([p], old, new)
+ self.assertEqual(got, [e], (old, new, p))
+ merged = map_notes([65, 66], ("E", "ionian"), ("E", "phrygian"))
+ self.assertEqual(merged, ([64, 65], {"runs_moved": 0, "folded": 0, "merged": 1, "revoiced": 0,
+ "chord_moved": 0, "chord_dropped": 0, "chord_collapsed": 0}))
+ wide = map_notes([55, 60, 66, 64, 71, 85], ("E", "ionian"), ("B", "locrian"))[0]
+ self.assertTrue(all(40 <= p <= 86 for p in wide), wide)
+
+ def test_every_mode_pair_matches_the_independent_oracle(self):
+ for pitches in (list(range(48, 85, 3)), list(range(55, 70, 2))):
+ for old_tonic in ("E", "A", "D"):
+ for old_mode in composer.KEY_MODES:
+ for new_tonic in composer.TONICS:
+ for new_mode in composer.KEY_MODES:
+ old, new = (old_tonic, old_mode), (new_tonic, new_mode)
+ got, rep = map_notes(pitches, old, new)
+ shift = oracle_shift(old, new, pitches)
+ want = [oracle_pitch(p, old, new, shift) for p in pitches]
+ high = max(want) > 86
+ order = (-1, 1, -2, 2) if high else (1, -1, 2, -2)
+ if min(want) >= 40 and not high:
+ expected = want
+ else:
+ k = next((k for k in order if all(40 <= p + 12 * k <= 86 for p in want)), None)
+ expected = want if k is None else [p + 12 * k for p in want]
+ if rep["folded"] == 0:
+ self.assertEqual(got, expected, (old, new))
+ else:
+ self.assertTrue(all((a - b) % 12 == 0 for a, b in zip(got, want)), (old, new))
+
+ def test_round_trip_restores_pitches_and_fails_when_mapping_is_a_no_op(self):
+ checked = 0
+ for old in (("E", "ionian"), ("G", "mixolydian"), ("A", "aeolian"), ("D", "dorian")):
+ scale = ORACLE_SCALES[old[1]]
+ src = [p for p in range(50, 80) if (p - 48 - ORACLE_PC[old[0]]) % 12 in scale][::2]
+ for new in (("D", "aeolian"), ("C#", "ionian"), ("E", "phrygian"), ("B", "locrian"), ("G", "lydian")):
+ if new == old:
+ continue
+ there, _ = map_notes(src, old, new)
+ self.assertNotEqual(there, src, (old, new))
+ back, _ = map_notes(there, new, old)
+ self.assertEqual(back, src, (old, new))
+ checked += 1
+ self.assertEqual(map_notes([67], ("G", "ionian"), ("C#", "ionian"))[0], [61])
+ self.assertEqual(map_notes([61], ("C#", "ionian"), ("G", "ionian"))[0], [67])
+ self.assertGreater(checked, 15)
+
+ def test_notes_move_to_the_same_scale_degree_and_nothing_else_changes(self):
+ for seed in KEY_SEEDS:
+ rec = studio_engine.new_recipe(seed)
+ trace = {}
+ src = composer.compose(rec, _trace=trace)
+ pre = trace["pre"]
+ ref = [n["pitch"] for g in ("g1", "g2") for n in pre[g]]
+ old = (rec["intent"]["tonic"], rec["intent"]["mode"])
+ for tonic, mode in KEY_TARGETS:
+ if (tonic, mode) == old:
+ continue
+ ktrace = {}
+ krec = studio_engine.set_option(rec, "key", {"tonic": tonic, "mode": mode})
+ dst = composer.compose(krec, _trace=ktrace)
+ ctx = (seed, tonic, mode)
+ rep = dst["report"]["key"]
+ resolved = set(dst["report"]["m9_resolved"])
+ shift = oracle_shift(old, (tonic, mode), ref)
+ KEY_STATS["pieces"] += 1
+ for name in ("runs_moved", "folded", "merged", "revoiced", "chord_moved", "chord_dropped", "chord_collapsed"):
+ KEY_STATS[name] += rep[name]
+ KEY_STATS["pieces_with_moved_run"] += rep["runs_moved"] > 0
+ KEY_STATS["pieces_with_folds"] += rep["folded"] > 0
+ self.assertEqual(dst["total16"], src["total16"], ctx)
+ self.assertEqual(dst["chords"], src["chords"], ctx)
+ moved_notes = 0
+ for g in ("g1", "g2"):
+ a_notes, b_notes = pre[g], ktrace["pre"][g]
+ if len(a_notes) != len(b_notes):
+ self.assertGreater(rep["chord_dropped"] + rep["chord_collapsed"], 0, ctx)
+ key = lambda n: (n["start"], n["dur"], n["vel"])
+ self.assertFalse(collections.Counter(map(key, b_notes)) - collections.Counter(map(key, a_notes)), ctx)
+ continue
+ deltas = []
+ off_degree = 0
+ for a, b in zip(a_notes, b_notes):
+ self.assertEqual((a["start"], a["dur"], a["vel"]), (b["start"], b["dur"], b["vel"]), (ctx, g, a))
+ delta = b["pitch"] - oracle_pitch(a["pitch"], old, (tonic, mode), shift)
+ off_degree += delta % 12 != 0
+ deltas.append(delta)
+ self.assertLessEqual(off_degree, rep["chord_moved"], (ctx, g))
+ moved_notes += sum(x != 0 for x in deltas) # includes chord tones moved by tidy
+ for i in range(len(a_notes) - 1):
+ if deltas[i] == deltas[i + 1] and a_notes[i]["start"] < a_notes[i + 1]["start"]:
+ self.assertEqual(sign(b_notes[i + 1]["pitch"] - b_notes[i]["pitch"]),
+ sign(a_notes[i + 1]["pitch"] - a_notes[i]["pitch"]), (ctx, g, i))
+ adjusted = rep["runs_moved"] + rep["folded"] + rep["revoiced"] + rep["chord_moved"] + rep["chord_dropped"]
+ self.assertEqual(adjusted > 0, moved_notes > 0, ctx)
+ chord_budget = rep["chord_dropped"] + rep["chord_collapsed"]
+ for g in ("g1", "g2"):
+ pool = collections.Counter((n["start"], n["vel"]) for n in dst["parts"][g])
+ for n in src["parts"][g]:
+ KEY_STATS["notes"] += 1
+ if pool[(n["start"], n["vel"])] > 0:
+ pool[(n["start"], n["vel"])] -= 1
+ else:
+ if n["start"] not in resolved:
+ chord_budget -= 1
+ self.assertGreaterEqual(chord_budget, 0, (ctx, g, n))
+ self.assertNotIn("dead", n["tech"], (ctx, g, n))
+ KEY_STATS["dropped"] += 1
+ self.assertEqual(
+ sum("dead" in n["tech"] for g in dst["parts"] for n in dst["parts"][g]),
+ sum("dead" in n["tech"] for g in src["parts"] for n in src["parts"][g]), ctx)
+ same = [sorted(a["tech"]) == sorted(b["tech"]) for g in ("g1", "g2")
+ if len(src["parts"][g]) == len(dst["parts"][g])
+ for a, b in zip(src["parts"][g], dst["parts"][g])]
+ KEY_STATS["tech_differs"] += same.count(False)
+ KEY_STATS["tech_compared"] += len(same)
+ self.assert_playable(dst, ctx)
+ self.assert_no_minor_ninth(dst, ctx)
+
+ def chord(self, pitches, old, new):
+ parts = {"g1": [{"pitch": p, "start": 0, "dur": 4, "vel": 80, "fixed": (1, max(0, p - 45)), "ring": True}
+ for p in pitches], "g2": []}
+ rep = composer.apply_key_to_parts(
+ parts, [{"start": 0, "sec": "A"}], 16, composer.Theory(composer.TONICS[old[0]], old[1]),
+ composer.Theory(composer.TONICS[new[0]], new[1]), pitches)
+ return parts["g1"], rep
+
+ def test_regression_chord_tones_are_moved_dropped_or_collapsed(self):
+ notes, rep = self.chord([57, 59, 64, 71], ("G", "mixolydian"), ("D", "aeolian"))
+ ps = sorted(n["pitch"] for n in notes)
+ self.assertEqual(len(set(ps)), len(ps))
+ self.assertFalse(any(abs(a - b) % 12 == 1 for a in ps for b in ps), ps)
+ self.assertGreater(rep["chord_moved"] + rep["chord_dropped"], 0)
+ self.assertEqual(ps[0], 52)
+ fretted = [n["fixed"][1] for n in notes if n["fixed"][1]]
+ self.assertLessEqual(max(fretted) - min(fretted), fretboard.SPAN)
+ notes, rep = self.chord([64, 65], ("E", "ionian"), ("E", "phrygian"))
+ self.assertEqual([n["pitch"] for n in notes], [64])
+ self.assertEqual(rep["chord_collapsed"], 1)
+ notes, rep = self.chord([40, 44, 47, 52], ("E", "ionian"), ("E", "ionian"))
+ self.assertEqual(len(notes), 4)
+ cluster, rep = self.chord([55, 57, 60], ("A", "aeolian"), ("A", "dorian"))
+ self.assertFalse(fretboard.low_cluster([n["pitch"] for n in cluster]))
+
+ def test_regression_chords_keep_a_playable_span_and_stay_consonant(self):
+ for seed, tonic, mode, g, start in ((986307, "C#", "ionian", "g2", 128), (801000, "D", "aeolian", "g1", 323)):
+ _, krec = keyed(seed, tonic, mode)
+ p = composer.compose(krec)
+ self.assert_playable(p, (seed, tonic, mode))
+ group = notes_at(p, g, start)
+ self.assertGreaterEqual(len(group), 2)
+ fretted = [n["fret"] for n in group if n["fret"]]
+ self.assertLessEqual(max(fretted) - min(fretted) if fretted else 0, fretboard.SPAN)
+ rec = studio_engine.new_recipe(986307)
+ p = composer.compose(studio_engine.set_option(rec, "key", {"tonic": "D", "mode": "aeolian"}))
+ self.assert_playable(p, 986307)
+
+ def test_runs_move_whole_and_square_copies_decide_alike(self):
+ for seed, tonic, mode in ((801000, "F#", "locrian"), (801000, "D", "aeolian"), (802000, "B", "phrygian")):
+ rec, krec = keyed(seed, tonic, mode, square_repeat=2)
+ p = composer.compose(krec)
+ spans = section_spans(p)
+ a_spans = [(s, e) for sec, s, e in spans if sec == "A"]
+ half = (a_spans[0][1] - a_spans[0][0]) // 2
+ for g in ("g1", "g2"):
+ first = section_notes(p, g, a_spans[0][0], a_spans[0][0] + half)
+ second = section_notes(p, g, a_spans[0][0] + half, a_spans[0][1])
+ self.assertEqual(first, second, (seed, g))
+
+ def test_regression_octave_fold_keeps_descent_and_octave_chord(self):
+ _, krec = keyed(801000, "D", "aeolian")
+ p = composer.compose(krec)
+ a, b = notes_at(p, "g1", 5), notes_at(p, "g1", 6)
+ self.assertTrue(a and b)
+ self.assertGreater(a[0]["pitch"], b[0]["pitch"])
+ rec = studio_engine.set_option(studio_engine.new_recipe(40), "octave_share", 1.0)
+ p = composer.compose(studio_engine.set_option(rec, "key", {"tonic": "C#", "mode": "mixolydian"}))
+ dyads = [n for g in p["parts"] for n in p["parts"][g] if n["start"] == 42 and n.get("dyad")]
+ self.assertEqual(len(dyads), 2)
+ self.assertEqual(abs(dyads[0]["pitch"] - dyads[1]["pitch"]), 12)
+ self.assertNotEqual((dyads[0]["string"], dyads[0]["fret"]), (dyads[1]["string"], dyads[1]["fret"]))
+
+ def test_regression_fingering_never_stacks_or_overlaps_a_string(self):
+ for seed, tonic, mode in ((801000, "F#", "locrian"), (807000, "G", "dorian"), (70, "E", "ionian"),
+ (834000, "G", "dorian"), (23, "D", "aeolian")):
+ _, krec = keyed(seed, tonic, mode)
+ p = composer.compose(krec)
+ self.assert_playable(p, (seed, tonic, mode))
+ for g in ("g1", "g2"):
+ by_string = {}
+ for n in sorted(p["parts"][g], key=lambda n: n["start"]):
+ prev = by_string.get(n["string"])
+ if prev is not None and prev["start"] < n["start"]:
+ self.assertLessEqual(prev["start"] + prev["dur"], n["start"], (seed, g, prev, n))
+ by_string[n["string"]] = n
+
+ def test_regression_locked_intro_keeps_its_register_when_another_section_is_rerolled(self):
+ rec = studio_engine.set_lock(studio_engine.new_recipe(802000), "intro", "intro", True)
+ rec = studio_engine.set_option(rec, "key", {"tonic": "B", "mode": "phrygian"})
+ before = composer.compose(rec)
+ after = composer.compose(studio_engine.reroll(rec, "b", "B"))
+ end = section_spans(before)[0][2]
+ for g in ("g1", "g2"):
+ self.assertEqual(section_notes(before, g, 0, end), section_notes(after, g, 0, end), g)
+
+ def test_regression_dead_strokes_survive_and_legacy_recipes_get_the_minor_ninth_rule(self):
+ _, krec = keyed(801000, "D", "aeolian", mute_share=1.0)
+ p = composer.compose(krec)
+ self.assertTrue(any("dead" in n["tech"] for g in p["parts"] for n in notes_at(p, g, 285)))
+ args = argparse.Namespace(meter=None, mode=None, key=None, tempo=None)
+ legacy = studio_engine._ensure_studio(composer.make_recipe(801000, args))
+ self.assertFalse(legacy.get("fix") or legacy.get("v6"))
+ for tonic, mode in (("F#", "locrian"), ("D", "aeolian")):
+ p = composer.compose(studio_engine.set_option(legacy, "key", {"tonic": tonic, "mode": mode}))
+ self.assert_no_minor_ninth(p, (tonic, mode))
+
+ def test_locking_the_ending_with_a_key_set_does_not_change_the_music(self):
+ rec = studio_engine.set_option(studio_engine.new_recipe(801000), "key", {"tonic": "D", "mode": "aeolian"})
+ locked = studio_engine.set_lock(rec, "ending", "end", True)
+ self.assertEqual(midi_sha256(composer.compose(locked)), midi_sha256(composer.compose(rec)))
+
+ def test_key_option_validation_labels_and_history(self):
+ rec = studio_engine.new_recipe(801000)
+ for bad in ("D", ["D", "aeolian"], {"tonic": "D"}, {"mode": "aeolian"}, {"tonic": "H", "mode": "aeolian"},
+ {"tonic": "D", "mode": "blues"}, {"tonic": "D", "mode": "aeolian", "x": 1}, True, 0,
+ {"tonic": 4, "mode": "aeolian"}):
+ with self.assertRaises(ValueError, msg=bad):
+ studio_engine.set_option(rec, "key", bad)
+ r1 = studio_engine.set_option(rec, "key", {"tonic": "D", "mode": "aeolian"})
+ self.assertEqual(r1["studio"]["options"]["key"], {"tonic": "D", "mode": "aeolian"})
+ self.assertEqual(studio_engine.change_label(rec, r1), "тональность: D натуральный минор")
+ self.assertEqual(studio_engine.change_label(r1, rec), "тональность: как в пьесе")
+ r2 = studio_engine.set_option(r1, "key", {"tonic": "F#", "mode": "locrian"})
+ self.assertEqual(studio_engine.change_label(r1, r2), "тональность: F# локрийский")
+ self.assertEqual(studio_engine.set_option(r2, "key", {"tonic": "F#", "mode": "locrian"}), r2)
+
+ def test_store_undo_redo_log_and_detail_show_the_key(self):
+ with tempfile.TemporaryDirectory() as d:
+ render = RecordingRender()
+ store = studio_engine.StudioStore(d, render_fn=render)
+ det0 = store.create_piece(801000)
+ pid = det0["id"]
+ pdir = store._piece_dir(pid)
+ self.assertIsNone(det0["options"]["key"])
+ calls0 = render.calls
+ own = {"tonic": det0["key"], "mode": det0["mode"]}
+ det = store.set_option(pid, "key", own)
+ self.assertFalse(det["can_undo"])
+ self.assertEqual(render.calls, calls0)
+ det1 = store.set_option(pid, "key", {"tonic": "D", "mode": "aeolian"})
+ self.assertEqual((det1["key"], det1["mode"]), ("D", "aeolian"))
+ self.assertEqual(det1["options"]["key"], {"tonic": "D", "mode": "aeolian"})
+ self.assertEqual(det1["undo_label"], "тональность: D натуральный минор")
+ self.assertEqual(store.list_pieces()[0]["key"], "D")
+ self.assertEqual(len(store._read_undo(pdir)), 1)
+ rows = [json.loads(x) for x in (pdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if x]
+ self.assertEqual(rows[-1]["value"], {"key": {"tonic": "D", "mode": "aeolian"}})
+ piece = composer.compose(json.loads((pdir / "recipe.json").read_text(encoding="utf-8")))
+ self.assertEqual(piece["theory"].tonic_pc, composer.TONICS["D"])
+ det2 = store.undo(pid)
+ self.assertIsNone(det2["options"]["key"])
+ self.assertEqual((det2["key"], det2["mode"]), (det0["key"], det0["mode"]))
+ self.assertEqual(det2["redo_label"], "тональность: D натуральный минор")
+ det3 = store.redo(pid)
+ self.assertEqual(det3["options"]["key"], {"tonic": "D", "mode": "aeolian"})
+ self.assertEqual(det3["undo_label"], "тональность: D натуральный минор")
+
+ def test_key_applies_with_other_whole_piece_options(self):
+ for seed in KEY_SEEDS[:8]:
+ rng = random.Random(seed)
+ tonic, mode = rng.choice(KEY_TARGETS)
+ _, krec = keyed(seed, tonic, mode, mute_share=rng.choice([0.3, 1.0]),
+ octave_share=rng.choice([None, 1.0]), intro_bars=rng.choice([1, 4]),
+ square_repeat=rng.choice([1, 2]))
+ p = composer.compose(krec)
+ self.assert_playable(p, (seed, tonic, mode))
+ self.assert_no_minor_ninth(p, (seed, tonic, mode))
+
+ def test_server_accepts_and_rejects_key_values_and_page_has_the_controls(self):
+ with tempfile.TemporaryDirectory() as d:
+ srv = studio_server.create_server(d, host="127.0.0.1", port=0, render_fn=studio_render.fake_render)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ base = f"http://127.0.0.1:{srv.server_address[1]}"
+ try:
+ with urllib.request.urlopen(base + "/", timeout=10) as resp:
+ html = resp.read().decode("utf-8")
+ for text in ("Тональность", "Как в пьесе",
+ "Переводит все ноты в выбранную тональность по ступеням; ритм и форма не меняются. Применяется сразу.",
+ "натуральный минор"):
+ self.assertIn(text, html)
+
+ def post(path, body):
+ req = urllib.request.Request(base + path, data=json.dumps(body).encode("utf-8"), method="POST",
+ headers={"Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=10) as r:
+ return r.status, json.loads(r.read())
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read())
+
+ st, det = post("/api/new", {"seed": 801000})
+ pid = det["id"]
+ st, out = post(f"/api/piece/{pid}/option", {"name": "key", "value": {"tonic": "G", "mode": "dorian"}})
+ self.assertEqual(st, 200, out)
+ self.assertEqual((out["key"], out["mode"]), ("G", "dorian"))
+ st, out = post(f"/api/piece/{pid}/option", {"name": "key", "value": None})
+ self.assertEqual(st, 200, out)
+ self.assertIsNone(out["options"]["key"])
+ for bad in ("G", {"tonic": "G"}, {"tonic": "G", "mode": "blues"}, {"tonic": "H", "mode": "dorian"}):
+ st, out = post(f"/api/piece/{pid}/option", {"name": "key", "value": bad})
+ self.assertEqual(st, 400, (bad, out))
+ finally:
+ srv.shutdown()
+ srv.server_close()
+
+
+class TestStudioKeyPage(unittest.TestCase):
+ def test_key_controls_send_options_and_reflect_the_current_key(self):
+ out = _run_page("""
+show({ key: "A", mode: "aeolian", options: { key: null, octave_share: null, mute_share: 0 } });
+const btns = (o) => findAll((e) => e.dataset && e.dataset.option === o && e.tagName === "button");
+const snap = () => ({
+ tonics: btns("key_tonic").map((b) => [b.dataset.value, b.getAttribute("aria-pressed")]),
+ modes: btns("key_mode").map((b) => [b.dataset.value, b.textContent, b.getAttribute("aria-pressed")]),
+ reset: btns("key").map((b) => [b.textContent, b.getAttribute("aria-pressed")]),
+});
+const first = snap();
+respond = async (url, body) => {
+ if (!url.endsWith("/option")) return { pieces: [] };
+ const v = body.value;
+ return piece({ key: v ? v.tonic : "A", mode: v ? v.mode : "aeolian", options: { key: v, octave_share: null, mute_share: 0 } });
+};
+const click = async (o, v) => { find((e) => e.dataset && e.dataset.option === o && e.dataset.value === v && e.tagName === "button").onclick(); await sleep(20); };
+await click("key_tonic", "D");
+await click("key_mode", "dorian");
+const second = snap();
+await click("key", "auto");
+console.log(JSON.stringify({ first, second, sent: calls.filter((c) => c.url.endsWith("/option")).map((c) => c.body) }));
+""")
+ self.assertEqual([t[0] for t in out["first"]["tonics"]], ["E", "F#", "G", "A", "B", "C#", "D"])
+ self.assertEqual([t[1] for t in out["first"]["tonics"]], ["false", "false", "false", "true", "false", "false", "false"])
+ self.assertEqual(
+ [m[1] for m in out["first"]["modes"]],
+ ["мажор", "дорийский", "фригийский", "лидийский", "миксолидийский", "натуральный минор", "локрийский"],
+ )
+ self.assertEqual([m[2] for m in out["first"]["modes"]].count("true"), 1)
+ self.assertEqual(out["first"]["reset"], [["Как в пьесе", "true"]])
+ self.assertEqual(out["second"]["reset"], [["Как в пьесе", "false"]])
+ self.assertEqual(
+ out["sent"],
+ [{"name": "key", "value": {"tonic": "D", "mode": "aeolian"}},
+ {"name": "key", "value": {"tonic": "D", "mode": "dorian"}},
+ {"name": "key", "value": None}],
+ )
+
+
+ def test_two_quick_key_clicks_end_in_the_combined_key(self):
+ out = _run_page("""
+show({ key: "E", mode: "lydian", options: { key: null, octave_share: null, mute_share: 0 } });
+let held = [];
+respond = (url, body) => {
+ if (!url.endsWith("/option")) return { pieces: [] };
+ const v = body.value;
+ return new Promise((resolve) => held.push(() => resolve(piece({ key: v.tonic, mode: v.mode, options: { key: v, octave_share: null, mute_share: 0 } }))));
+};
+const click = (o, v) => find((e) => e.dataset && e.dataset.option === o && e.dataset.value === v && e.tagName === "button").onclick();
+click("key_tonic", "D");
+await sleep(20);
+click("key_mode", "aeolian");
+await sleep(20);
+while (held.length) { held.shift()(); await sleep(20); }
+console.log(JSON.stringify({ sent: calls.filter((c) => c.url.endsWith("/option")).map((c) => c.body.value) }));
+""")
+ self.assertEqual(out["sent"], [{"tonic": "D", "mode": "lydian"}, {"tonic": "D", "mode": "aeolian"}])
+
+
+ def test_reset_while_a_key_request_is_pending_does_not_reuse_the_old_key(self):
+ out = _run_page("""
+show({ key: "E", mode: "lydian", own_key: { tonic: "E", mode: "lydian" }, options: { key: null, octave_share: null, mute_share: 0 } });
+let held = [];
+respond = (url, body) => {
+ if (!url.endsWith("/option")) return { pieces: [] };
+ const v = body.value || { tonic: "E", mode: "lydian" };
+ return new Promise((resolve) => held.push(() => resolve(piece({ key: v.tonic, mode: v.mode, own_key: { tonic: "E", mode: "lydian" }, options: { key: body.value, octave_share: null, mute_share: 0 } }))));
+};
+const click = (o, v) => find((e) => e.dataset && e.dataset.option === o && e.dataset.value === v && e.tagName === "button").onclick();
+click("key_tonic", "D");
+await sleep(20);
+click("key", "auto");
+await sleep(20);
+click("key_mode", "dorian");
+await sleep(20);
+while (held.length) { held.shift()(); await sleep(20); }
+console.log(JSON.stringify({ sent: calls.filter((c) => c.url.endsWith("/option")).map((c) => c.body.value) }));
+""")
+ self.assertEqual(out["sent"], [{"tonic": "D", "mode": "lydian"}, None, {"tonic": "E", "mode": "dorian"}])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/composer-lab/test_web_api.py b/composer-lab/test_web_api.py
index b22224e..c009b05 100644
--- a/composer-lab/test_web_api.py
+++ b/composer-lab/test_web_api.py
@@ -303,6 +303,79 @@ def test_noop_option_does_not_push_undo(self):
self.assertEqual(legacy_after["undo"], [])
+class TestWebApiKey(unittest.TestCase):
+ D_MINOR = {"tonic": "D", "mode": "aeolian"}
+
+ def test_key_sequence_with_undo_and_redo_matches_studio_store(self):
+ with tempfile.TemporaryDirectory() as d:
+ store = studio_engine.StudioStore(d, render_fn=studio_render.fake_render)
+ pid = store.create_piece(801000)["id"]
+ pdir = Path(d) / pid
+ st = web_api.new_piece(801000)
+ steps = [
+ ("option", ("key", self.D_MINOR)),
+ ("option", ("key", {"tonic": "F#", "mode": "locrian"})),
+ ("option", ("intro_bars", 4)),
+ ("option", ("key", None)),
+ ("undo", ()),
+ ("undo", ()),
+ ("redo", ()),
+ ]
+ for kind, args in steps:
+ s_det = getattr(store, "set_option" if kind == "option" else kind)(pid, *args)
+ st = json.loads(json.dumps(getattr(web_api, kind)(st, *args)))
+ self.assertEqual(web_api.detail(st), s_det, (kind, args))
+ self.assertEqual(st["recipe"], json.loads((pdir / "recipe.json").read_text(encoding="utf-8")), (kind, args))
+ self.assertEqual(
+ base64.b64decode(web_api.export_midi(st)), (pdir / "piece.mid").read_bytes(), (kind, args)
+ )
+
+ def test_key_detail_labels_and_handle_json(self):
+ st = web_api.new_piece(801000)
+ own = {"tonic": web_api.detail(st)["key"], "mode": web_api.detail(st)["mode"]}
+ self.assertEqual(web_api.option(st, "key", own)["undo"], [])
+ st1 = web_api.option(st, "key", self.D_MINOR)
+ det = web_api.detail(st1)
+ self.assertEqual((det["key"], det["mode"]), ("D", "aeolian"))
+ self.assertEqual(det["undo_label"], "тональность: D натуральный минор")
+ out = json.loads(web_api.handle_json(json.dumps({"cmd": "option", "payload": {"state": st, "name": "key", "value": self.D_MINOR}})))
+ self.assertEqual(out["detail"]["options"]["key"], self.D_MINOR)
+ undone = web_api.undo(st1)
+ self.assertEqual(web_api.detail(undone)["redo_label"], "тональность: D натуральный минор")
+ self.assertIsNone(web_api.detail(undone)["options"]["key"])
+
+ def test_key_validation_on_option_and_on_imported_state(self):
+ st = web_api.new_piece(801000)
+ for bad in ("D", {"tonic": "D"}, {"tonic": "D", "mode": "blues"}, {"tonic": "H", "mode": "aeolian"},
+ {"tonic": "D", "mode": "aeolian", "x": 1}, True, 3, []):
+ with self.assertRaises(ValueError, msg=bad):
+ web_api.option(st, "key", bad)
+ bad_st = copy.deepcopy(st)
+ bad_st["recipe"]["studio"]["options"]["key"] = bad
+ with self.assertRaises(ValueError, msg=("validate", bad)):
+ web_api.detail(bad_st)
+ ok_st = copy.deepcopy(st)
+ ok_st["recipe"]["studio"]["options"]["key"] = self.D_MINOR
+ self.assertEqual(web_api.detail(ok_st)["key"], "D")
+ legacy = copy.deepcopy(st)
+ del legacy["recipe"]["studio"]["options"]["key"]
+ self.assertIsNone(web_api.detail(legacy)["options"]["key"])
+
+
+ def test_import_turns_an_explicit_own_key_into_unset(self):
+ st = web_api.new_piece(801000)
+ det = web_api.detail(st)
+ explicit = copy.deepcopy(st)
+ explicit["recipe"]["studio"]["options"]["key"] = {"tonic": det["key"], "mode": det["mode"]}
+ explicit["undo"] = [copy.deepcopy(explicit["recipe"])]
+ snap = web_api.import_state(explicit)
+ self.assertIsNone(snap["state"]["recipe"]["studio"]["options"]["key"])
+ self.assertIsNone(snap["detail"]["options"]["key"])
+ self.assertIsNone(snap["state"]["undo"][0]["studio"]["options"]["key"])
+ same = web_api.option(snap["state"], "key", None)
+ self.assertEqual(len(same["undo"]), 1)
+
+
class TestReviewFixesPython(unittest.TestCase):
def _load_check_site(self):
path = Path(__file__).resolve().parent / "web" / "check_site.py"
diff --git a/composer-lab/web/app.js b/composer-lab/web/app.js
index 8b1d05d..aaeb041 100644
--- a/composer-lab/web/app.js
+++ b/composer-lab/web/app.js
@@ -18,6 +18,16 @@
locrian: "локрийский",
};
const modeLabel = (mode) => MODE_LABELS[mode] || mode;
+ const KEY_TONICS = ["E", "F#", "G", "A", "B", "C#", "D"];
+ const KEY_MODES = [
+ ["ionian", "мажор"],
+ ["dorian", "дорийский"],
+ ["phrygian", "фригийский"],
+ ["lydian", "лидийский"],
+ ["mixolydian", "миксолидийский"],
+ ["aeolian", "натуральный минор"],
+ ["locrian", "локрийский"],
+ ];
const appState = {
pendingSliders: [],
@@ -1731,16 +1741,11 @@
grid.appendChild(wrap);
}
- function addChoiceGroup(grid, title, name, choices, current, hint) {
- const box = document.createElement("div");
- const titleEl = document.createElement("div");
- titleEl.className = "piece-meta";
- titleEl.style.marginBottom = "6px";
- titleEl.textContent = title;
+ function makeChoiceRow(label, name, choices, current, pick, force) {
const row = document.createElement("div");
row.className = "row";
row.setAttribute("role", "group");
- row.setAttribute("aria-label", title);
+ row.setAttribute("aria-label", label);
for (const [val, txt] of choices) {
const selected = current === val;
const b = document.createElement("button");
@@ -1750,16 +1755,72 @@
b.textContent = txt;
b.setAttribute("aria-pressed", selected ? "true" : "false");
b.onclick = () => {
- if (!selected) sendOption(name, val, b);
+ if (!selected || (force && force())) pick(val, b);
};
row.appendChild(b);
}
+ return row;
+ }
+
+ function addChoiceGroup(grid, title, name, choices, current, hint) {
+ const box = document.createElement("div");
+ const titleEl = document.createElement("div");
+ titleEl.className = "piece-meta";
+ titleEl.style.marginBottom = "6px";
+ titleEl.textContent = title;
box.appendChild(titleEl);
- box.appendChild(row);
+ box.appendChild(makeChoiceRow(title, name, choices, current, (val, b) => sendOption(name, val, b)));
if (hint) addOptionHint(box, hint);
grid.appendChild(box);
}
+ function pendingKey() {
+ return appState.keyPending && appState.keyPending.id === d.id ? appState.keyPending.value : null;
+ }
+
+ function trackKey(value, request) {
+ appState.keyPending = { id: d.id, value };
+ appState.keyBusy = (appState.keyBusy || 0) + 1;
+ return Promise.resolve(request()).finally(() => {
+ if (--appState.keyBusy === 0) appState.keyPending = null;
+ });
+ }
+
+ function sendKey(patch, ctl) {
+ const pending = pendingKey();
+ const next = Object.assign({}, pending || { tonic: d.key, mode: d.mode }, patch);
+ return trackKey(next, () => sendOption("key", next, ctl));
+ }
+
+ function resetKey(ctl) {
+ return trackKey(d.own_key || { tonic: d.key, mode: d.mode }, () => sendOption("key", null, ctl));
+ }
+
+ function addKeyControl(grid) {
+ const title = "Тональность";
+ const box = document.createElement("div");
+ const titleEl = document.createElement("div");
+ titleEl.className = "piece-meta";
+ titleEl.style.marginBottom = "6px";
+ titleEl.textContent = title;
+ box.appendChild(titleEl);
+ box.appendChild(
+ makeChoiceRow(`${title}: основной тон`, "key_tonic", KEY_TONICS.map((t) => [t, t]), d.key, (t, b) =>
+ sendKey({ tonic: t }, b)
+ )
+ );
+ box.appendChild(
+ makeChoiceRow(`${title}: лад`, "key_mode", KEY_MODES, d.mode, (m, b) => sendKey({ mode: m }, b))
+ );
+ box.appendChild(
+ makeChoiceRow(`${title}: как в пьесе`, "key", [["auto", "Как в пьесе"]], opts.key ? null : "auto", (v, b) =>
+ resetKey(b), pendingKey
+ )
+ );
+ addOptionHint(box, "Переводит все ноты в выбранную тональность по ступеням; ритм и форма не меняются. Применяется сразу.");
+ grid.appendChild(box);
+ }
+
addSliderControl(
oGrid,
"mute_share",
@@ -1852,6 +1913,7 @@
opts.square_repeat ?? 1,
"Повторяет 4-тактовый квадрат куплетов A и A2 дважды подряд; применяется сразу."
);
+ addKeyControl(oGrid);
addChoiceGroup(
oGrid,
"Соло в середине B",
diff --git a/composer-lab/web/tests/harness.js b/composer-lab/web/tests/harness.js
index 460d13b..625c0e0 100644
--- a/composer-lab/web/tests/harness.js
+++ b/composer-lab/web/tests/harness.js
@@ -44,6 +44,7 @@ function makeFakeState(seed = 801000, overrides = {}) {
octave_sixteenths: 0.3,
dead_notes: 0.2,
slide_max: 5,
+ key: null,
},
comp_doses: {},
},
@@ -72,9 +73,14 @@ function describeFakeChange(prevRec, curRec) {
"octave_sixteenths",
"dead_notes",
"slide_max",
+ "key",
]) {
- if (po[k] !== co[k]) {
+ if (JSON.stringify(po[k] ?? null) !== JSON.stringify(co[k] ?? null)) {
const v = co[k];
+ if (k === "key") {
+ const modes = { ionian: "мажор", dorian: "дорийский", phrygian: "фригийский", lydian: "лидийский", mixolydian: "миксолидийский", aeolian: "натуральный минор", locrian: "локрийский" };
+ return v ? `тональность: ${v.tonic} ${modes[v.mode]}` : "тональность: как в пьесе";
+ }
if (k === "mute_share") return `глухие ноты ${fmtNum(v)}`;
if (k === "octave_share") return v === null || v === undefined ? "октавные аккорды: авто" : `октавные аккорды ${fmtNum(v)}`;
if (k === "intro_bars") return v === "auto" ? "длина вступления: авто" : `длина вступления: ${v}`;
@@ -201,8 +207,9 @@ function buildDetailFromState(st, sectionLabels = {}) {
id: st.id,
seed: rec.seed,
meter: rec.intent.meter,
- mode: rec.intent.mode,
- key: rec.intent.tonic,
+ mode: opts.key ? opts.key.mode : rec.intent.mode,
+ key: opts.key ? opts.key.tonic : rec.intent.tonic,
+ own_key: { tonic: rec.intent.tonic, mode: rec.intent.mode },
tempo: rec.intent.tempo,
length: Math.max(2, cursor),
sections,
@@ -233,6 +240,7 @@ function buildDetailFromState(st, sectionLabels = {}) {
octave_sixteenths: opts.octave_sixteenths ?? 0.3,
dead_notes: opts.dead_notes ?? 0.2,
slide_max: opts.slide_max ?? 5,
+ key: opts.key ?? null,
},
can_undo: undo.length > 0,
can_redo: redo.length > 0,
diff --git a/composer-lab/web/tests/test_app.mjs b/composer-lab/web/tests/test_app.mjs
index cf5d4cc..65e6549 100644
--- a/composer-lab/web/tests/test_app.mjs
+++ b/composer-lab/web/tests/test_app.mjs
@@ -398,7 +398,7 @@ test("Studio controls send option immediately without reroll, refresh UI, and hi
}
const hints = ws.querySelectorAll(".option-hint");
- assert.equal(hints.length, 4, "each of the 4 new controls must have a one-line Russian hint");
+ assert.equal(hints.length, 5, "each of the 5 whole-piece controls must have a one-line Russian hint");
for (const h of hints) {
assert.match(h.textContent, /применяется сразу/i);
}
@@ -1102,3 +1102,118 @@ test("Review N4: every pending slider is flushed in the order it was moved", asy
const sent = env.workerMessages.filter((m) => m.type === "call").map((m) => (m.cmd === "option" ? m.payload.name : m.cmd));
assert.deepEqual(sent, ["mute_share", "octave_piece", "undo"]);
});
+
+const keyButtons = (env, option) => env.document.getElementById("workspace").querySelectorAll("button").filter((b) => b.dataset.option === option);
+const keyButton = (env, option, value) => keyButtons(env, option).find((b) => b.dataset.value === value);
+const keyCalls = (env) => env.workerMessages.filter((m) => m.type === "call" && m.cmd === "option" && m.payload.name === "key").map((m) => m.payload.value);
+
+test("Key: Тональность offers tonics and Russian modes, marks the current key and has a reset", async () => {
+ const env = await bootWithPiece();
+ const ws = env.document.getElementById("workspace");
+ assert.match(ws.textContent, /Тональность/);
+ assert.match(ws.textContent, /Переводит все ноты в выбранную тональность по ступеням; ритм и форма не меняются\. Применяется сразу\./);
+ assert.deepEqual(keyButtons(env, "key_tonic").map((b) => b.dataset.value), ["E", "F#", "G", "A", "B", "C#", "D"]);
+ assert.deepEqual(
+ keyButtons(env, "key_mode").map((b) => b.textContent),
+ ["мажор", "дорийский", "фригийский", "лидийский", "миксолидийский", "натуральный минор", "локрийский"],
+ );
+ for (const opt of ["key_tonic", "key_mode", "key"]) {
+ const group = keyButtons(env, opt);
+ assert.equal(group.filter((b) => b.getAttribute("aria-pressed") === "true").length, 1, opt);
+ for (const b of group) assert.ok(["true", "false"].includes(b.getAttribute("aria-pressed")), opt);
+ }
+ assert.equal(keyButton(env, "key_tonic", "E").getAttribute("aria-pressed"), "true");
+ assert.equal(keyButton(env, "key_mode", "lydian").getAttribute("aria-pressed"), "true");
+ assert.equal(keyButton(env, "key", "auto").textContent, "Как в пьесе");
+ assert.equal(keyButton(env, "key", "auto").getAttribute("aria-pressed"), "true");
+});
+
+test("Key: choices send the whole key, the header shows it, undo and redo name it, reset sends null", async () => {
+ const env = await bootWithPiece();
+ keyButton(env, "key_tonic", "D").click();
+ await env.flushAll(15);
+ keyButton(env, "key_mode", "aeolian").click();
+ await env.flushAll(15);
+ assert.deepEqual(keyCalls(env), [{ tonic: "D", mode: "lydian" }, { tonic: "D", mode: "aeolian" }]);
+ assert.match(env.document.getElementById("workspace").textContent, /D минор \(эолийский\)/);
+ assert.equal(keyButton(env, "key", "auto").getAttribute("aria-pressed"), "false");
+ assert.equal(keyButton(env, "key_tonic", "D").getAttribute("aria-pressed"), "true");
+ assert.match(env.document.getElementById("undoBtn").title, /Отменить: тональность: D натуральный минор/);
+ env.document.getElementById("undoBtn").click();
+ await env.flushAll(15);
+ assert.match(env.document.getElementById("redoBtn").title, /Вернуть: тональность: D натуральный минор/);
+ env.document.getElementById("redoBtn").click();
+ await env.flushAll(15);
+ keyButton(env, "key", "auto").click();
+ await env.flushAll(15);
+ assert.deepEqual(keyCalls(env).pop(), null);
+ assert.match(env.document.getElementById("workspace").textContent, /E лидийский/);
+ const saved = env.indexedDB._pieces.get("piece_801000").state;
+ assert.equal(saved.recipe.studio.options.key, null);
+ assert.ok(env.indexedDB._logs.some((l) => l.action === "option" && l.value && "key" in l.value));
+});
+
+test("Key: the pressed choice does nothing, controls are disabled while busy and an error reaches the banner", async () => {
+ const env = await bootWithPiece();
+ keyButton(env, "key_tonic", "E").click();
+ keyButton(env, "key", "auto").click();
+ await env.flushAll(10);
+ assert.deepEqual(keyCalls(env), []);
+ env.autoRunWorkerCalls = false;
+ const btn = keyButton(env, "key_tonic", "G");
+ btn.click();
+ await env.flushAll(10);
+ assert.equal(btn.disabled, true);
+ assert.equal(env.document.getElementById("statusChip").textContent, "Пересчёт…");
+ env.pendingWorkerCalls.shift().reject("key boom");
+ await env.flushAll(15);
+ assert.equal(env.document.getElementById("statusChip").textContent, "");
+ assert.equal(env.document.getElementById("errorBanner").hidden, false);
+ assert.match(env.document.getElementById("errorText").textContent, /key boom/);
+ assert.equal(keyButton(env, "key_tonic", "G").disabled, false);
+});
+
+test("Key: a pending slider is flushed before the key change", async () => {
+ const env = await bootWithPiece();
+ env.workerMessages.length = 0;
+ const mute = findSlider(env, "mute_share");
+ mute.value = "0.35";
+ mute.oninput();
+ keyButton(env, "key_mode", "dorian").click();
+ await env.flushAll(20);
+ await new Promise((r) => setTimeout(r, 700));
+ await env.flushAll(15);
+ const sent = env.workerMessages.filter((m) => m.type === "call").map((m) => (m.cmd === "option" ? m.payload.name : m.cmd));
+ assert.deepEqual(sent, ["mute_share", "key"]);
+});
+
+test("Key: two quick clicks, tonic then mode, end in the combined key", async () => {
+ const env = await bootWithPiece();
+ env.autoRunWorkerCalls = false;
+ env.workerMessages.length = 0;
+ keyButton(env, "key_tonic", "D").click();
+ await env.flushAll(10);
+ keyButton(env, "key_mode", "aeolian").click();
+ await env.flushAll(10);
+ await resolveAll(env);
+ await env.flushAll(15);
+ assert.deepEqual(keyCalls(env), [{ tonic: "D", mode: "lydian" }, { tonic: "D", mode: "aeolian" }]);
+ const saved = env.indexedDB._pieces.get("piece_801000").state;
+ assert.deepEqual(saved.recipe.studio.options.key, { tonic: "D", mode: "aeolian" });
+ assert.match(env.document.getElementById("workspace").textContent, /D минор \(эолийский\)/);
+});
+
+test("Key: Как в пьесе while a key request is pending does not reuse the old key", async () => {
+ const env = await bootWithPiece();
+ env.autoRunWorkerCalls = false;
+ env.workerMessages.length = 0;
+ keyButton(env, "key_tonic", "D").click();
+ await env.flushAll(10);
+ keyButton(env, "key", "auto").click();
+ await env.flushAll(10);
+ keyButton(env, "key_mode", "dorian").click();
+ await env.flushAll(10);
+ await resolveAll(env);
+ await env.flushAll(15);
+ assert.deepEqual(keyCalls(env), [{ tonic: "D", mode: "lydian" }, null, { tonic: "E", mode: "dorian" }]);
+});