Skip to content

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

feat(tui): centralize text editing with grapheme-safe TextInputBuffer

Samir Hossainsf49c1c9ed505
diff --git a/src/tui/app/addons.rs b/src/tui/app/addons.rs
index 665b101..532cedb 100644
--- a/src/tui/app/addons.rs
+++ b/src/tui/app/addons.rs
@@ -65,8 +65,7 @@ impl App {
return None;
}
- self.state
- .set_status("Verifying addon manifest...".to_string(), 200);
+ self.state.set_status_long("Verifying addon manifest...");
let client = self.service.addon_client.clone();
let sender = self.action_sender.clone();
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 70d0fad..0a7beca 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -69,7 +69,7 @@ impl App {
self.state.show_theme_popup = false;
self.state.theme_list_state.select(None);
self.state
- .set_status(format!("{theme_name} theme applied."), 150);
+ .set_status_default(format!("{theme_name} theme applied."));
}
}
Some(None) => {}
diff --git a/src/tui/app/tv.rs b/src/tui/app/tv.rs
index d1129f7..ea09e33 100644
--- a/src/tui/app/tv.rs
+++ b/src/tui/app/tv.rs
@@ -45,20 +45,16 @@ impl App {
pub(super) fn announce_mode(&mut self) {
match self.state.mode() {
crate::tui::state::AppMode::Streaming => {
- self.state.set_status(
- format!(
- "Streaming mode active ({}).",
- self.state.active_provider.label()
- ),
- 150,
- );
+ self.state.set_status_default(format!(
+ "Streaming mode active ({}).",
+ self.state.active_provider.label()
+ ));
}
crate::tui::state::AppMode::Tv => {
- self.state
- .set_status("Loading TV playlists...".to_string(), 200);
+ self.state.set_status_long("Loading TV playlists...");
}
crate::tui::state::AppMode::Addon => {
- self.state.set_status("Addon mode active.".to_string(), 150);
+ self.state.set_status_default("Addon mode active.");
}
}
}
@@ -146,8 +142,7 @@ impl App {
}
Action::TvReloadPlaylists => {
- self.state
- .set_status("Reloading TV playlists...".to_string(), 150);
+ self.state.set_status_default("Reloading TV playlists...");
self.reload_tv_playlists();
}
@@ -187,7 +182,7 @@ impl App {
} else {
"No TV channels found. Add a playlist (/config).".to_string()
};
- self.state.set_status(status, 200);
+ self.state.set_status_long(status);
} else {
let mut status = format!(
"{} TV channels imported from {} playlist(s).",
@@ -197,7 +192,7 @@ impl App {
if failed > 0 {
status.push_str(&format!(" {failed} playlist(s) failed to load."));
}
- self.state.set_status(status, 200);
+ self.state.set_status_long(status);
}
}
_ => return None,
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index e704c78..9d4e23b 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -9,7 +9,6 @@ use ratatui::{
text::{Line, Span},
widgets::{Block, Cell, Paragraph, Row, Table},
};
-use unicode_segmentation::UnicodeSegmentation;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchViewState {
@@ -1340,6 +1339,39 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
} else {
"Enter playlist URL:"
};
+ let segments = state.tv_input_buffer.graphemes();
+ let cursor = state.tv_input_buffer.cursor();
+ let max_width = inner_area.width.saturating_sub(6) as usize;
+
+ let mut start = 0;
+ if cursor >= max_width {
+ start = cursor - max_width + 1;
+ }
+
+ let mut before_cursor: String = segments[start..cursor].concat();
+ if start > 0 && before_cursor.chars().count() > 3 {
+ before_cursor = format!("...{}", &before_cursor[3..]);
+ }
+
+ let cursor_char = if cursor < segments.len() {
+ segments[cursor].to_string()
+ } else {
+ " ".to_string()
+ };
+
+ let end = (start + max_width).min(segments.len());
+ let after_slice = &segments[cursor.saturating_add(1).min(segments.len())..end];
+ let mut after_cursor: String = after_slice.concat();
+ if end < segments.len() {
+ let len = after_cursor.chars().count();
+ if len > 3 {
+ let keep: String = after_cursor.chars().take(len - 3).collect();
+ after_cursor = format!("{keep}...");
+ } else if !after_cursor.is_empty() {
+ after_cursor = "...".to_string();
+ }
+ }
+
let lines = vec![
ratatui::text::Line::from(vec![
ratatui::text::Span::raw(" "),
@@ -1347,8 +1379,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
]),
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(" ❯ ", theme.sapphire),
- ratatui::text::Span::styled(&state.tv_input_buffer, theme.text),
- ratatui::text::Span::styled("█", theme.rating),
+ ratatui::text::Span::styled(before_cursor, theme.text),
+ ratatui::text::Span::styled(
+ cursor_char,
+ theme.text.add_modifier(ratatui::style::Modifier::REVERSED),
+ ),
+ ratatui::text::Span::styled(after_cursor, theme.text),
]),
];
frame.render_widget(
@@ -1481,8 +1517,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
])
.split(inner_area);
- let segments: Vec<&str> = state.addon_input_buffer.graphemes(true).collect();
- let cursor = state.addon_input_cursor.min(segments.len());
+ let segments = state.addon_input_buffer.graphemes();
+ let cursor = state.addon_input_buffer.cursor();
let max_width = inner_area.width.saturating_sub(6) as usize;
let mut start = 0;
diff --git a/src/tui/state.rs b/src/tui/state.rs
index e41a379..3e7ab07 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -1,6 +1,5 @@
use crate::providers::models::ProviderKind;
use ratatui::widgets::{ListState, TableState};
-use unicode_segmentation::UnicodeSegmentation;
pub use crate::player::PlayerKind;
@@ -199,7 +198,7 @@ pub struct AppState {
pub tv_playlists: Vec<String>,
pub tv_manager_selected: usize,
pub tv_input_active: bool,
- pub tv_input_buffer: String,
+ pub tv_input_buffer: crate::tui::text::TextInputBuffer,
pub tv_input_is_file: bool,
pub is_addon_mode: bool,
@@ -208,8 +207,7 @@ pub struct AppState {
pub addon_manager_popup: bool,
pub addon_manager_selected: usize,
pub addon_input_active: bool,
- pub addon_input_buffer: String,
- pub addon_input_cursor: usize,
+ pub addon_input_buffer: crate::tui::text::TextInputBuffer,
pub history: crate::history::HistoryManager,
pub favorites: crate::favorites::FavoritesManager,
pub favorites_focus: bool,
@@ -351,7 +349,7 @@ impl Default for AppState {
tv_playlists: Vec::new(),
tv_manager_selected: 0,
tv_input_active: false,
- tv_input_buffer: String::new(),
+ tv_input_buffer: crate::tui::text::TextInputBuffer::new(),
tv_input_is_file: false,
is_addon_mode: false,
addons_enabled: false,
@@ -359,8 +357,7 @@ impl Default for AppState {
addon_manager_popup: false,
addon_manager_selected: 0,
addon_input_active: false,
- addon_input_buffer: String::new(),
- addon_input_cursor: 0,
+ addon_input_buffer: crate::tui::text::TextInputBuffer::new(),
history: crate::history::HistoryManager::new(),
favorites: crate::favorites::FavoritesManager::new(),
favorites_focus: false,
@@ -429,11 +426,27 @@ impl AppState {
.retain(|notification| !notification.expired());
}
+ pub const STATUS_TICKS_SHORT: u16 = 90;
+ pub const STATUS_TICKS_DEFAULT: u16 = 150;
+ pub const STATUS_TICKS_LONG: u16 = 240;
+
pub fn set_status(&mut self, message: impl Into<String>, timer: usize) {
self.status_message = message.into();
self.status_timer = timer;
}
+ pub fn set_status_default(&mut self, msg: impl Into<String>) {
+ self.set_status(msg, Self::STATUS_TICKS_DEFAULT as usize);
+ }
+
+ pub fn set_status_short(&mut self, msg: impl Into<String>) {
+ self.set_status(msg, Self::STATUS_TICKS_SHORT as usize);
+ }
+
+ pub fn set_status_long(&mut self, msg: impl Into<String>) {
+ self.set_status(msg, Self::STATUS_TICKS_LONG as usize);
+ }
+
pub fn result_metrics(&self, results_height: u16, results_width: u16) -> ResultMetrics {
let max_rows = results_height.saturating_sub(1).max(3);
let poster_rows_eff = self.poster_rows.max(3).min(max_rows);
@@ -451,23 +464,6 @@ impl AppState {
}
}
- pub fn addon_input_graphemes(&self) -> Vec<&str> {
- self.addon_input_buffer.graphemes(true).collect()
- }
-
- pub fn previous_grapheme_index(&self, index: usize) -> usize {
- let segments = self.addon_input_graphemes();
- if index == 0 {
- return 0;
- }
- (index - 1).min(segments.len().saturating_sub(1))
- }
-
- pub fn next_grapheme_index(&self, index: usize) -> usize {
- let segments = self.addon_input_graphemes();
- (index + 1).min(segments.len())
- }
-
pub fn normalize_result_view(&mut self) {
let total = self.search_results.len();
if total == 0 {
diff --git a/src/tui/text.rs b/src/tui/text.rs
index 6cbc8ff..6c946aa 100644
--- a/src/tui/text.rs
+++ b/src/tui/text.rs
@@ -11,6 +11,217 @@ pub fn remove_last_grapheme(value: &mut String) {
}
}
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct TextInputBuffer {
+ content: String,
+ cursor: usize,
+}
+
+impl TextInputBuffer {
+ pub fn new() -> Self {
+ Self {
+ content: String::new(),
+ cursor: 0,
+ }
+ }
+
+ #[allow(clippy::should_implement_trait)]
+ pub fn from_str(s: &str) -> Self {
+ let content = s.to_string();
+ let cursor = content.graphemes(true).count();
+ Self { content, cursor }
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.content
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.content.is_empty()
+ }
+
+ pub fn len_graphemes(&self) -> usize {
+ self.content.graphemes(true).count()
+ }
+
+ pub fn cursor(&self) -> usize {
+ self.cursor
+ }
+
+ pub fn set_cursor(&mut self, pos: usize) {
+ self.cursor = pos.min(self.len_graphemes());
+ }
+
+ pub fn set_content(&mut self, content: impl Into<String>) {
+ self.content = content.into();
+ self.cursor = self.cursor.min(self.len_graphemes());
+ }
+
+ pub fn graphemes(&self) -> Vec<&str> {
+ self.content.graphemes(true).collect()
+ }
+
+ pub fn cursor_byte_offset(&self) -> usize {
+ if self.cursor == 0 {
+ return 0;
+ }
+ self.content
+ .grapheme_indices(true)
+ .nth(self.cursor)
+ .map(|(idx, _)| idx)
+ .unwrap_or(self.content.len())
+ }
+
+ pub fn insert(&mut self, c: char) {
+ let offset = self.cursor_byte_offset();
+ self.content.insert(offset, c);
+ self.cursor = (self.cursor + 1).min(self.len_graphemes());
+ }
+
+ pub fn insert_str(&mut self, s: &str) {
+ let offset = self.cursor_byte_offset();
+ self.content.insert_str(offset, s);
+ let s_graphemes = s.graphemes(true).count();
+ self.cursor = (self.cursor + s_graphemes).min(self.len_graphemes());
+ }
+
+ pub fn delete_backwards(&mut self) -> bool {
+ if self.cursor == 0 || self.content.is_empty() {
+ return false;
+ }
+ let target_idx = self.cursor - 1;
+ let mut indices = self.content.grapheme_indices(true);
+ if let Some((start_byte, grapheme)) = indices.nth(target_idx) {
+ let end_byte = start_byte + grapheme.len();
+ self.content.replace_range(start_byte..end_byte, "");
+ self.cursor = self.cursor.saturating_sub(1);
+ true
+ } else {
+ false
+ }
+ }
+
+ pub fn delete_forwards(&mut self) -> bool {
+ if self.content.is_empty() || self.cursor >= self.len_graphemes() {
+ return false;
+ }
+ let mut indices = self.content.grapheme_indices(true);
+ if let Some((start_byte, grapheme)) = indices.nth(self.cursor) {
+ let end_byte = start_byte + grapheme.len();
+ self.content.replace_range(start_byte..end_byte, "");
+ true
+ } else {
+ false
+ }
+ }
+
+ pub fn delete_word_backwards(&mut self) -> bool {
+ if self.cursor == 0 || self.content.is_empty() {
+ return false;
+ }
+ let graphemes: Vec<&str> = self.graphemes();
+ let old_cursor = self.cursor.min(graphemes.len());
+ if old_cursor == 0 {
+ return false;
+ }
+
+ let is_delim = |g: &str| -> bool {
+ g.chars()
+ .all(|c| c.is_whitespace() || matches!(c, '/' | '-' | '_' | ':' | '.' | '\\'))
+ };
+
+ let mut new_cursor = old_cursor;
+ while new_cursor > 0 && is_delim(graphemes[new_cursor - 1]) {
+ new_cursor -= 1;
+ }
+ while new_cursor > 0 && !is_delim(graphemes[new_cursor - 1]) {
+ new_cursor -= 1;
+ }
+
+ if new_cursor == old_cursor {
+ return false;
+ }
+
+ let start_byte = if new_cursor == 0 {
+ 0
+ } else {
+ self.content
+ .grapheme_indices(true)
+ .nth(new_cursor)
+ .map(|(idx, _)| idx)
+ .unwrap_or(self.content.len())
+ };
+
+ let end_byte = if old_cursor >= graphemes.len() {
+ self.content.len()
+ } else {
+ self.content
+ .grapheme_indices(true)
+ .nth(old_cursor)
+ .map(|(idx, _)| idx)
+ .unwrap_or(self.content.len())
+ };
+
+ self.content.replace_range(start_byte..end_byte, "");
+ self.cursor = new_cursor;
+ true
+ }
+
+ pub fn clear(&mut self) {
+ self.content.clear();
+ self.cursor = 0;
+ }
+
+ pub fn move_left(&mut self) {
+ self.cursor = self.cursor.saturating_sub(1);
+ }
+
+ pub fn move_right(&mut self) {
+ self.cursor = (self.cursor + 1).min(self.len_graphemes());
+ }
+
+ pub fn move_home(&mut self) {
+ self.cursor = 0;
+ }
+
+ pub fn move_end(&mut self) {
+ self.cursor = self.len_graphemes();
+ }
+}
+
+impl From<&str> for TextInputBuffer {
+ fn from(s: &str) -> Self {
+ Self::from_str(s)
+ }
+}
+
+impl From<String> for TextInputBuffer {
+ fn from(s: String) -> Self {
+ let cursor = s.graphemes(true).count();
+ Self { content: s, cursor }
+ }
+}
+
+impl std::fmt::Display for TextInputBuffer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.content)
+ }
+}
+
+impl AsRef<str> for TextInputBuffer {
+ fn as_ref(&self) -> &str {
+ &self.content
+ }
+}
+
+impl std::str::FromStr for TextInputBuffer {
+ type Err = std::convert::Infallible;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Ok(Self::from_str(s))
+ }
+}
+
pub fn truncate_width(value: &str, max_width: usize) -> String {
if width(value) <= max_width {
return value.to_string();
@@ -323,4 +534,182 @@ mod tests {
assert_eq!(parse_duration_seconds("N/A"), None);
assert_eq!(parse_duration_seconds(""), None);
}
+
+ #[test]
+ fn test_text_input_buffer_basic_ascii() {
+ let mut buf = TextInputBuffer::new();
+ assert!(buf.is_empty());
+ assert_eq!(buf.len_graphemes(), 0);
+ assert_eq!(buf.cursor(), 0);
+ assert_eq!(buf.as_str(), "");
+
+ buf.insert('a');
+ buf.insert('b');
+ buf.insert('c');
+ assert_eq!(buf.as_str(), "abc");
+ assert_eq!(buf.cursor(), 3);
+ assert_eq!(buf.len_graphemes(), 3);
+
+ buf.move_left();
+ assert_eq!(buf.cursor(), 2);
+ buf.insert('X');
+ assert_eq!(buf.as_str(), "abXc");
+ assert_eq!(buf.cursor(), 3);
+
+ buf.move_home();
+ assert_eq!(buf.cursor(), 0);
+ buf.insert('Z');
+ assert_eq!(buf.as_str(), "ZabXc");
+ assert_eq!(buf.cursor(), 1);
+
+ buf.move_end();
+ assert_eq!(buf.cursor(), 5);
+ }
+
+ #[test]
+ fn test_text_input_buffer_unicode_multibyte() {
+ let mut buf = TextInputBuffer::from_str("café");
+ assert_eq!(buf.len_graphemes(), 4);
+ assert_eq!(buf.cursor(), 4);
+
+ buf.insert_str(" ☕ 日本語");
+ assert_eq!(buf.as_str(), "café ☕ 日本語");
+ assert_eq!(buf.len_graphemes(), 10);
+ assert_eq!(buf.cursor(), 10);
+
+ buf.move_left();
+ assert_eq!(buf.cursor(), 9);
+ assert!(buf.delete_forwards());
+ assert_eq!(buf.as_str(), "café ☕ 日本");
+ assert_eq!(buf.cursor(), 9);
+
+ buf.move_left();
+ assert_eq!(buf.cursor(), 8);
+ assert!(buf.delete_backwards());
+ assert_eq!(buf.as_str(), "café ☕ 本");
+ assert_eq!(buf.cursor(), 7);
+ }
+
+ #[test]
+ fn test_text_input_buffer_emojis() {
+ let mut buf = TextInputBuffer::new();
+ buf.insert_str("🦀🚀");
+ assert_eq!(buf.len_graphemes(), 2);
+ assert_eq!(buf.cursor(), 2);
+
+ // Compound emoji with ZWJ sequence: Family (👨‍👩‍👧‍👦)
+ let family = "👨‍👩‍👧‍👦";
+ buf.insert_str(family);
+ assert_eq!(buf.len_graphemes(), 3);
+ assert_eq!(buf.cursor(), 3);
+
+ assert!(buf.delete_backwards());
+ assert_eq!(buf.as_str(), "🦀🚀");
+ assert_eq!(buf.cursor(), 2);
+
+ buf.move_home();
+ assert_eq!(buf.cursor(), 0);
+ assert!(buf.delete_forwards());
+ assert_eq!(buf.as_str(), "🚀");
+ assert_eq!(buf.cursor(), 0);
+ }
+
+ #[test]
+ fn test_text_input_buffer_cursor_boundaries_and_clamping() {
+ let mut buf = TextInputBuffer::from_str("movie");
+ assert_eq!(buf.cursor(), 5);
+
+ buf.move_right();
+ assert_eq!(buf.cursor(), 5);
+
+ buf.move_home();
+ assert_eq!(buf.cursor(), 0);
+ buf.move_left();
+ assert_eq!(buf.cursor(), 0);
+
+ buf.set_cursor(100);
+ assert_eq!(buf.cursor(), 5);
+
+ buf.set_cursor(2);
+ assert_eq!(buf.cursor(), 2);
+
+ buf.set_content("tv");
+ assert_eq!(buf.as_str(), "tv");
+ assert_eq!(buf.cursor(), 2);
+
+ buf.set_cursor(2);
+ buf.set_content("x");
+ assert_eq!(buf.cursor(), 1);
+ }
+
+ #[test]
+ fn test_text_input_buffer_backwards_and_forwards_deletion() {
+ let mut buf = TextInputBuffer::from_str("abc");
+ buf.move_home();
+ assert!(!buf.delete_backwards());
+ assert_eq!(buf.as_str(), "abc");
+
+ buf.move_end();
+ assert!(!buf.delete_forwards());
+ assert_eq!(buf.as_str(), "abc");
+
+ buf.set_cursor(1); // after 'a'
+ assert!(buf.delete_backwards()); // deletes 'a'
+ assert_eq!(buf.as_str(), "bc");
+ assert_eq!(buf.cursor(), 0);
+
+ assert!(buf.delete_forwards()); // deletes 'b'
+ assert_eq!(buf.as_str(), "c");
+ assert_eq!(buf.cursor(), 0);
+
+ assert!(buf.delete_forwards()); // deletes 'c'
+ assert_eq!(buf.as_str(), "");
+ assert!(buf.is_empty());
+ assert!(!buf.delete_forwards());
+ assert!(!buf.delete_backwards());
+ }
+
+ #[test]
+ fn test_text_input_buffer_word_deletion_backwards() {
+ let mut buf = TextInputBuffer::from_str("https://example.com/path/file.m3u");
+ assert!(buf.delete_word_backwards());
+ assert_eq!(buf.as_str(), "https://example.com/path/file.");
+ assert_eq!(buf.cursor(), 30);
+
+ assert!(buf.delete_word_backwards());
+ assert_eq!(buf.as_str(), "https://example.com/path/");
+
+ assert!(buf.delete_word_backwards());
+ assert_eq!(buf.as_str(), "https://example.com/");
+
+ let mut buf2 = TextInputBuffer::from_str("foo - bar_baz:test\\file.txt");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "foo - bar_baz:test\\file.");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "foo - bar_baz:test\\");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "foo - bar_baz:");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "foo - bar_");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "foo - ");
+ assert!(buf2.delete_word_backwards());
+ assert_eq!(buf2.as_str(), "");
+ assert!(!buf2.delete_word_backwards());
+
+ let mut buf3 = TextInputBuffer::from_str("hello world ");
+ assert!(buf3.delete_word_backwards());
+ assert_eq!(buf3.as_str(), "hello ");
+ assert!(buf3.delete_word_backwards());
+ assert_eq!(buf3.as_str(), "");
+ }
+
+ #[test]
+ fn test_text_input_buffer_clear() {
+ let mut buf = TextInputBuffer::from_str("some text");
+ buf.clear();
+ assert!(buf.is_empty());
+ assert_eq!(buf.cursor(), 0);
+ assert_eq!(buf.as_str(), "");
+ }
}