Optimize MPV polling with single batch query every 200ms
All checks were successful
Build and Release / build-and-release (push) Successful in 1m18s
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.
This commit is contained in:
parent
ccc762419f
commit
0ec328881a
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cm-player"
|
||||
version = "0.1.26"
|
||||
version = "0.1.27"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@ -50,22 +50,6 @@ impl ApiResponse {
|
||||
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
|
||||
|
||||
90
src/main.rs
90
src/main.rs
@ -19,9 +19,8 @@ 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<()> {
|
||||
@ -226,7 +225,7 @@ fn action_play_selection(state: &mut AppState, player: &mut player::Player, skip
|
||||
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 {
|
||||
@ -254,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);
|
||||
}
|
||||
}
|
||||
@ -287,7 +285,7 @@ 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(())
|
||||
@ -319,7 +317,7 @@ fn action_navigate_track(state: &mut AppState, player: &mut player::Player, dire
|
||||
*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);
|
||||
}
|
||||
}
|
||||
@ -328,7 +326,7 @@ fn action_navigate_track(state: &mut AppState, player: &mut player::Player, dire
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -351,6 +349,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
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 {
|
||||
@ -359,7 +358,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
*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);
|
||||
}
|
||||
}
|
||||
@ -367,7 +366,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -376,7 +375,7 @@ fn action_play_from_playlist(state: &mut AppState, player: &mut player::Player,
|
||||
*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);
|
||||
}
|
||||
}
|
||||
@ -388,7 +387,7 @@ fn action_play_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
|
||||
tracing::info!("Playing from playlist: {:?}", path);
|
||||
}
|
||||
}
|
||||
@ -438,7 +437,6 @@ fn run_app<B: ratatui::backend::Backend>(
|
||||
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;
|
||||
@ -529,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 {
|
||||
@ -572,9 +570,6 @@ fn run_app<B: ratatui::backend::Backend>(
|
||||
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;
|
||||
@ -587,16 +582,8 @@ 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
|
||||
// Skip this iteration if we just started a new track to avoid stale MPV values
|
||||
if skip_position_update {
|
||||
@ -1097,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
|
||||
@ -1164,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
|
||||
|
||||
@ -119,84 +119,75 @@ 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<()> {
|
||||
@ -242,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> {
|
||||
@ -330,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
|
||||
|
||||
166
src/ui/mod.rs
166
src/ui/mod.rs
@ -28,22 +28,53 @@ 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
|
||||
// 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 {
|
||||
(80, 20) // File panel focused: large file panel, small playlist
|
||||
Style::default().fg(Theme::bright_foreground())
|
||||
};
|
||||
|
||||
let content_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Percentage(left_percent), Constraint::Percentage(right_percent)])
|
||||
.split(main_chunks[1]);
|
||||
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
|
||||
@ -57,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>> {
|
||||
@ -115,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;
|
||||
|
||||
@ -233,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
|
||||
@ -249,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;
|
||||
|
||||
@ -335,20 +364,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
|
||||
@ -590,23 +606,9 @@ 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
|
||||
// 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));
|
||||
}
|
||||
@ -619,21 +621,59 @@ fn render_progress_bar(frame: &mut Frame, _state: &AppState, player: &mut Player
|
||||
right_parts.push(format!("{} Hz", samplerate));
|
||||
}
|
||||
|
||||
// Build text parts
|
||||
let left_text = if !left_parts.is_empty() {
|
||||
format!(" {}", left_parts.join(" | "))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// Build right text
|
||||
let right_text = if !right_parts.is_empty() {
|
||||
format!("{} ", right_parts.join(" | "))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// Calculate filled width based on progress
|
||||
// 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
|
||||
|
||||
@ -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())
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user