Sine Striker
2024-05-19 4e7058084d51193e3c975bcddbe749e7fd29e356
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (C) 2023-2024 Stdware Collections (https://www.github.com/stdware)
// Copyright (C) 2021-2023 wangwenx190 (Yuhang Zhao)
// SPDX-License-Identifier: Apache-2.0
 
#include "styleagent_p.h"
 
#include <Cocoa/Cocoa.h>
 
#include <QtCore/QVariant>
 
namespace QWK {
 
    static StyleAgent::SystemTheme getSystemTheme() {
        NSString *osxMode =
            [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
        bool isDark = [osxMode isEqualToString:@"Dark"];
        return isDark ? StyleAgent::Dark : StyleAgent::Light;
    }
 
    static void notifyAllStyleAgents();
 
}
 
//
// Objective C++ Begin
//
 
@interface QWK_SystemThemeObserver : NSObject {
}
@end
 
@implementation QWK_SystemThemeObserver
 
- (id)init {
    self = [super init];
    if (self) {
        [[NSDistributedNotificationCenter defaultCenter]
            addObserver:self
               selector:@selector(interfaceModeChanged:)
                   name:@"AppleInterfaceThemeChangedNotification"
                 object:nil];
    }
    return self;
}
 
- (void)dealloc {
    [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
 
- (void)interfaceModeChanged:(NSNotification *)notification {
    QWK::notifyAllStyleAgents();
}
 
@end
 
//
// Objective C++ End
//
 
 
namespace QWK {
 
    using StyleAgentSet = QSet<StyleAgentPrivate *>;
    Q_GLOBAL_STATIC(StyleAgentSet, g_styleAgentSet)
 
    static QWK_SystemThemeObserver *g_systemThemeObserver = nil;
 
    void notifyAllStyleAgents() {
        auto theme = getSystemTheme();
        for (auto &&ap : std::as_const(*g_styleAgentSet())) {
            ap->notifyThemeChanged(theme);
        }
    }
 
    void StyleAgentPrivate::setupSystemThemeHook() {
        systemTheme = getSystemTheme();
 
        // Alloc
        if (g_styleAgentSet->isEmpty()) {
            g_systemThemeObserver = [[QWK_SystemThemeObserver alloc] init];
        }
 
        g_styleAgentSet->insert(this);
    }
 
    void StyleAgentPrivate::removeSystemThemeHook() {
        if (!g_styleAgentSet->remove(this))
            return;
 
        if (g_styleAgentSet->isEmpty()) {
            // Delete
            [g_systemThemeObserver release];
            g_systemThemeObserver = nil;
        }
    }
 
}