Don't rely on AppleInterfaceStyle for theme switching (#8615)

* Fix #7615 - Don't rely on AppleInterfaceStyle preference key for dark mode detection, as it's not always correct
This commit is contained in:
Lars Fröder 2023-01-30 02:15:12 +01:00 committed by GitHub
parent d90b32a7c9
commit 1e770e3a71
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -38,10 +38,7 @@
name:NSWorkspaceSessionDidResignActiveNotification name:NSWorkspaceSessionDidResignActiveNotification
object:nil]; object:nil];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self [NSApp addObserver:self forKeyPath:@"effectiveAppearance" options:NSKeyValueObservingOptionNew context:nil];
selector:@selector(interfaceThemeChanged:)
name:@"AppleInterfaceThemeChangedNotification"
object:nil];
// Unfortunately, there is no notification for a wallpaper change, which affects // Unfortunately, there is no notification for a wallpaper change, which affects
// the status bar colour on macOS Big Sur, but we can at least subscribe to this. // the status bar colour on macOS Big Sur, but we can at least subscribe to this.
@ -67,14 +64,29 @@
} }
} }
// - (void) observeValueForKeyPath:(NSString *)keyPath
// Light / dark theme toggled ofObject:(id)object
// change:(NSDictionary<NSKeyValueChangeKey,id> *)change
- (void) interfaceThemeChanged:(NSNotification*) notification context:(void *)context
{ {
Q_UNUSED(notification); Q_UNUSED(object)
Q_UNUSED(change)
Q_UNUSED(context)
if ([keyPath isEqualToString:@"effectiveAppearance"]) {
if (m_appkit) { if (m_appkit) {
void (^emitBlock)(void) = ^{
emit m_appkit->interfaceThemeChanged(); emit m_appkit->interfaceThemeChanged();
};
if(@available(macOS 11.0, *)) {
// Not sure why exactly this call is needed, but Apple sample code uses it so it's best to use it here too
[NSApp.effectiveAppearance performAsCurrentDrawingAppearance:emitBlock];
}
else {
emitBlock();
}
}
} }
} }
@ -127,10 +139,7 @@
// //
- (bool) isDarkMode - (bool) isDarkMode
{ {
NSDictionary* dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain]; return [NSApp.effectiveAppearance.name isEqualToString:NSAppearanceNameDarkAqua];
id style = [dict objectForKey:@"AppleInterfaceStyle"];
return ( style && [style isKindOfClass:[NSString class]]
&& NSOrderedSame == [style caseInsensitiveCompare:@"dark"] );
} }