Skip to main content

phosphor_app/state/
track_ops.rs

1//! NavState methods: track ops.
2
3use super::*;
4
5impl NavState {
6
7    pub fn toggle_mute(&mut self) {
8        if let Some(t) = self.current_track_mut() {
9            t.muted = !t.muted;
10            t.sync_to_audio();
11        }
12    }
13
14
15    pub fn toggle_solo(&mut self) {
16        if let Some(t) = self.current_track_mut() {
17            t.soloed = !t.soloed;
18            t.sync_to_audio();
19        }
20    }
21
22
23    pub fn toggle_arm(&mut self) {
24        if let Some(t) = self.current_track_mut() {
25            t.armed = !t.armed;
26            t.sync_to_audio();
27        }
28    }
29
30    /// Move the selected track's fader by `steps` presses, syncing to the
31    /// audio thread. Returns the new linear gain, or `None` if there is no
32    /// track under the cursor.
33    ///
34    /// Not undoable, and deliberately: the fader is a continuous control like
35    /// the synth parameters, and none of those push onto the undo stack
36    /// either. The stack is for structural edits — notes, clips, tracks —
37    /// where the change cannot be reversed by looking at the screen and
38    /// pressing the other key.
39    pub fn adjust_volume(&mut self, steps: i32) -> Option<f32> {
40        self.current_track_mut().map(|t| t.adjust_volume(steps))
41    }
42
43
44    pub fn digit_input(&mut self, ch: char) {
45        if self.focused_pane == Pane::Tracks && self.track_selected {
46            self.number_buf.push_digit(ch);
47        }
48    }
49
50
51    pub fn tick(&mut self) {
52        if let Some(clip_num) = self.number_buf.check_timeout() {
53            self.jump_to_clip(clip_num);
54        }
55    }
56
57
58    pub fn jump_to_clip(&mut self, clip_number: usize) {
59        if let Some(track) = self.current_track() {
60            tracing::debug!(
61                "jump_to_clip: looking for #{}, track has {} clips: {:?}",
62                clip_number, track.clips.len(),
63                track.clips.iter().map(|c| (c.number, c.start_tick, c.length_ticks)).collect::<Vec<_>>()
64            );
65            if let Some(idx) = track.clips.iter().position(|c| c.number == clip_number) {
66                self.track_element = TrackElement::Clip(idx);
67                self.open_clip_view(self.track_cursor, idx);
68                tracing::debug!("jump_to_clip: selected idx={}", idx);
69            }
70        }
71    }
72
73
74    pub fn activate_element(&mut self) {
75        match self.track_element {
76            TrackElement::Mute => self.toggle_mute(),
77            TrackElement::Solo => self.toggle_solo(),
78            TrackElement::RecordArm => self.toggle_arm(),
79            TrackElement::Fx => {
80                self.fx_menu.open = true;
81                self.fx_menu.cursor = 0;
82            }
83            TrackElement::Volume => {
84                // Lock the fader so h/l adjusts it instead of stepping to the
85                // next element — the same Enter-to-lock, Esc-to-release shape
86                // as a clip and as the transport's BPM field. Only on tracks
87                // that have a fader: a bus track's header does not draw one,
88                // and locking a control that is not on screen is a dead end.
89                if self.current_track().is_some_and(super::TrackState::is_live) {
90                    self.element_locked = true;
91                }
92            }
93            TrackElement::Clip(idx) => {
94                self.element_locked = true;
95                self.open_clip_view(self.track_cursor, idx);
96                self.clip_view.clip_tab = ClipTab::PianoRoll;
97                self.clip_view.focus = ClipViewFocus::PianoRoll;
98                tracing::debug!(
99                    "clip locked: track={} clip={} start={} len={}",
100                    self.track_cursor, idx,
101                    self.tracks.get(self.track_cursor).and_then(|t| t.clips.get(idx)).map(|c| c.start_tick).unwrap_or(-1),
102                    self.tracks.get(self.track_cursor).and_then(|t| t.clips.get(idx)).map(|c| c.length_ticks).unwrap_or(-1),
103                );
104            }
105            _ => {}
106        }
107    }
108
109    /// Add a new instrument track. Inserts before the send/master tracks.
110    /// `handle` is the shared audio-thread handle for this track.
111    /// `mixer_id` is the track's ID in the mixer.
112
113    /// Add a new instrument track. Inserts before the send/master tracks.
114    /// `handle` is the shared audio-thread handle for this track.
115    /// `mixer_id` is the track's ID in the mixer.
116    pub fn add_instrument_track(
117        &mut self,
118        instrument: InstrumentType,
119        mixer_id: usize,
120        handle: std::sync::Arc<phosphor_core::project::TrackHandle>,
121    ) {
122        let name = match instrument {
123            InstrumentType::Synth => "synth",
124            InstrumentType::DrumRack => "drums",
125            InstrumentType::DX7 => "dx7",
126            InstrumentType::Jupiter8 => "jup8",
127            InstrumentType::Odyssey => "odyss",
128            InstrumentType::Juno60 => "juno",
129            InstrumentType::Sampler => "smplr",
130        };
131
132        // Find insert position: before sends/master
133        let insert_pos = self.tracks.iter().position(|t| {
134            matches!(t.kind, TrackKind::SendA | TrackKind::SendB | TrackKind::Master)
135        }).unwrap_or(self.tracks.len());
136
137        let color = insert_pos % 8;
138        let mut track = TrackState::new(name, color, true, TrackKind::Instrument, vec![]);
139        track.mixer_id = Some(mixer_id);
140        track.handle = Some(handle);
141        track.instrument_type = Some(instrument);
142        track.synth_params = match instrument {
143            InstrumentType::Synth | InstrumentType::Sampler => {
144                phosphor_dsp::synth::PARAM_DEFAULTS.to_vec()
145            }
146            InstrumentType::DrumRack => {
147                phosphor_dsp::drum_rack::PARAM_DEFAULTS.to_vec()
148            }
149            InstrumentType::DX7 => {
150                phosphor_dsp::dx7::PARAM_DEFAULTS.to_vec()
151            }
152            InstrumentType::Jupiter8 => {
153                phosphor_dsp::jupiter::PARAM_DEFAULTS.to_vec()
154            }
155            InstrumentType::Odyssey => {
156                phosphor_dsp::odyssey::PARAM_DEFAULTS.to_vec()
157            }
158            InstrumentType::Juno60 => {
159                phosphor_dsp::juno::PARAM_DEFAULTS.to_vec()
160            }
161        };
162        // Sync the initial armed state to audio
163        track.sync_to_audio();
164        self.tracks.insert(insert_pos, track);
165
166        // Move cursor to the new track and open clip view with synth controls
167        self.track_cursor = insert_pos;
168        if self.track_cursor >= self.track_scroll + MAX_VISIBLE_TRACKS {
169            self.track_scroll = self.track_cursor + 1 - MAX_VISIBLE_TRACKS;
170        }
171
172        // Select the track, show synth controls, and route MIDI to it
173        self.track_selected = true;
174        self.track_element = TrackElement::Label;
175        self.show_current_track_controls();
176    }
177
178
179    pub fn open_clip_view(&mut self, track_idx: usize, clip_idx: usize) {
180        self.clip_view_visible = true;
181        self.clip_view_target = Some((track_idx, clip_idx));
182        self.clip_view.fx_cursor = 0;
183        tracing::debug!(
184            "open_clip_view: track={} clip={} (notes={})",
185            track_idx, clip_idx,
186            self.tracks.get(track_idx).and_then(|t| t.clips.get(clip_idx)).map(|c| c.notes.len()).unwrap_or(0)
187        );
188    }
189
190    /// Show controls for the currently selected track and route MIDI to it.
191    /// For instrument tracks: opens clip view with Synth tab, activates MIDI input.
192    /// For bus tracks: no clip view, deactivates MIDI.
193
194    pub fn fx_menu_select(&mut self) {
195        // Add FX
196        if let Some(fx_type) = FxType::ALL.get(self.fx_menu.cursor) {
197            let inst = FxInstance::new(*fx_type);
198            if let Some(t) = self.current_track_mut() {
199                t.fx_chain.push(inst);
200            }
201        }
202        self.fx_menu.open = false;
203    }
204
205
206    pub fn active_fx_chain_len(&self) -> usize {
207        match self.clip_view.fx_panel_tab {
208            FxPanelTab::TrackFx | FxPanelTab::Synth => {
209                self.current_track().map(|t| t.fx_chain.len().max(1)).unwrap_or(1)
210            }
211        }
212    }
213
214    /// Keep clip_view_target in sync with the currently selected clip element.
215    /// Called every frame as a safety net and after clip-modifying operations.
216    pub fn sync_clip_view_target(&mut self) {
217        if self.track_selected {
218            if let TrackElement::Clip(idx) = self.track_element {
219                let track_idx = self.track_cursor;
220                if let Some(track) = self.tracks.get(track_idx) {
221                    if idx < track.clips.len() {
222                        self.clip_view_target = Some((track_idx, idx));
223                        self.clip_view_visible = true;
224                        return;
225                    }
226                }
227            }
228        }
229    }
230
231    /// Remove phantom clips: when two clips overlap at the same start position,
232    /// keep the longer one and absorb the shorter one's notes (rescaled).
233    /// Returns (mixer_id, removed_clip_index) pairs so the caller can sync audio.
234    pub fn dedup_clips(&mut self) -> Vec<(usize, usize)> {
235        let ppq = phosphor_core::transport::Transport::PPQ;
236        let tolerance = ppq;
237        let mut removed = Vec::new();
238
239        for track in &mut self.tracks {
240            if track.clips.len() < 2 { continue; }
241
242            track.clips.sort_by(|a, b| {
243                a.start_tick.cmp(&b.start_tick)
244                    .then(b.length_ticks.cmp(&a.length_ticks))
245            });
246
247            let mut i = 0;
248            while i + 1 < track.clips.len() {
249                let starts_close = (track.clips[i].start_tick - track.clips[i + 1].start_tick).abs() <= tolerance;
250                if starts_close {
251                    let shorter_len = track.clips[i + 1].length_ticks;
252                    let longer_len = track.clips[i].length_ticks;
253                    if longer_len > 0 {
254                        let scale = shorter_len as f64 / longer_len as f64;
255                        let absorbed: Vec<_> = track.clips[i + 1].notes.iter().map(|n| {
256                            let mut rescaled = *n;
257                            rescaled.start_frac *= scale;
258                            rescaled.duration_frac *= scale;
259                            rescaled
260                        }).collect();
261                        track.clips[i].notes.extend(absorbed);
262                    }
263                    tracing::debug!(
264                        "dedup: absorbed clip #{} (len={}) into clip #{} (len={}) on '{}'",
265                        track.clips[i + 1].number, shorter_len,
266                        track.clips[i].number, longer_len, track.name
267                    );
268                    // Record the removal for audio thread sync
269                    if let Some(mid) = track.mixer_id {
270                        removed.push((mid, i + 1));
271                    }
272                    track.clips.remove(i + 1);
273                } else {
274                    i += 1;
275                }
276            }
277
278            for (idx, clip) in track.clips.iter_mut().enumerate() {
279                clip.number = idx + 1;
280            }
281        }
282        removed
283    }
284
285    // ── Accessors ──
286
287
288    /// Receive a clip snapshot from the audio thread and add it to the
289    /// corresponding TUI track's clip list.
290    /// `is_recording` = true when transport is actively recording (snapshots are fresh overdubs).
291    /// When NOT recording, snapshots matching the viewed clip are stale (from panic/reset) and ignored.
292    /// Returns (mixer_id, count_absorbed) so caller can send RemoveClip commands to audio.
293    pub fn receive_clip_snapshot(&mut self, snap: phosphor_core::clip::ClipSnapshot, is_recording: bool) -> Option<(usize, usize)> {
294        tracing::debug!(
295            "clip received: track={} events={} notes={} ticks={}..{} recording={}",
296            snap.track_id, snap.event_count, snap.notes.len(),
297            snap.start_tick, snap.start_tick + snap.length_ticks, is_recording,
298        );
299
300        // When NOT recording AND no grace remaining, ignore snapshots.
301        // These are stale commits from panic/reset_all that would re-add
302        // deleted notes or create phantom clips.
303        // Accept if: (a) currently recording, OR (b) grace counter > 0
304        // (final commits from tracks that just stopped recording).
305        if !is_recording && self.recording_grace == 0 {
306            tracing::debug!("IGNORED: snapshot while not recording (stale from panic/reset)");
307            return None;
308        }
309        // Decrement grace after accepting a post-recording snapshot
310        if !is_recording && self.recording_grace > 0 {
311            self.recording_grace -= 1;
312        }
313
314        // Find the track index (we need it for clip_view_target fixup)
315        let track_idx = match self.tracks.iter().position(|t| t.mixer_id == Some(snap.track_id)) {
316            Some(idx) => idx,
317            None => return None,
318        };
319
320        let mut absorbed_count = 0usize;
321        {
322            let track = &mut self.tracks[track_idx];
323            let ppq = phosphor_core::transport::Transport::PPQ;
324            let beats = (snap.length_ticks as f64 / ppq as f64).ceil() as u16;
325            let width = beats.max(2);
326            let snap_end = snap.start_tick + snap.length_ticks;
327
328            // Absorb any clips that the new recording fully covers.
329            // A clip is covered if it starts within the snap range and ends within it.
330            let mut absorbed_notes = Vec::new();
331            track.clips.retain(|c| {
332                let c_end = c.start_tick + c.length_ticks;
333                let covered = c.start_tick >= snap.start_tick && c_end <= snap_end;
334                if covered {
335                    tracing::debug!(
336                        "  absorbing clip #{}: tick {}..{} (snap covers {}..{})",
337                        c.number, c.start_tick, c_end, snap.start_tick, snap_end
338                    );
339                    // Rescale notes to snap's coordinate space
340                    let offset = (c.start_tick - snap.start_tick) as f64 / snap.length_ticks as f64;
341                    let scale = c.length_ticks as f64 / snap.length_ticks as f64;
342                    for mut n in c.notes.clone() {
343                        n.start_frac = n.start_frac * scale + offset;
344                        n.duration_frac *= scale;
345                        absorbed_notes.push(n);
346                    }
347                    absorbed_count += 1;
348                    false
349                } else {
350                    true
351                }
352            });
353
354            // Combine absorbed notes with the new recording's notes
355            let mut all_notes = absorbed_notes;
356            all_notes.extend(snap.notes);
357
358            // Try to merge into an existing clip with a close start
359            let merge_tolerance = ppq;
360            if let Some(existing) = track.clips.iter_mut().find(|c| {
361                (c.start_tick - snap.start_tick).abs() <= merge_tolerance
362            }) {
363                // Rescale if lengths differ
364                if snap.length_ticks != existing.length_ticks && existing.length_ticks > 0 {
365                    let scale = snap.length_ticks as f64 / existing.length_ticks as f64;
366                    let offset = (snap.start_tick - existing.start_tick) as f64 / existing.length_ticks as f64;
367                    for n in &mut all_notes {
368                        n.start_frac = n.start_frac * scale + offset;
369                        n.duration_frac *= scale;
370                    }
371                }
372                existing.notes.extend(all_notes);
373                existing.has_content = true;
374                existing.length_ticks = existing.length_ticks.max(snap.length_ticks);
375                existing.width = width.max(existing.width);
376                tracing::debug!(
377                    "  merged into existing clip: now {} notes, len={}",
378                    existing.notes.len(), existing.length_ticks
379                );
380            } else {
381                // Create new clip
382                let clip_number = track.clips.len() + 1;
383                tracing::debug!(
384                    "  new clip: #{} at tick {} len {} ({} notes, absorbed {})",
385                    clip_number, snap.start_tick, snap.length_ticks, all_notes.len(), absorbed_count
386                );
387                track.clips.push(Clip {
388                    number: clip_number,
389                    width,
390                    has_content: true,
391                    start_tick: snap.start_tick,
392                    length_ticks: snap.length_ticks,
393                    notes: all_notes,
394                    hidden_notes: Vec::new(),
395                });
396            }
397
398            // Renumber clips sequentially
399            for (i, c) in track.clips.iter_mut().enumerate() {
400                c.number = i + 1;
401            }
402        }
403
404        // Fix clip_view_target if it was pointing at this track
405        // (clips may have been absorbed/reordered)
406        if let Some((ti, ci)) = self.clip_view_target {
407            if ti == track_idx {
408                let num_clips = self.tracks[track_idx].clips.len();
409                if num_clips == 0 {
410                    self.clip_view_target = None;
411                    self.clip_view_visible = false;
412                } else if ci >= num_clips {
413                    // Target was past the end — point to the last clip
414                    self.clip_view_target = Some((track_idx, num_clips - 1));
415                    tracing::debug!(
416                        "  clip_view_target fixed: {} -> {}", ci, num_clips - 1
417                    );
418                }
419            }
420        }
421
422        // Return absorption info so caller can sync removed clips to audio
423        if absorbed_count > 0 {
424            Some((snap.track_id, absorbed_count))
425        } else {
426            None
427        }
428    }
429}
430
431// ── Initial Data ──
432
433/// Initial tracks: just the bus tracks. Instruments are added by the user via Space+A.
434pub fn initial_tracks() -> Vec<TrackState> {
435    vec![
436        TrackState::new("snd a", 5, false, TrackKind::SendA, vec![]),
437        TrackState::new("snd b", 6, false, TrackKind::SendB, vec![]),
438        TrackState::new("mstr", 7, false, TrackKind::Master, vec![]),
439    ]
440}