Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ccc762419f | |||
| 93741320ac | |||
| 7b4c664011 |
66
CLAUDE.md
66
CLAUDE.md
@@ -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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cm-player"
|
||||
version = "0.1.24"
|
||||
version = "0.1.26"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
136
src/api/mod.rs
Normal file
136
src/api/mod.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn success_with_data(data: serde_json::Value) -> Self {
|
||||
Self {
|
||||
success: true,
|
||||
message: None,
|
||||
data: Some(data),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(message: String) -> Self {
|
||||
Self {
|
||||
success: false,
|
||||
message: Some(message),
|
||||
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"))
|
||||
}
|
||||
260
src/main.rs
260
src/main.rs
@@ -1,3 +1,4 @@
|
||||
mod api;
|
||||
mod cache;
|
||||
mod config;
|
||||
mod player;
|
||||
@@ -13,7 +14,8 @@ 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
|
||||
@@ -23,6 +25,12 @@ 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<()> {
|
||||
// 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 +68,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 +84,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,6 +106,102 @@ 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) {
|
||||
@@ -110,9 +219,10 @@ 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()?;
|
||||
@@ -183,7 +293,7 @@ fn action_remove_from_playlist(state: &mut AppState, player: &mut player::Player
|
||||
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,6 +316,7 @@ 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();
|
||||
@@ -215,6 +326,7 @@ fn action_navigate_track(state: &mut AppState, player: &mut player::Player, dire
|
||||
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();
|
||||
tracing::info!("{} track (paused): {:?}", track_name, path);
|
||||
@@ -235,7 +347,7 @@ 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());
|
||||
|
||||
@@ -244,6 +356,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
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();
|
||||
@@ -252,6 +365,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
}
|
||||
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();
|
||||
tracing::info!("Jumped to track (paused): {:?}", path);
|
||||
@@ -259,6 +373,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
}
|
||||
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();
|
||||
@@ -269,6 +384,7 @@ 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()?;
|
||||
@@ -279,11 +395,11 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
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 +436,12 @@ 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 +450,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() {
|
||||
@@ -353,12 +539,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,6 +567,7 @@ 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()?;
|
||||
@@ -411,21 +598,26 @@ fn run_app<B: ratatui::backend::Backend>(
|
||||
}
|
||||
|
||||
// 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 +646,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 +666,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 +761,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 +812,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 +885,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 +938,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 +1007,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 {
|
||||
@@ -939,7 +1131,7 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
|
||||
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
|
||||
@@ -997,7 +1189,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;
|
||||
|
||||
@@ -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())
|
||||
@@ -200,6 +201,9 @@ impl Player {
|
||||
|
||||
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 +211,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);
|
||||
|
||||
152
src/ui/mod.rs
152
src/ui/mod.rs
@@ -29,9 +29,16 @@ pub fn render(frame: &mut Frame, state: &mut AppState, player: &mut Player) -> (
|
||||
.split(frame.area());
|
||||
|
||||
// Main content: left (files) | right (status + playlist)
|
||||
// Switch proportions based on focus: 80/20 for focused panel
|
||||
let (left_percent, right_percent) = if state.focus_playlist {
|
||||
(20, 80) // Playlist focused: small file panel, large playlist
|
||||
} else {
|
||||
(80, 20) // File panel focused: large file panel, small playlist
|
||||
};
|
||||
|
||||
let content_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||
.constraints([Constraint::Percentage(left_percent), Constraint::Percentage(right_percent)])
|
||||
.split(main_chunks[1]);
|
||||
|
||||
render_title_bar(frame, state, player, main_chunks[0]);
|
||||
@@ -462,9 +469,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 +501,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 +556,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 +588,97 @@ 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 left_parts = Vec::new();
|
||||
let mut right_parts = Vec::new();
|
||||
|
||||
// Left side: Artist | Album | Title
|
||||
if let Some(ref artist) = player.artist {
|
||||
left_parts.push(artist.clone());
|
||||
}
|
||||
|
||||
if let Some(ref album) = player.album {
|
||||
left_parts.push(album.clone());
|
||||
}
|
||||
|
||||
if let Some(ref title) = player.media_title {
|
||||
left_parts.push(title.clone());
|
||||
}
|
||||
|
||||
// Right side: Bitrate | Codec | Sample rate | Cache
|
||||
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 text parts
|
||||
let left_text = if !left_parts.is_empty() {
|
||||
format!(" {}", left_parts.join(" | "))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let right_text = if !right_parts.is_empty() {
|
||||
format!("{} ", right_parts.join(" | "))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// Calculate filled width based on progress
|
||||
let total_width = area.width as usize;
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user