diff --git a/Cargo.lock b/Cargo.lock index e903df5..da32334 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,7 @@ dependencies = [ "termlens", "toml", "tui-input", + "umbra", ] [[package]] @@ -1958,6 +1959,17 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" +[[package]] +name = "umbra" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8b5b6e2005966dde02e54e697995aa53a827c3fea19098eae3c33e3dc35bf2" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/Cargo.toml b/Cargo.toml index 94072a1..1e98c87 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ serde_json = "1.0.154" tempfile = "3.27.0" toml = "1.2.0" tui-input = { version = "0.15.5", default-features = false } +umbra = "0.6.0" [dev-dependencies] insta = "1.49.0" diff --git a/README.md b/README.md index 5404f07..579ec32 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ In Explore / Compare: 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. +To customize UI colors and text styles, see [Configuration](https://lusingander.github.io/asinus/reference/configuration.html). + ## License Asinus is distributed under the [MIT License](./LICENSE). diff --git a/config.json.schema b/config.json.schema new file mode 100644 index 0000000..c846a0b --- /dev/null +++ b/config.json.schema @@ -0,0 +1,147 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Asinus Configuration Schema", + "description": "Schema for the Asinus TOML configuration file.", + "type": "object", + "properties": { + "ui": { "$ref": "#/definitions/uiSettings" } + }, + "additionalProperties": false, + "definitions": { + "uiSettings": { + "type": "object", + "properties": { + "style": { "$ref": "#/definitions/uiStyles" } + }, + "additionalProperties": false + }, + "uiStyles": { + "description": "Styles for the application UI. Omitted colors use the role's built-in color when available and otherwise inherit the base color.", + "type": "object", + "properties": { + "base": { "$ref": "#/definitions/baseStyle" }, + "heading": { + "description": "View and panel headings.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "modifiers": ["bold"] } + }, + "focus": { + "description": "The active panel or input control.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "cyan", "modifiers": ["bold"] } + }, + "selection": { + "description": "Selected rows and menu items. Set modifiers to an empty array to disable the default reverse video.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "modifiers": ["reverse"] } + }, + "key": { + "description": "Shortcut keys in footers and Help. Help uses bold by default.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "cyan" } + }, + "muted": { + "description": "Descriptions beside shortcut keys in footers.", + "allOf": [{ "$ref": "#/definitions/style" }] + }, + "condition_key": { + "description": "Search condition keys such as type:.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "green" } + }, + "search_match": { + "description": "Matching text in theme names.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "yellow", "modifiers": ["bold"] } + }, + "comparison_diff": { + "description": "Color comparison difference labels.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "yellow" } + }, + "notice": { + "description": "Informational notices.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "blue" } + }, + "success": { + "description": "Success notices.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "green" } + }, + "warning": { + "description": "Warning notices.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "yellow" } + }, + "error": { + "description": "Error notices and search input errors. Search input errors use bold by default.", + "allOf": [{ "$ref": "#/definitions/style" }], + "default": { "fg": "red" } + } + }, + "additionalProperties": false + }, + "baseStyle": { + "description": "Base foreground and background colors for the application UI.", + "type": "object", + "properties": { + "fg": { + "allOf": [{ "$ref": "#/definitions/color" }], + "default": "default" + }, + "bg": { + "allOf": [{ "$ref": "#/definitions/color" }], + "default": "default" + } + }, + "additionalProperties": false + }, + "style": { + "type": "object", + "properties": { + "fg": { "$ref": "#/definitions/color" }, + "bg": { "$ref": "#/definitions/color" }, + "modifiers": { + "description": "Text attributes that replace the default attributes for this role. An empty array clears them. Omit this field to use the default attributes.", + "type": "array", + "items": { + "enum": ["bold", "dim", "underline", "reverse"] + } + } + }, + "additionalProperties": false + }, + "color": { + "description": "An ANSI palette color name, an RGB color in #RRGGBB form, or default for the terminal's default color.", + "type": "string", + "anyOf": [ + { + "enum": [ + "default", + "black", + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "white", + "bright_black", + "bright_red", + "bright_green", + "bright_yellow", + "bright_blue", + "bright_magenta", + "bright_cyan", + "bright_white" + ] + }, + { + "pattern": "^#[0-9A-Fa-f]{6}$", + "maxLength": 7 + } + ] + } + } +} diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 66361ce..371231c 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -13,5 +13,6 @@ # Reference - [Keybindings](reference/keybindings.md) +- [Configuration](reference/configuration.md) - [Data Files](reference/data-files.md) - [Compatibility](reference/compatibility.md) diff --git a/docs/src/reference/compatibility.md b/docs/src/reference/compatibility.md index de56a49..97dcd31 100644 --- a/docs/src/reference/compatibility.md +++ b/docs/src/reference/compatibility.md @@ -6,7 +6,7 @@ Asinus targets macOS and Linux. Windows is not currently supported. Use a terminal with True Color (24-bit RGB) support and at least **60 columns × 22 rows**. Larger windows give previews more room. Some panels fill the screen at smaller sizes, and preview content may be clipped. -The surrounding UI uses your terminal's colors; previews use the selected theme's RGB colors. Text attributes such as bold and dim depend on terminal settings. +The surrounding UI uses your terminal's colors by default. Preview samples use the selected theme's RGB colors. Text attributes such as bold and dim depend on terminal settings. To customize the UI, see [Configuration](configuration.md). ## Clipboard diff --git a/docs/src/reference/configuration.md b/docs/src/reference/configuration.md new file mode 100644 index 0000000..71e9741 --- /dev/null +++ b/docs/src/reference/configuration.md @@ -0,0 +1,62 @@ +# Configuration + +Use `config.toml` to customize the Asinus UI. + +## Configuration File Location + +Asinus selects the configuration file in this order. + +1. The path set in `ASINUS_CONFIG_FILE`. +2. `$XDG_CONFIG_HOME/asinus/config.toml` if `XDG_CONFIG_HOME` is nonempty. +3. `$HOME/.config/asinus/config.toml`. + +Asinus reads only the selected file. Relative paths are resolved from the current working directory. If the selected default file is missing, Asinus uses its built-in settings. + +An empty `ASINUS_CONFIG_FILE`, a missing file specified by that variable, or an unreadable or invalid configuration file prevents startup. Unknown settings are reported as errors. + +## Create a Configuration + +Save the following example as `config.toml` in your current directory. It sets the colors of selected items and turns off reverse video. + +```toml +[ui.style.selection] +fg = "#1e1e2e" +bg = "#89b4fa" +modifiers = [] +``` + +Run Asinus with this file. + +```sh +ASINUS_CONFIG_FILE=./config.toml asinus +``` + +All settings are optional. Add only the values you want to change. + +## UI Style + +`[ui.style]` controls the application UI. Preview samples and color swatches use the colors of the theme being inspected. + +Each setting below is a table under `[ui.style]`. Use `fg` for the foreground color and `bg` for the background color. When omitted, `bg` inherits from `base`, and `fg` uses the listed color or inherits from `base`. + +| Setting | Default | Use | +| --- | --- | --- | +| `base` | `"default"` for both colors | Main text and background | +| `heading` | Bold | Screen and panel headings | +| `focus` | `"cyan"`, bold | Active panels and controls | +| `selection` | Reverse video | Selected rows and menu items | +| `key` | `"cyan"`, bold in Help | Shortcut keys in Help and footers | +| `muted` | Base colors | Descriptions beside shortcut keys in footers | +| `condition_key` | `"green"` | Keys in search conditions | +| `search_match` | `"yellow"`, bold | Matching text in theme names | +| `comparison_diff` | `"yellow"` | Difference labels in Color details | +| `notice` | `"blue"` | Informational notices | +| `success` | `"green"` | Success notices | +| `warning` | `"yellow"` | Warning notices | +| `error` | `"red"`, bold for search input errors | Error notices and search input errors | + +Color values are strings. Use `"default"` for the terminal's default color or `"#RRGGBB"` for an RGB color. ANSI color names are `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, and `white`, plus their `bright_` forms such as `bright_cyan`. + +Styles other than `base` also accept a `modifiers` array with `"bold"`, `"dim"`, `"underline"`, and `"reverse"`. An explicit array replaces the default attributes, and `[]` clears them. Omit the array to keep the default attributes. + +For editor validation, see the [configuration schema](https://github.com/lusingander/asinus/blob/master/config.json.schema). diff --git a/docs/src/reference/data-files.md b/docs/src/reference/data-files.md index 6a67e49..ebcbfa2 100644 --- a/docs/src/reference/data-files.md +++ b/docs/src/reference/data-files.md @@ -1,6 +1,6 @@ # Data Files -Asinus manages two TOML files: +Asinus saves application data in two TOML files. For the settings file you edit, see [Configuration](configuration.md). | File | Contents | Path override | | --- | --- | --- | diff --git a/src/config.rs b/src/config.rs index 19f322a..7371028 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,162 @@ -use crate::{keybindings::KeyBindings, ui::theme::UiTheme}; +mod style; + +use std::{ + env, + error::Error, + ffi::OsString, + fmt, fs, + io::{self, ErrorKind}, + path::{Path, PathBuf}, +}; + +use serde::Deserialize; +use umbra::optional; + +use crate::{config::style::StyleConfig, keybindings::KeyBindings, ui::theme::UiTheme}; + +const CONFIG_FILE_ENV: &str = "ASINUS_CONFIG_FILE"; #[derive(Default)] pub struct Config { pub ui_theme: UiTheme, pub keybindings: KeyBindings, } + +#[optional(derives = [Debug, Deserialize], attrs = [serde(deny_unknown_fields)])] +#[derive(Default)] +struct FileConfig { + #[nested] + ui: UiConfig, +} + +#[optional(derives = [Debug, Deserialize], attrs = [serde(deny_unknown_fields)])] +#[derive(Default)] +struct UiConfig { + style: StyleConfig, +} + +enum ConfigFile { + Explicit(PathBuf), + Default(PathBuf), +} + +#[derive(Debug)] +pub enum ConfigError { + EmptyExplicitPath, + ExplicitFileNotFound(PathBuf), + Read { + path: PathBuf, + source: io::Error, + }, + Parse { + path: PathBuf, + source: toml::de::Error, + }, +} + +impl fmt::Display for ConfigError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyExplicitPath => write!(formatter, "${CONFIG_FILE_ENV} must not be empty"), + Self::ExplicitFileNotFound(path) => write!( + formatter, + "config file specified by ${CONFIG_FILE_ENV} was not found: {}", + path.display() + ), + Self::Read { path, source } => { + write!( + formatter, + "failed to read config file {}: {source}", + path.display() + ) + } + Self::Parse { path, source } => { + write!( + formatter, + "failed to parse config file {}: {source}", + path.display() + ) + } + } + } +} + +impl Error for ConfigError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Read { source, .. } => Some(source), + Self::Parse { source, .. } => Some(source), + Self::EmptyExplicitPath | Self::ExplicitFileNotFound(_) => None, + } + } +} + +pub fn load() -> Result { + let config_file = resolve_config_file( + env::var_os(CONFIG_FILE_ENV), + env::var_os("XDG_CONFIG_HOME"), + env::var_os("HOME"), + )?; + let Some(config_file) = config_file else { + return Ok(Config::default()); + }; + load_file(config_file) +} + +fn resolve_config_file( + explicit: Option, + xdg: Option, + home: Option, +) -> Result, ConfigError> { + if let Some(path) = explicit { + if path.is_empty() { + return Err(ConfigError::EmptyExplicitPath); + } + return Ok(Some(ConfigFile::Explicit(PathBuf::from(path)))); + } + + let config_home = xdg + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .or_else(|| { + home.filter(|path| !path.is_empty()) + .map(|path| PathBuf::from(path).join(".config")) + }); + Ok(config_home.map(|path| ConfigFile::Default(path.join("asinus/config.toml")))) +} + +fn load_file(file: ConfigFile) -> Result { + let (path, explicit) = match &file { + ConfigFile::Explicit(path) => (path.as_path(), true), + ConfigFile::Default(path) => (path.as_path(), false), + }; + let content = match fs::read_to_string(path) { + Ok(content) => content, + Err(source) if source.kind() == ErrorKind::NotFound && !explicit => { + return Ok(Config::default()); + } + Err(source) if source.kind() == ErrorKind::NotFound => { + return Err(ConfigError::ExplicitFileNotFound(path.to_owned())); + } + Err(source) => { + return Err(ConfigError::Read { + path: path.to_owned(), + source, + }); + } + }; + parse(&content, path) +} + +fn parse(content: &str, path: &Path) -> Result { + let optional = + toml::from_str::(content).map_err(|source| ConfigError::Parse { + path: path.to_owned(), + source, + })?; + let config = FileConfig::from(optional); + Ok(Config { + ui_theme: config.ui.style.resolve(), + keybindings: KeyBindings::default(), + }) +} diff --git a/src/config/style.rs b/src/config/style.rs new file mode 100644 index 0000000..a786e3a --- /dev/null +++ b/src/config/style.rs @@ -0,0 +1,134 @@ +use ratatui::style::{Color, Modifier}; +use serde::{Deserialize, Deserializer, de}; + +use crate::ui::theme::{UiStyle, UiTheme}; + +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct StyleConfig { + base: BaseColors, + heading: StyleOverride, + focus: StyleOverride, + selection: StyleOverride, + key: StyleOverride, + muted: StyleOverride, + condition_key: StyleOverride, + search_match: StyleOverride, + comparison_diff: StyleOverride, + notice: StyleOverride, + success: StyleOverride, + warning: StyleOverride, + error: StyleOverride, +} + +impl StyleConfig { + pub fn resolve(self) -> UiTheme { + let defaults = UiTheme::default(); + UiTheme { + fg: self.base.fg.map_or(defaults.fg, |color| color.0), + bg: self.base.bg.map_or(defaults.bg, |color| color.0), + heading: self.heading.resolve(defaults.heading), + focus: self.focus.resolve(defaults.focus), + selection: self.selection.resolve(defaults.selection), + key: self.key.resolve(defaults.key), + muted: self.muted.resolve(defaults.muted), + condition_key: self.condition_key.resolve(defaults.condition_key), + search_match: self.search_match.resolve(defaults.search_match), + comparison_diff: self.comparison_diff.resolve(defaults.comparison_diff), + notice: self.notice.resolve(defaults.notice), + success: self.success.resolve(defaults.success), + warning: self.warning.resolve(defaults.warning), + error: self.error.resolve(defaults.error), + } + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct BaseColors { + fg: Option, + bg: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct StyleOverride { + fg: Option, + bg: Option, + modifiers: Option>, +} + +impl StyleOverride { + fn resolve(self, defaults: UiStyle) -> UiStyle { + UiStyle { + fg: self.fg.map(|color| color.0).or(defaults.fg), + bg: self.bg.map(|color| color.0).or(defaults.bg), + modifiers: self + .modifiers + .map(|modifiers| modifiers.into_iter().map(|modifier| modifier.0).collect()) + .or(defaults.modifiers), + } + } +} + +#[derive(Debug)] +struct ConfigColor(Color); + +impl<'de> Deserialize<'de> for ConfigColor { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + let color = match value.as_str() { + "default" => Color::Reset, + "black" => Color::Black, + "red" => Color::Red, + "green" => Color::Green, + "yellow" => Color::Yellow, + "blue" => Color::Blue, + "magenta" => Color::Magenta, + "cyan" => Color::Cyan, + "white" => Color::Gray, + "bright_black" => Color::DarkGray, + "bright_red" => Color::LightRed, + "bright_green" => Color::LightGreen, + "bright_yellow" => Color::LightYellow, + "bright_blue" => Color::LightBlue, + "bright_magenta" => Color::LightMagenta, + "bright_cyan" => Color::LightCyan, + "bright_white" => Color::White, + hex if hex.starts_with('#') + && hex.len() == 7 + && hex.as_bytes()[1..].iter().all(u8::is_ascii_hexdigit) => + { + hex.parse().map_err(de::Error::custom)? + } + _ => { + return Err(de::Error::custom(format!( + "invalid color {value:?}, expected an ANSI color name, #RRGGBB, or default" + ))); + } + }; + Ok(Self(color)) + } +} + +#[derive(Debug)] +struct ConfigModifier(Modifier); + +impl<'de> Deserialize<'de> for ConfigModifier { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + let modifier = match value.as_str() { + "bold" => Modifier::BOLD, + "dim" => Modifier::DIM, + "underline" => Modifier::UNDERLINED, + "reverse" => Modifier::REVERSED, + _ => { + return Err(de::Error::unknown_variant( + &value, + &["bold", "dim", "underline", "reverse"], + )); + } + }; + Ok(Self(modifier)) + } +} diff --git a/src/main.rs b/src/main.rs index 53a537a..f536a76 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,20 +19,30 @@ mod workspace; #[cfg(test)] mod test_support; -use std::io; +use std::{error::Error, process::ExitCode}; use clap::Parser; -use crate::{app::App, config::Config, marks::MarkStore, workspace::WorkspaceStore}; +use crate::{app::App, marks::MarkStore, workspace::WorkspaceStore}; /// Terminal Color Theme Explorer 🫏 #[derive(Parser)] #[command(version)] struct Cli {} -fn main() -> io::Result<()> { +fn main() -> ExitCode { Cli::parse(); + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("asinus: {error}"); + ExitCode::FAILURE + } + } +} +fn run() -> Result<(), Box> { + let config = config::load()?; let mut store = MarkStore::from_env()?; let mut workspace_store = WorkspaceStore::from_env()?; let (marks, marks_error) = store.load(); @@ -48,5 +58,6 @@ fn main() -> io::Result<()> { } else { Some((store, workspace_store)) }; - terminal::run(app, Config::default(), stores) + terminal::run(app, config, stores)?; + Ok(()) } diff --git a/src/terminal/tests.rs b/src/terminal/tests.rs index 4ede34e..f269c90 100644 --- a/src/terminal/tests.rs +++ b/src/terminal/tests.rs @@ -2,6 +2,7 @@ use ratatui::{ Terminal, backend::TestBackend, crossterm::event::{KeyCode, KeyModifiers}, + style::Color, }; use rstest::rstest; @@ -52,7 +53,7 @@ fn browser_opening_uses_the_complete_selected_url_and_preserves_the_panel_on_fai render(&mut terminal, &mut app, &config); let failed = terminal.backend().buffer(); let footer = layout::screen(failed.area).unwrap().footer; - assert!(failed[(footer.x, footer.y)].fg == config.ui_theme.error); + assert_eq!(failed[(footer.x, footer.y)].fg, Color::Red); let footer_text: String = (footer.x..footer.right()) .map(|x| failed[(x, footer.y)].symbol()) .collect(); diff --git a/src/ui.rs b/src/ui.rs index 315d449..687d71b 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -224,7 +224,7 @@ fn draw_preset_selection( frame.render_widget( Paragraph::new(format!("{} {label}", if focused { ">" } else { " " })).style( if focused { - theme.active_style() + theme.focus_style() } else { theme.base_style() }, @@ -315,7 +315,7 @@ fn draw_themes( Line::styled( title.trim().to_owned(), if app.context() == InputContext::Browse { - ui_theme.active_style() + ui_theme.focus_style() } else { ui_theme.heading_style() }, @@ -389,7 +389,7 @@ fn matched_name( let style = if selected { Style::default() } else { - ui_theme.match_style() + ui_theme.search_match_style() }; let mut spans = Vec::new(); let mut cursor = 0; @@ -417,11 +417,12 @@ fn matched_name( } fn footer(app: &App, config: &Config, width: u16) -> Line<'static> { - let (message, color) = match &app.notice { - Some(Notice::Message(message)) => (message.clone(), config.ui_theme.notice), - Some(Notice::Success(message)) => (message.clone(), config.ui_theme.success), - Some(Notice::Warning(message)) => (message.clone(), config.ui_theme.warning), - Some(Notice::Error(message)) => (format!("Error: {message}"), config.ui_theme.error), + let theme = config.ui_theme; + let (message, role) = match &app.notice { + Some(Notice::Message(message)) => (message.clone(), theme.notice), + Some(Notice::Success(message)) => (message.clone(), theme.success), + Some(Notice::Warning(message)) => (message.clone(), theme.warning), + Some(Notice::Error(message)) => (format!("Error: {message}"), theme.error), Some(Notice::PinRequired) => ( config .keybindings @@ -430,13 +431,13 @@ fn footer(app: &App, config: &Config, width: u16) -> Line<'static> { || "Pin a theme first".to_owned(), |key| format!("Pin a theme first ({})", key.label()), ), - config.ui_theme.warning, + theme.warning, ), - None => return help::footer(app, width, &config.keybindings, config.ui_theme), + None => return help::footer(app, width, &config.keybindings, theme), }; Line::styled( theme_label(&message, usize::from(width)), - config.ui_theme.base_style().fg(color), + theme.role_style(role), ) } diff --git a/src/ui/colors.rs b/src/ui/colors.rs index f9088d9..b732ed1 100644 --- a/src/ui/colors.rs +++ b/src/ui/colors.rs @@ -81,7 +81,7 @@ pub fn draw(frame: &mut Frame, app: &App, layout: &ColorDetailsLayout, ui: UiThe Some(relation) => Line::styled( relation_label(relation), if relation == ColorRelation::Different && !selected { - style.fg(ui.comparison_diff) + ui.role_style(ui.comparison_diff) } else { style }, @@ -145,7 +145,7 @@ fn draw_header(frame: &mut Frame, area: Rect, app: &App, ui: UiTheme) { let title = Line::styled( "Color details", if app.context() == InputContext::Colors { - ui.active_style() + ui.focus_style() } else { ui.heading_style() }, @@ -201,7 +201,7 @@ fn comparison_summary( }), Span::styled( if compact { "D" } else { "Diff" }, - ui.base_style().fg(ui.comparison_diff), + ui.role_style(ui.comparison_diff), ), Span::raw(if compact { format!("{} M{}", counts[1], counts[2]) diff --git a/src/ui/condition.rs b/src/ui/condition.rs index 4531402..cad4e37 100644 --- a/src/ui/condition.rs +++ b/src/ui/condition.rs @@ -11,7 +11,7 @@ pub fn line(query: &str, theme: UiTheme) -> Line<'static> { } spans.push(Span::styled( query[range.clone()].to_owned(), - theme.condition_key_style(), + theme.role_style(theme.condition_key), )); cursor = range.end; } @@ -48,10 +48,8 @@ mod tests { #[case] query: &str, #[case] expected_keys: &str, ) { - let theme = UiTheme { - condition_key: Color::Magenta, - ..UiTheme::default() - }; + let mut theme = UiTheme::default(); + theme.condition_key.fg = Some(Color::Magenta); let line = line(query, theme); assert_eq!( line.spans diff --git a/src/ui/copy.rs b/src/ui/copy.rs index b04653b..3c092ba 100644 --- a/src/ui/copy.rs +++ b/src/ui/copy.rs @@ -18,7 +18,7 @@ pub fn draw(frame: &mut Frame, app: &App, config: &Config, main: Rect) { let width = main.width.min(52).saturating_sub(4); let mut lines = vec![Line::styled( format!("Target: {}", selection.target.label()), - theme.active_style(), + theme.focus_style(), )]; lines.extend(wrap_text( &format!("Theme: {}", app.copy_theme().unwrap().name), diff --git a/src/ui/help.rs b/src/ui/help.rs index f79d204..acdd9a5 100644 --- a/src/ui/help.rs +++ b/src/ui/help.rs @@ -547,7 +547,7 @@ fn help_entry( let description_x = key_width + 2; if width <= description_x { let mut lines = wrap_lines( - vec![Line::styled(keys.to_owned(), theme.active_style())], + vec![Line::styled(keys.to_owned(), theme.help_key_style())], width, ); lines.extend(wrap_words(description, width).into_iter().map(Line::raw)); @@ -564,7 +564,7 @@ fn help_entry( let key = keys.get(index).cloned().unwrap_or_default(); let padding = description_x - Line::raw(&key).width(); Line::from(vec![ - Span::styled(key, theme.active_style()), + Span::styled(key, theme.help_key_style()), Span::raw(format!( "{}{}", " ".repeat(padding), @@ -687,11 +687,11 @@ fn fit(mut groups: Vec, width: u16, theme: UiTheme) -> Line<'stat } spans.push(Span::styled( group.keys.clone(), - Style::default().fg(theme.key), + theme.role_style(theme.key), )); spans.push(Span::styled( format!(" {}", group.description), - Style::default().fg(theme.muted), + theme.role_style(theme.muted), )); } let line = Line::from(spans); diff --git a/src/ui/info.rs b/src/ui/info.rs index 16dedd4..9e1d8b5 100644 --- a/src/ui/info.rs +++ b/src/ui/info.rs @@ -229,7 +229,7 @@ fn draw_header(frame: &mut Frame, app: &App, layout: &ThemeInfoLayout, ui: UiThe InfoSection::Credits => "Credits", }, if app.context() == InputContext::ThemeInfo { - ui.active_style() + ui.focus_style() } else { ui.heading_style() }, diff --git a/src/ui/preview.rs b/src/ui/preview.rs index 5e4f3ef..6f479c2 100644 --- a/src/ui/preview.rs +++ b/src/ui/preview.rs @@ -75,7 +75,7 @@ fn draw_current_preview( ) { let focused = app.context() == InputContext::Browse && !app.theme_list_visible(); let heading_style = if focused { - ui_theme.active_style() + ui_theme.focus_style() } else { ui_theme.heading_style() }; diff --git a/src/ui/saved.rs b/src/ui/saved.rs index 7c18417..fb51005 100644 --- a/src/ui/saved.rs +++ b/src/ui/saved.rs @@ -40,7 +40,7 @@ pub fn draw(frame: &mut Frame, app: &App, left: Rect, right: Rect, theme: UiThem Line::styled( "Saved filters", if app.context() == InputContext::Saved { - theme.active_style() + theme.focus_style() } else { theme.heading_style() }, @@ -112,7 +112,7 @@ fn filter_dialog(app: &App, main: Rect, theme: UiTheme) -> FilterDialogLayout { let mut input_start = None; let title = match &dialog.kind { DialogKind::New { .. } | DialogKind::Rename { .. } => { - let prefix = Line::styled("> Name ", theme.active_style()); + let prefix = Line::styled("> Name ", theme.focus_style()); input_start = Some((prefix.width() as u16, lines.len() as u16)); lines.push(prefix); if matches!(dialog.kind, DialogKind::New { .. }) { diff --git a/src/ui/search.rs b/src/ui/search.rs index 4cdaeb0..eed46de 100644 --- a/src/ui/search.rs +++ b/src/ui/search.rs @@ -138,7 +138,7 @@ pub fn draw_editor(frame: &mut Frame, app: &App, config: &Config, area: Rect, pr frame.render_widget(block, area); let width = inner.width.saturating_sub(2); frame.render_widget( - Paragraph::new("/ ").style(theme.active_style()), + Paragraph::new("/ ").style(theme.focus_style()), Rect::new(inner.x, inner.y, 2, 1), ); draw_input( @@ -159,10 +159,7 @@ fn editor_panel(name: &str, error: Option<&str>, width: u16, theme: UiTheme) -> panel_with_title( Line::from(vec![ Span::styled(prefix, theme.heading_style()), - Span::styled( - theme_label(error, available), - theme.heading_style().fg(theme.error), - ), + Span::styled(theme_label(error, available), theme.search_error_style()), ]), theme, ) @@ -211,7 +208,7 @@ fn draw_filters(frame: &mut Frame, app: &App, config: &Config, area: Rect, previ frame.render_widget( Paragraph::new(format!("{} {label}", if focused { ">" } else { " " })).style( if focused { - theme.active_style() + theme.focus_style() } else { theme.base_style() }, diff --git a/src/ui/tests.rs b/src/ui/tests.rs index 846f936..bb51692 100644 --- a/src/ui/tests.rs +++ b/src/ui/tests.rs @@ -688,6 +688,44 @@ fn saved_selection_is_visible_in_the_prepared_viewport() { assert!(!text(terminal.backend().buffer()).contains("┃")); } +#[rstest] +#[case(None)] +#[case(Some(Modifier::UNDERLINED))] +fn focus_and_shortcut_keys_use_independent_styles(#[case] key_modifiers: Option) { + let mut app = App::default(); + let mut config = Config::default(); + config.ui_theme.bg = Color::Blue; + config.ui_theme.focus.fg = Some(Color::Magenta); + config.ui_theme.key.fg = Some(Color::Green); + config.ui_theme.key.bg = Some(Color::Reset); + config.ui_theme.key.modifiers = key_modifiers; + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + render(&mut terminal, &mut app, &config); + + let buffer = terminal.backend().buffer(); + let screen = layout::screen(buffer.area).unwrap(); + let themes = screen.theme_preview(&app).themes.unwrap(); + let title = &buffer[(themes.x, themes.y)]; + assert_eq!((title.symbol(), title.fg), ("T", Color::Magenta)); + assert_eq!(title.bg, Color::Blue); + assert!(title.modifier.contains(Modifier::BOLD)); + let key = &buffer[(screen.footer.x, screen.footer.y)]; + assert_eq!((key.symbol(), key.fg), ("j", Color::Green)); + assert_eq!(key.bg, Color::Reset); + assert_eq!(key.modifier, key_modifiers.unwrap_or(Modifier::empty())); + + app.update(Action::ToggleHelp, screen.visible_rows()); + render(&mut terminal, &mut app, &config); + let buffer = terminal.backend().buffer(); + let y = (screen.main.y..screen.main.bottom()) + .find(|&y| row(buffer, y).contains("Select the next theme")) + .unwrap(); + let key = &buffer[(screen.main.x, y)]; + assert_eq!((key.symbol(), key.fg), ("j", Color::Green)); + assert_eq!(key.bg, Color::Reset); + assert_eq!(key.modifier, key_modifiers.unwrap_or(Modifier::BOLD)); +} + #[test] fn custom_bindings_appear_in_footer_notice_and_comparison() { let mut app = App::default(); @@ -864,6 +902,40 @@ fn selection_and_matching_have_distinct_styles_and_aligned_marks() { } } +#[rstest] +#[case(None, Modifier::REVERSED)] +#[case(Some(Modifier::empty()), Modifier::empty())] +fn custom_selection_applies_without_recoloring_preview( + #[case] selection_modifiers: Option, + #[case] expected_modifiers: Modifier, +) { + let mut app = App::default(); + let mut config = Config::default(); + config.ui_theme.bg = Color::Yellow; + config.ui_theme.selection.fg = Some(Color::Black); + config.ui_theme.selection.bg = Some(Color::Blue); + config.ui_theme.selection.modifiers = selection_modifiers; + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + render(&mut terminal, &mut app, &config); + + let buffer = terminal.backend().buffer(); + let screen = layout::screen(buffer.area).unwrap(); + let view = screen.theme_preview(&app); + let list = panel("", config.ui_theme).inner(view.themes.unwrap()); + for x in list.x..list.right() { + let cell = &buffer[(x, list.y)]; + assert_eq!((cell.fg, cell.bg), (Color::Black, Color::Blue)); + assert_eq!(cell.modifier, expected_modifiers); + } + assert_eq!(buffer[(list.x, list.y + 1)].bg, Color::Yellow); + + let theme = app.theme().unwrap(); + let sample = &buffer[(view.preview.x, view.preview.y + 2)]; + assert_eq!(sample.fg, Color::from(theme.foreground)); + assert_eq!(sample.bg, Color::from(theme.background)); + assert!(sample.modifier.is_empty()); +} + #[rstest] #[case(Direction::Horizontal, "Pin: LiquidCarb..", "Current: Liquid..")] #[case( @@ -1459,7 +1531,7 @@ fn modals_keep_reset_borders_and_clear_padding_and_restore_the_original_view( } } let mut config = Config::default(); - config.ui_theme.condition_key = Color::Magenta; + config.ui_theme.condition_key.fg = Some(Color::Magenta); let mut t = Terminal::new(TestBackend::new(w, h)).unwrap(); render(&mut t, &mut app, &config); let before = t.backend().buffer().clone(); diff --git a/src/ui/theme.rs b/src/ui/theme.rs index 12f476f..6310be3 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -1,21 +1,38 @@ use ratatui::style::{Color, Modifier, Style}; +#[derive(Debug, Default, Clone, Copy)] +pub struct UiStyle { + pub fg: Option, + pub bg: Option, + /// An explicit empty set clears the default modifiers for the role. + pub modifiers: Option, +} + +impl UiStyle { + fn foreground(color: Color) -> Self { + Self { + fg: Some(color), + ..Self::default() + } + } +} + #[derive(Debug, Clone, Copy)] pub struct UiTheme { pub fg: Color, pub bg: Color, - pub heading: Color, - pub selection_fg: Color, - pub selection_bg: Color, - pub key: Color, - pub condition_key: Color, - pub muted: Color, - pub match_fg: Color, - pub comparison_diff: Color, - pub notice: Color, - pub warning: Color, - pub error: Color, - pub success: Color, + pub heading: UiStyle, + pub selection: UiStyle, + pub focus: UiStyle, + pub key: UiStyle, + pub condition_key: UiStyle, + pub muted: UiStyle, + pub search_match: UiStyle, + pub comparison_diff: UiStyle, + pub notice: UiStyle, + pub warning: UiStyle, + pub error: UiStyle, + pub success: UiStyle, } impl Default for UiTheme { @@ -23,51 +40,59 @@ impl Default for UiTheme { Self { fg: Color::Reset, bg: Color::Reset, - heading: Color::Reset, - selection_fg: Color::Reset, - selection_bg: Color::Reset, - key: Color::Cyan, - condition_key: Color::Green, - muted: Color::Reset, - match_fg: Color::Yellow, - comparison_diff: Color::Yellow, - notice: Color::Blue, - warning: Color::Yellow, - error: Color::Red, - success: Color::Green, + heading: UiStyle::default(), + selection: UiStyle::default(), + focus: UiStyle::foreground(Color::Cyan), + key: UiStyle::foreground(Color::Cyan), + condition_key: UiStyle::foreground(Color::Green), + muted: UiStyle::default(), + search_match: UiStyle::foreground(Color::Yellow), + comparison_diff: UiStyle::foreground(Color::Yellow), + notice: UiStyle::foreground(Color::Blue), + warning: UiStyle::foreground(Color::Yellow), + error: UiStyle::foreground(Color::Red), + success: UiStyle::foreground(Color::Green), } } } impl UiTheme { - pub fn condition_key_style(self) -> Style { - self.base_style().fg(self.condition_key) + pub fn base_style(self) -> Style { + Style::reset().fg(self.fg).bg(self.bg) } - pub fn active_style(self) -> Style { - self.base_style().fg(self.key).add_modifier(Modifier::BOLD) + pub fn role_style(self, role: UiStyle) -> Style { + self.resolve_style(role, Modifier::empty()) } - pub fn base_style(self) -> Style { - Style::reset().fg(self.fg).bg(self.bg) + pub fn heading_style(self) -> Style { + self.resolve_style(self.heading, Modifier::BOLD) } - pub fn heading_style(self) -> Style { - self.base_style() - .fg(self.heading) - .add_modifier(Modifier::BOLD) + pub fn focus_style(self) -> Style { + self.resolve_style(self.focus, Modifier::BOLD) } pub fn selection_style(self) -> Style { - self.base_style() - .fg(self.selection_fg) - .bg(self.selection_bg) - .add_modifier(Modifier::REVERSED) + self.resolve_style(self.selection, Modifier::REVERSED) + } + + pub fn help_key_style(self) -> Style { + self.resolve_style(self.key, Modifier::BOLD) + } + + pub fn search_match_style(self) -> Style { + self.resolve_style(self.search_match, Modifier::BOLD) + } + + pub fn search_error_style(self) -> Style { + self.resolve_style(self.error, Modifier::BOLD) } - pub fn match_style(self) -> Style { + fn resolve_style(self, role: UiStyle, default_modifiers: Modifier) -> Style { self.base_style() - .fg(self.match_fg) - .add_modifier(Modifier::BOLD) + .fg(role.fg.unwrap_or(self.fg)) + .bg(role.bg.unwrap_or(self.bg)) + .add_modifier(role.modifiers.unwrap_or(default_modifiers)) } } diff --git a/tests/config_e2e.rs b/tests/config_e2e.rs new file mode 100644 index 0000000..5e44794 --- /dev/null +++ b/tests/config_e2e.rs @@ -0,0 +1,159 @@ +mod support; + +use std::{fs, process::Command}; + +use rstest::rstest; +use termlens::Color; + +#[test] +fn configured_ui_styles_are_visible_on_startup() -> termlens::Result<()> { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("config.toml"); + fs::write( + &config, + r##" +[ui.style] +base = { fg = "#D1D2D3", bg = "#101112" } +focus = { fg = "bright_cyan", modifiers = ["underline"] } +key = { bg = "default" } + +[ui.style.selection] +fg = "white" +bg = "bright_white" +modifiers = [] +"##, + ) + .unwrap(); + let mut terminal = termlens::bin!( + "asinus", + size(80, 24), + env_clear(), + env("ASINUS_CONFIG_FILE", config), + env("ASINUS_STATE_PATH", dir.path().join("marks.toml")), + env("ASINUS_WORKSPACE_PATH", dir.path().join("workspace.toml")) + )?; + let screen = support::wait_for_explore(&mut terminal)?; + + let heading = screen.cell(0, 1).unwrap().style(); + assert_eq!(heading.fg, Color::Rgb(0xd1, 0xd2, 0xd3)); + assert_eq!(heading.bg, Color::Rgb(0x10, 0x11, 0x12)); + assert!(heading.bold); + + let focus = screen.cell(4, 1).unwrap().style(); + assert_eq!(focus.fg, Color::Indexed(14)); + assert_eq!(focus.bg, heading.bg); + assert!(focus.underline); + assert!(!focus.bold); + + let selection = screen.cell(6, 5).unwrap().style(); + assert_eq!(selection.fg, Color::Indexed(7)); + assert_eq!(selection.bg, Color::Indexed(15)); + assert!(!selection.reverse); + + let key = screen.cell(23, 1).unwrap().style(); + assert_eq!(key.fg, Color::Indexed(6)); + assert_eq!(key.bg, Color::Default); + + let preview = screen.cell(6, 31).unwrap().style(); + assert_eq!(preview.fg, Color::Rgb(0x4a, 0x45, 0x43)); + assert_eq!(preview.bg, Color::Rgb(0xf7, 0xf7, 0xf7)); + support::quit(&mut terminal) +} + +#[rstest] +#[case(Some("explicit.toml"), Some("xdg"), Color::Indexed(1))] +#[case(None, Some("xdg"), Color::Indexed(2))] +#[case(None, Some(""), Color::Indexed(4))] +#[case(None, None, Color::Indexed(4))] +#[case(None, Some("absent"), Color::Default)] +fn config_path_selects_a_single_file( + #[case] explicit: Option<&str>, + #[case] xdg: Option<&str>, + #[case] expected_fg: Color, +) -> termlens::Result<()> { + let dir = tempfile::tempdir().unwrap(); + for (path, color) in [ + ("explicit.toml", "red"), + ("xdg/asinus/config.toml", "green"), + ("home/.config/asinus/config.toml", "blue"), + ] { + let path = dir.path().join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, format!("[ui.style.base]\nfg = '{color}'")).unwrap(); + } + let mut terminal = termlens::bin!( + "asinus", + size(80, 24), + current_dir(dir.path()), + env_clear(), + envs( + explicit + .into_iter() + .map(|path| ("ASINUS_CONFIG_FILE", path)) + ), + envs(xdg.into_iter().map(|path| ("XDG_CONFIG_HOME", path))), + env("HOME", dir.path().join("home")), + env("ASINUS_STATE_PATH", dir.path().join("marks.toml")), + env("ASINUS_WORKSPACE_PATH", dir.path().join("workspace.toml")) + )?; + let screen = support::wait_for_explore(&mut terminal)?; + assert_eq!(screen.cell(0, 1).unwrap().style().fg, expected_fg); + support::quit(&mut terminal) +} + +#[rstest] +#[case(Some(""), None, "must not be empty")] +#[case(Some("missing.toml"), None, "was not found: missing.toml")] +#[case(None, Some("[ui.theme]"), "unknown field `theme`")] +#[case(None, Some("[ui.style.foucs]"), "unknown field `foucs`")] +#[case( + None, + Some("[ui.style.base]\nmodifiers = []"), + "unknown field `modifiers`" +)] +#[case(None, Some("[ui.style.focus]\nfg = 'light-cyan'"), "invalid color")] +#[case(None, Some("[ui.style.focus]\nfg = '#+12345'"), "invalid color")] +#[case( + None, + Some("[ui.style.focus]\nmodifiers = ['blink']"), + "unknown variant `blink`" +)] +#[case( + None, + Some("[ui.style.focus]\nmodifiers = [{ bold = {} }]"), + "expected a string" +)] +fn invalid_configuration_fails_before_initializing_state( + #[case] explicit: Option<&str>, + #[case] content: Option<&str>, + #[case] reason: &str, +) { + let dir = tempfile::tempdir().unwrap(); + let config = "xdg/asinus/config.toml"; + if let Some(content) = content { + let path = dir.path().join(config); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + let state = dir.path().join("state"); + let output = Command::new(env!("CARGO_BIN_EXE_asinus")) + .current_dir(dir.path()) + .env_clear() + .envs( + explicit + .into_iter() + .map(|path| ("ASINUS_CONFIG_FILE", path)), + ) + .env("XDG_CONFIG_HOME", "xdg") + .env("XDG_DATA_HOME", &state) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert!(!state.exists()); + let error = String::from_utf8_lossy(&output.stderr); + assert!(error.contains(reason), "{error}"); + if content.is_some() { + assert!(error.contains(config), "{error}"); + } +} diff --git a/tests/copy_e2e.rs b/tests/copy_e2e.rs index 09ea7ae..f542709 100644 --- a/tests/copy_e2e.rs +++ b/tests/copy_e2e.rs @@ -37,6 +37,7 @@ fn start(path: &Path, width: u16, height: u16) -> termlens::Result { let mut terminal = termlens::bin!( "asinus", size(width, height), + env_clear(), env("ASINUS_STATE_PATH", path.join("marks.toml")), env("ASINUS_WORKSPACE_PATH", path.join("workspace.toml")), env("PATH", path), diff --git a/tests/marks_e2e.rs b/tests/marks_e2e.rs index 9403ef7..92cd35a 100644 --- a/tests/marks_e2e.rs +++ b/tests/marks_e2e.rs @@ -209,6 +209,7 @@ fn default_storage_respects_data_home_and_is_created_on_first_mark( .join("asinus/marks.toml"); let mut terminal = termlens::bin!( "asinus", + env_clear(), env("HOME", home.path()), envs(xdg.into_iter().map(|path| ("XDG_DATA_HOME", path))) )?; diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 2123b16..3a9fff1 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -20,6 +20,7 @@ pub fn spawn( termlens::bin!( "asinus", size(width, height), + env_clear(), env("ASINUS_STATE_PATH", marks), env("ASINUS_WORKSPACE_PATH", workspace) )