src/util.rs
348 lines · 11048 bytes
1//! # Utility functions
2
3use std::io::stdout;
4
5use modalkit::crossterm;
6use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow};
7use modalkit::crossterm::event::{
8 DisableBracketedPaste,
9 DisableFocusChange,
10 DisableMouseCapture,
11 EnableBracketedPaste,
12 EnableFocusChange,
13 EnableMouseCapture,
14 KeyboardEnhancementFlags,
15 PopKeyboardEnhancementFlags,
16 PushKeyboardEnhancementFlags,
17};
18use modalkit::crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle};
19use regex::{Regex, RegexBuilder};
20
21use crate::prelude::*;
22
23pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
24 match cow {
25 Cow::Borrowed(s) => {
26 let s1 = Cow::Borrowed(&s[idx..]);
27 let s0 = Cow::Borrowed(&s[..idx]);
28
29 (s0, s1)
30 },
31 Cow::Owned(mut s) => {
32 let s1 = Cow::Owned(s.split_off(idx));
33 let s0 = Cow::Owned(s);
34
35 (s0, s1)
36 },
37 }
38}
39pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
40 // Find where to split the line.
41 let mut cur_width = 0;
42
43 let idx = UnicodeSegmentation::split_word_bound_indices(s.as_ref())
44 .find_map(|(i, word)| {
45 let word_width = UnicodeWidthStr::width(word);
46 if cur_width + word_width > width {
47 Some(i)
48 } else {
49 cur_width += word_width;
50 None
51 }
52 })
53 .unwrap_or(s.len());
54
55 if idx == 0 {
56 // first word is wider than available; fall back to splitting by width
57 return take_width_grapheme(s, width);
58 }
59
60 let (s0, s1) = split_cow(s, idx);
61
62 ((s0, cur_width), s1)
63}
64
65pub fn take_width_grapheme(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
66 let mut cur_width = 0;
67 let idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true)
68 .find_map(|(i, graph)| {
69 let graph_width = UnicodeWidthStr::width(graph);
70 if cur_width + graph_width > width {
71 Some(i)
72 } else {
73 cur_width += graph_width;
74 None
75 }
76 })
77 .unwrap_or(s.len());
78
79 let (s0, s1) = split_cow(s, idx);
80 ((s0, cur_width), s1)
81}
82
83pub struct WrappedLinesIterator<'a> {
84 iter: std::vec::IntoIter<Cow<'a, str>>,
85 curr: Option<Cow<'a, str>>,
86 width: usize,
87}
88
89impl<'a> WrappedLinesIterator<'a> {
90 fn new<T>(input: T, width: usize) -> Self
91 where
92 T: Into<Cow<'a, str>>,
93 {
94 let width = width.max(2);
95
96 let cows: Vec<Cow<'a, str>> = match input.into() {
97 Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(),
98 Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(),
99 };
100
101 WrappedLinesIterator { iter: cows.into_iter(), curr: None, width }
102 }
103}
104
105impl<'a> Iterator for WrappedLinesIterator<'a> {
106 type Item = (Cow<'a, str>, usize);
107
108 fn next(&mut self) -> Option<Self::Item> {
109 if self.curr.is_none() {
110 self.curr = self.iter.next();
111 }
112
113 if let Some(s) = self.curr.take() {
114 let width = UnicodeWidthStr::width(s.as_ref());
115
116 if width <= self.width {
117 return Some((s, width));
118 } else {
119 let (prefix, s1) = take_width(s, self.width);
120 self.curr = Some(s1);
121 return Some(prefix);
122 }
123 } else {
124 return None;
125 }
126 }
127}
128
129pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a>
130where
131 T: Into<Cow<'a, str>>,
132{
133 WrappedLinesIterator::new(input, width)
134}
135
136pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a>
137where
138 T: Into<Cow<'a, str>>,
139{
140 let mut text = Text::default();
141
142 for (line, w) in wrap(s, width) {
143 let space = space_span(width.saturating_sub(w), style);
144 let spans = Line::from(vec![Span::styled(line, style), space]);
145
146 text.lines.push(spans);
147 }
148
149 return text;
150}
151
152pub fn space(width: usize) -> String {
153 " ".repeat(width)
154}
155
156pub fn space_span(width: usize, style: Style) -> Span<'static> {
157 Span::styled(space(width), style)
158}
159
160pub fn space_text(width: usize, style: Style) -> Text<'static> {
161 space_span(width, style).into()
162}
163
164pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>, style: Style) -> Text<'a> {
165 let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0);
166 let mut text = Text::from(vec![Line::from(vec![join.clone()]); height]);
167
168 for (mut t, w) in texts.into_iter() {
169 for i in 0..height {
170 if let Some(line) = t.lines.get_mut(i) {
171 text.lines[i].spans.append(&mut line.spans);
172 } else {
173 text.lines[i].spans.push(space_span(w, style));
174 }
175
176 text.lines[i].spans.push(join.clone());
177 }
178 }
179
180 text
181}
182
183fn replace_emoji_in_grapheme(grapheme: &str) -> String {
184 emojis::get(grapheme)
185 .and_then(|emoji| emoji.shortcode())
186 .map(|shortcode| format!(":{shortcode}:"))
187 .unwrap_or_else(|| grapheme.to_owned())
188}
189
190pub fn replace_emojis_in_str(s: &str) -> String {
191 let graphemes = s.graphemes(true);
192 graphemes.map(replace_emoji_in_grapheme).collect()
193}
194
195pub fn replace_emojis_in_span(span: &mut Span) {
196 span.content = Cow::Owned(replace_emojis_in_str(span.content.as_ref()))
197}
198
199pub fn replace_emojis_in_line(line: &mut Line) {
200 for span in &mut line.spans {
201 replace_emojis_in_span(span);
202 }
203}
204
205/// Compile a search pattern, optionally ignoring case.
206pub fn compile_search(pattern: &str, case_insensitive: bool) -> Result<Regex, regex::Error> {
207 RegexBuilder::new(pattern).case_insensitive(case_insensitive).build()
208}
209
210/// Set up the terminal for drawing the TUI, and getting additional info.
211pub fn setup_tty(settings: &ApplicationSettings) -> std::io::Result<()> {
212 // Enable raw mode and enter the alternate screen.
213 crossterm::terminal::enable_raw_mode()?;
214 crossterm::execute!(stdout(), EnterAlternateScreen)?;
215
216 if settings.enable_enhanced_keys {
217 // Enable the Kitty keyboard enhancement protocol for improved keypresses.
218 crossterm::queue!(
219 stdout(),
220 PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
221 )?;
222 }
223
224 if settings.tunables.mouse.enabled {
225 crossterm::execute!(stdout(), EnableMouseCapture)?;
226 }
227
228 if settings.tunables.terminal.enable_title {
229 let title = format!("iamb ({})", settings.user_id.as_str());
230 crossterm::execute!(stdout(), SetTitle(title))?;
231 }
232
233 let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape);
234
235 crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape)
236}
237
238// Do our best to reverse what we did in setup_tty() when we exit or crash.
239pub fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
240 // The keyboard enhancement flags were pushed onto the alternate screen's
241 // stack, which the terminal keeps separate from the main screen's, so they
242 // have to be popped before LeaveAlternateScreen below.
243 if enable_enhanced_keys {
244 let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
245 }
246
247 if enable_mouse {
248 let _ = crossterm::queue!(stdout(), DisableMouseCapture);
249 }
250
251 let _ = crossterm::execute!(
252 stdout(),
253 DisableBracketedPaste,
254 DisableFocusChange,
255 SetCursorStyle::DefaultUserShape,
256 LeaveAlternateScreen,
257 CursorShow,
258 );
259
260 let _ = crossterm::terminal::disable_raw_mode();
261}
262
263/// Hands the terminal back to an external program, and sets it up for the TUI
264/// again when dropped.
265///
266/// Programs that use the alternate screen themselves (editors, pagers) leave it
267/// on exit, which drops us back to the main screen without iamb knowing, and the
268/// TUI then draws over the user's scrollback. Suspending around the child keeps
269/// the alternate screen entries and exits balanced.
270pub struct SuspendedTty<'a> {
271 settings: &'a ApplicationSettings,
272}
273
274impl<'a> SuspendedTty<'a> {
275 pub fn new(settings: &'a ApplicationSettings) -> Self {
276 restore_tty(settings.enable_enhanced_keys, settings.tunables.mouse.enabled);
277
278 SuspendedTty { settings }
279 }
280}
281
282impl Drop for SuspendedTty<'_> {
283 fn drop(&mut self) {
284 if let Err(e) = setup_tty(self.settings) {
285 tracing::error!(err = %e, "Failed to set the terminal back up after an external program");
286 }
287 }
288}
289
290#[cfg(test)]
291pub mod tests {
292 use super::*;
293
294 #[test]
295 fn test_compile_search_case_insensitive() {
296 let re = compile_search("chicken", true).unwrap();
297 assert!(re.is_match("CHICKEN"));
298 assert!(re.is_match("Chicken"));
299 assert!(re.is_match("chicken"));
300
301 let re = compile_search("chicken", false).unwrap();
302 assert!(!re.is_match("CHICKEN"));
303 assert!(!re.is_match("Chicken"));
304 assert!(re.is_match("chicken"));
305 }
306
307 #[test]
308 fn test_wrapped_lines_ascii() {
309 let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
310
311 let mut iter = wrap(s, 100);
312 assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
313 assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
314 assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
315 assert_eq!(iter.next(), None);
316
317 let mut iter = wrap(s, 5);
318 assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
319 assert_eq!(iter.next(), Some((Cow::Borrowed(" "), 1)));
320 assert_eq!(iter.next(), Some((Cow::Borrowed("world"), 5)));
321 assert_eq!(iter.next(), Some((Cow::Borrowed("!"), 1)));
322 assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
323 assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
324 assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
325 assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
326 assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
327 assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
328 assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
329 assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
330 assert_eq!(iter.next(), None);
331 }
332
333 #[test]
334 fn test_wrapped_lines_unicode() {
335 let s = "CHICKEN";
336
337 let mut iter = wrap(s, 14);
338 assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
339 assert_eq!(iter.next(), None);
340
341 let mut iter = wrap(s, 5);
342 assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
343 assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
344 assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
345 assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
346 assert_eq!(iter.next(), None);
347 }
348}