-
Notifications
You must be signed in to change notification settings - Fork 222
/
MenuMetersMenuExtraBase.m
305 lines (295 loc) · 11.7 KB
/
MenuMetersMenuExtraBase.m
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//
// NSMenuExtraBase.m
// MenuMeters
//
// Created by Yuji on 2015/08/01.
//
//
#import "MenuMetersMenuExtraBase.h"
#import "MenuMeterWorkarounds.h"
#import "MenuMeterCPUExtra.h"
#import "MenuMeterDiskExtra.h"
#import "MenuMeterMemExtra.h"
#import "MenuMeterNetExtra.h"
#define kAppleInterfaceThemeChangedNotification @"AppleInterfaceThemeChangedNotification"
@implementation MenuMetersMenuExtraBase
-(NSColor*)colorByAdjustingForLightDark:(NSColor*)c
{
[self setupAppearance];
return [c blendedColorWithFraction:[[NSUserDefaults standardUserDefaults] floatForKey:@"tintPercentage"]/100 ofColor:self.isDark?[[NSColor whiteColor] colorWithAlphaComponent:[c alphaComponent]]:[[NSColor blackColor] colorWithAlphaComponent:[c alphaComponent]]];
}
-(instancetype)initWithBundleID:(NSString*)bundleID
{
self=[super init];
self.bundleID=bundleID;
// Register for pref changes
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(configFromPrefs:)
name:self.bundleID
object:kPrefChangeNotification];
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"tintPercentage" options:NSKeyValueObservingOptionNew context:nil];
if(@available(macOS 10.14,*)){
}else{
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(setupColor:)
name:kAppleInterfaceThemeChangedNotification
object:nil];
}
return self;
}
-(void)configFromPrefs:(NSNotification *)notification
{
NSLog(@"shouldn't happen");
abort();
}
-(NSMenu*)menu
{
NSLog(@"shouldn't happen");
abort();
}
-(void)setupColor:(NSNotification*)notification
{
NSLog(@"shouldn't happen");
abort();
}
-(CGFloat)imageHeight
{
return self.height-1;
}
-(NSImage*)image
{
NSSize imageSize=NSMakeSize(menuWidth,self.imageHeight);
return [NSImage imageWithSize:imageSize
flipped:NO
drawingHandler:^BOOL(NSRect dstRect) {
return [self renderImage];
}];
}
-(BOOL)renderImage
{
NSLog(@"shouldn't happen");
abort();
}
-(void)timerFired:(id)notused
{
statusItem.button.image=self.image;
if(@available(macOS 12,*)){
if(self.isInstalledButHiddenBySystem){
[[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenBySystem" object:nil];
}
}
/* NSImage*image=self.image;
NSImage*canvas=[NSImage imageWithSize:image.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
[[[NSColor systemGrayColor] colorWithAlphaComponent:.3] setFill];
[NSBezierPath fillRect:(CGRect) {.size = image.size}];
[image drawAtPoint:CGPointZero fromRect:(CGRect) {.size = image.size} operation:NSCompositeSourceOver fraction:1.0];
return YES;
}];
statusItem.button.image=canvas;*/
}
/*
-(void)timerXired:(id)notused
{
NSImage *oldCanvas = statusItem.button.image;
NSImage *canvas = oldCanvas;
NSImage *image = self.image;
NSSize imageSize = image.size;
NSSize oldImageSize = canvas.size;
if (imageSize.width != oldImageSize.width || imageSize.height != oldImageSize.height) {
canvas = [[NSImage alloc] initWithSize:imageSize];
}
[canvas lockFocus];
[image drawAtPoint:CGPointZero fromRect:(CGRect) {.size = image.size} operation:NSCompositeCopy fraction:1.0];
[canvas unlockFocus];
if (canvas != oldCanvas) {
statusItem.button.image = canvas;
} else {
[statusItem.button displayRectIgnoringOpacity:statusItem.button.bounds];
}
}
*/
- (void)configDisplay:(NSString*)bundleID fromPrefs:(MenuMeterDefaults*)ourPrefs withTimerInterval:(NSTimeInterval)interval
{
if([ourPrefs loadBoolPref:bundleID defaultValue:YES]){
if(!statusItem){
statusItem=[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101600)
if(@available(macOS 11,*)){
// 11.0.1 does not keep the position unless autosaveName is explicitly set,
// see https://github.com/feedback-assistant/reports/issues/151 .
// This is done here in order not to lose positions on pre-macOS 11 systems.
statusItem.autosaveName=self.bundleID;
}
#endif
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200)
if(@available(macOS 10.12,*)){
statusItem.behavior=NSStatusItemBehaviorRemovalAllowed;
[statusItem addObserver:self forKeyPath:@"visible" options:NSKeyValueObservingOptionNew context:nil];
}
#endif
statusItem.menu = self.menu;
statusItem.menu.delegate = self;
/*
Observing effectiveAppearance has a serious drawback when the Mac has two moniters, one with a light menubar and another with a dard menubar, which can happen since Big Sur depending on the chosen desktop pictures.
In such cases statusItem.button.effectiveAppearance changes each time the system redraws the statusItem.button on two menubars, making configFromPrefs: called every time.
Honestly, the way a single NSStatusItem behaves differently on two menubars with different appearances is undocumented, especially with a dynamically-drawn block-based image attached on a button...
*/
[statusItem.button addObserver:self forKeyPath:@"effectiveAppearance" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
[updateTimer invalidate];
updateTimer=[NSTimer timerWithTimeInterval:interval target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
[updateTimer setTolerance:.2*interval];
[[NSRunLoop currentRunLoop] addTimer:updateTimer forMode:NSRunLoopCommonModes];
}else if(![ourPrefs loadBoolPref:bundleID defaultValue:YES] && statusItem){
[self removeStatusItem];
}
}
-(void)removeStatusItem
{
[updateTimer invalidate];
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
statusItem=nil;
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"menuExtraUnloaded" object:self.bundleID]];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if(object==statusItem.button && [keyPath isEqualToString:@"effectiveAppearance"]){
NSAppearance*old=change[NSKeyValueChangeOldKey];
NSAppearance*new=change[NSKeyValueChangeNewKey];
if(![old.name isEqualToString:new.name]){
[self setupColor:nil];
}
}
if(@available(macOS 10.12,*)){
if(object==statusItem && [keyPath isEqualToString:@"visible"]){
if(!statusItem.visible){
[self removeStatusItem];
}
}
}
if([keyPath isEqualToString:@"tintPercentage"]){
[self setupColor:nil];
}
}
- (void)openMenuMetersPref:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"openPref" object:self]];
}
- (void)openActivityMonitor:(id)sender {
if (![[NSWorkspace sharedWorkspace] launchApplication:@"Activity Monitor.app"]) {
NSLog(@"MenuMeter unable to launch the Activity Monitor.");
}
BOOL x=[[NSUserDefaults standardUserDefaults] boolForKey:@"activityMonitorOpenSpecificPanes"];
if(!x)
return;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(),^{
// if(@available(macOS 10.15,*)){
int tab=1;
if([self isKindOfClass:[MenuMeterCPUExtra class]]){
tab=1;
}
// on some Mac's there is a "GPU" tab at the 2nd position.
// So the rest needs to be addressed from the last
if([self isKindOfClass:[MenuMeterDiskExtra class]]){
tab=-2;
}
if([self isKindOfClass:[MenuMeterMemExtra class]]){
tab=-4;
}
if([self isKindOfClass:[MenuMeterNetExtra class]]){
tab=-1;
}
NSString*source=[NSString stringWithFormat:@"tell application \"System Events\" to tell process \"Activity Monitor\" to click radio button %@ of radio group 1 of group 2 of toolbar of window 1", @(tab)];
NSAppleScript*script=[[NSAppleScript alloc] initWithSource:source];
NSDictionary* errorDict=nil;
[script executeAndReturnError:&errorDict];
if(errorDict){
NSLog(@"%@",errorDict);
}
// }
});
} // openActivityMonitor
- (void)addStandardMenuEntriesTo:(NSMenu*)extraMenu
{
NSMenuItem* menuItem = (NSMenuItem *)[extraMenu addItemWithTitle:NSLocalizedString(kOpenActivityMonitorTitle, kOpenActivityMonitorTitle)
action:@selector(openActivityMonitor:)
keyEquivalent:@""];
[menuItem setTarget:self];
menuItem = (NSMenuItem *)[extraMenu addItemWithTitle:NSLocalizedString(kOpenMenuMetersPref, kOpenMenuMetersPref)
action:@selector(openMenuMetersPref:)
keyEquivalent:@""];
[menuItem setTarget:self];
}
-(BOOL)isDark
{
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101400)
if(@available(macOS 10.14,*)){
// https://github.com/ruiaureliano/macOS-Appearance/blob/master/Appearance/Source/AppDelegate.swift
return [statusItem.button.effectiveAppearance.name containsString:@"ark"];
}
#endif
// https://stackoverflow.com/questions/25207077/how-to-detect-if-os-x-is-in-dark-mode
// On 10.10 there is no documented API for theme, so we'll guess a couple of different ways.
BOOL isDark = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];
NSString *interfaceStyle = [defaults stringForKey:@"AppleInterfaceStyle"];
if (interfaceStyle && [interfaceStyle isEqualToString:@"Dark"]) {
isDark = YES;
}
return isDark;
}
-(BOOL)isInstalledButHiddenBySystem
{
NSWindow*window=statusItem.button.window;
if(!window){
return NO;
}
NSInteger windowID=window.windowNumber;
NSArray*onScreenWindows=CFBridgingRelease(CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID));
for(id x in onScreenWindows){
if(windowID==(NSInteger)x)
return NO;
}
return YES;
}
-(NSColor*)menuBarTextColor
{
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101400)
if(@available(macOS 10.14,*)){
return [NSColor labelColor];
}
#endif
if (self.isDark){
return [NSColor whiteColor];
}
return [NSColor blackColor];
}
-(CGFloat)height
{
CGFloat height=statusItem.button.frame.size.height;
// height is sometimes zero here, which causes a lot of headaches if untreated...
if(height<10){
height=22; // the value before Big Sur.
}
return height;
}
- (void)setupAppearance {
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101400)
if(@available(macOS 10.14,*)){
[NSAppearance setCurrentAppearance:statusItem.button.effectiveAppearance];
}
#endif
}
#pragma mark NSMenuDelegate
- (void)menuNeedsUpdate:(NSMenu*)menu {
statusItem.menu = self.menu;
statusItem.menu.delegate = self;
}
- (void)menuWillOpen:(NSMenu*)menu {
_isMenuVisible = YES;
}
- (void)menuDidClose:(NSMenu*)menu {
_isMenuVisible = NO;
}
@end