Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load themes under ~/.config/presenterm/themes #73

Merged
merged 1 commit into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ pub use crate::{
presenter::{PresentMode, Presenter},
render::highlighting::CodeHighlighter,
resource::Resources,
theme::PresentationTheme,
theme::{LoadThemeError, PresentationTheme},
};
19 changes: 13 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use clap::{error::ErrorKind, CommandFactory, Parser};
use comrak::Arena;
use presenterm::{
CodeHighlighter, CommandSource, Exporter, MarkdownParser, PresentMode, PresentationTheme, Presenter, Resources,
CodeHighlighter, CommandSource, Exporter, LoadThemeError, MarkdownParser, PresentMode, PresentationTheme,
Presenter, Resources,
};
use std::{
env,
Expand Down Expand Up @@ -57,12 +58,17 @@ fn create_splash() -> String {
)
}

fn load_custom_themes() {
fn load_custom_themes() -> Result<(), Box<dyn std::error::Error>> {
let Ok(home) = env::var("HOME") else {
return;
return Ok(());
};
let config = PathBuf::from(home).join(".config/presenterm");
let _ = CodeHighlighter::load_themes_from_path(&config.join("themes/highlighting"));
CodeHighlighter::register_themes_from_path(&config.join("themes/highlighting"))?;
match PresentationTheme::register_themes_from_path(&config.join("themes")) {
Ok(_) => Ok(()),
Err(e @ (LoadThemeError::Duplicate(_) | LoadThemeError::Corrupted(..))) => Err(e.into()),
_ => Ok(()),
}
}

fn display_acknowledgements() {
Expand All @@ -71,13 +77,14 @@ fn display_acknowledgements() {
}

fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
load_custom_themes()?;

let Some(default_theme) = PresentationTheme::from_name(&cli.theme) else {
let mut cmd = Cli::command();
let valid_themes = PresentationTheme::theme_names().collect::<Vec<_>>().join(", ");
let valid_themes = PresentationTheme::theme_names().join(", ");
let error_message = format!("invalid theme name, valid themes are: {valid_themes}");
cmd.error(ErrorKind::InvalidValue, error_message).exit();
};
load_custom_themes();

let mode = match (cli.present, cli.export) {
(true, _) => PresentMode::Presentation,
Expand Down
9 changes: 8 additions & 1 deletion src/render/highlighting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use once_cell::sync::Lazy;
use serde::Deserialize;
use std::{
collections::BTreeMap,
fs,
io::{self, Write},
path::Path,
sync::{Arc, Mutex},
Expand Down Expand Up @@ -77,7 +78,13 @@ impl CodeHighlighter {
}

/// Load .tmTheme themes from the provided path.
pub fn load_themes_from_path(path: &Path) -> Result<(), LoadingError> {
pub fn register_themes_from_path(path: &Path) -> Result<(), LoadingError> {
let Ok(metadata) = fs::metadata(path) else {
return Ok(());
};
if !metadata.is_dir() {
return Ok(());
}
let themes = ThemeSet::load_from_folder(path)?;
THEMES.merge(themes);
Ok(())
Expand Down
60 changes: 50 additions & 10 deletions src/theme.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::style::Colors;
use serde::{Deserialize, Serialize};
use std::{fs, io, path::Path};
use std::{fs, io, path::Path, sync::Mutex};

include!(concat!(env!("OUT_DIR"), "/themes.rs"));

static CUSTOM_THEMES: Lazy<Mutex<HashMap<String, PresentationTheme>>> = Lazy::new(Default::default);

/// A presentation theme.
#[derive(Default, Clone, Debug, Deserialize, Serialize)]
pub struct PresentationTheme {
Expand Down Expand Up @@ -54,19 +56,54 @@ impl PresentationTheme {
/// Default themes are bundled into the final binary during build time so this is an in-memory
/// lookup.
pub fn from_name(name: &str) -> Option<Self> {
let contents = THEMES.get(name)?;
// This is going to be caught by the test down here.
Some(serde_yaml::from_slice(contents).expect("corrupted theme"))
if let Some(contents) = THEMES.get(name) {
// This is going to be caught by the test down here.
Some(serde_yaml::from_slice(contents).expect("corrupted theme"))
} else if let Some(theme) = CUSTOM_THEMES.lock().unwrap().get(name).cloned() {
return Some(theme);
} else {
None
}
}

pub fn theme_names() -> impl Iterator<Item = &'static str> {
THEMES.keys().copied()
/// Register all the themes in the given directory.
pub fn register_themes_from_path(path: &Path) -> Result<(), LoadThemeError> {
let Ok(metadata) = fs::metadata(path) else {
return Ok(());
};
if !metadata.is_dir() {
return Ok(());
}
for entry in fs::read_dir(path)? {
let entry = entry?;
let metadata = entry.metadata()?;
let Some(file_name) = entry.file_name().to_str().map(ToOwned::to_owned) else {
continue;
};
if metadata.is_file() && file_name.ends_with(".yaml") {
let theme_name = file_name.trim_end_matches(".yaml");
if THEMES.contains_key(theme_name) {
return Err(LoadThemeError::Duplicate(theme_name.into()));
}
let theme = Self::from_path(&entry.path())?;
CUSTOM_THEMES.lock().unwrap().insert(theme_name.into(), theme);
}
}
Ok(())
}

/// Get all the registered theme names.
pub fn theme_names() -> Vec<String> {
let builtin_themes = THEMES.keys().map(|name| name.to_string());
let themes = CUSTOM_THEMES.lock().unwrap().keys().cloned().chain(builtin_themes).collect();
themes
}

/// Construct a presentation from a path.
pub(crate) fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, LoadThemeError> {
let contents = fs::read_to_string(path)?;
let theme = serde_yaml::from_str(&contents)?;
let contents = fs::read_to_string(&path)?;
let theme = serde_yaml::from_str(&contents)
.map_err(|e| LoadThemeError::Corrupted(path.as_ref().display().to_string(), e))?;
Ok(theme)
}

Expand Down Expand Up @@ -435,8 +472,11 @@ pub enum LoadThemeError {
#[error(transparent)]
Io(#[from] io::Error),

#[error(transparent)]
Corrupted(#[from] serde_yaml::Error),
#[error("theme at '{0}' is corrupted: {1}")]
Corrupted(String, serde_yaml::Error),

#[error("duplicate custom theme '{0}'")]
Duplicate(String),
}

#[cfg(test)]
Expand Down
Loading