cm-player/src/main.rs
Christoffer Martinsson 4529fad61d
All checks were successful
Build and Release / build-and-release (push) Successful in 50s
Reduce memory usage by ~50 MB for large libraries
FlattenedItem now stores only essential fields (path, name, is_dir, depth)
instead of cloning entire FileTreeNode structures. For 500,000 files, this
reduces memory from ~100 MB to ~50 MB for the flattened view.

- Extract only needed fields in flatten_tree()
- Add find_node_by_path() helper to look up full nodes when needed
- Update all UI and state code to use new structure
2025-12-11 19:39:26 +01:00

1034 lines
39 KiB
Rust

mod cache;
mod config;
mod player;
mod scanner;
mod state;
mod ui;
use anyhow::{Context, Result};
use crossterm::{
event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind, EnableMouseCapture, DisableMouseCapture},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use state::{AppState, PlayerState};
use std::io;
use tracing_subscriber;
// UI update intervals and thresholds
const METADATA_UPDATE_INTERVAL: u32 = 20; // Update metadata every N iterations (~2 seconds)
const POLL_DURATION_STOPPED_MS: u64 = 200; // 5 FPS when stopped
const POLL_DURATION_ACTIVE_MS: u64 = 100; // 10 FPS when playing/paused
const DOUBLE_CLICK_MS: u128 = 500; // Double-click detection threshold
fn main() -> Result<()> {
// Initialize logging to file to avoid interfering with TUI
let log_file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open("/tmp/cm-player.log")
.ok();
if let Some(file) = log_file {
tracing_subscriber::fmt()
.with_writer(std::sync::Mutex::new(file))
.init();
}
// Get config and cache paths
let config_path = config::get_config_path()?;
let cache_dir = cache::get_cache_dir()?;
// Load config
let config = config::Config::load(&config_path)
.context("Failed to load config")?;
tracing::info!("Loaded config from {:?}", config_path);
// Load cache (empty if doesn't exist - user must press 'r' to scan)
let cache = cache::Cache::load(&cache_dir)
.context("Failed to load cache")?;
tracing::info!("Loaded cache from {:?}", cache_dir);
// Initialize player
let mut player = player::Player::new()?;
tracing::info!("Player initialized");
// Initialize app state
let mut state = AppState::new(cache, config);
tracing::info!("State initialized");
// Setup terminal
enable_raw_mode()?;
tracing::info!("Raw mode enabled");
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
tracing::info!("Terminal setup complete");
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
tracing::info!("Terminal created, entering main loop");
// Run app (ensure terminal cleanup even on error)
let result = run_app(&mut terminal, &mut state, &mut player);
// Restore terminal (always run cleanup, even if result is Err)
let cleanup_result = (|| -> Result<()> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
})();
// Log cleanup errors but prioritize original error
if let Err(e) = cleanup_result {
tracing::error!("Terminal cleanup failed: {}", e);
}
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.is_dir {
let path = item.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)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
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<()> {
if let Some(player_state) = player.get_player_state() {
match player_state {
PlayerState::Playing => {
player.pause()?;
tracing::info!("Paused");
}
PlayerState::Paused => {
player.resume()?;
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());
if let Some(ref path) = state.current_file {
player.play(path)?;
player.resume()?;
player.update_metadata();
tracing::info!("Restarting playback: {:?}", path);
}
}
}
}
}
Ok(())
}
fn action_stop(state: &mut AppState, player: &mut player::Player) -> Result<()> {
player.stop()?;
state.current_position = 0.0;
state.current_duration = 0.0;
tracing::info!("Stopped");
Ok(())
}
fn action_remove_from_playlist(state: &mut AppState, player: &mut player::Player) -> Result<()> {
let was_playing_removed = state.playlist_index == state.selected_playlist_index;
let was_playing = player.get_player_state() == Some(PlayerState::Playing);
state.remove_selected_playlist_item();
if state.playlist.is_empty() {
state.current_file = None;
player.stop()?;
} else if was_playing_removed && was_playing && state.playlist_index < state.playlist.len() {
// Validate index before accessing playlist
state.current_file = Some(state.playlist[state.playlist_index].clone());
if let Some(ref path) = state.current_file {
player.play(path)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
player.update_metadata();
}
}
Ok(())
}
fn action_navigate_track(state: &mut AppState, player: &mut player::Player, direction: i32) -> Result<()> {
// direction: 1 for next, -1 for previous
let new_index = if direction > 0 {
state.playlist_index.saturating_add(1)
} else {
state.playlist_index.saturating_sub(1)
};
// Validate bounds
if state.playlist.is_empty() || new_index >= state.playlist.len() {
return Ok(());
}
state.playlist_index = new_index;
state.current_file = Some(state.playlist[state.playlist_index].clone());
let track_name = if direction > 0 { "Next" } else { "Previous" };
if let Some(player_state) = player.get_player_state() {
match player_state {
PlayerState::Playing => {
// Keep playing
if let Some(ref path) = state.current_file {
player.play(path)?;
player.resume()?;
player.update_metadata();
tracing::info!("{} track: {:?}", track_name, path);
}
}
PlayerState::Paused => {
// Load but stay paused
if let Some(ref path) = state.current_file {
player.play_paused(path)?;
player.update_metadata();
tracing::info!("{} track (paused): {:?}", track_name, path);
}
}
PlayerState::Stopped => {
// Just update current file, stay stopped
tracing::info!("{} track selected (stopped): {:?}", track_name, state.current_file);
}
}
}
// Auto-scroll playlist to show current track (only if user is not browsing playlist)
if !state.focus_playlist {
state.update_playlist_scroll(20);
}
Ok(())
}
fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player, preserve_pause: bool) -> Result<()> {
state.playlist_index = state.selected_playlist_index;
state.current_file = Some(state.playlist[state.playlist_index].clone());
if preserve_pause {
if let Some(player_state) = player.get_player_state() {
match player_state {
PlayerState::Playing => {
if let Some(ref path) = state.current_file {
player.play(path)?;
player.resume()?;
player.update_metadata();
tracing::info!("Jumped to track: {:?}", path);
}
}
PlayerState::Paused => {
if let Some(ref path) = state.current_file {
player.play_paused(path)?;
player.update_metadata();
tracing::info!("Jumped to track (paused): {:?}", path);
}
}
PlayerState::Stopped => {
if let Some(ref path) = state.current_file {
player.play(path)?;
player.resume()?;
player.update_metadata();
tracing::info!("Started playing track: {:?}", path);
}
}
}
}
} else {
if let Some(ref path) = state.current_file {
player.play(path)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
player.update_metadata();
tracing::info!("Playing from playlist: {:?}", path);
}
}
Ok(())
}
fn handle_context_menu_action(menu_type: state::ContextMenuType, selected: usize, state: &mut AppState, player: &mut player::Player) -> Result<()> {
match menu_type {
state::ContextMenuType::FilePanel => {
match selected {
0 => action_play_selection(state, player)?,
1 => state.add_to_playlist(),
_ => {}
}
}
state::ContextMenuType::Playlist => {
match selected {
0 => action_remove_from_playlist(state, player)?,
1 => {
state.shuffle_playlist();
tracing::info!("Playlist randomised from context menu");
}
_ => {}
}
}
state::ContextMenuType::TitleBar => {
match selected {
0 => action_stop(state, player)?,
1 => {
state.cycle_play_mode();
tracing::info!("Play mode: {:?}", state.play_mode);
}
2 => {
state.show_refresh_confirm = true;
tracing::info!("Refresh requested from context menu");
}
_ => {}
}
}
}
Ok(())
}
fn run_app<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
state: &mut AppState,
player: &mut player::Player,
) -> Result<()> {
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();
let mut playlist_area = ratatui::layout::Rect::default();
let mut previous_player_state: Option<PlayerState> = None;
loop {
let mut state_changed = false;
// Check if mpv process died (e.g., user closed video window)
if !player.is_process_alive() {
if let Some(player_state) = player.get_player_state() {
if player_state != PlayerState::Stopped {
state.current_position = 0.0;
state.current_duration = 0.0;
state_changed = true;
}
}
}
// Always update properties to keep state synchronized with MPV
player.update_properties();
// Only proceed if we can successfully query player state
let Some(player_state) = player.get_player_state() else {
// Can't get state from MPV, skip this iteration
if event::poll(std::time::Duration::from_millis(100))? {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key)?;
needs_redraw = true;
}
}
Event::Mouse(mouse) => {
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, playlist_area, player)?;
needs_redraw = true;
}
_ => {}
}
}
continue;
};
// Check if track ended and play next
// When MPV finishes playing a file, it goes to idle (Stopped state)
// Detect Playing → Stopped transition = track ended, play next
if previous_player_state == Some(PlayerState::Playing)
&& player_state == PlayerState::Stopped
{
let should_continue = state.play_next();
// play_next() returns true if should continue playing, false if should stop
if should_continue {
if let Some(ref path) = state.current_file {
// Reset position/duration before playing new track
state.current_position = 0.0;
state.current_duration = 0.0;
last_position = 0.0;
player.play(path)?;
player.resume()?;
}
// Update metadata immediately when track changes
player.update_metadata();
metadata_update_counter = 0;
// Auto-scroll playlist to show current track (only if user is not browsing playlist)
if !state.focus_playlist {
let playlist_visible_height = playlist_area.height.saturating_sub(2) as usize;
state.update_playlist_scroll(playlist_visible_height);
}
} else {
// Reached end of playlist in Normal mode - stop playback
player.stop()?;
}
state_changed = true;
}
// Only update metadata and track playback when not stopped
if player_state != PlayerState::Stopped {
// Update metadata periodically to reduce IPC calls
metadata_update_counter += 1;
if metadata_update_counter >= METADATA_UPDATE_INTERVAL {
player.update_metadata();
metadata_update_counter = 0;
state_changed = true;
}
// Update position and duration from player
let new_position = player.get_position().unwrap_or(0.0);
let new_duration = player.get_duration().unwrap_or(0.0);
// Only update if displayed value (rounded to seconds) changed
let old_display_secs = last_position as u32;
let new_display_secs = new_position as u32;
if new_display_secs != old_display_secs {
state.current_position = new_position;
last_position = new_position;
state_changed = true;
}
if state.current_duration != new_duration {
state.current_duration = new_duration;
state_changed = true;
}
}
// Save current state for next iteration
previous_player_state = Some(player_state);
// Only redraw if something changed or forced
if needs_redraw || state_changed {
terminal.draw(|f| {
let areas = ui::render(f, state, player);
title_bar_area = areas.0;
file_panel_area = areas.1;
playlist_area = areas.2;
})?;
needs_redraw = false;
}
// Poll for events - use longer timeout when stopped to reduce CPU
let poll_duration = if player_state == PlayerState::Stopped {
std::time::Duration::from_millis(POLL_DURATION_STOPPED_MS)
} else {
std::time::Duration::from_millis(POLL_DURATION_ACTIVE_MS)
};
if event::poll(poll_duration)? {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key)?;
needs_redraw = true; // Force redraw after key event
}
}
Event::Mouse(mouse) => {
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, playlist_area, player)?;
needs_redraw = true; // Force redraw after mouse event
}
_ => {}
}
}
if state.should_quit {
break;
}
}
Ok(())
}
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 {
KeyCode::Char(c) => {
if state.focus_playlist {
state.append_playlist_search_char(c);
} else {
state.append_search_char(c);
}
}
KeyCode::Backspace => {
if state.focus_playlist {
state.backspace_playlist_search();
} else {
state.backspace_search();
}
}
KeyCode::Tab => {
if state.focus_playlist {
state.playlist_tab_search_next();
} else {
state.tab_search_next();
}
}
KeyCode::BackTab => {
if state.focus_playlist {
state.playlist_tab_search_prev();
} else {
state.tab_search_prev();
}
}
KeyCode::Enter => {
if state.focus_playlist {
state.execute_playlist_search();
} else {
state.execute_search();
}
}
KeyCode::Esc => {
state.exit_search_mode();
}
_ => {}
}
return Ok(());
}
// Handle context menu navigation if menu is shown
if let Some(ref mut menu) = state.context_menu {
use crate::state::ContextMenuType;
match key.code {
KeyCode::Up | KeyCode::Char('k') => {
if menu.selected_index > 0 {
menu.selected_index -= 1;
}
}
KeyCode::Down | KeyCode::Char('j') => {
let max_items = match menu.menu_type {
ContextMenuType::FilePanel => 2,
ContextMenuType::Playlist => 2,
ContextMenuType::TitleBar => 3,
};
if menu.selected_index < max_items - 1 {
menu.selected_index += 1;
}
}
KeyCode::Enter => {
// Execute selected action
let menu_type = menu.menu_type;
let selected = menu.selected_index;
state.context_menu = None;
handle_context_menu_action(menu_type, selected, state, player)?;
}
KeyCode::Esc => {
state.context_menu = None;
}
_ => {}
}
return Ok(());
}
match (key.code, key.modifiers) {
(KeyCode::Char('q'), _) => {
state.should_quit = true;
}
(KeyCode::Char('/'), _) => {
if state.search_mode && state.search_query.is_empty() {
// Exit search mode only if search query is blank
state.exit_search_mode();
} else if !state.search_mode {
state.enter_search_mode();
}
}
(KeyCode::Esc, _) => {
if !state.search_matches.is_empty() {
state.search_matches.clear();
}
if !state.playlist_search_matches.is_empty() {
state.playlist_search_matches.clear();
state.playlist_tab_search_results.clear();
}
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
}
(KeyCode::Char('n'), _) => {
if !state.search_matches.is_empty() {
state.next_search_match();
} else if !state.playlist_search_matches.is_empty() {
state.next_playlist_search_match();
}
}
(KeyCode::Char('N'), KeyModifiers::SHIFT) => {
if !state.search_matches.is_empty() {
state.prev_search_match();
} else if !state.playlist_search_matches.is_empty() {
state.prev_playlist_search_match();
}
}
(KeyCode::Char('J'), KeyModifiers::SHIFT) => {
// Next track
action_navigate_track(state, player, 1)?;
}
(KeyCode::Char('K'), KeyModifiers::SHIFT) => {
// Previous track
action_navigate_track(state, player, -1)?;
}
(KeyCode::Char('d'), KeyModifiers::CONTROL) => {
if state.focus_playlist {
state.playlist_page_down();
} else {
state.page_down();
}
}
(KeyCode::Char('u'), KeyModifiers::CONTROL) => {
if state.focus_playlist {
state.playlist_page_up();
} else {
state.page_up();
}
}
(KeyCode::Tab, _) => {
// Switch focus between file panel and playlist panel
state.focus_playlist = !state.focus_playlist;
}
(KeyCode::Char('k'), _) | (KeyCode::Up, _) => {
if state.focus_playlist {
state.move_playlist_selection_up();
} else {
state.move_selection_up();
}
}
(KeyCode::Char('j'), _) | (KeyCode::Down, _) => {
if state.focus_playlist {
state.move_playlist_selection_down(state.playlist_visible_height);
} else {
state.move_selection_down();
}
}
(KeyCode::Char('h'), _) | (KeyCode::Left, _) => {
if !state.focus_playlist {
state.collapse_selected();
}
}
(KeyCode::Char('l'), _) | (KeyCode::Right, _) => {
if !state.focus_playlist {
state.expand_selected();
}
}
(KeyCode::Char('v'), _) => {
if !state.focus_playlist {
state.toggle_mark();
}
}
(KeyCode::Char('a'), _) => {
if !state.focus_playlist {
state.add_to_playlist();
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
}
}
(KeyCode::Char('c'), _) => {
state.clear_playlist();
}
(KeyCode::Char('d'), _) => {
if state.focus_playlist {
action_remove_from_playlist(state, player)?;
}
}
(KeyCode::Enter, _) => {
if state.focus_playlist {
if state.selected_playlist_index < state.playlist.len() {
action_play_from_playlist(state, player, false)?;
}
} else {
action_play_selection(state, player)?;
}
}
(KeyCode::Char('s'), _) => {
action_stop(state, player)?;
}
(KeyCode::Char('m'), _) => {
state.cycle_play_mode();
tracing::info!("Play mode: {:?}", state.play_mode);
}
(KeyCode::Char('R'), KeyModifiers::SHIFT) => {
state.shuffle_playlist();
tracing::info!("Playlist shuffled");
}
(KeyCode::Char(' '), _) => {
action_toggle_play_pause(state, player)?;
}
(KeyCode::Char('H'), KeyModifiers::SHIFT) => {
if player.get_player_state() != Some(PlayerState::Stopped) {
player.seek(-10.0)?;
tracing::info!("Seek backward 10s");
}
}
(KeyCode::Char('L'), KeyModifiers::SHIFT) => {
if player.get_player_state() != Some(PlayerState::Stopped) {
player.seek(10.0)?;
tracing::info!("Seek forward 10s");
}
}
(KeyCode::Char('+'), _) | (KeyCode::Char('='), _) => {
let new_volume = (state.volume + 5).min(100);
state.volume = new_volume;
player.set_volume(new_volume)?;
tracing::info!("Volume: {}%", new_volume);
}
(KeyCode::Char('-'), _) => {
let new_volume = (state.volume - 5).max(0);
state.volume = new_volume;
player.set_volume(new_volume)?;
tracing::info!("Volume: {}%", new_volume);
}
(KeyCode::Char('r'), _) => {
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, playlist_area: ratatui::layout::Rect, player: &mut player::Player) -> Result<()> {
use crossterm::event::MouseButton;
use crate::state::ContextMenuType;
let x = mouse.column;
let y = mouse.row;
// Handle context menu if open (like cm-dashboard)
if let Some(ref menu) = state.context_menu.clone() {
// Calculate popup bounds
let items = match menu.menu_type {
ContextMenuType::FilePanel => 2,
ContextMenuType::Playlist => 2,
ContextMenuType::TitleBar => 3,
};
let popup_width = 13;
let popup_height = items as u16 + 2; // +2 for borders
// Get screen dimensions
let screen_width = title_bar_area.width.max(file_panel_area.width + playlist_area.width);
let screen_height = title_bar_area.height + file_panel_area.height.max(playlist_area.height) + 1;
let popup_x = if menu.x + popup_width < screen_width {
menu.x
} else {
screen_width.saturating_sub(popup_width)
};
let popup_y = if menu.y + popup_height < screen_height {
menu.y
} else {
screen_height.saturating_sub(popup_height)
};
let popup_area = ratatui::layout::Rect {
x: popup_x,
y: popup_y,
width: popup_width,
height: popup_height,
};
// Check if mouse is in popup area
let in_popup = x >= popup_area.x
&& x < popup_area.x + popup_area.width
&& y >= popup_area.y
&& y < popup_area.y + popup_area.height;
// Update selected index on mouse move
if matches!(mouse.kind, MouseEventKind::Moved) {
if in_popup {
let relative_y = y.saturating_sub(popup_y + 1) as usize; // +1 for top border
if relative_y < items {
if let Some(ref mut menu) = state.context_menu {
menu.selected_index = relative_y;
}
}
}
return Ok(());
}
// Handle left click
if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
if in_popup {
// Click inside popup - execute action
let relative_y = y.saturating_sub(popup_y + 1) as usize; // +1 for top border
if relative_y < items {
let menu_type = menu.menu_type;
let selected = relative_y;
state.context_menu = None;
handle_context_menu_action(menu_type, selected, state, player)?;
}
return Ok(());
} else {
// Click outside popup - close it
state.context_menu = None;
return Ok(());
}
}
// Any other event while popup is open - don't process panels
return Ok(());
}
match mouse.kind {
MouseEventKind::ScrollDown => {
// Check which panel the mouse is over
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
{
// Scroll on title bar = decrease volume
let new_volume = (state.volume - 5).max(0);
state.volume = new_volume;
player.set_volume(new_volume)?;
tracing::info!("Volume: {}%", new_volume);
} else if x >= playlist_area.x
&& x < playlist_area.x + playlist_area.width
&& y >= playlist_area.y
&& y < playlist_area.y + playlist_area.height
{
// Scroll playlist
let visible_height = playlist_area.height.saturating_sub(2) as usize;
state.scroll_playlist_down(visible_height);
} else {
// Scroll file panel
let visible_height = file_panel_area.height.saturating_sub(2) as usize;
state.scroll_view_down(visible_height);
}
}
MouseEventKind::ScrollUp => {
// Check which panel the mouse is over
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
{
// Scroll on title bar = increase volume
let new_volume = (state.volume + 5).min(100);
state.volume = new_volume;
player.set_volume(new_volume)?;
tracing::info!("Volume: {}%", new_volume);
} else if x >= playlist_area.x
&& x < playlist_area.x + playlist_area.width
&& y >= playlist_area.y
&& y < playlist_area.y + playlist_area.height
{
// Scroll playlist
state.scroll_playlist_up();
} else {
// Scroll file panel
state.scroll_view_up();
}
}
MouseEventKind::Down(button) => {
// 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 = show context menu
use crate::state::{ContextMenu, ContextMenuType};
state.context_menu = Some(ContextMenu {
menu_type: ContextMenuType::TitleBar,
x,
y,
selected_index: 0,
});
}
_ => {}
}
}
// 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;
state.focus_playlist = false; // Switch focus to file panel
// Handle different mouse buttons
match button {
MouseButton::Left => {
// Detect double-click (same item within 500ms)
let now = std::time::Instant::now();
let is_double_click = if let (Some(last_time), Some(last_idx), false) =
(state.last_click_time, state.last_click_index, state.last_click_is_playlist) {
last_idx == clicked_index && now.duration_since(last_time).as_millis() < DOUBLE_CLICK_MS
} else {
false
};
if is_double_click {
// Double click = toggle folder or play file
if let Some(item) = state.get_selected_item() {
if item.is_dir {
action_toggle_folder(state);
} else {
action_play_selection(state, player)?;
}
}
// Reset click tracking after action
state.last_click_time = None;
state.last_click_index = None;
} else {
// Single click = just select
state.last_click_time = Some(now);
state.last_click_index = Some(clicked_index);
state.last_click_is_playlist = false;
}
}
MouseButton::Right => {
// Right click = show context menu at mouse position
use crate::state::{ContextMenu, ContextMenuType};
state.context_menu = Some(ContextMenu {
menu_type: ContextMenuType::FilePanel,
x,
y,
selected_index: 0,
});
}
_ => {}
}
}
}
// Check if click is within playlist area
else if x >= playlist_area.x
&& x < playlist_area.x + playlist_area.width
&& y >= playlist_area.y
&& y < playlist_area.y + playlist_area.height
{
// Calculate which track was clicked (accounting for borders)
let relative_y = (y - playlist_area.y).saturating_sub(1);
let clicked_track = relative_y as usize;
// Add scroll offset to get actual index
let actual_track = state.playlist_scroll_offset + clicked_track;
match button {
MouseButton::Left => {
if actual_track < state.playlist.len() {
state.selected_playlist_index = actual_track;
state.focus_playlist = true; // Switch focus to playlist
// Detect double-click (same track within 500ms)
let now = std::time::Instant::now();
let is_double_click = if let (Some(last_time), Some(last_idx), true) =
(state.last_click_time, state.last_click_index, state.last_click_is_playlist) {
last_idx == actual_track && now.duration_since(last_time).as_millis() < DOUBLE_CLICK_MS
} else {
false
};
if is_double_click {
// Double click = play the track (preserve pause state)
state.selected_playlist_index = actual_track;
action_play_from_playlist(state, player, true)?;
// Reset click tracking after action
state.last_click_time = None;
state.last_click_index = None;
} else {
// Single click = just select
state.last_click_time = Some(now);
state.last_click_index = Some(actual_track);
state.last_click_is_playlist = true;
}
}
}
MouseButton::Right => {
// Right click shows context menu at mouse position
if actual_track < state.playlist.len() {
state.selected_playlist_index = actual_track;
state.focus_playlist = true; // Switch focus to playlist
use crate::state::{ContextMenu, ContextMenuType};
state.context_menu = Some(ContextMenu {
menu_type: ContextMenuType::Playlist,
x,
y,
selected_index: 0,
});
}
}
_ => {}
}
}
}
_ => {}
}
Ok(())
}