Skip to content

Commit

Permalink
Don't rely on AppleInterfaceStyle for theme switching (keepassxreboot…
Browse files Browse the repository at this point in the history
…#8615)

* Fix keepassxreboot#7615 - Don't rely on AppleInterfaceStyle preference key for dark mode detection, as it's not always correct
  • Loading branch information
opa334 authored and pull[bot] committed Jan 30, 2023
1 parent a52d0bc commit 0914524
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions src/gui/osutils/macutils/AppKitImpl.mm
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ - (id) initWithObject:(AppKit*)appkit
name:NSWorkspaceSessionDidResignActiveNotification
object:nil];

[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(interfaceThemeChanged:)
name:@"AppleInterfaceThemeChangedNotification"
object:nil];
[NSApp addObserver:self forKeyPath:@"effectiveAppearance" options:NSKeyValueObservingOptionNew context:nil];

// 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.
Expand All @@ -67,14 +64,29 @@ - (void) didDeactivateApplicationObserver:(NSNotification*) notification
}
}

//
// Light / dark theme toggled
//
- (void) interfaceThemeChanged:(NSNotification*) notification
- (void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey,id> *)change
context:(void *)context
{
Q_UNUSED(notification);
if (m_appkit) {
emit m_appkit->interfaceThemeChanged();
Q_UNUSED(object)
Q_UNUSED(change)
Q_UNUSED(context)
if ([keyPath isEqualToString:@"effectiveAppearance"]) {
if (m_appkit) {

void (^emitBlock)(void) = ^{
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();
}
}
}
}

Expand Down Expand Up @@ -127,10 +139,7 @@ - (bool) isHidden:(pid_t) pid
//
- (bool) isDarkMode
{
NSDictionary* dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
id style = [dict objectForKey:@"AppleInterfaceStyle"];
return ( style && [style isKindOfClass:[NSString class]]
&& NSOrderedSame == [style caseInsensitiveCompare:@"dark"] );
return [NSApp.effectiveAppearance.name isEqualToString:NSAppearanceNameDarkAqua];
}


Expand Down

0 comments on commit 0914524

Please sign in to comment.