new layout (wip) (#34)
Reviewed-on: #34
This commit was merged in pull request #34.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
//! The adapter for unknown systems:
|
||||
//! no colors of its own, resolution degrades to the neutral presets.
|
||||
|
||||
use super::ThemeSource;
|
||||
use crate::theme::ThemeVariant;
|
||||
use crate::theme::system::SystemTheme;
|
||||
|
||||
// Constructed only by `platform_source` on platforms without their own adapter.
|
||||
#[cfg_attr(any(target_os = "macos", target_os = "linux"), allow(dead_code))]
|
||||
pub(crate) struct FallbackSource;
|
||||
|
||||
impl ThemeSource for FallbackSource {
|
||||
fn snapshot(&self, variant: ThemeVariant) -> SystemTheme {
|
||||
SystemTheme::fallback(variant)
|
||||
}
|
||||
|
||||
fn label(&self) -> &'static str {
|
||||
crate::theme::system::SourceKind::Fallback.label()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! KDE adapter: reads the color groups Plasma writes into `~/.config/kdeglobals`
|
||||
//! (plus the Plasma 6.2+ `[General] AccentColor`). The parse is pure, so
|
||||
//! fixtures run on every OS; the IO lives behind the Linux cfg.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use gpui::Hsla;
|
||||
|
||||
use crate::theme::system::{SourceKind, SystemTheme};
|
||||
|
||||
/// The accent and window background stated in kdeglobals.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct KdeScheme {
|
||||
pub(crate) accent: Option<Hsla>,
|
||||
pub(crate) background: Option<Hsla>,
|
||||
}
|
||||
|
||||
impl KdeScheme {
|
||||
/// Parses kdeglobals text.
|
||||
pub(crate) fn parse(text: &str) -> Self {
|
||||
let groups = parse_groups(text);
|
||||
|
||||
let background = groups
|
||||
.get("Colors:Window")
|
||||
.and_then(|group| group_color(group, "BackgroundNormal"));
|
||||
|
||||
let accent = groups
|
||||
.get("General")
|
||||
.and_then(|group| group.get("AccentColor"))
|
||||
.and_then(|value| color_list(value));
|
||||
|
||||
Self { accent, background }
|
||||
}
|
||||
|
||||
pub(crate) fn into_system(
|
||||
self,
|
||||
accessibility: crate::theme::system::AccessibilityPreferences,
|
||||
portal_accent: Option<Hsla>,
|
||||
portal_variant: Option<crate::theme::ThemeVariant>,
|
||||
) -> SystemTheme {
|
||||
SystemTheme {
|
||||
// The portal states the mode on Plasma 5.21+.
|
||||
//
|
||||
// Older setups fall back to the scheme's background lightness.
|
||||
variant: portal_variant
|
||||
.or(self
|
||||
.background
|
||||
.map(crate::theme::ThemeVariant::by_lightness))
|
||||
.unwrap_or(crate::theme::ThemeVariant::Light),
|
||||
accent: self.accent.or(portal_accent),
|
||||
accessibility,
|
||||
window_background: None,
|
||||
source: SourceKind::Kde,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_groups(text: &str) -> HashMap<&str, HashMap<&str, &str>> {
|
||||
let mut groups: HashMap<&str, HashMap<&str, &str>> = HashMap::new();
|
||||
let mut section: Option<&str> = None;
|
||||
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('[') {
|
||||
section = Some(rest.split(']').next().unwrap_or(rest));
|
||||
continue;
|
||||
}
|
||||
if let (Some(section), Some((key, value))) = (section, line.split_once('=')) {
|
||||
groups
|
||||
.entry(section)
|
||||
.or_default()
|
||||
.insert(key.trim(), value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
groups
|
||||
}
|
||||
|
||||
fn group_color<'a>(group: &'a HashMap<&'a str, &'a str>, key: &str) -> Option<Hsla> {
|
||||
color_list(group.get(key)?)
|
||||
}
|
||||
|
||||
/// Parses `r,g,b[,a]` with components in 0..=255.
|
||||
fn color_list(value: &str) -> Option<Hsla> {
|
||||
let mut components = value.split(',').map(str::trim);
|
||||
let red = components.next()?.parse::<f32>().ok()?;
|
||||
let green = components.next()?.parse::<f32>().ok()?;
|
||||
let blue = components.next()?.parse::<f32>().ok()?;
|
||||
let alpha = components.next().and_then(|a| a.parse::<f32>().ok());
|
||||
if !(0.0..=255.0).contains(&red)
|
||||
|| !(0.0..=255.0).contains(&green)
|
||||
|| !(0.0..=255.0).contains(&blue)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let scale = |component: f32| component / 255.0;
|
||||
|
||||
Some(Hsla::from(gpui::Rgba {
|
||||
r: scale(red),
|
||||
g: scale(green),
|
||||
b: scale(blue),
|
||||
a: alpha.map(|a| a / 255.0).unwrap_or(1.0),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod io {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::KdeScheme;
|
||||
|
||||
fn kdeglobals_path() -> Option<PathBuf> {
|
||||
Some(
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)?
|
||||
.join(".config/kdeglobals"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn read_current() -> Option<KdeScheme> {
|
||||
let text = std::fs::read_to_string(kdeglobals_path()?).ok()?;
|
||||
Some(KdeScheme::parse(&text))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! Linux adapter selection: Omarchy → KDE → portal (GNOME/generic) →
|
||||
//! fallback, per the plan's detection cascade. Omarchy and KDE state the mode
|
||||
//! and accent; the portal supplements both with the accessibility flags;
|
||||
//! `gsettings` covers sessions without a portal.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use gpui::Hsla;
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
|
||||
use super::signal::ReapplySignal;
|
||||
use super::{ThemeSource, kde, omarchy, portal};
|
||||
use crate::theme::ThemeVariant;
|
||||
use crate::theme::system::{SourceKind, SystemTheme};
|
||||
|
||||
pub(crate) struct LinuxSource {
|
||||
backend: Backend,
|
||||
portal: Option<portal::io::PortalClient>,
|
||||
gsettings: Option<GSettingsSnapshot>,
|
||||
file_watcher: Option<notify::RecommendedWatcher>,
|
||||
/// Keeps the main-thread channel loop alive.
|
||||
_signal: Option<ReapplySignal>,
|
||||
}
|
||||
|
||||
/// Which payload the source reads.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Backend {
|
||||
Omarchy,
|
||||
Kde,
|
||||
Portal,
|
||||
Fallback,
|
||||
}
|
||||
|
||||
fn home_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME").map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// Whether the session runs on Wayland, where compositors state blur protocols.
|
||||
fn wayland_session() -> bool {
|
||||
std::env::var_os("WAYLAND_DISPLAY").is_some()
|
||||
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland")
|
||||
}
|
||||
|
||||
fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend {
|
||||
let omarchy_marker = home
|
||||
.join(".local/state/omarchy/current/theme.name")
|
||||
.exists()
|
||||
|| home.join(".local/state/omarchy/current/theme").is_dir()
|
||||
|| home.join(".config/omarchy").is_dir();
|
||||
if omarchy_marker {
|
||||
Backend::Omarchy
|
||||
} else if home.join(".config/kdeglobals").exists() {
|
||||
Backend::Kde
|
||||
} else if portal_reachable || gsettings_reachable {
|
||||
Backend::Portal
|
||||
} else {
|
||||
Backend::Fallback
|
||||
}
|
||||
}
|
||||
|
||||
/// What `gsettings` states for GNOME sessions.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct GSettingsSnapshot {
|
||||
variant: Option<ThemeVariant>,
|
||||
accent: Option<Hsla>,
|
||||
}
|
||||
|
||||
fn gsettings_value(args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new("gsettings")
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout).ok()
|
||||
}
|
||||
|
||||
/// The named accent colors GNOME ships (libadwaita's background variants).
|
||||
fn accent_rgb(name: &str) -> Option<Hsla> {
|
||||
let hex = match name {
|
||||
"blue" => 0x3584e4,
|
||||
"teal" => 0x2190a4,
|
||||
"green" => 0x3a944a,
|
||||
"yellow" => 0xc88800,
|
||||
"orange" => 0xed5b00,
|
||||
"red" => 0xe62d42,
|
||||
"pink" => 0xd56199,
|
||||
"purple" => 0x9141ac,
|
||||
"slate" => 0x6f8396,
|
||||
_ => return None,
|
||||
};
|
||||
Some(Hsla::from(gpui::rgb(hex)))
|
||||
}
|
||||
|
||||
fn read_gsettings() -> Option<GSettingsSnapshot> {
|
||||
let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"])
|
||||
.and_then(|value| match value.trim().trim_matches('\'') {
|
||||
"prefer-dark" => Some(ThemeVariant::Dark),
|
||||
"prefer-light" => Some(ThemeVariant::Light),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"])
|
||||
.and_then(|value| accent_rgb(value.trim().trim_matches('\'')));
|
||||
|
||||
if variant.is_none() && accent.is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(GSettingsSnapshot { variant, accent })
|
||||
}
|
||||
|
||||
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
|
||||
let portal = portal::io::PortalClient::connect();
|
||||
let gsettings = read_gsettings();
|
||||
|
||||
let backend = home_dir()
|
||||
.map(|home| detect(&home, portal.is_some(), gsettings.is_some()))
|
||||
.unwrap_or(Backend::Fallback);
|
||||
|
||||
Box::new(LinuxSource {
|
||||
backend,
|
||||
portal,
|
||||
gsettings,
|
||||
file_watcher: None,
|
||||
_signal: None,
|
||||
})
|
||||
}
|
||||
|
||||
impl LinuxSource {
|
||||
fn gnome_snapshot(
|
||||
&self,
|
||||
variant: ThemeVariant,
|
||||
accent: Option<Hsla>,
|
||||
accessibility: crate::theme::system::AccessibilityPreferences,
|
||||
) -> SystemTheme {
|
||||
SystemTheme {
|
||||
variant,
|
||||
accent,
|
||||
accessibility,
|
||||
window_background: None,
|
||||
source: SourceKind::Gnome,
|
||||
}
|
||||
}
|
||||
|
||||
fn portal_snapshot(
|
||||
&self,
|
||||
variant: ThemeVariant,
|
||||
portal_appearance: Option<portal::Appearance>,
|
||||
accessibility: crate::theme::system::AccessibilityPreferences,
|
||||
) -> SystemTheme {
|
||||
if let Some(appearance) = portal_appearance {
|
||||
return self.gnome_snapshot(
|
||||
appearance.variant(variant),
|
||||
appearance.accent,
|
||||
accessibility,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(gsettings) = self.gsettings {
|
||||
return self.gnome_snapshot(
|
||||
gsettings.variant.unwrap_or(variant),
|
||||
gsettings.accent,
|
||||
accessibility,
|
||||
);
|
||||
}
|
||||
|
||||
SystemTheme::fallback(variant)
|
||||
}
|
||||
}
|
||||
|
||||
impl ThemeSource for LinuxSource {
|
||||
fn snapshot(&self, variant: ThemeVariant) -> SystemTheme {
|
||||
let portal_appearance = self.portal.as_ref().map(|portal| portal.appearance());
|
||||
let accessibility = portal_appearance
|
||||
.map(portal::Appearance::accessibility)
|
||||
.unwrap_or_default();
|
||||
|
||||
match self.backend {
|
||||
Backend::Omarchy => omarchy::io::read_current()
|
||||
.map(|theme| {
|
||||
let mut system = theme.into_system(accessibility);
|
||||
// Hyprland blurs transparent surfaces on its own.
|
||||
system.window_background = Some(gpui::WindowBackgroundAppearance::Blurred);
|
||||
system
|
||||
})
|
||||
.unwrap_or_else(|| SystemTheme::fallback(variant)),
|
||||
Backend::Kde => kde::io::read_current()
|
||||
.map(|scheme| {
|
||||
let mut system = scheme.into_system(
|
||||
accessibility,
|
||||
portal_appearance.and_then(|appearance| appearance.accent),
|
||||
portal_appearance.map(|appearance| appearance.variant(variant)),
|
||||
);
|
||||
// KWin states the blur protocols; X11 compositors do not.
|
||||
system.window_background =
|
||||
wayland_session().then_some(gpui::WindowBackgroundAppearance::Blurred);
|
||||
system
|
||||
})
|
||||
.unwrap_or_else(|| SystemTheme::fallback(variant)),
|
||||
Backend::Portal => self.portal_snapshot(variant, portal_appearance, accessibility),
|
||||
Backend::Fallback => SystemTheme::fallback(variant),
|
||||
}
|
||||
}
|
||||
|
||||
fn install_watchers(&mut self, async_cx: gpui::AsyncApp) {
|
||||
let signal = ReapplySignal::install(&async_cx);
|
||||
let file_signal = signal.sender();
|
||||
|
||||
if let Some(portal) = &self.portal {
|
||||
portal.spawn_watch(signal.sender());
|
||||
}
|
||||
|
||||
// Stored before any fallible step: an early return below
|
||||
// must not drop and cancel the reapply loop.
|
||||
self._signal = Some(signal);
|
||||
|
||||
match self.backend {
|
||||
Backend::Omarchy => {
|
||||
let Some(current) = omarchy::io::current_dir() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let watcher = notify::recommended_watcher(
|
||||
move |event: std::result::Result<notify::Event, notify::Error>| match event {
|
||||
Ok(_) => ReapplySignal::poke(&file_signal),
|
||||
Err(error) => log::warn!("theme: omarchy watch error: {error}"),
|
||||
},
|
||||
);
|
||||
|
||||
match watcher {
|
||||
Ok(mut watcher) => {
|
||||
if let Err(error) = watcher.watch(¤t, RecursiveMode::NonRecursive) {
|
||||
log::warn!("theme: omarchy watch failed: {error}");
|
||||
return;
|
||||
}
|
||||
self.file_watcher = Some(watcher);
|
||||
}
|
||||
Err(error) => log::warn!("theme: omarchy watcher unavailable: {error}"),
|
||||
}
|
||||
}
|
||||
Backend::Kde => {
|
||||
let Some(config) = home_dir().map(|home| home.join(".config")) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let watcher = notify::recommended_watcher(
|
||||
move |event: std::result::Result<notify::Event, notify::Error>| match event {
|
||||
Ok(event) => {
|
||||
if event.paths.iter().any(|path| {
|
||||
path.file_name().is_some_and(|name| name == "kdeglobals")
|
||||
}) {
|
||||
ReapplySignal::poke(&file_signal);
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("theme: kde watch error: {error}"),
|
||||
},
|
||||
);
|
||||
match watcher {
|
||||
Ok(mut watcher) => {
|
||||
if let Err(error) = watcher.watch(&config, RecursiveMode::NonRecursive) {
|
||||
log::warn!("theme: kde watch failed: {error}");
|
||||
return;
|
||||
}
|
||||
self.file_watcher = Some(watcher);
|
||||
}
|
||||
Err(error) => log::warn!("theme: kde watcher unavailable: {error}"),
|
||||
}
|
||||
}
|
||||
Backend::Portal | Backend::Fallback => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> &'static str {
|
||||
match self.backend {
|
||||
Backend::Omarchy => SourceKind::Omarchy.label(),
|
||||
Backend::Kde => SourceKind::Kde.label(),
|
||||
Backend::Portal => SourceKind::Gnome.label(),
|
||||
Backend::Fallback => SourceKind::Fallback.label(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! macOS Adapter
|
||||
//!
|
||||
//! Reads the system accent and watches the system's color preferences.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyObject, NSObject};
|
||||
use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{
|
||||
NSColor, NSColorSpace, NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification,
|
||||
NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults,
|
||||
};
|
||||
|
||||
use super::signal::ReapplySignal;
|
||||
use super::{ThemeSource, narrow_component};
|
||||
use crate::theme::ThemeVariant;
|
||||
use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme};
|
||||
|
||||
// An observer that forwards distributed notifications and preference.
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[ivars = async_channel::Sender<()>]
|
||||
struct ThemeObserver;
|
||||
|
||||
impl ThemeObserver {
|
||||
#[unsafe(method(themeDidChange:))]
|
||||
fn theme_did_change(&self, _notification: &NSNotification) {
|
||||
ReapplySignal::poke(self.ivars());
|
||||
}
|
||||
|
||||
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
|
||||
fn observe_value_for_key_path(
|
||||
&self,
|
||||
_key_path: &NSString,
|
||||
_object: Option<&AnyObject>,
|
||||
_change: Option<&NSDictionary<NSString, AnyObject>>,
|
||||
_context: *mut core::ffi::c_void,
|
||||
) {
|
||||
ReapplySignal::poke(self.ivars());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl ThemeObserver {
|
||||
fn new(reapply: async_channel::Sender<()>) -> Retained<Self> {
|
||||
let this = Self::alloc().set_ivars(reapply);
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct MacosSource {
|
||||
/// The notification centers track, but do not retain, the observer.
|
||||
_observer: Option<Retained<ThemeObserver>>,
|
||||
/// Keeps the reapply loop alive.
|
||||
_signal: Option<ReapplySignal>,
|
||||
}
|
||||
|
||||
impl MacosSource {
|
||||
fn color_to_hsla(color: &NSColor) -> Option<gpui::Hsla> {
|
||||
let srgb = NSColorSpace::sRGBColorSpace();
|
||||
let converted = color.colorUsingColorSpace(&srgb)?;
|
||||
|
||||
Some(gpui::Hsla::from(gpui::Rgba {
|
||||
r: narrow_component(converted.redComponent()),
|
||||
g: narrow_component(converted.greenComponent()),
|
||||
b: narrow_component(converted.blueComponent()),
|
||||
a: narrow_component(converted.alphaComponent()),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl ThemeSource for MacosSource {
|
||||
fn snapshot(&self, variant: ThemeVariant) -> SystemTheme {
|
||||
let workspace = NSWorkspace::sharedWorkspace();
|
||||
|
||||
let accessibility = AccessibilityPreferences {
|
||||
high_contrast: workspace.accessibilityDisplayShouldIncreaseContrast(),
|
||||
reduce_motion: workspace.accessibilityDisplayShouldReduceMotion(),
|
||||
reduce_transparency: workspace.accessibilityDisplayShouldReduceTransparency(),
|
||||
};
|
||||
|
||||
SystemTheme {
|
||||
variant,
|
||||
accent: Self::color_to_hsla(&NSColor::controlAccentColor()),
|
||||
accessibility,
|
||||
// macOS blurs what is behind the window natively.
|
||||
window_background: Some(gpui::WindowBackgroundAppearance::Blurred),
|
||||
source: SourceKind::Macos,
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-runs the resolve pipeline when the system's theme changes.
|
||||
fn install_watchers(&mut self, async_cx: gpui::AsyncApp) {
|
||||
let signal = ReapplySignal::install(&async_cx);
|
||||
let observer = ThemeObserver::new(signal.sender());
|
||||
|
||||
let center = NSDistributedNotificationCenter::defaultCenter();
|
||||
for name in [
|
||||
"AppleColorPreferencesChangedNotification",
|
||||
"AppleInterfaceThemeChangedNotification",
|
||||
] {
|
||||
let name = NSNotificationName::from_str(name);
|
||||
// SAFETY: the observer is retained past every delivery.
|
||||
unsafe {
|
||||
center.addObserver_selector_name_object(
|
||||
&observer,
|
||||
sel!(themeDidChange:),
|
||||
Some(&name),
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let defaults = NSUserDefaults::standardUserDefaults();
|
||||
for key in [
|
||||
"AppleAccentColor",
|
||||
"AppleAquaColorVariant",
|
||||
"AppleInterfaceStyle",
|
||||
] {
|
||||
let key = NSString::from_str(key);
|
||||
// SAFETY: as above
|
||||
unsafe {
|
||||
defaults.addObserver_forKeyPath_options_context(
|
||||
&observer,
|
||||
&key,
|
||||
NSKeyValueObservingOptions::empty(),
|
||||
core::ptr::null_mut(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter();
|
||||
let accessibility_name =
|
||||
unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification };
|
||||
|
||||
// SAFETY: as above.
|
||||
unsafe {
|
||||
workspace_center.addObserver_selector_name_object(
|
||||
&observer,
|
||||
sel!(themeDidChange:),
|
||||
Some(accessibility_name),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
self._observer = Some(observer);
|
||||
self._signal = Some(signal);
|
||||
}
|
||||
|
||||
fn label(&self) -> &'static str {
|
||||
SourceKind::Macos.label()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Omarchy adapter: reads the current theme's `colors.toml` from the state
|
||||
//! directory (`~/.local/state/omarchy/current/theme/`). The parse is pure,
|
||||
//! so fixtures run on every OS; the IO lives behind the Linux cfg.
|
||||
|
||||
use gpui::Hsla;
|
||||
use toml::Table;
|
||||
|
||||
use crate::theme::system::{SourceKind, SystemTheme};
|
||||
use crate::theme::{AccessibilityPreferences, ThemeVariant};
|
||||
|
||||
/// The mode and accent Omarchy deploys with the current theme.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct OmarchyTheme {
|
||||
pub(crate) variant: ThemeVariant,
|
||||
pub(crate) accent: Option<Hsla>,
|
||||
}
|
||||
|
||||
impl OmarchyTheme {
|
||||
pub(crate) fn parse(text: &str) -> Option<Self> {
|
||||
let table = text.parse::<Table>().ok()?;
|
||||
|
||||
let background = hex_color(&table, "background")?;
|
||||
|
||||
let variant = table
|
||||
.get("mode")
|
||||
.and_then(toml::Value::as_str)
|
||||
.and_then(mode_variant)
|
||||
.unwrap_or_else(|| ThemeVariant::by_lightness(background));
|
||||
|
||||
let accent = hex_color(&table, "accent").or_else(|| hex_color(&table, "color4"));
|
||||
|
||||
Some(Self { variant, accent })
|
||||
}
|
||||
|
||||
pub(crate) fn into_system(self, accessibility: AccessibilityPreferences) -> SystemTheme {
|
||||
SystemTheme {
|
||||
variant: self.variant,
|
||||
accent: self.accent,
|
||||
accessibility,
|
||||
window_background: None,
|
||||
source: SourceKind::Omarchy,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mode_variant(mode: &str) -> Option<ThemeVariant> {
|
||||
match mode {
|
||||
"dark" => Some(ThemeVariant::Dark),
|
||||
"light" => Some(ThemeVariant::Light),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_color(table: &Table, key: &str) -> Option<Hsla> {
|
||||
let value = table.get(key)?.as_str()?;
|
||||
let digits = value.trim().strip_prefix('#')?;
|
||||
if digits.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
let hex = u32::from_str_radix(digits, 16).ok()?;
|
||||
Some(Hsla::from(gpui::rgb(hex)))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod io {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::OmarchyTheme;
|
||||
|
||||
fn home_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME").map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// The directory theme-set swaps on every theme change.
|
||||
pub(crate) fn current_dir() -> Option<PathBuf> {
|
||||
Some(home_dir()?.join(".local/state/omarchy/current"))
|
||||
}
|
||||
|
||||
pub(crate) fn read_current() -> Option<OmarchyTheme> {
|
||||
let text = std::fs::read_to_string(
|
||||
home_dir()?.join(".local/state/omarchy/current/theme/colors.toml"),
|
||||
)
|
||||
.ok()?;
|
||||
OmarchyTheme::parse(&text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! The xdg-desktop-portal Settings reader (`org.freedesktop.appearance`).
|
||||
//! GTK and GNOME toolkits take these values from the same place, so this is
|
||||
//! the canonical source on generic Linux. The value mapping is pure and
|
||||
//! fixture-tested on every OS; the DBus client lives behind the Linux cfg.
|
||||
|
||||
use gpui::Hsla;
|
||||
|
||||
use super::narrow_component;
|
||||
use crate::theme::ThemeVariant;
|
||||
use crate::theme::system::AccessibilityPreferences;
|
||||
|
||||
/// The raw portal values, already converted off the DBus wire types.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct AppearanceValues {
|
||||
/// 0 = no preference, 1 = prefer dark, 2 = prefer light.
|
||||
pub(crate) color_scheme: Option<u32>,
|
||||
/// The `accent-color` sRGB tuple, each component in 0..1.
|
||||
pub(crate) accent_rgb: Option<(f64, f64, f64)>,
|
||||
/// 0 = normal, 1 = higher.
|
||||
pub(crate) contrast: Option<u32>,
|
||||
/// 0 = no preference, 1 = reduced.
|
||||
pub(crate) reduced_motion: Option<u32>,
|
||||
}
|
||||
|
||||
impl AppearanceValues {
|
||||
pub(crate) fn decode(self) -> Appearance {
|
||||
Appearance {
|
||||
color_scheme: self.color_scheme,
|
||||
accent: self.accent_rgb.map(|(r, g, b)| {
|
||||
Hsla::from(gpui::Rgba {
|
||||
r: narrow_component(r),
|
||||
g: narrow_component(g),
|
||||
b: narrow_component(b),
|
||||
a: 1.0,
|
||||
})
|
||||
}),
|
||||
contrast: self.contrast.unwrap_or(0),
|
||||
reduced_motion: self.reduced_motion.unwrap_or(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the portal states under `org.freedesktop.appearance`.
|
||||
///
|
||||
/// Per the portal spec, unknown values read as unset.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Appearance {
|
||||
pub(crate) color_scheme: Option<u32>,
|
||||
pub(crate) accent: Option<Hsla>,
|
||||
pub(crate) contrast: u32,
|
||||
pub(crate) reduced_motion: u32,
|
||||
}
|
||||
|
||||
impl Appearance {
|
||||
pub(crate) fn variant(&self, no_preference: ThemeVariant) -> ThemeVariant {
|
||||
match self.color_scheme {
|
||||
Some(1) => ThemeVariant::Dark,
|
||||
Some(2) => ThemeVariant::Light,
|
||||
_ => no_preference,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn accessibility(self) -> AccessibilityPreferences {
|
||||
AccessibilityPreferences {
|
||||
high_contrast: self.contrast >= 1,
|
||||
reduce_motion: self.reduced_motion >= 1,
|
||||
reduce_transparency: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod io {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::OwnedValue;
|
||||
|
||||
use super::{Appearance, AppearanceValues};
|
||||
|
||||
type AppearanceCache = Arc<Mutex<Appearance>>;
|
||||
|
||||
const SERVICE: &str = "org.freedesktop.portal.Desktop";
|
||||
const PATH: &str = "/org/freedesktop/portal/desktop";
|
||||
const INTERFACE: &str = "org.freedesktop.portal.Settings";
|
||||
const NAMESPACE: &str = "org.freedesktop.appearance";
|
||||
|
||||
pub(crate) struct PortalClient {
|
||||
appearance: AppearanceCache,
|
||||
}
|
||||
|
||||
impl PortalClient {
|
||||
/// Reads the appearance once.
|
||||
pub(crate) fn connect() -> Option<Self> {
|
||||
let proxy = settings_proxy(Connection::session().ok()?)?;
|
||||
let appearance = Arc::new(Mutex::new(read_appearance(&proxy)?));
|
||||
Some(Self { appearance })
|
||||
}
|
||||
|
||||
/// The most recently read appearance.
|
||||
pub(crate) fn appearance(&self) -> Appearance {
|
||||
// A watch-thread panic must not crash the UI thread.
|
||||
let cache = self.appearance.lock();
|
||||
*cache.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Forwards portal `SettingChanged` events to the reapply signal from a dedicated thread.
|
||||
pub(crate) fn spawn_watch(&self, reapply_signal: async_channel::Sender<()>) {
|
||||
let appearance = self.appearance.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let Some(connection) = Connection::session().ok() else {
|
||||
log::warn!("theme: portal watch skipped, no session bus");
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(proxy) = settings_proxy(connection) else {
|
||||
log::warn!("theme: portal watch skipped, settings proxy unavailable");
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(signals) = proxy.receive_signal("SettingChanged") else {
|
||||
log::warn!("theme: portal watch skipped, signal subscription failed");
|
||||
return;
|
||||
};
|
||||
|
||||
for message in signals {
|
||||
let Ok((namespace, _key, _value)) =
|
||||
message.body().deserialize::<(String, String, OwnedValue)>()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if namespace != NAMESPACE {
|
||||
continue;
|
||||
}
|
||||
|
||||
match read_appearance(&proxy) {
|
||||
Some(latest) => {
|
||||
let mut cache = appearance
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
*cache = latest;
|
||||
super::super::signal::ReapplySignal::poke(&reapply_signal);
|
||||
}
|
||||
None => log::warn!("theme: portal read failed on SettingChanged"),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_proxy(connection: Connection) -> Option<Proxy<'static>> {
|
||||
Proxy::new(&connection, SERVICE, PATH, INTERFACE).ok()
|
||||
}
|
||||
|
||||
fn read_appearance(proxy: &Proxy<'static>) -> Option<Appearance> {
|
||||
let values: HashMap<String, HashMap<String, OwnedValue>> =
|
||||
proxy.call("ReadAll", &([NAMESPACE],)).ok()?;
|
||||
|
||||
let namespace = values.get(NAMESPACE)?;
|
||||
let field = |key: &str| namespace.get(key);
|
||||
|
||||
Some(
|
||||
AppearanceValues {
|
||||
color_scheme: field("color-scheme")
|
||||
.and_then(|value| u32::try_from(value.clone()).ok()),
|
||||
accent_rgb: field("accent-color")
|
||||
.and_then(|value| <(f64, f64, f64)>::try_from(value.clone()).ok()),
|
||||
contrast: field("contrast").and_then(|value| u32::try_from(value.clone()).ok()),
|
||||
reduced_motion: field("reduced-motion")
|
||||
.and_then(|value| u32::try_from(value.clone()).ok()),
|
||||
}
|
||||
.decode(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Wakes the main-thread resolve pipeline from watcher threads, which hold
|
||||
//! no gpui context (the pinned gpui's `AsyncApp` is not `Send`).
|
||||
|
||||
use gpui::{AsyncApp, Task};
|
||||
|
||||
pub(crate) struct ReapplySignal {
|
||||
sender: async_channel::Sender<()>,
|
||||
_task: Task<()>,
|
||||
}
|
||||
|
||||
impl ReapplySignal {
|
||||
pub(crate) fn install(async_cx: &AsyncApp) -> Self {
|
||||
let executor = async_cx.foreground_executor().clone();
|
||||
let async_cx = async_cx.clone();
|
||||
|
||||
let (sender, events) = async_channel::unbounded::<()>();
|
||||
|
||||
let task = executor.spawn(async move {
|
||||
while events.recv().await.is_ok() {
|
||||
async_cx.update(crate::theme::reapply);
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
sender,
|
||||
_task: task,
|
||||
}
|
||||
}
|
||||
|
||||
/// A clone for a watcher thread to poke the pipeline with.
|
||||
pub(crate) fn sender(&self) -> async_channel::Sender<()> {
|
||||
self.sender.clone()
|
||||
}
|
||||
|
||||
/// Pokes the pipeline from a thread holding a [`Self::sender`] clone.
|
||||
pub(crate) fn poke(sender: &async_channel::Sender<()>) {
|
||||
if let Err(error) = sender.try_send(()) {
|
||||
log::warn!("theme: reapply signal failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Windows 11 adapter: WinRT `UISettings` accent and background with a
|
||||
//! `Personalize` registry fallback, watched through `ColorValuesChanged`,
|
||||
//! `AdvancedEffectsEnabledChanged`, and `HighContrastChanged`.
|
||||
|
||||
use windows::Foundation::TypedEventHandler;
|
||||
use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings};
|
||||
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
|
||||
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
|
||||
use windows::core::IInspectable;
|
||||
|
||||
use super::ThemeSource;
|
||||
use super::signal::ReapplySignal;
|
||||
use crate::theme::ThemeVariant;
|
||||
use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme};
|
||||
|
||||
/// The `Personalize` registry values and the OS build number.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct RegistrySettings {
|
||||
apps_use_light_theme: Option<bool>,
|
||||
enable_transparency: Option<bool>,
|
||||
current_build: Option<u32>,
|
||||
}
|
||||
|
||||
impl RegistrySettings {
|
||||
fn read() -> Self {
|
||||
let personalize = || {
|
||||
windows_registry::CURRENT_USER
|
||||
.open(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")
|
||||
};
|
||||
let current_version = || {
|
||||
windows_registry::LOCAL_MACHINE.open(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
|
||||
};
|
||||
Self {
|
||||
apps_use_light_theme: personalize()
|
||||
.and_then(|key| key.get_u32("AppsUseLightTheme"))
|
||||
.ok()
|
||||
.map(|value| value != 0),
|
||||
enable_transparency: personalize()
|
||||
.and_then(|key| key.get_u32("EnableTransparency"))
|
||||
.ok()
|
||||
.map(|value| value != 0),
|
||||
current_build: current_version()
|
||||
.and_then(|key| key.get_string("CurrentBuildNumber"))
|
||||
.ok()
|
||||
.and_then(|build| build.parse::<u32>().ok()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WindowsSource {
|
||||
ui_settings: UISettings,
|
||||
accessibility_settings: AccessibilitySettings,
|
||||
registry: RegistrySettings,
|
||||
/// Keeps the main-thread channel loop alive.
|
||||
_signal: Option<ReapplySignal>,
|
||||
}
|
||||
|
||||
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
|
||||
// SAFETY: WinRT activation requires COM on this thread; the STA matches
|
||||
// the UI thread's message pump, and RPC_E_CHANGED_MODE means COM is
|
||||
// already initialized in another apartment.
|
||||
let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||
|
||||
if initialized.is_err() && initialized != RPC_E_CHANGED_MODE {
|
||||
log::error!("theme: COM initialization failed: {initialized:?}");
|
||||
}
|
||||
|
||||
match WindowsSource::new() {
|
||||
Some(source) => Box::new(source),
|
||||
None => {
|
||||
log::warn!("theme: Windows system theme unavailable; using fallback");
|
||||
Box::new(super::fallback::FallbackSource)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowsSource {
|
||||
fn new() -> Option<Self> {
|
||||
let ui_settings = match UISettings::new() {
|
||||
Ok(ui_settings) => ui_settings,
|
||||
Err(error) => {
|
||||
log::warn!("theme: UISettings unavailable: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let accessibility_settings = match AccessibilitySettings::new() {
|
||||
Ok(accessibility_settings) => accessibility_settings,
|
||||
Err(error) => {
|
||||
log::warn!("theme: AccessibilitySettings unavailable: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
Some(Self {
|
||||
ui_settings,
|
||||
accessibility_settings,
|
||||
registry: RegistrySettings::read(),
|
||||
_signal: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn color(&self, kind: UIColorType) -> Option<gpui::Hsla> {
|
||||
let color = self.ui_settings.GetColorValue(kind).ok()?;
|
||||
Some(gpui::Hsla::from(gpui::Rgba {
|
||||
r: color.R as f32 / 255.0,
|
||||
g: color.G as f32 / 255.0,
|
||||
b: color.B as f32 / 255.0,
|
||||
a: color.A as f32 / 255.0,
|
||||
}))
|
||||
}
|
||||
|
||||
fn accessibility(&self) -> AccessibilityPreferences {
|
||||
AccessibilityPreferences {
|
||||
high_contrast: self.accessibility_settings.HighContrast().unwrap_or(false),
|
||||
// Windows states animations separately in Win32; not read yet.
|
||||
reduce_motion: false,
|
||||
reduce_transparency: self
|
||||
.registry
|
||||
.enable_transparency
|
||||
.map(|enabled| !enabled)
|
||||
.unwrap_or(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The native backdrop: Mica on Windows 11, acrylic on Windows 10 1809+.
|
||||
fn window_material(&self) -> Option<gpui::WindowBackgroundAppearance> {
|
||||
match self.registry.current_build {
|
||||
// 22621: Windows 11 22H2, where the DWM backdrop types exist.
|
||||
Some(build) if build >= 22621 => Some(gpui::WindowBackgroundAppearance::MicaBackdrop),
|
||||
// 17763: Windows 10 1809, where acrylic blur-behind exists.
|
||||
Some(build) if build >= 17763 => Some(gpui::WindowBackgroundAppearance::Blurred),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThemeSource for WindowsSource {
|
||||
fn snapshot(&self, variant: ThemeVariant) -> SystemTheme {
|
||||
let accent = self.color(UIColorType::Accent);
|
||||
let background = self.color(UIColorType::Background);
|
||||
|
||||
let variant = background
|
||||
.map(ThemeVariant::by_lightness)
|
||||
.or(self.registry.apps_use_light_theme.map(|light| {
|
||||
if light {
|
||||
ThemeVariant::Light
|
||||
} else {
|
||||
ThemeVariant::Dark
|
||||
}
|
||||
}))
|
||||
.unwrap_or(variant);
|
||||
|
||||
SystemTheme {
|
||||
variant,
|
||||
accent,
|
||||
accessibility: self.accessibility(),
|
||||
window_background: self.window_material(),
|
||||
source: SourceKind::Windows,
|
||||
}
|
||||
}
|
||||
|
||||
fn install_watchers(&mut self, async_cx: gpui::AsyncApp) {
|
||||
let signal = ReapplySignal::install(&async_cx);
|
||||
let color_signal = signal.sender();
|
||||
let color_handler = TypedEventHandler::<UISettings, IInspectable>::new(move |_, _| {
|
||||
ReapplySignal::poke(&color_signal);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
if let Err(error) = self.ui_settings.ColorValuesChanged(&color_handler) {
|
||||
log::warn!("theme: color change watch failed: {error}");
|
||||
}
|
||||
|
||||
let effects_signal = signal.sender();
|
||||
let effects_handler = TypedEventHandler::<UISettings, IInspectable>::new(move |_, _| {
|
||||
ReapplySignal::poke(&effects_signal);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
if let Err(error) = self
|
||||
.ui_settings
|
||||
.AdvancedEffectsEnabledChanged(&effects_handler)
|
||||
{
|
||||
log::warn!("theme: advanced effects watch failed: {error}");
|
||||
}
|
||||
|
||||
let contrast_signal = signal.sender();
|
||||
let contrast_handler =
|
||||
TypedEventHandler::<AccessibilitySettings, IInspectable>::new(move |_, _| {
|
||||
ReapplySignal::poke(&contrast_signal);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
if let Err(error) = self
|
||||
.accessibility_settings
|
||||
.HighContrastChanged(&contrast_handler)
|
||||
{
|
||||
log::warn!("theme: high contrast watch failed: {error}");
|
||||
}
|
||||
|
||||
self._signal = Some(signal);
|
||||
}
|
||||
|
||||
fn label(&self) -> &'static str {
|
||||
SourceKind::Windows.label()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user