From 5afb3c5e7e938501a8b688c0c90d4d2dc3f56688 Mon Sep 17 00:00:00 2001 From: Alex Pasmantier Date: Sun, 4 May 2025 03:31:41 +0200 Subject: [PATCH] wip: compiles and works TODO: we seem to be sending quite a lot of preview requests (see logs) --- .config/config.toml | 9 - Cargo.lock | 17 +- Cargo.toml | 9 +- cable/unix-channels.toml | 4 +- television/channels/cable/prototypes.rs | 32 +- television/channels/entry.rs | 9 - television/channels/preview.rs | 3 + television/channels/stdin.rs | 156 -------- television/cli/args.rs | 2 +- television/main.rs | 7 +- television/preview/ansi.rs | 34 -- television/preview/ansi/LICENSE | 7 - television/preview/ansi/code.rs | 140 ------- television/preview/ansi/error.rs | 24 -- television/preview/ansi/parser.rs | 461 ------------------------ television/preview/mod.rs | 1 - television/screen/preview.rs | 78 +--- television/television.rs | 21 +- 18 files changed, 73 insertions(+), 941 deletions(-) delete mode 100644 television/channels/stdin.rs delete mode 100644 television/preview/ansi.rs delete mode 100644 television/preview/ansi/LICENSE delete mode 100644 television/preview/ansi/code.rs delete mode 100644 television/preview/ansi/error.rs delete mode 100644 television/preview/ansi/parser.rs diff --git a/.config/config.toml b/.config/config.toml index cd7172f..686f5c5 100644 --- a/.config/config.toml +++ b/.config/config.toml @@ -61,15 +61,6 @@ orientation = "landscape" # directory in your configuration directory (see the `config.toml` location above). theme = "default" -# Previewers settings -# ---------------------------------------------------------------------------- -[previewers.file] -# The theme to use for syntax highlighting. -# Bulitin syntax highlighting uses the same syntax highlighting engine as bat. -# To get a list of your currently available themes, run `bat --list-themes` -# Note that setting the BAT_THEME environment variable will override this setting. -theme = "TwoDark" - # Keybindings # ---------------------------------------------------------------------------- # diff --git a/Cargo.lock b/Cargo.lock index 912f34f..49d1581 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,6 +38,19 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" +[[package]] +name = "ansi-to-tui" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67555e1f1ece39d737e28c8a017721287753af3f93225e4a445b29ccb0f5912c" +dependencies = [ + "nom", + "ratatui", + "simdutf8", + "smallvec", + "thiserror 1.0.69", +] + [[package]] name = "anstream" version = "0.6.18" @@ -1392,6 +1405,7 @@ dependencies = [ name = "television" version = "0.11.9" dependencies = [ + "ansi-to-tui", "anyhow", "base64", "better-panic", @@ -1404,15 +1418,12 @@ dependencies = [ "directories", "human-panic", "lazy-regex", - "nom", "nucleo", "parking_lot", "ratatui", "rustc-hash", "serde", "signal-hook", - "simdutf8", - "smallvec", "strum", "television-derive", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index 6152ed0..bc1f846 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,15 +51,13 @@ human-panic = "2.0" # FIXME: we probably don't need strum anymore strum = { version = "0.26", features = ["derive"] } parking_lot = "0.12" -nom = "7.1" thiserror = "2.0" -simdutf8 = { version = "0.1", optional = true } -smallvec = { version = "1.13", features = ["const_generics"] } nucleo = "0.5" toml = "0.8" lazy-regex = { version = "3.4.1", features = [ "lite", ], default-features = false } +ansi-to-tui = "7.0.0" # target specific dependencies @@ -78,11 +76,6 @@ clipboard-win = "5.4.0" criterion = { version = "0.5", features = ["async_tokio"] } tempfile = "3.16.0" -[features] -simd = ["dep:simdutf8"] -zero-copy = [] -default = ["zero-copy", "simd"] - [build-dependencies] clap = { version = "4.5", features = ["derive", "cargo"] } diff --git a/cable/unix-channels.toml b/cable/unix-channels.toml index fdc25a1..387a3ab 100644 --- a/cable/unix-channels.toml +++ b/cable/unix-channels.toml @@ -2,7 +2,7 @@ [[cable_channel]] name = "files" source_command = "fd -t f" -preview_command = ":files:" +preview_command = "bat -n --color=always {0}" # Text [[cable_channel]] @@ -72,7 +72,7 @@ preview_command = "aws s3 ls s3://{0}" [[cable_channel]] name = "my-dotfiles" source_command = "fd -t f . $HOME/.config" -preview_command = ":files:" +preview_command = "bat -n --color=always {0}" # Shell history [[cable_channel]] diff --git a/television/channels/cable/prototypes.rs b/television/channels/cable/prototypes.rs index 8d28931..891af78 100644 --- a/television/channels/cable/prototypes.rs +++ b/television/channels/cable/prototypes.rs @@ -4,7 +4,9 @@ use std::{ ops::Deref, }; -use crate::cable::SerializedChannelPrototypes; +use crate::{ + cable::SerializedChannelPrototypes, channels::preview::PreviewCommand, +}; /// A prototype for a cable channel. /// @@ -49,6 +51,9 @@ pub struct CableChannelPrototype { pub preview_offset: Option, } +const STDIN_CHANNEL_NAME: &str = "stdin"; +const STDIN_SOURCE_COMMAND: &str = "cat"; + impl CableChannelPrototype { pub fn new( name: &str, @@ -67,6 +72,31 @@ impl CableChannelPrototype { preview_offset, } } + + pub fn stdin(preview: Option) -> Self { + match preview { + Some(PreviewCommand { + command, + delimiter, + offset_expr, + }) => Self { + name: STDIN_CHANNEL_NAME.to_string(), + source_command: STDIN_SOURCE_COMMAND.to_string(), + interactive: false, + preview_command: Some(command), + preview_delimiter: Some(delimiter), + preview_offset: offset_expr, + }, + None => Self { + name: STDIN_CHANNEL_NAME.to_string(), + source_command: STDIN_SOURCE_COMMAND.to_string(), + interactive: false, + preview_command: None, + preview_delimiter: None, + preview_offset: None, + }, + } + } } const DEFAULT_PROTOTYPE_NAME: &str = "files"; diff --git a/television/channels/entry.rs b/television/channels/entry.rs index 7a2d553..68c65b5 100644 --- a/television/channels/entry.rs +++ b/television/channels/entry.rs @@ -143,15 +143,6 @@ impl Entry { } } -pub const ENTRY_PLACEHOLDER: Entry = Entry { - name: String::new(), - value: None, - name_match_ranges: None, - value_match_ranges: None, - icon: None, - line_number: None, -}; - #[cfg(test)] mod tests { use super::*; diff --git a/television/channels/preview.rs b/television/channels/preview.rs index 4c7b936..70b4fe9 100644 --- a/television/channels/preview.rs +++ b/television/channels/preview.rs @@ -3,6 +3,7 @@ use std::fmt::Display; use super::{cable::prototypes::DEFAULT_DELIMITER, entry::Entry}; use crate::channels::cable::prototypes::CableChannelPrototype; use lazy_regex::{regex, Lazy, Regex}; +use tracing::debug; static CMD_RE: &Lazy = regex!(r"\{(\d+)\}"); @@ -49,6 +50,8 @@ impl PreviewCommand { let mut formatted_command = self .command .replace("{}", format!("'{}'", entry.name).as_str()); + debug!("FORMATTED_COMMAND: {formatted_command}"); + debug!("PARTS: {parts:?}"); formatted_command = CMD_RE .replace_all(&formatted_command, |caps: ®ex::Captures| { diff --git a/television/channels/stdin.rs b/television/channels/stdin.rs deleted file mode 100644 index c2d12fb..0000000 --- a/television/channels/stdin.rs +++ /dev/null @@ -1,156 +0,0 @@ -use std::{ - collections::HashSet, - io::{stdin, BufRead}, - thread::spawn, -}; - -use rustc_hash::{FxBuildHasher, FxHashSet}; -use tracing::debug; - -use super::{preview::PreviewCommand, OnAir}; -use crate::channels::entry::Entry; -use crate::matcher::{config::Config, injector::Injector, Matcher}; - -pub struct Channel { - matcher: Matcher, - pub preview_command: Option, - selected_entries: FxHashSet, - instream_handle: std::thread::JoinHandle<()>, -} - -impl Channel { - pub fn new(preview_command: Option) -> Self { - let matcher = Matcher::new(Config::default()); - let injector = matcher.injector(); - - let instream_handle = spawn(move || stream_from_stdin(&injector)); - - Self { - matcher, - preview_command, - selected_entries: HashSet::with_hasher(FxBuildHasher), - instream_handle, - } - } -} - -impl Default for Channel { - fn default() -> Self { - Self::new(None) - } -} - -impl From for Channel -where - E: AsRef>, -{ - fn from(entries: E) -> Self { - let matcher = Matcher::new(Config::default()); - let injector = matcher.injector(); - - let entries = entries.as_ref().clone(); - - let instream_handle = spawn(move || { - for entry in entries { - injector.push(entry.clone(), |e, cols| { - cols[0] = e.to_string().into(); - }); - } - }); - - Self { - matcher, - preview_command: None, - selected_entries: HashSet::with_hasher(FxBuildHasher), - instream_handle, - } - } -} - -const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -fn stream_from_stdin(injector: &Injector) { - let mut stdin = stdin().lock(); - let mut buffer = String::new(); - - let instant = std::time::Instant::now(); - loop { - match stdin.read_line(&mut buffer) { - Ok(c) if c > 0 => { - let trimmed = buffer.trim(); - if !trimmed.is_empty() { - injector.push(trimmed.to_owned(), |e, cols| { - cols[0] = e.clone().into(); - }); - } - buffer.clear(); - } - Ok(0) => { - debug!("EOF"); - break; - } - _ => { - debug!("Error reading from stdin"); - if instant.elapsed() > TIMEOUT { - break; - } - } - } - } -} - -impl OnAir for Channel { - fn find(&mut self, pattern: &str) { - self.matcher.find(pattern); - } - - fn results(&mut self, num_entries: u32, offset: u32) -> Vec { - self.matcher.tick(); - self.matcher - .results(num_entries, offset) - .into_iter() - .map(|item| { - // NOTE: we're passing `PreviewType::Basic` here just as a placeholder - // to avoid storing the preview command multiple times for each item. - Entry::new(item.matched_string) - .with_name_match_indices(&item.match_indices) - }) - .collect() - } - - fn get_result(&self, index: u32) -> Option { - self.matcher - .get_result(index) - .map(|item| Entry::new(item.matched_string)) - } - - fn selected_entries(&self) -> &FxHashSet { - &self.selected_entries - } - - fn toggle_selection(&mut self, entry: &Entry) { - if self.selected_entries.contains(entry) { - self.selected_entries.remove(entry); - } else { - self.selected_entries.insert(entry.clone()); - } - } - - fn result_count(&self) -> u32 { - self.matcher.matched_item_count - } - - fn total_count(&self) -> u32 { - self.matcher.total_item_count - } - - fn running(&self) -> bool { - self.matcher.status.running || !self.instream_handle.is_finished() - } - - fn shutdown(&self) {} - - fn supports_preview(&self) -> bool { - self.preview_command.is_some() - } -} diff --git a/television/cli/args.rs b/television/cli/args.rs index eb44b0d..571d484 100644 --- a/television/cli/args.rs +++ b/television/cli/args.rs @@ -12,7 +12,7 @@ pub struct Cli { #[arg(value_enum, index = 1, verbatim_doc_comment)] pub channel: Option, - /// A preview command to use with the stdin channel. + /// A preview command to use with the current channel. /// /// If provided, the preview command will be executed and formatted using /// the entry. diff --git a/television/main.rs b/television/main.rs index 49857ed..82ff12f 100644 --- a/television/main.rs +++ b/television/main.rs @@ -5,7 +5,6 @@ use std::process::exit; use anyhow::Result; use clap::Parser; -use crossterm::terminal::enable_raw_mode; use television::cable; use television::channels::cable::prototypes::{ CableChannelPrototype, CableChannelPrototypes, @@ -52,8 +51,6 @@ async fn main() -> Result<()> { .as_ref() .map(|x| handle_subcommands(x, &config)); - enable_raw_mode()?; - // optionally change the working directory args.working_directory.as_ref().map(set_current_dir); @@ -161,9 +158,7 @@ pub fn determine_channel( ) -> Result { if readable_stdin { debug!("Using stdin channel"); - Ok(CableChannelPrototype::new( - "STDIN", "cat", false, None, None, None, - )) + Ok(CableChannelPrototype::stdin(args.preview_command)) } else if let Some(prompt) = args.autocomplete_prompt { debug!("Using autocomplete prompt: {:?}", prompt); let channel_prototype = guess_channel_from_prompt( diff --git a/television/preview/ansi.rs b/television/preview/ansi.rs deleted file mode 100644 index f841281..0000000 --- a/television/preview/ansi.rs +++ /dev/null @@ -1,34 +0,0 @@ -#![allow(unused_imports)] -//! This module provides a way to parse ansi escape codes and convert them to ratatui objects. -//! -//! This code is a modified version of [ansi_to_tui](https://github.com/ratatui/ansi-to-tui). - -// mod ansi; -pub mod code; -pub mod error; -pub mod parser; -pub use error::Error; -use ratatui::text::Text; - -/// `IntoText` will convert any type that has a `AsRef<[u8]>` to a Text. -pub trait IntoText { - /// Convert the type to a Text. - #[allow(clippy::wrong_self_convention)] - fn into_text(&self) -> Result, Error>; - /// Convert the type to a Text while trying to copy as less as possible - #[cfg(feature = "zero-copy")] - fn to_text(&self) -> Result, Error>; -} -impl IntoText for T -where - T: AsRef<[u8]>, -{ - fn into_text(&self) -> Result, Error> { - Ok(parser::text(self.as_ref())?.1) - } - - #[cfg(feature = "zero-copy")] - fn to_text(&self) -> Result, Error> { - Ok(parser::text_fast(self.as_ref())?.1) - } -} diff --git a/television/preview/ansi/LICENSE b/television/preview/ansi/LICENSE deleted file mode 100644 index 73313cb..0000000 --- a/television/preview/ansi/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2021 Uttarayan Mondal - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/television/preview/ansi/code.rs b/television/preview/ansi/code.rs deleted file mode 100644 index d23d3c9..0000000 --- a/television/preview/ansi/code.rs +++ /dev/null @@ -1,140 +0,0 @@ -use ratatui::style::Color; - -/// This enum stores most types of ansi escape sequences -/// -/// You can turn an escape sequence to this enum variant using -/// `AnsiCode::from(code: u8)` -/// This doesn't support all of them but does support most of them. - -#[derive(Debug, PartialEq, Clone)] -#[non_exhaustive] -pub enum AnsiCode { - /// Reset the terminal - Reset, - /// Set font to bold - Bold, - /// Set font to faint - Faint, - /// Set font to italic - Italic, - /// Set font to underline - Underline, - /// Set cursor to slowblink - SlowBlink, - /// Set cursor to rapidblink - RapidBlink, - /// Invert the colors - Reverse, - /// Conceal text - Conceal, - /// Display crossed out text - CrossedOut, - /// Choose primary font - PrimaryFont, - /// Choose alternate font - AlternateFont, - /// Choose alternate fonts 1-9 - #[allow(dead_code)] - AlternateFonts(u8), // = 11..19, // from 11 to 19 - /// Fraktur ? No clue - Fraktur, - /// Turn off bold - BoldOff, - /// Set text to normal - Normal, - /// Turn off Italic - NotItalic, - /// Turn off underline - UnderlineOff, - /// Turn off blinking - BlinkOff, - // 26 ? - /// Don't invert colors - InvertOff, - /// Reveal text - Reveal, - /// Turn off Crossedout text - CrossedOutOff, - /// Set foreground color (4-bit) - ForegroundColor(Color), //, 31..37//Issue 60553 https://github.com/rust-lang/rust/issues/60553 - /// Set foreground color (8-bit and 24-bit) - SetForegroundColor, - /// Default foreground color - DefaultForegroundColor, - /// Set background color (4-bit) - BackgroundColor(Color), // 41..47 - /// Set background color (8-bit and 24-bit) - SetBackgroundColor, - /// Default background color - DefaultBackgroundColor, // 49 - /// Other / non supported escape codes - Code(Vec), -} - -impl From for AnsiCode { - fn from(code: u8) -> Self { - match code { - 0 => AnsiCode::Reset, - 1 => AnsiCode::Bold, - 2 => AnsiCode::Faint, - 3 => AnsiCode::Italic, - 4 => AnsiCode::Underline, - 5 => AnsiCode::SlowBlink, - 6 => AnsiCode::RapidBlink, - 7 => AnsiCode::Reverse, - 8 => AnsiCode::Conceal, - 9 => AnsiCode::CrossedOut, - 10 => AnsiCode::PrimaryFont, - 11 => AnsiCode::AlternateFont, - // AnsiCode::// AlternateFont = 11..19, // from 11 to 19 - 20 => AnsiCode::Fraktur, - 21 => AnsiCode::BoldOff, - 22 => AnsiCode::Normal, - 23 => AnsiCode::NotItalic, - 24 => AnsiCode::UnderlineOff, - 25 => AnsiCode::BlinkOff, - // 26 ? - 27 => AnsiCode::InvertOff, - 28 => AnsiCode::Reveal, - 29 => AnsiCode::CrossedOutOff, - 30 => AnsiCode::ForegroundColor(Color::Black), - 31 => AnsiCode::ForegroundColor(Color::Red), - 32 => AnsiCode::ForegroundColor(Color::Green), - 33 => AnsiCode::ForegroundColor(Color::Yellow), - 34 => AnsiCode::ForegroundColor(Color::Blue), - 35 => AnsiCode::ForegroundColor(Color::Magenta), - 36 => AnsiCode::ForegroundColor(Color::Cyan), - 37 => AnsiCode::ForegroundColor(Color::Gray), - 38 => AnsiCode::SetForegroundColor, - 39 => AnsiCode::DefaultForegroundColor, - 40 => AnsiCode::BackgroundColor(Color::Black), - 41 => AnsiCode::BackgroundColor(Color::Red), - 42 => AnsiCode::BackgroundColor(Color::Green), - 43 => AnsiCode::BackgroundColor(Color::Yellow), - 44 => AnsiCode::BackgroundColor(Color::Blue), - 45 => AnsiCode::BackgroundColor(Color::Magenta), - 46 => AnsiCode::BackgroundColor(Color::Cyan), - 47 => AnsiCode::BackgroundColor(Color::Gray), - 48 => AnsiCode::SetBackgroundColor, - 49 => AnsiCode::DefaultBackgroundColor, - 90 => AnsiCode::ForegroundColor(Color::DarkGray), - 91 => AnsiCode::ForegroundColor(Color::LightRed), - 92 => AnsiCode::ForegroundColor(Color::LightGreen), - 93 => AnsiCode::ForegroundColor(Color::LightYellow), - 94 => AnsiCode::ForegroundColor(Color::LightBlue), - 95 => AnsiCode::ForegroundColor(Color::LightMagenta), - 96 => AnsiCode::ForegroundColor(Color::LightCyan), - #[allow(clippy::match_same_arms)] - 97 => AnsiCode::ForegroundColor(Color::White), - 100 => AnsiCode::BackgroundColor(Color::DarkGray), - 101 => AnsiCode::BackgroundColor(Color::LightRed), - 102 => AnsiCode::BackgroundColor(Color::LightGreen), - 103 => AnsiCode::BackgroundColor(Color::LightYellow), - 104 => AnsiCode::BackgroundColor(Color::LightBlue), - 105 => AnsiCode::BackgroundColor(Color::LightMagenta), - 106 => AnsiCode::BackgroundColor(Color::LightCyan), - 107 => AnsiCode::ForegroundColor(Color::White), - code => AnsiCode::Code(vec![code]), - } - } -} diff --git a/television/preview/ansi/error.rs b/television/preview/ansi/error.rs deleted file mode 100644 index 4930749..0000000 --- a/television/preview/ansi/error.rs +++ /dev/null @@ -1,24 +0,0 @@ -/// This enum stores the error types -#[derive(Debug, thiserror::Error, PartialEq)] -pub enum Error { - /// Stack is empty (should never happen) - #[error("Internal error: stack is empty")] - NomError(String), - - /// Error parsing the input as utf-8 - #[cfg(feature = "simd")] - /// Cannot determine the foreground or background - #[error("{0:?}")] - Utf8Error(#[from] simdutf8::basic::Utf8Error), - - #[cfg(not(feature = "simd"))] - /// Cannot determine the foreground or background - #[error("{0:?}")] - Utf8Error(#[from] std::string::FromUtf8Error), -} - -impl From>> for Error { - fn from(e: nom::Err>) -> Self { - Self::NomError(format!("{:?}", e)) - } -} diff --git a/television/preview/ansi/parser.rs b/television/preview/ansi/parser.rs deleted file mode 100644 index a24cb86..0000000 --- a/television/preview/ansi/parser.rs +++ /dev/null @@ -1,461 +0,0 @@ -use crate::preview::ansi::code::AnsiCode; -use nom::{ - branch::alt, - bytes::complete::{tag, take, take_till, take_while}, - character::{ - complete::{char, i64, not_line_ending, u8}, - is_alphabetic, - }, - combinator::{map_res, opt}, - multi::fold_many0, - sequence::{delimited, preceded, tuple}, - IResult, Parser, -}; -use ratatui::{ - style::{Color, Modifier, Style, Stylize}, - text::{Line, Span, Text}, -}; -use smallvec::SmallVec; -use std::str::FromStr; - -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -enum ColorType { - /// Eight Bit color - EightBit, - /// 24-bit color or true color - TrueColor, -} - -#[derive(Debug, Clone, PartialEq)] -struct AnsiItem { - code: AnsiCode, - color: Option, -} - -#[derive(Debug, Clone, PartialEq)] -struct AnsiStates { - pub items: SmallVec<[AnsiItem; 2]>, - pub style: Style, -} - -impl From for Style { - fn from(states: AnsiStates) -> Self { - let mut style = states.style; - for item in states.items { - match item.code { - AnsiCode::Bold => style = style.add_modifier(Modifier::BOLD), - AnsiCode::Faint => style = style.add_modifier(Modifier::DIM), - AnsiCode::Normal => { - style = style - .remove_modifier(Modifier::BOLD) - .remove_modifier(Modifier::DIM); - } - AnsiCode::Italic => { - style = style.add_modifier(Modifier::ITALIC); - } - AnsiCode::Underline => { - style = style.add_modifier(Modifier::UNDERLINED); - } - AnsiCode::SlowBlink => { - style = style.add_modifier(Modifier::SLOW_BLINK); - } - AnsiCode::RapidBlink => { - style = style.add_modifier(Modifier::RAPID_BLINK); - } - AnsiCode::Reverse => { - style = style.add_modifier(Modifier::REVERSED); - } - AnsiCode::Conceal => { - style = style.add_modifier(Modifier::HIDDEN); - } - AnsiCode::CrossedOut => { - style = style.add_modifier(Modifier::CROSSED_OUT); - } - AnsiCode::DefaultForegroundColor => { - style = style.fg(Color::Reset); - } - AnsiCode::SetForegroundColor => { - if let Some(color) = item.color { - style = style.fg(color); - } - } - AnsiCode::ForegroundColor(color) => style = style.fg(color), - AnsiCode::Reset => style = style.fg(Color::Reset), - _ => (), - } - } - style - } -} - -#[allow(clippy::unnecessary_wraps)] -pub(crate) fn text(mut s: &[u8]) -> IResult<&[u8], Text<'static>> { - let mut lines = Vec::new(); - let mut last_style = Style::new(); - while let Ok((remaining, (line, style))) = line(last_style)(s) { - lines.push(line); - last_style = style; - s = remaining; - if s.is_empty() { - break; - } - } - Ok((s, Text::from(lines))) -} - -#[cfg(feature = "zero-copy")] -#[allow(clippy::unnecessary_wraps)] -pub(crate) fn text_fast(mut s: &[u8]) -> IResult<&[u8], Text<'_>> { - let mut lines = Vec::new(); - let mut last = Style::new(); - while let Ok((c, (line, style))) = line_fast(last)(s) { - lines.push(line); - last = style; - s = c; - if s.is_empty() { - break; - } - } - Ok((s, Text::from(lines))) -} - -fn line( - style: Style, -) -> impl Fn(&[u8]) -> IResult<&[u8], (Line<'static>, Style)> { - // let style_: Style = Default::default(); - move |s: &[u8]| -> IResult<&[u8], (Line<'static>, Style)> { - // consume s until a line ending is found - let (s, mut text) = not_line_ending(s)?; - // discard the line ending - let (s, _) = opt(alt((tag("\r\n"), tag("\n"))))(s)?; - let mut spans = Vec::new(); - // carry over the style from the previous line (passed in as an argument) - let mut last_style = style; - // parse spans from the given text - while let Ok((remaining, span)) = span(last_style)(text) { - // Since reset now tracks separately we can skip the reset check - last_style = last_style.patch(span.style); - - if !span.content.is_empty() { - spans.push(span); - } - text = remaining; - if text.is_empty() { - break; - } - } - - // NOTE: what is last_style here - Ok((s, (Line::from(spans), last_style))) - } -} - -#[cfg(feature = "zero-copy")] -fn line_fast( - style: Style, -) -> impl Fn(&[u8]) -> IResult<&[u8], (Line<'_>, Style)> { - // let style_: Style = Default::default(); - move |s: &[u8]| -> IResult<&[u8], (Line<'_>, Style)> { - let (s, mut text) = not_line_ending(s)?; - let (s, _) = opt(alt((tag("\r\n"), tag("\n"))))(s)?; - let mut spans = Vec::new(); - let mut last = style; - while let Ok((s, span)) = span_fast(last)(text) { - last = last.patch(span.style); - // If the spans is empty then it might be possible that the style changes - // but there is no text change - if !span.content.is_empty() { - spans.push(span); - } - text = s; - if text.is_empty() { - break; - } - } - - Ok((s, (Line::from(spans), last))) - } -} - -// fn span(s: &[u8]) -> IResult<&[u8], tui::text::Span> { -fn span( - last: Style, -) -> impl Fn(&[u8]) -> IResult<&[u8], Span<'static>, nom::error::Error<&[u8]>> -{ - move |s: &[u8]| -> IResult<&[u8], Span<'static>> { - let mut last_style = last; - // optionally consume a style - let (s, maybe_style) = opt(style(last_style))(s)?; - - // consume until an escape sequence is found - #[cfg(feature = "simd")] - let (s, text) = map_res(take_while(|c| c != b'\x1b'), |t| { - simdutf8::basic::from_utf8(t) - })(s)?; - - #[cfg(not(feature = "simd"))] - let (s, text) = - map_res(take_while(|c| c != b'\x1b'), |t| std::str::from_utf8(t))( - s, - )?; - - // if a style was found, patch the last style with it - if let Some(st) = maybe_style.flatten() { - last_style = last_style.patch(st); - } - - Ok((s, Span::styled(text.to_owned(), last_style))) - } -} - -#[cfg(feature = "zero-copy")] -fn span_fast( - last: Style, -) -> impl Fn(&[u8]) -> IResult<&[u8], Span<'_>, nom::error::Error<&[u8]>> { - move |s: &[u8]| -> IResult<&[u8], Span<'_>> { - let mut last = last; - let (s, style) = opt(style(last))(s)?; - - #[cfg(feature = "simd")] - let (s, text) = map_res(take_while(|c| c != b'\x1b'), |t| { - simdutf8::basic::from_utf8(t) - })(s)?; - - #[cfg(not(feature = "simd"))] - let (s, text) = - map_res(take_while(|c| c != b'\x1b'), |t| std::str::from_utf8(t))( - s, - )?; - - if let Some(style) = style.flatten() { - last = last.patch(style); - } - - Ok((s, Span::styled(text, last))) - } -} - -#[allow(clippy::type_complexity)] -fn style( - style: Style, -) -> impl Fn(&[u8]) -> IResult<&[u8], Option