T1: four more themes, theme picker, theme file import, editor font settings
Plum Night, River, Paper and Reed (designed by Amy, approved by Daniel) join the brand pair. theme.list/current/select/import, a picker with live preview (view.selectTheme) and "Import Theme…" (view.importTheme); imported themes are validated and stored in <data_dir>/themes. Editor font family and line height settings apply live. Docs: docs/themes.md. Gate: fmt, clippy and the rest pass up to cargo test, where only the unrelated lutra-terminal PTY test a_full_buffer_stops_the_shell timed out under load; to be re-run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
872b5cb258
commit
086bc8a925
26 changed files with 2881 additions and 100 deletions
|
|
@ -55,6 +55,9 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(settings::Set))?;
|
||||
registry.register(Box::new(settings::Reset))?;
|
||||
registry.register(Box::new(theme::List))?;
|
||||
registry.register(Box::new(theme::Current))?;
|
||||
registry.register(Box::new(theme::Select))?;
|
||||
registry.register(Box::new(theme::Import))?;
|
||||
registry.register(Box::new(theme::SystemPreference))?;
|
||||
registry.register(Box::new(ui::RegisterCommands))?;
|
||||
registry.register(Box::new(search::Find))?;
|
||||
|
|
|
|||
|
|
@ -19,12 +19,24 @@ impl Command for List {
|
|||
label: "List Settings",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns [{ key, type: enum|int|bool|string, default, enumValues?, min?, max?, labelKey, descriptionKey, section }]",
|
||||
params: "none; returns [{ key, type: enum|int|bool|string, default, enumValues?, valueNames?, min?, max?, labelKey, descriptionKey, section }]; valueNames holds display names of enum values without a catalog key (imported themes)",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let list: Vec<_> = DEFS.iter().map(settings::Def::info).collect();
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let mut list: Vec<_> = DEFS.iter().map(settings::Def::info).collect();
|
||||
if let Some(info) = list.iter_mut().find(|i| i.key == theme::SETTING) {
|
||||
let (ids, names) = theme::choices(state);
|
||||
info.enum_values = Some(ids);
|
||||
if !names.is_empty() {
|
||||
info.value_names = Some(
|
||||
names
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| Some((k, v.as_str()?.to_string())))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let value = serde_json::to_value(list).map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
Ok(Outcome::value(value))
|
||||
}
|
||||
|
|
@ -97,6 +109,16 @@ impl Command for Set {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let id = self.spec().id;
|
||||
let p: SetParams = parse(id, params)?;
|
||||
if p.key == theme::SETTING
|
||||
&& let Some(name) = p.value.as_str()
|
||||
&& !theme::known(state, name)
|
||||
{
|
||||
let (ids, _) = theme::choices(state);
|
||||
return Err(EngineError::invalid_params(
|
||||
id,
|
||||
format!("unknown theme: {name}; known: {}", ids.join(", ")),
|
||||
));
|
||||
}
|
||||
let before = theme::resolved(state);
|
||||
let changed = state
|
||||
.settings
|
||||
|
|
@ -138,7 +160,7 @@ impl Command for Reset {
|
|||
}
|
||||
|
||||
/// Maps a settings error to the command error.
|
||||
fn set_error(command: &str, error: SetError) -> EngineError {
|
||||
pub(crate) fn set_error(command: &str, error: SetError) -> EngineError {
|
||||
match error {
|
||||
SetError::Invalid(message) => EngineError::invalid_params(command, message),
|
||||
SetError::Save(message) => {
|
||||
|
|
@ -153,7 +175,7 @@ fn finish(
|
|||
state: &mut State,
|
||||
key: &str,
|
||||
changed: bool,
|
||||
before: crate::theme::Theme,
|
||||
before: crate::theme::ResolvedTheme,
|
||||
) -> Result<Outcome, EngineError> {
|
||||
if changed {
|
||||
state.emit(Event::SettingsChanged {
|
||||
|
|
|
|||
|
|
@ -1,45 +1,190 @@
|
|||
//! Theme commands: `theme.list` and `theme.systemPreference`. Switching
|
||||
//! themes goes through `settings.set appearance.theme`; whenever the
|
||||
//! resolved theme changes, `themeChanged` carries its tokens.
|
||||
//! Theme commands: `theme.list`, `theme.current`, `theme.select`,
|
||||
//! `theme.import` and `theme.systemPreference`. The selected theme is the
|
||||
//! setting `appearance.theme`; whenever the resolved theme changes,
|
||||
//! `themeChanged` carries its tokens. Imported themes live as normalised
|
||||
//! theme files in `<data_dir>/themes/<id>.json` and are loaded at start
|
||||
//! ([`load_imported`]).
|
||||
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::cmd::params::parse;
|
||||
use crate::theme::{self, BUILTIN, Theme};
|
||||
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
|
||||
use crate::theme::{self, BUILTIN, ResolvedTheme, UserTheme};
|
||||
use crate::{Command, CommandSpec, EngineError, Event, NotificationLevel, Outcome, State};
|
||||
|
||||
/// The setting that selects the theme.
|
||||
pub const SETTING: &str = "appearance.theme";
|
||||
|
||||
/// Directory of imported themes inside the data directory.
|
||||
pub const DIR_NAME: &str = "themes";
|
||||
|
||||
/// Most imported themes loaded at start; further files are ignored.
|
||||
pub const MAX_IMPORTED: usize = 200;
|
||||
|
||||
/// The theme the current settings and OS preference resolve to.
|
||||
pub fn resolved(state: &State) -> Theme {
|
||||
pub fn resolved(state: &State) -> ResolvedTheme {
|
||||
let setting = state.settings.get(SETTING);
|
||||
let id = setting
|
||||
.as_ref()
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(theme::SYSTEM);
|
||||
theme::resolve(id, state.system_dark)
|
||||
theme::resolve_with(id, state.system_dark, &state.themes)
|
||||
}
|
||||
|
||||
/// Whether `id` names a theme Lutra can apply: [`theme::SYSTEM`], a
|
||||
/// built-in theme or an imported one.
|
||||
pub fn known(state: &State, id: &str) -> bool {
|
||||
theme::reserved_id(id) || state.themes.iter().any(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// Every theme id in picker order (built-in, imported by name, then
|
||||
/// `system`) and the names of the imported ones, for `settings.list`.
|
||||
pub fn choices(state: &State) -> (Vec<String>, Map<String, Value>) {
|
||||
let mut ids: Vec<String> = BUILTIN.iter().map(|t| t.id.to_string()).collect();
|
||||
let mut names = Map::new();
|
||||
for t in sorted_imports(state) {
|
||||
ids.push(t.id.clone());
|
||||
names.insert(t.id.clone(), Value::from(t.name.clone()));
|
||||
}
|
||||
ids.push(theme::SYSTEM.to_string());
|
||||
(ids, names)
|
||||
}
|
||||
|
||||
/// The imported themes sorted by name, then id.
|
||||
fn sorted_imports(state: &State) -> Vec<&UserTheme> {
|
||||
let mut list: Vec<_> = state.themes.iter().collect();
|
||||
list.sort_by(|a, b| {
|
||||
a.name
|
||||
.to_lowercase()
|
||||
.cmp(&b.name.to_lowercase())
|
||||
.then_with(|| a.id.cmp(&b.id))
|
||||
});
|
||||
list
|
||||
}
|
||||
|
||||
/// The `themeChanged` event for a theme.
|
||||
pub fn changed_event(theme: &Theme) -> Event {
|
||||
pub fn changed_event(theme: &ResolvedTheme) -> Event {
|
||||
Event::ThemeChanged {
|
||||
id: theme.id.to_string(),
|
||||
id: theme.id.clone(),
|
||||
dark: theme.dark,
|
||||
tokens: theme::token_map(theme),
|
||||
tokens: theme.tokens.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits `themeChanged` if the resolved theme is no longer `before`.
|
||||
pub fn emit_if_changed(state: &mut State, before: Theme) {
|
||||
pub fn emit_if_changed(state: &mut State, before: ResolvedTheme) {
|
||||
let now = resolved(state);
|
||||
if now != before {
|
||||
state.emit(changed_event(&now));
|
||||
}
|
||||
}
|
||||
|
||||
/// `theme.list`: the built-in themes.
|
||||
/// A resolved theme as a command result: `{ id, dark, tokens }`.
|
||||
fn theme_value(theme: &ResolvedTheme) -> Value {
|
||||
json!({ "id": theme.id, "dark": theme.dark, "tokens": theme.tokens })
|
||||
}
|
||||
|
||||
/// The directory of imported themes, or `None` without persistence.
|
||||
fn themes_dir(state: &State) -> Option<PathBuf> {
|
||||
state.config.as_ref().map(|c| c.data_dir.join(DIR_NAME))
|
||||
}
|
||||
|
||||
/// Reads a theme file with the size cap of [`theme::MAX_FILE_SIZE`].
|
||||
///
|
||||
/// # Errors
|
||||
/// An English sentence for the user: the file cannot be read, is too
|
||||
/// large or is not a valid theme file.
|
||||
fn read_theme_file(path: &Path) -> Result<UserTheme, String> {
|
||||
let file = fs::File::open(path).map_err(|e| format!("cannot read it: {e}"))?;
|
||||
let mut text = String::new();
|
||||
file.take(theme::MAX_FILE_SIZE + 1)
|
||||
.read_to_string(&mut text)
|
||||
.map_err(|e| format!("cannot read it as UTF-8 text: {e}"))?;
|
||||
if text.len() as u64 > theme::MAX_FILE_SIZE {
|
||||
return Err(format!(
|
||||
"it is larger than {} KiB",
|
||||
theme::MAX_FILE_SIZE / 1024
|
||||
));
|
||||
}
|
||||
theme::parse_file(&text)
|
||||
}
|
||||
|
||||
/// Loads the imported themes from `<data_dir>/themes/*.json` into the
|
||||
/// state. A missing directory means none. A file that is not a valid
|
||||
/// theme file, or whose id another file already took, is skipped with a
|
||||
/// warning notification naming it and the reason, so a broken file never
|
||||
/// blocks startup. At most [`MAX_IMPORTED`] files are read.
|
||||
pub fn load_imported(state: &mut State) {
|
||||
let Some(dir) = themes_dir(state) else {
|
||||
return;
|
||||
};
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
return;
|
||||
};
|
||||
let mut paths: Vec<PathBuf> = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|ext| ext == "json"))
|
||||
.collect();
|
||||
paths.sort();
|
||||
for path in paths.into_iter().take(MAX_IMPORTED) {
|
||||
match read_theme_file(&path) {
|
||||
Ok(theme) if !state.themes.iter().any(|t| t.id == theme.id) => {
|
||||
state.themes.push(theme);
|
||||
}
|
||||
Ok(theme) => broken_file(state, &path, &format!("the id {} is taken", theme.id)),
|
||||
Err(reason) => broken_file(state, &path, &reason),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Warns that an imported theme file was skipped.
|
||||
fn broken_file(state: &mut State, path: &Path, reason: &str) {
|
||||
let file = path.display().to_string();
|
||||
let mut params = Map::new();
|
||||
params.insert("file".into(), Value::from(file.clone()));
|
||||
params.insert("reason".into(), Value::from(reason));
|
||||
state.notify(
|
||||
NotificationLevel::Warning,
|
||||
Some("theme.notification.skipped"),
|
||||
Some(format!("Skipped the theme file {file}: {reason}")),
|
||||
Some(params),
|
||||
);
|
||||
}
|
||||
|
||||
/// Sets `appearance.theme` to a known theme and emits `settingsChanged`
|
||||
/// and, if the resolved theme changed, `themeChanged`.
|
||||
///
|
||||
/// # Errors
|
||||
/// `invalid_params` for an unknown id; `failed` if the settings cannot be
|
||||
/// saved.
|
||||
pub fn select(state: &mut State, command: &str, id: &str) -> Result<(), EngineError> {
|
||||
if !known(state, id) {
|
||||
let (ids, _) = choices(state);
|
||||
return Err(EngineError::invalid_params(
|
||||
command,
|
||||
format!("unknown theme: {id}; known: {}", ids.join(", ")),
|
||||
));
|
||||
}
|
||||
let before = resolved(state);
|
||||
let changed = state
|
||||
.settings
|
||||
.set(SETTING, Value::from(id))
|
||||
.map_err(|e| super::settings::set_error(command, e))?;
|
||||
if changed {
|
||||
state.emit(Event::SettingsChanged {
|
||||
keys: vec![SETTING.to_string()],
|
||||
});
|
||||
emit_if_changed(state, before);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `theme.list`: the built-in and imported themes.
|
||||
pub struct List;
|
||||
|
||||
impl Command for List {
|
||||
|
|
@ -49,16 +194,156 @@ impl Command for List {
|
|||
label: "List Themes",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns [{ id, label, dark }], label is a message-catalog key",
|
||||
params: "none; returns [{ id, label, name, dark, builtin, tokens }]: label is a message-catalog key (null for an imported theme), name is the imported theme's display name (null for a built-in one), tokens as in themeChanged",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let list: Vec<_> = BUILTIN
|
||||
.iter()
|
||||
.map(|t| json!({ "id": t.id, "label": t.label_key, "dark": t.dark }))
|
||||
.collect();
|
||||
Ok(Outcome::value(Value::Array(list)))
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let builtin = BUILTIN.iter().map(|t| {
|
||||
json!({
|
||||
"id": t.id,
|
||||
"label": t.label_key,
|
||||
"name": Value::Null,
|
||||
"dark": t.dark,
|
||||
"builtin": true,
|
||||
"tokens": theme::token_map(t),
|
||||
})
|
||||
});
|
||||
let imported = sorted_imports(state).into_iter().map(|t| {
|
||||
json!({
|
||||
"id": t.id,
|
||||
"label": Value::Null,
|
||||
"name": t.name,
|
||||
"dark": t.dark,
|
||||
"builtin": false,
|
||||
"tokens": t.resolved().tokens,
|
||||
})
|
||||
});
|
||||
Ok(Outcome::value(Value::Array(
|
||||
builtin.chain(imported).collect(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `theme.current`: the theme in use.
|
||||
pub struct Current;
|
||||
|
||||
impl Command for Current {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "theme.current",
|
||||
label: "Current Theme",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns the resolved theme { id, dark, tokens }",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
Ok(Outcome::value(theme_value(&resolved(state))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `theme.select`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SelectParams {
|
||||
/// Theme id or `system`.
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// `theme.select`: switches the theme, live.
|
||||
pub struct Select;
|
||||
|
||||
impl Command for Select {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "theme.select",
|
||||
label: "Select Theme",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ id }: a theme id from theme.list or \"system\"; returns the resolved theme { id, dark, tokens }; emits settingsChanged and themeChanged",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let id = self.spec().id;
|
||||
let p: SelectParams = parse(id, params)?;
|
||||
select(state, id, &p.id)?;
|
||||
Ok(Outcome::value(theme_value(&resolved(state))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `theme.import`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ImportParams {
|
||||
/// Path of the theme file.
|
||||
path: PathBuf,
|
||||
/// Whether to switch to the theme; true when absent.
|
||||
select: Option<bool>,
|
||||
}
|
||||
|
||||
/// `theme.import`: reads a theme file, keeps it in the data directory and,
|
||||
/// by default, switches to it. Importing an id again replaces that theme.
|
||||
pub struct Import;
|
||||
|
||||
impl Command for Import {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "theme.import",
|
||||
label: "Import Theme",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ path, select?: bool = true }; returns { id, name, dark, replaced }; failed with the reason for an unreadable or invalid file (format: docs/themes.md); emits settingsChanged for appearance.theme",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let id = self.spec().id;
|
||||
let p: ImportParams = parse(id, params)?;
|
||||
let imported = read_theme_file(&p.path).map_err(|reason| {
|
||||
EngineError::Failed(format!(
|
||||
"cannot import the theme {}: {reason}",
|
||||
p.path.display()
|
||||
))
|
||||
})?;
|
||||
if let Some(dir) = themes_dir(state) {
|
||||
let text = serde_json::to_string_pretty(&imported.to_file())
|
||||
.map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
fs::create_dir_all(&dir)
|
||||
.and_then(|()| fs::write(dir.join(format!("{}.json", imported.id)), text))
|
||||
.map_err(|e| {
|
||||
EngineError::Failed(format!("cannot store the theme in {}: {e}", dir.display()))
|
||||
})?;
|
||||
}
|
||||
let before = resolved(state);
|
||||
let replaced = match state.themes.iter_mut().find(|t| t.id == imported.id) {
|
||||
Some(slot) => {
|
||||
*slot = imported.clone();
|
||||
true
|
||||
}
|
||||
None => {
|
||||
state.themes.push(imported.clone());
|
||||
false
|
||||
}
|
||||
};
|
||||
if p.select.unwrap_or(true) {
|
||||
state
|
||||
.settings
|
||||
.set(SETTING, Value::from(imported.id.clone()))
|
||||
.map_err(|e| super::settings::set_error(id, e))?;
|
||||
}
|
||||
state.emit(Event::SettingsChanged {
|
||||
keys: vec![SETTING.to_string()],
|
||||
});
|
||||
emit_if_changed(state, before);
|
||||
Ok(Outcome::value(json!({
|
||||
"id": imported.id,
|
||||
"name": imported.name,
|
||||
"dark": imported.dark,
|
||||
"replaced": replaced,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -90,18 +375,17 @@ impl Command for SystemPreference {
|
|||
let before = resolved(state);
|
||||
state.system_dark = Some(p.dark);
|
||||
emit_if_changed(state, before);
|
||||
let now = resolved(state);
|
||||
let value = serde_json::to_value(changed_event(&now))
|
||||
.map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
let Value::Object(mut fields) = value else {
|
||||
return Err(EngineError::Internal("theme is not an object".into()));
|
||||
};
|
||||
fields.remove("kind");
|
||||
Ok(Outcome::value(Value::Object(fields)))
|
||||
Ok(Outcome::value(theme_value(&resolved(state))))
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the commands this module registers, checked against the
|
||||
/// registry by the engine's listing test. Add a new command's id here.
|
||||
#[cfg(test)]
|
||||
pub(crate) const COMMAND_IDS: &[&str] = &["theme.list", "theme.systemPreference"];
|
||||
pub(crate) const COMMAND_IDS: &[&str] = &[
|
||||
"theme.list",
|
||||
"theme.current",
|
||||
"theme.select",
|
||||
"theme.import",
|
||||
"theme.systemPreference",
|
||||
];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue