2 Commits

Author SHA1 Message Date
59f9f548c1 Add playlist bounds validation and search mode visual indicator
All checks were successful
Build and Release / build-and-release (push) Successful in 1m1s
- Add bounds checking to prevent accessing invalid playlist indices
- Yellow/orange selection bar when in search mode
- Validate playlist index after navigation operations
- Handle empty playlists gracefully
2025-12-07 16:02:44 +01:00
248c5701fb Refactor mouse and keyboard handlers with shared actions
All checks were successful
Build and Release / build-and-release (push) Successful in 1m24s
- Extract common action functions to eliminate code duplication
- Mouse left-click toggles folder open/close
- Mouse right-click plays selection (identical to Enter key)
- Add confirmation popup for library refresh operation
- Improve popup visibility with Clear widget
2025-12-07 13:56:52 +01:00
5 changed files with 335 additions and 131 deletions

View File

@@ -1,6 +1,6 @@
[package]
name = "cm-player"
version = "0.1.10"
version = "0.1.12"
edition = "2021"
[dependencies]

View File

@@ -7,7 +7,7 @@ mod ui;
use anyhow::{Context, Result};
use crossterm::{
event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind, EnableMouseCapture, DisableMouseCapture},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
@@ -56,7 +56,7 @@ async fn main() -> Result<()> {
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
@@ -67,13 +67,83 @@ async fn main() -> Result<()> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
// Common action functions that both keyboard and mouse handlers can call
fn action_toggle_folder(state: &mut AppState) {
if let Some(item) = state.get_selected_item() {
if item.node.is_dir {
let path = item.node.path.clone();
if state.expanded_dirs.contains(&path) {
// Folder is open, close it
state.collapse_selected();
} else {
// Folder is closed, open it
state.expand_selected();
}
}
}
}
fn action_play_selection(state: &mut AppState, player: &mut player::Player) -> Result<()> {
state.play_selection();
if let Some(ref path) = state.current_file {
player.play(path)?;
state.player_state = PlayerState::Playing;
player.update_metadata();
tracing::info!("Playing: {:?} (playlist: {} tracks)", path, state.playlist.len());
}
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
Ok(())
}
fn action_toggle_play_pause(state: &mut AppState, player: &mut player::Player) -> Result<()> {
match state.player_state {
PlayerState::Playing => {
player.pause()?;
state.player_state = PlayerState::Paused;
tracing::info!("Paused");
}
PlayerState::Paused => {
player.resume()?;
state.player_state = PlayerState::Playing;
tracing::info!("Resumed");
}
PlayerState::Stopped => {
// Restart playback from current playlist position
if !state.playlist.is_empty() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
state.player_state = PlayerState::Playing;
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata();
tracing::info!("Restarting playback: {:?}", path);
}
}
}
}
Ok(())
}
fn action_stop(state: &mut AppState, player: &mut player::Player) -> Result<()> {
player.stop()?;
state.player_state = PlayerState::Stopped;
state.current_position = 0.0;
state.current_duration = 0.0;
tracing::info!("Stopped");
Ok(())
}
async fn run_app<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
state: &mut AppState,
@@ -82,6 +152,8 @@ async fn run_app<B: ratatui::backend::Backend>(
let mut metadata_update_counter = 0u32;
let mut last_position = 0.0f64;
let mut needs_redraw = true;
let mut title_bar_area = ratatui::layout::Rect::default();
let mut file_panel_area = ratatui::layout::Rect::default();
loop {
let mut state_changed = false;
@@ -142,7 +214,11 @@ async fn run_app<B: ratatui::backend::Backend>(
// Only redraw if something changed or forced
if needs_redraw || state_changed {
terminal.draw(|f| ui::render(f, state, player))?;
terminal.draw(|f| {
let areas = ui::render(f, state, player);
title_bar_area = areas.0;
file_panel_area = areas.1;
})?;
needs_redraw = false;
}
@@ -154,12 +230,19 @@ async fn run_app<B: ratatui::backend::Backend>(
};
if event::poll(poll_duration)? {
if let Event::Key(key) = event::read()? {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key).await?;
needs_redraw = true; // Force redraw after key event
}
}
Event::Mouse(mouse) => {
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, player)?;
needs_redraw = true; // Force redraw after mouse event
}
_ => {}
}
}
if state.should_quit {
@@ -171,6 +254,30 @@ async fn run_app<B: ratatui::backend::Backend>(
}
async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, state: &mut AppState, player: &mut player::Player, key: KeyEvent) -> Result<()> {
// Handle confirmation popup
if state.show_refresh_confirm {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
state.show_refresh_confirm = false;
state.is_refreshing = true;
terminal.draw(|f| { let _ = ui::render(f, state, player); })?; // Show "Refreshing library..." immediately
tracing::info!("Rescanning...");
let cache_dir = cache::get_cache_dir()?;
let new_cache = scanner::scan_paths(&state.config.scan_paths.paths)?;
new_cache.save(&cache_dir)?;
state.cache = new_cache;
state.refresh_flattened_items();
state.is_refreshing = false;
tracing::info!("Rescan complete");
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
state.show_refresh_confirm = false;
}
_ => {}
}
return Ok(());
}
// Handle search mode separately
if state.search_mode {
match key.code {
@@ -232,6 +339,8 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
// Next track
if !state.playlist.is_empty() && state.playlist_index + 1 < state.playlist.len() {
state.playlist_index += 1;
// Validate index before accessing playlist
if state.playlist_index < state.playlist.len() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
match state.player_state {
@@ -259,10 +368,13 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
}
}
}
}
(KeyCode::Char('K'), KeyModifiers::SHIFT) => {
// Previous track
if !state.playlist.is_empty() && state.playlist_index > 0 {
state.playlist_index -= 1;
// Validate index before accessing playlist
if state.playlist_index < state.playlist.len() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
match state.player_state {
@@ -290,6 +402,7 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
}
}
}
}
(KeyCode::Char('d'), KeyModifiers::CONTROL) => {
state.page_down();
}
@@ -322,50 +435,13 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
state.clear_playlist();
}
(KeyCode::Enter, _) => {
state.play_selection();
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata(); // Update metadata immediately when playing new file
tracing::info!("Playing: {:?} (playlist: {} tracks)", path, state.playlist.len());
}
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
action_play_selection(state, player)?;
}
(KeyCode::Char('s'), _) => {
// s: Stop playback
player.stop()?;
state.player_state = PlayerState::Stopped;
state.current_position = 0.0;
state.current_duration = 0.0;
tracing::info!("Stopped");
action_stop(state, player)?;
}
(KeyCode::Char(' '), _) => {
match state.player_state {
PlayerState::Playing => {
player.pause()?;
state.player_state = PlayerState::Paused;
tracing::info!("Paused");
}
PlayerState::Paused => {
player.resume()?;
state.player_state = PlayerState::Playing;
tracing::info!("Resumed");
}
PlayerState::Stopped => {
// Restart playback from current playlist position
if !state.playlist.is_empty() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
state.player_state = PlayerState::Playing;
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata(); // Update metadata immediately
tracing::info!("Restarting playback: {:?}", path);
}
}
}
}
action_toggle_play_pause(state, player)?;
}
(KeyCode::Char('H'), KeyModifiers::SHIFT) => {
if state.player_state != PlayerState::Stopped {
@@ -392,19 +468,79 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
tracing::info!("Volume: {}%", new_volume);
}
(KeyCode::Char('r'), _) => {
state.is_refreshing = true;
terminal.draw(|f| ui::render(f, state, player))?; // Show "Refreshing library..." immediately
tracing::info!("Rescanning...");
let cache_dir = cache::get_cache_dir()?;
let new_cache = scanner::scan_paths(&state.config.scan_paths.paths)?;
new_cache.save(&cache_dir)?;
state.cache = new_cache;
state.refresh_flattened_items();
state.is_refreshing = false;
tracing::info!("Rescan complete");
state.show_refresh_confirm = true;
}
_ => {}
}
Ok(())
}
fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: ratatui::layout::Rect, file_panel_area: ratatui::layout::Rect, player: &mut player::Player) -> Result<()> {
use crossterm::event::MouseButton;
match mouse.kind {
MouseEventKind::ScrollDown => {
// Scroll down - move selection down
state.move_selection_down();
}
MouseEventKind::ScrollUp => {
// Scroll up - move selection up
state.move_selection_up();
}
MouseEventKind::Down(button) => {
let x = mouse.column;
let y = mouse.row;
// Check if click is on title bar
if x >= title_bar_area.x
&& x < title_bar_area.x + title_bar_area.width
&& y >= title_bar_area.y
&& y < title_bar_area.y + title_bar_area.height
{
match button {
MouseButton::Left => {
// Left click on title bar = play/pause toggle
action_toggle_play_pause(state, player)?;
}
MouseButton::Right => {
// Right click on title bar = stop
action_stop(state, player)?;
}
_ => {}
}
}
// Check if click is within file panel area
else if x >= file_panel_area.x
&& x < file_panel_area.x + file_panel_area.width
&& y >= file_panel_area.y
&& y < file_panel_area.y + file_panel_area.height
{
// Calculate which item was clicked (accounting for borders and scroll offset)
// Border takes 1 line at top, so subtract 1 from y position
let relative_y = (y - file_panel_area.y).saturating_sub(1);
let clicked_index = state.scroll_offset + relative_y as usize;
// Set selection to clicked item if valid
if clicked_index < state.flattened_items.len() {
state.selected_index = clicked_index;
// Handle different mouse buttons
match button {
MouseButton::Left => {
// Left click = toggle folder open/close
action_toggle_folder(state);
}
MouseButton::Right => {
// Right click = play (like Enter key)
action_play_selection(state, player)?;
}
_ => {}
}
}
}
}
_ => {}
}
Ok(())
}

View File

@@ -36,6 +36,7 @@ pub struct AppState {
pub visual_mode: bool,
pub visual_anchor: usize,
pub saved_expanded_dirs: HashSet<PathBuf>,
pub show_refresh_confirm: bool,
}
#[derive(Debug, Clone)]
@@ -77,6 +78,7 @@ impl AppState {
visual_mode: false,
visual_anchor: 0,
saved_expanded_dirs: HashSet::new(),
show_refresh_confirm: false,
}
}
@@ -269,6 +271,10 @@ impl AppState {
if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone());
self.player_state = PlayerState::Playing;
} else {
// Empty playlist
self.current_file = None;
self.player_state = PlayerState::Stopped;
}
} else if let Some(item) = self.get_selected_item() {
let node = item.node.clone();
@@ -279,6 +285,10 @@ impl AppState {
if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone());
self.player_state = PlayerState::Playing;
} else {
// Empty directory
self.current_file = None;
self.player_state = PlayerState::Stopped;
}
} else {
// Play single file
@@ -294,10 +304,13 @@ impl AppState {
pub fn play_next(&mut self) {
if self.playlist_index + 1 < self.playlist.len() {
self.playlist_index += 1;
// Double-check index is valid before accessing
if self.playlist_index < self.playlist.len() {
self.current_file = Some(self.playlist[self.playlist_index].clone());
self.player_state = PlayerState::Playing;
}
}
}
pub fn refresh_flattened_items(&mut self) {
// Keep current expanded state after rescan

View File

@@ -6,12 +6,12 @@ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Clear},
Frame,
};
use theme::Theme;
pub fn render(frame: &mut Frame, state: &mut AppState, player: &Player) {
pub fn render(frame: &mut Frame, state: &mut AppState, player: &Player) -> (Rect, Rect) {
// Clear background
frame.render_widget(
Block::default().style(Theme::secondary()),
@@ -38,9 +38,17 @@ pub fn render(frame: &mut Frame, state: &mut AppState, player: &Player) {
render_file_panel(frame, state, content_chunks[0]);
render_right_panel(frame, state, content_chunks[1]);
render_status_bar(frame, state, player, main_chunks[2]);
// Show confirmation popup if needed
if state.show_refresh_confirm {
render_confirm_popup(frame, "Refresh library?", "This may take a while");
}
// Return title bar area and file panel area for mouse event handling
(main_chunks[0], content_chunks[0])
}
fn highlight_search_matches<'a>(text: &str, query: &str, search_typing: bool, is_selected: bool) -> Vec<Span<'a>> {
fn highlight_search_matches<'a>(text: &str, query: &str, is_selected: bool) -> Vec<Span<'a>> {
let query_lower = query.to_lowercase();
let mut spans = Vec::new();
@@ -58,17 +66,9 @@ fn highlight_search_matches<'a>(text: &str, query: &str, search_typing: bool, is
spans.push(Span::raw(current_segment.clone()));
current_segment.clear();
}
// Add matched character with styling based on mode
if search_typing && is_selected {
// While typing on selected row: green bg with black fg (inverted)
spans.push(Span::styled(
ch.to_string(),
Style::default()
.fg(Theme::background())
.bg(Theme::success()),
));
} else if !search_typing && is_selected {
// After Enter on selected row: bold black text on blue selection bar
// Add matched character with styling
if is_selected {
// On selected row: bold black text on selection bar (yellow or blue)
spans.push(Span::styled(
ch.to_string(),
Style::default()
@@ -108,7 +108,6 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
state.update_scroll_offset(visible_height);
let in_search = state.search_mode || !state.search_matches.is_empty();
let search_typing = state.search_mode; // True when actively typing search
let search_query = if in_search { state.search_query.to_lowercase() } else { String::new() };
let items: Vec<ListItem> = state
@@ -125,7 +124,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
// Add folder icon for directories
let icon = if item.node.is_dir {
// Bold black icon on selection bar, blue otherwise
if !search_typing && is_selected {
if is_selected {
Span::styled("", Style::default().fg(Theme::background()).add_modifier(Modifier::BOLD))
} else {
Span::styled("", Style::default().fg(Theme::highlight()))
@@ -134,23 +133,20 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
Span::raw(" ")
};
let name_spans = if in_search && !search_query.is_empty() {
highlight_search_matches(&item.node.name, &search_query, search_typing, is_selected)
highlight_search_matches(&item.node.name, &search_query, is_selected)
} else {
vec![Span::raw(&item.node.name)]
};
let suffix = if item.node.is_dir { "/" } else { "" };
let base_style = if search_typing {
// While typing search: no selection bar, just normal colors
if state.marked_files.contains(&item.node.path) {
Theme::marked()
let base_style = if is_selected {
// Selection bar: yellow/orange when in search (typing or viewing results), blue otherwise
if in_search {
Theme::search_selected()
} else {
Theme::secondary()
}
} else if is_selected {
// After pressing Enter or normal mode: normal blue selection bar
Theme::selected()
}
} else if state.marked_files.contains(&item.node.path) {
Theme::marked()
} else {
@@ -181,11 +177,8 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
);
let mut list_state = ListState::default();
// Don't show selection bar widget while typing search - we use inverted colors instead
// Show it in normal mode and after executing search (Enter)
if !search_typing {
// Always show selection bar (yellow/orange in search mode, blue otherwise)
list_state.select(Some(state.selected_index));
}
*list_state.offset_mut() = state.scroll_offset;
frame.render_stateful_widget(list, area, &mut list_state);
}
@@ -420,3 +413,59 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, player: &Player, area:
frame.render_widget(right_bar, chunks[1]);
}
}
fn render_confirm_popup(frame: &mut Frame, title: &str, message: &str) {
// Create centered popup area
let area = frame.area();
let popup_width = 52;
let popup_height = 7;
let popup_area = Rect {
x: (area.width.saturating_sub(popup_width)) / 2,
y: (area.height.saturating_sub(popup_height)) / 2,
width: popup_width.min(area.width),
height: popup_height.min(area.height),
};
// Use Clear widget to completely erase the background
frame.render_widget(Clear, popup_area);
// Render the popup block with solid background
let block = Block::default()
.title(title)
.borders(Borders::ALL)
.style(Style::default()
.bg(Theme::background())
.fg(Theme::bright_foreground()))
.title_style(Style::default()
.fg(Theme::bright_foreground())
.add_modifier(Modifier::BOLD));
let inner = block.inner(popup_area);
frame.render_widget(block, popup_area);
// Render message and prompt
let text_area = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // Empty line
Constraint::Length(1), // Message
Constraint::Length(1), // Empty line
Constraint::Length(1), // Prompt
])
.split(inner);
let message_text = Paragraph::new(message)
.style(Style::default()
.fg(Theme::bright_foreground())
.bg(Theme::background()))
.alignment(Alignment::Center);
frame.render_widget(message_text, text_area[1]);
let prompt_text = Paragraph::new("Press 'y' to confirm or 'n' to cancel")
.style(Style::default()
.fg(Theme::foreground())
.bg(Theme::background()))
.alignment(Alignment::Center);
frame.render_widget(prompt_text, text_area[3]);
}

View File

@@ -91,4 +91,10 @@ impl Theme {
.fg(Self::warning())
.bg(Self::background())
}
pub fn search_selected() -> Style {
Style::default()
.fg(Self::background())
.bg(Self::warning())
}
}