phosphor-app 0.3.21

Shared business logic for Phosphor DAW frontends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! TUI navigation state — focus, cursors, selection, leader keys, FX.
//!
//! Navigation:
//!   Space+N  → jump to component (1=Tracks, 2=ClipView)
//!   Tab      → cycle focus between components
//!   j/k      → vertical nav
//!   h/l      → horizontal nav
//!   Enter    → select / activate / open menus
//!   Esc      → back out one level

mod clip_view;
mod input;
mod loop_editor;
mod menu;
mod track;
mod transport_ui;
pub mod undo;

pub use clip_view::*;
pub use input::*;
pub use loop_editor::*;
pub use menu::*;
pub use track::*;
pub use transport_ui::*;
mod navigation;
mod params;
mod track_ops;
pub use track_ops::initial_tracks;

use phosphor_core::project::TrackKind;

// ── Panes ──

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    Transport,
    Tracks,
    ClipView,
}

impl Pane {
    pub fn number(self) -> u8 {
        match self {
            Self::Transport => 1,
            Self::Tracks => 2,
            Self::ClipView => 3,
        }
    }

    pub fn from_number(n: u8) -> Option<Self> {
        match n {
            1 => Some(Self::Transport),
            2 => Some(Self::Tracks),
            3 => Some(Self::ClipView),
            _ => None,
        }
    }

    pub fn next(self) -> Self {
        match self {
            Self::Transport => Self::Tracks,
            Self::Tracks => Self::ClipView,
            Self::ClipView => Self::Transport,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            Self::Transport => Self::ClipView,
            Self::Tracks => Self::Transport,
            Self::ClipView => Self::Tracks,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Transport => "transport",
            Self::Tracks => "tracks",
            Self::ClipView => "clip",
        }
    }
}

// ── Full Nav State ──

pub const MAX_VISIBLE_TRACKS: usize = 5;
/// Total number of parameters in the inst config panel (LFO:4 + Filter:4 + Envelope:4 + Pitch:3).
pub const INST_CONFIG_PARAM_COUNT: usize = 15;

#[derive(Debug)]
pub struct NavState {
    pub focused_pane: Pane,
    pub track_cursor: usize,
    pub track_scroll: usize,
    pub track_selected: bool,
    pub track_element: TrackElement,
    pub number_buf: NumberBuffer,
    pub space_menu: SpaceMenu,
    pub clip_view: ClipViewState,
    pub clip_view_visible: bool,
    /// (track_idx, clip_idx) shown in clip view.
    pub clip_view_target: Option<(usize, usize)>,
    /// FX menu state (per-track fx button).
    pub fx_menu: FxMenu,
    pub instrument_modal: InstrumentModal,
    pub loop_editor: LoopEditor,
    pub transport_ui: TransportUiState,
    pub tracks: Vec<TrackState>,
    /// Text input modal (for save/open file paths).
    pub input_modal: InputModal,
    /// Confirmation modal (for delete actions).
    pub confirm_modal: ConfirmModal,
    /// Undo/redo stack.
    pub undo_stack: undo::UndoStack,
    /// Quantize modal state.
    pub quantize_modal: QuantizeModal,
    /// User preset browser for the track under the cursor.
    pub preset_modal: PresetModal,
    /// Whether the selected track element is "locked" for editing — Enter
    /// locks, Esc releases. While locked, h/l edits that element instead of
    /// navigating between elements, which is the same shape as the
    /// transport's BPM field and the loop editor.
    ///
    /// One flag rather than one per element: `track_element` already says
    /// *which* element the keys go to, so a second flag would only make it
    /// possible to have two things locked at once.
    pub element_locked: bool,
    /// Grace counter: set to the number of armed tracks when recording stops.
    /// Decremented as each valid snapshot is accepted. Prevents stale snapshots
    /// while allowing final recording commits from all tracks to come through.
    pub recording_grace: usize,
}

impl NavState {
    pub fn new(tracks: Vec<TrackState>) -> Self {
        Self {
            focused_pane: Pane::Tracks,
            track_cursor: 0,
            track_scroll: 0,
            track_selected: false,
            track_element: TrackElement::Label,
            number_buf: NumberBuffer::new(),
            space_menu: SpaceMenu::new(),
            clip_view: ClipViewState::new(),
            clip_view_visible: false,
            clip_view_target: None,
            fx_menu: FxMenu::new(),
            instrument_modal: InstrumentModal::new(),
            loop_editor: LoopEditor::new(),
            transport_ui: TransportUiState::new(),
            tracks,
            input_modal: InputModal::new(),
            confirm_modal: ConfirmModal::new(),
            undo_stack: undo::UndoStack::new(),
            quantize_modal: QuantizeModal::new(),
            preset_modal: PresetModal::new(),
            element_locked: false,
            recording_grace: 0,
        }
    }
    pub fn visible_tracks(&self) -> &[TrackState] {
        let end = (self.track_scroll + MAX_VISIBLE_TRACKS).min(self.tracks.len());
        &self.tracks[self.track_scroll..end]
    }

    pub fn can_scroll_up(&self) -> bool { self.track_scroll > 0 }

    pub fn can_scroll_down(&self) -> bool {
        self.track_scroll + MAX_VISIBLE_TRACKS < self.tracks.len()
    }

    pub fn current_track(&self) -> Option<&TrackState> { self.tracks.get(self.track_cursor) }

    pub fn current_track_mut(&mut self) -> Option<&mut TrackState> {
        self.tracks.get_mut(self.track_cursor)
    }

    pub fn active_clip(&self) -> Option<&Clip> {
        let (ti, ci) = self.clip_view_target?;
        self.tracks.get(ti)?.clips.get(ci)
    }

    pub fn active_clip_mut(&mut self) -> Option<&mut Clip> {
        let (ti, ci) = self.clip_view_target?;
        self.tracks.get_mut(ti)?.clips.get_mut(ci)
    }

    pub fn active_clip_track(&self) -> Option<&TrackState> {
        let (ti, _) = self.clip_view_target?;
        self.tracks.get(ti)
    }
}

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

    #[test]
    fn pane_numbers() {
        assert_eq!(Pane::Transport.number(), 1);
        assert_eq!(Pane::Tracks.number(), 2);
        assert_eq!(Pane::ClipView.number(), 3);
        assert_eq!(Pane::from_number(1), Some(Pane::Transport));
        assert_eq!(Pane::from_number(2), Some(Pane::Tracks));
        assert_eq!(Pane::from_number(3), Some(Pane::ClipView));
        assert_eq!(Pane::from_number(9), None);
    }

    #[test]
    fn track_element_navigation_full() {
        let e = TrackElement::Label;
        assert_eq!(e.move_right(3), TrackElement::Fx);
        assert_eq!(TrackElement::Fx.move_right(3), TrackElement::Volume);
        assert_eq!(TrackElement::Volume.move_right(3), TrackElement::Mute);
        assert_eq!(TrackElement::Mute.move_right(3), TrackElement::Solo);
        assert_eq!(TrackElement::Solo.move_right(3), TrackElement::RecordArm);
        assert_eq!(TrackElement::RecordArm.move_right(3), TrackElement::Clip(0));
        assert_eq!(TrackElement::Clip(2).move_right(3), TrackElement::Clip(2));
    }

    #[test]
    fn track_element_left_full() {
        assert_eq!(TrackElement::Clip(0).move_left(), TrackElement::RecordArm);
        assert_eq!(TrackElement::RecordArm.move_left(), TrackElement::Solo);
        assert_eq!(TrackElement::Solo.move_left(), TrackElement::Mute);
        assert_eq!(TrackElement::Mute.move_left(), TrackElement::Volume);
        assert_eq!(TrackElement::Volume.move_left(), TrackElement::Fx);
        assert_eq!(TrackElement::Fx.move_left(), TrackElement::Label);
        assert_eq!(TrackElement::Label.move_left(), TrackElement::Label);
    }

    #[test]
    fn initial_tracks_has_sends_and_master() {
        let tracks = initial_tracks();
        assert_eq!(tracks.len(), 3); // send A + send B + master
        assert_eq!(tracks[0].kind, TrackKind::SendA);
        assert_eq!(tracks[1].kind, TrackKind::SendB);
        assert_eq!(tracks[2].kind, TrackKind::Master);
    }

    #[test]
    fn sends_are_at_end() {
        let mut nav = NavState::new(initial_tracks());
        nav.move_down();
        nav.move_down();
        assert_eq!(nav.track_cursor, 2);
        assert_eq!(nav.tracks[nav.track_cursor].kind, TrackKind::Master);
    }

    #[test]
    fn fx_menu_opens_and_closes() {
        let mut nav = NavState::new(initial_tracks());
        nav.enter(); // select track
        // Navigate to FX
        nav.move_right(); // -> Fx
        assert_eq!(nav.track_element, TrackElement::Fx);
        nav.enter(); // open FX menu
        assert!(nav.fx_menu.open);

        nav.escape(); // close menu
        assert!(!nav.fx_menu.open);
    }

    #[test]
    fn fx_menu_add_effect() {
        let mut nav = NavState::new(initial_tracks());
        let initial_count = nav.tracks[0].fx_chain.len();
        nav.enter();
        nav.move_right(); // -> Fx
        nav.enter(); // open menu
        nav.enter(); // select first item (Reverb)
        assert!(!nav.fx_menu.open);
        assert_eq!(nav.tracks[0].fx_chain.len(), initial_count + 1);
        assert_eq!(nav.tracks[0].fx_chain.last().unwrap().fx_type, FxType::Reverb);
    }

    #[test]
    fn clip_view_focus_toggle() {
        let mut nav = NavState::new(initial_tracks());
        // Manually set up clip view (simulating an instrument track being selected)
        nav.clip_view_visible = true;
        nav.clip_view_target = Some((0, 0));

        nav.focus_pane(Pane::ClipView);
        assert_eq!(nav.clip_view.focus, ClipViewFocus::PianoRoll);

        nav.move_left(); // -> FxPanel
        assert_eq!(nav.clip_view.focus, ClipViewFocus::FxPanel);
    }

    #[test]
    fn clip_view_tabs_cycle() {
        let mut nav = NavState::new(initial_tracks());
        nav.focused_pane = Pane::ClipView;
        nav.clip_view.focus = ClipViewFocus::FxPanel;

        // Tab cycles: trk fx → synth → inst config → piano → auto → trk fx
        assert_eq!(nav.clip_view.fx_panel_tab, FxPanelTab::TrackFx);
        nav.cycle_tab();
        assert_eq!(nav.clip_view.fx_panel_tab, FxPanelTab::Synth);
        nav.cycle_tab();
        // Now switches to inst config
        assert_eq!(nav.clip_view.focus, ClipViewFocus::PianoRoll);
        assert_eq!(nav.clip_view.clip_tab, ClipTab::InstConfig);
        nav.cycle_tab();
        // Now switches to piano roll
        assert_eq!(nav.clip_view.clip_tab, ClipTab::PianoRoll);
        nav.cycle_tab();
        assert_eq!(nav.clip_view.clip_tab, ClipTab::Settings);
        nav.cycle_tab();
        // Back to FX panel
        assert_eq!(nav.clip_view.focus, ClipViewFocus::FxPanel);
        assert_eq!(nav.clip_view.fx_panel_tab, FxPanelTab::TrackFx);
    }

    #[test]
    fn arm_toggle() {
        let mut nav = NavState::new(initial_tracks());
        assert!(!nav.tracks[0].armed); // bus tracks start unarmed
        nav.toggle_arm();
        assert!(nav.tracks[0].armed);
        nav.toggle_arm();
        assert!(!nav.tracks[0].armed);
    }

    #[test]
    fn space_menu_toggle() {
        let mut nav = NavState::new(initial_tracks());
        assert!(!nav.space_menu.open);
        nav.toggle_space_menu();
        assert!(nav.space_menu.open);
        nav.toggle_space_menu();
        assert!(!nav.space_menu.open);
    }

    #[test]
    fn space_menu_handle_pane_jump() {
        let mut nav = NavState::new(initial_tracks());
        nav.toggle_space_menu();
        let action = nav.space_menu_handle('2');
        assert_eq!(nav.focused_pane, Pane::Tracks);
        assert!(action.is_none());
        assert!(!nav.space_menu.open);

        nav.toggle_space_menu();
        let action = nav.space_menu_handle('1');
        assert_eq!(nav.focused_pane, Pane::Transport);
        assert!(action.is_none());
    }

    #[test]
    fn space_menu_handle_play_pause() {
        let mut nav = NavState::new(initial_tracks());
        nav.toggle_space_menu();
        let action = nav.space_menu_handle('p');
        assert_eq!(action, Some(SpaceAction::PlayPause));
        assert!(!nav.space_menu.open);
    }

    #[test]
    fn space_menu_enter_select() {
        let mut nav = NavState::new(initial_tracks());
        nav.toggle_space_menu();
        // cursor at 0 = "spc+1" = tracks
        let action = nav.enter();
        assert!(action.is_none()); // pane jump
        assert!(!nav.space_menu.open);
    }

    #[test]
    fn space_menu_nav_and_help() {
        let mut nav = NavState::new(initial_tracks());
        nav.toggle_space_menu();
        assert_eq!(nav.space_menu.section, SpaceMenuSection::Actions);
        nav.space_menu.switch_section();
        assert_eq!(nav.space_menu.section, SpaceMenuSection::Help);
        assert_eq!(nav.space_menu.cursor, 0);
    }

    #[test]
    fn number_buffer_commit() {
        let mut buf = NumberBuffer::new();
        buf.push_digit('1');
        assert_eq!(buf.commit(), Some(1));
        buf.push_digit('1');
        buf.push_digit('2');
        assert_eq!(buf.commit(), Some(12));
    }

    #[test]
    fn number_buffer_empty_commit() {
        assert_eq!(NumberBuffer::new().commit(), None);
    }

    #[test]
    fn nav_cursor_bounds() {
        let mut nav = NavState::new(initial_tracks());
        for _ in 0..20 { nav.move_down(); }
        assert_eq!(nav.track_cursor, 2); // 3 bus tracks
    }

    #[test]
    fn enter_escape_track() {
        let mut nav = NavState::new(initial_tracks());
        nav.enter();
        assert!(nav.track_selected);
        nav.escape();
        assert!(!nav.track_selected);
    }

    #[test]
    fn mute_solo_toggle() {
        let mut nav = NavState::new(initial_tracks());
        nav.toggle_mute();
        assert!(nav.tracks[0].muted);
        nav.toggle_solo();
        assert!(nav.tracks[0].soloed);
    }

    #[test]
    fn volume_element_in_chain() {
        // Ensure volume is navigable
        let e = TrackElement::Fx;
        assert_eq!(e.move_right(1), TrackElement::Volume);
        assert_eq!(TrackElement::Volume.move_left(), TrackElement::Fx);
    }

    // ── Fader ──

    use phosphor_core::project::{TrackConfig, TrackHandle};

    /// A track wired to an audio-thread handle, so the tests can check the
    /// fader reaches it rather than only the UI mirror.
    fn live_track() -> TrackState {
        let mut t = TrackState::new("t", 0, false, TrackKind::Instrument, vec![]);
        t.handle = Some(std::sync::Arc::new(TrackHandle::new(0, TrackKind::Instrument)));
        t.mixer_id = Some(0);
        t
    }

    fn handle_volume(t: &TrackState) -> f32 {
        t.handle.as_ref().unwrap().config.get_volume()
    }

    /// Every press moves the readout by exactly one dB. This is the property
    /// the dB-stepping exists for: a linear step would round to the same
    /// displayed number several presses in a row.
    #[test]
    fn fader_steps_one_db_per_press() {
        let mut t = live_track();
        // The default is -2.5 dB, off the grid; the first press snaps onto it.
        t.adjust_volume(1);
        let start = t.volume_db().unwrap().round();
        for i in 1..=6 {
            t.adjust_volume(1);
            let db = t.volume_db().unwrap();
            assert!(
                (db - (start + i as f32)).abs() < 0.01,
                "press {i} landed at {db:.3} dB, expected {:.3}",
                start + i as f32
            );
        }
    }

    /// The fader reaches unity exactly, so "no gain change" is a position the
    /// user can actually select rather than one they can only get near.
    #[test]
    fn fader_lands_exactly_on_unity() {
        let mut t = live_track();
        for _ in 0..40 {
            t.adjust_volume(1);
        }
        // At the top; walk back down to 0 dB.
        while t.volume_db().unwrap() > 0.5 {
            t.adjust_volume(-1);
        }
        assert!(
            (t.volume - TrackConfig::UNITY_VOLUME).abs() < 1.0e-3,
            "fader stopped at {} instead of unity",
            t.volume
        );
    }

    /// The travel has ends. Holding `l` cannot push the track past +6 dB, and
    /// holding `h` reaches silence rather than an ever-smaller number.
    #[test]
    fn fader_travel_is_bounded_at_both_ends() {
        let mut t = live_track();
        for _ in 0..200 {
            t.adjust_volume(1);
        }
        assert_eq!(t.volume, TrackConfig::MAX_VOLUME);
        assert_eq!(handle_volume(&t), TrackConfig::MAX_VOLUME);

        for _ in 0..200 {
            t.adjust_volume(-1);
        }
        assert_eq!(t.volume, TrackConfig::MIN_VOLUME);
        assert_eq!(handle_volume(&t), TrackConfig::MIN_VOLUME);

        // And it comes back off the bottom rather than sticking there.
        t.adjust_volume(1);
        assert!(t.volume > 0.0, "fader stuck at silence");
    }

    /// Every press pushes the new position to the audio thread. Without this
    /// the fader moves on screen and nothing happens in the speakers, which
    /// is the state this control was in before.
    #[test]
    fn fader_syncs_to_the_audio_thread() {
        let mut t = live_track();
        for steps in [1, 1, -1, 3, -7] {
            t.adjust_volume(steps);
            assert_eq!(
                handle_volume(&t),
                t.volume,
                "audio thread has {} while the UI shows {}",
                handle_volume(&t),
                t.volume
            );
        }
    }

    /// A position loaded from a session that is not on the dB grid snaps onto
    /// it on the first press instead of carrying the offset forever.
    #[test]
    fn fader_snaps_a_loaded_position_onto_the_grid() {
        let mut t = live_track();
        t.volume = 0.6234; // -4.1 dB, as if hand-edited into a .phos file
        t.adjust_volume(1);
        let db = t.volume_db().unwrap();
        assert!((db - db.round()).abs() < 0.01, "off the grid at {db:.3} dB");
    }

    /// Enter locks the fader so h/l edits it, and only on tracks that have
    /// one — a bus track's header does not draw a fader.
    #[test]
    fn enter_locks_the_fader_only_on_tracks_that_have_one() {
        let mut nav = NavState::new(initial_tracks()); // bus tracks only
        nav.enter();
        nav.move_right(); // Label -> Fx
        nav.move_right(); // Fx -> Volume
        assert_eq!(nav.track_element, TrackElement::Volume);
        nav.enter();
        assert!(!nav.element_locked, "locked the fader on a bus track");

        nav.tracks.push(live_track());
        nav.track_cursor = nav.tracks.len() - 1;
        nav.enter();
        assert!(nav.element_locked, "did not lock the fader on an instrument track");

        // Esc releases, leaving the element selected.
        nav.escape();
        assert!(!nav.element_locked);
        assert_eq!(nav.track_element, TrackElement::Volume);
    }

    /// The fader is not undoable — it is a continuous control, and neither
    /// mute, solo, arm nor the synth parameters push onto the stack either.
    #[test]
    fn fader_does_not_push_onto_the_undo_stack() {
        let mut nav = NavState::new(vec![live_track()]);
        assert!(!nav.undo_stack.can_undo());
        nav.adjust_volume(3);
        nav.adjust_volume(-1);
        assert!(
            !nav.undo_stack.can_undo(),
            "the fader pushed an undo entry; mute and solo do not"
        );
    }
}