maolan 0.2.0

Rust DAW application for recording, editing, routing, automation, export, and plugin hosting
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
mod editor;
mod mixer;
mod ruler;
mod tempo;
mod tracks;

use crate::{
    consts::{
        state_ids::METRONOME_TRACK_ID,
        widget_piano::{
            KEYBOARD_WIDTH, MAIN_SPLIT_SPACING, RIGHT_SCROLL_GUTTER_WIDTH, TOOLS_STRIP_WIDTH,
        },
        workspace::{MIN_TIMELINE_BARS, PLAYHEAD_WIDTH_PX, TIMELINE_LEFT_INSET_PX},
    },
    gui::visible_bars_to_zoom_slider,
    message::{DraggedClip, Message, SnapMode},
    state::{ClipPeaks, MidiClipPreviewMap, State},
    widget::{midi_edit, pitch_correction},
};
use editor::{EditorViewArgs, OwnedEditorViewArgs};
use iced::{
    Background, Color, Element, Length, Point,
    widget::{Id, Space, Stack, column, container, lazy, mouse_area, pin, row, scrollable, slider},
};
use maolan_widgets::{
    horizontal_scrollbar::HorizontalScrollbar, vertical_scrollbar::VerticalScrollbar,
};
use ruler::RulerViewArgs;
use std::{collections::HashMap, path::PathBuf};
use tempo::TempoViewArgs;

pub use crate::consts::workspace_ids::{
    EDITOR_SCROLL_ID, EDITOR_TIMELINE_SCROLL_ID, PIANO_RULER_SCROLL_ID, PIANO_TEMPO_SCROLL_ID,
    TRACKS_SCROLL_ID, WORKSPACE_RULER_SCROLL_ID, WORKSPACE_TEMPO_SCROLL_ID,
};

pub(crate) fn timeline_sample_to_x_f64(sample: f64, pixels_per_sample: f32, inset_px: f32) -> f32 {
    inset_px + (sample as f32 * pixels_per_sample).max(0.0)
}

pub(crate) fn timeline_sample_to_x(sample: usize, pixels_per_sample: f32, inset_px: f32) -> f32 {
    timeline_sample_to_x_f64(sample as f64, pixels_per_sample, inset_px)
}

pub(crate) fn timeline_x_to_sample_f32(x: f32, pixels_per_sample: f32, inset_px: f32) -> f32 {
    if pixels_per_sample <= 1.0e-9 {
        0.0
    } else {
        ((x - inset_px).max(0.0) / pixels_per_sample).max(0.0)
    }
}

fn clip_kind_key(kind: maolan_engine::kind::Kind) -> u8 {
    match kind {
        maolan_engine::kind::Kind::Audio => 0,
        maolan_engine::kind::Kind::MIDI => 1,
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ClipSnapEdge {
    pub clip_id: crate::state::ClipId,
    pub sample: usize,
}

#[derive(Debug, Clone, Copy)]
pub(super) struct VisibleTrackWindow {
    pub start_index: usize,
    pub end_index: usize,
    pub top_padding: f32,
    pub bottom_padding: f32,
}

fn compute_visible_track_window(
    track_heights: &[f32],
    scroll_y: f32,
    viewport_height: f32,
) -> VisibleTrackWindow {
    if track_heights.is_empty() {
        return VisibleTrackWindow {
            start_index: 0,
            end_index: 0,
            top_padding: 0.0,
            bottom_padding: 0.0,
        };
    }

    const OVERSCAN_PX: f32 = 240.0;

    let total_height = track_heights.iter().sum::<f32>().max(1.0);
    let viewport_height = viewport_height.max(track_heights[0]).min(total_height);
    let max_scroll = (total_height - viewport_height).max(0.0);
    let scroll_top = scroll_y.clamp(0.0, 1.0) * max_scroll;
    let visible_top = (scroll_top - OVERSCAN_PX).max(0.0);
    let visible_bottom = (scroll_top + viewport_height + OVERSCAN_PX).min(total_height);

    let mut top_padding = 0.0;
    let mut start_index = 0;
    while start_index < track_heights.len()
        && top_padding + track_heights[start_index] <= visible_top
    {
        top_padding += track_heights[start_index];
        start_index += 1;
    }

    let mut bottom_edge = top_padding;
    let mut end_index = start_index;
    while end_index < track_heights.len() && bottom_edge < visible_bottom {
        bottom_edge += track_heights[end_index];
        end_index += 1;
    }

    if start_index == end_index {
        end_index = (start_index + 1).min(track_heights.len());
        bottom_edge = top_padding + track_heights[start_index.min(track_heights.len() - 1)];
    }

    VisibleTrackWindow {
        start_index,
        end_index,
        top_padding,
        bottom_padding: (total_height - bottom_edge).max(0.0),
    }
}

pub struct Workspace {
    state: State,
    editor: editor::Editor,
    mixer: mixer::Mixer,
    midi_edit: midi_edit::MIDIEdit,
    pitch_correction: pitch_correction::PitchCorrection,
    ruler: ruler::Ruler,
    tempo: tempo::Tempo,
    tracks: tracks::Tracks,
}

pub struct WorkspaceViewArgs<'a> {
    pub session_root: Option<&'a PathBuf>,
    pub playhead_samples: Option<f64>,
    pub transport_active: bool,
    pub pixels_per_sample: f32,
    pub beat_pixels: f32,
    pub samples_per_bar: f32,
    pub loop_range_samples: Option<(usize, usize)>,
    pub punch_range_samples: Option<(usize, usize)>,
    pub snap_mode: SnapMode,
    pub samples_per_beat: f64,
    pub zoom_visible_bars: f32,
    pub editor_scroll_x: f32,
    pub mixer_scroll_x: f32,
    pub window_width: f32,
    pub window_height: f32,
    pub editor_scroll_y: f32,
    pub track_drag_active: bool,
    pub tracks_resize_hovered: bool,
    pub mixer_resize_hovered: bool,
    pub tracks_visible: bool,
    pub editor_visible: bool,
    pub mixer_visible: bool,
    pub active_clip_drag: Option<&'a DraggedClip>,
    pub active_clip_target_track: Option<&'a str>,
    pub active_clip_target_valid: bool,
    pub active_clip_snap_adjust_samples: f32,
    pub active_clip_snap_targets: &'a [crate::state::ClipId],
    pub recording_preview_bounds: Option<(usize, usize)>,
    pub recording_preview_peaks: Option<&'a HashMap<String, ClipPeaks>>,
    pub midi_clip_previews: Option<&'a MidiClipPreviewMap>,
    pub shift_pressed: bool,
    pub selected_tempo_points: Vec<usize>,
    pub selected_time_signature_points: Vec<usize>,
    pub mixer_level_edit_track: Option<&'a str>,
    pub mixer_level_edit_input: &'a str,
    pub sample_rate: f64,
}

impl Workspace {
    pub fn new(state: State) -> Self {
        Self {
            state: state.clone(),
            editor: editor::Editor::new(state.clone()),
            mixer: mixer::Mixer::new(state.clone()),
            midi_edit: midi_edit::MIDIEdit::new(state.clone()),
            pitch_correction: pitch_correction::PitchCorrection::new(state.clone()),
            ruler: ruler::Ruler::new(),
            tempo: tempo::Tempo::new(),
            tracks: tracks::Tracks::new(state.clone()),
        }
    }

    pub fn update(&mut self, _message: &Message) {}

    pub fn set_midi_edit_midnam_note_names(
        &mut self,
        names: &std::collections::HashMap<u8, String>,
    ) {
        self.midi_edit.set_midnam_note_names(names);
    }

    fn collect_clip_snap_edges(&self) -> Vec<ClipSnapEdge> {
        let state = self.state.blocking_read();
        let mut edges = Vec::new();
        for track in &state.tracks {
            for (clip_idx, clip) in track.audio.clips.iter().enumerate() {
                let clip_id = crate::state::ClipId {
                    track_idx: track.name.clone(),
                    clip_idx,
                    kind: maolan_engine::kind::Kind::Audio,
                };
                edges.push(ClipSnapEdge {
                    clip_id: clip_id.clone(),
                    sample: clip.start,
                });
                edges.push(ClipSnapEdge {
                    clip_id,
                    sample: clip.start.saturating_add(clip.length),
                });
            }
            for (clip_idx, clip) in track.midi.clips.iter().enumerate() {
                let clip_id = crate::state::ClipId {
                    track_idx: track.name.clone(),
                    clip_idx,
                    kind: maolan_engine::kind::Kind::MIDI,
                };
                edges.push(ClipSnapEdge {
                    clip_id: clip_id.clone(),
                    sample: clip.start,
                });
                edges.push(ClipSnapEdge {
                    clip_id,
                    sample: clip.start.saturating_add(clip.length),
                });
            }
        }
        edges.sort_unstable_by(|a, b| {
            a.sample
                .cmp(&b.sample)
                .then_with(|| a.clip_id.track_idx.cmp(&b.clip_id.track_idx))
                .then_with(|| a.clip_id.clip_idx.cmp(&b.clip_id.clip_idx))
                .then_with(|| clip_kind_key(a.clip_id.kind).cmp(&clip_kind_key(b.clip_id.kind)))
        });
        edges.dedup();
        edges
    }

    fn playhead_line() -> Element<'static, Message> {
        container("")
            .width(Length::Fixed(PLAYHEAD_WIDTH_PX))
            .height(Length::Fill)
            .style(|_theme| container::Style {
                background: Some(Background::Color(Color {
                    r: 0.95,
                    g: 0.18,
                    b: 0.14,
                    a: 0.95,
                })),
                ..container::Style::default()
            })
            .into()
    }

    pub fn view<'a>(&'a self, args: WorkspaceViewArgs<'a>) -> Element<'a, Message> {
        let WorkspaceViewArgs {
            session_root,
            playhead_samples,
            transport_active,
            pixels_per_sample,
            beat_pixels,
            samples_per_bar,
            loop_range_samples,
            punch_range_samples,
            snap_mode,
            samples_per_beat,
            zoom_visible_bars,
            editor_scroll_x,
            mixer_scroll_x,
            window_width,
            window_height,
            editor_scroll_y,
            track_drag_active,
            tracks_resize_hovered,
            mixer_resize_hovered,
            tracks_visible,
            editor_visible,
            mixer_visible,
            active_clip_drag,
            active_clip_target_track,
            active_clip_target_valid,
            active_clip_snap_adjust_samples,
            active_clip_snap_targets,
            recording_preview_bounds,
            recording_preview_peaks,
            midi_clip_previews,
            shift_pressed,
            selected_tempo_points,
            selected_time_signature_points,
            mixer_level_edit_track,
            mixer_level_edit_input,
            sample_rate,
        } = args;
        let (
            tracks_width,
            tracks_width_px,
            max_end_samples,
            tracks_total_height,
            track_heights,
            tempo,
            time_signature,
            tempo_points,
            time_signature_points,
            mixer_height_px,
            markers,
        ) = {
            let state = self.state.blocking_read();
            let max_end_samples = state
                .tracks
                .iter()
                .map(|track| {
                    let audio_max = track
                        .audio
                        .clips
                        .iter()
                        .map(|clip| clip.start.saturating_add(clip.length))
                        .max()
                        .unwrap_or(0);
                    let midi_max = track
                        .midi
                        .clips
                        .iter()
                        .map(|clip| clip.start.saturating_add(clip.length))
                        .max()
                        .unwrap_or(0);
                    audio_max.max(midi_max)
                })
                .max()
                .unwrap_or(0);
            let track_heights = state
                .tracks
                .iter()
                .filter(|track| track.name != METRONOME_TRACK_ID)
                .map(|track| {
                    if track.is_inside_closed_folder(&state.tracks) {
                        0.0
                    } else {
                        track.height
                    }
                })
                .collect::<Vec<_>>();
            let markers = state
                .session_markers
                .iter()
                .map(|m| (m.sample, m.name.clone()))
                .collect::<Vec<_>>();
            (
                state.tracks_width,
                match state.tracks_width {
                    Length::Fixed(width) => width,
                    _ => 200.0,
                },
                max_end_samples,
                track_heights.iter().sum::<f32>().max(1.0),
                track_heights,
                state.tempo,
                (state.time_signature_num, state.time_signature_denom),
                state
                    .tempo_points
                    .iter()
                    .map(|p| (p.sample, p.bpm))
                    .collect::<Vec<_>>(),
                state
                    .time_signature_points
                    .iter()
                    .map(|p| (p.sample, p.numerator, p.denominator))
                    .collect::<Vec<_>>(),
                match state.mixer_height {
                    Length::Fixed(height) => height,
                    _ => 300.0,
                },
                markers,
            )
        };
        const TOP_CHROME_ESTIMATE_PX: f32 = 72.0;
        const MIXER_SPLITTER_HEIGHT_PX: f32 = 3.0;
        let track_viewport_height = (window_height
            - TOP_CHROME_ESTIMATE_PX
            - if mixer_visible {
                mixer_height_px + MIXER_SPLITTER_HEIGHT_PX
            } else {
                0.0
            }
            - self.tempo.height()
            - self.ruler.height())
        .max(160.0);
        let visible_track_window =
            compute_visible_track_window(&track_heights, editor_scroll_y, track_viewport_height);
        let tracks_visible_window = if track_drag_active {
            VisibleTrackWindow {
                start_index: 0,
                end_index: track_heights.len(),
                top_padding: 0.0,
                bottom_padding: 0.0,
            }
        } else {
            visible_track_window
        };
        let min_visible_samples = (samples_per_bar * zoom_visible_bars).max(1.0) as usize;
        let min_timeline_samples = (samples_per_bar * MIN_TIMELINE_BARS).max(1.0) as usize;
        let right_padding_samples = ((samples_per_bar * zoom_visible_bars) * 0.5).max(1.0) as usize;
        let playhead_extent_samples = playhead_samples
            .map(|sample| sample.max(0.0) as usize)
            .unwrap_or(0)
            .saturating_add(right_padding_samples);
        let content_extent_samples = max_end_samples.saturating_add(right_padding_samples);
        let timeline_samples = max_end_samples
            .max(playhead_extent_samples)
            .max(content_extent_samples)
            .max(min_visible_samples)
            .max(min_timeline_samples);
        let editor_content_width = (timeline_samples as f32 * pixels_per_sample).max(1.0);
        let workspace_content_height =
            self.tempo.height() + self.ruler.height() + tracks_total_height;
        let track_context_menu_overlay = {
            let state = self.state.blocking_read();
            tracks::track_context_menu_overlay(&state, track_viewport_height - 36.0)
        };
        let clip_context_menu_overlay = {
            let state = self.state.blocking_read();
            editor::clip_context_menu_overlay(&state, transport_active)
        };
        let playhead_x_timeline = playhead_samples.map(|sample| {
            timeline_sample_to_x_f64(sample, pixels_per_sample, TIMELINE_LEFT_INSET_PX)
        });
        let clip_snap_edges = self.collect_clip_snap_edges();

        let editor_render_hash = self.editor.render_hash(&EditorViewArgs {
            session_root,
            pixels_per_sample,
            samples_per_bar,
            snap_mode,
            samples_per_beat,
            active_clip_drag,
            active_target_track: active_clip_target_track,
            active_target_valid: active_clip_target_valid,
            active_clip_snap_adjust_samples,
            active_clip_snap_targets,
            recording_preview_bounds,
            recording_preview_peaks,
            midi_clip_previews,
            visible_track_window,
        });
        let editor = self.editor.clone();
        let editor_args_owned = OwnedEditorViewArgs {
            session_root: session_root.cloned(),
            pixels_per_sample,
            samples_per_bar,
            snap_mode,
            samples_per_beat,
            active_clip_drag: active_clip_drag.cloned(),
            active_target_track: active_clip_target_track.map(str::to_string),
            active_target_valid: active_clip_target_valid,
            active_clip_snap_adjust_samples,
            active_clip_snap_targets: active_clip_snap_targets.to_vec(),
            recording_preview_bounds,
            recording_preview_peaks: recording_preview_peaks.cloned(),
            midi_clip_previews: midi_clip_previews.cloned(),
            visible_track_window,
        };
        let editor_body: Element<'_, Message> = lazy(editor_render_hash, move |_| {
            editor.clone().into_view_owned(editor_args_owned.clone())
        })
        .into();
        let editor_with_playhead = if let Some(x) = playhead_x_timeline {
            Stack::from_vec(vec![
                editor_body,
                pin(Self::playhead_line())
                    .position(Point::new(x.max(0.0), 0.0))
                    .into(),
            ])
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
        } else {
            editor_body
        };

        let editor_timeline_scrolled = scrollable(
            container(editor_with_playhead)
                .width(Length::Fixed(editor_content_width))
                .height(Length::Fixed(tracks_total_height)),
        )
        .id(Id::new(EDITOR_TIMELINE_SCROLL_ID))
        .direction(scrollable::Direction::Horizontal(
            scrollable::Scrollbar::hidden(),
        ))
        .on_scroll(|viewport| Message::EditorScrollXChanged(viewport.relative_offset().x))
        .width(Length::Fill)
        .height(Length::Fixed(tracks_total_height));

        let right_lanes_scrolled = scrollable(editor_timeline_scrolled)
            .id(Id::new(EDITOR_SCROLL_ID))
            .direction(scrollable::Direction::Vertical(
                scrollable::Scrollbar::hidden(),
            ))
            .on_scroll(|viewport| Message::EditorScrollYChanged(viewport.relative_offset().y))
            .width(Length::Fill)
            .height(Length::Fill);
        let right_lanes_with_scrollbar: Element<'_, Message> = row![
            right_lanes_scrolled,
            VerticalScrollbar::new(
                tracks_total_height,
                editor_scroll_y,
                Message::EditorScrollYChanged,
            )
            .width(Length::Fixed(16.0))
            .height(Length::Fill),
        ]
        .spacing(0)
        .width(Length::Fill)
        .height(Length::Fill)
        .into();

        let h_scroll = HorizontalScrollbar::new(
            editor_content_width,
            editor_scroll_x,
            Message::EditorScrollXChanged,
        )
        .width(Length::Fill)
        .height(Length::Fixed(16.0));

        let editor_with_zoom = right_lanes_with_scrollbar;
        let tracks_scrolled = scrollable(self.tracks.view(tracks_visible_window))
            .id(Id::new(TRACKS_SCROLL_ID))
            .direction(scrollable::Direction::Vertical(
                scrollable::Scrollbar::hidden(),
            ))
            .on_scroll(|viewport| Message::EditorScrollYChanged(viewport.relative_offset().y))
            .width(tracks_width)
            .height(Length::Fill);

        let tempo_scrolled: Element<'_, Message> = scrollable(self.tempo.view(TempoViewArgs {
            bpm: tempo,
            time_signature,
            pixels_per_sample,
            playhead_x: playhead_x_timeline.map(|x| x.max(0.0)),
            punch_range_samples,
            clip_snap_edges: clip_snap_edges.clone(),
            snap_mode,
            samples_per_beat,
            samples_per_bar: samples_per_bar as f64,
            content_width: editor_content_width,
            tempo_points,
            time_signature_points,
            shift_pressed,
            selected_tempo_points,
            selected_time_signature_points,
            timeline_left_inset_px: TIMELINE_LEFT_INSET_PX,
            clip_start_samples: 0,
            sample_rate,
            markers: markers.clone(),
        }))
        .id(Id::new(WORKSPACE_TEMPO_SCROLL_ID))
        .direction(scrollable::Direction::Horizontal(
            scrollable::Scrollbar::hidden(),
        ))
        .on_scroll(|viewport| Message::EditorScrollXChanged(viewport.relative_offset().x))
        .height(Length::Fixed(self.tempo.height()))
        .into();
        let ruler_scrolled: Element<'_, Message> = scrollable(self.ruler.view(RulerViewArgs {
            playhead_x: playhead_x_timeline.map(|x| x.max(0.0)),
            beat_pixels,
            pixels_per_sample,
            loop_range_samples,
            clip_snap_edges: clip_snap_edges.clone(),
            snap_mode,
            samples_per_beat,
            content_width: editor_content_width,
            timeline_left_inset_px: TIMELINE_LEFT_INSET_PX,
            clip_start_samples: 0,
        }))
        .id(Id::new(WORKSPACE_RULER_SCROLL_ID))
        .direction(scrollable::Direction::Horizontal(
            scrollable::Scrollbar::hidden(),
        ))
        .on_scroll(|viewport| Message::EditorScrollXChanged(viewport.relative_offset().x))
        .height(Length::Fixed(self.ruler.height()))
        .into();

        let right_panel = column![
            tempo_scrolled,
            ruler_scrolled,
            container(editor_with_zoom).height(Length::Fixed(tracks_total_height)),
        ]
        .width(Length::Fill);

        let left_panel = column![
            container("")
                .width(tracks_width)
                .height(Length::Fixed(self.tempo.height()))
                .style(|_theme| container::Style {
                    background: Some(Background::Color(Color {
                        r: 0.1,
                        g: 0.1,
                        b: 0.1,
                        a: 1.0,
                    })),
                    ..container::Style::default()
                }),
            container("")
                .width(tracks_width)
                .height(Length::Fixed(self.ruler.height()))
                .style(|_theme| container::Style {
                    background: Some(Background::Color(Color {
                        r: 0.1,
                        g: 0.1,
                        b: 0.1,
                        a: 1.0,
                    })),
                    ..container::Style::default()
                }),
            tracks_scrolled,
        ]
        .width(tracks_width);

        let tracks_splitter = mouse_area(column![
            container("")
                .width(Length::Fixed(3.0))
                .height(Length::Fixed(self.tempo.height()))
                .style(|_theme| container::Style {
                    background: Some(Background::Color(Color {
                        r: 0.5,
                        g: 0.5,
                        b: 0.5,
                        a: 0.5,
                    })),
                    ..container::Style::default()
                }),
            container("")
                .width(Length::Fixed(3.0))
                .height(Length::Fixed(self.ruler.height()))
                .style(|_theme| container::Style {
                    background: Some(Background::Color(Color {
                        r: 0.5,
                        g: 0.5,
                        b: 0.5,
                        a: 0.5,
                    })),
                    ..container::Style::default()
                }),
            container("")
                .width(Length::Fixed(3.0))
                .height(Length::Fill)
                .style(move |_theme| container::Style {
                    background: Some(Background::Color(Color {
                        r: 0.7,
                        g: 0.7,
                        b: 0.7,
                        a: if tracks_resize_hovered { 0.95 } else { 0.6 },
                    })),
                    ..container::Style::default()
                }),
        ])
        .on_enter(Message::TracksResizeHover(true))
        .on_exit(Message::TracksResizeHover(false))
        .on_press(Message::TracksResizeStart);

        let shared_workspace: Element<'_, Message> = match (tracks_visible, editor_visible) {
            (true, true) => row![left_panel, tracks_splitter, right_panel]
                .height(Length::Fixed(workspace_content_height))
                .into(),
            (true, false) => row![left_panel]
                .height(Length::Fixed(workspace_content_height))
                .into(),
            (false, true) => row![right_panel]
                .height(Length::Fixed(workspace_content_height))
                .into(),
            (false, false) => container("")
                .width(Length::Fill)
                .height(Length::Fixed(workspace_content_height))
                .into(),
        };

        let shared_workspace: Element<'_, Message> = {
            let mut stack = Stack::new().push(shared_workspace);
            if let Some((anchor, menu)) = track_context_menu_overlay {
                stack = stack.push(pin(menu).position(Point::new(
                    anchor.x.max(0.0),
                    self.tempo.height() + self.ruler.height() + anchor.y.max(0.0),
                )));
            }
            if let Some((anchor, menu)) = clip_context_menu_overlay {
                stack = stack.push(pin(menu).position(Point::new(
                    tracks_width_px + 3.0 + anchor.x.max(0.0),
                    self.tempo.height() + self.ruler.height() + anchor.y.max(0.0),
                )));
            }
            stack.into()
        };

        let editor_footer: Element<'_, Message> = if editor_visible {
            container(
                row![
                    Space::new().width(Length::Fixed(if tracks_visible {
                        tracks_width_px + 3.0
                    } else {
                        0.0
                    })),
                    container(
                        row![
                            h_scroll,
                            slider(
                                0.0..=1.0,
                                visible_bars_to_zoom_slider(zoom_visible_bars),
                                Message::ZoomSliderChanged,
                            )
                            .step(0.001)
                            .width(Length::Fixed(105.0)),
                        ]
                        .spacing(8),
                    )
                    .width(Length::Fill)
                    .height(Length::Fixed(16.0))
                    .padding([0, 8]),
                ]
                .height(Length::Fill)
                .align_y(iced::alignment::Vertical::Bottom),
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
        } else {
            Space::new().into()
        };

        let workspace_with_footer = Stack::from_vec(vec![
            shared_workspace,
            container(editor_footer)
                .width(Length::Fill)
                .height(Length::Fill)
                .into(),
        ])
        .width(Length::Fill)
        .height(Length::Fill);
        let workspace_body: Element<'_, Message> = if mixer_visible {
            column![
                workspace_with_footer,
                mouse_area(
                    container("")
                        .width(Length::Fill)
                        .height(Length::Fixed(3.0))
                        .style(move |_theme| container::Style {
                            background: Some(Background::Color(Color {
                                r: 0.7,
                                g: 0.7,
                                b: 0.7,
                                a: if mixer_resize_hovered { 0.95 } else { 0.6 },
                            })),
                            ..container::Style::default()
                        }),
                )
                .on_enter(Message::MixerResizeHover(true))
                .on_exit(Message::MixerResizeHover(false))
                .on_press(Message::MixerResizeStart),
                self.mixer.view(
                    mixer_level_edit_track,
                    mixer_level_edit_input,
                    window_width,
                    mixer_scroll_x,
                ),
            ]
            .width(Length::Fill)
            .into()
        } else {
            column![workspace_with_footer].width(Length::Fill).into()
        };
        container(workspace_body)
            .style(|_theme| crate::style::app_background())
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    pub fn piano_view<'a>(&'a self, args: WorkspaceViewArgs<'a>) -> Element<'a, Message> {
        let WorkspaceViewArgs {
            playhead_samples,
            pixels_per_sample,
            beat_pixels,
            samples_per_bar,
            snap_mode,
            samples_per_beat,
            shift_pressed,
            mixer_visible: _,
            selected_tempo_points,
            selected_time_signature_points,
            sample_rate,
            ..
        } = args;

        let (
            tempo,
            time_signature,
            tempo_points,
            time_signature_points,
            clip_start_samples,
            clip_length_samples,
            zoom_x,
            markers,
        ) = {
            let state = self.state.blocking_read();
            let markers = state
                .session_markers
                .iter()
                .map(|m| (m.sample, m.name.clone()))
                .collect::<Vec<_>>();
            (
                state.tempo,
                (state.time_signature_num, state.time_signature_denom),
                state
                    .tempo_points
                    .iter()
                    .map(|p| (p.sample, p.bpm))
                    .collect::<Vec<_>>(),
                state
                    .time_signature_points
                    .iter()
                    .map(|p| (p.sample, p.numerator, p.denominator))
                    .collect::<Vec<_>>(),
                state
                    .piano
                    .as_ref()
                    .map(|roll| roll.clip_start_samples)
                    .unwrap_or(0),
                state
                    .piano
                    .as_ref()
                    .map(|roll| roll.clip_length_samples)
                    .unwrap_or(samples_per_bar.max(1.0) as usize),
                state.piano_zoom_x,
                markers,
            )
        };
        let horizontal_zoom = zoom_x.max(1.0);
        let horizontal_pixels_per_sample = (pixels_per_sample * horizontal_zoom).max(0.0001);
        let horizontal_beat_pixels = (beat_pixels * horizontal_zoom).max(0.0001);
        let timeline_content_width =
            (clip_length_samples.max(1) as f32 * horizontal_pixels_per_sample).max(1.0);
        let playhead_x = playhead_samples.map(|sample| {
            ((sample as f32 - clip_start_samples as f32) * horizontal_pixels_per_sample).max(0.0)
        });

        let piano_content = self
            .midi_edit
            .view(pixels_per_sample, samples_per_bar, playhead_x);

        container(
            column![
                row![
                    container("")
                        .width(Length::Fixed(TOOLS_STRIP_WIDTH + MAIN_SPLIT_SPACING,))
                        .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(KEYBOARD_WIDTH))
                        .height(Length::Fill),
                    scrollable(container(self.tempo.view(TempoViewArgs {
                        bpm: tempo,
                        time_signature,
                        pixels_per_sample: horizontal_pixels_per_sample,
                        playhead_x,
                        punch_range_samples: None,
                        clip_snap_edges: self.collect_clip_snap_edges(),
                        snap_mode,
                        samples_per_beat,
                        samples_per_bar: samples_per_bar as f64,
                        content_width: timeline_content_width,
                        tempo_points,
                        time_signature_points,
                        shift_pressed,
                        selected_tempo_points,
                        selected_time_signature_points,
                        timeline_left_inset_px: 0.0,
                        clip_start_samples: 0,
                        sample_rate,
                        markers,
                    })))
                    .id(Id::new(PIANO_TEMPO_SCROLL_ID))
                    .direction(scrollable::Direction::Horizontal(
                        scrollable::Scrollbar::hidden(),
                    ))
                    .on_scroll(|viewport| Message::PianoScrollXChanged(
                        viewport.relative_offset().x
                    ))
                    .width(Length::Fill)
                    .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(RIGHT_SCROLL_GUTTER_WIDTH))
                        .height(Length::Fill),
                ]
                .width(Length::Fill)
                .height(Length::Fixed(self.tempo.height())),
                row![
                    container("")
                        .width(Length::Fixed(TOOLS_STRIP_WIDTH + MAIN_SPLIT_SPACING,))
                        .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(KEYBOARD_WIDTH))
                        .height(Length::Fill),
                    scrollable(container(self.ruler.view(RulerViewArgs {
                        playhead_x,
                        beat_pixels: horizontal_beat_pixels,
                        pixels_per_sample: horizontal_pixels_per_sample,
                        loop_range_samples: None,
                        clip_snap_edges: self.collect_clip_snap_edges(),
                        snap_mode,
                        samples_per_beat,
                        content_width: timeline_content_width,
                        timeline_left_inset_px: 0.0,
                        clip_start_samples,
                    })))
                    .id(Id::new(PIANO_RULER_SCROLL_ID))
                    .direction(scrollable::Direction::Horizontal(
                        scrollable::Scrollbar::hidden(),
                    ))
                    .on_scroll(|viewport| Message::PianoScrollXChanged(
                        viewport.relative_offset().x
                    ))
                    .width(Length::Fill)
                    .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(RIGHT_SCROLL_GUTTER_WIDTH))
                        .height(Length::Fill),
                ]
                .width(Length::Fill)
                .height(Length::Fixed(self.ruler.height())),
                piano_content,
            ]
            .width(Length::Fill)
            .height(Length::Fill),
        )
        .style(|_theme| crate::style::app_background())
        .width(Length::Fill)
        .height(Length::Fill)
        .into()
    }

    pub fn pitch_correction_view<'a>(
        &'a self,
        args: WorkspaceViewArgs<'a>,
    ) -> Element<'a, Message> {
        let WorkspaceViewArgs {
            playhead_samples,
            pixels_per_sample,
            beat_pixels,
            samples_per_bar,
            snap_mode,
            samples_per_beat,
            shift_pressed,
            selected_tempo_points,
            selected_time_signature_points,
            sample_rate,
            ..
        } = args;
        let (
            clip_length_samples,
            zoom_x,
            tempo,
            time_signature,
            tempo_points,
            time_signature_points,
            markers,
        ) = {
            let state = self.state.blocking_read();
            let markers = state
                .session_markers
                .iter()
                .map(|m| (m.sample, m.name.clone()))
                .collect::<Vec<_>>();
            (
                state
                    .pitch_correction
                    .as_ref()
                    .map(|roll| roll.clip_length_samples)
                    .unwrap_or(samples_per_bar.max(1.0) as usize),
                state.piano_zoom_x,
                state.tempo,
                (state.time_signature_num, state.time_signature_denom),
                state
                    .tempo_points
                    .iter()
                    .map(|p| (p.sample, p.bpm))
                    .collect::<Vec<_>>(),
                state
                    .time_signature_points
                    .iter()
                    .map(|p| (p.sample, p.numerator, p.denominator))
                    .collect::<Vec<_>>(),
                markers,
            )
        };
        let horizontal_zoom = zoom_x.max(1.0);
        let horizontal_pixels_per_sample = (pixels_per_sample * horizontal_zoom).max(0.0001);
        let horizontal_beat_pixels = (beat_pixels * horizontal_zoom).max(0.0001);
        let timeline_content_width =
            (clip_length_samples.max(1) as f32 * horizontal_pixels_per_sample).max(1.0);
        let playhead_x =
            playhead_samples.map(|sample| (sample as f32 * horizontal_pixels_per_sample).max(0.0));
        let pitch_correction_content =
            self.pitch_correction
                .view(pixels_per_sample, samples_per_bar, playhead_x);

        container(
            column![
                row![
                    container("")
                        .width(Length::Fixed(TOOLS_STRIP_WIDTH + MAIN_SPLIT_SPACING,))
                        .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(KEYBOARD_WIDTH))
                        .height(Length::Fill),
                    scrollable(container(self.tempo.view(TempoViewArgs {
                        bpm: tempo,
                        time_signature,
                        pixels_per_sample: horizontal_pixels_per_sample,
                        playhead_x,
                        punch_range_samples: None,
                        clip_snap_edges: self.collect_clip_snap_edges(),
                        snap_mode,
                        samples_per_beat,
                        samples_per_bar: samples_per_bar as f64,
                        content_width: timeline_content_width,
                        tempo_points,
                        time_signature_points,
                        shift_pressed,
                        selected_tempo_points,
                        selected_time_signature_points,
                        timeline_left_inset_px: 0.0,
                        clip_start_samples: 0,
                        sample_rate,
                        markers,
                    })))
                    .id(Id::new(PIANO_TEMPO_SCROLL_ID))
                    .direction(scrollable::Direction::Horizontal(
                        scrollable::Scrollbar::hidden(),
                    ))
                    .on_scroll(|viewport| Message::PianoScrollXChanged(
                        viewport.relative_offset().x
                    ))
                    .width(Length::Fill)
                    .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(RIGHT_SCROLL_GUTTER_WIDTH))
                        .height(Length::Fill),
                ]
                .width(Length::Fill)
                .height(Length::Fixed(self.tempo.height())),
                row![
                    container("")
                        .width(Length::Fixed(TOOLS_STRIP_WIDTH + MAIN_SPLIT_SPACING,))
                        .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(KEYBOARD_WIDTH))
                        .height(Length::Fill),
                    scrollable(container(self.ruler.view(RulerViewArgs {
                        playhead_x,
                        beat_pixels: horizontal_beat_pixels,
                        pixels_per_sample: horizontal_pixels_per_sample,
                        loop_range_samples: None,
                        clip_snap_edges: self.collect_clip_snap_edges(),
                        snap_mode,
                        samples_per_beat,
                        content_width: timeline_content_width,
                        timeline_left_inset_px: 0.0,
                        clip_start_samples: 0,
                    })))
                    .id(Id::new(PIANO_RULER_SCROLL_ID))
                    .direction(scrollable::Direction::Horizontal(
                        scrollable::Scrollbar::hidden(),
                    ))
                    .on_scroll(|viewport| Message::PianoScrollXChanged(
                        viewport.relative_offset().x
                    ))
                    .width(Length::Fill)
                    .height(Length::Fill),
                    container("")
                        .width(Length::Fixed(RIGHT_SCROLL_GUTTER_WIDTH))
                        .height(Length::Fill),
                ]
                .width(Length::Fill)
                .height(Length::Fixed(self.ruler.height())),
                pitch_correction_content,
            ]
            .width(Length::Fill)
            .height(Length::Fill),
        )
        .style(|_theme| crate::style::app_background())
        .width(Length::Fill)
        .height(Length::Fill)
        .into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tokio::sync::RwLock;

    #[test]
    fn update_is_a_no_op() {
        let state = Arc::new(RwLock::new(crate::state::StateData::default()));
        let mut workspace = Workspace::new(state);

        workspace.update(&Message::Cancel);
    }

    #[test]
    fn timeline_sample_to_x_f64_calculates_correctly() {
        let x = timeline_sample_to_x_f64(100.0, 0.5, 10.0);
        assert!((x - 60.0).abs() < 0.01);
    }

    #[test]
    fn timeline_sample_to_x_calculates_correctly() {
        let x = timeline_sample_to_x(100, 0.5, 10.0);
        assert!((x - 60.0).abs() < 0.01);
    }

    #[test]
    fn timeline_x_to_sample_f32_calculates_correctly() {
        let sample = timeline_x_to_sample_f32(60.0, 0.5, 10.0);
        assert!((sample - 100.0).abs() < 0.01);
    }

    #[test]
    fn timeline_x_to_sample_f32_handles_zero_pixels_per_sample() {
        let sample = timeline_x_to_sample_f32(100.0, 0.0, 10.0);
        assert_eq!(sample, 0.0);
    }

    #[test]
    fn clip_kind_key_returns_expected_values() {
        assert_eq!(clip_kind_key(maolan_engine::kind::Kind::Audio), 0);
        assert_eq!(clip_kind_key(maolan_engine::kind::Kind::MIDI), 1);
    }

    #[test]
    fn clip_snap_edge_creation() {
        let edge = ClipSnapEdge {
            clip_id: crate::state::ClipId {
                track_idx: "track1".to_string(),
                clip_idx: 0,
                kind: maolan_engine::kind::Kind::Audio,
            },
            sample: 100,
        };
        assert_eq!(edge.sample, 100);
    }

    #[test]
    fn visible_track_window_creation() {
        let window = VisibleTrackWindow {
            start_index: 0,
            end_index: 5,
            top_padding: 10.0,
            bottom_padding: 20.0,
        };
        assert_eq!(window.start_index, 0);
        assert_eq!(window.end_index, 5);
        assert!((window.top_padding - 10.0).abs() < f32::EPSILON);
    }

    #[test]
    fn compute_visible_track_window_empty() {
        let window = compute_visible_track_window(&[], 0.0, 100.0);
        assert_eq!(window.start_index, 0);
        assert_eq!(window.end_index, 0);
    }

    #[test]
    fn workspace_new_creates_instance() {
        let state = Arc::new(RwLock::new(crate::state::StateData::default()));
        let workspace = Workspace::new(state);
        let _ = &workspace;
    }
}