Add count-in

This commit is contained in:
Skyler Lehmkuhl
2026-03-20 20:51:50 -04:00
parent c938ea44b0
commit 121fa3a50a
8 changed files with 189 additions and 38 deletions
@@ -339,6 +339,7 @@ impl From<MenuAction> for AppAction {
MenuAction::AddShapeTween => Self::AddShapeTween,
MenuAction::ReturnToStart => Self::ReturnToStart,
MenuAction::Play => Self::Play,
MenuAction::ToggleCountIn => Self::Play, // not directly mappable to AppAction
MenuAction::ZoomIn => Self::ZoomIn,
MenuAction::ZoomOut => Self::ZoomOut,
MenuAction::ActualSize => Self::ActualSize,
@@ -856,6 +856,7 @@ struct EditorApp {
armed_layers: HashSet<Uuid>,
is_recording: bool, // Whether recording is currently active
metronome_enabled: bool, // Whether metronome clicks during recording
count_in_enabled: bool, // Whether count-in fires before recording
recording_clips: HashMap<Uuid, u32>, // layer_id -> backend clip_id during recording
recording_start_time: f64, // Playback time when recording started
recording_layer_ids: Vec<Uuid>, // Layers being recorded to (for creating clips)
@@ -1128,6 +1129,7 @@ impl EditorApp {
armed_layers: HashSet::new(), // No layers explicitly armed
is_recording: false, // Not recording initially
metronome_enabled: false, // Metronome off by default
count_in_enabled: false, // Count-in off by default
recording_clips: HashMap::new(), // No active recording clips
recording_start_time: 0.0, // Will be set when recording starts
recording_layer_ids: Vec::new(), // Will be populated when recording starts
@@ -3577,6 +3579,12 @@ impl EditorApp {
println!("Menu: Play");
// TODO: Implement play/pause
}
MenuAction::ToggleCountIn => {
// Only effective when metronome is enabled (count-in requires a click track)
if self.metronome_enabled {
self.count_in_enabled = !self.count_in_enabled;
}
}
// View menu
MenuAction::ZoomIn => {
@@ -5632,9 +5640,28 @@ impl eframe::App for EditorApp {
if let Some(menu_system) = &self.menu_system {
let recent_files = self.config.get_recent_files();
let layout_names: Vec<String> = self.layouts.iter().map(|l| l.name.clone()).collect();
// Determine timeline measures mode for conditional menu items
let timeline_is_measures = self.pane_instances.values().any(|p| {
if let panes::PaneInstance::Timeline(t) = p { t.is_measures_mode() } else { false }
});
// Checked actions show "✔ Label"; hidden actions are not rendered at all
let checked: &[crate::menu::MenuAction] = if self.count_in_enabled && self.metronome_enabled {
&[crate::menu::MenuAction::ToggleCountIn]
} else {
&[]
};
let hidden: &[crate::menu::MenuAction] = if timeline_is_measures && self.metronome_enabled {
&[]
} else {
&[crate::menu::MenuAction::ToggleCountIn]
};
if let Some(action) = menu_system.render_egui_menu_bar(
ui, &recent_files, Some(&self.keymap),
&layout_names, self.current_layout_index,
checked, hidden,
) {
self.handle_menu_action(action);
}
@@ -5774,6 +5801,7 @@ impl eframe::App for EditorApp {
is_playing: &mut self.is_playing,
is_recording: &mut self.is_recording,
metronome_enabled: &mut self.metronome_enabled,
count_in_enabled: &mut self.count_in_enabled,
recording_clips: &mut self.recording_clips,
recording_start_time: &mut self.recording_start_time,
recording_layer_ids: &mut self.recording_layer_ids,
@@ -324,6 +324,7 @@ pub enum MenuAction {
AddShapeTween,
ReturnToStart,
Play,
ToggleCountIn,
// View menu
ZoomIn,
@@ -422,6 +423,7 @@ impl MenuItemDef {
const ADD_SHAPE_TWEEN: Self = Self { label: "Add Shape Tween", action: MenuAction::AddShapeTween, shortcut: None };
const RETURN_TO_START: Self = Self { label: "Return to start", action: MenuAction::ReturnToStart, shortcut: None };
const PLAY: Self = Self { label: "Play", action: MenuAction::Play, shortcut: None };
const COUNT_IN: Self = Self { label: "Count In", action: MenuAction::ToggleCountIn, shortcut: None };
// View menu items
const ZOOM_IN: Self = Self { label: "Zoom In", action: MenuAction::ZoomIn, shortcut: Some(Shortcut::new(ShortcutKey::Equals, CTRL, NO_SHIFT, NO_ALT)) };
@@ -548,6 +550,8 @@ impl MenuItemDef {
MenuDef::Separator,
MenuDef::Item(&Self::RETURN_TO_START),
MenuDef::Item(&Self::PLAY),
MenuDef::Separator,
MenuDef::Item(&Self::COUNT_IN),
],
},
// View menu
@@ -805,6 +809,8 @@ impl MenuSystem {
keymap: Option<&crate::keymap::KeymapManager>,
layout_names: &[String],
current_layout_index: usize,
checked_actions: &[MenuAction],
hidden_actions: &[MenuAction],
) -> Option<MenuAction> {
let mut action = None;
let ctx = ui.ctx().clone();
@@ -819,7 +825,7 @@ impl MenuSystem {
let response = ui.button(*label);
let popup_id = egui::Popup::default_response_id(&response);
button_entries.push((response, popup_id, menu_def));
} else if let Some(a) = self.render_menu_def(ui, menu_def, recent_files, keymap, layout_names, current_layout_index) {
} else if let Some(a) = self.render_menu_def(ui, menu_def, recent_files, keymap, layout_names, current_layout_index, checked_actions, hidden_actions) {
action = Some(a);
}
}
@@ -847,7 +853,7 @@ impl MenuSystem {
ui.set_width(min_width);
let mut a = None;
for child in *children {
if let Some(result) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index) {
if let Some(result) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index, checked_actions, hidden_actions) {
a = Some(result);
ui.close();
}
@@ -875,10 +881,15 @@ impl MenuSystem {
keymap: Option<&crate::keymap::KeymapManager>,
layout_names: &[String],
current_layout_index: usize,
checked_actions: &[MenuAction],
hidden_actions: &[MenuAction],
) -> Option<MenuAction> {
match def {
MenuDef::Item(item_def) => {
if Self::render_menu_item(ui, item_def, keymap) {
if hidden_actions.contains(&item_def.action) {
return None;
}
if Self::render_menu_item(ui, item_def, keymap, checked_actions) {
Some(item_def.action)
} else {
None
@@ -914,7 +925,7 @@ impl MenuSystem {
} else if *label == "Layout" {
let mut action = None;
for child in *children {
if let Some(a) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index) {
if let Some(a) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index, checked_actions, hidden_actions) {
action = Some(a);
ui.close();
}
@@ -937,7 +948,7 @@ impl MenuSystem {
} else {
let mut action = None;
for child in *children {
if let Some(a) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index) {
if let Some(a) = self.render_menu_def(ui, child, recent_files, keymap, layout_names, current_layout_index, checked_actions, hidden_actions) {
action = Some(a);
ui.close();
}
@@ -951,7 +962,7 @@ impl MenuSystem {
}
/// Render a single menu item with label and shortcut
fn render_menu_item(ui: &mut egui::Ui, def: &MenuItemDef, keymap: Option<&crate::keymap::KeymapManager>) -> bool {
fn render_menu_item(ui: &mut egui::Ui, def: &MenuItemDef, keymap: Option<&crate::keymap::KeymapManager>, checked_actions: &[MenuAction]) -> bool {
// Look up shortcut from keymap if available, otherwise use static default
let effective_shortcut = if let Some(km) = keymap {
if let Ok(app_action) = crate::keymap::AppAction::try_from(def.action) {
@@ -987,10 +998,15 @@ impl MenuSystem {
ui.visuals().widgets.inactive.text_color()
};
let label_pos = rect.min + egui::vec2(4.0, (rect.height() - 14.0) / 2.0);
let label = if checked_actions.contains(&def.action) {
format!("✔ {}", def.label)
} else {
def.label.to_owned()
};
ui.painter().text(
label_pos,
egui::Align2::LEFT_TOP,
def.label,
label,
egui::FontId::proportional(14.0),
text_color,
);
@@ -213,6 +213,7 @@ pub struct SharedPaneState<'a> {
/// Recording state
pub is_recording: &'a mut bool, // Whether recording is currently active
pub metronome_enabled: &'a mut bool, // Whether metronome clicks during recording
pub count_in_enabled: &'a mut bool, // Whether count-in fires before recording
pub recording_clips: &'a mut std::collections::HashMap<uuid::Uuid, u32>, // layer_id -> clip_id
pub recording_start_time: &'a mut f64, // Playback time when recording started
pub recording_layer_ids: &'a mut Vec<uuid::Uuid>, // Layers being recorded to
@@ -223,6 +223,16 @@ pub struct TimelinePane {
automation_topology_generation: u64,
/// Cached metronome icon texture (loaded on first use)
metronome_icon: Option<egui::TextureHandle>,
/// Count-in pre-roll state: set when count-in is active, cleared when recording fires
pending_recording_start: Option<PendingRecordingStart>,
}
/// Deferred recording start created during count-in pre-roll
struct PendingRecordingStart {
/// Original playhead position — where clips will be placed in the timeline
original_playhead: f64,
/// Transport time at which to fire the actual recording commands
trigger_time: f64,
}
/// Check if a clip type can be dropped on a layer type
@@ -675,9 +685,15 @@ impl TimelinePane {
automation_cache_generation: u64::MAX,
automation_topology_generation: u64::MAX,
metronome_icon: None,
pending_recording_start: None,
}
}
/// Returns true if the timeline is currently in Measures display mode.
pub fn is_measures_mode(&self) -> bool {
self.time_display_format == TimeDisplayFormat::Measures
}
/// Execute a view action with the given parameters
/// Called from main.rs after determining this is the best handler
#[allow(dead_code)] // Mirrors StagePane; wiring in main.rs pending (see TODO at view action dispatch)
@@ -910,6 +926,37 @@ impl TimelinePane {
});
let start_time = *shared.playback_time;
// Count-in: seek back N beats, start transport + metronome, defer ALL recording commands.
// Must happen before Step 4 so no clips or backend recordings are created yet.
if *shared.count_in_enabled
&& *shared.metronome_enabled
&& self.time_display_format == TimeDisplayFormat::Measures
{
let (bpm, beats_per_measure) = {
let doc = shared.action_executor.document();
(doc.bpm, doc.time_signature.numerator as f64)
};
let count_in_duration = beats_per_measure * (60.0 / bpm);
let seek_to = start_time - count_in_duration; // may be negative
if let Some(controller_arc) = shared.audio_controller {
let mut controller = controller_arc.lock().unwrap();
controller.seek(seek_to);
controller.set_metronome_enabled(true);
if !*shared.is_playing {
controller.play();
*shared.is_playing = true;
}
}
self.pending_recording_start = Some(PendingRecordingStart {
original_playhead: start_time,
trigger_time: start_time,
});
return; // Recording commands are deferred — check_pending_recording_start fires them
}
shared.recording_layer_ids.clear();
// Step 4: Dispatch recording for each candidate
@@ -986,8 +1033,8 @@ impl TimelinePane {
return;
}
// Auto-start playback if needed, and enable metronome if requested.
// Metronome must be enabled BEFORE play() so beat 0 is not missed.
// No count-in (or deferred re-call from check_pending_recording_start):
// Start immediately. Metronome must be enabled BEFORE play() so beat 0 is not missed.
if let Some(controller_arc) = shared.audio_controller {
let mut controller = controller_arc.lock().unwrap();
if *shared.metronome_enabled {
@@ -1005,7 +1052,31 @@ impl TimelinePane {
}
/// Stop all active recordings
/// Called every frame; fires deferred recording commands once the count-in pre-roll ends.
fn check_pending_recording_start(&mut self, shared: &mut SharedPaneState) {
let Some(ref pending) = self.pending_recording_start else { return };
if !*shared.is_playing || *shared.playback_time < pending.trigger_time {
return;
}
let original_playhead = pending.original_playhead;
self.pending_recording_start = None;
// Re-run start_recording with playback_time temporarily set to the original playhead
// so it captures the correct start_time and places clips at the right position.
// Disable count_in_enabled so start_recording takes the immediate path (no re-seek).
let saved_time = *shared.playback_time;
let saved_count_in = *shared.count_in_enabled;
*shared.playback_time = original_playhead;
*shared.count_in_enabled = false;
self.start_recording(shared);
*shared.playback_time = saved_time;
*shared.count_in_enabled = saved_count_in;
}
fn stop_recording(&mut self, shared: &mut SharedPaneState) {
// Cancel any in-progress count-in
self.pending_recording_start = None;
let stop_wall = std::time::Instant::now();
eprintln!("[STOP] stop_recording called at {:?}", stop_wall);
@@ -4652,6 +4723,9 @@ impl TimelinePane {
impl PaneRenderer for TimelinePane {
fn render_header(&mut self, ui: &mut egui::Ui, shared: &mut SharedPaneState) -> bool {
// Fire deferred recording commands once count-in pre-roll has elapsed
self.check_pending_recording_start(shared);
ui.spacing_mut().item_spacing.x = 2.0; // Small spacing between button groups
// Main playback controls group
@@ -4804,6 +4878,7 @@ impl PaneRenderer for TimelinePane {
}
}
}
}
});
});