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",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ impl Engine {
|
|||
let (settings, problem) = Settings::load(&config.config_dir);
|
||||
engine.state.settings = settings;
|
||||
engine.state.config = Some(config);
|
||||
cmd::theme::load_imported(&mut engine.state);
|
||||
if let Some(problem) = problem {
|
||||
engine.state.notify(
|
||||
NotificationLevel::Warning,
|
||||
|
|
|
|||
|
|
@ -48,6 +48,19 @@ pub enum Kind {
|
|||
/// Longest accepted value in bytes.
|
||||
max_len: usize,
|
||||
},
|
||||
/// A theme id or `system`: any well-formed id
|
||||
/// ([`crate::theme::valid_id`]), so an imported theme's id survives a
|
||||
/// restart. `settings.set` also requires the theme to exist; listed as
|
||||
/// an enum of the built-in ids and `system`, which `settings.list`
|
||||
/// extends with the imported ones.
|
||||
Theme,
|
||||
/// A font family list for CSS, such as `"Fira Code", monospace`: at
|
||||
/// most `max_len` bytes without control characters or `;{}<>\`, so it
|
||||
/// cannot leave the `font-family` value. Empty means the theme's font.
|
||||
FontFamily {
|
||||
/// Longest accepted value in bytes.
|
||||
max_len: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// Checks a path setting's text: at most `max_len` bytes, no control
|
||||
|
|
@ -162,22 +175,57 @@ impl Def {
|
|||
}
|
||||
None => Err(format!("{} must be a path string, got {value}", self.key)),
|
||||
},
|
||||
Kind::Theme => match value.as_str() {
|
||||
Some(s) if crate::theme::valid_id(s) => Ok(()),
|
||||
_ => Err(format!(
|
||||
"{} must be a theme id (lowercase letters, digits and dashes) or system, got {value}",
|
||||
self.key
|
||||
)),
|
||||
},
|
||||
Kind::FontFamily { max_len } => match value.as_str() {
|
||||
Some(s)
|
||||
if s.len() <= max_len
|
||||
&& !s.chars().any(|c| c.is_control() || ";{}<>\\".contains(c)) =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(format!(
|
||||
"{} must be a font family list of at most {max_len} bytes without control characters or ; {{ }} < > \\",
|
||||
self.key
|
||||
)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The description for `settings.list`.
|
||||
pub fn info(&self) -> SettingInfo {
|
||||
let (kind, enum_values, min, max) = match self.kind {
|
||||
Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None),
|
||||
Kind::Enum(values) => (
|
||||
"enum",
|
||||
Some(values.iter().map(|v| (*v).to_string()).collect()),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
Kind::Int { min, max } => ("int", None, Some(min), Some(max)),
|
||||
Kind::Bool => ("bool", None, None, None),
|
||||
Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None),
|
||||
Kind::Str { .. } | Kind::Path { .. } | Kind::FontFamily { .. } => {
|
||||
("string", None, None, None)
|
||||
}
|
||||
Kind::Theme => {
|
||||
let mut ids: Vec<_> = crate::theme::BUILTIN
|
||||
.iter()
|
||||
.map(|t| t.id.to_string())
|
||||
.collect();
|
||||
ids.push(crate::theme::SYSTEM.to_string());
|
||||
("enum", Some(ids), None, None)
|
||||
}
|
||||
};
|
||||
SettingInfo {
|
||||
key: self.key,
|
||||
kind,
|
||||
default: self.default.to_value(),
|
||||
enum_values,
|
||||
value_names: None,
|
||||
min,
|
||||
max,
|
||||
path: matches!(self.kind, Kind::Path { .. }),
|
||||
|
|
@ -201,7 +249,11 @@ pub struct SettingInfo {
|
|||
pub default: Value,
|
||||
/// Accepted values of an enum.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enum_values: Option<Vec<&'static str>>,
|
||||
pub enum_values: Option<Vec<String>>,
|
||||
/// Display names of enum values that have no catalog key, such as
|
||||
/// imported themes, by value.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub value_names: Option<std::collections::BTreeMap<String, String>>,
|
||||
/// Smallest value of an int.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub min: Option<i64>,
|
||||
|
|
@ -224,7 +276,7 @@ pub struct SettingInfo {
|
|||
pub const DEFS: &[Def] = &[
|
||||
Def {
|
||||
key: "appearance.theme",
|
||||
kind: Kind::Enum(&["lutra-dark", "lutra-light", "system"]),
|
||||
kind: Kind::Theme,
|
||||
default: DefaultValue::Str("system"),
|
||||
label_key: "settings.appearance.theme.label",
|
||||
description_key: "settings.appearance.theme.description",
|
||||
|
|
@ -238,6 +290,22 @@ pub const DEFS: &[Def] = &[
|
|||
description_key: "settings.editor.fontSize.description",
|
||||
section: "editor",
|
||||
},
|
||||
Def {
|
||||
key: "editor.fontFamily",
|
||||
kind: Kind::FontFamily { max_len: 256 },
|
||||
default: DefaultValue::Str(""),
|
||||
label_key: "settings.editor.fontFamily.label",
|
||||
description_key: "settings.editor.fontFamily.description",
|
||||
section: "editor",
|
||||
},
|
||||
Def {
|
||||
key: "editor.lineHeight",
|
||||
kind: Kind::Int { min: 100, max: 300 },
|
||||
default: DefaultValue::Int(150),
|
||||
label_key: "settings.editor.lineHeight.label",
|
||||
description_key: "settings.editor.lineHeight.description",
|
||||
section: "editor",
|
||||
},
|
||||
Def {
|
||||
key: "ui.language",
|
||||
kind: Kind::Enum(&["en"]),
|
||||
|
|
@ -687,9 +755,31 @@ mod tests {
|
|||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
s.set("appearance.theme", json!("dark")),
|
||||
s.set("appearance.theme", json!("Dark Mode")),
|
||||
Err(SetError::Invalid(_))
|
||||
));
|
||||
assert_eq!(s.set("appearance.theme", json!("my-import")), Ok(true));
|
||||
assert_eq!(s.get("editor.fontFamily"), Some(json!("")));
|
||||
assert_eq!(s.get("editor.lineHeight"), Some(json!(150)));
|
||||
assert_eq!(
|
||||
s.set("editor.fontFamily", json!("\"Fira Code\", monospace")),
|
||||
Ok(true)
|
||||
);
|
||||
for bad in ["a; color: red", "x{", "</style>", "a\\b", "tab\there"] {
|
||||
assert!(
|
||||
matches!(
|
||||
s.set("editor.fontFamily", json!(bad)),
|
||||
Err(SetError::Invalid(_))
|
||||
),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
for bad in [json!(99), json!(301), json!(1.5)] {
|
||||
assert!(matches!(
|
||||
s.set("editor.lineHeight", bad),
|
||||
Err(SetError::Invalid(_))
|
||||
));
|
||||
}
|
||||
assert!(matches!(s.set("x.y", json!(1)), Err(SetError::Invalid(_))));
|
||||
assert_eq!(s.get("editor.fontSize"), Some(json!(16)));
|
||||
assert_eq!(s.reset("editor.fontSize"), Ok(true));
|
||||
|
|
@ -812,7 +902,7 @@ mod tests {
|
|||
"key": "appearance.theme",
|
||||
"type": "enum",
|
||||
"default": "system",
|
||||
"enumValues": ["lutra-dark", "lutra-light", "system"],
|
||||
"enumValues": ["lutra-dark", "lutra-light", "lutra-plum-night", "lutra-river", "lutra-paper", "lutra-reed", "system"],
|
||||
"labelKey": "settings.appearance.theme.label",
|
||||
"descriptionKey": "settings.appearance.theme.description",
|
||||
"section": "appearance",
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ pub struct State {
|
|||
/// Whether the OS prefers a dark theme, as the frontend reported it with
|
||||
/// `theme.systemPreference`; `None` until then.
|
||||
pub system_dark: Option<bool>,
|
||||
/// Themes imported from theme files (`theme.import`), loaded from
|
||||
/// `<data_dir>/themes` at start.
|
||||
pub themes: Vec<crate::theme::UserTheme>,
|
||||
/// Where the engine stores its files; `None` for an engine without
|
||||
/// persistence ([`crate::Engine::new`]).
|
||||
pub config: Option<EngineConfig>,
|
||||
|
|
|
|||
|
|
@ -8,9 +8,15 @@
|
|||
//! meet WCAG AA in both themes; `ui/tests/theme` checks it against the snapshot `ui/tests/theme/themes.json`, which the test
|
||||
//! `ui_snapshot_is_current` keeps in step with this file.
|
||||
//!
|
||||
//! Besides the brand pair (`lutra-dark`, `lutra-light`) Lutra ships four
|
||||
//! more themes from the same palette family (C9): Plum Night and River
|
||||
//! (dark), Paper and Reed (light). Users can import their own as theme
|
||||
//! files ([`parse_file`], format in `docs/themes.md`); the engine keeps
|
||||
//! them as [`UserTheme`]s and [`resolve_with`] finds them.
|
||||
//!
|
||||
//! The setting `appearance.theme` holds a theme id or [`SYSTEM`]. "System"
|
||||
//! follows the OS: the frontend reports the OS preference and
|
||||
//! [`resolve`] picks the theme.
|
||||
//! [`resolve`] picks the theme (always the brand pair).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
|
|
@ -30,7 +36,10 @@ pub struct Theme {
|
|||
/// The `appearance.theme` value that follows the OS preference.
|
||||
pub const SYSTEM: &str = "system";
|
||||
|
||||
/// Tokens shared by every theme (fonts and sizes).
|
||||
/// Tokens shared by every theme (fonts, sizes and the editor's line
|
||||
/// height). The editor settings `editor.fontFamily`, `editor.fontSize` and
|
||||
/// `editor.lineHeight` override `font-mono`, `font-size-editor` and
|
||||
/// `line-height-editor` in the frontend.
|
||||
const COMMON: &[(&str, &str)] = &[
|
||||
(
|
||||
"font-ui",
|
||||
|
|
@ -43,6 +52,7 @@ const COMMON: &[(&str, &str)] = &[
|
|||
("font-size-ui", "13px"),
|
||||
("font-size-small", "12px"),
|
||||
("font-size-editor", "14px"),
|
||||
("line-height-editor", "1.5"),
|
||||
];
|
||||
|
||||
/// Syntax token names (`--lt-syntax-<name>`) every theme defines. The
|
||||
|
|
@ -249,8 +259,281 @@ pub const LIGHT: Theme = Theme {
|
|||
],
|
||||
};
|
||||
|
||||
/// Every built-in theme.
|
||||
pub const BUILTIN: &[Theme] = &[DARK, LIGHT];
|
||||
/// Plum Night (dark): Deep, warm plum surfaces with a soft cream-gold accent. The banner after sunset: cosy for long evening sessions.
|
||||
pub const PLUM_NIGHT: Theme = Theme {
|
||||
id: "lutra-plum-night",
|
||||
label_key: "theme.lutraPlumNight",
|
||||
dark: true,
|
||||
tokens: &[
|
||||
("bg", "#241a22"),
|
||||
("editor-bg", "#1c1419"),
|
||||
("fg", "#f0e6dc"),
|
||||
("fg-muted", "#a8969f"),
|
||||
("border", "#3d2c38"),
|
||||
("accent", "#e6c27f"),
|
||||
("error", "#f48a78"),
|
||||
("statusbar-bg", "#2a1e27"),
|
||||
("statusbar-fg", "#c4b3bb"),
|
||||
("editor-selection-bg", "#56334a"),
|
||||
("editor-active-line-bg", "#291e27"),
|
||||
("editor-cursor", "#e6c27f"),
|
||||
("editor-gutter-bg", "#1c1419"),
|
||||
("editor-gutter-fg", "#a8969f"),
|
||||
("editor-match-bg", "#43303a"),
|
||||
("tab-active-bg", "#1c1419"),
|
||||
("tab-modified", "#e6c27f"),
|
||||
("notice-bg", "#3e2836"),
|
||||
("syntax-keyword", "#ec92bd"),
|
||||
("syntax-string", "#b6c98a"),
|
||||
("syntax-number", "#efa985"),
|
||||
("syntax-comment", "#9c8a94"),
|
||||
("syntax-variable", "#e3cdbb"),
|
||||
("syntax-function", "#ebca7d"),
|
||||
("syntax-type", "#8cc0cc"),
|
||||
("syntax-constant", "#c5a8ec"),
|
||||
("syntax-tag", "#e8907a"),
|
||||
("syntax-attribute", "#d4b98a"),
|
||||
("syntax-operator", "#c4b3bb"),
|
||||
("diag-error", "#f48a78"),
|
||||
("diag-warning", "#e8b85a"),
|
||||
("diag-info", "#9db4ea"),
|
||||
("diag-hint", "#a8969f"),
|
||||
("vcs-added", "#a6c784"),
|
||||
("vcs-modified", "#9db4ea"),
|
||||
("vcs-deleted", "#dc9890"),
|
||||
("vcs-untracked", "#e8aa6c"),
|
||||
("vcs-ignored", "#9e8e97"),
|
||||
("vcs-conflicted", "#f6788e"),
|
||||
("terminal-bg", "#1c1419"),
|
||||
("terminal-fg", "#f0e6dc"),
|
||||
("terminal-cursor", "#e6c27f"),
|
||||
("terminal-selection-bg", "#56334a"),
|
||||
("terminal-ansi-black", "#33262f"),
|
||||
("terminal-ansi-red", "#f28474"),
|
||||
("terminal-ansi-green", "#b6c98a"),
|
||||
("terminal-ansi-yellow", "#ebca7d"),
|
||||
("terminal-ansi-blue", "#98aee6"),
|
||||
("terminal-ansi-magenta", "#ec92bd"),
|
||||
("terminal-ansi-cyan", "#8cc0cc"),
|
||||
("terminal-ansi-white", "#d9cdc6"),
|
||||
("terminal-ansi-bright-black", "#a8969f"),
|
||||
("terminal-ansi-bright-red", "#f8a596"),
|
||||
("terminal-ansi-bright-green", "#cbdca6"),
|
||||
("terminal-ansi-bright-yellow", "#f4dc9a"),
|
||||
("terminal-ansi-bright-blue", "#b8c6f2"),
|
||||
("terminal-ansi-bright-magenta", "#f4b0cf"),
|
||||
("terminal-ansi-bright-cyan", "#acd6de"),
|
||||
("terminal-ansi-bright-white", "#faf3ea"),
|
||||
],
|
||||
};
|
||||
|
||||
/// River (dark): Cool slate and river teal, with raspberry keywords as the family link. Calm and crisp, like the water an otter dives into.
|
||||
pub const RIVER: Theme = Theme {
|
||||
id: "lutra-river",
|
||||
label_key: "theme.lutraRiver",
|
||||
dark: true,
|
||||
tokens: &[
|
||||
("bg", "#1a2125"),
|
||||
("editor-bg", "#151b1e"),
|
||||
("fg", "#e2e8e6"),
|
||||
("fg-muted", "#8e9ca3"),
|
||||
("border", "#2c373d"),
|
||||
("accent", "#6fc6b8"),
|
||||
("error", "#f08a7a"),
|
||||
("statusbar-bg", "#1e272b"),
|
||||
("statusbar-fg", "#adbbc0"),
|
||||
("editor-selection-bg", "#28434a"),
|
||||
("editor-active-line-bg", "#1b2327"),
|
||||
("editor-cursor", "#6fc6b8"),
|
||||
("editor-gutter-bg", "#151b1e"),
|
||||
("editor-gutter-fg", "#8e9ca3"),
|
||||
("editor-match-bg", "#24393b"),
|
||||
("tab-active-bg", "#151b1e"),
|
||||
("tab-modified", "#6fc6b8"),
|
||||
("notice-bg", "#223a3c"),
|
||||
("syntax-keyword", "#e392b6"),
|
||||
("syntax-string", "#9fcb94"),
|
||||
("syntax-number", "#e8ae86"),
|
||||
("syntax-comment", "#87959c"),
|
||||
("syntax-variable", "#d2dcd9"),
|
||||
("syntax-function", "#e4cb7c"),
|
||||
("syntax-type", "#74c3d1"),
|
||||
("syntax-constant", "#b4aaea"),
|
||||
("syntax-tag", "#e6957c"),
|
||||
("syntax-attribute", "#c9bd86"),
|
||||
("syntax-operator", "#adbbc0"),
|
||||
("diag-error", "#f08a7a"),
|
||||
("diag-warning", "#e2b65c"),
|
||||
("diag-info", "#8fb6ec"),
|
||||
("diag-hint", "#8e9ca3"),
|
||||
("vcs-added", "#93c98a"),
|
||||
("vcs-modified", "#8fb6ec"),
|
||||
("vcs-deleted", "#d69a92"),
|
||||
("vcs-untracked", "#e3aa6a"),
|
||||
("vcs-ignored", "#86939a"),
|
||||
("vcs-conflicted", "#f27a90"),
|
||||
("terminal-bg", "#151b1e"),
|
||||
("terminal-fg", "#e2e8e6"),
|
||||
("terminal-cursor", "#6fc6b8"),
|
||||
("terminal-selection-bg", "#28434a"),
|
||||
("terminal-ansi-black", "#263035"),
|
||||
("terminal-ansi-red", "#ee8172"),
|
||||
("terminal-ansi-green", "#9fcb94"),
|
||||
("terminal-ansi-yellow", "#e4cb7c"),
|
||||
("terminal-ansi-blue", "#8cb0e8"),
|
||||
("terminal-ansi-magenta", "#e392b6"),
|
||||
("terminal-ansi-cyan", "#74c3d1"),
|
||||
("terminal-ansi-white", "#c6d0cd"),
|
||||
("terminal-ansi-bright-black", "#8e9ca3"),
|
||||
("terminal-ansi-bright-red", "#f6a597"),
|
||||
("terminal-ansi-bright-green", "#bfdeb2"),
|
||||
("terminal-ansi-bright-yellow", "#f0dc9c"),
|
||||
("terminal-ansi-bright-blue", "#afc6f2"),
|
||||
("terminal-ansi-bright-magenta", "#f0b0cd"),
|
||||
("terminal-ansi-bright-cyan", "#a6dbe3"),
|
||||
("terminal-ansi-bright-white", "#f3f6f5"),
|
||||
],
|
||||
};
|
||||
|
||||
/// Paper (light): High-key, almost white paper with deep plum ink as the accent. Bright and airy for daylight; the quietest of the family.
|
||||
pub const PAPER: Theme = Theme {
|
||||
id: "lutra-paper",
|
||||
label_key: "theme.lutraPaper",
|
||||
dark: false,
|
||||
tokens: &[
|
||||
("bg", "#f6f5f1"),
|
||||
("editor-bg", "#fefdfb"),
|
||||
("fg", "#221d20"),
|
||||
("fg-muted", "#625b5f"),
|
||||
("border", "#e2dfd7"),
|
||||
("accent", "#83224b"),
|
||||
("error", "#ad3524"),
|
||||
("statusbar-bg", "#eeece6"),
|
||||
("statusbar-fg", "#4f474b"),
|
||||
("editor-selection-bg", "#efd9e3"),
|
||||
("editor-active-line-bg", "#f7f5f0"),
|
||||
("editor-cursor", "#83224b"),
|
||||
("editor-gutter-bg", "#fefdfb"),
|
||||
("editor-gutter-fg", "#625b5f"),
|
||||
("editor-match-bg", "#f4e3ea"),
|
||||
("tab-active-bg", "#fefdfb"),
|
||||
("tab-modified", "#83224b"),
|
||||
("notice-bg", "#f3e2e8"),
|
||||
("syntax-keyword", "#8e2856"),
|
||||
("syntax-string", "#46661f"),
|
||||
("syntax-number", "#984216"),
|
||||
("syntax-comment", "#686064"),
|
||||
("syntax-variable", "#5c3f4e"),
|
||||
("syntax-function", "#745306"),
|
||||
("syntax-type", "#1f6476"),
|
||||
("syntax-constant", "#5a44a0"),
|
||||
("syntax-tag", "#a23f27"),
|
||||
("syntax-attribute", "#645a17"),
|
||||
("syntax-operator", "#4f474b"),
|
||||
("diag-error", "#ad3524"),
|
||||
("diag-warning", "#7f5000"),
|
||||
("diag-info", "#2d58a6"),
|
||||
("diag-hint", "#625b5f"),
|
||||
("vcs-added", "#38701f"),
|
||||
("vcs-modified", "#2d58a6"),
|
||||
("vcs-deleted", "#9e4236"),
|
||||
("vcs-untracked", "#8c520a"),
|
||||
("vcs-ignored", "#6d6569"),
|
||||
("vcs-conflicted", "#a81c40"),
|
||||
("terminal-bg", "#fefdfb"),
|
||||
("terminal-fg", "#221d20"),
|
||||
("terminal-cursor", "#83224b"),
|
||||
("terminal-selection-bg", "#efd9e3"),
|
||||
("terminal-ansi-black", "#221d20"),
|
||||
("terminal-ansi-red", "#ad3524"),
|
||||
("terminal-ansi-green", "#46661f"),
|
||||
("terminal-ansi-yellow", "#745306"),
|
||||
("terminal-ansi-blue", "#2c52a2"),
|
||||
("terminal-ansi-magenta", "#8e2856"),
|
||||
("terminal-ansi-cyan", "#1f6476"),
|
||||
("terminal-ansi-white", "#e2dfd7"),
|
||||
("terminal-ansi-bright-black", "#625b5f"),
|
||||
("terminal-ansi-bright-red", "#8a2717"),
|
||||
("terminal-ansi-bright-green", "#365015"),
|
||||
("terminal-ansi-bright-yellow", "#5a4003"),
|
||||
("terminal-ansi-bright-blue", "#213c7c"),
|
||||
("terminal-ansi-bright-magenta", "#6a1a40"),
|
||||
("terminal-ansi-bright-cyan", "#174e5c"),
|
||||
("terminal-ansi-bright-white", "#f6f5f1"),
|
||||
],
|
||||
};
|
||||
|
||||
/// Reed (light): Soft sand and sage surfaces with a muted pine accent. The riverbank in the afternoon: gentle on the eyes, still clearly Lutra.
|
||||
pub const REED: Theme = Theme {
|
||||
id: "lutra-reed",
|
||||
label_key: "theme.lutraReed",
|
||||
dark: false,
|
||||
tokens: &[
|
||||
("bg", "#e9e7d8"),
|
||||
("editor-bg", "#f3f2e8"),
|
||||
("fg", "#25261f"),
|
||||
("fg-muted", "#5b5a4f"),
|
||||
("border", "#d2cfbb"),
|
||||
("accent", "#3c6447"),
|
||||
("error", "#a63424"),
|
||||
("statusbar-bg", "#e1dfce"),
|
||||
("statusbar-fg", "#4a4a40"),
|
||||
("editor-selection-bg", "#d7e0cc"),
|
||||
("editor-active-line-bg", "#eceadd"),
|
||||
("editor-cursor", "#3c6447"),
|
||||
("editor-gutter-bg", "#f3f2e8"),
|
||||
("editor-gutter-fg", "#5b5a4f"),
|
||||
("editor-match-bg", "#e2e6d2"),
|
||||
("tab-active-bg", "#f3f2e8"),
|
||||
("tab-modified", "#3c6447"),
|
||||
("notice-bg", "#dde3cf"),
|
||||
("syntax-keyword", "#8c2a5a"),
|
||||
("syntax-string", "#3d6020"),
|
||||
("syntax-number", "#913f17"),
|
||||
("syntax-comment", "#625f55"),
|
||||
("syntax-variable", "#6c4433"),
|
||||
("syntax-function", "#6e5006"),
|
||||
("syntax-type", "#1d5f6e"),
|
||||
("syntax-constant", "#57439a"),
|
||||
("syntax-tag", "#9a3c26"),
|
||||
("syntax-attribute", "#5f5718"),
|
||||
("syntax-operator", "#4a4a40"),
|
||||
("diag-error", "#a63424"),
|
||||
("diag-warning", "#784c00"),
|
||||
("diag-info", "#2b549c"),
|
||||
("diag-hint", "#5b5a4f"),
|
||||
("vcs-added", "#356a1e"),
|
||||
("vcs-modified", "#2b549c"),
|
||||
("vcs-deleted", "#973f33"),
|
||||
("vcs-untracked", "#844d0a"),
|
||||
("vcs-ignored", "#615e54"),
|
||||
("vcs-conflicted", "#a11c3e"),
|
||||
("terminal-bg", "#f3f2e8"),
|
||||
("terminal-fg", "#25261f"),
|
||||
("terminal-cursor", "#3c6447"),
|
||||
("terminal-selection-bg", "#d7e0cc"),
|
||||
("terminal-ansi-black", "#25261f"),
|
||||
("terminal-ansi-red", "#a63424"),
|
||||
("terminal-ansi-green", "#3d6020"),
|
||||
("terminal-ansi-yellow", "#6e5006"),
|
||||
("terminal-ansi-blue", "#2a4f98"),
|
||||
("terminal-ansi-magenta", "#8c2a5a"),
|
||||
("terminal-ansi-cyan", "#1d5f6e"),
|
||||
("terminal-ansi-white", "#d2cfbb"),
|
||||
("terminal-ansi-bright-black", "#5b5a4f"),
|
||||
("terminal-ansi-bright-red", "#842617"),
|
||||
("terminal-ansi-bright-green", "#304b14"),
|
||||
("terminal-ansi-bright-yellow", "#553d03"),
|
||||
("terminal-ansi-bright-blue", "#203a76"),
|
||||
("terminal-ansi-bright-magenta", "#6a1c42"),
|
||||
("terminal-ansi-bright-cyan", "#164a56"),
|
||||
("terminal-ansi-bright-white", "#e9e7d8"),
|
||||
],
|
||||
};
|
||||
|
||||
/// Every built-in theme, in picker order: the brand pair first, then the
|
||||
/// themes of C9 (dark before light).
|
||||
pub const BUILTIN: &[Theme] = &[DARK, LIGHT, PLUM_NIGHT, RIVER, PAPER, REED];
|
||||
|
||||
/// Looks a built-in theme up by id.
|
||||
pub fn by_id(id: &str) -> Option<Theme> {
|
||||
|
|
@ -287,18 +570,281 @@ pub fn token_map(theme: &Theme) -> BTreeMap<String, String> {
|
|||
|
||||
/// Renders a theme as a `:root { … }` rule of CSS custom properties.
|
||||
pub fn css_variables(theme: &Theme) -> String {
|
||||
css_of(&theme.resolved())
|
||||
}
|
||||
|
||||
/// Renders a resolved theme as a `:root { … }` rule of CSS custom
|
||||
/// properties, `color-scheme` first.
|
||||
pub fn css_of(theme: &ResolvedTheme) -> String {
|
||||
let mut css = String::from(":root {\n");
|
||||
css.push_str(&format!(
|
||||
" color-scheme: {};\n",
|
||||
if theme.dark { "dark" } else { "light" }
|
||||
));
|
||||
for (name, value) in COMMON.iter().chain(theme.tokens) {
|
||||
css.push_str(&format!(" --lt-{name}: {value};\n"));
|
||||
for (name, value) in &theme.tokens {
|
||||
css.push_str(&format!(" {name}: {value};\n"));
|
||||
}
|
||||
css.push('}');
|
||||
css
|
||||
}
|
||||
|
||||
/// A theme ready to apply, built-in or imported: what `themeChanged`
|
||||
/// carries.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedTheme {
|
||||
/// Theme id.
|
||||
pub id: String,
|
||||
/// Whether the theme is dark.
|
||||
pub dark: bool,
|
||||
/// Every token, shared ones included, as `--lt-<name>` → value.
|
||||
pub tokens: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
/// The theme with its shared tokens, ready to apply.
|
||||
pub fn resolved(&self) -> ResolvedTheme {
|
||||
ResolvedTheme {
|
||||
id: self.id.to_string(),
|
||||
dark: self.dark,
|
||||
tokens: token_map(self),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `lutraTheme` value of the current theme file format
|
||||
/// (`docs/themes.md`).
|
||||
pub const FILE_FORMAT: u64 = 1;
|
||||
|
||||
/// Largest theme file that is read.
|
||||
pub const MAX_FILE_SIZE: u64 = 256 * 1024;
|
||||
|
||||
/// Longest theme id and display name, in bytes.
|
||||
pub const MAX_ID_LEN: usize = 64;
|
||||
|
||||
/// A theme imported from a theme file. Its colour tokens are exactly the
|
||||
/// colour tokens of the built-in themes; fonts and sizes stay shared.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UserTheme {
|
||||
/// Id, unique among built-in and imported themes.
|
||||
pub id: String,
|
||||
/// Display name, shown as typed.
|
||||
pub name: String,
|
||||
/// Whether the theme is dark.
|
||||
pub dark: bool,
|
||||
/// Colour tokens without the `--lt-` prefix → `#rrggbb`.
|
||||
pub tokens: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl UserTheme {
|
||||
/// The theme with the shared tokens, ready to apply.
|
||||
pub fn resolved(&self) -> ResolvedTheme {
|
||||
let tokens = COMMON
|
||||
.iter()
|
||||
.map(|(name, value)| (format!("--lt-{name}"), (*value).to_string()))
|
||||
.chain(
|
||||
self.tokens
|
||||
.iter()
|
||||
.map(|(name, value)| (format!("--lt-{name}"), value.clone())),
|
||||
)
|
||||
.collect();
|
||||
ResolvedTheme {
|
||||
id: self.id.clone(),
|
||||
dark: self.dark,
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme as a theme file, in the normalised form Lutra stores.
|
||||
pub fn to_file(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"lutraTheme": FILE_FORMAT,
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"dark": self.dark,
|
||||
"tokens": self.tokens,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour token names every theme defines, in the order of [`DARK`].
|
||||
pub fn colour_tokens() -> impl Iterator<Item = &'static str> {
|
||||
DARK.tokens.iter().map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
/// Whether `id` is a well-formed theme id: 1 to [`MAX_ID_LEN`] bytes of
|
||||
/// lowercase ASCII letters, digits and `-`, starting with a letter.
|
||||
pub fn valid_id(id: &str) -> bool {
|
||||
id.len() <= MAX_ID_LEN
|
||||
&& id.chars().next().is_some_and(|c| c.is_ascii_lowercase())
|
||||
&& id
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
}
|
||||
|
||||
/// Whether `id` is taken by a built-in theme or is [`SYSTEM`].
|
||||
pub fn reserved_id(id: &str) -> bool {
|
||||
id == SYSTEM || by_id(id).is_some()
|
||||
}
|
||||
|
||||
/// Whether `value` is a `#rrggbb` colour.
|
||||
fn is_hex_colour(value: &str) -> bool {
|
||||
value.len() == 7
|
||||
&& value.starts_with('#')
|
||||
&& value.chars().skip(1).all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// Most token names listed in one error message.
|
||||
const MAX_LISTED: usize = 8;
|
||||
|
||||
/// Joins names for an error message, at most [`MAX_LISTED`] of them.
|
||||
fn listing(names: &[String]) -> String {
|
||||
let shown = names
|
||||
.iter()
|
||||
.take(MAX_LISTED)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
match names.len().checked_sub(MAX_LISTED) {
|
||||
Some(more) if more > 0 => format!("{shown} and {more} more"),
|
||||
_ => shown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a theme file (`docs/themes.md`).
|
||||
///
|
||||
/// The file is untrusted. It must be a JSON object with `lutraTheme`
|
||||
/// ([`FILE_FORMAT`]), `id` (see [`valid_id`], not a built-in id), `name`
|
||||
/// (1 to [`MAX_ID_LEN`] bytes, no control characters), `dark` and
|
||||
/// `tokens`: every colour token of the built-in themes, named with or
|
||||
/// without the `--lt-` prefix, as `#rrggbb`. `description` and `author`
|
||||
/// strings are allowed and ignored; any other key is refused, so a typo
|
||||
/// does not pass unnoticed. Colours are stored in lowercase.
|
||||
///
|
||||
/// # Errors
|
||||
/// One English sentence saying what is wrong, for the user.
|
||||
pub fn parse_file(text: &str) -> Result<UserTheme, String> {
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(text).map_err(|e| format!("the file is not valid JSON: {e}"))?;
|
||||
let serde_json::Value::Object(fields) = value else {
|
||||
return Err("the file must contain a JSON object".into());
|
||||
};
|
||||
for key in fields.keys() {
|
||||
if ![
|
||||
"lutraTheme",
|
||||
"id",
|
||||
"name",
|
||||
"dark",
|
||||
"tokens",
|
||||
"description",
|
||||
"author",
|
||||
]
|
||||
.contains(&key.as_str())
|
||||
{
|
||||
return Err(format!("unknown key \"{key}\""));
|
||||
}
|
||||
}
|
||||
if fields.get("lutraTheme").and_then(serde_json::Value::as_u64) != Some(FILE_FORMAT) {
|
||||
return Err(format!(
|
||||
"this is not a Lutra theme file: it needs \"lutraTheme\": {FILE_FORMAT}"
|
||||
));
|
||||
}
|
||||
for key in ["description", "author"] {
|
||||
if fields.get(key).is_some_and(|v| !v.is_string()) {
|
||||
return Err(format!("\"{key}\" must be a string"));
|
||||
}
|
||||
}
|
||||
let id = fields
|
||||
.get("id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or("\"id\" is missing or not a string")?;
|
||||
if !valid_id(id) {
|
||||
return Err(format!(
|
||||
"the id \"{id}\" is not allowed: use up to {MAX_ID_LEN} lowercase letters, digits and dashes, starting with a letter"
|
||||
));
|
||||
}
|
||||
if reserved_id(id) {
|
||||
return Err(format!(
|
||||
"the id \"{id}\" belongs to a built-in theme; choose another one"
|
||||
));
|
||||
}
|
||||
let name = fields
|
||||
.get("name")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.ok_or("\"name\" is missing or not a string")?;
|
||||
if name.is_empty() || name.len() > MAX_ID_LEN || name.chars().any(char::is_control) {
|
||||
return Err(format!(
|
||||
"\"name\" must be 1 to {MAX_ID_LEN} characters without control characters"
|
||||
));
|
||||
}
|
||||
let dark = fields
|
||||
.get("dark")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.ok_or("\"dark\" is missing or not true/false")?;
|
||||
let Some(serde_json::Value::Object(raw)) = fields.get("tokens") else {
|
||||
return Err("\"tokens\" is missing or not an object".into());
|
||||
};
|
||||
let mut tokens = BTreeMap::new();
|
||||
let mut unknown = Vec::new();
|
||||
for (key, value) in raw {
|
||||
let name = key.strip_prefix("--lt-").unwrap_or(key);
|
||||
if !colour_tokens().any(|known| known == name) {
|
||||
unknown.push(key.clone());
|
||||
continue;
|
||||
}
|
||||
let Some(colour) = value.as_str().filter(|v| is_hex_colour(v)) else {
|
||||
return Err(format!(
|
||||
"the token \"{name}\" must be a colour like \"#1e1b1e\", got {value}"
|
||||
));
|
||||
};
|
||||
if tokens
|
||||
.insert(name.to_string(), colour.to_ascii_lowercase())
|
||||
.is_some()
|
||||
{
|
||||
return Err(format!("the token \"{name}\" is given twice"));
|
||||
}
|
||||
}
|
||||
if !unknown.is_empty() {
|
||||
return Err(format!("unknown tokens: {}", listing(&unknown)));
|
||||
}
|
||||
let missing: Vec<String> = colour_tokens()
|
||||
.filter(|name| !tokens.contains_key(*name))
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"{} tokens are missing: {}",
|
||||
missing.len(),
|
||||
listing(&missing)
|
||||
));
|
||||
}
|
||||
Ok(UserTheme {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
dark,
|
||||
tokens,
|
||||
})
|
||||
}
|
||||
|
||||
/// The theme for an `appearance.theme` value, imported themes included.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `setting`: a theme id or [`SYSTEM`].
|
||||
/// - `system_dark`: the OS preference, as for [`resolve`].
|
||||
/// - `imported`: the imported themes.
|
||||
///
|
||||
/// Returns [`DARK`] for an id that is neither built in nor imported.
|
||||
pub fn resolve_with(
|
||||
setting: &str,
|
||||
system_dark: Option<bool>,
|
||||
imported: &[UserTheme],
|
||||
) -> ResolvedTheme {
|
||||
match imported.iter().find(|t| t.id == setting) {
|
||||
Some(theme) => theme.resolved(),
|
||||
None => resolve(setting, system_dark).resolved(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The CSS for an `appearance.theme` value: the theme's variables, or for
|
||||
/// [`SYSTEM`] the dark theme with the light one inside a
|
||||
/// `prefers-color-scheme: light` media query, so the first frame follows the
|
||||
|
|
@ -318,7 +864,14 @@ pub fn css_for_setting(setting: &str) -> String {
|
|||
/// `<style id="lt-theme">` element as soon as the document has a `<head>`,
|
||||
/// for use as a webview initialization script.
|
||||
pub fn init_script(setting: &str) -> String {
|
||||
let css = serde_json::Value::String(css_for_setting(setting)).to_string();
|
||||
init_script_for_css(&css_for_setting(setting))
|
||||
}
|
||||
|
||||
/// JavaScript that installs `css` as the `<style id="lt-theme">` element,
|
||||
/// as [`init_script`] does; for an imported theme, which only the engine
|
||||
/// knows.
|
||||
pub fn init_script_for_css(css: &str) -> String {
|
||||
let css = serde_json::Value::String(css.to_string()).to_string();
|
||||
format!(
|
||||
"(function(){{var css={css};function apply(){{var s=document.getElementById('lt-theme');if(!s){{s=document.createElement('style');s.id='lt-theme';document.head.appendChild(s);}}s.textContent=css;}}if(document.head){{apply();}}else{{document.addEventListener('DOMContentLoaded',apply);}}}})();"
|
||||
)
|
||||
|
|
@ -349,7 +902,108 @@ mod tests {
|
|||
#[test]
|
||||
fn themes_define_the_same_tokens() {
|
||||
let names = |t: &Theme| t.tokens.iter().map(|(n, _)| *n).collect::<Vec<_>>();
|
||||
assert_eq!(names(&DARK), names(&LIGHT));
|
||||
for theme in BUILTIN {
|
||||
assert_eq!(names(&DARK), names(theme), "{}", theme.id);
|
||||
assert!(valid_id(theme.id), "{}", theme.id);
|
||||
assert!(
|
||||
theme.tokens.iter().all(|(_, v)| is_hex_colour(v)),
|
||||
"{}",
|
||||
theme.id
|
||||
);
|
||||
}
|
||||
let mut ids: Vec<_> = BUILTIN.iter().map(|t| t.id).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), BUILTIN.len());
|
||||
assert_eq!(BUILTIN.iter().filter(|t| t.dark).count(), 3);
|
||||
}
|
||||
|
||||
/// A valid theme file built from a built-in theme's colours.
|
||||
fn file_from(theme: &Theme, id: &str) -> serde_json::Value {
|
||||
let tokens: serde_json::Map<_, _> = theme
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|(n, v)| ((*n).to_string(), serde_json::Value::from(*v)))
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"lutraTheme": 1,
|
||||
"id": id,
|
||||
"name": " My Dusk ",
|
||||
"dark": theme.dark,
|
||||
"description": "test",
|
||||
"tokens": tokens,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_a_theme_file() {
|
||||
let mut file = file_from(&RIVER, "my-dusk");
|
||||
file["tokens"]["--lt-bg"] = file["tokens"]["bg"].take();
|
||||
file["tokens"].as_object_mut().unwrap().remove("bg");
|
||||
file["tokens"]["accent"] = "#ABCDEF".into();
|
||||
let theme = parse_file(&file.to_string()).unwrap();
|
||||
assert_eq!(theme.id, "my-dusk");
|
||||
assert_eq!(theme.name, "My Dusk");
|
||||
assert!(theme.dark);
|
||||
assert_eq!(theme.tokens["bg"], "#1a2125");
|
||||
assert_eq!(theme.tokens["accent"], "#abcdef");
|
||||
let resolved = theme.resolved();
|
||||
assert_eq!(resolved.tokens.len(), token_map(&RIVER).len());
|
||||
assert_eq!(resolved.tokens["--lt-font-size-editor"], "14px");
|
||||
let again = parse_file(&theme.to_file().to_string()).unwrap();
|
||||
assert_eq!(again, theme);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_broken_theme_files() {
|
||||
let good = file_from(&PAPER, "fine");
|
||||
let broken = |edit: &dyn Fn(&mut serde_json::Value)| {
|
||||
let mut file = good.clone();
|
||||
edit(&mut file);
|
||||
parse_file(&file.to_string()).unwrap_err()
|
||||
};
|
||||
assert!(parse_file("{nope").unwrap_err().contains("not valid JSON"));
|
||||
assert!(parse_file("[]").unwrap_err().contains("JSON object"));
|
||||
assert!(broken(&|f| f["lutraTheme"] = 2.into()).contains("lutraTheme"));
|
||||
assert!(broken(&|f| f["Dark"] = true.into()).contains("unknown key \"Dark\""));
|
||||
assert!(broken(&|f| f["id"] = "Bad Id".into()).contains("not allowed"));
|
||||
assert!(broken(&|f| f["id"] = "lutra-river".into()).contains("built-in"));
|
||||
assert!(broken(&|f| f["id"] = SYSTEM.into()).contains("built-in"));
|
||||
assert!(broken(&|f| f["name"] = " ".into()).contains("name"));
|
||||
assert!(broken(&|f| f["dark"] = "yes".into()).contains("dark"));
|
||||
assert!(broken(&|f| f["tokens"]["bg"] = "red".into()).contains("\"bg\" must be a colour"));
|
||||
assert!(broken(&|f| f["tokens"]["--lt-bg"] = "#000000".into()).contains("twice"));
|
||||
assert!(
|
||||
broken(&|f| f["tokens"]["sparkle"] = "#000000".into())
|
||||
.contains("unknown tokens: sparkle")
|
||||
);
|
||||
let missing = broken(&|f| f["tokens"] = serde_json::json!({}));
|
||||
assert!(
|
||||
missing.starts_with("59 tokens are missing: bg, editor-bg"),
|
||||
"{missing}"
|
||||
);
|
||||
assert!(missing.ends_with("and 51 more"), "{missing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_imported_themes() {
|
||||
let mine = parse_file(&file_from(&REED, "mine").to_string()).unwrap();
|
||||
let imported = [mine.clone()];
|
||||
assert_eq!(resolve_with("mine", Some(true), &imported), mine.resolved());
|
||||
assert_eq!(
|
||||
resolve_with("lutra-paper", None, &imported),
|
||||
PAPER.resolved()
|
||||
);
|
||||
assert_eq!(resolve_with("gone", None, &imported), DARK.resolved());
|
||||
assert_eq!(
|
||||
resolve_with(SYSTEM, Some(false), &imported),
|
||||
LIGHT.resolved()
|
||||
);
|
||||
assert!(css_of(&mine.resolved()).contains(
|
||||
" --lt-bg: #e9e7d8;
|
||||
"
|
||||
));
|
||||
assert!(init_script_for_css("a").contains("var css=\"a\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -434,6 +1088,9 @@ mod tests {
|
|||
assert_eq!(resolve(SYSTEM, Some(true)), DARK);
|
||||
assert_eq!(resolve(SYSTEM, None), DARK);
|
||||
assert_eq!(resolve("nope", Some(false)), DARK);
|
||||
assert_eq!(resolve("lutra-river", Some(false)), RIVER);
|
||||
assert_eq!(by_id("lutra-plum-night"), Some(PLUM_NIGHT));
|
||||
assert_eq!(by_id("lutra-reed"), Some(REED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
|
|||
[
|
||||
"appearance.theme",
|
||||
"editor.fontSize",
|
||||
"editor.fontFamily",
|
||||
"editor.lineHeight",
|
||||
"ui.language",
|
||||
"php.executable",
|
||||
"phpactor.path",
|
||||
|
|
@ -72,12 +74,14 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
|
|||
}
|
||||
assert_eq!(list[1]["type"], "int");
|
||||
assert_eq!(list[1]["default"], 14);
|
||||
assert_eq!(list[2]["enumValues"], json!(["en"]));
|
||||
assert_eq!(list[3]["type"], "string");
|
||||
assert_eq!(list[3]["default"], "");
|
||||
assert_eq!(list[5]["type"], "bool");
|
||||
assert_eq!(list[5]["default"], true);
|
||||
assert_eq!(list[5]["section"], "php");
|
||||
assert_eq!(list[2]["type"], "string");
|
||||
assert_eq!(list[3]["default"], 150);
|
||||
assert_eq!(list[4]["enumValues"], json!(["en"]));
|
||||
assert_eq!(list[5]["type"], "string");
|
||||
assert_eq!(list[5]["default"], "");
|
||||
assert_eq!(list[7]["type"], "bool");
|
||||
assert_eq!(list[7]["default"], true);
|
||||
assert_eq!(list[7]["section"], "php");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -117,6 +121,8 @@ fn get_set_reset_and_events() {
|
|||
json!({
|
||||
"appearance.theme": "system",
|
||||
"editor.fontSize": 14,
|
||||
"editor.fontFamily": "",
|
||||
"editor.lineHeight": 150,
|
||||
"ui.language": "en",
|
||||
"php.executable": "",
|
||||
"phpactor.path": "",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! Theme commands and `themeChanged`: switching through `settings.set`, the
|
||||
//! "system" mode following the reported OS preference, and the stored theme
|
||||
//! surviving a restart.
|
||||
//! "system" mode following the reported OS preference, the stored theme
|
||||
//! surviving a restart, `theme.select`, `theme.current` and importing theme
|
||||
//! files (C9 T1).
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
|
|
@ -45,13 +46,156 @@ fn report(engine: &mut Engine, dark: bool) -> (Value, Vec<(String, bool)>) {
|
|||
fn list_names_the_builtin_themes_by_catalog_key() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
let rows: Vec<_> = list
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
(
|
||||
t["id"].as_str().unwrap(),
|
||||
t["label"].as_str().unwrap(),
|
||||
t["dark"].as_bool().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
list,
|
||||
json!([
|
||||
{"id": "lutra-dark", "label": "theme.lutraDark", "dark": true},
|
||||
{"id": "lutra-light", "label": "theme.lutraLight", "dark": false},
|
||||
])
|
||||
rows,
|
||||
[
|
||||
("lutra-dark", "theme.lutraDark", true),
|
||||
("lutra-light", "theme.lutraLight", false),
|
||||
("lutra-plum-night", "theme.lutraPlumNight", true),
|
||||
("lutra-river", "theme.lutraRiver", true),
|
||||
("lutra-paper", "theme.lutraPaper", false),
|
||||
("lutra-reed", "theme.lutraReed", false),
|
||||
]
|
||||
);
|
||||
assert_eq!(list[3]["tokens"], json!(theme::token_map(&theme::RIVER)));
|
||||
assert_eq!(list[3]["builtin"], true);
|
||||
assert_eq!(list[3]["name"], Value::Null);
|
||||
}
|
||||
|
||||
/// A valid theme file with the colours of `base`.
|
||||
fn theme_file(base: &theme::Theme, id: &str, name: &str) -> String {
|
||||
let tokens: serde_json::Map<_, _> = base
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|(n, v)| (format!("--lt-{n}"), Value::from(*v)))
|
||||
.collect();
|
||||
json!({"lutraTheme": 1, "id": id, "name": name, "dark": base.dark, "tokens": tokens})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_and_current_switch_live() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let out = e
|
||||
.execute("theme.select", json!({"id": "lutra-paper"}))
|
||||
.unwrap();
|
||||
assert_eq!(out.value["id"], "lutra-paper");
|
||||
assert_eq!(out.value["tokens"]["--lt-bg"], "#f6f5f1");
|
||||
assert_eq!(themes(&out.events), [("lutra-paper".into(), false)]);
|
||||
assert!(matches!(
|
||||
out.events.first(),
|
||||
Some(Event::SettingsChanged { keys }) if keys == &["appearance.theme"]
|
||||
));
|
||||
let current = e.execute("theme.current", Value::Null).unwrap().value;
|
||||
assert_eq!(current["id"], "lutra-paper");
|
||||
assert_eq!(current["tokens"], json!(theme::token_map(&theme::PAPER)));
|
||||
let again = e
|
||||
.execute("theme.select", json!({"id": "lutra-paper"}))
|
||||
.unwrap();
|
||||
assert!(again.events.is_empty());
|
||||
for bad in [json!({"id": "nope"}), json!({}), json!({"id": "x", "y": 1})] {
|
||||
let err = e.execute("theme.select", bad).unwrap_err();
|
||||
assert_eq!(err.code(), "invalid_params");
|
||||
}
|
||||
let err = e
|
||||
.execute(
|
||||
"settings.set",
|
||||
json!({"key": "appearance.theme", "value": "not-imported"}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("unknown theme"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_themes_are_selected_stored_and_reloaded() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let config = EngineConfig {
|
||||
config_dir: dir.path().join("config"),
|
||||
data_dir: dir.path().join("data"),
|
||||
};
|
||||
let file = dir.path().join("dusk.json");
|
||||
std::fs::write(&file, theme_file(&theme::RIVER, "dusk", "Dusk")).unwrap();
|
||||
let mut e = Engine::with_config(config.clone()).unwrap();
|
||||
let out = e.execute("theme.import", json!({"path": file})).unwrap();
|
||||
assert_eq!(
|
||||
out.value,
|
||||
json!({"id": "dusk", "name": "Dusk", "dark": true, "replaced": false})
|
||||
);
|
||||
assert_eq!(themes(&out.events), [("dusk".into(), true)]);
|
||||
let stored = dir.path().join("data/themes/dusk.json");
|
||||
assert!(stored.is_file());
|
||||
let list = e.execute("settings.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list[0]["enumValues"].as_array().unwrap().len(), 8);
|
||||
assert_eq!(list[0]["enumValues"][6], "dusk");
|
||||
assert_eq!(list[0]["valueNames"], json!({"dusk": "Dusk"}));
|
||||
|
||||
std::fs::write(&file, theme_file(&theme::REED, "dusk", "Dusk 2")).unwrap();
|
||||
let out = e
|
||||
.execute("theme.import", json!({"path": file, "select": false}))
|
||||
.unwrap();
|
||||
assert_eq!(out.value["replaced"], true);
|
||||
assert_eq!(themes(&out.events), [("dusk".into(), false)]);
|
||||
drop(e);
|
||||
|
||||
std::fs::write(dir.path().join("data/themes/broken.json"), "{oops").unwrap();
|
||||
let mut e = Engine::with_config(config).unwrap();
|
||||
let events = e.take_events();
|
||||
assert!(
|
||||
events.iter().any(|ev| matches!(
|
||||
ev,
|
||||
Event::Notification { message: Some(m), .. } if m.contains("broken.json") && m.contains("not valid JSON")
|
||||
)),
|
||||
"{events:?}"
|
||||
);
|
||||
let current = e.execute("theme.current", Value::Null).unwrap().value;
|
||||
assert_eq!(current["id"], "dusk");
|
||||
assert_eq!(current["tokens"]["--lt-bg"], "#e9e7d8");
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list[6]["name"], "Dusk 2");
|
||||
assert_eq!(list[6]["builtin"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_theme_file_is_refused_with_the_reason() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut e = Engine::new().unwrap();
|
||||
let missing = e
|
||||
.execute(
|
||||
"theme.import",
|
||||
json!({"path": dir.path().join("none.json")}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(missing.code(), "failed");
|
||||
assert!(missing.to_string().contains("cannot read it"), "{missing}");
|
||||
let file = dir.path().join("bad.json");
|
||||
std::fs::write(&file, r##"{"lutraTheme": 1, "id": "bad", "name": "Bad", "dark": true, "tokens": {"bg": "#000"}}"##).unwrap();
|
||||
let err = e
|
||||
.execute("theme.import", json!({"path": file}))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("the token \"bg\" must be a colour"),
|
||||
"{err}"
|
||||
);
|
||||
std::fs::write(&file, "x".repeat(300 * 1024)).unwrap();
|
||||
let err = e
|
||||
.execute("theme.import", json!({"path": file}))
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("larger than 256 KiB"), "{err}");
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list.as_array().unwrap().len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue