From d7e404707031b35b34291d236307f3b54b5e9727 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 16 Nov 2026 11:06:25 +0700 Subject: [PATCH] theme: extend live theme change watching on macos and windows --- crates/theme/Cargo.toml | 5 +- crates/theme/src/source.rs | 2 +- crates/theme/src/source/macos.rs | 111 +++++++++++++++++++++++------ crates/theme/src/source/signal.rs | 15 ++-- crates/theme/src/source/windows.rs | 27 ++++++- 5 files changed, 128 insertions(+), 32 deletions(-) diff --git a/crates/theme/Cargo.toml b/crates/theme/Cargo.toml index eedb9e0..7d46378 100644 --- a/crates/theme/Cargo.toml +++ b/crates/theme/Cargo.toml @@ -14,7 +14,7 @@ toml = "0.8" [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } -[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] +[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies] async-channel = "2" [target.'cfg(target_os = "linux")'.dependencies] @@ -44,9 +44,12 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [ "objc2-core-foundation", ] } objc2-foundation = { version = "=0.3.2", default-features = false, features = [ + "NSDictionary", "NSDistributedNotificationCenter", "NSNotification", + "NSKeyValueObserving", "NSOperation", + "NSUserDefaults", "NSString", "block2", "std", diff --git a/crates/theme/src/source.rs b/crates/theme/src/source.rs index a509cf7..0cc9703 100644 --- a/crates/theme/src/source.rs +++ b/crates/theme/src/source.rs @@ -51,7 +51,7 @@ pub(crate) mod linux; #[cfg(target_os = "windows")] pub(crate) mod windows; -#[cfg(any(target_os = "linux", target_os = "windows"))] +#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] pub(crate) mod signal; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] diff --git a/crates/theme/src/source/macos.rs b/crates/theme/src/source/macos.rs index 31a90fb..cfb2a70 100644 --- a/crates/theme/src/source/macos.rs +++ b/crates/theme/src/source/macos.rs @@ -4,19 +4,21 @@ //! the system's color preferences. use objc2::rc::Retained; -use objc2::runtime::{NSObjectProtocol, ProtocolObject}; +use objc2::runtime::{AnyObject, NSObject}; +use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel}; use objc2_app_kit::{ NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSColor, NSColorSpace, - NSWorkspace, + NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification, }; use objc2_foundation::{ - NSDistributedNotificationCenter, NSNotification, NSNotificationName, NSOperationQueue, + NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification, + NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults, }; -use std::ptr::NonNull; use super::narrow_component; use super::ThemeSource; +use super::signal::ReapplySignal; use crate::ThemeVariant; use crate::system::{AccessibilityPreferences, PartialPalette, SourceKind, SystemTheme}; @@ -37,9 +39,44 @@ const TITLEBAR_HEIGHT_PTS: f32 = 32.0; /// The HIG's default body text on macOS is 13 pt (system font size 13 at 1x). const ROOT_FONT_SIZE_PTS: f32 = 13.0; +// 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>, + _context: *mut core::ffi::c_void, + ) { + ReapplySignal::poke(self.ivars()); + } + } +); + +impl ThemeObserver { + fn new(reapply: async_channel::Sender<()>) -> Retained { + let this = Self::alloc().set_ivars(reapply); + unsafe { msg_send![super(this), init] } + } +} + #[derive(Default)] pub(crate) struct MacosSource { - _observers: Vec>>, + /// The notification centers track, but do not retain, the observer. + _observer: Option>, + /// Keeps the reapply loop alive. + _signal: Option, } impl MacosSource { @@ -142,34 +179,62 @@ impl ThemeSource for MacosSource { } } - /// Fires on accent and appearance changes (System Settings > Appearance) - /// and re-runs the resolve pipeline through `async_cx`. + /// Re-runs the resolve pipeline when the system's theme changes. fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { - let center = NSDistributedNotificationCenter::defaultCenter(); - let queue = NSOperationQueue::mainQueue(); + let signal = ReapplySignal::install(&async_cx); + let observer = ThemeObserver::new(signal.sender()); + let center = NSDistributedNotificationCenter::defaultCenter(); for name in [ "AppleColorPreferencesChangedNotification", "AppleInterfaceThemeChangedNotification", ] { - let async_cx = async_cx.clone(); - let block = block2::RcBlock::new(move |_notification: NonNull| { - async_cx.update(crate::reapply); - }); let name = NSNotificationName::from_str(name); - // SAFETY: the observer token is retained for the source's lifetime, - // the block is sendable (AsyncApp is Clone + 'static) - // and the main queue runs it outside any App borrow. - let observer = unsafe { - center.addObserverForName_object_queue_usingBlock( + // SAFETY: the observer is retained past every delivery. + unsafe { + center.addObserver_selector_name_object( + &observer, + sel!(themeDidChange:), Some(&name), None, - Some(&queue), - &block, - ) - }; - self._observers.push(observer); + ); + } } + + 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 { diff --git a/crates/theme/src/source/signal.rs b/crates/theme/src/source/signal.rs index 6a78a41..82bb51b 100644 --- a/crates/theme/src/source/signal.rs +++ b/crates/theme/src/source/signal.rs @@ -10,14 +10,17 @@ pub(crate) struct ReapplySignal { 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 = async_cx.update(|cx| { - cx.spawn(async move |cx| { - while events.recv().await.is_ok() { - cx.update(crate::reapply); - } - }) + + let task = executor.spawn(async move { + while events.recv().await.is_ok() { + async_cx.update(crate::reapply); + } }); + Self { sender, _task: task, diff --git a/crates/theme/src/source/windows.rs b/crates/theme/src/source/windows.rs index 562dc85..49bd5c4 100644 --- a/crates/theme/src/source/windows.rs +++ b/crates/theme/src/source/windows.rs @@ -1,5 +1,7 @@ //! Windows 11 adapter: WinRT `UISettings` semantic colors with a -//! `Personalize` registry fallback, watched through `ColorValuesChanged`. +//! `Personalize` registry fallback, watched through `ColorValuesChanged`, +//! `TextScaleFactorChanged`, `AdvancedEffectsEnabledChanged`, and +//! `HighContrastChanged`. use windows::Foundation::TypedEventHandler; use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings}; @@ -212,6 +214,29 @@ impl ThemeSource for WindowsSource { log::warn!("theme: color change watch failed: {error}"); } + let scale_signal = signal.sender(); + let scale_handler = TypedEventHandler::::new(move |_, _| { + ReapplySignal::poke(&scale_signal); + Ok(()) + }); + + if let Err(error) = self.ui_settings.TextScaleFactorChanged(&scale_handler) { + log::warn!("theme: text scale watch failed: {error}"); + } + + let effects_signal = signal.sender(); + let effects_handler = TypedEventHandler::::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::::new(move |_, _| {