diff --git a/Cargo.lock b/Cargo.lock index da32334..106e839 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -101,7 +101,9 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" name = "asinus" version = "0.1.0" dependencies = [ + "anstyle-parse", "clap", + "crossterm", "insta", "open", "ratatui", @@ -332,6 +334,7 @@ dependencies = [ "crossterm_winapi", "derive_more", "document-features", + "filedescriptor", "mio", "parking_lot", "rustix", diff --git a/Cargo.toml b/Cargo.toml index 1e98c87..a84d962 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ rust-version = "1.89.0" exclude = ["/.github", "/docs", "/img", "/scripts", "/tools"] [dependencies] +anstyle-parse = "1.0.0" clap = { version = "4.6.7", features = ["derive"] } open = "5.4.5" ratatui = "0.30.2" @@ -25,6 +26,10 @@ toml = "1.2.0" tui-input = { version = "0.15.5", default-features = false } umbra = "0.6.0" +[target.'cfg(target_os = "macos")'.dependencies] +# Use the polling backend for keyboard input after reading piped stdin. +crossterm = { version = "0.29.0", default-features = false, features = ["use-dev-tty"] } + [dev-dependencies] insta = "1.49.0" rstest = "0.28.0" diff --git a/README.md b/README.md index 579ec32..f8b0d0d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Terminal Color Theme Explorer 🫏 Asinus is a TUI application for exploring, previewing, and comparing terminal color themes. -- Preview themes with built-in terminal samples and compare them side by side. +- Preview themes with built-in samples or your own text, and compare them side by side. - Search by name, appearance, background color, brightness, and text contrast. - Inspect color values and credits, mark favorites, and save search conditions. @@ -37,6 +37,8 @@ Run Asinus in a True Color terminal with at least 60 columns and 22 rows: asinus ``` +Run `asinus --preview sample.txt` to preview your own text. See [Custom Samples](https://lusingander.github.io/asinus/features/explore-compare.html#custom-samples) for piped input and supported formats. + In Explore / Compare: | Keys | Action | @@ -48,7 +50,7 @@ In Explore / Compare: | `F1` | Open contextual help | | `Ctrl-C` | Quit from any screen | -See [Explore & Compare](https://lusingander.github.io/asinus/features/explore-compare.html) for previews and [Keybindings](https://lusingander.github.io/asinus/reference/keybindings.html) for all controls. +See [Keybindings](https://lusingander.github.io/asinus/reference/keybindings.html) for all controls. To customize UI colors and text styles, see [Configuration](https://lusingander.github.io/asinus/reference/configuration.html). diff --git a/docs/src/features/explore-compare.md b/docs/src/features/explore-compare.md index 4ffeb1d..6c4c1e8 100644 --- a/docs/src/features/explore-compare.md +++ b/docs/src/features/explore-compare.md @@ -8,6 +8,12 @@ The pin stays available when you change search conditions. You can hide the them ## Preview Samples +Compare shows the same portion of the selected sample for both themes. Content extending beyond the preview is clipped. + +Previews show theme colors within Asinus. Use [Theme Details](theme-details.md) to inspect colors and find source links. + +### Built-in Samples + | Sample | Content | | --- | --- | | Palette | Foreground, background, ANSI colors, and text attributes | @@ -17,11 +23,22 @@ The pin stays available when you change search conditions. You can hide the them | TUI | Lists, tables, selections, and bars | | Code | A Rust syntax sample | -All samples are built in. They show how the theme's colors work together; actual applications may use different color assignments. +These samples show how the theme's colors work together. Applications may use different color assignments. + +The preview selector offers Auto, Small, Medium, and Large content sizes. Auto chooses a size for the available area. Fixed sizes keep the same content when resizing. + +### Custom Samples + +Use `-p, --preview ` to load a file as the **Custom** sample for the current run. Use `-` as the file argument to read from stdin. + +```sh +asinus --preview sample.txt +git diff --color=always | asinus -p - +``` -The preview selector offers Auto, Small, Medium, and Large content sizes. Auto chooses a size for the available area. Fixed sizes keep the same content when resizing. Content extending beyond the preview is clipped. Compare uses the same content size for both themes. +Input must be nonempty UTF-8 text, up to 1 MiB. When reading from stdin, Asinus waits for EOF before opening the TUI. The TUI requires an interactive terminal. -Previewing does not apply a theme to your terminal. Use [Theme Details](theme-details.md) to inspect colors and find source links. +The preview supports ANSI colors and text attributes such as bold and underline. Color indices 0–15 use the selected theme's palette. Indices 16–255 and explicit RGB colors retain their specified values. ## Operations @@ -41,7 +58,7 @@ In the preview selector: | Keys | Action | | --- | --- | -| `Tab` | Switch between Sample and Content | +| `Tab` | Switch between Sample and Content for built-in samples | | `←` / `→` | Change the selected value | | `Enter` | Apply the preview settings | diff --git a/docs/src/getting-started.md b/docs/src/getting-started.md index c14125a..d6b3c4b 100644 --- a/docs/src/getting-started.md +++ b/docs/src/getting-started.md @@ -44,4 +44,6 @@ asinus 3. Use `[` / `]` to switch preview samples, or `/` to search. 4. Press `F1` for help and `Ctrl-C` to quit. -Continue with [Explore & Compare](features/explore-compare.md), or see [Keybindings](reference/keybindings.md) for all controls. Run `asinus --help` for command line help and `asinus --version` to check the installed version. +Continue with [Explore & Compare](features/explore-compare.md) or try [your own preview sample](features/explore-compare.md#custom-samples). See [Keybindings](reference/keybindings.md) for all controls. + +Run `asinus --help` for command line help and `asinus --version` to check the installed version. diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 80e3bc3..1bff663 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -6,7 +6,7 @@ Asinus is a TUI application for exploring, previewing, and comparing terminal co ## Key Features -- Preview themes with built-in terminal samples and compare them side by side. +- Preview themes with built-in samples or your own text, and compare them side by side. - Search by name, appearance, background color, brightness, and text contrast. - Inspect color values and credits, mark favorites, and save search conditions. diff --git a/docs/src/reference/data-files.md b/docs/src/reference/data-files.md index ebcbfa2..31f2bfe 100644 --- a/docs/src/reference/data-files.md +++ b/docs/src/reference/data-files.md @@ -5,7 +5,7 @@ Asinus saves application data in two TOML files. For the settings file you edit, | File | Contents | Path override | | --- | --- | --- | | `marks.toml` | Favorites and ignored themes | `ASINUS_STATE_PATH` | -| `workspace.toml` | Saved filters, last applied conditions, preview sample and content size, comparison direction | `ASINUS_WORKSPACE_PATH` | +| `workspace.toml` | Saved filters, last applied conditions, built-in preview sample and content size, comparison direction | `ASINUS_WORKSPACE_PATH` | ## Locations diff --git a/docs/src/reference/keybindings.md b/docs/src/reference/keybindings.md index cb2bab9..ceff471 100644 --- a/docs/src/reference/keybindings.md +++ b/docs/src/reference/keybindings.md @@ -88,7 +88,7 @@ Modified keys depend on terminal settings. See [Compatibility](compatibility.md# | Keys | Action | | --- | --- | -| `Tab` / `Shift-Tab` | Switch between Sample and Content | +| `Tab` / `Shift-Tab` | Switch between Sample and Content for built-in samples | | `←` / `h`, `→` / `l` | Change the selected value | | `Enter` | Apply the settings | diff --git a/src/app.rs b/src/app.rs index 49d6b8b..18e6b76 100644 --- a/src/app.rs +++ b/src/app.rs @@ -27,7 +27,7 @@ use crate::{ saved::{FilterDialog, SavedScreen}, }, marks::{MarkChange, Marks}, - preview::{ContentSize, Preset}, + preview::{ContentSize, Preset, Sample, custom::CustomPreview}, search::Filter, theme::{self, Theme}, workspace::{Session, Workspace, WorkspaceAction}, @@ -72,7 +72,7 @@ pub struct App { pub browser_action: Option, pub copy_selection: Option, pub copy_action: Option, - pub preset_selection: Option, + pub preview_selection: Option, pub help: Option, pub saved: Option, pub dialog: Option, @@ -89,7 +89,8 @@ pub struct App { pub filter: Filter, pub editor: Option, pub theme_list: ListState, - pub preset: Preset, + pub preview_sample: Sample, + pub custom_preview: Option, pub preview_content: ContentSize, pub mode: Mode, pub compare_direction: Direction, @@ -110,7 +111,7 @@ impl Default for App { browser_action: None, copy_selection: None, copy_action: None, - preset_selection: None, + preview_selection: None, help: None, saved: None, dialog: None, @@ -127,7 +128,8 @@ impl Default for App { filter: Filter::default(), editor: None, theme_list: ListState::default().with_selected(Some(0)), - preset: Preset::Palette, + preview_sample: Sample::BuiltIn(Preset::default()), + custom_preview: None, preview_content: ContentSize::Auto, mode: Mode::Explore, compare_direction: Direction::Horizontal, @@ -260,7 +262,7 @@ impl App { } return; } - if self.preset_selection.is_some() { + if self.preview_selection.is_some() { self.update_preview(action); return; } @@ -319,12 +321,10 @@ impl App { *visible = !*visible; } Action::PresetPrevious | Action::PresetNext => { - self.preset = if action == Action::PresetNext { - self.preset.next() - } else { - self.preset.previous() - }; - self.record_session(false); + let sample = self + .preview_sample + .adjacent(action == Action::PresetNext, self.custom_preview.is_some()); + self.select_sample(sample, self.preview_content); } Action::ToggleFavorite | Action::ToggleIgnore => { self.update_marks(action); diff --git a/src/app/input.rs b/src/app/input.rs index 7dc1882..55fb481 100644 --- a/src/app/input.rs +++ b/src/app/input.rs @@ -195,7 +195,7 @@ impl App { if self.copy_selection.is_some() { return InputContext::Copy; } - if self.preset_selection.is_some() { + if self.preview_selection.is_some() { return InputContext::Preset; } if let Some(dialog) = &self.dialog { diff --git a/src/app/persistence.rs b/src/app/persistence.rs index 4ec4d9d..b62b78c 100644 --- a/src/app/persistence.rs +++ b/src/app/persistence.rs @@ -1,6 +1,7 @@ use crate::{ app::{App, Notice}, marks::Marks, + preview::Sample, search::Filter, workspace::{Workspace, WorkspaceAction, WorkspaceChange}, }; @@ -11,7 +12,7 @@ impl App { self.notice = read_error.map(|reason| Notice::Warning(format!("Read-only: {reason}"))); self.marks = marks; self.session = workspace.session.clone(); - self.preset = self.session.preset; + self.preview_sample = Sample::BuiltIn(self.session.preset); self.preview_content = self.session.preview_content; self.compare_direction = self.session.layout.into(); let query = self.session.query.as_deref().unwrap_or("ignore:false"); @@ -28,7 +29,6 @@ impl App { if condition && (self.session.query.is_some() || !self.filter.is_default()) { self.session.query = Some(self.filter.query()); } - self.session.preset = self.preset; self.session.preview_content = self.preview_content; self.session.layout = self.compare_direction.into(); if self.session != self.workspace.session { diff --git a/src/app/preview.rs b/src/app/preview.rs index 62eb7e7..d2d045d 100644 --- a/src/app/preview.rs +++ b/src/app/preview.rs @@ -1,6 +1,6 @@ use crate::{ app::{Action, App}, - preview::{ContentSize, Preset}, + preview::{ContentSize, Sample, custom::CustomPreview}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -11,15 +11,31 @@ pub enum PreviewField { #[derive(Debug, Clone, Copy)] pub struct PreviewSelection { - pub preset: Preset, + pub sample: Sample, pub content: ContentSize, pub field: PreviewField, } impl App { + pub fn use_custom_preview(&mut self, preview: CustomPreview) { + self.custom_preview = Some(preview); + self.preview_sample = Sample::Custom; + } + + pub fn select_sample(&mut self, sample: Sample, content: ContentSize) { + self.preview_sample = sample; + if let Sample::BuiltIn(preset) = sample { + self.preview_content = content; + if !self.read_only { + self.session.preset = preset; + } + self.record_session(false); + } + } + pub fn open_preview(&mut self) { - self.preset_selection = Some(PreviewSelection { - preset: self.preset, + self.preview_selection = Some(PreviewSelection { + sample: self.preview_sample, content: self.preview_content, field: PreviewField::Sample, }); @@ -27,11 +43,11 @@ impl App { pub fn update_preview(&mut self, action: Action) { let selection = self - .preset_selection + .preview_selection .as_mut() .expect("preview selector is open"); match action { - Action::FieldNext | Action::FieldPrevious => { + Action::FieldNext | Action::FieldPrevious if selection.sample != Sample::Custom => { selection.field = match selection.field { PreviewField::Sample => PreviewField::Content, PreviewField::Content => PreviewField::Sample, @@ -39,11 +55,9 @@ impl App { } Action::ValueNext | Action::ValuePrevious => match selection.field { PreviewField::Sample => { - selection.preset = if action == Action::ValueNext { - selection.preset.next() - } else { - selection.preset.previous() - }; + selection.sample = selection + .sample + .adjacent(action == Action::ValueNext, self.custom_preview.is_some()); } PreviewField::Content => { let index = ContentSize::ALL @@ -60,14 +74,14 @@ impl App { } }, Action::Confirm => { - let selection = self.preset_selection.take().unwrap(); - if self.preset != selection.preset || self.preview_content != selection.content { - self.preset = selection.preset; - self.preview_content = selection.content; - self.record_session(false); + let selection = self.preview_selection.take().unwrap(); + if self.preview_sample != selection.sample + || self.preview_content != selection.content + { + self.select_sample(selection.sample, selection.content); } } - Action::Cancel => self.preset_selection = None, + Action::Cancel => self.preview_selection = None, _ => {} } } diff --git a/src/app/tests.rs b/src/app/tests.rs index 0caab39..39cfc86 100644 --- a/src/app/tests.rs +++ b/src/app/tests.rs @@ -305,7 +305,7 @@ fn help_blocks_background_actions(#[case] context: InputContext) { assert_eq!(app.pinned_theme().unwrap().name, "3024 Day"); assert_eq!(app.mode, mode); assert_eq!(app.theme_list_visible(), list_visible); - assert_eq!(app.preset, Preset::Palette); + assert_eq!(app.preview_sample, Sample::BuiltIn(Preset::Palette)); assert!(app.marks.is_empty()); assert!(app.workspace_action.is_none()); assert!(app.storage_action.is_none()); diff --git a/src/main.rs b/src/main.rs index f536a76..42fbac5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,20 +19,31 @@ mod workspace; #[cfg(test)] mod test_support; -use std::{error::Error, process::ExitCode}; +use std::{ + error::Error, + fs::File, + io, + path::{Path, PathBuf}, + process::ExitCode, +}; use clap::Parser; -use crate::{app::App, marks::MarkStore, workspace::WorkspaceStore}; +use crate::{ + app::App, marks::MarkStore, preview::custom::CustomPreview, workspace::WorkspaceStore, +}; /// Terminal Color Theme Explorer 🫏 #[derive(Parser)] #[command(version)] -struct Cli {} +struct Cli { + /// Use a UTF-8 file as the preview for this run (- reads stdin) + #[arg(short = 'p', long, value_name = "FILE")] + preview: Option, +} fn main() -> ExitCode { - Cli::parse(); - match run() { + match run(Cli::parse()) { Ok(()) => ExitCode::SUCCESS, Err(error) => { eprintln!("asinus: {error}"); @@ -41,8 +52,13 @@ fn main() -> ExitCode { } } -fn run() -> Result<(), Box> { +fn run(cli: Cli) -> Result<(), Box> { let config = config::load()?; + let custom_preview = cli + .preview + .as_deref() + .map(load_custom_preview) + .transpose()?; let mut store = MarkStore::from_env()?; let mut workspace_store = WorkspaceStore::from_env()?; let (marks, marks_error) = store.load(); @@ -52,6 +68,9 @@ fn run() -> Result<(), Box> { .or_else(|| workspace_error.map(|error| format!("workspace: {error}"))); let mut app = App::default(); app.restore(marks, workspace, read_error); + if let Some(preview) = custom_preview { + app.use_custom_preview(preview); + } let stores = if app.read_only { drop((store, workspace_store)); None @@ -61,3 +80,16 @@ fn run() -> Result<(), Box> { terminal::run(app, config, stores)?; Ok(()) } + +fn load_custom_preview(path: &Path) -> Result> { + if path.as_os_str() == "-" { + terminal::ensure_available()?; + return preview::input::read(io::stdin().lock()) + .map_err(|error| format!("could not read preview from stdin: {error}").into()); + } + let sample = File::open(path) + .and_then(preview::input::read) + .map_err(|error| format!("could not read preview file {path:?}: {error}"))?; + terminal::ensure_available()?; + Ok(sample) +} diff --git a/src/preview.rs b/src/preview.rs index 44ddaa4..a7ac697 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -1,5 +1,7 @@ mod code; +pub mod custom; mod git; +pub mod input; mod logs; mod palette; mod shell; @@ -11,6 +13,32 @@ use serde::{Deserialize, Serialize}; use crate::theme::Theme; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Sample { + BuiltIn(Preset), + Custom, +} + +impl Sample { + pub fn name(self) -> &'static str { + match self { + Self::BuiltIn(preset) => preset.name(), + Self::Custom => "Custom", + } + } + + pub fn adjacent(self, forward: bool, has_custom: bool) -> Self { + match (self, forward, has_custom) { + (Self::BuiltIn(Preset::Code), true, true) + | (Self::BuiltIn(Preset::Palette), false, true) => Self::Custom, + (Self::Custom, true, _) => Self::BuiltIn(Preset::Palette), + (Self::Custom, false, _) => Self::BuiltIn(Preset::Code), + (Self::BuiltIn(preset), true, _) => Self::BuiltIn(preset.next()), + (Self::BuiltIn(preset), false, _) => Self::BuiltIn(preset.previous()), + } + } +} + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Preset { diff --git a/src/preview/custom.rs b/src/preview/custom.rs new file mode 100644 index 0000000..88101e6 --- /dev/null +++ b/src/preview/custom.rs @@ -0,0 +1,250 @@ +use anstyle_parse::{Params, ParamsIter, Parser, Perform}; +use ratatui::{ + style::{Color, Modifier, Style}, + text::{Line, Span}, +}; + +use crate::theme::Theme; + +pub struct CustomPreview { + lines: Vec>, +} + +impl CustomPreview { + pub fn parse(input: &str) -> Self { + let mut parser: Parser = Parser::default(); + let mut sample = SampleParser::default(); + for byte in input.bytes() { + parser.advance(&mut sample, byte); + } + if !sample.text.is_empty() || !sample.line.spans.is_empty() { + sample.finish_line(); + } + Self { + lines: sample.lines, + } + } + + pub fn lines(&self, theme: &Theme, height: u16) -> Vec> { + let resolve = |color| match color { + Color::Indexed(index @ 0..=7) => theme.palette.normal[usize::from(index)].into(), + Color::Indexed(index @ 8..=15) => theme.palette.bright[usize::from(index - 8)].into(), + color => color, + }; + self.lines + .iter() + .take(usize::from(height)) + .map(|line| { + Line::from_iter(line.spans.iter().map(|span| { + let mut style = span.style; + style.fg = style.fg.map(resolve); + style.bg = style.bg.map(resolve); + Span::styled(span.content.as_ref(), style) + })) + }) + .collect() + } +} + +#[derive(Default)] +struct SampleParser { + lines: Vec>, + line: Line<'static>, + text: String, + style: Style, +} + +impl SampleParser { + fn finish_span(&mut self) { + if !self.text.is_empty() { + self.line + .spans + .push(Span::styled(std::mem::take(&mut self.text), self.style)); + } + } + + fn finish_line(&mut self) { + self.finish_span(); + self.lines.push(std::mem::take(&mut self.line)); + } +} + +impl Perform for SampleParser { + fn print(&mut self, character: char) { + if !character.is_control() { + self.text.push(character); + } + } + + fn execute(&mut self, byte: u8) { + match byte { + b'\n' => self.finish_line(), + b'\t' => self.text.push_str(" "), + _ => {} + } + } + + fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], ignore: bool, action: u8) { + if ignore || !intermediates.is_empty() || action != b'm' { + return; + } + + let mut style = self.style; + let mut params = params.iter(); + while let Some(parameter) = params.next() { + style = match *parameter { + [0] => Style::new(), + [1] => style.add_modifier(Modifier::BOLD), + [2] => style.add_modifier(Modifier::DIM), + [3] => style.add_modifier(Modifier::ITALIC), + [4] => style.add_modifier(Modifier::UNDERLINED), + [5] => style.add_modifier(Modifier::SLOW_BLINK), + [6] => style.add_modifier(Modifier::RAPID_BLINK), + [7] => style.add_modifier(Modifier::REVERSED), + [8] => style.add_modifier(Modifier::HIDDEN), + [9] => style.add_modifier(Modifier::CROSSED_OUT), + [22] => style.remove_modifier(Modifier::BOLD | Modifier::DIM), + [23] => style.remove_modifier(Modifier::ITALIC), + [24] => style.remove_modifier(Modifier::UNDERLINED), + [25] => style.remove_modifier(Modifier::SLOW_BLINK | Modifier::RAPID_BLINK), + [27] => style.remove_modifier(Modifier::REVERSED), + [28] => style.remove_modifier(Modifier::HIDDEN), + [29] => style.remove_modifier(Modifier::CROSSED_OUT), + [code @ 30..=37] => style.fg(Color::Indexed((code - 30) as u8)), + [code @ 40..=47] => style.bg(Color::Indexed((code - 40) as u8)), + [code @ 90..=97] => style.fg(Color::Indexed((code - 90 + 8) as u8)), + [code @ 100..=107] => style.bg(Color::Indexed((code - 100 + 8) as u8)), + [38, ref color @ ..] => { + extended_color(color, &mut params).map_or(style, |color| style.fg(color)) + } + [48, ref color @ ..] => { + extended_color(color, &mut params).map_or(style, |color| style.bg(color)) + } + [58, ref color @ ..] => { + // Consume underline color parameters even though only foreground and background are used. + let _ = extended_color(color, &mut params); + style + } + [39] => Style { fg: None, ..style }, + [49] => Style { bg: None, ..style }, + _ => style, + }; + } + if style != self.style { + self.finish_span(); + self.style = style; + } + } +} + +fn extended_color(inline: &[u16], params: &mut ParamsIter<'_>) -> Option { + match inline { + [] => match params.next()? { + [5] => match params.next()? { + [index] => indexed(*index), + _ => None, + }, + [2] => match (params.next(), params.next(), params.next()) { + (Some([red]), Some([green]), Some([blue])) => rgb(*red, *green, *blue), + _ => None, + }, + _ => None, + }, + [5, index] => indexed(*index), + [2, red, green, blue] | [2, 0, red, green, blue] => rgb(*red, *green, *blue), + _ => None, + } +} + +fn indexed(index: u16) -> Option { + Some(Color::Indexed(u8::try_from(index).ok()?)) +} + +fn rgb(red: u16, green: u16, blue: u16) -> Option { + Some(Color::Rgb( + u8::try_from(red).ok()?, + u8::try_from(green).ok()?, + u8::try_from(blue).ok()?, + )) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + use crate::theme::THEMES; + + #[rstest] + #[case("\x1b[31;104m", Some(1), Some(12))] + #[case("\x1b[38;5;1;48:5:12m", Some(1), Some(12))] + #[case("\x1b[31;104m\x1b[39m", None, Some(12))] + #[case("\x1b[31;104m\x1b[49m", Some(1), None)] + #[case("\x1b[31;104m\x1b[m", None, None)] + fn resolves_palette_and_default_colors( + #[case] sgr: &str, + #[case] fg: Option, + #[case] bg: Option, + ) { + let sample = CustomPreview::parse(&format!("{sgr}sample")); + for theme in &THEMES[..2] { + let lines = sample.lines(theme, 1); + let style = lines[0].spans[0].style; + let palette = |index: u8| match index { + 0..=7 => theme.palette.normal[usize::from(index)].into(), + _ => theme.palette.bright[usize::from(index - 8)].into(), + }; + assert_eq!(style.fg, fg.map(palette)); + assert_eq!(style.bg, bg.map(palette)); + } + } + + #[test] + fn keeps_explicit_colors_and_carries_styles_across_lines() { + let sample = CustomPreview::parse( + "\x1b[1;38:2::12:34:56;48;5;200m色\r\n\x1b[38;2;999;1;2mB\x1b[22mC\x1b[0mD", + ); + let lines = sample.lines(&THEMES[0], 2); + let styled = &lines[0].spans[0]; + assert_eq!(styled.content, "色"); + assert_eq!(styled.style.fg, Some(Color::Rgb(12, 34, 56))); + assert_eq!(styled.style.bg, Some(Color::Indexed(200))); + assert!(styled.style.add_modifier.contains(Modifier::BOLD)); + assert_eq!(lines[1].spans[0].style, styled.style); + assert!( + !lines[1].spans[1] + .style + .add_modifier + .contains(Modifier::BOLD) + ); + assert_eq!(lines[1].spans[2].style, Style::new()); + } + + #[test] + fn unsupported_underline_colors_do_not_apply_other_attributes() { + let sample = CustomPreview::parse("\x1b[1;58;5;42;31mA\x1b[58;2;0;0;0mB"); + let lines = sample.lines(&THEMES[0], 1); + assert_eq!(lines[0].spans.len(), 1); + let span = &lines[0].spans[0]; + assert_eq!(span.content, "AB"); + assert_eq!( + span.style, + Style::new() + .fg(THEMES[0].palette.normal[1].into()) + .add_modifier(Modifier::BOLD) + ); + } + + #[test] + fn keeps_visible_text_and_discards_other_terminal_sequences() { + let sample = CustomPreview::parse( + "A\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\\x1bPqignored\x1b\\\x1b[1~\tB\x07\r\n\nC\x1b[", + ); + let text: Vec<_> = sample + .lines(&THEMES[0], 3) + .iter() + .map(ToString::to_string) + .collect(); + assert_eq!(text, ["Alink B", "", "C"]); + } +} diff --git a/src/preview/input.rs b/src/preview/input.rs new file mode 100644 index 0000000..22c8845 --- /dev/null +++ b/src/preview/input.rs @@ -0,0 +1,25 @@ +use std::io::{self, Read}; + +use crate::preview::custom::CustomPreview; + +const MAX_INPUT_BYTES: u64 = 1024 * 1024; + +pub fn read(reader: impl Read) -> io::Result { + let mut bytes = Vec::new(); + reader.take(MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_INPUT_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("preview input exceeds {MAX_INPUT_BYTES} bytes"), + )); + } + if bytes.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "preview input is empty", + )); + } + let input = str::from_utf8(&bytes) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + Ok(CustomPreview::parse(input)) +} diff --git a/src/terminal.rs b/src/terminal.rs index e71017f..2baa0be 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,7 +1,10 @@ #[cfg(test)] mod tests; -use std::{io, time::Duration}; +use std::{ + io::{self, IsTerminal}, + time::Duration, +}; use ratatui::{ DefaultTerminal, @@ -22,6 +25,28 @@ use crate::{ workspace::{WorkspaceAction, WorkspaceStore}, }; +pub fn ensure_available() -> io::Result<()> { + if !io::stdout().is_terminal() { + return Err(io::Error::other( + "the preview requires a terminal on stdout", + )); + } + #[cfg(unix)] + if !io::stdin().is_terminal() { + std::fs::File::options() + .read(true) + .write(true) + .open("/dev/tty") + .map_err(|error| { + io::Error::new( + error.kind(), + format!("could not open the controlling terminal: {error}"), + ) + })?; + } + Ok(()) +} + pub fn run( mut app: App, config: Config, diff --git a/src/terminal/tests.rs b/src/terminal/tests.rs index f269c90..a48e246 100644 --- a/src/terminal/tests.rs +++ b/src/terminal/tests.rs @@ -406,7 +406,10 @@ fn custom_bindings_replace_defaults_in_runtime_dispatch() { ); assert_eq!(app.theme().unwrap().name, "Aardvark Blue"); - assert_eq!(app.preset, crate::preview::Preset::Shell); + assert_eq!( + app.preview_sample, + crate::preview::Sample::BuiltIn(crate::preview::Preset::Shell) + ); assert_eq!(app.selected(), Some(2)); handle_key( @@ -868,7 +871,10 @@ fn remapped_common_actions_drive_their_menus_and_both_help_views() { assert_eq!(app.context(), InputContext::Preset); } press(&mut app, KeyCode::F(5), KeyModifiers::NONE, &config); - assert_eq!(app.preset, crate::preview::Preset::Shell); + assert_eq!( + app.preview_sample, + crate::preview::Sample::BuiltIn(crate::preview::Preset::Shell) + ); assert!(app.workspace_action.is_some()); app.workspace_action = None; press(&mut app, KeyCode::F(3), KeyModifiers::NONE, &config); diff --git a/src/ui.rs b/src/ui.rs index 7427738..d832540 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -24,7 +24,7 @@ use ratatui::{ use crate::{ app::{Action, App, InputContext, Notice, preview::PreviewField}, config::Config, - preview::{ContentSize, SampleSize}, + preview::{ContentSize, Sample, SampleSize}, ui::{ layout::{MIN_HEIGHT, MIN_WIDTH, SCREEN_MARGIN}, theme::UiTheme, @@ -100,6 +100,7 @@ pub fn draw(frame: &mut Frame, app: &App, config: &Config) { }; let resolved = layout .preview(app) + .filter(|_| app.preview_sample != Sample::Custom) .map(|area| preview::size(area, app, app.preview_content)); draw_header(frame, app, layout.header, resolved, ui_theme); search::draw_query(frame, app, layout.query, ui_theme); @@ -158,7 +159,7 @@ pub fn draw(frame: &mut Frame, app: &App, config: &Config) { preview::draw(frame, preview_layout.preview, app, ui_theme); } saved::draw_dialog(frame, app, layout.main, config); - draw_preset_selection(frame, app, &layout, config); + draw_preview_selection(frame, app, &layout, config); copy::draw(frame, app, config, layout.main); help::draw(frame, app, config, layout.main); frame.render_widget( @@ -186,8 +187,8 @@ fn draw_header( area, ); let value = resolved.map_or_else( - || app.preset.name().to_owned(), - |size| format!("{} {}", app.preset.name(), size.name()), + || app.preview_sample.name().to_owned(), + |size| format!("{} {}", app.preview_sample.name(), size.name()), ); frame.render_widget( Paragraph::new(Line::from(vec![ @@ -199,24 +200,26 @@ fn draw_header( ); } -fn draw_preset_selection( +fn draw_preview_selection( frame: &mut Frame, app: &App, screen: &layout::ScreenLayout, config: &Config, ) { - let Some(selected) = app.preset_selection else { + let Some(selected) = app.preview_selection else { return; }; let theme = config.ui_theme; let layout = layout::modal(screen.main, 52, 4); draw_modal(frame, &layout, "Select preview", theme); let inner = layout.content; + let has_content_size = selected.sample != Sample::Custom; for (index, (label, field, value)) in [ - ("Sample", PreviewField::Sample, selected.preset.name()), + ("Sample", PreviewField::Sample, selected.sample.name()), ("Content", PreviewField::Content, selected.content.name()), ] .into_iter() + .take(if has_content_size { 2 } else { 1 }) .enumerate() { let focused = selected.field == field; @@ -240,7 +243,7 @@ fn draw_preset_selection( Rect::new(inner.x + 14, y, inner.width.saturating_sub(14), 1), ); } - if let Some(area) = screen.preview(app) { + if has_content_size && let Some(area) = screen.preview(app) { let size = preview::size(area, app, selected.content); let (width, height) = size.dimensions(); let label = if selected.content == ContentSize::Auto { diff --git a/src/ui/help.rs b/src/ui/help.rs index acdd9a5..6e75fda 100644 --- a/src/ui/help.rs +++ b/src/ui/help.rs @@ -10,6 +10,7 @@ use crate::{ app::{Action, App, InputContext, saved::DialogKind}, config::Config, keybindings::{KeyBindings, KeyChord}, + preview::Sample, ui::{ theme::UiTheme, widgets::{draw_scrollbar, panel}, @@ -227,8 +228,13 @@ fn groups(app: &App, context: InputContext) -> Vec { } } InputContext::Preset => { + if app + .preview_selection + .is_some_and(|selection| selection.sample != Sample::Custom) + { + groups.push(group("Selection", &[FieldNext, FieldPrevious], "Field", 2)); + } groups.extend([ - group("Selection", &[FieldNext, FieldPrevious], "Field", 2), group("Selection", &[ValuePrevious, ValueNext], "Value", 2), group("Selection", &[Confirm], "Use", 1), group("Selection", &[Cancel], "Cancel", 1), diff --git a/src/ui/preview.rs b/src/ui/preview.rs index 6f479c2..1d91872 100644 --- a/src/ui/preview.rs +++ b/src/ui/preview.rs @@ -1,6 +1,6 @@ use ratatui::{ Frame, - layout::{Margin, Rect}, + layout::{Margin, Rect, Size}, style::{Color, Style}, text::{Line, Span}, widgets::{Block, Paragraph}, @@ -8,7 +8,7 @@ use ratatui::{ use crate::{ app::{App, InputContext, theme_target::ThemeTarget}, - preview::{self, ContentSize, Preset, SampleSize}, + preview::{self, ContentSize, Sample, SampleSize}, theme::Theme, ui::{ layout, @@ -18,15 +18,15 @@ use crate::{ }; pub fn draw(frame: &mut Frame, area: Rect, app: &App, theme: UiTheme) { - let size = size(area, app, app.preview_content); + let dimensions = shared_dimensions(area, app); if app.mode.is_compare() { let [pin, current_area] = layout::comparison(area, app.compare_direction); draw_preview( frame, pin, app.pinned_theme().expect("comparison has a pinned theme"), - app.preset, - size, + app, + dimensions, Line::styled( theme_title( ThemeTarget::Pin, @@ -37,9 +37,9 @@ pub fn draw(frame: &mut Frame, area: Rect, app: &App, theme: UiTheme) { ), theme, ); - draw_current_preview(frame, current_area, app, size, theme); + draw_current_preview(frame, current_area, app, dimensions, theme); } else { - draw_current_preview(frame, area, app, size, theme); + draw_current_preview(frame, area, app, dimensions, theme); } } @@ -57,20 +57,25 @@ fn sample_area(area: Rect) -> Rect { } pub fn size(area: Rect, app: &App, content: ContentSize) -> SampleSize { + let Size { width, height } = shared_dimensions(area, app); + content.resolve(width, height) +} + +fn shared_dimensions(area: Rect, app: &App) -> Size { let panes = if app.mode.is_compare() { layout::comparison(area, app.compare_direction) } else { [area, area] }; let [a, b] = panes.map(content_area); - content.resolve(a.width.min(b.width), a.height.min(b.height)) + Size::new(a.width.min(b.width), a.height.min(b.height)) } fn draw_current_preview( frame: &mut Frame, area: Rect, app: &App, - size: SampleSize, + dimensions: Size, ui_theme: UiTheme, ) { let focused = app.context() == InputContext::Browse && !app.theme_list_visible(); @@ -102,7 +107,7 @@ fn draw_current_preview( ) }; if let Some(theme) = app.theme() { - draw_preview(frame, area, theme, app.preset, size, title, ui_theme); + draw_preview(frame, area, theme, app, dimensions, title, ui_theme); } else { let block = panel_with_title(title, ui_theme); let inner = block.inner(area); @@ -120,14 +125,29 @@ fn draw_preview( frame: &mut Frame, area: Rect, theme: &Theme, - preset: Preset, - size: SampleSize, + app: &App, + dimensions: Size, title: Line<'static>, ui_theme: UiTheme, ) { let sample_area = sample_area(area); - let content = content_area(area); - let lines = preview::lines(theme, preset, size); + let mut content = content_area(area); + let lines = match app.preview_sample { + Sample::BuiltIn(preset) => { + let size = app + .preview_content + .resolve(dimensions.width, dimensions.height); + preview::lines(theme, preset, size) + } + Sample::Custom => { + content.width = dimensions.width; + content.height = dimensions.height; + app.custom_preview + .as_ref() + .expect("custom preview is available") + .lines(theme, content.height) + } + }; frame.render_widget(panel_with_title(title, ui_theme), area); let style = Style::reset() .fg(Color::from(theme.foreground)) diff --git a/src/ui/tests.rs b/src/ui/tests.rs index 321d93c..1ce5748 100644 --- a/src/ui/tests.rs +++ b/src/ui/tests.rs @@ -12,7 +12,7 @@ use super::*; use crate::{ app::{Action, InputContext}, marks::{Mark, MarkChange}, - preview::Preset, + preview::{Preset, Sample}, test_support::{custom_navigation_config, insert_text, render}, ui::widgets::panel, workspace::WorkspaceChange, @@ -1441,7 +1441,7 @@ fn search_previews_keep_visible_content_at_width_and_height_boundaries( ) { let mut app = crate::test_support::comparison_in_context(InputContext::Query); app.compare_direction = direction; - app.preset = Preset::Code; + app.preview_sample = Sample::BuiltIn(Preset::Code); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); render(&mut terminal, &mut app, &Config::default()); let buffer = terminal.backend().buffer(); @@ -1795,7 +1795,7 @@ fn auto_preview_uses_content_dimensions_and_a_shared_comparison_size( #[case] copies: usize, ) { let mut app = App::default(); - app.preset = Preset::Git; + app.preview_sample = Sample::BuiltIn(Preset::Git); if compare { app.update(Action::TogglePin, 14); app.update(Action::Next, 14); @@ -1882,7 +1882,7 @@ fn log_and_code_roles_use_the_selected_theme_palette( #[case] index: usize, ) { let mut app = App::default(); - app.preset = preset; + app.preview_sample = Sample::BuiltIn(preset); app.preview_content = crate::preview::ContentSize::Large; let mut terminal = Terminal::new(TestBackend::new(120, 36)).unwrap(); for theme_index in [0, 49] { @@ -1922,7 +1922,7 @@ fn tui_backgrounds_share_sample_width_and_reset_outside_highlighted_rows( #[case] width: u16, ) { let mut app = App::default(); - app.preset = Preset::Tui; + app.preview_sample = Sample::BuiltIn(Preset::Tui); app.preview_content = size; let mut terminal = Terminal::new(TestBackend::new(120, 36)).unwrap(); render(&mut terminal, &mut app, &Config::default()); @@ -1966,7 +1966,7 @@ fn tui_backgrounds_share_sample_width_and_reset_outside_highlighted_rows( assert_eq!(buffer[(x, y)].bg, background); assert!(buffer[(x, y)].modifier.is_empty()); - app.preset = Preset::Code; + app.preview_sample = Sample::BuiltIn(Preset::Code); render(&mut terminal, &mut app, &Config::default()); let buffer = terminal.backend().buffer(); for y in title_y..title_y + 24 { diff --git a/tests/preview_e2e.rs b/tests/preview_e2e.rs new file mode 100644 index 0000000..b1710dc --- /dev/null +++ b/tests/preview_e2e.rs @@ -0,0 +1,183 @@ +mod support; + +use std::{fs, process::Command}; + +use rstest::rstest; +use support::{quit, screen, wait_for}; +use termlens::{Color, Key}; + +#[test] +fn preview_file_uses_each_theme_and_keeps_the_builtin_selection_on_restart() -> termlens::Result<()> +{ + let dir = tempfile::tempdir().unwrap(); + let marks = dir.path().join("marks.toml"); + let workspace = dir.path().join("workspace.toml"); + let sample = dir.path().join("sample with spaces.txt"); + fs::write(&sample, "\x1b[1;31mColored sample\x1b[0m\nDefault sample\n").unwrap(); + fs::write( + &workspace, + "version = 1\nsaved_filters = []\n[session]\npreset = 'git'\nlayout = 'horizontal'\npreview_content = 'large'\n", + ) + .unwrap(); + let mut terminal = termlens::bin!( + "asinus", + size(101, 30), + env_clear(), + env("ASINUS_STATE_PATH", &marks), + env("ASINUS_WORKSPACE_PATH", &workspace), + arg("--preview"), + arg(&sample) + )?; + + let initial = support::wait_for_explore(&mut terminal)?; + assert!(initial.row_text(0).contains("Preview Custom")); + assert!(initial.contains("Colored sample")); + fs::write(&sample, "Changed after startup").unwrap(); + terminal.send_str("pjjc")?; + let compared = wait_for(&mut terminal, |s| s.find_all("Colored sample").len() == 2)?; + assert!(screen::preview_name_matches(&compared, "Pin:", "3024 Day")); + assert!(screen::preview_name_matches( + &compared, + "Current:", + "Aardvark Blue" + )); + for ((row, column), expected) in compared + .find_all("Colored sample") + .into_iter() + .zip([Color::Rgb(219, 45, 32), Color::Rgb(170, 52, 46)]) + { + let style = compared.cell(row, column).unwrap().style(); + assert_eq!(style.fg, expected); + assert!(style.bold); + } + for ((row, column), (fg, bg)) in compared.find_all("Default sample").into_iter().zip([ + (Color::Rgb(74, 69, 67), Color::Rgb(247, 247, 247)), + (Color::Rgb(221, 221, 221), Color::Rgb(16, 32, 64)), + ]) { + let style = compared.cell(row, column).unwrap().style(); + assert_eq!((style.fg, style.bg), (fg, bg)); + assert!(!style.bold); + } + terminal.send(Key::Char('v'))?; + wait_for(&mut terminal, |s| screen::comparison_layout(s, true))?; + quit(&mut terminal)?; + + let persisted = fs::read_to_string(&workspace).unwrap(); + let value: toml::Value = toml::from_str(&persisted).unwrap(); + let session = &value["session"]; + assert_eq!(session["layout"].as_str(), Some("vertical")); + assert_eq!(session["preset"].as_str(), Some("git")); + assert_eq!(session["preview_content"].as_str(), Some("large")); + assert!(!persisted.contains("sample")); + let (mut terminal, restored) = support::start(80, 24, &marks, &workspace)?; + assert!(restored.row_text(0).contains("Preview Git Large")); + quit(&mut terminal) +} + +#[test] +fn switches_between_custom_and_built_in_previews() -> termlens::Result<()> { + let dir = tempfile::tempdir().unwrap(); + let sample = dir.path().join("sample.txt"); + fs::write(&sample, "Custom sample body").unwrap(); + let mut terminal = termlens::bin!( + "asinus", + size(80, 24), + env_clear(), + env("ASINUS_STATE_PATH", dir.path().join("marks.toml")), + env("ASINUS_WORKSPACE_PATH", dir.path().join("workspace.toml")), + arg("-p"), + arg(&sample) + )?; + support::wait_for_explore(&mut terminal)?; + terminal.send(Key::Char(']'))?; + wait_for(&mut terminal, |s| { + s.row_text(0).contains("Preview Palette") + })?; + terminal.send(Key::Char('['))?; + wait_for(&mut terminal, |s| s.contains("Custom sample body"))?; + terminal.send(Key::Char('P'))?; + let selector = wait_for(&mut terminal, |s| { + screen::focused_field_value(s, "Sample", "Custom") + })?; + assert!(!selector.contains("Content")); + assert!(!selector.contains("Tab Field")); + terminal.send(Key::Tab)?; + terminal.send(Key::Left)?; + wait_for(&mut terminal, |s| { + screen::focused_field_value(s, "Sample", "Code") + })?; + terminal.send(Key::Enter)?; + wait_for(&mut terminal, |s| s.row_text(0).contains("Preview Code"))?; + terminal.send(Key::Char(']'))?; + wait_for(&mut terminal, |s| s.contains("Custom sample body"))?; + quit(&mut terminal) +} + +#[rstest] +#[case(None, "could not read preview file")] +#[case(Some(vec![]), "preview input is empty")] +#[case(Some(vec![0xff]), "invalid utf-8")] +#[case(Some(vec![b'x'; 1024 * 1024 + 1]), "preview input exceeds")] +fn rejects_invalid_preview_files(#[case] input: Option>, #[case] expected: &str) { + let dir = tempfile::tempdir().unwrap(); + let sample = dir.path().join("sample.txt"); + if let Some(input) = input { + fs::write(&sample, input).unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_asinus")) + .env_clear() + .arg("--preview") + .arg(sample) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let error = String::from_utf8(output.stderr).unwrap(); + assert!(error.contains(expected), "{error}"); +} + +#[test] +#[cfg(any(target_os = "macos", target_os = "linux"))] +fn stdin_preview_accepts_keys_and_resizes_after_eof() -> termlens::Result<()> { + let dir = tempfile::tempdir().unwrap(); + let mut terminal = termlens::Terminal::builder() + .size(80, 24) + .env_clear() + .env("ASINUS_STATE_PATH", dir.path().join("marks.toml")) + .env("ASINUS_WORKSPACE_PATH", dir.path().join("workspace.toml")) + .env("ASINUS_BIN", env!("CARGO_BIN_EXE_asinus")) + .args([ + "-c", + r#"printf '\033[32mPiped sample\033[0m\n' | "$ASINUS_BIN" --preview -"#, + ]) + .spawn("/bin/sh")?; + let initial = support::wait_for_explore(&mut terminal)?; + assert!(initial.row_text(0).contains("Preview Custom")); + let (row, column) = initial.find("Piped sample").unwrap(); + assert_eq!( + initial.cell(row, column).unwrap().style().fg, + Color::Rgb(1, 162, 82) + ); + terminal.send_str("pjjc")?; + wait_for(&mut terminal, |s| s.find_all("Piped sample").len() == 2)?; + support::resize_and_wait(&mut terminal, 100, 30, |s| { + s.find_all("Piped sample").len() == 2 + })?; + quit(&mut terminal) +} + +#[test] +fn stdin_preview_requires_a_terminal() { + let output = Command::new(env!("CARGO_BIN_EXE_asinus")) + .env_clear() + .args(["--preview", "-"]) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let error = String::from_utf8(output.stderr).unwrap(); + assert!( + error.contains("the preview requires a terminal on stdout"), + "{error}" + ); +}