4 Commits

Author SHA1 Message Date
59f9f548c1 Add playlist bounds validation and search mode visual indicator
All checks were successful
Build and Release / build-and-release (push) Successful in 1m1s
- Add bounds checking to prevent accessing invalid playlist indices
- Yellow/orange selection bar when in search mode
- Validate playlist index after navigation operations
- Handle empty playlists gracefully
2025-12-07 16:02:44 +01:00
248c5701fb Refactor mouse and keyboard handlers with shared actions
All checks were successful
Build and Release / build-and-release (push) Successful in 1m24s
- Extract common action functions to eliminate code duplication
- Mouse left-click toggles folder open/close
- Mouse right-click plays selection (identical to Enter key)
- Add confirmation popup for library refresh operation
- Improve popup visibility with Clear widget
2025-12-07 13:56:52 +01:00
0cef231cd3 Add metadata display and optimize CPU usage
All checks were successful
Build and Release / build-and-release (push) Successful in 58s
Metadata features:
- Display artist, album, title in bottom status bar (left-aligned)
- Display bitrate, codec, sample rate in bottom status bar (right-aligned)
- Fetch metadata from MPV using metadata/by-key properties
- Support both lowercase and uppercase metadata tags

Performance optimizations:
- Split property updates: fast updates (position/duration) vs slow (metadata)
- Update metadata only every 2 seconds instead of every 100ms
- Skip MPV property updates entirely when stopped
- Conditional UI redraws - only when state actually changes
- Variable poll rate: 200ms when stopped, 100ms when playing
- Position update throttling (0.5s minimum change)
- Reduces CPU usage from constant 10 FPS to ~0.1 FPS when idle
2025-12-06 23:07:33 +01:00
ae80e9a5db Improve search mode UX and fix playback bugs
All checks were successful
Build and Release / build-and-release (push) Successful in 51s
Search mode improvements:
- Search results persist until explicitly cleared
- Bold black highlighted chars on selection bar
- Fix fuzzy match scoring to select first occurrence
- Search info moved to bottom status bar

Keybinding changes:
- J/K for next/prev track (was n/p)
- H/L for seeking (was arrow keys)
- Simplified status bar shortcuts

UI improvements:
- Dynamic title bar color (green=playing, blue=paused, gray=stopped)
- White bold text for current playlist item
- Removed mouse capture for terminal text selection

Bug fixes:
- Fix auto-advance triggering multiple times when restarting from stopped state
2025-12-06 22:14:57 +01:00
6 changed files with 744 additions and 210 deletions

View File

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

View File

@@ -7,7 +7,7 @@ mod ui;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use crossterm::{ use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}, event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind, EnableMouseCapture, DisableMouseCapture},
execute, execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
}; };
@@ -75,45 +75,173 @@ async fn main() -> Result<()> {
result result
} }
// Common action functions that both keyboard and mouse handlers can call
fn action_toggle_folder(state: &mut AppState) {
if let Some(item) = state.get_selected_item() {
if item.node.is_dir {
let path = item.node.path.clone();
if state.expanded_dirs.contains(&path) {
// Folder is open, close it
state.collapse_selected();
} else {
// Folder is closed, open it
state.expand_selected();
}
}
}
}
fn action_play_selection(state: &mut AppState, player: &mut player::Player) -> Result<()> {
state.play_selection();
if let Some(ref path) = state.current_file {
player.play(path)?;
state.player_state = PlayerState::Playing;
player.update_metadata();
tracing::info!("Playing: {:?} (playlist: {} tracks)", path, state.playlist.len());
}
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
Ok(())
}
fn action_toggle_play_pause(state: &mut AppState, player: &mut player::Player) -> Result<()> {
match state.player_state {
PlayerState::Playing => {
player.pause()?;
state.player_state = PlayerState::Paused;
tracing::info!("Paused");
}
PlayerState::Paused => {
player.resume()?;
state.player_state = PlayerState::Playing;
tracing::info!("Resumed");
}
PlayerState::Stopped => {
// Restart playback from current playlist position
if !state.playlist.is_empty() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
state.player_state = PlayerState::Playing;
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata();
tracing::info!("Restarting playback: {:?}", path);
}
}
}
}
Ok(())
}
fn action_stop(state: &mut AppState, player: &mut player::Player) -> Result<()> {
player.stop()?;
state.player_state = PlayerState::Stopped;
state.current_position = 0.0;
state.current_duration = 0.0;
tracing::info!("Stopped");
Ok(())
}
async fn run_app<B: ratatui::backend::Backend>( async 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,
) -> Result<()> { ) -> Result<()> {
let mut metadata_update_counter = 0u32;
let mut last_position = 0.0f64;
let mut needs_redraw = true;
let mut title_bar_area = ratatui::layout::Rect::default();
let mut file_panel_area = ratatui::layout::Rect::default();
loop { loop {
let mut state_changed = false;
// 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() && state.player_state != PlayerState::Stopped { if !player.is_process_alive() && state.player_state != PlayerState::Stopped {
state.player_state = PlayerState::Stopped; state.player_state = PlayerState::Stopped;
state.current_position = 0.0; state.current_position = 0.0;
state.current_duration = 0.0; state.current_duration = 0.0;
state_changed = true;
} }
// Update player properties from MPV // Only update properties when playing or paused (not when stopped)
player.update_properties(); if state.player_state != PlayerState::Stopped {
player.update_properties();
// Update position and duration from player // Update metadata only every 20 iterations (~2 seconds) to reduce IPC calls
state.current_position = player.get_position().unwrap_or(0.0); metadata_update_counter += 1;
state.current_duration = player.get_duration().unwrap_or(0.0); if metadata_update_counter >= 20 {
player.update_metadata();
metadata_update_counter = 0;
state_changed = true;
}
// Check if track ended and play next // Update position and duration from player
if player.is_idle() && state.player_state == PlayerState::Playing { let new_position = player.get_position().unwrap_or(0.0);
if state.playlist_index + 1 < state.playlist.len() { let new_duration = player.get_duration().unwrap_or(0.0);
state.play_next();
if let Some(ref path) = state.current_file { // Only mark as changed if position moved by at least 0.5 seconds
player.play(path)?; if (new_position - last_position).abs() >= 0.5 {
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;
}
// Check if track ended and play next (but only if track was actually loaded)
if player.is_idle() && state.player_state == PlayerState::Playing && state.current_duration > 0.0 {
if state.playlist_index + 1 < state.playlist.len() {
state.play_next();
if let Some(ref path) = state.current_file {
player.play(path)?;
}
// Update metadata immediately when track changes
player.update_metadata();
metadata_update_counter = 0;
state_changed = true;
} else {
state.player_state = PlayerState::Stopped;
state_changed = true;
} }
} else {
state.player_state = PlayerState::Stopped;
} }
} }
terminal.draw(|f| ui::render(f, state))?; // Only redraw if something changed or forced
if needs_redraw || state_changed {
terminal.draw(|f| {
let areas = ui::render(f, state, player);
title_bar_area = areas.0;
file_panel_area = areas.1;
})?;
needs_redraw = false;
}
if event::poll(std::time::Duration::from_millis(100))? { // Poll for events - use longer timeout when stopped to reduce CPU
if let Event::Key(key) = event::read()? { let poll_duration = if state.player_state == PlayerState::Stopped {
if key.kind == KeyEventKind::Press { std::time::Duration::from_millis(200) // 5 FPS when stopped
handle_key_event(terminal, state, player, key).await?; } else {
std::time::Duration::from_millis(100) // 10 FPS when playing/paused
};
if event::poll(poll_duration)? {
match event::read()? {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
handle_key_event(terminal, state, player, key).await?;
needs_redraw = true; // Force redraw after key event
}
} }
Event::Mouse(mouse) => {
handle_mouse_event(state, mouse, title_bar_area, file_panel_area, player)?;
needs_redraw = true; // Force redraw after mouse event
}
_ => {}
} }
} }
@@ -126,6 +254,30 @@ async fn run_app<B: ratatui::backend::Backend>(
} }
async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, state: &mut AppState, player: &mut player::Player, key: KeyEvent) -> Result<()> { async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<B>, state: &mut AppState, player: &mut player::Player, key: KeyEvent) -> Result<()> {
// Handle confirmation popup
if state.show_refresh_confirm {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
state.show_refresh_confirm = false;
state.is_refreshing = true;
terminal.draw(|f| { let _ = ui::render(f, state, player); })?; // Show "Refreshing library..." immediately
tracing::info!("Rescanning...");
let cache_dir = cache::get_cache_dir()?;
let new_cache = scanner::scan_paths(&state.config.scan_paths.paths)?;
new_cache.save(&cache_dir)?;
state.cache = new_cache;
state.refresh_flattened_items();
state.is_refreshing = false;
tracing::info!("Rescan complete");
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
state.show_refresh_confirm = false;
}
_ => {}
}
return Ok(());
}
// Handle search mode separately // Handle search mode separately
if state.search_mode { if state.search_mode {
match key.code { match key.code {
@@ -157,10 +309,17 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
state.should_quit = true; state.should_quit = true;
} }
(KeyCode::Char('/'), _) => { (KeyCode::Char('/'), _) => {
state.enter_search_mode(); if state.search_mode && state.search_query.is_empty() {
// Exit search mode only if search query is blank
state.exit_search_mode();
} else if !state.search_mode {
state.enter_search_mode();
}
} }
(KeyCode::Esc, _) => { (KeyCode::Esc, _) => {
state.search_matches.clear(); if !state.search_matches.is_empty() {
state.search_matches.clear();
}
if state.visual_mode { if state.visual_mode {
state.visual_mode = false; state.visual_mode = false;
state.marked_files.clear(); state.marked_files.clear();
@@ -169,10 +328,19 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
(KeyCode::Char('n'), _) => { (KeyCode::Char('n'), _) => {
if !state.search_matches.is_empty() { if !state.search_matches.is_empty() {
state.next_search_match(); state.next_search_match();
} else if !state.playlist.is_empty() { }
// Advance to next track }
if state.playlist_index + 1 < state.playlist.len() { (KeyCode::Char('N'), KeyModifiers::SHIFT) => {
state.playlist_index += 1; if !state.search_matches.is_empty() {
state.prev_search_match();
}
}
(KeyCode::Char('J'), KeyModifiers::SHIFT) => {
// Next track
if !state.playlist.is_empty() && state.playlist_index + 1 < state.playlist.len() {
state.playlist_index += 1;
// Validate index before accessing playlist
if state.playlist_index < state.playlist.len() {
state.current_file = Some(state.playlist[state.playlist_index].clone()); state.current_file = Some(state.playlist[state.playlist_index].clone());
match state.player_state { match state.player_state {
@@ -180,6 +348,7 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
// Keep playing // Keep playing
if let Some(ref path) = state.current_file { if let Some(ref path) = state.current_file {
player.play(path)?; player.play(path)?;
player.update_metadata(); // Update metadata immediately
tracing::info!("Next track: {:?}", path); tracing::info!("Next track: {:?}", path);
} }
} }
@@ -187,6 +356,7 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
// Load but stay paused // Load but stay paused
if let Some(ref path) = state.current_file { if let Some(ref path) = state.current_file {
player.play(path)?; player.play(path)?;
player.update_metadata(); // Update metadata immediately
player.pause()?; player.pause()?;
tracing::info!("Next track (paused): {:?}", path); tracing::info!("Next track (paused): {:?}", path);
} }
@@ -199,8 +369,39 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
} }
} }
} }
(KeyCode::Char('N'), KeyModifiers::SHIFT) => { (KeyCode::Char('K'), KeyModifiers::SHIFT) => {
state.prev_search_match(); // Previous track
if !state.playlist.is_empty() && state.playlist_index > 0 {
state.playlist_index -= 1;
// Validate index before accessing playlist
if state.playlist_index < state.playlist.len() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
match state.player_state {
PlayerState::Playing => {
// Keep playing
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata(); // Update metadata immediately
tracing::info!("Previous track: {:?}", path);
}
}
PlayerState::Paused => {
// Load but stay paused
if let Some(ref path) = state.current_file {
player.play(path)?;
player.update_metadata(); // Update metadata immediately
player.pause()?;
tracing::info!("Previous track (paused): {:?}", path);
}
}
PlayerState::Stopped => {
// Just update current file, stay stopped
tracing::info!("Previous track selected (stopped): {:?}", state.current_file);
}
}
}
}
} }
(KeyCode::Char('d'), KeyModifiers::CONTROL) => { (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
state.page_down(); state.page_down();
@@ -233,85 +434,22 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
(KeyCode::Char('c'), _) => { (KeyCode::Char('c'), _) => {
state.clear_playlist(); state.clear_playlist();
} }
(KeyCode::Char('p'), _) => {
if !state.playlist.is_empty() && state.playlist_index > 0 {
state.playlist_index -= 1;
state.current_file = Some(state.playlist[state.playlist_index].clone());
match state.player_state {
PlayerState::Playing => {
// Keep playing
if let Some(ref path) = state.current_file {
player.play(path)?;
tracing::info!("Previous track: {:?}", path);
}
}
PlayerState::Paused => {
// Load but stay paused
if let Some(ref path) = state.current_file {
player.play(path)?;
player.pause()?;
tracing::info!("Previous track (paused): {:?}", path);
}
}
PlayerState::Stopped => {
// Just update current file, stay stopped
tracing::info!("Previous track selected (stopped): {:?}", state.current_file);
}
}
}
}
(KeyCode::Enter, _) => { (KeyCode::Enter, _) => {
state.play_selection(); action_play_selection(state, player)?;
if let Some(ref path) = state.current_file {
player.play(path)?;
tracing::info!("Playing: {:?} (playlist: {} tracks)", path, state.playlist.len());
}
if state.visual_mode {
state.visual_mode = false;
state.marked_files.clear();
}
} }
(KeyCode::Char('s'), _) => { (KeyCode::Char('s'), _) => {
// s: Stop playback action_stop(state, player)?;
player.stop()?;
state.player_state = PlayerState::Stopped;
state.current_position = 0.0;
state.current_duration = 0.0;
tracing::info!("Stopped");
} }
(KeyCode::Char(' '), _) => { (KeyCode::Char(' '), _) => {
match state.player_state { action_toggle_play_pause(state, player)?;
PlayerState::Playing => {
player.pause()?;
state.player_state = PlayerState::Paused;
tracing::info!("Paused");
}
PlayerState::Paused => {
player.resume()?;
state.player_state = PlayerState::Playing;
tracing::info!("Resumed");
}
PlayerState::Stopped => {
// Restart playback from current playlist position
if !state.playlist.is_empty() {
state.current_file = Some(state.playlist[state.playlist_index].clone());
state.player_state = PlayerState::Playing;
if let Some(ref path) = state.current_file {
player.play(path)?;
tracing::info!("Restarting playback: {:?}", path);
}
}
}
}
} }
(KeyCode::Left, _) => { (KeyCode::Char('H'), KeyModifiers::SHIFT) => {
if state.player_state != PlayerState::Stopped { if state.player_state != PlayerState::Stopped {
player.seek(-10.0)?; player.seek(-10.0)?;
tracing::info!("Seek backward 10s"); tracing::info!("Seek backward 10s");
} }
} }
(KeyCode::Right, _) => { (KeyCode::Char('L'), KeyModifiers::SHIFT) => {
if state.player_state != PlayerState::Stopped { if state.player_state != PlayerState::Stopped {
player.seek(10.0)?; player.seek(10.0)?;
tracing::info!("Seek forward 10s"); tracing::info!("Seek forward 10s");
@@ -330,19 +468,79 @@ async fn handle_key_event<B: ratatui::backend::Backend>(terminal: &mut Terminal<
tracing::info!("Volume: {}%", new_volume); tracing::info!("Volume: {}%", new_volume);
} }
(KeyCode::Char('r'), _) => { (KeyCode::Char('r'), _) => {
state.is_refreshing = true; state.show_refresh_confirm = true;
terminal.draw(|f| ui::render(f, state))?; // Show "Refreshing library..." immediately
tracing::info!("Rescanning...");
let cache_dir = cache::get_cache_dir()?;
let new_cache = scanner::scan_paths(&state.config.scan_paths.paths)?;
new_cache.save(&cache_dir)?;
state.cache = new_cache;
state.refresh_flattened_items();
state.is_refreshing = false;
tracing::info!("Rescan complete");
} }
_ => {} _ => {}
} }
Ok(()) Ok(())
} }
fn handle_mouse_event(state: &mut AppState, mouse: MouseEvent, title_bar_area: ratatui::layout::Rect, file_panel_area: ratatui::layout::Rect, player: &mut player::Player) -> Result<()> {
use crossterm::event::MouseButton;
match mouse.kind {
MouseEventKind::ScrollDown => {
// Scroll down - move selection down
state.move_selection_down();
}
MouseEventKind::ScrollUp => {
// Scroll up - move selection up
state.move_selection_up();
}
MouseEventKind::Down(button) => {
let x = mouse.column;
let y = mouse.row;
// Check if click is on title bar
if x >= title_bar_area.x
&& x < title_bar_area.x + title_bar_area.width
&& y >= title_bar_area.y
&& y < title_bar_area.y + title_bar_area.height
{
match button {
MouseButton::Left => {
// Left click on title bar = play/pause toggle
action_toggle_play_pause(state, player)?;
}
MouseButton::Right => {
// Right click on title bar = stop
action_stop(state, player)?;
}
_ => {}
}
}
// Check if click is within file panel area
else if x >= file_panel_area.x
&& x < file_panel_area.x + file_panel_area.width
&& y >= file_panel_area.y
&& y < file_panel_area.y + file_panel_area.height
{
// Calculate which item was clicked (accounting for borders and scroll offset)
// Border takes 1 line at top, so subtract 1 from y position
let relative_y = (y - file_panel_area.y).saturating_sub(1);
let clicked_index = state.scroll_offset + relative_y as usize;
// Set selection to clicked item if valid
if clicked_index < state.flattened_items.len() {
state.selected_index = clicked_index;
// Handle different mouse buttons
match button {
MouseButton::Left => {
// Left click = toggle folder open/close
action_toggle_folder(state);
}
MouseButton::Right => {
// Right click = play (like Enter key)
action_play_selection(state, player)?;
}
_ => {}
}
}
}
}
_ => {}
}
Ok(())
}

View File

@@ -15,6 +15,12 @@ pub struct Player {
duration: f64, duration: f64,
is_paused: bool, is_paused: bool,
is_idle: bool, is_idle: bool,
pub media_title: Option<String>,
pub artist: Option<String>,
pub album: Option<String>,
pub audio_codec: Option<String>,
pub audio_bitrate: Option<f64>,
pub sample_rate: Option<i64>,
} }
impl Player { impl Player {
@@ -50,6 +56,12 @@ impl Player {
duration: 0.0, duration: 0.0,
is_paused: false, is_paused: false,
is_idle: true, is_idle: true,
media_title: None,
artist: None,
album: None,
audio_codec: None,
audio_bitrate: None,
sample_rate: None,
}) })
} }
@@ -101,6 +113,12 @@ impl Player {
self.position = 0.0; self.position = 0.0;
self.duration = 0.0; self.duration = 0.0;
self.is_paused = false; self.is_paused = false;
self.media_title = None;
self.artist = None;
self.album = None;
self.audio_codec = None;
self.audio_bitrate = None;
self.sample_rate = None;
// Wait for socket to be created and mpv to be ready // Wait for socket to be created and mpv to be ready
std::thread::sleep(Duration::from_millis(800)); std::thread::sleep(Duration::from_millis(800));
@@ -230,6 +248,63 @@ impl Player {
} }
} }
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());
}
}
// 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());
}
}
// 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());
}
}
// 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());
}
}
// Update audio codec
if let Some(val) = self.get_property("audio-codec-name") {
self.audio_codec = val.as_str().map(|s| s.to_string());
}
// 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);
}
// Update sample rate
if let Some(val) = self.get_property("audio-params/samplerate") {
self.sample_rate = val.as_i64();
}
}
pub fn get_position(&self) -> Option<f64> { pub fn get_position(&self) -> Option<f64> {
Some(self.position) Some(self.position)
} }

View File

@@ -29,12 +29,14 @@ pub struct AppState {
pub is_refreshing: bool, pub is_refreshing: bool,
pub search_mode: bool, pub search_mode: bool,
pub search_query: String, pub search_query: String,
pub search_matches: Vec<usize>, pub search_matches: Vec<PathBuf>,
pub search_match_index: usize, pub search_match_index: usize,
pub tab_search_results: Vec<PathBuf>, pub tab_search_results: Vec<PathBuf>,
pub tab_search_index: usize, pub tab_search_index: usize,
pub visual_mode: bool, pub visual_mode: bool,
pub visual_anchor: usize, pub visual_anchor: usize,
pub saved_expanded_dirs: HashSet<PathBuf>,
pub show_refresh_confirm: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -75,6 +77,8 @@ impl AppState {
tab_search_index: 0, tab_search_index: 0,
visual_mode: false, visual_mode: false,
visual_anchor: 0, visual_anchor: 0,
saved_expanded_dirs: HashSet::new(),
show_refresh_confirm: false,
} }
} }
@@ -139,9 +143,13 @@ impl AppState {
let was_expanded = self.expanded_dirs.contains(&path); let was_expanded = self.expanded_dirs.contains(&path);
if was_expanded { if was_expanded {
// Close the expanded folder // Close the expanded folder and keep selection on it
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
if let Some(idx) = self.flattened_items.iter().position(|i| i.node.path == path) {
self.selected_index = idx;
}
} else { } else {
// Folder is collapsed, close parent instead and jump to it // Folder is collapsed, close parent instead and jump to it
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
@@ -263,6 +271,10 @@ impl AppState {
if let Some(first) = self.playlist.first() { if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone()); self.current_file = Some(first.clone());
self.player_state = PlayerState::Playing; self.player_state = PlayerState::Playing;
} else {
// Empty playlist
self.current_file = None;
self.player_state = PlayerState::Stopped;
} }
} else if let Some(item) = self.get_selected_item() { } else if let Some(item) = self.get_selected_item() {
let node = item.node.clone(); let node = item.node.clone();
@@ -273,6 +285,10 @@ impl AppState {
if let Some(first) = self.playlist.first() { if let Some(first) = self.playlist.first() {
self.current_file = Some(first.clone()); self.current_file = Some(first.clone());
self.player_state = PlayerState::Playing; self.player_state = PlayerState::Playing;
} else {
// Empty directory
self.current_file = None;
self.player_state = PlayerState::Stopped;
} }
} else { } else {
// Play single file // Play single file
@@ -288,8 +304,11 @@ impl AppState {
pub fn play_next(&mut self) { pub fn play_next(&mut self) {
if self.playlist_index + 1 < self.playlist.len() { if self.playlist_index + 1 < self.playlist.len() {
self.playlist_index += 1; self.playlist_index += 1;
self.current_file = Some(self.playlist[self.playlist_index].clone()); // Double-check index is valid before accessing
self.player_state = PlayerState::Playing; if self.playlist_index < self.playlist.len() {
self.current_file = Some(self.playlist[self.playlist_index].clone());
self.player_state = PlayerState::Playing;
}
} }
} }
@@ -298,7 +317,7 @@ impl AppState {
self.rebuild_flattened_items(); self.rebuild_flattened_items();
} }
fn rebuild_flattened_items(&mut self) { pub fn rebuild_flattened_items(&mut self) {
self.flattened_items = flatten_tree(&self.cache.file_tree, 0, &self.expanded_dirs); self.flattened_items = flatten_tree(&self.cache.file_tree, 0, &self.expanded_dirs);
if self.selected_index >= self.flattened_items.len() { if self.selected_index >= self.flattened_items.len() {
self.selected_index = self.flattened_items.len().saturating_sub(1); self.selected_index = self.flattened_items.len().saturating_sub(1);
@@ -312,12 +331,17 @@ impl AppState {
self.search_match_index = 0; self.search_match_index = 0;
self.tab_search_results.clear(); self.tab_search_results.clear();
self.tab_search_index = 0; self.tab_search_index = 0;
// Save current folder state
self.saved_expanded_dirs = self.expanded_dirs.clone();
} }
pub fn exit_search_mode(&mut self) { pub fn exit_search_mode(&mut self) {
self.search_mode = false; self.search_mode = false;
self.tab_search_results.clear(); self.tab_search_results.clear();
self.tab_search_index = 0; self.tab_search_index = 0;
// Restore folder state from before search
self.expanded_dirs = self.saved_expanded_dirs.clone();
self.rebuild_flattened_items();
} }
pub fn append_search_char(&mut self, c: char) { pub fn append_search_char(&mut self, c: char) {
@@ -347,29 +371,34 @@ impl AppState {
return; return;
} }
// Sort by score (highest first) // Add index to preserve original tree order when scores are equal
matching_paths_with_scores.sort_by(|a, b| b.1.cmp(&a.1)); let mut indexed_matches: Vec<(PathBuf, i32, usize)> = matching_paths_with_scores
.into_iter()
.enumerate()
.map(|(idx, (path, score))| (path, score, idx))
.collect();
// Sort by score (highest first), then by original index to prefer first occurrence
indexed_matches.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.2.cmp(&b.2)));
// Store all matches for tab completion // Store all matches for tab completion
self.tab_search_results = matching_paths_with_scores.iter().map(|(path, _)| path.clone()).collect(); self.tab_search_results = indexed_matches.iter().map(|(path, _, _)| path.clone()).collect();
self.tab_search_index = 0; self.tab_search_index = 0;
// Expand parent directories of ALL matches (not just best match) // Close all folders and expand only for the best match
// This ensures folders deep in the tree become visible self.expanded_dirs.clear();
for (path, _) in &matching_paths_with_scores { let best_match = self.tab_search_results[0].clone();
let mut parent = path.parent(); let mut parent = best_match.parent();
while let Some(p) = parent { while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf()); self.expanded_dirs.insert(p.to_path_buf());
parent = p.parent(); parent = p.parent();
}
} }
// Rebuild flattened items // Rebuild flattened items
self.rebuild_flattened_items(); self.rebuild_flattened_items();
// Find the best match in the flattened list and jump to it // Find the best match in the flattened list and jump to it
let best_match = &self.tab_search_results[0]; 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.node.path == best_match) {
self.selected_index = idx; self.selected_index = idx;
} }
} }
@@ -380,7 +409,7 @@ impl AppState {
return; return;
} }
// Collect all matching paths with scores // Collect all matching paths with scores and preserve order
let mut matching_paths_with_scores = Vec::new(); let mut matching_paths_with_scores = Vec::new();
collect_matching_paths(&self.cache.file_tree, &self.search_query, &mut matching_paths_with_scores); collect_matching_paths(&self.cache.file_tree, &self.search_query, &mut matching_paths_with_scores);
@@ -389,35 +418,43 @@ impl AppState {
return; return;
} }
// Sort by score (highest first) // Add index to preserve original tree order when scores are equal
matching_paths_with_scores.sort_by(|a, b| b.1.cmp(&a.1)); let mut indexed_matches: Vec<(PathBuf, i32, usize)> = matching_paths_with_scores
.into_iter()
.enumerate()
.map(|(idx, (path, score))| (path, score, idx))
.collect();
// Sort by score (highest first), then by original index to prefer first occurrence
indexed_matches.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.2.cmp(&b.2)));
let matching_paths_with_scores: Vec<(PathBuf, i32)> = indexed_matches
.into_iter()
.map(|(path, score, _)| (path, score))
.collect();
let matching_paths: Vec<PathBuf> = matching_paths_with_scores.iter().map(|(path, _)| path.clone()).collect(); let matching_paths: Vec<PathBuf> = matching_paths_with_scores.iter().map(|(path, _)| path.clone()).collect();
// Expand all parent directories // Store matching paths (not indices, as they change when folders collapse)
for path in &matching_paths { self.search_matches = matching_paths;
let mut parent = path.parent();
if !self.search_matches.is_empty() {
self.search_match_index = 0;
// Close all folders and expand only for first match
self.expanded_dirs.clear();
let first_match = self.search_matches[0].clone();
let mut parent = first_match.parent();
while let Some(p) = parent { while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf()); self.expanded_dirs.insert(p.to_path_buf());
parent = p.parent(); parent = p.parent();
} }
}
// Rebuild flattened items // Rebuild flattened items
self.rebuild_flattened_items(); self.rebuild_flattened_items();
// Find indices of matches in the flattened list // Find first match in flattened list
self.search_matches = matching_paths if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == first_match) {
.iter() self.selected_index = idx;
.filter_map(|path| { }
self.flattened_items
.iter()
.position(|item| &item.node.path == path)
})
.collect();
if !self.search_matches.is_empty() {
self.search_match_index = 0;
self.selected_index = self.search_matches[0];
} }
self.search_mode = false; self.search_mode = false;
@@ -426,7 +463,23 @@ impl AppState {
pub fn next_search_match(&mut self) { pub fn next_search_match(&mut self) {
if !self.search_matches.is_empty() { if !self.search_matches.is_empty() {
self.search_match_index = (self.search_match_index + 1) % self.search_matches.len(); self.search_match_index = (self.search_match_index + 1) % self.search_matches.len();
self.selected_index = self.search_matches[self.search_match_index]; let target_path = self.search_matches[self.search_match_index].clone();
// Close all folders and expand only for this match
self.expanded_dirs.clear();
let mut parent = target_path.parent();
while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf());
parent = p.parent();
}
// Rebuild flattened items
self.rebuild_flattened_items();
// Find the path in current flattened items
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == target_path) {
self.selected_index = idx;
}
} }
} }
@@ -437,7 +490,23 @@ impl AppState {
} else { } else {
self.search_match_index -= 1; self.search_match_index -= 1;
} }
self.selected_index = self.search_matches[self.search_match_index]; let target_path = self.search_matches[self.search_match_index].clone();
// Close all folders and expand only for this match
self.expanded_dirs.clear();
let mut parent = target_path.parent();
while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf());
parent = p.parent();
}
// Rebuild flattened items
self.rebuild_flattened_items();
// Find the path in current flattened items
if let Some(idx) = self.flattened_items.iter().position(|item| item.node.path == target_path) {
self.selected_index = idx;
}
} }
} }
@@ -450,7 +519,8 @@ impl AppState {
self.tab_search_index = (self.tab_search_index + 1) % self.tab_search_results.len(); self.tab_search_index = (self.tab_search_index + 1) % self.tab_search_results.len();
let next_match = self.tab_search_results[self.tab_search_index].clone(); let next_match = self.tab_search_results[self.tab_search_index].clone();
// Expand parent directories // Close all folders and expand only for this match
self.expanded_dirs.clear();
let mut parent = next_match.parent(); let mut parent = next_match.parent();
while let Some(p) = parent { while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf()); self.expanded_dirs.insert(p.to_path_buf());
@@ -479,7 +549,8 @@ impl AppState {
} }
let prev_match = self.tab_search_results[self.tab_search_index].clone(); let prev_match = self.tab_search_results[self.tab_search_index].clone();
// Expand parent directories // Close all folders and expand only for this match
self.expanded_dirs.clear();
let mut parent = prev_match.parent(); let mut parent = prev_match.parent();
while let Some(p) = parent { while let Some(p) = parent {
self.expanded_dirs.insert(p.to_path_buf()); self.expanded_dirs.insert(p.to_path_buf());
@@ -570,9 +641,6 @@ fn fuzzy_match(text: &str, query: &str) -> Option<i32> {
} }
} }
// Bonus for shorter strings (better matches)
score += 100 - text_lower.len() as i32;
Some(score) Some(score)
} }

View File

@@ -1,16 +1,17 @@
mod theme; mod theme;
use crate::player::Player;
use crate::state::{AppState, PlayerState}; use crate::state::{AppState, PlayerState};
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect}, layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, List, ListItem, ListState, Paragraph}, widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Clear},
Frame, Frame,
}; };
use theme::Theme; use theme::Theme;
pub fn render(frame: &mut Frame, state: &mut AppState) { pub fn render(frame: &mut Frame, state: &mut AppState, player: &Player) -> (Rect, Rect) {
// Clear background // Clear background
frame.render_widget( frame.render_widget(
Block::default().style(Theme::secondary()), Block::default().style(Theme::secondary()),
@@ -36,7 +37,69 @@ pub fn render(frame: &mut Frame, state: &mut AppState) {
render_title_bar(frame, state, main_chunks[0]); render_title_bar(frame, state, main_chunks[0]);
render_file_panel(frame, state, content_chunks[0]); render_file_panel(frame, state, content_chunks[0]);
render_right_panel(frame, state, content_chunks[1]); render_right_panel(frame, state, content_chunks[1]);
render_status_bar(frame, state, main_chunks[2]); render_status_bar(frame, state, player, main_chunks[2]);
// Show confirmation popup if needed
if state.show_refresh_confirm {
render_confirm_popup(frame, "Refresh library?", "This may take a while");
}
// Return title bar area and file panel area for mouse event handling
(main_chunks[0], content_chunks[0])
}
fn highlight_search_matches<'a>(text: &str, query: &str, is_selected: bool) -> Vec<Span<'a>> {
let query_lower = query.to_lowercase();
let mut spans = Vec::new();
let mut query_chars = query_lower.chars();
let mut current_query_char = query_chars.next();
let mut current_segment = String::new();
for ch in text.chars() {
let ch_lower = ch.to_lowercase().next().unwrap();
if let Some(query_ch) = current_query_char {
if ch_lower == query_ch {
// Found a match - flush current segment
if !current_segment.is_empty() {
spans.push(Span::raw(current_segment.clone()));
current_segment.clear();
}
// Add matched character with styling
if is_selected {
// On selected row: bold black text on selection bar (yellow or blue)
spans.push(Span::styled(
ch.to_string(),
Style::default()
.fg(Theme::background())
.add_modifier(Modifier::BOLD),
));
} else {
// Other rows: just green text
spans.push(Span::styled(
ch.to_string(),
Style::default().fg(Theme::success()),
));
}
// Move to next query character
current_query_char = query_chars.next();
} else {
// No match - add to current segment
current_segment.push(ch);
}
} else {
// No more query characters to match
current_segment.push(ch);
}
}
// Flush remaining segment
if !current_segment.is_empty() {
spans.push(Span::raw(current_segment));
}
spans
} }
fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) { fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
@@ -44,6 +107,9 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
let visible_height = area.height.saturating_sub(2) as usize; let visible_height = area.height.saturating_sub(2) as usize;
state.update_scroll_offset(visible_height); state.update_scroll_offset(visible_height);
let in_search = state.search_mode || !state.search_matches.is_empty();
let search_query = if in_search { state.search_query.to_lowercase() } else { String::new() };
let items: Vec<ListItem> = state let items: Vec<ListItem> = state
.flattened_items .flattened_items
.iter() .iter()
@@ -51,20 +117,53 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
.map(|(idx, item)| { .map(|(idx, item)| {
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.node.path) { "* " } else { "" };
let suffix = if item.node.is_dir { "/" } else { "" };
let text = format!("{}{}{}{}", indent, mark, item.node.name, suffix);
let style = if idx == state.selected_index { // Build name with search highlighting
Theme::selected() let is_selected = idx == state.selected_index;
} else if item.node.is_dir {
Theme::directory() // Add folder icon for directories
let icon = if item.node.is_dir {
// Bold black icon on selection bar, blue otherwise
if is_selected {
Span::styled("", Style::default().fg(Theme::background()).add_modifier(Modifier::BOLD))
} else {
Span::styled("", Style::default().fg(Theme::highlight()))
}
} else {
Span::raw(" ")
};
let name_spans = if in_search && !search_query.is_empty() {
highlight_search_matches(&item.node.name, &search_query, is_selected)
} else {
vec![Span::raw(&item.node.name)]
};
let suffix = if item.node.is_dir { "/" } else { "" };
let base_style = if is_selected {
// Selection bar: yellow/orange when in search (typing or viewing results), blue otherwise
if in_search {
Theme::search_selected()
} else {
Theme::selected()
}
} else if state.marked_files.contains(&item.node.path) { } else if state.marked_files.contains(&item.node.path) {
Theme::marked() Theme::marked()
} else { } else {
Theme::secondary() Theme::secondary()
}; };
ListItem::new(text).style(style) let mut line_spans = vec![
Span::raw(indent),
Span::raw(mark),
icon,
];
line_spans.extend(name_spans);
line_spans.push(Span::raw(suffix));
let line = Line::from(line_spans);
ListItem::new(line).style(base_style)
}) })
.collect(); .collect();
@@ -78,6 +177,7 @@ fn render_file_panel(frame: &mut Frame, state: &mut AppState, area: Rect) {
); );
let mut list_state = ListState::default(); let mut list_state = ListState::default();
// Always show selection bar (yellow/orange in search mode, blue otherwise)
list_state.select(Some(state.selected_index)); list_state.select(Some(state.selected_index));
*list_state.offset_mut() = state.scroll_offset; *list_state.offset_mut() = state.scroll_offset;
frame.render_stateful_widget(list, area, &mut list_state); frame.render_stateful_widget(list, area, &mut list_state);
@@ -96,21 +196,11 @@ fn render_right_panel(frame: &mut Frame, state: &AppState, area: Rect) {
.unwrap_or_else(|| path.to_string_lossy().to_string()); .unwrap_or_else(|| path.to_string_lossy().to_string());
let style = if idx == state.playlist_index { let style = if idx == state.playlist_index {
// Color based on player state with bold text // Current file: white bold
match state.player_state { Style::default()
PlayerState::Playing => Style::default() .fg(Theme::bright_foreground())
.fg(Theme::success()) // Green text .bg(Theme::background())
.bg(Theme::background()) .add_modifier(Modifier::BOLD)
.add_modifier(Modifier::BOLD),
PlayerState::Paused => Style::default()
.fg(Theme::highlight()) // Blue text
.bg(Theme::background())
.add_modifier(Modifier::BOLD),
PlayerState::Stopped => Style::default()
.fg(Theme::warning()) // Yellow/orange text
.bg(Theme::background())
.add_modifier(Modifier::BOLD),
}
} else { } else {
Theme::secondary() Theme::secondary()
}; };
@@ -140,7 +230,11 @@ fn render_right_panel(frame: &mut Frame, state: &AppState, area: Rect) {
} }
fn render_title_bar(frame: &mut Frame, state: &AppState, area: Rect) { fn render_title_bar(frame: &mut Frame, state: &AppState, area: Rect) {
let background_color = Theme::success(); // Green for normal operation let background_color = match state.player_state {
PlayerState::Playing => Theme::success(), // Green for playing
PlayerState::Paused => Theme::highlight(), // Blue for paused
PlayerState::Stopped => Theme::dim_foreground(), // Gray for stopped
};
// Split the title bar into left and right sections // Split the title bar into left and right sections
let chunks = Layout::default() let chunks = Layout::default()
@@ -217,29 +311,11 @@ fn render_title_bar(frame: &mut Frame, state: &AppState, area: Rect) {
// Volume // Volume
right_spans.push(Span::styled( right_spans.push(Span::styled(
format!(" • Vol: {}%", state.volume), format!(" • Vol: {}% ", state.volume),
Style::default() Style::default()
.fg(Theme::background()) .fg(Theme::background())
.bg(background_color) .bg(background_color)
)); ));
// Add search info if active
if !state.search_matches.is_empty() {
right_spans.push(Span::styled(
format!(" • Search: {}/{} ", state.search_match_index + 1, state.search_matches.len()),
Style::default()
.fg(Theme::background())
.bg(background_color)
.add_modifier(Modifier::BOLD)
));
} else {
right_spans.push(Span::styled(
" ",
Style::default()
.fg(Theme::background())
.bg(background_color)
));
}
} }
let right_title = Paragraph::new(Line::from(right_spans)) let right_title = Paragraph::new(Line::from(right_spans))
@@ -248,7 +324,7 @@ fn render_title_bar(frame: &mut Frame, state: &AppState, area: Rect) {
frame.render_widget(right_title, chunks[1]); frame.render_widget(right_title, chunks[1]);
} }
fn render_status_bar(frame: &mut Frame, state: &AppState, area: Rect) { fn render_status_bar(frame: &mut Frame, state: &AppState, player: &Player, area: Rect) {
if state.search_mode { if state.search_mode {
// Show search prompt with current query and match count - LEFT aligned // Show search prompt with current query and match count - LEFT aligned
let search_text = if !state.tab_search_results.is_empty() { let search_text = if !state.tab_search_results.is_empty() {
@@ -261,6 +337,12 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, area: Rect) {
let status_bar = Paragraph::new(search_text) let status_bar = Paragraph::new(search_text)
.style(Style::default().fg(Theme::foreground()).bg(Theme::background())); .style(Style::default().fg(Theme::foreground()).bg(Theme::background()));
frame.render_widget(status_bar, area); frame.render_widget(status_bar, area);
} else if !state.search_matches.is_empty() {
// Show search navigation when search results are active
let search_text = format!("Search: {}/{} • n: Next • N: Prev • Esc: Clear", state.search_match_index + 1, state.search_matches.len());
let status_bar = Paragraph::new(search_text)
.style(Style::default().fg(Theme::foreground()).bg(Theme::background()));
frame.render_widget(status_bar, area);
} else if state.visual_mode { } else if state.visual_mode {
// Show visual mode indicator // Show visual mode indicator
let visual_text = format!("-- VISUAL -- {} files marked", state.marked_files.len()); let visual_text = format!("-- VISUAL -- {} files marked", state.marked_files.len());
@@ -268,11 +350,122 @@ fn render_status_bar(frame: &mut Frame, state: &AppState, area: Rect) {
.style(Style::default().fg(Theme::foreground()).bg(Theme::background())); .style(Style::default().fg(Theme::foreground()).bg(Theme::background()));
frame.render_widget(status_bar, area); frame.render_widget(status_bar, area);
} else { } else {
// Normal mode shortcuts (always shown when not in search or visual mode) // Normal mode: show media metadata if playing
let shortcuts = "/: Search • v: Visual • a: Add • c: Clear • Enter: Play • Space: Pause • s: Stop • ←→: Seek • +/-: Vol • n/p: Next/Prev • r: Rescan • q: Quit"; // Split into left (artist/album/title) and right (technical info)
let status_bar = Paragraph::new(shortcuts)
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
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));
}
// Create layout for left and right sections
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area);
// Left side text
let left_text = if !left_parts.is_empty() {
format!(" {}", left_parts.join(" | "))
} else {
String::new()
};
let left_bar = Paragraph::new(left_text)
.style(Style::default().fg(Theme::muted_text()).bg(Theme::background())) .style(Style::default().fg(Theme::muted_text()).bg(Theme::background()))
.alignment(Alignment::Center); .alignment(Alignment::Left);
frame.render_widget(status_bar, area); frame.render_widget(left_bar, chunks[0]);
// Right side text
let right_text = if !right_parts.is_empty() {
format!("{} ", right_parts.join(" | "))
} else {
String::new()
};
let right_bar = Paragraph::new(right_text)
.style(Style::default().fg(Theme::muted_text()).bg(Theme::background()))
.alignment(Alignment::Right);
frame.render_widget(right_bar, chunks[1]);
} }
} }
fn render_confirm_popup(frame: &mut Frame, title: &str, message: &str) {
// Create centered popup area
let area = frame.area();
let popup_width = 52;
let popup_height = 7;
let popup_area = Rect {
x: (area.width.saturating_sub(popup_width)) / 2,
y: (area.height.saturating_sub(popup_height)) / 2,
width: popup_width.min(area.width),
height: popup_height.min(area.height),
};
// Use Clear widget to completely erase the background
frame.render_widget(Clear, popup_area);
// Render the popup block with solid background
let block = Block::default()
.title(title)
.borders(Borders::ALL)
.style(Style::default()
.bg(Theme::background())
.fg(Theme::bright_foreground()))
.title_style(Style::default()
.fg(Theme::bright_foreground())
.add_modifier(Modifier::BOLD));
let inner = block.inner(popup_area);
frame.render_widget(block, popup_area);
// Render message and prompt
let text_area = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // Empty line
Constraint::Length(1), // Message
Constraint::Length(1), // Empty line
Constraint::Length(1), // Prompt
])
.split(inner);
let message_text = Paragraph::new(message)
.style(Style::default()
.fg(Theme::bright_foreground())
.bg(Theme::background()))
.alignment(Alignment::Center);
frame.render_widget(message_text, text_area[1]);
let prompt_text = Paragraph::new("Press 'y' to confirm or 'n' to cancel")
.style(Style::default()
.fg(Theme::foreground())
.bg(Theme::background()))
.alignment(Alignment::Center);
frame.render_widget(prompt_text, text_area[3]);
}

View File

@@ -86,15 +86,15 @@ impl Theme {
.bg(Self::highlight()) .bg(Self::highlight())
} }
pub fn directory() -> Style {
Style::default()
.fg(Self::normal_blue())
.bg(Self::background())
}
pub fn marked() -> Style { pub fn marked() -> Style {
Style::default() Style::default()
.fg(Self::warning()) .fg(Self::warning())
.bg(Self::background()) .bg(Self::background())
} }
pub fn search_selected() -> Style {
Style::default()
.fg(Self::background())
.bg(Self::warning())
}
} }