Add resolved appearance engine and paired theme settings
Resolve light, dark and automatic appearance centrally and publish live theme snapshots to native surfaces and the appearance portal. Add paired preset families, custom theme imports, accessibility transforms and contrast-safe transitions. Refine the Settings gallery and Auto controls, move overrides under advanced customization, and share palette-aware switches and circular slider thumbs. Document configuration and include theme licenses and integration coverage.
This commit is contained in:
1 parent
2bb4c086f5
commit
3d950a0411
58 files changed
+5556
-644
No files matched your search
+52
-22
@@ -1,7 +1,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::{fmt, fs, io};
|
||||
|
||||
use ferese_animation::SpringConfig;
|
||||
use ferese_core::LayoutMode;
|
||||
@@ -187,6 +187,7 @@ pub struct ThemeSettings {
|
||||
pub focus_ring_gradient: Option<BorderGradient>,
|
||||
pub shadow_color: RgbaColor,
|
||||
pub surface_base_color: RgbaColor,
|
||||
pub bar_background_color: RgbaColor,
|
||||
pub text_primary_color: RgbaColor,
|
||||
pub shell_opacity: f64,
|
||||
pub inactive_dim: InactiveDimSettings,
|
||||
@@ -196,6 +197,7 @@ pub struct ThemeSettings {
|
||||
pub shadow_opacity: f64,
|
||||
pub material_style: MaterialStyle,
|
||||
pub backdrop_blur: f64,
|
||||
pub material_tint_strength: f64,
|
||||
pub material_radius: f64,
|
||||
pub panel_radius: f64,
|
||||
}
|
||||
@@ -258,9 +260,23 @@ struct ThemeConfig {
|
||||
shadow: ThemeShadowConfig,
|
||||
#[serde(default)]
|
||||
material: ThemeMaterialConfig,
|
||||
#[serde(default)]
|
||||
surface: ThemeSurfaceConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct ThemeSurfaceConfig {
|
||||
#[serde(default)]
|
||||
bar: ThemeBarConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct ThemeBarConfig {
|
||||
background: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_source(source: &str) -> Result<Self, ConfigError> {
|
||||
ferese_config::from_str(source).map_err(|source| ConfigError::Parse {
|
||||
path: config_path().unwrap_or_default(),
|
||||
@@ -268,6 +284,18 @@ impl Config {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn resolved_theme_settings(
|
||||
theme: &ferese_config::theme::ResolvedTheme,
|
||||
inactive_dim: InactiveDimSettings,
|
||||
) -> Result<ThemeSettings, ConfigError> {
|
||||
let mut config = Self::default();
|
||||
config.theme = serde_json::from_value(serde_json::to_value(&theme.tokens).unwrap())
|
||||
.expect("resolved theme matches runtime schema");
|
||||
let mut settings = config.theme_settings()?;
|
||||
settings.inactive_dim = inactive_dim;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_config(&self) -> Result<crate::RuntimeConfig, ConfigError> {
|
||||
self.notifications.validate().map_err(ConfigError::InvalidBinding)?;
|
||||
self.desktop_widgets.validate().map_err(ConfigError::InvalidBinding)?;
|
||||
@@ -328,6 +356,8 @@ struct ThemeMaterialConfig {
|
||||
style: MaterialStyle,
|
||||
#[serde(default = "default_backdrop_blur")]
|
||||
blur_radius: f64,
|
||||
#[serde(default = "default_material_tint_strength")]
|
||||
tint_strength: f64,
|
||||
}
|
||||
|
||||
impl Default for ThemeMaterialConfig {
|
||||
@@ -336,6 +366,7 @@ impl Default for ThemeMaterialConfig {
|
||||
style: MaterialStyle::Solid,
|
||||
opacity: default_shell_opacity(),
|
||||
blur_radius: default_backdrop_blur(),
|
||||
tint_strength: default_material_tint_strength(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,6 +375,10 @@ fn default_shell_opacity() -> f64 {
|
||||
ferese_config::DEFAULT_MATERIAL_OPACITY
|
||||
}
|
||||
|
||||
fn default_material_tint_strength() -> f64 {
|
||||
0.5
|
||||
}
|
||||
|
||||
fn default_backdrop_blur() -> f64 {
|
||||
12.0
|
||||
}
|
||||
@@ -834,10 +869,7 @@ enum ColumnWidthValue {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
Read {
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
#[cfg(test)]
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
source: ferese_config::Error,
|
||||
@@ -870,9 +902,7 @@ pub enum ConfigError {
|
||||
impl fmt::Display for ConfigError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Read { path, source } => {
|
||||
write!(formatter, "failed to read {}: {source}", path.display())
|
||||
}
|
||||
#[cfg(test)]
|
||||
Self::Parse { path, source } => {
|
||||
write!(formatter, "failed to parse {}: {source}", path.display())
|
||||
}
|
||||
@@ -904,7 +934,7 @@ impl fmt::Display for ConfigError {
|
||||
impl Error for ConfigError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Read { source, .. } => Some(source),
|
||||
#[cfg(test)]
|
||||
Self::Parse { source, .. } => Some(source),
|
||||
Self::InvalidColumnWidth { .. }
|
||||
| Self::InvalidAnimationValue { .. }
|
||||
@@ -919,19 +949,6 @@ impl Error for ConfigError {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self, ConfigError> {
|
||||
let Some(path) = config_path() else {
|
||||
return Ok(Self::default());
|
||||
};
|
||||
let source = match fs::read_to_string(&path) {
|
||||
Ok(source) => source,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
|
||||
Err(source) => return Err(ConfigError::Read { path, source }),
|
||||
};
|
||||
|
||||
ferese_config::from_str(&source).map_err(|source| ConfigError::Parse { path, source })
|
||||
}
|
||||
|
||||
pub fn layout_mode(&self) -> LayoutMode {
|
||||
match self.layout.mode.unwrap_or(LayoutModeValue::Scrolling) {
|
||||
LayoutModeValue::Scrolling => LayoutMode::Scrolling,
|
||||
@@ -1173,6 +1190,15 @@ impl Config {
|
||||
focus_ring_gradient: self.theme.focus_ring.settings("focus_ring")?,
|
||||
shadow_color: parse_color(&self.theme.colors.shadow, "colors.shadow")?,
|
||||
surface_base_color: parse_color(&self.theme.colors.surface_base, "colors.surface_base")?,
|
||||
bar_background_color: parse_color(
|
||||
self.theme
|
||||
.surface
|
||||
.bar
|
||||
.background
|
||||
.as_deref()
|
||||
.unwrap_or(&self.theme.colors.surface_base),
|
||||
"surface.bar.background",
|
||||
)?,
|
||||
shell_opacity: unit_theme_value(self.theme.material.opacity, "material.opacity")?,
|
||||
inactive_dim: InactiveDimSettings {
|
||||
enabled: self.appearance.inactive_dim.enabled,
|
||||
@@ -1188,6 +1214,7 @@ impl Config {
|
||||
shadow_opacity,
|
||||
material_style: self.theme.material.style,
|
||||
backdrop_blur: nonnegative_theme_value(self.theme.material.blur_radius, "material.blur_radius")?.min(32.0),
|
||||
material_tint_strength: unit_theme_value(self.theme.material.tint_strength, "material.tint_strength")?,
|
||||
material_radius,
|
||||
panel_radius: material_radius,
|
||||
})
|
||||
@@ -2020,6 +2047,7 @@ mod tests {
|
||||
focus_ring_gradient: None,
|
||||
shadow_color: RgbaColor([1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 128.0 / 255.0]),
|
||||
surface_base_color: RgbaColor([17.0 / 255.0, 24.0 / 255.0, 33.0 / 255.0, 1.0,]),
|
||||
bar_background_color: RgbaColor([17.0 / 255.0, 24.0 / 255.0, 33.0 / 255.0, 1.0,]),
|
||||
text_primary_color: RgbaColor([244.0 / 255.0, 247.0 / 255.0, 251.0 / 255.0, 1.0]),
|
||||
shell_opacity: 0.78,
|
||||
inactive_dim: InactiveDimSettings {
|
||||
@@ -2033,6 +2061,7 @@ mod tests {
|
||||
shadow_opacity: 0.4,
|
||||
material_style: MaterialStyle::Translucent,
|
||||
backdrop_blur: 12.0,
|
||||
material_tint_strength: 0.5,
|
||||
material_radius: 14.0,
|
||||
panel_radius: 14.0,
|
||||
}
|
||||
@@ -2103,6 +2132,7 @@ mod tests {
|
||||
.theme_settings()
|
||||
.unwrap();
|
||||
assert_eq!(theme.surface_base_color, RgbaColor([0.0, 0.0, 0.0, 1.0]));
|
||||
assert_eq!(theme.bar_background_color, RgbaColor([1.0, 1.0, 1.0, 1.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+41
-1
@@ -117,6 +117,7 @@ pub(crate) fn init(event_loop: &mut EventLoop<'static, Ferese>) -> Result<Screen
|
||||
}
|
||||
state.portal_shortcuts.remove(owner);
|
||||
state.portal_session.remove(owner);
|
||||
state.theme_engine.remove(owner);
|
||||
state.refresh_idle_inhibition();
|
||||
return;
|
||||
}
|
||||
@@ -143,6 +144,22 @@ pub(crate) fn init(event_loop: &mut EventLoop<'static, Ferese>) -> Result<Screen
|
||||
"Missing capture session",
|
||||
));
|
||||
}
|
||||
} else if call.request.command == "theme-watch" {
|
||||
if let Err(error) = validate_request(&call.request) {
|
||||
let _ = call
|
||||
.response
|
||||
.try_send(Response::error(call.request.id, error.code, error.message));
|
||||
} else if let Some(since) = call.request.args["since"].as_u64() {
|
||||
state
|
||||
.theme_engine
|
||||
.watch(call.owner, call.request.id, since, call.response);
|
||||
} else {
|
||||
let _ = call.response.try_send(Response::error(
|
||||
call.request.id,
|
||||
"invalid_argument",
|
||||
"Missing theme revision",
|
||||
));
|
||||
}
|
||||
} else if call.request.command == "session-watch" {
|
||||
if let Err(error) = validate_request(&call.request) {
|
||||
let _ = call
|
||||
@@ -323,6 +340,19 @@ fn serve_connection(mut stream: UnixStream, sender: channel::SyncSender<IpcEvent
|
||||
return;
|
||||
}
|
||||
};
|
||||
if request.command == "theme-preview" {
|
||||
let response = match validate_request(&request) {
|
||||
Err(error) => Response::error(request.id, error.code, error.message),
|
||||
Ok(()) => match crate::theme::preview(&request.args) {
|
||||
Ok(value) => Response::success(request.id, value),
|
||||
Err(error) => Response::error(request.id, "invalid_config", error),
|
||||
},
|
||||
};
|
||||
if write_frame(&mut stream, &response).is_err() {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (response, receiver) = sync_channel(1);
|
||||
let exit_requested = request.command == "exit";
|
||||
let screenshot_requested = matches!(request.command.as_str(), "screenshot" | "screenshot-window");
|
||||
@@ -404,7 +434,9 @@ impl Ferese {
|
||||
if self.session_lock.active
|
||||
&& !matches!(
|
||||
request.command.as_str(),
|
||||
"portal-shortcuts-poll"
|
||||
"theme-get"
|
||||
| "theme-status"
|
||||
| "portal-shortcuts-poll"
|
||||
| "input-capture-disable"
|
||||
| "input-capture-release"
|
||||
| "get-session-state"
|
||||
@@ -429,6 +461,14 @@ impl Ferese {
|
||||
|
||||
fn dispatch_ipc_command(&mut self, owner: u64, command: &str, args: &Value) -> Result<Value, CommandError> {
|
||||
match command {
|
||||
"theme-get" | "theme-status" => return Ok(self.theme_engine.value()),
|
||||
"theme-set-mode" => {
|
||||
let mode = serde_json::from_value(args["mode"].clone())
|
||||
.map_err(|error| CommandError::new("invalid_argument", error.to_string()))?;
|
||||
return self
|
||||
.set_theme_mode(mode)
|
||||
.map_err(|error| CommandError::new("invalid_config", error));
|
||||
}
|
||||
"portal-inhibit" => {
|
||||
let inhibition = serde_json::from_value(args.clone())
|
||||
.map_err(|error| CommandError::new("invalid_argument", error.to_string()))?;
|
||||
|
||||
+18
-39
@@ -24,6 +24,7 @@ mod session_lock;
|
||||
mod shell_control;
|
||||
mod stacking;
|
||||
mod state;
|
||||
mod theme;
|
||||
mod wallpaper;
|
||||
mod window_rules;
|
||||
mod winit;
|
||||
@@ -40,7 +41,6 @@ pub use state::{Ferese, RuntimeConfig};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::backends::LaunchConfig;
|
||||
use crate::config::Config;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
init_logging();
|
||||
@@ -53,18 +53,27 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
return Err("usage: ferese --check-config PATH".into());
|
||||
}
|
||||
let source = std::fs::read_to_string(&args[1])?;
|
||||
Config::parse_source(&source)?.runtime_config()?;
|
||||
theme::prepare(
|
||||
&source,
|
||||
std::path::Path::new(&args[1])
|
||||
.parent()
|
||||
.unwrap_or(std::path::Path::new(".")),
|
||||
)?;
|
||||
println!("Configuration is valid");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let launch =
|
||||
LaunchConfig::from_environment().map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
|
||||
let initial_source = config::config_path().and_then(|path| std::fs::read_to_string(path).ok());
|
||||
let config = match initial_source.as_deref() {
|
||||
Some(source) => Config::parse_source(source)?,
|
||||
None => Config::load()?,
|
||||
};
|
||||
let initial_source = config::config_path()
|
||||
.filter(|path| path.exists())
|
||||
.map(|path| theme::read_source(&path))
|
||||
.transpose()?;
|
||||
let source = initial_source.as_deref().unwrap_or("");
|
||||
let directory = config::config_path()
|
||||
.and_then(|path| path.parent().map(ToOwned::to_owned))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
let (config, runtime, candidate) = theme::prepare(source, &directory)?;
|
||||
let mut event_loop = EventLoop::try_new()?;
|
||||
let signals = Signals::new(&[Signal::SIGINT, Signal::SIGTERM])?;
|
||||
event_loop
|
||||
@@ -74,20 +83,11 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
state.loop_signal.stop();
|
||||
})?;
|
||||
let display = Display::new()?;
|
||||
let runtime = config.runtime_config()?;
|
||||
let mut state = Ferese::new(&mut event_loop, display, runtime)?;
|
||||
state.config_source = initial_source.filter(|source| source.len() <= 60 * 1024);
|
||||
theme::init(&mut event_loop, &mut state, candidate)?;
|
||||
overview::init_font_loader(&mut event_loop, &mut state)?;
|
||||
backends::init(launch.backend, &mut event_loop, &mut state)?;
|
||||
let mut monitor = config::config_path().and_then(|path| {
|
||||
match reload::ConfigMonitor::with_wakeup(path, Some(event_loop.get_signal())) {
|
||||
Ok(monitor) => Some(monitor),
|
||||
Err(error) => {
|
||||
warn!(%error, "automatic config watching unavailable; use feresectl reload-config");
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
use calloop::timer::{TimeoutAction, Timer};
|
||||
info!(socket = ?state.socket_name, backend = ?launch.backend, "Ferese is accepting Wayland clients");
|
||||
let mut child = spawn_client(&mut state, launch.client, launch.client_capabilities);
|
||||
@@ -104,30 +104,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
TimeoutAction::ToDuration(Duration::from_secs(1))
|
||||
},
|
||||
)?;
|
||||
let reload_timer_pending = std::rc::Rc::new(std::cell::Cell::new(false));
|
||||
let reload_handle = event_loop.handle();
|
||||
let result = event_loop.run(None, &mut state, |state| {
|
||||
if let Some(monitor) = &mut monitor {
|
||||
if let Some(result) = monitor.poll(std::time::Instant::now())
|
||||
&& let Err(error) = result.and_then(|source| state.reload_config_source(source))
|
||||
{
|
||||
warn!(%error, "config reload rejected; retaining last working config");
|
||||
}
|
||||
// At most one timer exists. Edits arriving during debounce move the
|
||||
// deadline; the old timer wakes once and is replaced if necessary.
|
||||
if !reload_timer_pending.get()
|
||||
&& let Some(deadline) = monitor.next_deadline()
|
||||
{
|
||||
let pending = reload_timer_pending.clone();
|
||||
match reload_handle.insert_source(Timer::from_deadline(deadline), move |_, _, _| {
|
||||
pending.set(false);
|
||||
TimeoutAction::Drop
|
||||
}) {
|
||||
Ok(_) => reload_timer_pending.set(true),
|
||||
Err(error) => warn!(%error, "could not schedule config debounce"),
|
||||
}
|
||||
}
|
||||
}
|
||||
state.poll_theme();
|
||||
// The decoder wakes the loop after publishing its result, including
|
||||
// when no output has a pending frame.
|
||||
let wallpaper_changed = state.wallpaper.poll();
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Filesystem events wake the loop; only pending edits need a debounce timer.
|
||||
#[cfg(test)]
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
#[cfg(test)]
|
||||
use std::sync::mpsc;
|
||||
#[cfg(test)]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(test)]
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
|
||||
#[cfg(test)]
|
||||
fn read_source(path: &std::path::Path) -> Result<String, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
let mut source = String::new();
|
||||
@@ -18,6 +23,7 @@ fn read_source(path: &std::path::Path) -> Result<String, String> {
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) struct ConfigMonitor {
|
||||
_watcher: RecommendedWatcher,
|
||||
events: mpsc::Receiver<()>,
|
||||
@@ -26,6 +32,7 @@ pub(crate) struct ConfigMonitor {
|
||||
observed: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl ConfigMonitor {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(path: PathBuf) -> notify::Result<Self> {
|
||||
@@ -115,13 +122,33 @@ impl crate::Ferese {
|
||||
if source.len() > 60 * 1024 {
|
||||
return Err("configuration exceeds the 60 KiB live-reload limit".into());
|
||||
}
|
||||
if self.config_source.as_ref() == Some(&source) {
|
||||
return Ok(());
|
||||
}
|
||||
// Validate every runtime field before mutating any scene/input state.
|
||||
let config = crate::config::Config::parse_source(&source).map_err(|e| e.to_string())?;
|
||||
let runtime = config.runtime_config().map_err(|e| e.to_string())?;
|
||||
self.apply_runtime_config(runtime)?;
|
||||
let directory = crate::config::config_path()
|
||||
.and_then(|path| path.parent().map(ToOwned::to_owned))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let (_, mut runtime, candidate) = match crate::theme::prepare(&source, &directory) {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
self.theme_engine.reject(error.clone());
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let wallpaper = runtime.wallpaper.clone();
|
||||
runtime.wallpaper = self.wallpaper.configuration().clone();
|
||||
let previous_theme = self.theme_settings;
|
||||
let non_theme = |source: &str| -> Option<serde_json::Value> {
|
||||
let document = ferese_config::Document::parse(source).ok()?;
|
||||
let mut value = document.value().clone();
|
||||
value.as_object_mut()?.remove("theme");
|
||||
Some(value)
|
||||
};
|
||||
if self.config_source.as_deref().and_then(non_theme) != non_theme(&source) {
|
||||
self.apply_runtime_config(runtime)?;
|
||||
}
|
||||
self.overview
|
||||
.set_font_family(candidate.theme.tokens.typography.font_family.clone());
|
||||
self.theme_settings = previous_theme;
|
||||
self.accept_theme(candidate, wallpaper);
|
||||
self.config_source = Some(source.clone());
|
||||
self.shell_resources.retain(|resource| {
|
||||
if let Ok(shell) = resource.upgrade() {
|
||||
@@ -139,7 +166,7 @@ impl crate::Ferese {
|
||||
|
||||
pub(crate) fn reload_config(&mut self) -> Result<(), String> {
|
||||
let path = crate::config::config_path().ok_or("config directory is unavailable")?;
|
||||
let source = read_source(&path)?;
|
||||
let source = crate::theme::read_source(&path)?;
|
||||
self.reload_config_source(source)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +225,7 @@ pub struct Ferese {
|
||||
pub(crate) session_lock: Lock,
|
||||
pub(crate) lock_idle: IdleSettings,
|
||||
pub(crate) config_source: Option<String>,
|
||||
pub(crate) theme_engine: crate::theme::Engine,
|
||||
pub start_time: Instant,
|
||||
pub socket_name: OsString,
|
||||
pub display_handle: DisplayHandle,
|
||||
@@ -439,6 +440,7 @@ impl Ferese {
|
||||
session_lock: crate::session_lock::Lock::default(),
|
||||
lock_idle: config.lock_idle,
|
||||
config_source: None,
|
||||
theme_engine: Default::default(),
|
||||
start_time,
|
||||
socket_name,
|
||||
display_handle,
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::{self, Read};
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use calloop::generic::Generic;
|
||||
use calloop::timer::{TimeoutAction, Timer};
|
||||
use calloop::{Interest, Mode as PollMode, PostAction};
|
||||
use ferese_config::Document;
|
||||
use ferese_config::theme::{Candidate, Mode, Snapshot, TRANSITION_MS, resolve_with_context};
|
||||
use ferese_ipc::Response;
|
||||
use jiff::Timestamp;
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde_json::{Value, json};
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::output::Output;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::wallpaper::{WallpaperConfig, WallpaperState};
|
||||
use crate::{Ferese, RuntimeConfig};
|
||||
|
||||
const DEBOUNCE: Duration = Duration::from_millis(150);
|
||||
const WALLPAPER_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
pub(crate) fn read_source(path: &Path) -> Result<String, String> {
|
||||
let mut source = String::new();
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?
|
||||
.take(60 * 1024 + 1)
|
||||
.read_to_string(&mut source)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if source.len() > 60 * 1024 {
|
||||
return Err(format!("{} exceeds 60 KiB", path.display()));
|
||||
}
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(source: &str, directory: &Path) -> Result<(Config, RuntimeConfig, Candidate), String> {
|
||||
let document = Document::parse(source).map_err(|e| e.to_string())?;
|
||||
let candidate = resolve_with_context(&document, directory, Timestamp::now(), &auto_context(), read_source)?;
|
||||
let config: Config =
|
||||
serde_json::from_value(document.with_theme(&candidate.theme).value().clone()).map_err(|e| e.to_string())?;
|
||||
let runtime = config.runtime_config().map_err(|e| e.to_string())?;
|
||||
Ok((config, runtime, candidate))
|
||||
}
|
||||
|
||||
pub(crate) fn preview(args: &Value) -> Result<Value, String> {
|
||||
let source = args["source"]
|
||||
.as_str()
|
||||
.filter(|source| source.len() <= 60 * 1024)
|
||||
.ok_or("Missing candidate configuration")?;
|
||||
let directory = args["directory"]
|
||||
.as_str()
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| crate::config::config_path().and_then(|path| path.parent().map(ToOwned::to_owned)))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let document = Document::parse(source).map_err(|e| e.to_string())?;
|
||||
let candidate = resolve_with_context(&document, &directory, Timestamp::now(), &auto_context(), read_source)?;
|
||||
Ok(
|
||||
json!({"theme": candidate.theme, "warnings": candidate.warnings, "families": candidate.families, "fallback_note": candidate.fallback_note}),
|
||||
)
|
||||
}
|
||||
|
||||
fn system_appearance_value(value: &str) -> Option<ferese_config::theme::Appearance> {
|
||||
use ferese_config::theme::Appearance;
|
||||
if value.contains("prefer-dark") {
|
||||
Some(Appearance::Dark)
|
||||
} else if value.contains("prefer-light") || value.contains("default") {
|
||||
Some(Appearance::Light)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
static SYSTEM_APPEARANCE: std::sync::OnceLock<Mutex<Option<ferese_config::theme::Appearance>>> =
|
||||
std::sync::OnceLock::new();
|
||||
|
||||
fn auto_context() -> ferese_config::theme::AutoContext {
|
||||
let appearance = SYSTEM_APPEARANCE.get_or_init(|| {
|
||||
let value = std::process::Command::new("gsettings")
|
||||
.args(["get", "org.gnome.desktop.interface", "color-scheme"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| system_appearance_value(&String::from_utf8_lossy(&output.stdout)));
|
||||
Mutex::new(value)
|
||||
});
|
||||
ferese_config::theme::AutoContext {
|
||||
system: *appearance.lock().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
candidate: Candidate,
|
||||
wallpaper: Option<WallpaperState>,
|
||||
ready: HashSet<Output>,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
struct Transition {
|
||||
from: ferese_config::theme::ResolvedTheme,
|
||||
started: Instant,
|
||||
previous_wallpaper: Option<WallpaperState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Engine {
|
||||
pub(crate) snapshot: Snapshot,
|
||||
waiters: HashMap<u64, (u64, mpsc::SyncSender<Response>)>,
|
||||
watcher: Option<RecommendedWatcher>,
|
||||
watched_directories: HashSet<PathBuf>,
|
||||
active_files: Vec<PathBuf>,
|
||||
paths: Arc<Mutex<HashSet<PathBuf>>>,
|
||||
events: Option<mpsc::Receiver<()>>,
|
||||
dirty: Option<Instant>,
|
||||
timer_pending: bool,
|
||||
clock: Option<OwnedFd>,
|
||||
pending: Option<Pending>,
|
||||
transition: Option<Transition>,
|
||||
last_frame: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub(crate) fn watch(&mut self, owner: u64, id: u64, since: u64, response: mpsc::SyncSender<Response>) {
|
||||
if since != self.snapshot.revision {
|
||||
let _ = response.try_send(Response::success(id, self.value()));
|
||||
} else {
|
||||
self.waiters.insert(owner, (id, response));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, owner: u64) {
|
||||
self.waiters.remove(&owner);
|
||||
}
|
||||
|
||||
pub(crate) fn value(&self) -> Value {
|
||||
serde_json::to_value(&self.snapshot).expect("serializable theme snapshot")
|
||||
}
|
||||
|
||||
fn publish(&mut self) {
|
||||
self.snapshot.revision = self.snapshot.revision.wrapping_add(1);
|
||||
let value = self.value();
|
||||
for (_, (id, response)) in self.waiters.drain() {
|
||||
let _ = response.try_send(Response::success(id, value.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reject(&mut self, error: String) {
|
||||
if self.snapshot.error.as_ref() != Some(&error) {
|
||||
tracing::warn!(%error, "theme reload rejected; retaining active theme");
|
||||
self.snapshot.error = Some(error);
|
||||
self.publish();
|
||||
}
|
||||
}
|
||||
|
||||
fn watch_files(&mut self, files: &[PathBuf]) {
|
||||
let mut targets = HashSet::from([PathBuf::from("/etc/localtime")]);
|
||||
if let Some(path) = crate::config::config_path() {
|
||||
targets.insert(path);
|
||||
}
|
||||
for path in self.active_files.iter().chain(files) {
|
||||
let path = if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
|
||||
parent.canonicalize().unwrap_or_else(|_| parent.to_owned()).join(name)
|
||||
} else {
|
||||
path.clone()
|
||||
};
|
||||
if let Ok(target) = path.canonicalize() {
|
||||
targets.insert(target);
|
||||
}
|
||||
targets.insert(path);
|
||||
}
|
||||
let mut directories: HashSet<_> = targets
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let mut directory = path.parent().unwrap_or(Path::new("."));
|
||||
while !directory.is_dir() {
|
||||
directory = directory.parent().unwrap_or(Path::new("/"));
|
||||
}
|
||||
directory.to_owned()
|
||||
})
|
||||
.collect();
|
||||
*self.paths.lock().unwrap() = targets;
|
||||
if let Some(watcher) = &mut self.watcher {
|
||||
for directory in self.watched_directories.difference(&directories) {
|
||||
let _ = watcher.unwatch(directory);
|
||||
}
|
||||
let mut failed = Vec::new();
|
||||
for directory in directories.difference(&self.watched_directories) {
|
||||
let mode = if directory == Path::new("/etc") {
|
||||
RecursiveMode::NonRecursive
|
||||
} else {
|
||||
RecursiveMode::Recursive
|
||||
};
|
||||
if let Err(error) = watcher.watch(directory, mode) {
|
||||
tracing::warn!(%error, path = %directory.display(), "cannot watch theme directory");
|
||||
failed.push(directory.clone());
|
||||
}
|
||||
}
|
||||
for directory in failed {
|
||||
directories.remove(&directory);
|
||||
}
|
||||
}
|
||||
self.watched_directories = directories;
|
||||
}
|
||||
|
||||
fn arm_clock(&self, next: Option<Timestamp>) -> io::Result<()> {
|
||||
let Some(fd) = &self.clock else { return Ok(()) };
|
||||
let mut timer: libc::itimerspec = unsafe { std::mem::zeroed() };
|
||||
if let Some(next) = next {
|
||||
timer.it_value.tv_sec = next.as_second();
|
||||
timer.it_value.tv_nsec = i64::from(next.subsec_nanosecond());
|
||||
}
|
||||
let result = unsafe {
|
||||
libc::timerfd_settime(
|
||||
fd.as_raw_fd(),
|
||||
libc::TFD_TIMER_ABSTIME | libc::TFD_TIMER_CANCEL_ON_SET,
|
||||
&timer,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result < 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn init(
|
||||
event_loop: &mut calloop::EventLoop<'static, Ferese>,
|
||||
state: &mut Ferese,
|
||||
candidate: Candidate,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let clock = unsafe { libc::timerfd_create(libc::CLOCK_REALTIME, libc::TFD_CLOEXEC | libc::TFD_NONBLOCK) };
|
||||
if clock < 0 {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
let clock = unsafe { OwnedFd::from_raw_fd(clock) };
|
||||
let source = clock.try_clone()?;
|
||||
state.theme_engine.clock = Some(clock);
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(Generic::new(source, Interest::READ, PollMode::Level), |_, _, state| {
|
||||
if let Some(clock) = &state.theme_engine.clock {
|
||||
let mut expirations = 0u64;
|
||||
unsafe { libc::read(clock.as_raw_fd(), (&mut expirations as *mut u64).cast(), 8) };
|
||||
}
|
||||
state.refresh_theme();
|
||||
Ok(PostAction::Continue)
|
||||
})?;
|
||||
let (sender, events) = mpsc::sync_channel(1);
|
||||
let paths = state.theme_engine.paths.clone();
|
||||
if let Some(config) = crate::config::config_path() {
|
||||
paths.lock().unwrap().insert(config);
|
||||
}
|
||||
paths.lock().unwrap().insert(PathBuf::from("/etc/localtime"));
|
||||
let wakeup = state.loop_signal.clone();
|
||||
let resume_sender = sender.clone();
|
||||
let resume_wakeup = wakeup.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("ferese-theme-resume".into())
|
||||
.spawn(move || {
|
||||
let monitor = || -> zbus::Result<()> {
|
||||
let connection = zbus::blocking::Connection::system()?;
|
||||
let proxy = zbus::blocking::Proxy::new(
|
||||
&connection,
|
||||
"org.freedesktop.login1",
|
||||
"/org/freedesktop/login1",
|
||||
"org.freedesktop.login1.Manager",
|
||||
)?;
|
||||
for message in proxy.receive_signal("PrepareForSleep")? {
|
||||
let (sleeping,): (bool,) = message.body().deserialize()?;
|
||||
if !sleeping {
|
||||
let _ = resume_sender.try_send(());
|
||||
resume_wakeup.wakeup();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
if let Err(error) = monitor() {
|
||||
tracing::warn!(%error, "theme resume monitor unavailable");
|
||||
}
|
||||
})?;
|
||||
let system_sender = sender.clone();
|
||||
let system_wakeup = wakeup.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("ferese-system-appearance".into())
|
||||
.spawn(move || {
|
||||
use std::io::BufRead;
|
||||
use std::os::unix::process::CommandExt;
|
||||
let mut command = std::process::Command::new("gsettings");
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let monitor = command
|
||||
.args(["monitor", "org.gnome.desktop.interface", "color-scheme"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn();
|
||||
if let Ok(mut monitor) = monitor {
|
||||
if let Ok(output) = std::process::Command::new("gsettings")
|
||||
.args(["get", "org.gnome.desktop.interface", "color-scheme"])
|
||||
.output()
|
||||
{
|
||||
if let Some(state) = SYSTEM_APPEARANCE.get() {
|
||||
*state.lock().unwrap() = system_appearance_value(&String::from_utf8_lossy(&output.stdout));
|
||||
}
|
||||
let _ = system_sender.try_send(());
|
||||
system_wakeup.wakeup();
|
||||
}
|
||||
if let Some(output) = monitor.stdout.take() {
|
||||
for line in std::io::BufReader::new(output).lines().map_while(Result::ok) {
|
||||
let value = system_appearance_value(&line);
|
||||
if let Some(state) = SYSTEM_APPEARANCE.get() {
|
||||
*state.lock().unwrap() = value;
|
||||
}
|
||||
let _ = system_sender.try_send(());
|
||||
system_wakeup.wakeup();
|
||||
}
|
||||
}
|
||||
let _ = monitor.wait();
|
||||
}
|
||||
})?;
|
||||
let watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
if let Ok(event) = event
|
||||
&& !event.kind.is_access()
|
||||
&& event.paths.iter().any(|path| {
|
||||
paths
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|target| target == path || target.starts_with(path))
|
||||
})
|
||||
{
|
||||
let _ = sender.try_send(());
|
||||
wakeup.wakeup();
|
||||
}
|
||||
})?;
|
||||
state.theme_engine.watcher = Some(watcher);
|
||||
state.theme_engine.events = Some(events);
|
||||
state.theme_engine.active_files = candidate.files.clone();
|
||||
state.theme_engine.watch_files(&candidate.files);
|
||||
state.theme_engine.arm_clock(candidate.next_transition)?;
|
||||
state.theme_engine.snapshot.families = candidate.families;
|
||||
state.theme_engine.snapshot.fallback_note = candidate.fallback_note;
|
||||
state.theme_engine.snapshot.mode = candidate.policy.mode;
|
||||
state.theme_engine.snapshot.theme = candidate.theme.clone();
|
||||
state.theme_engine.snapshot.presented = candidate.theme;
|
||||
state.theme_engine.snapshot.warnings = candidate.warnings;
|
||||
state.theme_engine.publish();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Ferese {
|
||||
pub(crate) fn refresh_theme(&mut self) {
|
||||
let result = crate::config::config_path()
|
||||
.map_or_else(
|
||||
|| {
|
||||
self.config_source
|
||||
.clone()
|
||||
.ok_or_else(|| "No configuration available".into())
|
||||
},
|
||||
|path| {
|
||||
if path.exists() {
|
||||
read_source(&path)
|
||||
} else {
|
||||
Ok(String::new())
|
||||
}
|
||||
},
|
||||
)
|
||||
.and_then(|source| {
|
||||
if let Ok(document) = Document::parse(&source)
|
||||
&& let Some(value) = document.get("theme")
|
||||
&& let Ok(policy) = serde_json::from_value::<ferese_config::theme::Policy>(value.clone())
|
||||
{
|
||||
let directory = crate::config::config_path()
|
||||
.and_then(|path| path.parent().map(ToOwned::to_owned))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let files: Vec<_> = [&policy.file, &policy.light.file, &policy.dark.file]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.map(|path| ferese_config::theme::theme_path(&directory, path))
|
||||
.collect();
|
||||
let mut files = files;
|
||||
files.extend(
|
||||
policy
|
||||
.custom_themes
|
||||
.values()
|
||||
.map(|theme| ferese_config::theme::theme_path(&directory, &theme.file)),
|
||||
);
|
||||
self.theme_engine.watch_files(&files);
|
||||
}
|
||||
self.reload_config_source(source)
|
||||
});
|
||||
if let Err(error) = result {
|
||||
self.theme_engine.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn accept_theme(&mut self, candidate: Candidate, wallpaper: WallpaperConfig) {
|
||||
self.theme_engine.active_files = candidate.files.clone();
|
||||
self.theme_engine.watch_files(&candidate.files);
|
||||
if let Err(error) = self.theme_engine.arm_clock(candidate.next_transition) {
|
||||
tracing::warn!(%error, "cannot arm appearance schedule");
|
||||
}
|
||||
if candidate.theme == self.theme_engine.snapshot.theme && self.theme_engine.pending.is_none() {
|
||||
let changed = self.theme_engine.snapshot.mode != candidate.policy.mode
|
||||
|| self.theme_engine.snapshot.warnings != candidate.warnings
|
||||
|| self.theme_engine.snapshot.error.is_some()
|
||||
|| self.theme_engine.snapshot.families != candidate.families
|
||||
|| self.theme_engine.snapshot.fallback_note != candidate.fallback_note;
|
||||
self.theme_engine.snapshot.families = candidate.families;
|
||||
self.theme_engine.snapshot.fallback_note = candidate.fallback_note;
|
||||
self.theme_engine.snapshot.mode = candidate.policy.mode;
|
||||
self.theme_engine.snapshot.warnings = candidate.warnings;
|
||||
self.theme_engine.snapshot.error = None;
|
||||
if changed {
|
||||
self.theme_engine.publish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(pending) = &mut self.theme_engine.pending
|
||||
&& pending
|
||||
.wallpaper
|
||||
.as_ref()
|
||||
.is_some_and(|state| state.configuration() == &wallpaper)
|
||||
{
|
||||
pending.candidate = candidate;
|
||||
self.poll_theme();
|
||||
return;
|
||||
}
|
||||
let wallpaper = (self.wallpaper.configuration() != &wallpaper)
|
||||
.then(|| WallpaperState::with_wakeup(wallpaper, Some(self.loop_signal.clone())));
|
||||
self.theme_engine.pending = Some(Pending {
|
||||
candidate,
|
||||
wallpaper,
|
||||
ready: HashSet::new(),
|
||||
deadline: Instant::now() + WALLPAPER_TIMEOUT,
|
||||
});
|
||||
self.poll_theme();
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_theme_wallpaper(&mut self, renderer: &mut GlesRenderer, output: &Output) {
|
||||
if let Some(pending) = &mut self.theme_engine.pending
|
||||
&& let Some(wallpaper) = &mut pending.wallpaper
|
||||
{
|
||||
wallpaper.poll();
|
||||
if wallpaper.element(renderer, output).is_some() || wallpaper.configuration().path.is_none() {
|
||||
pending.ready.insert(output.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn previous_theme_wallpaper(
|
||||
&mut self,
|
||||
renderer: &mut GlesRenderer,
|
||||
output: &Output,
|
||||
) -> Option<crate::presentation::NativeTextureElement> {
|
||||
let transition = self.theme_engine.transition.as_mut()?;
|
||||
transition.previous_wallpaper.as_mut()?.element(renderer, output)
|
||||
}
|
||||
|
||||
pub(crate) fn theme_progress(&self) -> f32 {
|
||||
self.theme_engine
|
||||
.transition
|
||||
.as_ref()
|
||||
.filter(|transition| transition.previous_wallpaper.is_some())
|
||||
.map_or(1., |transition| {
|
||||
(transition.started.elapsed().as_secs_f32() / (TRANSITION_MS as f32 / 1000.)).clamp(0., 1.)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn poll_theme(&mut self) {
|
||||
let now = Instant::now();
|
||||
if self
|
||||
.theme_engine
|
||||
.events
|
||||
.as_ref()
|
||||
.is_some_and(|events| events.try_iter().next().is_some())
|
||||
{
|
||||
self.theme_engine.dirty = Some(now + DEBOUNCE);
|
||||
}
|
||||
if self.theme_engine.dirty.is_some_and(|deadline| now >= deadline) {
|
||||
self.theme_engine.dirty = None;
|
||||
self.refresh_theme();
|
||||
}
|
||||
let mut start = false;
|
||||
if let Some(pending) = &mut self.theme_engine.pending {
|
||||
if let Some(wallpaper) = &mut pending.wallpaper {
|
||||
wallpaper.poll();
|
||||
}
|
||||
let ready =
|
||||
pending.wallpaper.is_none() || self.space.outputs().all(|output| pending.ready.contains(output));
|
||||
let failed = pending.wallpaper.as_ref().is_some_and(WallpaperState::failed);
|
||||
start = ready || failed || now >= pending.deadline;
|
||||
if start && !ready {
|
||||
pending.wallpaper = None;
|
||||
pending
|
||||
.candidate
|
||||
.warnings
|
||||
.push("Wallpaper unavailable; retained previous image".into());
|
||||
tracing::warn!("theme wallpaper was not ready; retaining previous image");
|
||||
}
|
||||
}
|
||||
if start {
|
||||
let pending = self.theme_engine.pending.take().unwrap();
|
||||
let from = self.theme_engine.snapshot.presented.clone();
|
||||
let previous_wallpaper = pending
|
||||
.wallpaper
|
||||
.map(|next| std::mem::replace(&mut self.wallpaper, next));
|
||||
self.theme_engine.snapshot.families = pending.candidate.families;
|
||||
self.theme_engine.snapshot.fallback_note = pending.candidate.fallback_note;
|
||||
self.theme_engine.snapshot.mode = pending.candidate.policy.mode;
|
||||
self.theme_engine.snapshot.theme = pending.candidate.theme;
|
||||
self.theme_engine.snapshot.warnings = pending.candidate.warnings;
|
||||
self.theme_engine.snapshot.error = None;
|
||||
self.theme_engine.transition = Some(Transition {
|
||||
from,
|
||||
started: now,
|
||||
previous_wallpaper,
|
||||
});
|
||||
self.theme_engine.last_frame = None;
|
||||
// Publish the target appearance before drawing transitional tokens.
|
||||
self.theme_engine.publish();
|
||||
}
|
||||
let frame_due = self
|
||||
.theme_engine
|
||||
.last_frame
|
||||
.is_none_or(|last| now.saturating_duration_since(last) >= Duration::from_millis(16));
|
||||
if frame_due && let Some(transition) = &self.theme_engine.transition {
|
||||
self.theme_engine.last_frame = Some(now);
|
||||
let progress =
|
||||
now.saturating_duration_since(transition.started).as_secs_f64() / (TRANSITION_MS as f64 / 1000.);
|
||||
let target = &self.theme_engine.snapshot.theme;
|
||||
let complete = progress >= 1. || target.reduced_motion;
|
||||
let presented = if complete {
|
||||
target.clone()
|
||||
} else {
|
||||
transition.from.transition(target, progress)
|
||||
};
|
||||
self.theme_settings = Config::resolved_theme_settings(&presented, self.theme_settings.inactive_dim)
|
||||
.expect("validated resolved theme");
|
||||
self.theme_engine.snapshot.presented = presented;
|
||||
self.theme_engine.publish();
|
||||
self.backdrop_generation = self.backdrop_generation.wrapping_add(1);
|
||||
if complete {
|
||||
self.theme_engine.transition = None;
|
||||
}
|
||||
crate::backends::direct::render_all(self);
|
||||
} else if frame_due && self.theme_engine.pending.is_some() {
|
||||
self.theme_engine.last_frame = Some(now);
|
||||
crate::backends::direct::render_all(self);
|
||||
}
|
||||
if !self.theme_engine.timer_pending {
|
||||
let deadline = if self.theme_engine.transition.is_some() || self.theme_engine.pending.is_some() {
|
||||
Some(now + Duration::from_millis(16))
|
||||
} else {
|
||||
self.theme_engine.dirty
|
||||
};
|
||||
if let Some(deadline) = deadline {
|
||||
self.theme_engine.timer_pending = true;
|
||||
if let Err(error) = self
|
||||
.loop_handle
|
||||
.insert_source(Timer::from_deadline(deadline), |_, _, state| {
|
||||
state.theme_engine.timer_pending = false;
|
||||
state.poll_theme();
|
||||
TimeoutAction::Drop
|
||||
})
|
||||
{
|
||||
self.theme_engine.timer_pending = false;
|
||||
tracing::warn!(%error, "cannot schedule theme update");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_theme_mode(&mut self, mode: Mode) -> Result<Value, String> {
|
||||
let path = crate::config::config_path().ok_or("No configuration directory")?;
|
||||
let original = read_source(&path)?;
|
||||
let mut document = Document::parse(&original).map_err(|e| e.to_string())?;
|
||||
document.set("theme.mode", json!(mode)).map_err(|e| e.to_string())?;
|
||||
let source = document.to_string();
|
||||
prepare(&source, path.parent().unwrap_or(Path::new(".")))?;
|
||||
let temporary = path.with_extension(format!("kdl.{}.tmp", std::process::id()));
|
||||
let result = (|| -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Ok(metadata) = std::fs::metadata(&path) {
|
||||
file.set_permissions(metadata.permissions())
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
file.write_all(source.as_bytes()).map_err(|e| e.to_string())?;
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
if read_source(&path)? != original {
|
||||
return Err("Configuration changed while updating the mode; please try again".into());
|
||||
}
|
||||
std::fs::rename(&temporary, &path).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(temporary);
|
||||
}
|
||||
result?;
|
||||
self.reload_config_source(source)?;
|
||||
Ok(self.theme_engine.value())
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,14 @@ impl WallpaperState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn configuration(&self) -> &WallpaperConfig {
|
||||
&self.config
|
||||
}
|
||||
|
||||
pub(crate) fn failed(&self) -> bool {
|
||||
self.config.path.is_some() && self.receiver.is_none() && self.pixels.is_none()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn owns_background(&self) -> bool {
|
||||
self.owned
|
||||
|
||||
+28
-11
@@ -442,8 +442,6 @@ void main() {
|
||||
}
|
||||
"#;
|
||||
|
||||
const BLURRED_MATERIAL_TINT: f32 = 0.5;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct BlurProgram(GlesTexProgram);
|
||||
|
||||
@@ -1378,9 +1376,20 @@ fn output_elements(
|
||||
output,
|
||||
&[Layer::Bottom, Layer::Background],
|
||||
));
|
||||
if let Some(wallpaper) = state.wallpaper.element(renderer, output) {
|
||||
state.prepare_theme_wallpaper(renderer, output);
|
||||
let progress = state.theme_progress();
|
||||
let wallpaper = state.wallpaper.element(renderer, output);
|
||||
let has_wallpaper = wallpaper.is_some();
|
||||
if let Some(mut wallpaper) = wallpaper {
|
||||
wallpaper.alpha = progress;
|
||||
elements.push(wallpaper.into());
|
||||
}
|
||||
if let Some(mut previous) = state.previous_theme_wallpaper(renderer, output) {
|
||||
if !has_wallpaper {
|
||||
previous.alpha = 1. - progress;
|
||||
}
|
||||
elements.push(previous.into());
|
||||
}
|
||||
elements
|
||||
}
|
||||
|
||||
@@ -2397,14 +2406,19 @@ fn material_element(
|
||||
let mode = output.current_mode()?;
|
||||
let scale = output.current_scale().fractional_scale();
|
||||
let transform = output.current_transform().invert();
|
||||
let [red, green, blue, _] = state.theme_settings.surface_base_color.0;
|
||||
let background = if role == crate::effects::SemanticRole::Panel {
|
||||
state.theme_settings.bar_background_color
|
||||
} else {
|
||||
state.theme_settings.surface_base_color
|
||||
};
|
||||
let [red, green, blue, _] = background.0;
|
||||
let radius = radius.min(geometry.size.w.min(geometry.size.h) as f32 * 0.5);
|
||||
let [offset_y, shadow_blur, shadow_opacity] = material.shadow;
|
||||
let edge_bar = role == crate::effects::SemanticRole::Panel && radius == 0.0 && geometry.loc.y == 0;
|
||||
let shadow_opacity = if edge_bar {
|
||||
0.0
|
||||
} else {
|
||||
shadow_opacity * f64::from(presentation_alpha)
|
||||
shadow_opacity * (state.theme_settings.shadow_opacity / 0.2) * f64::from(presentation_alpha)
|
||||
};
|
||||
let shadow_geometry = Rectangle::new(
|
||||
(geometry.loc.x, geometry.loc.y + offset_y.round() as i32).into(),
|
||||
@@ -2479,7 +2493,7 @@ fn material_element(
|
||||
None
|
||||
};
|
||||
if capture.is_some() {
|
||||
parameters.tint[3] = BLURRED_MATERIAL_TINT;
|
||||
parameters.tint[3] = state.theme_settings.material_tint_strength as f32;
|
||||
}
|
||||
let make_element = || {
|
||||
if let Some((capture, program)) = &capture {
|
||||
@@ -2771,7 +2785,12 @@ mod tests {
|
||||
let mut target_texture: GlesTexture = renderer.create_buffer(Fourcc::Abgr8888, size).unwrap();
|
||||
let damage = Rectangle::<i32, Physical>::from_size((32, 32).into());
|
||||
|
||||
for opacity in [0.2f32, 0.71, 1.0] {
|
||||
for (opacity, strength, tint) in [
|
||||
(0.2f32, 0.5f32, 0.1f32),
|
||||
(0.71, 0.5, 0.1),
|
||||
(1.0, 0.5, 0.1),
|
||||
(0.94, 1.0, 245.0 / 255.0),
|
||||
] {
|
||||
let uniforms = vec![
|
||||
Uniform::new("visible_rect", [0.0f32, 0.0, 32.0, 32.0]),
|
||||
Uniform::new("material_radius", 0.0f32),
|
||||
@@ -2780,7 +2799,7 @@ mod tests {
|
||||
Uniform::new("blur_radius", 12.0f32),
|
||||
Uniform::new("presentation_alpha", 1.0f32),
|
||||
Uniform::new("background_opacity", opacity),
|
||||
Uniform::new("tint", [0.1f32, 0.1, 0.1, super::BLURRED_MATERIAL_TINT]),
|
||||
Uniform::new("tint", [tint, tint, tint, strength]),
|
||||
];
|
||||
let mut target = renderer.bind(&mut target_texture).unwrap();
|
||||
{
|
||||
@@ -2820,9 +2839,7 @@ mod tests {
|
||||
left.abs_diff(right) <= 2,
|
||||
"opacity {opacity} leaked the original backdrop: {left} versus {right}"
|
||||
);
|
||||
let expected = (128.0 * (1.0 - super::BLURRED_MATERIAL_TINT * opacity)
|
||||
+ 25.5 * super::BLURRED_MATERIAL_TINT * opacity)
|
||||
.round() as u8;
|
||||
let expected = (128.0 * (1.0 - strength * opacity) + tint * 255.0 * strength * opacity).round() as u8;
|
||||
assert!(
|
||||
left.abs_diff(expected) <= 2,
|
||||
"opacity {opacity} failed to control tint: {left} versus {expected}"
|
||||
|
||||
Reference in new issue
Block a user