Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

refactor: consolidate media player logic, add text utility helpers, and implement adaptive layout and sixel redraw support

Samir Hossains1907babe6d7c
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 6d00590..e839aac 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -17,18 +17,6 @@ use crate::tui::{
theme::Theme,
};
-fn configure_mpv_window(command: &mut std::process::Command, iina: bool) {
- let prefix = if iina { "--mpv-" } else { "--" };
- command
- .arg(format!("{prefix}autofit=960x540"))
- .arg(format!("{prefix}autofit-larger=640x360"))
- .arg(format!("{prefix}geometry=50%:50%"));
-}
-
-fn configure_vlc_window(command: &mut std::process::Command) {
- command.arg("--width=960").arg("--height=540");
-}
-
pub fn clean_moviebox_title(raw_title: &str) -> String {
let mut end = raw_title.len();
@@ -137,6 +125,7 @@ impl App {
if provider == self.state.active_provider {
return;
}
+ self.prepare_sixel_redraw();
self.state
.fetch_cancel
.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -185,6 +174,17 @@ impl App {
self.switch_provider(next);
}
+ fn prepare_sixel_redraw(&mut self) {
+ if self.state.image_picker.as_ref().is_some_and(|picker| {
+ matches!(
+ picker.protocol_type(),
+ ratatui_image::picker::ProtocolType::Sixel
+ )
+ }) {
+ self.state.clear_terminal_before_draw = true;
+ }
+ }
+
fn trigger_episode_fetch(&mut self) {
if let Some(id) = &self.state.active_subject_id {
let stype = self
@@ -531,43 +531,17 @@ impl App {
let player_sender = self.action_sender.clone();
tokio::task::spawn_blocking(move || {
- let mut players = Vec::new();
- let which_cmd = if cfg!(target_os = "windows") {
- "where"
- } else {
- "which"
- };
- let check_player = |cmd: &str| -> bool {
- std::process::Command::new(which_cmd)
- .arg(cmd)
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- };
-
- #[cfg(target_os = "macos")]
- {
- if std::path::Path::new("/Applications/IINA.app").exists() || check_player("iina") {
- players.push(crate::tui::state::PlayerKind::Iina);
- }
- }
- if std::path::Path::new("/Applications/mpv.app").exists()
- || std::path::Path::new("C:\\Program Files\\mpv\\mpv.exe").exists()
- || check_player("mpv")
- {
- players.push(crate::tui::state::PlayerKind::Mpv);
- }
- if std::path::Path::new("/Applications/VLC.app").exists()
- || std::path::Path::new("C:\\Program Files\\VideoLAN\\VLC\\vlc.exe").exists()
- || std::path::Path::new("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe").exists()
- || check_player("vlc")
- {
- players.push(crate::tui::state::PlayerKind::Vlc);
- }
- player_sender.send(Action::PlayersDetected(players)).ok();
+ player_sender
+ .send(Action::PlayersDetected(crate::tui::player::detect()))
+ .ok();
});
loop {
+ if self.state.clear_terminal_before_draw {
+ terminal.clear()?;
+ self.state.clear_terminal_before_draw = false;
+ self.state.dirty = true;
+ }
if self.state.dirty {
terminal.draw(|frame| self.draw(frame))?;
self.state.dirty = false;
@@ -644,11 +618,15 @@ impl App {
let pause1 = 90;
let pause2 = 15;
- let greeting_cycle =
- greeting.len() * type_speed + pause1 + greeting.len() * del_speed + pause2;
+ let greeting_graphemes = crate::tui::text::grapheme_count(&greeting);
+ let greeting_cycle = greeting_graphemes * type_speed
+ + pause1
+ + greeting_graphemes * del_speed
+ + pause2;
let mut total_ticks = 0;
for p in prompts.iter() {
- total_ticks += p.len() * type_speed + pause1 + p.len() * del_speed + pause2;
+ let count = crate::tui::text::grapheme_count(p);
+ total_ticks += count * type_speed + pause1 + count * del_speed + pause2;
}
let tick_u = self.state.tick_count as usize;
@@ -656,7 +634,7 @@ impl App {
if tick_u < greeting_cycle {
let t = tick_u;
- let greeting_len = greeting.chars().count();
+ let greeting_len = greeting_graphemes;
let t_type = greeting_len * type_speed;
let t_del = greeting_len * del_speed;
let display_len = if t < t_type {
@@ -668,14 +646,14 @@ impl App {
} else {
0
};
- animated_text = greeting
- .chars()
- .take(display_len.min(greeting_len))
- .collect::<String>();
+ animated_text = crate::tui::text::take_graphemes(
+ &greeting,
+ display_len.min(greeting_len),
+ );
} else {
let mut t = (tick_u - greeting_cycle) % total_ticks;
for p in prompts.iter() {
- let p_len = p.chars().count();
+ let p_len = crate::tui::text::grapheme_count(p);
let t_type = p_len * type_speed;
let t_del = p_len * del_speed;
let cycle = t_type + pause1 + t_del + pause2;
@@ -690,7 +668,7 @@ impl App {
0
};
animated_text =
- p.chars().take(display_len.min(p_len)).collect::<String>();
+ crate::tui::text::take_graphemes(p, display_len.min(p_len));
break;
} else {
t -= cycle;
@@ -773,11 +751,13 @@ impl App {
return Some(());
}
Action::FocusChange => {
+ self.prepare_sixel_redraw();
self.state.poster_protocol = None;
self.state.search_poster_protocols.clear();
if self.state.image_picker.is_some() {}
}
Action::Resize(_w, _h) => {
+ self.prepare_sixel_redraw();
self.state.poster_protocol = None;
self.state.search_poster_protocols.clear();
if self.state.image_picker.is_some() {}
@@ -841,7 +821,7 @@ impl App {
}
}
KeyCode::Backspace => {
- self.state.search_query.pop();
+ crate::tui::text::remove_last_grapheme(&mut self.state.search_query);
self.state.suggest_index = None;
self.state.last_search_edit = std::time::Instant::now();
}
@@ -1300,6 +1280,7 @@ impl App {
self.state.status_timer = 150;
}
Action::GoBack => {
+ self.prepare_sixel_redraw();
if self.state.player_picker_popup {
self.state.player_picker_popup = false;
self.state.player_picker_link = None;
@@ -2263,6 +2244,9 @@ impl App {
self.state.status_timer = 150;
}
Action::MoveUp => {
+ if self.state.active_screen == Screen::Home {
+ self.prepare_sixel_redraw();
+ }
if self.state.player_picker_popup {
let i = match self.state.player_picker_state.selected() {
Some(i) => {
@@ -2372,6 +2356,9 @@ impl App {
}
}
Action::MoveDown => {
+ if self.state.active_screen == Screen::Home {
+ self.prepare_sixel_redraw();
+ }
if self.state.player_picker_popup {
let i = match self.state.player_picker_state.selected() {
Some(i) => {
@@ -4117,86 +4104,8 @@ impl App {
}
}
- let mut cmd = match kind {
- crate::tui::state::PlayerKind::Mpv => {
- let mut c = if std::path::Path::new("C:\\Program Files\\mpv\\mpv.exe")
- .exists()
- {
- std::process::Command::new("C:\\Program Files\\mpv\\mpv.exe")
- } else if std::path::Path::new(
- "/Applications/mpv.app/Contents/MacOS/mpv",
- )
- .exists()
- {
- std::process::Command::new(
- "/Applications/mpv.app/Contents/MacOS/mpv",
- )
- } else {
- std::process::Command::new("mpv")
- };
- configure_mpv_window(&mut c, false);
- c.arg(&link);
- if let Some(s) = local_sub {
- c.arg(format!("--sub-file={}", s));
- }
- c
- }
- crate::tui::state::PlayerKind::Iina => {
- #[cfg(target_os = "macos")]
- {
- let mut c = std::process::Command::new("open");
- c.arg("-a").arg("IINA").arg("--args");
- configure_mpv_window(&mut c, true);
- if let Some(s) = &local_sub {
- c.arg(&link).arg(format!("--mpv-sub-files={}", s));
- } else {
- c.arg(&link);
- }
- c
- }
- #[cfg(not(target_os = "macos"))]
- {
- let mut c = std::process::Command::new("mpv");
- configure_mpv_window(&mut c, false);
- c.arg(&link);
- if let Some(s) = local_sub {
- c.arg(format!("--sub-file={}", s));
- }
- c
- }
- }
- crate::tui::state::PlayerKind::Vlc => {
- let mut c = if std::path::Path::new("/Applications/VLC.app").exists() {
- std::process::Command::new(
- "/Applications/VLC.app/Contents/MacOS/VLC",
- )
- } else if std::path::Path::new(
- "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe",
- )
- .exists()
- {
- std::process::Command::new(
- "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe",
- )
- } else if std::path::Path::new(
- "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
- )
- .exists()
- {
- std::process::Command::new(
- "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
- )
- } else {
- std::process::Command::new("vlc")
- };
- configure_vlc_window(&mut c);
- c.arg(&link);
- if let Some(s) = local_sub {
- c.arg(format!("--sub-file={}", s));
- }
- c
- }
- };
+ let mut cmd =
+ crate::tui::player::command(kind, &link, local_sub.as_deref(), &[]);
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
@@ -4211,92 +4120,19 @@ impl App {
}
Action::LaunchPlayback(kind, source) => {
self.state.player_picker_popup = false;
- if kind == crate::tui::state::PlayerKind::Vlc
- && source.headers.iter().any(|(name, _)| {
- !name.eq_ignore_ascii_case("referer")
- && !name.eq_ignore_ascii_case("user-agent")
- })
- {
+ if !crate::tui::player::supports_headers(kind, &source.headers) {
self.state.status_message =
"This source needs headers VLC cannot provide; use mpv or IINA.".into();
self.state.status_timer = 180;
return None;
}
tokio::spawn(async move {
- let header_fields = source
- .headers
- .iter()
- .map(|(name, value)| format!("{name}: {value}"))
- .collect::<Vec<_>>()
- .join(",");
- let mut cmd = match kind {
- crate::tui::state::PlayerKind::Mpv => {
- let executable =
- if std::path::Path::new("/Applications/mpv.app/Contents/MacOS/mpv")
- .exists()
- {
- "/Applications/mpv.app/Contents/MacOS/mpv"
- } else {
- "mpv"
- };
- let mut command = std::process::Command::new(executable);
- configure_mpv_window(&mut command, false);
- command.arg(&source.url);
- if !header_fields.is_empty() {
- command.arg(format!("--http-header-fields={header_fields}"));
- }
- if let Some(subtitle) = &source.subtitle {
- command.arg(format!("--sub-file={subtitle}"));
- }
- command
- }
- crate::tui::state::PlayerKind::Iina => {
- #[cfg(target_os = "macos")]
- let mut command = {
- let mut command = std::process::Command::new("open");
- command.arg("-a").arg("IINA").arg("--args");
- configure_mpv_window(&mut command, true);
- command.arg(&source.url);
- command
- };
- #[cfg(not(target_os = "macos"))]
- let mut command = {
- let mut command = std::process::Command::new("mpv");
- configure_mpv_window(&mut command, false);
- command.arg(&source.url);
- command
- };
- if !header_fields.is_empty() {
- command.arg(format!("--mpv-http-header-fields={header_fields}"));
- }
- if let Some(subtitle) = &source.subtitle {
- command.arg(format!("--mpv-sub-files={subtitle}"));
- }
- command
- }
- crate::tui::state::PlayerKind::Vlc => {
- let executable =
- if std::path::Path::new("/Applications/VLC.app").exists() {
- "/Applications/VLC.app/Contents/MacOS/VLC"
- } else {
- "vlc"
- };
- let mut command = std::process::Command::new(executable);
- configure_vlc_window(&mut command);
- command.arg(&source.url);
- for (name, value) in &source.headers {
- if name.eq_ignore_ascii_case("referer") {
- command.arg(format!("--http-referrer={value}"));
- } else if name.eq_ignore_ascii_case("user-agent") {
- command.arg(format!("--http-user-agent={value}"));
- }
- }
- if let Some(subtitle) = &source.subtitle {
- command.arg(format!("--sub-file={subtitle}"));
- }
- command
- }
- };
+ let mut cmd = crate::tui::player::command(
+ kind,
+ &source.url,
+ source.subtitle.as_deref(),
+ &source.headers,
+ );
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
#[cfg(unix)]
diff --git a/src/tui/mod.rs b/src/tui/mod.rs
index b1d812a..065026d 100644
--- a/src/tui/mod.rs
+++ b/src/tui/mod.rs
@@ -2,8 +2,10 @@ pub mod action;
pub mod app;
pub mod event;
pub mod iptv_data;
+pub mod player;
pub mod state;
pub mod terminal;
+pub mod text;
pub mod theme;
pub fn clear_area(frame: &mut ratatui::Frame, area: ratatui::layout::Rect, _theme: &theme::Theme) {
diff --git a/src/tui/player.rs b/src/tui/player.rs
new file mode 100644
index 0000000..e76675f
--- /dev/null
+++ b/src/tui/player.rs
@@ -0,0 +1,142 @@
+use crate::tui::state::PlayerKind;
+use std::{path::Path, process::Command};
+
+const MPV_WINDOWS: &str = r"C:\Program Files\mpv\mpv.exe";
+const MPV_MACOS: &str = "/Applications/mpv.app/Contents/MacOS/mpv";
+const VLC_WINDOWS: &str = r"C:\Program Files\VideoLAN\VLC\vlc.exe";
+const VLC_WINDOWS_X86: &str = r"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe";
+const VLC_MACOS: &str = "/Applications/VLC.app/Contents/MacOS/VLC";
+
+pub fn detect() -> Vec<PlayerKind> {
+ let mut players = Vec::new();
+
+ #[cfg(target_os = "macos")]
+ if Path::new("/Applications/IINA.app").exists() || command_exists("iina") {
+ players.push(PlayerKind::Iina);
+ }
+
+ if mpv_executable().is_some() {
+ players.push(PlayerKind::Mpv);
+ }
+ if vlc_executable().is_some() {
+ players.push(PlayerKind::Vlc);
+ }
+
+ players
+}
+
+pub fn supports_headers(kind: PlayerKind, headers: &[(String, String)]) -> bool {
+ kind != PlayerKind::Vlc
+ || headers.iter().all(|(name, _)| {
+ name.eq_ignore_ascii_case("referer") || name.eq_ignore_ascii_case("user-agent")
+ })
+}
+
+pub fn command(
+ kind: PlayerKind,
+ url: &str,
+ subtitle: Option<&str>,
+ headers: &[(String, String)],
+) -> Command {
+ match kind {
+ PlayerKind::Mpv => mpv_command(url, subtitle, headers, false),
+ PlayerKind::Iina => iina_command(url, subtitle, headers),
+ PlayerKind::Vlc => vlc_command(url, subtitle, headers),
+ }
+}
+
+fn mpv_command(
+ url: &str,
+ subtitle: Option<&str>,
+ headers: &[(String, String)],
+ iina: bool,
+) -> Command {
+ let executable = mpv_executable().unwrap_or_else(|| "mpv".into());
+ let mut command = Command::new(executable);
+ let prefix = if iina { "--mpv-" } else { "--" };
+
+ command
+ .arg(format!("{prefix}autofit=960x540"))
+ .arg(format!("{prefix}autofit-larger=640x360"))
+ .arg(format!("{prefix}geometry=50%:50%"))
+ .arg(url);
+
+ if !headers.is_empty() {
+ let fields = headers
+ .iter()
+ .map(|(name, value)| format!("{name}: {value}"))
+ .collect::<Vec<_>>()
+ .join(",");
+ command.arg(format!("{prefix}http-header-fields={fields}"));
+ }
+ if let Some(subtitle) = subtitle {
+ if iina {
+ command.arg(format!("--mpv-sub-files={subtitle}"));
+ } else {
+ command.arg(format!("--sub-file={subtitle}"));
+ }
+ }
+
+ command
+}
+
+#[cfg(target_os = "macos")]
+fn iina_command(url: &str, subtitle: Option<&str>, headers: &[(String, String)]) -> Command {
+ let mut command = Command::new("open");
+ command.arg("-a").arg("IINA").arg("--args");
+ let mpv = mpv_command(url, subtitle, headers, true);
+ command.args(mpv.get_args());
+ command
+}
+
+#[cfg(not(target_os = "macos"))]
+fn iina_command(url: &str, subtitle: Option<&str>, headers: &[(String, String)]) -> Command {
+ mpv_command(url, subtitle, headers, false)
+}
+
+fn vlc_command(url: &str, subtitle: Option<&str>, headers: &[(String, String)]) -> Command {
+ let executable = vlc_executable().unwrap_or_else(|| "vlc".into());
+ let mut command = Command::new(executable);
+ command.arg("--width=960").arg("--height=540").arg(url);
+
+ for (name, value) in headers {
+ if name.eq_ignore_ascii_case("referer") {
+ command.arg(format!("--http-referrer={value}"));
+ } else if name.eq_ignore_ascii_case("user-agent") {
+ command.arg(format!("--http-user-agent={value}"));
+ }
+ }
+ if let Some(subtitle) = subtitle {
+ command.arg(format!("--sub-file={subtitle}"));
+ }
+
+ command
+}
+
+fn mpv_executable() -> Option<String> {
+ first_executable(&[MPV_WINDOWS, MPV_MACOS], "mpv")
+}
+
+fn vlc_executable() -> Option<String> {
+ first_executable(&[VLC_WINDOWS, VLC_WINDOWS_X86, VLC_MACOS], "vlc")
+}
+
+fn first_executable(paths: &[&str], fallback: &str) -> Option<String> {
+ paths
+ .iter()
+ .find(|path| Path::new(path).exists())
+ .map(|path| (*path).to_string())
+ .or_else(|| command_exists(fallback).then(|| fallback.to_string()))
+}
+
+fn command_exists(command: &str) -> bool {
+ let finder = if cfg!(target_os = "windows") {
+ "where"
+ } else {
+ "which"
+ };
+ Command::new(finder)
+ .arg(command)
+ .output()
+ .is_ok_and(|output| output.status.success())
+}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index f4bddef..59a9bae 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -290,20 +290,43 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let is_series = type_val == 2 && !state.available_seasons.is_empty();
- let mut c = Vec::new();
+ let auxiliary_count = usize::from(has_languages) + if is_series { 2 } else { 0 };
+ let compact_panels = auxiliary_count > 0 && bottom_area.width < 110;
+ let (panel_area, streams_area) = if compact_panels {
+ let rows = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([Constraint::Length(6), Constraint::Min(1)])
+ .split(bottom_area);
+ (rows[0], rows[1])
+ } else {
+ (bottom_area, Rect::default())
+ };
+
+ let mut panel_constraints = Vec::new();
if has_languages {
- c.push(Constraint::Length(22));
+ panel_constraints.push(if compact_panels {
+ Constraint::Ratio(1, auxiliary_count as u32)
+ } else {
+ Constraint::Length(22)
+ });
}
if is_series {
- c.push(Constraint::Length(18));
- c.push(Constraint::Length(18));
+ for _ in 0..2 {
+ panel_constraints.push(if compact_panels {
+ Constraint::Ratio(1, auxiliary_count as u32)
+ } else {
+ Constraint::Length(18)
+ });
+ }
+ }
+ if !compact_panels {
+ panel_constraints.push(Constraint::Min(1));
}
- c.push(Constraint::Min(1));
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
- .constraints(c)
- .split(bottom_area);
+ .constraints(panel_constraints)
+ .split(panel_area);
let mut chunk_idx = 0;
let mut lang_area = None;
@@ -320,7 +343,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
eps_area = Some(bottom_chunks[chunk_idx]);
chunk_idx += 1;
}
- let streams_area = bottom_chunks[chunk_idx];
+ let streams_area = if compact_panels {
+ streams_area
+ } else {
+ bottom_chunks[chunk_idx]
+ };
if has_languages {
use ratatui::widgets::{List, ListItem};
@@ -549,23 +576,34 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.get("sourceCount")
.and_then(|value| value.as_u64())
.unwrap_or(0);
- let metadata = if is_fourk {
+ let stream_width = streams_area.width.saturating_sub(6) as usize;
+ let codec = codec.to_uppercase();
+ let metadata = if is_fourk && stream_width >= 58 {
format!(
- "{:<7} | {:<5} | {} | {} mirror{}",
- size_formatted,
- codec.to_uppercase(),
- language,
- source_count,
+ "{size_formatted:<7} | {codec:<5} | {language} | {source_count} mirror{}",
if source_count == 1 { "" } else { "s" }
)
- } else {
+ } else if is_fourk && stream_width >= 38 {
+ format!("{size_formatted:<7} | {codec:<5} | {language}")
+ } else if is_fourk {
+ format!("{size_formatted} | {codec}")
+ } else if stream_width >= 64 {
+ let fixed_width =
+ crate::tui::text::width(&size_formatted)
+ + crate::tui::text::width(&codec)
+ + crate::tui::text::width(&duration_str)
+ + 16;
+ let uploader = crate::tui::text::truncate_width(
+ upload_by,
+ stream_width.saturating_sub(fixed_width).max(4),
+ );
format!(
- "{:<7} | {:<5} | {} | By: {}",
- size_formatted,
- codec.to_uppercase(),
- duration_str,
- upload_by
+ "{size_formatted:<7} | {codec:<5} | {duration_str} | By: {uploader}"
)
+ } else if stream_width >= 38 {
+ format!("{size_formatted:<7} | {codec:<5} | {duration_str}")
+ } else {
+ format!("{size_formatted} | {codec}")
};
let stream_line = ratatui::text::Line::from(vec![
ratatui::text::Span::styled(pointer, theme.accent),
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index bddd6e8..2bf5d79 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -513,14 +513,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let title_style = if is_selected { theme.title } else { theme.text };
let max_title_width = text_area.width.saturating_sub(4) as usize;
- let mut display_title = res.title.clone();
- if display_title.chars().count() > max_title_width && max_title_width > 3 {
- display_title = display_title
- .chars()
- .take(max_title_width - 3)
- .collect::<String>();
- display_title.push_str("...");
- }
+ let display_title = crate::tui::text::truncate_width(&res.title, max_title_width);
let type_tag = if state.is_tv_mode || res.stype == 3 {
"TV Channel"
@@ -661,13 +654,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let max_len = state
.search_suggestions
.iter()
- .map(|s| s.len())
+ .map(|s| crate::tui::text::width(s))
.max()
.unwrap_or(0) as u16;
let dropdown_width = std::cmp::min(std::cmp::max(max_len + 8, 30), search_area.width);
- let text_len = search_content.chars().count() as u16;
+ let text_len = crate::tui::text::width(&search_content) as u16;
let text_start_x = search_area.x + search_area.width.saturating_sub(text_len) / 2;
let dropdown_x = if is_home_screen {
diff --git a/src/tui/state.rs b/src/tui/state.rs
index edabde8..9a5fda4 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -101,6 +101,7 @@ pub struct AppState {
pub poster_protocol: Option<(ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
pub image_picker: Option<ratatui_image::picker::Picker>,
pub image_supported: bool,
+ pub clear_terminal_before_draw: bool,
pub poster_rows: u16,
pub image_cache: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,
@@ -208,6 +209,7 @@ impl Default for AppState {
poster_protocol: None,
image_picker: None,
image_supported: crate::tui::terminal::should_query_images(),
+ clear_terminal_before_draw: false,
poster_rows: 3,
image_cache: lru::LruCache::new(std::num::NonZeroUsize::new(10).unwrap()),
show_help: false,
diff --git a/src/tui/terminal.rs b/src/tui/terminal.rs
index 0303ab0..ebd5d42 100644
--- a/src/tui/terminal.rs
+++ b/src/tui/terminal.rs
@@ -4,27 +4,14 @@ fn env(name: &str) -> String {
pub fn uses_basic_ui() -> bool {
let term = env("TERM");
- let term_program = env("TERM_PROGRAM");
- cfg!(target_os = "windows")
- || term == "dumb"
- || term == "linux"
- || term_program == "Apple_Terminal"
- || std::env::var_os("TMUX").is_some()
- || std::env::var_os("SSH_TTY").is_some()
- || std::env::var_os("SSH_CLIENT").is_some()
+ term == "dumb" || term == "linux"
}
pub fn should_query_images() -> bool {
let term = env("TERM");
- let term_program = env("TERM_PROGRAM");
- term != "dumb"
- && term != "linux"
- && term_program != "Apple_Terminal"
- && std::env::var_os("TMUX").is_none()
- && std::env::var_os("SSH_TTY").is_none()
- && std::env::var_os("SSH_CLIENT").is_none()
+ term != "dumb" && term != "linux"
}
pub fn background_is_light() -> bool {
diff --git a/src/tui/text.rs b/src/tui/text.rs
new file mode 100644
index 0000000..41ac1e6
--- /dev/null
+++ b/src/tui/text.rs
@@ -0,0 +1,43 @@
+use unicode_segmentation::UnicodeSegmentation;
+use unicode_width::UnicodeWidthStr;
+
+pub fn width(value: &str) -> usize {
+ UnicodeWidthStr::width(value)
+}
+
+pub fn grapheme_count(value: &str) -> usize {
+ value.graphemes(true).count()
+}
+
+pub fn take_graphemes(value: &str, count: usize) -> String {
+ value.graphemes(true).take(count).collect()
+}
+
+pub fn remove_last_grapheme(value: &mut String) {
+ if let Some((index, _)) = value.grapheme_indices(true).next_back() {
+ value.truncate(index);
+ }
+}
+
+pub fn truncate_width(value: &str, max_width: usize) -> String {
+ if width(value) <= max_width {
+ return value.to_string();
+ }
+ if max_width <= 3 {
+ return ".".repeat(max_width);
+ }
+
+ let content_width = max_width - 3;
+ let mut output = String::new();
+ let mut used = 0;
+ for grapheme in value.graphemes(true) {
+ let grapheme_width = width(grapheme);
+ if used + grapheme_width > content_width {
+ break;
+ }
+ output.push_str(grapheme);
+ used += grapheme_width;
+ }
+ output.push_str("...");
+ output
+}