GitCorner

Code

ossartcraftsoundcraft🌐
a02d892f831f
//! Event-menu operation windows: Beat Analysis, Tempo Operations, Time Operations, MIDI
//! Operations and MIDI Real-Time Properties. Each is a small form over engine commands.

use crate::SoundApp;
use crate::theme::Tokens;
use egui::vec2;
use serde_json::{Value, json};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct OpsState {
    pub beat_sensitivity: f32,
    pub beat_separate: bool,
    pub beat_set_tempo: bool,
    pub beat_result: String,
    pub tempo_curve: String,
    pub tempo_start: f64,
    pub tempo_end: f64,
    pub time_op: String,
    pub time_seconds: f64,
    pub meter_num: u32,
    pub meter_den: u32,
    pub midi_op: String,
    pub quant_grid: String,
    pub quant_strength: f64,
    pub quant_swing: f64,
    pub transpose: i64,
    pub velocity_add: i64,
    pub rtp_velocity: i64,
    pub rtp_transpose: i64,
    pub rtp_duration: f64,
    pub rtp_delay: i64,
    /// The MIDI tracks the Real-Time Properties form was last filled from, and the values it read:
    /// the form re-reads the tracks when either changes (#444).
    pub rtp_targets: Vec<soundcraft_model::TrackId>,
    pub rtp_loaded: Option<RtpValues>,
    pub identify_bars: u32,
}

impl Default for OpsState {
    fn default() -> Self {
        OpsState {
            beat_sensitivity: 0.5,
            beat_separate: true,
            beat_set_tempo: false,
            beat_result: String::new(),
            tempo_curve: "linear".into(),
            tempo_start: 100.0,
            tempo_end: 120.0,
            time_op: "insert".into(),
            time_seconds: 4.0,
            meter_num: 4,
            meter_den: 4,
            midi_op: "quantize".into(),
            quant_grid: "1/16".into(),
            quant_strength: 100.0,
            quant_swing: 0.0,
            transpose: 12,
            velocity_add: 10,
            rtp_velocity: 0,
            rtp_transpose: 0,
            rtp_duration: 100.0,
            rtp_delay: 0,
            rtp_targets: Vec::new(),
            rtp_loaded: None,
            identify_bars: 1,
        }
    }
}

fn result_line(ui: &mut egui::Ui, r: &Result<Value, String>) {
    match r {
        Ok(v) => {
            let s = v.to_string();
            ui.label(egui::RichText::new(if s.len() > 160 { format!("{}…", &s[..160]) } else { s }).small().color(Tokens::current().counter_text));
        }
        Err(e) => {
            ui.label(egui::RichText::new(e).small().color(Tokens::current().rec));
        }
    }
}

pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
    beat_detective(app, ctx);
    tempo_ops(app, ctx);
    time_ops(app, ctx);
    midi_ops(app, ctx);
    rtp(app, ctx);
}

/// Beat Analysis window: sensitivity, separate and set-tempo options, Analyze and Apply results, and Identify Beat.
fn beat_detective(app: &mut SoundApp, ctx: &egui::Context) {
    let mut open = app.ui.show_beat_detective;
    if !open {
        return;
    }
    egui::Window::new(crate::localization::text("Beat Analysis"))
        .id(egui::Id::unique("Beat Analysis"))
        .open(&mut open)
        .default_size(vec2(360.0, 220.0))
        .show(ctx, |ui| {
            ui.label(crate::localization::text("Analyses the edit selection on the selected tracks."));
            ui.add(egui::Slider::new(&mut app.ops.beat_sensitivity, 0.0..=1.0).text(crate::localization::text("Sensitivity")));
            crate::widgets::checkbox(ui, &mut app.ops.beat_separate, crate::localization::text("Separate clips at detected beats"));
            crate::widgets::checkbox(ui, &mut app.ops.beat_set_tempo, crate::localization::text("Set the session tempo from the beats"));
            ui.horizontal(|ui| {
                if ui.button(crate::localization::text("Analyze")).clicked() {
                    let r = app.run("event.beat_detective", json!({"sensitivity": app.ops.beat_sensitivity, "separate": false, "set_tempo": false}));
                    app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
                }
                if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
                    let r = app.run(
                        "event.beat_detective",
                        json!({"sensitivity": app.ops.beat_sensitivity, "separate": app.ops.beat_separate, "set_tempo": app.ops.beat_set_tempo}),
                    );
                    app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
                }
            });
            ui.separator();
            ui.horizontal(|ui| {
                ui.label(crate::localization::text("Identify Beat: selection is"));
                ui.add(egui::DragValue::new(&mut app.ops.identify_bars).range(1..=64))
                    .accessible_name(crate::localization::text("Identify beat bars"));
                ui.label(crate::localization::text("bar(s)"));
                if ui.button(crate::localization::text("Set Tempo")).clicked() {
                    let r = app.run("event.identify_beat", json!({"bars": app.ops.identify_bars}));
                    app.ops.beat_result = r.map_or_else(|e| e, |v| v.to_string());
                }
            });
            if !app.ops.beat_result.is_empty() {
                let s = app.ops.beat_result.clone();
                ui.label(egui::RichText::new(if s.len() > 300 { format!("{}…", &s[..300]) } else { s }).small());
            }
        });
    app.ui.show_beat_detective = open;
}

/// Command the Tempo Operations Apply button sends. Stretch uses `factor = start / end`
/// so a lower end BPM lengthens the selection (`event.tempo_stretch` has no `end_bpm`).
pub(crate) fn tempo_ops_apply(curve: &str, start_bpm: f64, end_bpm: f64) -> (&'static str, Value) {
    let start = if start_bpm.is_finite() { start_bpm.max(1.0) } else { 1.0 };
    let end = if end_bpm.is_finite() { end_bpm.max(1.0) } else { 1.0 };
    match curve {
        "constant" => ("event.tempo_constant", json!({"bpm": start_bpm})),
        "parabolic" => ("event.tempo_parabolic", json!({"start_bpm": start_bpm, "end_bpm": end_bpm})),
        "s-curve" => ("event.tempo_s_curve", json!({"start_bpm": start_bpm, "end_bpm": end_bpm})),
        "scale" => ("event.tempo_scale", json!({"factor": end / start})),
        "stretch" => ("event.tempo_stretch", json!({"factor": start / end})),
        _ => ("event.tempo_linear", json!({"start_bpm": start_bpm, "end_bpm": end_bpm})),
    }
}

/// Tempo Operations window: choose a curve and start/end tempo, then dispatch its command using the edit selection.
/// Constant sends only the start BPM; without a nonempty range, its command defaults to sample zero.
fn tempo_ops(app: &mut SoundApp, ctx: &egui::Context) {
    let mut open = app.ui.show_tempo_ops;
    if !open {
        return;
    }
    egui::Window::new(crate::localization::text("Tempo Operations"))
        .id(egui::Id::unique("Tempo Operations"))
        .open(&mut open)
        .default_size(vec2(360.0, 200.0))
        .show(ctx, |ui| {
            craft_ui::ComboBox::from_label(crate::localization::text("Curve"))
                .selected_text(crate::localization::text(&app.ops.tempo_curve))
                .show_ui(ui, |ui| {
                    for c in ["constant", "linear", "parabolic", "s-curve", "scale", "stretch"] {
                        ui.selectable_value(&mut app.ops.tempo_curve, c.to_string(), crate::localization::text(c));
                    }
                });
            ui.add(egui::DragValue::new(&mut app.ops.tempo_start).range(5.0..=999.0).prefix(crate::localization::text("start bpm ")))
                .accessible_name(crate::localization::text("Start tempo (BPM)"));
            ui.add(egui::DragValue::new(&mut app.ops.tempo_end).range(5.0..=999.0).prefix(crate::localization::text("end bpm ")))
                .accessible_name(crate::localization::text("End tempo (BPM)"));
            ui.label(
            egui::RichText::new(crate::localization::text(
                "Applies across the edit selection (constant: at the insertion point; scale: factor = end / start; stretch: factor = start / end).",
            ))
            .small(),
        );
            if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
                let (id, p) = tempo_ops_apply(&app.ops.tempo_curve, app.ops.tempo_start, app.ops.tempo_end);
                let r = app.run(id, p);
                result_line(ui, &r);
            }
        });
    app.ui.show_tempo_ops = open;
}

/// Time Operations window: insert a duration in seconds at the selection start, cut the edit selection, change the
/// meter, or move the song start to the selection start.
fn time_ops(app: &mut SoundApp, ctx: &egui::Context) {
    let mut open = app.ui.show_time_ops;
    if !open {
        return;
    }
    egui::Window::new(crate::localization::text("Time Operations"))
        .id(egui::Id::unique("Time Operations"))
        .open(&mut open)
        .default_size(vec2(360.0, 200.0))
        .show(ctx, |ui| {
            craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
                .selected_text(crate::localization::text(&app.ops.time_op))
                .show_ui(ui, |ui| {
                    for c in ["insert", "cut", "change meter", "move song start"] {
                        ui.selectable_value(&mut app.ops.time_op, c.to_string(), crate::localization::text(c));
                    }
                });
            match app.ops.time_op.as_str() {
                "change meter" => {
                    ui.horizontal(|ui| {
                        ui.add(egui::DragValue::new(&mut app.ops.meter_num).range(1..=64))
                            .accessible_name(crate::localization::text("Meter numerator"));
                        ui.label(crate::localization::text("/"));
                        let den = craft_ui::ComboBox::from_id_salt("den").selected_text(app.ops.meter_den.to_string()).show_ui(ui, |ui| {
                            for d in [2u32, 4, 8, 16] {
                                ui.selectable_value(&mut app.ops.meter_den, d, d.to_string());
                            }
                        });
                        den.response.accessible_name(crate::localization::text("Meter denominator"));
                    });
                }
                "insert" => {
                    ui.add(egui::DragValue::new(&mut app.ops.time_seconds).range(0.0..=3600.0).suffix(" s"))
                        .accessible_name(crate::localization::text("Time (seconds)"));
                }
                _ => {
                    ui.label(egui::RichText::new(crate::localization::text("Uses the edit selection.")).small());
                }
            }
            if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
                let at = app.engine.session().edit.selection.start;
                let r = match app.ops.time_op.as_str() {
                    "insert" => app.run("event.insert_time", json!({"start": at, "length": {"seconds": app.ops.time_seconds}})),
                    "cut" => app.run("event.cut_time", json!({})),
                    "change meter" => app.run("event.meter", json!({"numerator": app.ops.meter_num, "denominator": app.ops.meter_den, "at": at})),
                    _ => app.run("event.move_song_start", json!({"to": at})),
                };
                result_line(ui, &r);
            }
        });
    app.ui.show_time_ops = open;
}

fn midi_ops(app: &mut SoundApp, ctx: &egui::Context) {
    let mut open = app.ui.show_midi_ops;
    if !open {
        return;
    }
    egui::Window::new(crate::localization::text("MIDI Operations"))
        .id(egui::Id::unique("MIDI Operations"))
        .open(&mut open)
        .default_size(vec2(360.0, 220.0))
        .show(ctx, |ui| {
            craft_ui::ComboBox::from_label(crate::localization::text("Operation"))
                .selected_text(crate::localization::text(&app.ops.midi_op))
                .show_ui(ui, |ui| {
                    for c in ["quantize", "transpose", "change velocity", "flatten performance", "restore performance"] {
                        ui.selectable_value(&mut app.ops.midi_op, c.to_string(), crate::localization::text(c));
                    }
                });
            match app.ops.midi_op.as_str() {
                "quantize" => {
                    craft_ui::ComboBox::from_label(crate::localization::text("Grid")).selected_text(app.ops.quant_grid.clone()).show_ui(ui, |ui| {
                        for g in ["1/4", "1/8", "1/8t", "1/16", "1/16t", "1/32"] {
                            ui.selectable_value(&mut app.ops.quant_grid, g.to_string(), g);
                        }
                    });
                    ui.add(egui::Slider::new(&mut app.ops.quant_strength, 0.0..=100.0).text(crate::localization::text("Strength %")));
                    ui.add(egui::Slider::new(&mut app.ops.quant_swing, 0.0..=100.0).text(crate::localization::text("Swing %")));
                }
                "transpose" => {
                    ui.add(egui::Slider::new(&mut app.ops.transpose, -48..=48).text(crate::localization::text("Semitones")));
                }
                "change velocity" => {
                    ui.add(egui::Slider::new(&mut app.ops.velocity_add, -127..=127).text(crate::localization::text("Add")));
                }
                _ => {}
            }
            ui.label(egui::RichText::new(crate::localization::text("Applies to the selected MIDI clips (or those under the selection).")).small());
            if ui.button(egui::RichText::new(crate::localization::text("Apply")).strong()).clicked() {
                let r = match app.ops.midi_op.as_str() {
                    "quantize" => app
                        .run("event.quantize", json!({"grid": app.ops.quant_grid, "strength": app.ops.quant_strength, "swing": app.ops.quant_swing})),
                    "transpose" => app.run("event.transpose", json!({"semitones": app.ops.transpose})),
                    "change velocity" => app.run("event.change_velocity", json!({"add": app.ops.velocity_add})),
                    "flatten performance" => app.run("event.flatten_performance", json!({})),
                    _ => app.run("event.restore_performance", json!({})),
                };
                result_line(ui, &r);
            }
        });
    app.ui.show_midi_ops = open;
}

fn rtp(app: &mut SoundApp, ctx: &egui::Context) {
    let mut open = app.ui.show_rtp;
    if !open {
        return;
    }
    let targets = app.engine.target_tracks();
    sync_rtp_form(&mut app.ops, app.engine.session(), targets, ctx.dragged_id().is_some());
    egui::Window::new(crate::localization::text("MIDI Real-Time Properties"))
        .id(egui::Id::unique("MIDI Real-Time Properties"))
        .open(&mut open)
        .default_size(vec2(340.0, 200.0))
        .show(ctx, |ui| {
            ui.label(crate::localization::text("Non-destructive, applied at playback to the selected MIDI tracks."));
            let mut changed = RtpChanged::default();
            changed.velocity =
                ui.add(egui::Slider::new(&mut app.ops.rtp_velocity, -127..=127).text(crate::localization::text("Velocity +"))).changed();
            changed.transpose =
                ui.add(egui::Slider::new(&mut app.ops.rtp_transpose, -48..=48).text(crate::localization::text("Transpose"))).changed();
            changed.duration =
                ui.add(egui::Slider::new(&mut app.ops.rtp_duration, 1.0..=400.0).text(crate::localization::text("Duration %"))).changed();
            changed.delay = ui.add(egui::Slider::new(&mut app.ops.rtp_delay, -960..=960).text(crate::localization::text("Delay (ticks)"))).changed();
            if let Some(p) = rtp_params(changed, &app.ops) {
                let _ = app.engine.execute_merged("event.midi_rtp", &p, "rtp");
            }
            ui.horizontal(|ui| {
                if ui.button(crate::localization::text("Write to Notes")).clicked() {
                    let _ = app.run("track.write_midi_rtp", json!({}));
                }
                if ui.button(crate::localization::text("Clear")).clicked() {
                    let _ = app.run("event.midi_rtp", json!({"clear": true}));
                    app.ops.rtp_velocity = 0;
                    app.ops.rtp_transpose = 0;
                    app.ops.rtp_duration = 100.0;
                    app.ops.rtp_delay = 0;
                }
            });
        });
    app.ui.show_rtp = open;
}

/// Which of the form's controls the user changed this frame.
#[derive(Default, Clone, Copy)]
struct RtpChanged {
    velocity: bool,
    transpose: bool,
    duration: bool,
    delay: bool,
}

/// A form change submits only the properties the user touched: the command stores each key it is
/// sent, so sending untouched ones would overwrite the target's values with the form's (#444).
fn rtp_params(changed: RtpChanged, ops: &OpsState) -> Option<Value> {
    let mut p = serde_json::Map::new();
    if changed.velocity {
        p.insert("velocity".into(), json!(ops.rtp_velocity));
    }
    if changed.transpose {
        p.insert("transpose".into(), json!(ops.rtp_transpose));
    }
    if changed.duration {
        p.insert("duration".into(), json!(ops.rtp_duration));
    }
    if changed.delay {
        p.insert("delay".into(), json!(ops.rtp_delay));
    }
    (!p.is_empty()).then_some(Value::Object(p))
}

/// Velocity, transpose, duration % and delay, as the form shows them.
pub type RtpValues = (i64, i64, f64, i64);

/// Fills the form from the tracks it edits whenever the targets or their stored values change
/// (selection, undo, a command), so it never shows (and a control change never writes back) stale
/// values (#444). A slider being dragged keeps its value until it is released.
fn sync_rtp_form(ops: &mut OpsState, s: &soundcraft_model::Session, targets: Vec<soundcraft_model::TrackId>, dragging: bool) {
    let values = rtp_form_values(s, &targets);
    if ops.rtp_targets != targets || (ops.rtp_loaded != Some(values) && !dragging) {
        let (velocity, transpose, duration, delay) = values;
        ops.rtp_targets = targets;
        ops.rtp_loaded = Some(values);
        ops.rtp_velocity = velocity;
        ops.rtp_transpose = transpose;
        ops.rtp_duration = duration;
        ops.rtp_delay = delay;
    }
}

/// The values the form shows for `targets`: the first target's own Real-Time Properties, or the
/// neutral defaults when nothing is selected.
fn rtp_form_values(s: &soundcraft_model::Session, targets: &[soundcraft_model::TrackId]) -> RtpValues {
    let Some(&t) = targets.first() else { return (0, 0, 100.0, 0) };
    let value = |key: &str, d: f64| s.edit.value(&format!("rtp.{}.{key}", t.0), d);
    (
        value("velocity", 0.0).clamp(-127.0, 127.0) as i64,
        value("transpose", 0.0).clamp(-127.0, 127.0) as i64,
        value("duration", 100.0).clamp(1.0, 1000.0),
        value("delay", 0.0).clamp(-1e7, 1e7) as i64,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stretch_uses_start_over_end_and_scale_uses_end_over_start() {
        let (id, p) = tempo_ops_apply("stretch", 120.0, 60.0);
        assert_eq!(id, "event.tempo_stretch");
        assert!((p["factor"].as_f64().unwrap() - 2.0).abs() < 1e-9, "{p}");
        let (_, p) = tempo_ops_apply("stretch", 120.0, 120.0);
        assert!((p["factor"].as_f64().unwrap() - 1.0).abs() < 1e-9, "{p}");
        let (id, p) = tempo_ops_apply("scale", 120.0, 60.0);
        assert_eq!(id, "event.tempo_scale");
        assert!((p["factor"].as_f64().unwrap() - 0.5).abs() < 1e-9, "{p}");
        let (_, p) = tempo_ops_apply("stretch", f64::NAN, f64::INFINITY);
        assert!((p["factor"].as_f64().unwrap() - 1.0).abs() < 1e-9, "{p}");
        let (id, p) = tempo_ops_apply("linear", 100.0, 140.0);
        assert_eq!(id, "event.tempo_linear");
        assert_eq!(p["end_bpm"], 140.0);
    }

    /// One control moved: only its property is submitted, so the command cannot overwrite the
    /// target's other Real-Time Properties with the form's values (#444).
    #[test]
    fn rtp_submits_only_the_property_that_changed() {
        let ops = OpsState { rtp_velocity: 12, rtp_transpose: 7, rtp_duration: 50.0, rtp_delay: 480, ..OpsState::default() };
        let only_velocity = RtpChanged { velocity: true, ..RtpChanged::default() };
        assert_eq!(rtp_params(only_velocity, &ops), Some(json!({"velocity": 12})));
        let only_duration = RtpChanged { duration: true, ..RtpChanged::default() };
        assert_eq!(rtp_params(only_duration, &ops), Some(json!({"duration": 50.0})));
        assert_eq!(rtp_params(RtpChanged::default(), &ops), None, "no control moved, no command");
    }

    /// The form reads the target's own values when the window opens or the selection changes.
    #[test]
    fn the_rtp_form_shows_the_target_tracks_values() {
        let mut e = soundcraft_engine::Engine::default();
        e.execute("track.new", &json!({"kind": "instrument", "name": "Synth"})).unwrap();
        let t = e.session().tracks.last().unwrap().id;
        e.execute("event.midi_rtp", &json!({"track": t.0, "velocity": -12, "transpose": 7, "duration": 50.0, "delay": 480})).unwrap();
        assert_eq!(rtp_form_values(e.session(), &[]), (0, 0, 100.0, 0), "no target: the neutral defaults");
        assert_eq!(rtp_form_values(e.session(), &[t]), (-12, 7, 50.0, 480));
    }

    /// Undo keeps the same targets but changes their stored values: the form follows.
    #[test]
    fn the_rtp_form_follows_an_undo_on_the_same_targets() {
        let mut e = soundcraft_engine::Engine::default();
        e.execute("track.new", &json!({"kind": "instrument", "name": "Synth"})).unwrap();
        let t = e.session().tracks.last().unwrap().id;
        let mut ops = OpsState::default();
        sync_rtp_form(&mut ops, e.session(), vec![t], false);
        e.execute("event.midi_rtp", &json!({"track": t.0, "velocity": -12})).unwrap();
        sync_rtp_form(&mut ops, e.session(), vec![t], false);
        assert_eq!(ops.rtp_velocity, -12);
        e.execute("edit.undo", &json!({})).unwrap();
        sync_rtp_form(&mut ops, e.session(), vec![t], false);
        assert_eq!(ops.rtp_velocity, 0, "the form kept the undone value");
    }
}