//! # Utility functions use std::io::stdout; use modalkit::crossterm; use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow}; use modalkit::crossterm::event::{ DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste, EnableFocusChange, EnableMouseCapture, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags, }; use modalkit::crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle}; use regex::{Regex, RegexBuilder}; use crate::prelude::*; pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) { match cow { Cow::Borrowed(s) => { let s1 = Cow::Borrowed(&s[idx..]); let s0 = Cow::Borrowed(&s[..idx]); (s0, s1) }, Cow::Owned(mut s) => { let s1 = Cow::Owned(s.split_off(idx)); let s0 = Cow::Owned(s); (s0, s1) }, } } pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) { // Find where to split the line. let mut cur_width = 0; let idx = UnicodeSegmentation::split_word_bound_indices(s.as_ref()) .find_map(|(i, word)| { let word_width = UnicodeWidthStr::width(word); if cur_width + word_width > width { Some(i) } else { cur_width += word_width; None } }) .unwrap_or(s.len()); if idx == 0 { // first word is wider than available; fall back to splitting by width return take_width_grapheme(s, width); } let (s0, s1) = split_cow(s, idx); ((s0, cur_width), s1) } pub fn take_width_grapheme(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) { let mut cur_width = 0; let idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true) .find_map(|(i, graph)| { let graph_width = UnicodeWidthStr::width(graph); if cur_width + graph_width > width { Some(i) } else { cur_width += graph_width; None } }) .unwrap_or(s.len()); let (s0, s1) = split_cow(s, idx); ((s0, cur_width), s1) } pub struct WrappedLinesIterator<'a> { iter: std::vec::IntoIter>, curr: Option>, width: usize, } impl<'a> WrappedLinesIterator<'a> { fn new(input: T, width: usize) -> Self where T: Into>, { let width = width.max(2); let cows: Vec> = match input.into() { Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(), Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(), }; WrappedLinesIterator { iter: cows.into_iter(), curr: None, width } } } impl<'a> Iterator for WrappedLinesIterator<'a> { type Item = (Cow<'a, str>, usize); fn next(&mut self) -> Option { if self.curr.is_none() { self.curr = self.iter.next(); } if let Some(s) = self.curr.take() { let width = UnicodeWidthStr::width(s.as_ref()); if width <= self.width { return Some((s, width)); } else { let (prefix, s1) = take_width(s, self.width); self.curr = Some(s1); return Some(prefix); } } else { return None; } } } pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a> where T: Into>, { WrappedLinesIterator::new(input, width) } pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a> where T: Into>, { let mut text = Text::default(); for (line, w) in wrap(s, width) { let space = space_span(width.saturating_sub(w), style); let spans = Line::from(vec![Span::styled(line, style), space]); text.lines.push(spans); } return text; } pub fn space(width: usize) -> String { " ".repeat(width) } pub fn space_span(width: usize, style: Style) -> Span<'static> { Span::styled(space(width), style) } pub fn space_text(width: usize, style: Style) -> Text<'static> { space_span(width, style).into() } pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>, style: Style) -> Text<'a> { let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0); let mut text = Text::from(vec![Line::from(vec![join.clone()]); height]); for (mut t, w) in texts.into_iter() { for i in 0..height { if let Some(line) = t.lines.get_mut(i) { text.lines[i].spans.append(&mut line.spans); } else { text.lines[i].spans.push(space_span(w, style)); } text.lines[i].spans.push(join.clone()); } } text } fn replace_emoji_in_grapheme(grapheme: &str) -> String { emojis::get(grapheme) .and_then(|emoji| emoji.shortcode()) .map(|shortcode| format!(":{shortcode}:")) .unwrap_or_else(|| grapheme.to_owned()) } pub fn replace_emojis_in_str(s: &str) -> String { let graphemes = s.graphemes(true); graphemes.map(replace_emoji_in_grapheme).collect() } pub fn replace_emojis_in_span(span: &mut Span) { span.content = Cow::Owned(replace_emojis_in_str(span.content.as_ref())) } pub fn replace_emojis_in_line(line: &mut Line) { for span in &mut line.spans { replace_emojis_in_span(span); } } /// Compile a search pattern, optionally ignoring case. pub fn compile_search(pattern: &str, case_insensitive: bool) -> Result { RegexBuilder::new(pattern).case_insensitive(case_insensitive).build() } /// Set up the terminal for drawing the TUI, and getting additional info. pub fn setup_tty(settings: &ApplicationSettings) -> std::io::Result<()> { // Enable raw mode and enter the alternate screen. crossterm::terminal::enable_raw_mode()?; crossterm::execute!(stdout(), EnterAlternateScreen)?; if settings.enable_enhanced_keys { // Enable the Kitty keyboard enhancement protocol for improved keypresses. crossterm::queue!( stdout(), PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES) )?; } if settings.tunables.mouse.enabled { crossterm::execute!(stdout(), EnableMouseCapture)?; } if settings.tunables.terminal.enable_title { let title = format!("iamb ({})", settings.profile.user_id.as_str()); crossterm::execute!(stdout(), SetTitle(title))?; } let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape); crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape) } // Do our best to reverse what we did in setup_tty() when we exit or crash. pub fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) { // The keyboard enhancement flags were pushed onto the alternate screen's // stack, which the terminal keeps separate from the main screen's, so they // have to be popped before LeaveAlternateScreen below. if enable_enhanced_keys { let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags); } if enable_mouse { let _ = crossterm::queue!(stdout(), DisableMouseCapture); } let _ = crossterm::execute!( stdout(), DisableBracketedPaste, DisableFocusChange, SetCursorStyle::DefaultUserShape, LeaveAlternateScreen, CursorShow, ); let _ = crossterm::terminal::disable_raw_mode(); } /// Hands the terminal back to an external program, and sets it up for the TUI /// again when dropped. /// /// Programs that use the alternate screen themselves (editors, pagers) leave it /// on exit, which drops us back to the main screen without iamb knowing, and the /// TUI then draws over the user's scrollback. Suspending around the child keeps /// the alternate screen entries and exits balanced. pub struct SuspendedTty<'a> { settings: &'a ApplicationSettings, } impl<'a> SuspendedTty<'a> { pub fn new(settings: &'a ApplicationSettings) -> Self { restore_tty(settings.enable_enhanced_keys, settings.tunables.mouse.enabled); SuspendedTty { settings } } } impl Drop for SuspendedTty<'_> { fn drop(&mut self) { if let Err(e) = setup_tty(self.settings) { tracing::error!(err = %e, "Failed to set the terminal back up after an external program"); } } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_compile_search_case_insensitive() { let re = compile_search("chicken", true).unwrap(); assert!(re.is_match("CHICKEN")); assert!(re.is_match("Chicken")); assert!(re.is_match("chicken")); let re = compile_search("chicken", false).unwrap(); assert!(!re.is_match("CHICKEN")); assert!(!re.is_match("Chicken")); assert!(re.is_match("chicken")); } #[test] fn test_wrapped_lines_ascii() { let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye"; let mut iter = wrap(s, 100); assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12))); assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26))); assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7))); assert_eq!(iter.next(), None); let mut iter = wrap(s, 5); assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed(" "), 1))); assert_eq!(iter.next(), Some((Cow::Borrowed("world"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("!"), 1))); assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1))); assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5))); assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2))); assert_eq!(iter.next(), None); } #[test] fn test_wrapped_lines_unicode() { let s = "CHICKEN"; let mut iter = wrap(s, 14); assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14))); assert_eq!(iter.next(), None); let mut iter = wrap(s, 5); assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4))); assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4))); assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4))); assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2))); assert_eq!(iter.next(), None); } }