7 Commits

Author SHA1 Message Date
b438065c23 Use small triangle arrow for playlist playing indicator
All checks were successful
Build and Release / build-and-release (push) Successful in 54s
Replace large arrow with small triangle (▸) to match the style
used for directory indicators before nerd fonts were introduced.
2025-12-12 13:08:00 +01:00
0fa26db116 Add playing indicator arrow in playlist
All checks were successful
Build and Release / build-and-release (push) Successful in 54s
Display a small arrow (▶) to the left of the currently playing track in the playlist, making it easier to identify which song is playing.
2025-12-12 12:57:12 +01:00
0ec328881a Optimize MPV polling with single batch query every 200ms
All checks were successful
Build and Release / build-and-release (push) Successful in 1m18s
Replace separate property queries with unified batch fetching:
- Consolidate position, duration, and metadata into one IPC call
- Reduce polling from 100ms to 200ms (5 FPS)
- Remove complex timeout handling in favor of simple blocking reads
- Remove unused is_idle, is_paused, and get_property methods

This eliminates status bar flashing and reduces CPU usage.
2025-12-12 11:54:42 +01:00
ccc762419f Add progress bar and dynamic panel sizing
All checks were successful
Build and Release / build-and-release (push) Successful in 53s
Add progress bar to bottom status bar showing playback progress with
gray background fill and metadata text overlay.

- Add progress bar to status bar with border gray background
- Implement dynamic panel sizing: 80/20 split favoring focused panel
- Fix progress bar flashing on track change by resetting position/duration
- Remove cache/buffer duration from status display
- Reset player position/duration in play() to prevent stale values

The progress bar uses a gray background (border color) that fills from
left to right as the track plays, with white text for the filled portion
and muted text for the unfilled portion.
2025-12-11 21:38:41 +01:00
93741320ac Add Unix socket API for OS-wide keyboard shortcuts
All checks were successful
Build and Release / build-and-release (push) Successful in 55s
Implement single binary pattern where cm-player acts as both server
(TUI mode) and client (command sender) based on CLI arguments.

- Add Unix socket API server at $XDG_RUNTIME_DIR/cm-player.sock
- Add client mode for sending commands: cm-player play-pause, next, etc.
- Support all playback commands: play-pause, stop, next, prev
- Support volume commands: volume-up, volume-down, volume <0-100>
- Support seek commands: seek-forward, seek-backward
- Support status query and quit commands
- Add short command aliases (pp, n, p, vu, vd, sf, sb, s, q)
- Commands run in parallel thread, non-blocking main loop
- Enable OS-wide keyboard shortcut integration (XF86Audio* keys)
2025-12-11 20:15:07 +01:00
7b4c664011 Add audio buffer for WSLg stability
Increase mpv audio buffer to 2 seconds to fix stuttering on WSLg.

Ref: https://github.com/microsoft/wslg/issues/1257
2025-12-11 20:04:49 +01:00
4529fad61d Reduce memory usage by ~50 MB for large libraries
All checks were successful
Build and Release / build-and-release (push) Successful in 50s
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
8 changed files with 876 additions and 322 deletions

View File

@@ -90,6 +90,72 @@ paths = [
- `r` - Rescan library (manual refresh)
- `q` - Quit
## API for OS-Wide Shortcuts
cm-player provides a Unix socket API for external control, allowing integration with OS-wide media keys and custom shortcuts.
### Architecture
- **Single Binary**: `cm-player` acts as both TUI server and CLI client
- **IPC**: Unix socket at `$XDG_RUNTIME_DIR/cm-player.sock` (or `/tmp/cm-player.sock`)
- **Protocol**: JSON commands over Unix socket
### Usage
```bash
# Start TUI (server mode)
cm-player
# Send commands to running instance (client mode)
cm-player play-pause
cm-player next
cm-player prev
cm-player stop
cm-player volume-up
cm-player volume-down
cm-player volume 50
cm-player seek-forward 30
cm-player seek-backward 10
cm-player quit
```
### OS-Wide Keyboard Shortcuts
**i3/sway config:**
```
bindsym XF86AudioPlay exec cm-player play-pause
bindsym XF86AudioNext exec cm-player next
bindsym XF86AudioPrev exec cm-player prev
bindsym XF86AudioStop exec cm-player stop
```
**KDE/GNOME:**
Add custom shortcuts pointing to `cm-player <command>`
### JSON Protocol
Commands are JSON objects with a `command` field:
```json
{"command": "play-pause"}
{"command": "next"}
{"command": "prev"}
{"command": "stop"}
{"command": "volume-up"}
{"command": "volume-down"}
{"command": "volume-set", "volume": 50}
{"command": "seek-forward", "seconds": 30}
{"command": "seek-backward", "seconds": 10}
{"command": "get-status"}
{"command": "quit"}
```
Responses:
```json
{"success": true, "message": null, "data": null}
{"success": false, "message": "error details", "data": null}
```
### Technical Details
- **MPV IPC** - Communicates with mpv via Unix socket and JSON protocol
- **No Version Lock** - Uses mpv binary, not libmpv library (avoids version mismatch)

View File

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

120
src/api/mod.rs Normal file
View File

@@ -0,0 +1,120 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
/// Commands that can be sent to cm-player via the API
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "command", rename_all = "kebab-case")]
pub enum ApiCommand {
/// Toggle play/pause (play if stopped, pause if playing)
PlayPause,
/// Stop playback
Stop,
/// Next track
Next,
/// Previous track
Prev,
/// Volume up by 5%
VolumeUp,
/// Volume down by 5%
VolumeDown,
/// Set volume to specific value (0-100)
VolumeSet { volume: i64 },
/// Seek forward by seconds
SeekForward { seconds: f64 },
/// Seek backward by seconds
SeekBackward { seconds: f64 },
/// Get current player status
GetStatus,
/// Quit the application
Quit,
}
/// Response from the API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiResponse {
pub success: bool,
pub message: Option<String>,
pub data: Option<serde_json::Value>,
}
impl ApiResponse {
pub fn success() -> Self {
Self {
success: true,
message: None,
data: None,
}
}
}
/// Start the API server on a Unix socket
pub fn start_api_server(socket_path: PathBuf) -> Result<Receiver<ApiCommand>> {
// Remove old socket if it exists
if socket_path.exists() {
std::fs::remove_file(&socket_path)?;
}
let listener = UnixListener::bind(&socket_path)
.context("Failed to bind Unix socket for API")?;
tracing::info!("API server listening on {:?}", socket_path);
let (tx, rx) = mpsc::channel();
// Spawn thread to handle incoming connections
thread::spawn(move || {
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let tx = tx.clone();
thread::spawn(move || {
if let Err(e) = handle_client(stream, tx) {
tracing::warn!("API client error: {}", e);
}
});
}
Err(e) => {
tracing::error!("API connection error: {}", e);
}
}
}
});
Ok(rx)
}
fn handle_client(mut stream: UnixStream, tx: Sender<ApiCommand>) -> Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut line = String::new();
reader.read_line(&mut line)?;
// Parse command
let command: ApiCommand = serde_json::from_str(&line)
.context("Failed to parse API command")?;
tracing::debug!("Received API command: {:?}", command);
// Send command to main thread
tx.send(command.clone())
.context("Failed to send command to main thread")?;
// Send response
let response = ApiResponse::success();
let response_json = serde_json::to_string(&response)?;
writeln!(stream, "{}", response_json)?;
Ok(())
}
/// Helper function to get default socket path
pub fn get_default_socket_path() -> Result<PathBuf> {
let runtime_dir = std::env::var("XDG_RUNTIME_DIR")
.unwrap_or_else(|_| "/tmp".to_string());
Ok(PathBuf::from(runtime_dir).join("cm-player.sock"))
}

View File

@@ -1,3 +1,4 @@
mod api;
mod cache;
mod config;
mod player;
@@ -13,16 +14,22 @@ use crossterm::{
};
use ratatui::{backend::CrosstermBackend, Terminal};
use state::{AppState, PlayerState};
use std::io;
use std::io::{self, BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
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 POLL_DURATION_ACTIVE_MS: u64 = 200; // 5 FPS when playing/paused - single batch poll
const DOUBLE_CLICK_MS: u128 = 500; // Double-click detection threshold
fn main() -> Result<()> {
// Check if we're in client mode (sending command to running instance)
let args: Vec<String> = std::env::args().collect();
if args.len() > 1 {
return send_command(&args[1..]);
}
// Initialize logging to file to avoid interfering with TUI
let log_file = std::fs::OpenOptions::new()
.create(true)
@@ -60,6 +67,11 @@ fn main() -> Result<()> {
let mut state = AppState::new(cache, config);
tracing::info!("State initialized");
// Start API server
let socket_path = api::get_default_socket_path()?;
let api_rx = api::start_api_server(socket_path)?;
tracing::info!("API server started");
// Setup terminal
enable_raw_mode()?;
tracing::info!("Raw mode enabled");
@@ -71,7 +83,7 @@ fn main() -> Result<()> {
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);
let result = run_app(&mut terminal, &mut state, &mut player, api_rx);
// Restore terminal (always run cleanup, even if result is Err)
let cleanup_result = (|| -> Result<()> {
@@ -93,12 +105,108 @@ fn main() -> Result<()> {
result
}
/// Send a command to a running cm-player instance (client mode)
fn send_command(args: &[String]) -> Result<()> {
let socket_path = api::get_default_socket_path()?;
if !socket_path.exists() {
eprintln!("Error: cm-player is not running (socket not found at {:?})", socket_path);
std::process::exit(1);
}
// Parse command
let command = match args[0].as_str() {
"play-pause" | "pp" => api::ApiCommand::PlayPause,
"stop" => api::ApiCommand::Stop,
"next" | "n" => api::ApiCommand::Next,
"prev" | "p" => api::ApiCommand::Prev,
"volume-up" | "vu" => api::ApiCommand::VolumeUp,
"volume-down" | "vd" => api::ApiCommand::VolumeDown,
"volume" | "v" => {
if args.len() < 2 {
eprintln!("Usage: cm-player volume <0-100>");
std::process::exit(1);
}
let volume: i64 = args[1].parse()
.context("Volume must be a number between 0-100")?;
api::ApiCommand::VolumeSet { volume }
}
"seek-forward" | "sf" => {
let seconds = if args.len() > 1 {
args[1].parse().unwrap_or(10.0)
} else {
10.0
};
api::ApiCommand::SeekForward { seconds }
}
"seek-backward" | "sb" => {
let seconds = if args.len() > 1 {
args[1].parse().unwrap_or(10.0)
} else {
10.0
};
api::ApiCommand::SeekBackward { seconds }
}
"status" | "s" => api::ApiCommand::GetStatus,
"quit" | "q" => api::ApiCommand::Quit,
_ => {
eprintln!("Unknown command: {}", args[0]);
print_usage();
std::process::exit(1);
}
};
// Connect to socket and send command
let mut stream = UnixStream::connect(&socket_path)
.context("Failed to connect to cm-player")?;
let command_json = serde_json::to_string(&command)?;
writeln!(stream, "{}", command_json)?;
// Read response
let mut reader = BufReader::new(stream);
let mut response_line = String::new();
reader.read_line(&mut response_line)?;
let response: api::ApiResponse = serde_json::from_str(&response_line)?;
if response.success {
if let Some(data) = response.data {
println!("{}", serde_json::to_string_pretty(&data)?);
}
} else {
eprintln!("Error: {}", response.message.unwrap_or_else(|| "Unknown error".to_string()));
std::process::exit(1);
}
Ok(())
}
fn print_usage() {
eprintln!("Usage: cm-player [command] [args]");
eprintln!();
eprintln!("Commands:");
eprintln!(" play-pause, pp Toggle play/pause");
eprintln!(" stop Stop playback");
eprintln!(" next, n Next track");
eprintln!(" prev, p Previous track");
eprintln!(" volume-up, vu Volume up by 5%");
eprintln!(" volume-down, vd Volume down by 5%");
eprintln!(" volume, v <0-100> Set volume");
eprintln!(" seek-forward, sf [sec] Seek forward (default: 10s)");
eprintln!(" seek-backward, sb [sec] Seek backward (default: 10s)");
eprintln!(" status, s Get player status");
eprintln!(" quit, q Quit cm-player");
eprintln!();
eprintln!("If no command is provided, cm-player starts in TUI mode.");
}
// 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 item.is_dir {
let path = item.path.clone();
if state.expanded_dirs.contains(&path) {
// Folder is open, close it
state.collapse_selected();
@@ -110,13 +218,14 @@ fn action_toggle_folder(state: &mut AppState) {
}
}
fn action_play_selection(state: &mut AppState, player: &mut player::Player) -> Result<()> {
fn action_play_selection(state: &mut AppState, player: &mut player::Player, skip_position_update: &mut bool) -> Result<()> {
state.play_selection();
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play(path)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update once MPV has it ready
tracing::info!("Playing: {:?} (playlist: {} tracks)", path, state.playlist.len());
}
if state.visual_mode {
@@ -144,7 +253,6 @@ fn action_toggle_play_pause(state: &mut AppState, player: &mut player::Player) -
if let Some(ref path) = state.current_file {
player.play(path)?;
player.resume()?;
player.update_metadata();
tracing::info!("Restarting playback: {:?}", path);
}
}
@@ -177,13 +285,13 @@ fn action_remove_from_playlist(state: &mut AppState, player: &mut player::Player
player.play(path)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update
}
}
Ok(())
}
fn action_navigate_track(state: &mut AppState, player: &mut player::Player, direction: i32) -> Result<()> {
fn action_navigate_track(state: &mut AppState, player: &mut player::Player, direction: i32, skip_position_update: &mut bool) -> Result<()> {
// direction: 1 for next, -1 for previous
let new_index = if direction > 0 {
state.playlist_index.saturating_add(1)
@@ -206,17 +314,19 @@ fn action_navigate_track(state: &mut AppState, player: &mut player::Player, dire
PlayerState::Playing => {
// Keep playing
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play(path)?;
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update
tracing::info!("{} track: {:?}", track_name, path);
}
}
PlayerState::Paused => {
// Load but stay paused
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play_paused(path)?;
player.update_metadata();
// Metadata will be fetched by periodic update
tracing::info!("{} track (paused): {:?}", track_name, path);
}
}
@@ -235,33 +345,37 @@ fn action_navigate_track(state: &mut AppState, player: &mut player::Player, dire
Ok(())
}
fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player, preserve_pause: bool) -> Result<()> {
fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player, preserve_pause: bool, skip_position_update: &mut 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 {
*skip_position_update = true; // Skip position update after track change
player.play(path)?;
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update
tracing::info!("Jumped to track: {:?}", path);
}
}
PlayerState::Paused => {
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play_paused(path)?;
player.update_metadata();
// Metadata will be fetched by periodic update
tracing::info!("Jumped to track (paused): {:?}", path);
}
}
PlayerState::Stopped => {
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play(path)?;
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update
tracing::info!("Started playing track: {:?}", path);
}
}
@@ -269,21 +383,22 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
}
} else {
if let Some(ref path) = state.current_file {
*skip_position_update = true; // Skip position update after track change
player.play(path)?;
// Explicitly resume playback in case MPV was paused
player.resume()?;
player.update_metadata();
// Metadata will be fetched by periodic update
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<()> {
fn handle_context_menu_action(menu_type: state::ContextMenuType, selected: usize, state: &mut AppState, player: &mut player::Player, skip_position_update: &mut bool) -> Result<()> {
match menu_type {
state::ContextMenuType::FilePanel => {
match selected {
0 => action_play_selection(state, player)?,
0 => action_play_selection(state, player, skip_position_update)?,
1 => state.add_to_playlist(),
_ => {}
}
@@ -320,10 +435,11 @@ fn run_app<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
state: &mut AppState,
player: &mut player::Player,
api_rx: std::sync::mpsc::Receiver<api::ApiCommand>,
) -> Result<()> {
let mut metadata_update_counter = 0u32;
let mut last_position = 0.0f64;
let mut needs_redraw = true;
let mut skip_position_update = false;
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();
@@ -332,6 +448,74 @@ fn run_app<B: ratatui::backend::Backend>(
loop {
let mut state_changed = false;
// Check for API commands (non-blocking)
while let Ok(cmd) = api_rx.try_recv() {
tracing::debug!("Processing API command: {:?}", cmd);
match cmd {
api::ApiCommand::PlayPause => {
if let Some(player_state) = player.get_player_state() {
match player_state {
PlayerState::Stopped => {
// Play current file or first in playlist
if state.current_file.is_none() && !state.playlist.is_empty() {
state.current_file = Some(state.playlist[0].clone());
}
if let Some(ref file) = state.current_file {
player.play(file)?;
}
}
PlayerState::Playing => player.pause()?,
PlayerState::Paused => player.resume()?,
}
state_changed = true;
}
}
api::ApiCommand::Stop => {
player.stop()?;
state.current_file = None;
state_changed = true;
}
api::ApiCommand::Next => {
action_navigate_track(state, player, 1, &mut skip_position_update)?;
state_changed = true;
}
api::ApiCommand::Prev => {
action_navigate_track(state, player, -1, &mut skip_position_update)?;
state_changed = true;
}
api::ApiCommand::VolumeUp => {
state.volume = (state.volume + 5).min(100);
player.set_volume(state.volume)?;
state_changed = true;
}
api::ApiCommand::VolumeDown => {
state.volume = (state.volume - 5).max(0);
player.set_volume(state.volume)?;
state_changed = true;
}
api::ApiCommand::VolumeSet { volume } => {
state.volume = volume.clamp(0, 100);
player.set_volume(state.volume)?;
state_changed = true;
}
api::ApiCommand::SeekForward { seconds } => {
player.seek(seconds)?;
state_changed = true;
}
api::ApiCommand::SeekBackward { seconds } => {
player.seek(-seconds)?;
state_changed = true;
}
api::ApiCommand::GetStatus => {
// Status query - no state change needed
tracing::debug!("Status query received");
}
api::ApiCommand::Quit => {
state.should_quit = true;
}
}
}
// 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() {
@@ -343,8 +527,8 @@ fn run_app<B: ratatui::backend::Backend>(
}
}
// Always update properties to keep state synchronized with MPV
player.update_properties();
// Always update all properties in one batch to keep state synchronized with MPV
player.update_all_properties();
// Only proceed if we can successfully query player state
let Some(player_state) = player.get_player_state() else {
@@ -353,12 +537,12 @@ fn run_app<B: ratatui::backend::Backend>(
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key)?;
handle_key_event(terminal, state, player, key, &mut skip_position_update)?;
needs_redraw = true;
}
}
Event::Mouse(mouse) => {
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, playlist_area, player)?;
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, playlist_area, player, &mut skip_position_update)?;
needs_redraw = true;
}
_ => {}
@@ -381,13 +565,11 @@ fn run_app<B: ratatui::backend::Backend>(
state.current_position = 0.0;
state.current_duration = 0.0;
last_position = 0.0;
skip_position_update = true; // Skip position update this iteration
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;
@@ -400,32 +582,29 @@ fn run_app<B: ratatui::backend::Backend>(
state_changed = true;
}
// Only update metadata and track playback when not stopped
// Only update playback position 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);
// Skip this iteration if we just started a new track to avoid stale MPV values
if skip_position_update {
skip_position_update = false;
} else {
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;
}
// 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;
if state.current_duration != new_duration {
state.current_duration = new_duration;
state_changed = true;
}
}
}
@@ -454,12 +633,12 @@ fn run_app<B: ratatui::backend::Backend>(
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key)?;
handle_key_event(terminal, state, player, key, &mut skip_position_update)?;
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)?;
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, playlist_area, player, &mut skip_position_update)?;
needs_redraw = true; // Force redraw after mouse event
}
_ => {}
@@ -474,7 +653,7 @@ fn run_app<B: ratatui::backend::Backend>(
Ok(())
}
fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, state: &mut AppState, player: &mut player::Player, key: KeyEvent) -> Result<()> {
fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, state: &mut AppState, player: &mut player::Player, key: KeyEvent, skip_position_update: &mut bool) -> Result<()> {
// Handle confirmation popup
if state.show_refresh_confirm {
match key.code {
@@ -569,7 +748,7 @@ fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, st
let menu_type = menu.menu_type;
let selected = menu.selected_index;
state.context_menu = None;
handle_context_menu_action(menu_type, selected, state, player)?;
handle_context_menu_action(menu_type, selected, state, player, skip_position_update)?;
}
KeyCode::Esc => {
state.context_menu = None;
@@ -620,11 +799,11 @@ fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, st
}
(KeyCode::Char('J'), KeyModifiers::SHIFT) => {
// Next track
action_navigate_track(state, player, 1)?;
action_navigate_track(state, player, 1, skip_position_update)?;
}
(KeyCode::Char('K'), KeyModifiers::SHIFT) => {
// Previous track
action_navigate_track(state, player, -1)?;
action_navigate_track(state, player, -1, skip_position_update)?;
}
(KeyCode::Char('d'), KeyModifiers::CONTROL) => {
if state.focus_playlist {
@@ -693,10 +872,10 @@ fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, st
(KeyCode::Enter, _) => {
if state.focus_playlist {
if state.selected_playlist_index < state.playlist.len() {
action_play_from_playlist(state, player, false)?;
action_play_from_playlist(state, player, false, skip_position_update)?;
}
} else {
action_play_selection(state, player)?;
action_play_selection(state, player, skip_position_update)?;
}
}
(KeyCode::Char('s'), _) => {
@@ -746,7 +925,7 @@ fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, st
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<()> {
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, skip_position_update: &mut bool) -> Result<()> {
use crossterm::event::MouseButton;
use crate::state::ContextMenuType;
@@ -815,7 +994,7 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
let menu_type = menu.menu_type;
let selected = relative_y;
state.context_menu = None;
handle_context_menu_action(menu_type, selected, state, player)?;
handle_context_menu_action(menu_type, selected, state, player, skip_position_update)?;
}
return Ok(());
} else {
@@ -905,15 +1084,55 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
_ => {}
}
}
// Check if click is on the panel title border (to switch focus)
// The visible area is whichever one is not Rect::default()
else if (file_panel_area.width > 0 && y == file_panel_area.y) ||
(playlist_area.width > 0 && y == playlist_area.y) {
// Click is on the top border line where "Files | Playlist" is shown
// Get the actual visible area (not the default one)
let area = if file_panel_area.width > 0 { file_panel_area } else { playlist_area };
// Build title text to calculate positions
let playlist_text = if !state.playlist.is_empty() {
format!("Playlist [{}/{}]", state.playlist_index + 1, state.playlist.len())
} else {
"Playlist (empty)".to_string()
};
// Title is left-aligned by default in ratatui, starts after left border
// Border character takes 1 position, then title starts
let title_start_x = area.x + 1;
// Calculate where "Files" and "Playlist" text are
let files_start = title_start_x;
let files_end = files_start + 5; // "Files" is 5 chars
let separator_start = files_end;
let separator_end = separator_start + 3; // " | " is 3 chars
let playlist_start = separator_end;
let playlist_end = playlist_start + playlist_text.len() as u16;
match button {
MouseButton::Left => {
if x >= files_start && x < files_end {
// Clicked on "Files" - switch to file panel
state.focus_playlist = false;
} else if x >= playlist_start && x < playlist_end {
// Clicked on "Playlist" - switch to playlist
state.focus_playlist = true;
}
}
_ => {}
}
}
// 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);
// Calculate which item was clicked (accounting for scroll offset and outer border)
// Outer border takes 1 line at top, content starts at file_panel_area.y + 1
let relative_y = y.saturating_sub(file_panel_area.y + 1);
let clicked_index = state.scroll_offset + relative_y as usize;
// Set selection to clicked item if valid
@@ -936,10 +1155,10 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
if is_double_click {
// Double click = toggle folder or play file
if let Some(item) = state.get_selected_item() {
if item.node.is_dir {
if item.is_dir {
action_toggle_folder(state);
} else {
action_play_selection(state, player)?;
action_play_selection(state, player, skip_position_update)?;
}
}
// Reset click tracking after action
@@ -972,8 +1191,9 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
&& 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);
// Calculate which track was clicked (accounting for outer border)
// Outer border takes 1 line at top, content starts at playlist_area.y + 1
let relative_y = y.saturating_sub(playlist_area.y + 1);
let clicked_track = relative_y as usize;
// Add scroll offset to get actual index
@@ -997,7 +1217,7 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
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)?;
action_play_from_playlist(state, player, true, skip_position_update)?;
// Reset click tracking after action
state.last_click_time = None;
state.last_click_index = None;

View File

@@ -35,6 +35,7 @@ impl Player {
.arg("--no-terminal")
.arg("--profile=fast")
.arg("--audio-display=no") // Don't show cover art for audio files
.arg("--audio-buffer=2") // Larger buffer for WSLg audio stability
.arg(format!("--input-ipc-server={}", socket_path.display()))
.stdin(Stdio::null())
.stdout(Stdio::null())
@@ -118,88 +119,82 @@ impl Player {
Ok(())
}
fn get_property(&mut self, property: &str) -> Option<Value> {
// Try to connect - if respawning or connection fails, return None
if let Err(e) = self.connect() {
tracing::debug!("Failed to connect for property '{}': {}", property, e);
return None;
fn get_properties_batch(&mut self, properties: &[&str]) -> std::collections::HashMap<String, Value> {
let mut results = std::collections::HashMap::new();
// Try to connect
if self.connect().is_err() {
return results;
}
let cmd = json!({
"command": ["get_property", property],
"request_id": 1
});
if let Some(ref mut socket) = self.socket {
let msg = format!("{}\n", cmd);
// Write command
if let Err(e) = socket.write_all(msg.as_bytes()) {
tracing::warn!("Failed to write get_property command for '{}': {}", property, e);
self.socket = None;
return None;
// Send all property requests at once with unique request_ids
for (idx, property) in properties.iter().enumerate() {
let cmd = json!({
"command": ["get_property", property],
"request_id": idx + 1
});
let msg = format!("{}\n", cmd);
if socket.write_all(msg.as_bytes()).is_err() {
return results;
}
}
// Try to read response with timeout
// Read all responses
// IMPORTANT: Socket is non-blocking, need to set blocking mode for read
socket.set_nonblocking(false).ok();
socket.set_read_timeout(Some(Duration::from_millis(100))).ok();
let cloned_socket = match socket.try_clone() {
Ok(s) => s,
Err(e) => {
tracing::warn!("Failed to clone socket for '{}': {}", property, e);
Err(_) => {
socket.set_nonblocking(true).ok();
return None;
return results;
}
};
// Set timeout on cloned socket too (clone doesn't copy settings)
cloned_socket.set_nonblocking(false).ok();
cloned_socket.set_read_timeout(Some(Duration::from_millis(100))).ok();
let mut reader = BufReader::new(cloned_socket);
let mut response = String::new();
if let Err(e) = reader.read_line(&mut response) {
tracing::debug!("Failed to read response for '{}': {}", property, e);
socket.set_nonblocking(true).ok();
return None;
// Read responses - stop if we timeout or hit an error
for _ in 0..properties.len() {
let mut response = String::new();
if reader.read_line(&mut response).is_err() {
// Timeout or error - stop reading
break;
}
// Parse response
if let Ok(parsed) = serde_json::from_str::<Value>(&response) {
// Check for success
if let Some(error) = parsed.get("error").and_then(|e| e.as_str()) {
if error == "success" {
// Get request_id to match with property
if let Some(req_id) = parsed.get("request_id").and_then(|id| id.as_i64()) {
let idx = (req_id - 1) as usize;
if idx < properties.len() {
if let Some(data) = parsed.get("data") {
results.insert(properties[idx].to_string(), data.clone());
}
}
}
}
}
}
}
// Restore non-blocking mode
socket.set_nonblocking(true).ok();
// Parse and validate response
let parsed: Value = match serde_json::from_str(&response) {
Ok(v) => v,
Err(e) => {
tracing::warn!("Failed to parse JSON response for '{}': {} (response: {})", property, e, response.trim());
return None;
}
};
// Check for errors in response
// MPV returns {"error": "success"} when there's NO error
if let Some(error) = parsed.get("error").and_then(|e| e.as_str()) {
if error != "success" {
tracing::debug!("MPV returned error for '{}': {}", property, error);
return None;
}
}
// Validate request_id matches (should be 1)
if let Some(req_id) = parsed.get("request_id").and_then(|id| id.as_i64()) {
if req_id != 1 {
tracing::warn!("Request ID mismatch for '{}': expected 1, got {}", property, req_id);
}
}
return parsed.get("data").cloned();
}
None
results
}
pub fn play(&mut self, path: &Path) -> Result<()> {
let path_str = path.to_string_lossy();
// Reset position/duration before loading new file to avoid showing stale values
self.position = 0.0;
self.duration = 0.0;
self.send_command("loadfile", &[json!(path_str), json!("replace")])?;
tracing::info!("Playing: {}", path_str);
Ok(())
@@ -207,6 +202,9 @@ impl Player {
pub fn play_paused(&mut self, path: &Path) -> Result<()> {
let path_str = path.to_string_lossy();
// Reset position/duration before loading new file to avoid showing stale values
self.position = 0.0;
self.duration = 0.0;
// Load file but start paused - avoids audio blip when jumping tracks while paused
self.send_command("loadfile", &[json!(path_str), json!("replace"), json!({"pause": true})])?;
tracing::info!("Playing (paused): {}", path_str);
@@ -235,84 +233,73 @@ impl Player {
Ok(())
}
pub fn update_properties(&mut self) {
// Update position
if let Some(val) = self.get_property("time-pos") {
pub fn update_all_properties(&mut self) {
// Fetch ALL properties in one batch
let results = self.get_properties_batch(&[
"time-pos",
"duration",
"metadata/by-key/artist",
"metadata/by-key/ARTIST",
"metadata/by-key/album",
"metadata/by-key/ALBUM",
"metadata/by-key/title",
"metadata/by-key/TITLE",
"media-title",
"audio-codec-name",
"audio-bitrate",
"audio-params/samplerate",
"demuxer-cache-duration",
]);
// Position
if let Some(val) = results.get("time-pos") {
if let Some(pos) = val.as_f64() {
self.position = pos;
}
}
// Update duration
if let Some(val) = self.get_property("duration") {
// Duration
if let Some(val) = results.get("duration") {
if let Some(dur) = val.as_f64() {
self.duration = dur;
}
}
}
pub fn update_metadata(&mut self) {
// Try to get artist directly
if let Some(val) = self.get_property("metadata/by-key/artist") {
self.artist = val.as_str().map(|s| s.to_string());
}
// Fallback to ARTIST (uppercase)
if self.artist.is_none() {
if let Some(val) = self.get_property("metadata/by-key/ARTIST") {
self.artist = val.as_str().map(|s| s.to_string());
}
}
// Artist - try lowercase first, then uppercase
self.artist = results.get("metadata/by-key/artist")
.and_then(|v| v.as_str().map(|s| s.to_string()))
.or_else(|| results.get("metadata/by-key/ARTIST")
.and_then(|v| v.as_str().map(|s| s.to_string())));
// Try to get album directly
if let Some(val) = self.get_property("metadata/by-key/album") {
self.album = val.as_str().map(|s| s.to_string());
}
// Fallback to ALBUM (uppercase)
if self.album.is_none() {
if let Some(val) = self.get_property("metadata/by-key/ALBUM") {
self.album = val.as_str().map(|s| s.to_string());
}
}
// Album - try lowercase first, then uppercase
self.album = results.get("metadata/by-key/album")
.and_then(|v| v.as_str().map(|s| s.to_string()))
.or_else(|| results.get("metadata/by-key/ALBUM")
.and_then(|v| v.as_str().map(|s| s.to_string())));
// Try to get title directly
if let Some(val) = self.get_property("metadata/by-key/title") {
self.media_title = val.as_str().map(|s| s.to_string());
}
// Fallback to TITLE (uppercase)
if self.media_title.is_none() {
if let Some(val) = self.get_property("metadata/by-key/TITLE") {
self.media_title = val.as_str().map(|s| s.to_string());
}
}
// Title - try lowercase, then uppercase, then media-title
self.media_title = results.get("metadata/by-key/title")
.and_then(|v| v.as_str().map(|s| s.to_string()))
.or_else(|| results.get("metadata/by-key/TITLE")
.and_then(|v| v.as_str().map(|s| s.to_string())))
.or_else(|| results.get("media-title")
.and_then(|v| v.as_str().map(|s| s.to_string())));
// Final fallback to media-title if metadata doesn't have title
if self.media_title.is_none() {
if let Some(val) = self.get_property("media-title") {
self.media_title = val.as_str().map(|s| s.to_string());
}
}
// Audio codec
self.audio_codec = results.get("audio-codec-name")
.and_then(|v| v.as_str().map(|s| s.to_string()));
// Update audio codec
if let Some(val) = self.get_property("audio-codec-name") {
self.audio_codec = val.as_str().map(|s| s.to_string());
}
// Audio bitrate (convert from bps to kbps)
self.audio_bitrate = results.get("audio-bitrate")
.and_then(|v| v.as_f64().map(|b| b / 1000.0));
// Update audio bitrate (convert from bps to kbps)
if let Some(val) = self.get_property("audio-bitrate") {
self.audio_bitrate = val.as_f64().map(|b| b / 1000.0);
}
// Sample rate
self.sample_rate = results.get("audio-params/samplerate")
.and_then(|v| v.as_i64());
// Update sample rate
if let Some(val) = self.get_property("audio-params/samplerate") {
self.sample_rate = val.as_i64();
}
// Update cache duration (how many seconds are buffered ahead)
if let Some(val) = self.get_property("demuxer-cache-duration") {
self.cache_duration = val.as_f64();
} else {
self.cache_duration = None;
}
// Cache duration
self.cache_duration = results.get("demuxer-cache-duration")
.and_then(|v| v.as_f64());
}
pub fn get_position(&self) -> Option<f64> {
@@ -323,20 +310,14 @@ impl Player {
Some(self.duration)
}
pub fn is_idle(&mut self) -> Option<bool> {
self.get_property("idle-active")
.and_then(|v| v.as_bool())
}
pub fn is_paused(&mut self) -> Option<bool> {
self.get_property("pause")
.and_then(|v| v.as_bool())
}
pub fn get_player_state(&mut self) -> Option<crate::state::PlayerState> {
use crate::state::PlayerState;
let is_idle = self.is_idle()?;
let is_paused = self.is_paused()?;
// Batch fetch both properties at once
let results = self.get_properties_batch(&["idle-active", "pause"]);
let is_idle = results.get("idle-active").and_then(|v| v.as_bool())?;
let is_paused = results.get("pause").and_then(|v| v.as_bool())?;
Some(if is_idle {
PlayerState::Stopped

View File

@@ -1,7 +1,7 @@
use crate::cache::{Cache, FileTreeNode};
use crate::config::Config;
use std::collections::HashSet;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Instant;
// Fuzzy match scoring bonuses
@@ -96,7 +96,9 @@ pub struct AppState {
#[derive(Debug, Clone)]
pub struct FlattenedItem {
pub node: FileTreeNode,
pub path: PathBuf,
pub name: String,
pub is_dir: bool,
pub depth: usize,
}
@@ -336,11 +338,29 @@ impl AppState {
self.flattened_items.get(self.selected_index)
}
// Helper to find a node in the tree by path
fn find_node_by_path<'a>(&'a self, path: &Path) -> Option<&'a FileTreeNode> {
fn search_nodes<'a>(nodes: &'a [FileTreeNode], path: &Path) -> Option<&'a FileTreeNode> {
for node in nodes {
if node.path == path {
return Some(node);
}
if node.is_dir {
if let Some(found) = search_nodes(&node.children, path) {
return Some(found);
}
}
}
None
}
search_nodes(&self.cache.file_tree, path)
}
pub fn collapse_selected(&mut self) {
let item = self.get_selected_item().cloned();
if let Some(item) = item {
if item.node.is_dir {
let path = item.node.path.clone();
if item.is_dir {
let path = item.path.clone();
let was_expanded = self.expanded_dirs.contains(&path);
if was_expanded {
@@ -348,7 +368,7 @@ impl AppState {
self.expanded_dirs.remove(&path);
self.rebuild_flattened_items();
// Find the collapsed folder and select it
if let Some(idx) = self.flattened_items.iter().position(|i| i.node.path == path) {
if let Some(idx) = self.flattened_items.iter().position(|i| i.path == path) {
self.selected_index = idx;
}
} else {
@@ -358,19 +378,19 @@ impl AppState {
self.expanded_dirs.remove(&parent_buf);
self.rebuild_flattened_items();
// Jump to parent folder
if let Some(parent_idx) = self.flattened_items.iter().position(|i| i.node.path == parent_buf) {
if let Some(parent_idx) = self.flattened_items.iter().position(|i| i.path == parent_buf) {
self.selected_index = parent_idx;
}
}
}
} else {
// Close parent folder when on a file and jump to it
if let Some(parent) = item.node.path.parent() {
if let Some(parent) = item.path.parent() {
let parent_buf = parent.to_path_buf();
self.expanded_dirs.remove(&parent_buf);
self.rebuild_flattened_items();
// Jump to parent folder
if let Some(parent_idx) = self.flattened_items.iter().position(|i| i.node.path == parent_buf) {
if let Some(parent_idx) = self.flattened_items.iter().position(|i| i.path == parent_buf) {
self.selected_index = parent_idx;
}
}
@@ -380,8 +400,8 @@ impl AppState {
pub fn expand_selected(&mut self) {
if let Some(item) = self.get_selected_item() {
if item.node.is_dir {
let path = item.node.path.clone();
if item.is_dir {
let path = item.path.clone();
self.expanded_dirs.insert(path);
self.rebuild_flattened_items();
}
@@ -401,8 +421,8 @@ impl AppState {
self.marked_files.clear();
// Mark current file
if let Some(item) = self.get_selected_item() {
if !item.node.is_dir {
self.marked_files.insert(item.node.path.clone());
if !item.is_dir {
self.marked_files.insert(item.path.clone());
}
}
}
@@ -418,8 +438,8 @@ impl AppState {
for i in start..=end {
if let Some(item) = self.flattened_items.get(i) {
if !item.node.is_dir {
self.marked_files.insert(item.node.path.clone());
if !item.is_dir {
self.marked_files.insert(item.path.clone());
}
}
}
@@ -439,15 +459,19 @@ impl AppState {
files.sort();
self.playlist.extend(files);
} else if let Some(item) = self.get_selected_item() {
let node = item.node.clone();
if node.is_dir {
// Add all files in directory (allow duplicates)
let mut files = collect_files_from_node(&node);
files.sort();
self.playlist.extend(files);
let path = item.path.clone();
let is_dir = item.is_dir;
if is_dir {
// Look up the full node to get children
if let Some(node) = self.find_node_by_path(&path) {
// Add all files in directory (allow duplicates)
let mut files = collect_files_from_node(node);
files.sort();
self.playlist.extend(files);
}
} else {
// Add single file (allow duplicates)
self.playlist.push(node.path.clone());
self.playlist.push(path);
}
}
}
@@ -468,22 +492,24 @@ impl AppState {
self.current_file = None;
}
} else if let Some(item) = self.get_selected_item() {
let node = item.node.clone();
if node.is_dir {
// Play all files in directory
self.playlist = collect_files_from_node(&node);
self.playlist_index = 0;
self.playlist_scroll_offset = 0;
self.selected_playlist_index = 0;
if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone());
} else {
// Empty directory
self.current_file = None;
let path = item.path.clone();
let is_dir = item.is_dir;
if is_dir {
// Play all files in directory - look up node to get children
if let Some(node) = self.find_node_by_path(&path) {
self.playlist = collect_files_from_node(node);
self.playlist_index = 0;
self.playlist_scroll_offset = 0;
self.selected_playlist_index = 0;
if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone());
} else {
// Empty directory
self.current_file = None;
}
}
} else {
// Play single file
let path = node.path.clone();
self.playlist = vec![path.clone()];
self.playlist_index = 0;
self.playlist_scroll_offset = 0;
@@ -674,7 +700,7 @@ impl AppState {
}
// Find the best match in the flattened list and jump to it
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == best_match) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == best_match) {
self.selected_index = idx;
// Scroll to show the match
@@ -741,7 +767,7 @@ impl AppState {
self.rebuild_flattened_items();
// Find first match in flattened list
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == first_match) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == first_match) {
self.selected_index = idx;
}
}
@@ -766,7 +792,7 @@ impl AppState {
self.rebuild_flattened_items();
// Find the path in current flattened items
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == target_path) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == target_path) {
self.selected_index = idx;
// Scroll to show the match
@@ -813,7 +839,7 @@ impl AppState {
self.rebuild_flattened_items();
// Find the path in current flattened items
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == target_path) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == target_path) {
self.selected_index = idx;
// Scroll to show the match
@@ -860,7 +886,7 @@ impl AppState {
self.rebuild_flattened_items();
// Find and select the match
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == next_match) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == next_match) {
self.selected_index = idx;
// Scroll to show the match
@@ -903,7 +929,7 @@ impl AppState {
self.rebuild_flattened_items();
// Find and select the match
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == prev_match) {
if let Some(idx) = self.flattened_items.iter().position(|item| item.path == prev_match) {
self.selected_index = idx;
// Scroll to show the match
@@ -1160,7 +1186,9 @@ fn flatten_tree(nodes: &[FileTreeNode], depth: usize, expanded_dirs: &HashSet<Pa
let is_expanded = expanded_dirs.contains(&node.path);
result.push(FlattenedItem {
node: node.clone(),
path: node.path.clone(),
name: node.name.clone(),
is_dir: node.is_dir,
depth,
});

View File

@@ -28,15 +28,53 @@ pub fn render(frame: &mut Frame, state: &mut AppState, player: &mut Player) -> (
])
.split(frame.area());
// Main content: left (files) | right (status + playlist)
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(main_chunks[1]);
// Always use tab mode - show only the focused panel
let tab_mode = true;
// Build the title with focused panel in bold
let file_style = if !state.focus_playlist {
Style::default().fg(Theme::bright_foreground()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Theme::bright_foreground())
};
let playlist_style = if state.focus_playlist {
Style::default().fg(Theme::bright_foreground()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Theme::bright_foreground())
};
// Add playlist counter
let playlist_text = if !state.playlist.is_empty() {
format!("Playlist [{}/{}]", state.playlist_index + 1, state.playlist.len())
} else {
"Playlist (empty)".to_string()
};
let title = Line::from(vec![
Span::styled("Files", file_style),
Span::raw(" | "),
Span::styled(playlist_text, playlist_style),
]);
// Create one border around the entire content area
let main_block = Block::default()
.borders(Borders::ALL)
.title(title)
.style(Theme::widget_border_style());
let inner_area = main_block.inner(main_chunks[1]);
render_title_bar(frame, state, player, main_chunks[0]);
render_file_panel(frame, state, content_chunks[0]);
render_right_panel(frame, state, content_chunks[1]);
frame.render_widget(main_block, main_chunks[1]);
// Tab mode - show only focused panel
if state.focus_playlist {
render_right_panel(frame, state, inner_area, tab_mode);
} else {
render_file_panel(frame, state, inner_area, tab_mode);
}
render_status_bar(frame, state, player, main_chunks[2]);
// Show confirmation popup if needed
@@ -50,7 +88,12 @@ pub fn render(frame: &mut Frame, state: &mut AppState, player: &mut Player) -> (
}
// Return title bar area, file panel area, and playlist area for mouse event handling
(main_chunks[0], content_chunks[0], content_chunks[1])
// Use main_chunks[1] (full area) so mouse coordinates align properly
if state.focus_playlist {
(main_chunks[0], Rect::default(), main_chunks[1])
} else {
(main_chunks[0], main_chunks[1], Rect::default())
}
}
fn highlight_search_matches<'a>(text: &str, query: &str, is_selected: bool) -> Vec<Span<'a>> {
@@ -108,9 +151,9 @@ fn highlight_search_matches<'a>(text: &str, query: &str, is_selected: bool) -> V
spans
}
fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
// Calculate visible height (subtract 2 for borders)
let visible_height = area.height.saturating_sub(2) as usize;
fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect, _tab_mode: bool) {
// Calculate visible height (no borders on individual panels now)
let visible_height = area.height as usize;
// Store visible height for keyboard navigation scroll calculations
state.file_panel_visible_height = visible_height;
@@ -142,15 +185,15 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
.map(|(display_idx, item)| {
let idx = state.scroll_offset + display_idx;
let indent = " ".repeat(item.depth);
let mark = if state.marked_files.contains(&item.node.path) { "* " } else { "" };
let mark = if state.marked_files.contains(&item.path) { "* " } else { "" };
// Build name with search highlighting
// Only show selection bar when file panel has focus
let is_selected = !state.focus_playlist && idx == state.selected_index;
// Add icon for directories and files
let icon = if item.node.is_dir {
let is_expanded = state.expanded_dirs.contains(&item.node.path);
let icon = if item.is_dir {
let is_expanded = state.expanded_dirs.contains(&item.path);
// Nerd font folder icons: \u{eaf7} = open, \u{ea83} = closed
let icon_char = if is_expanded { "\u{eaf7} " } else { "\u{ea83} " };
@@ -162,7 +205,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
}
} else {
// File icons based on extension
let extension = item.node.path.extension()
let extension = item.path.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
@@ -184,12 +227,12 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
}
};
let name_spans = if in_search && !search_query.is_empty() {
highlight_search_matches(&item.node.name, &search_query, is_selected)
highlight_search_matches(&item.name, &search_query, is_selected)
} else {
vec![Span::raw(&item.node.name)]
vec![Span::raw(&item.name)]
};
let suffix = if item.node.is_dir { "/" } else { "" };
let suffix = if item.is_dir { "/" } else { "" };
let base_style = if is_selected {
// Selection bar: yellow/orange when in search (typing or viewing results), blue otherwise
@@ -198,7 +241,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
} else {
Theme::selected()
}
} else if state.marked_files.contains(&item.node.path) {
} else if state.marked_files.contains(&item.path) {
Theme::marked()
} else {
Theme::secondary()
@@ -226,14 +269,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
items.push(more_item);
}
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title("files")
.style(Theme::widget_border_style())
.title_style(Theme::title_style()),
);
let list = List::new(items);
let mut list_state = ListState::default();
// Don't set selection to avoid automatic scrolling - we manage scroll manually
@@ -242,9 +278,9 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
frame.render_stateful_widget(list, area, &mut list_state);
}
fn render_right_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
// Calculate visible height (subtract 2 for borders)
let visible_height = area.height.saturating_sub(2) as usize;
fn render_right_panel(frame: &mut Frame, state: &mut AppState, area: Rect, _tab_mode: bool) {
// Calculate visible height (no borders on individual panels now)
let visible_height = area.height as usize;
// Store visible height for keyboard navigation scroll calculations
state.playlist_visible_height = visible_height;
@@ -285,12 +321,17 @@ fn render_right_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
let is_selected = state.focus_playlist && idx == state.selected_playlist_index;
let is_playing = idx == state.playlist_index;
// Add playing indicator arrow
let indicator = if is_playing { "" } else { " " };
// Build line with search highlighting if searching
let line = if in_playlist_search && !playlist_search_query.is_empty() {
Line::from(highlight_search_matches(&filename, &playlist_search_query, is_selected))
let mut line_spans = vec![Span::raw(indicator)];
if in_playlist_search && !playlist_search_query.is_empty() {
line_spans.extend(highlight_search_matches(&filename, &playlist_search_query, is_selected));
} else {
Line::from(filename)
};
line_spans.push(Span::raw(filename));
}
let line = Line::from(line_spans);
let style = if is_selected && is_playing {
// Both selected and playing: selection bar with bold
@@ -328,20 +369,7 @@ fn render_right_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
playlist_items.push(more_item);
}
let playlist_title = if !state.playlist.is_empty() {
format!("playlist [{}/{}]", state.playlist_index + 1, state.playlist.len())
} else {
"playlist (empty)".to_string()
};
let playlist_widget = List::new(playlist_items)
.block(
Block::default()
.borders(Borders::ALL)
.title(playlist_title)
.style(Theme::widget_border_style())
.title_style(Theme::title_style()),
);
let playlist_widget = List::new(playlist_items);
let mut playlist_state = ListState::default();
// Don't set selection to avoid automatic scrolling - we manage scroll manually
@@ -462,9 +490,21 @@ fn render_title_bar(frame: &mut Frame, state: &AppState, player: &mut Player, ar
}
fn render_status_bar(frame: &mut Frame, state: &AppState, player: &mut Player, area: Rect) {
if state.search_mode {
// Calculate progress percentage for progress bar
let progress_percent = if state.current_duration > 0.0 {
(state.current_position / state.current_duration).clamp(0.0, 1.0)
} else {
0.0
};
// If playing and has duration, show progress bar with overlaid text
let player_state = player.get_player_state().unwrap_or(PlayerState::Stopped);
let show_progress_bar = player_state != PlayerState::Stopped && state.current_duration > 0.0;
// Determine text content based on mode
let status_text = if state.search_mode {
// Show search prompt with current query and match count - LEFT aligned
let search_text = if state.focus_playlist {
if state.focus_playlist {
// Searching in playlist
if !state.playlist_tab_search_results.is_empty() {
format!("/{}_ Playlist Search: {}/{}", state.search_query, state.playlist_tab_search_index + 1, state.playlist_tab_search_results.len())
@@ -482,28 +522,28 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, player: &mut Player, a
} else {
format!("/{}_", state.search_query)
}
};
let status_bar = Paragraph::new(search_text)
.style(Style::default().fg(Color::White).bg(Theme::background()));
frame.render_widget(status_bar, area);
}
} else if !state.search_matches.is_empty() {
// Show search navigation when file search results are active
let search_text = format!("/{} Search: {}/{}", state.search_query, state.search_match_index + 1, state.search_matches.len());
let status_bar = Paragraph::new(search_text)
.style(Style::default().fg(Color::White).bg(Theme::background()));
frame.render_widget(status_bar, area);
format!("/{} Search: {}/{}", state.search_query, state.search_match_index + 1, state.search_matches.len())
} else if !state.playlist_search_matches.is_empty() {
// Show search navigation when playlist search results are active
let search_text = format!("/{} Playlist Search: {}/{}", state.search_query, state.playlist_search_match_index + 1, state.playlist_search_matches.len());
let status_bar = Paragraph::new(search_text)
.style(Style::default().fg(Color::White).bg(Theme::background()));
frame.render_widget(status_bar, area);
format!("/{} Playlist Search: {}/{}", state.search_query, state.playlist_search_match_index + 1, state.playlist_search_matches.len())
} else if state.visual_mode {
// Show visual mode indicator
let visual_text = format!("-- VISUAL -- {} files marked", state.marked_files.len());
let status_bar = Paragraph::new(visual_text)
.style(Style::default().fg(Theme::foreground()).bg(Theme::background()));
format!("-- VISUAL -- {} files marked", state.marked_files.len())
} else {
String::new()
};
// If we have status text (search/visual mode), show it without progress bar
if !status_text.is_empty() {
let status_bar = Paragraph::new(status_text)
.style(Style::default().fg(Color::White).bg(Theme::background()));
frame.render_widget(status_bar, area);
} else if show_progress_bar {
// Show progress bar with metadata text overlay
render_progress_bar(frame, state, player, area, progress_percent);
} else {
// Normal mode: show media metadata if playing
// Split into left (artist/album/title) and right (technical info)
@@ -537,12 +577,6 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, player: &mut Player, a
right_parts.push(format!("{} Hz", samplerate));
}
if let Some(cache_dur) = player.cache_duration {
if cache_dur > 0.0 {
right_parts.push(format!("{:.1}s", cache_dur));
}
}
// Create layout for left and right sections
let chunks = Layout::default()
.direction(Direction::Horizontal)
@@ -575,6 +609,121 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, player: &mut Player, a
}
}
fn render_progress_bar(frame: &mut Frame, _state: &AppState, player: &mut Player, area: Rect, progress_percent: f64) {
// Get metadata to display
let mut right_parts = Vec::new();
// Right side: Bitrate | Codec | Sample rate (metrics that must always be visible)
if let Some(bitrate) = player.audio_bitrate {
right_parts.push(format!("{:.0} kbps", bitrate));
}
if let Some(ref codec) = player.audio_codec {
right_parts.push(codec.to_uppercase());
}
if let Some(samplerate) = player.sample_rate {
right_parts.push(format!("{} Hz", samplerate));
}
// Build right text
let right_text = if !right_parts.is_empty() {
format!("{} ", right_parts.join(" | "))
} else {
String::new()
};
// Calculate available space
let total_width = area.width as usize;
let right_text_len = right_text.chars().count();
// Reserve space: 1 char at start, gap between left and right
let available_for_left = total_width.saturating_sub(right_text_len).saturating_sub(2);
// Collect left side metadata
let mut left_fields = Vec::new();
if let Some(ref artist) = player.artist {
left_fields.push(("artist", artist.as_str()));
}
if let Some(ref album) = player.album {
left_fields.push(("album", album.as_str()));
}
if let Some(ref title) = player.media_title {
left_fields.push(("title", title.as_str()));
}
// Calculate space per field (divide available space among fields)
let left_text = if !left_fields.is_empty() {
let num_fields = left_fields.len();
let separator_space = (num_fields - 1) * 3; // " | " between fields
let available_for_fields = available_for_left.saturating_sub(separator_space);
let max_per_field = available_for_fields / num_fields;
// Truncate each field individually
let truncated_fields: Vec<String> = left_fields.iter().map(|(_name, value)| {
if value.chars().count() > max_per_field && max_per_field > 3 {
let mut s: String = value.chars().take(max_per_field - 3).collect();
s.push_str("...");
s
} else if value.chars().count() > max_per_field {
// Very tight space, just cut hard
value.chars().take(max_per_field).collect()
} else {
value.to_string()
}
}).collect();
format!(" {}", truncated_fields.join(" | "))
} else {
String::new()
};
// Calculate filled width based on progress
let filled_width = (total_width as f64 * progress_percent) as usize;
// Build the full line character by character with proper spacing
let left_chars: Vec<char> = left_text.chars().collect();
let right_chars: Vec<char> = right_text.chars().collect();
let right_start_pos = total_width.saturating_sub(right_chars.len());
// Build spans with progress bar background
let mut spans = Vec::new();
for i in 0..total_width {
// Determine which character to show
let ch = if i < left_chars.len() {
left_chars[i].to_string()
} else if i >= right_start_pos && i - right_start_pos < right_chars.len() {
right_chars[i - right_start_pos].to_string()
} else {
" ".to_string()
};
// Apply progress bar background
if i < filled_width {
// Filled portion - border color background with black text
spans.push(Span::styled(
ch,
Style::default()
.fg(Color::Black)
.bg(Theme::border())
));
} else {
// Unfilled portion - normal background
spans.push(Span::styled(
ch,
Style::default()
.fg(Theme::muted_text())
.bg(Theme::background())
));
}
}
let progress_line = Line::from(spans);
let progress_widget = Paragraph::new(progress_line);
frame.render_widget(progress_widget, area);
}
fn render_confirm_popup(frame: &mut Frame, title: &str, message: &str) {
// Create centered popup area
let area = frame.area();

View File

@@ -47,10 +47,6 @@ impl Theme {
Self::dim_foreground()
}
pub fn border_title() -> Color {
Self::bright_foreground()
}
pub fn highlight() -> Color {
Self::normal_blue()
}
@@ -68,12 +64,6 @@ impl Theme {
Style::default().fg(Self::border()).bg(Self::background())
}
pub fn title_style() -> Style {
Style::default()
.fg(Self::border_title())
.bg(Self::background())
}
pub fn secondary() -> Style {
Style::default()
.fg(Self::secondary_text())