Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 93741320ac | |||
| 7b4c664011 | |||
| 4529fad61d |
66
CLAUDE.md
66
CLAUDE.md
@@ -90,6 +90,72 @@ paths = [
|
|||||||
- `r` - Rescan library (manual refresh)
|
- `r` - Rescan library (manual refresh)
|
||||||
- `q` - Quit
|
- `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
|
### Technical Details
|
||||||
- **MPV IPC** - Communicates with mpv via Unix socket and JSON protocol
|
- **MPV IPC** - Communicates with mpv via Unix socket and JSON protocol
|
||||||
- **No Version Lock** - Uses mpv binary, not libmpv library (avoids version mismatch)
|
- **No Version Lock** - Uses mpv binary, not libmpv library (avoids version mismatch)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cm-player"
|
name = "cm-player"
|
||||||
version = "0.1.23"
|
version = "0.1.25"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[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"))
|
||||||
|
}
|
||||||
188
src/main.rs
188
src/main.rs
@@ -1,3 +1,4 @@
|
|||||||
|
mod api;
|
||||||
mod cache;
|
mod cache;
|
||||||
mod config;
|
mod config;
|
||||||
mod player;
|
mod player;
|
||||||
@@ -13,7 +14,8 @@ use crossterm::{
|
|||||||
};
|
};
|
||||||
use ratatui::{backend::CrosstermBackend, Terminal};
|
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||||
use state::{AppState, PlayerState};
|
use state::{AppState, PlayerState};
|
||||||
use std::io;
|
use std::io::{self, BufRead, BufReader, Write};
|
||||||
|
use std::os::unix::net::UnixStream;
|
||||||
use tracing_subscriber;
|
use tracing_subscriber;
|
||||||
|
|
||||||
// UI update intervals and thresholds
|
// 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
|
const DOUBLE_CLICK_MS: u128 = 500; // Double-click detection threshold
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
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
|
// Initialize logging to file to avoid interfering with TUI
|
||||||
let log_file = std::fs::OpenOptions::new()
|
let log_file = std::fs::OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
@@ -60,6 +68,11 @@ fn main() -> Result<()> {
|
|||||||
let mut state = AppState::new(cache, config);
|
let mut state = AppState::new(cache, config);
|
||||||
tracing::info!("State initialized");
|
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
|
// Setup terminal
|
||||||
enable_raw_mode()?;
|
enable_raw_mode()?;
|
||||||
tracing::info!("Raw mode enabled");
|
tracing::info!("Raw mode enabled");
|
||||||
@@ -71,7 +84,7 @@ fn main() -> Result<()> {
|
|||||||
tracing::info!("Terminal created, entering main loop");
|
tracing::info!("Terminal created, entering main loop");
|
||||||
|
|
||||||
// Run app (ensure terminal cleanup even on error)
|
// 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)
|
// Restore terminal (always run cleanup, even if result is Err)
|
||||||
let cleanup_result = (|| -> Result<()> {
|
let cleanup_result = (|| -> Result<()> {
|
||||||
@@ -93,12 +106,108 @@ fn main() -> Result<()> {
|
|||||||
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
|
// Common action functions that both keyboard and mouse handlers can call
|
||||||
|
|
||||||
fn action_toggle_folder(state: &mut AppState) {
|
fn action_toggle_folder(state: &mut AppState) {
|
||||||
if let Some(item) = state.get_selected_item() {
|
if let Some(item) = state.get_selected_item() {
|
||||||
if item.node.is_dir {
|
if item.is_dir {
|
||||||
let path = item.node.path.clone();
|
let path = item.path.clone();
|
||||||
if state.expanded_dirs.contains(&path) {
|
if state.expanded_dirs.contains(&path) {
|
||||||
// Folder is open, close it
|
// Folder is open, close it
|
||||||
state.collapse_selected();
|
state.collapse_selected();
|
||||||
@@ -320,6 +429,7 @@ fn run_app<B: ratatui::backend::Backend>(
|
|||||||
terminal: &mut Terminal<B>,
|
terminal: &mut Terminal<B>,
|
||||||
state: &mut AppState,
|
state: &mut AppState,
|
||||||
player: &mut player::Player,
|
player: &mut player::Player,
|
||||||
|
api_rx: std::sync::mpsc::Receiver<api::ApiCommand>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut metadata_update_counter = 0u32;
|
let mut metadata_update_counter = 0u32;
|
||||||
let mut last_position = 0.0f64;
|
let mut last_position = 0.0f64;
|
||||||
@@ -332,6 +442,74 @@ fn run_app<B: ratatui::backend::Backend>(
|
|||||||
loop {
|
loop {
|
||||||
let mut state_changed = false;
|
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)?;
|
||||||
|
state_changed = true;
|
||||||
|
}
|
||||||
|
api::ApiCommand::Prev => {
|
||||||
|
action_navigate_track(state, player, -1)?;
|
||||||
|
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)
|
// Check if mpv process died (e.g., user closed video window)
|
||||||
if !player.is_process_alive() {
|
if !player.is_process_alive() {
|
||||||
if let Some(player_state) = player.get_player_state() {
|
if let Some(player_state) = player.get_player_state() {
|
||||||
@@ -936,7 +1114,7 @@ fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: r
|
|||||||
if is_double_click {
|
if is_double_click {
|
||||||
// Double click = toggle folder or play file
|
// Double click = toggle folder or play file
|
||||||
if let Some(item) = state.get_selected_item() {
|
if let Some(item) = state.get_selected_item() {
|
||||||
if item.node.is_dir {
|
if item.is_dir {
|
||||||
action_toggle_folder(state);
|
action_toggle_folder(state);
|
||||||
} else {
|
} else {
|
||||||
action_play_selection(state, player)?;
|
action_play_selection(state, player)?;
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ impl Player {
|
|||||||
.arg("--no-terminal")
|
.arg("--no-terminal")
|
||||||
.arg("--profile=fast")
|
.arg("--profile=fast")
|
||||||
.arg("--audio-display=no") // Don't show cover art for audio files
|
.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()))
|
.arg(format!("--input-ipc-server={}", socket_path.display()))
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
|
|||||||
110
src/state/mod.rs
110
src/state/mod.rs
@@ -1,7 +1,7 @@
|
|||||||
use crate::cache::{Cache, FileTreeNode};
|
use crate::cache::{Cache, FileTreeNode};
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::path::PathBuf;
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
// Fuzzy match scoring bonuses
|
// Fuzzy match scoring bonuses
|
||||||
@@ -96,7 +96,9 @@ pub struct AppState {
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct FlattenedItem {
|
pub struct FlattenedItem {
|
||||||
pub node: FileTreeNode,
|
pub path: PathBuf,
|
||||||
|
pub name: String,
|
||||||
|
pub is_dir: bool,
|
||||||
pub depth: usize,
|
pub depth: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,11 +338,29 @@ impl AppState {
|
|||||||
self.flattened_items.get(self.selected_index)
|
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) {
|
pub fn collapse_selected(&mut self) {
|
||||||
let item = self.get_selected_item().cloned();
|
let item = self.get_selected_item().cloned();
|
||||||
if let Some(item) = item {
|
if let Some(item) = item {
|
||||||
if item.node.is_dir {
|
if item.is_dir {
|
||||||
let path = item.node.path.clone();
|
let path = item.path.clone();
|
||||||
let was_expanded = self.expanded_dirs.contains(&path);
|
let was_expanded = self.expanded_dirs.contains(&path);
|
||||||
|
|
||||||
if was_expanded {
|
if was_expanded {
|
||||||
@@ -348,7 +368,7 @@ impl AppState {
|
|||||||
self.expanded_dirs.remove(&path);
|
self.expanded_dirs.remove(&path);
|
||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
// Find the collapsed folder and select it
|
// 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;
|
self.selected_index = idx;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -358,19 +378,19 @@ impl AppState {
|
|||||||
self.expanded_dirs.remove(&parent_buf);
|
self.expanded_dirs.remove(&parent_buf);
|
||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
// Jump to parent folder
|
// 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;
|
self.selected_index = parent_idx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Close parent folder when on a file and jump to it
|
// 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();
|
let parent_buf = parent.to_path_buf();
|
||||||
self.expanded_dirs.remove(&parent_buf);
|
self.expanded_dirs.remove(&parent_buf);
|
||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
// Jump to parent folder
|
// 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;
|
self.selected_index = parent_idx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -380,8 +400,8 @@ impl AppState {
|
|||||||
|
|
||||||
pub fn expand_selected(&mut self) {
|
pub fn expand_selected(&mut self) {
|
||||||
if let Some(item) = self.get_selected_item() {
|
if let Some(item) = self.get_selected_item() {
|
||||||
if item.node.is_dir {
|
if item.is_dir {
|
||||||
let path = item.node.path.clone();
|
let path = item.path.clone();
|
||||||
self.expanded_dirs.insert(path);
|
self.expanded_dirs.insert(path);
|
||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
}
|
}
|
||||||
@@ -401,8 +421,8 @@ impl AppState {
|
|||||||
self.marked_files.clear();
|
self.marked_files.clear();
|
||||||
// Mark current file
|
// Mark current file
|
||||||
if let Some(item) = self.get_selected_item() {
|
if let Some(item) = self.get_selected_item() {
|
||||||
if !item.node.is_dir {
|
if !item.is_dir {
|
||||||
self.marked_files.insert(item.node.path.clone());
|
self.marked_files.insert(item.path.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -418,8 +438,8 @@ impl AppState {
|
|||||||
|
|
||||||
for i in start..=end {
|
for i in start..=end {
|
||||||
if let Some(item) = self.flattened_items.get(i) {
|
if let Some(item) = self.flattened_items.get(i) {
|
||||||
if !item.node.is_dir {
|
if !item.is_dir {
|
||||||
self.marked_files.insert(item.node.path.clone());
|
self.marked_files.insert(item.path.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -439,15 +459,19 @@ impl AppState {
|
|||||||
files.sort();
|
files.sort();
|
||||||
self.playlist.extend(files);
|
self.playlist.extend(files);
|
||||||
} else if let Some(item) = self.get_selected_item() {
|
} else if let Some(item) = self.get_selected_item() {
|
||||||
let node = item.node.clone();
|
let path = item.path.clone();
|
||||||
if node.is_dir {
|
let is_dir = item.is_dir;
|
||||||
// Add all files in directory (allow duplicates)
|
if is_dir {
|
||||||
let mut files = collect_files_from_node(&node);
|
// Look up the full node to get children
|
||||||
files.sort();
|
if let Some(node) = self.find_node_by_path(&path) {
|
||||||
self.playlist.extend(files);
|
// Add all files in directory (allow duplicates)
|
||||||
|
let mut files = collect_files_from_node(node);
|
||||||
|
files.sort();
|
||||||
|
self.playlist.extend(files);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Add single file (allow duplicates)
|
// 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;
|
self.current_file = None;
|
||||||
}
|
}
|
||||||
} else if let Some(item) = self.get_selected_item() {
|
} else if let Some(item) = self.get_selected_item() {
|
||||||
let node = item.node.clone();
|
let path = item.path.clone();
|
||||||
if node.is_dir {
|
let is_dir = item.is_dir;
|
||||||
// Play all files in directory
|
if is_dir {
|
||||||
self.playlist = collect_files_from_node(&node);
|
// Play all files in directory - look up node to get children
|
||||||
self.playlist_index = 0;
|
if let Some(node) = self.find_node_by_path(&path) {
|
||||||
self.playlist_scroll_offset = 0;
|
self.playlist = collect_files_from_node(node);
|
||||||
self.selected_playlist_index = 0;
|
self.playlist_index = 0;
|
||||||
if let Some(first) = self.playlist.first() {
|
self.playlist_scroll_offset = 0;
|
||||||
self.current_file = Some(first.clone());
|
self.selected_playlist_index = 0;
|
||||||
} else {
|
if let Some(first) = self.playlist.first() {
|
||||||
// Empty directory
|
self.current_file = Some(first.clone());
|
||||||
self.current_file = None;
|
} else {
|
||||||
|
// Empty directory
|
||||||
|
self.current_file = None;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Play single file
|
// Play single file
|
||||||
let path = node.path.clone();
|
|
||||||
self.playlist = vec![path.clone()];
|
self.playlist = vec![path.clone()];
|
||||||
self.playlist_index = 0;
|
self.playlist_index = 0;
|
||||||
self.playlist_scroll_offset = 0;
|
self.playlist_scroll_offset = 0;
|
||||||
@@ -674,7 +700,7 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Find the best match in the flattened list and jump to it
|
// 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;
|
self.selected_index = idx;
|
||||||
|
|
||||||
// Scroll to show the match
|
// Scroll to show the match
|
||||||
@@ -741,7 +767,7 @@ impl AppState {
|
|||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
|
|
||||||
// Find first match in flattened list
|
// 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;
|
self.selected_index = idx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -766,7 +792,7 @@ impl AppState {
|
|||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
|
|
||||||
// Find the path in current 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;
|
self.selected_index = idx;
|
||||||
|
|
||||||
// Scroll to show the match
|
// Scroll to show the match
|
||||||
@@ -813,7 +839,7 @@ impl AppState {
|
|||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
|
|
||||||
// Find the path in current 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;
|
self.selected_index = idx;
|
||||||
|
|
||||||
// Scroll to show the match
|
// Scroll to show the match
|
||||||
@@ -860,7 +886,7 @@ impl AppState {
|
|||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
|
|
||||||
// Find and select the match
|
// 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;
|
self.selected_index = idx;
|
||||||
|
|
||||||
// Scroll to show the match
|
// Scroll to show the match
|
||||||
@@ -903,7 +929,7 @@ impl AppState {
|
|||||||
self.rebuild_flattened_items();
|
self.rebuild_flattened_items();
|
||||||
|
|
||||||
// Find and select the match
|
// 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;
|
self.selected_index = idx;
|
||||||
|
|
||||||
// Scroll to show the match
|
// 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);
|
let is_expanded = expanded_dirs.contains(&node.path);
|
||||||
|
|
||||||
result.push(FlattenedItem {
|
result.push(FlattenedItem {
|
||||||
node: node.clone(),
|
path: node.path.clone(),
|
||||||
|
name: node.name.clone(),
|
||||||
|
is_dir: node.is_dir,
|
||||||
depth,
|
depth,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -142,15 +142,15 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
|||||||
.map(|(display_idx, item)| {
|
.map(|(display_idx, item)| {
|
||||||
let idx = state.scroll_offset + display_idx;
|
let idx = state.scroll_offset + display_idx;
|
||||||
let indent = " ".repeat(item.depth);
|
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
|
// Build name with search highlighting
|
||||||
// Only show selection bar when file panel has focus
|
// Only show selection bar when file panel has focus
|
||||||
let is_selected = !state.focus_playlist && idx == state.selected_index;
|
let is_selected = !state.focus_playlist && idx == state.selected_index;
|
||||||
|
|
||||||
// Add icon for directories and files
|
// Add icon for directories and files
|
||||||
let icon = if item.node.is_dir {
|
let icon = if item.is_dir {
|
||||||
let is_expanded = state.expanded_dirs.contains(&item.node.path);
|
let is_expanded = state.expanded_dirs.contains(&item.path);
|
||||||
// Nerd font folder icons: \u{eaf7} = open, \u{ea83} = closed
|
// Nerd font folder icons: \u{eaf7} = open, \u{ea83} = closed
|
||||||
let icon_char = if is_expanded { "\u{eaf7} " } else { "\u{ea83} " };
|
let icon_char = if is_expanded { "\u{eaf7} " } else { "\u{ea83} " };
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// File icons based on extension
|
// File icons based on extension
|
||||||
let extension = item.node.path.extension()
|
let extension = item.path.extension()
|
||||||
.and_then(|e| e.to_str())
|
.and_then(|e| e.to_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.to_lowercase();
|
.to_lowercase();
|
||||||
@@ -184,12 +184,12 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let name_spans = if in_search && !search_query.is_empty() {
|
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 {
|
} 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 {
|
let base_style = if is_selected {
|
||||||
// Selection bar: yellow/orange when in search (typing or viewing results), blue otherwise
|
// Selection bar: yellow/orange when in search (typing or viewing results), blue otherwise
|
||||||
@@ -198,7 +198,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
|
|||||||
} else {
|
} else {
|
||||||
Theme::selected()
|
Theme::selected()
|
||||||
}
|
}
|
||||||
} else if state.marked_files.contains(&item.node.path) {
|
} else if state.marked_files.contains(&item.path) {
|
||||||
Theme::marked()
|
Theme::marked()
|
||||||
} else {
|
} else {
|
||||||
Theme::secondary()
|
Theme::secondary()
|
||||||
|
|||||||
Reference in New Issue
Block a user