theme: extend live theme change watching on macos and windows

This commit is contained in:
2026-11-16 11:06:25 +07:00
parent 573d8a8303
commit d7e4047070
5 changed files with 128 additions and 32 deletions
+4 -1
View File
@@ -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",
+1 -1
View File
@@ -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))]
+88 -23
View File
@@ -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<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 {
_observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
/// The notification centers track, but do not retain, the observer.
_observer: Option<Retained<ThemeObserver>>,
/// Keeps the reapply loop alive.
_signal: Option<ReapplySignal>,
}
impl MacosSource {
@@ -142,36 +179,64 @@ 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<NSNotification>| {
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 {
SourceKind::Macos.label()
}
+7 -4
View File
@@ -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| {
let task = executor.spawn(async move {
while events.recv().await.is_ok() {
cx.update(crate::reapply);
async_cx.update(crate::reapply);
}
})
});
Self {
sender,
_task: task,
+26 -1
View File
@@ -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::<UISettings, IInspectable>::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::<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 |_, _| {