forked from rugarciap/Turbo-Boost-Switcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppDelegate.m
905 lines (670 loc) · 30.3 KB
/
AppDelegate.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//
// AppDelegate.m
// Turbo Boost Switcher
//
// Created by Rubén García Pérez on 19/07/13.
// Copyright (c) 2013 Rubén García Pérez.
// rugarciap.com
//
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#import "AppDelegate.h"
#import "SystemCommands.h"
#import "AboutWindowController.h"
#import "StartupHelper.h"
#import "CheckUpdatesWindowController.h"
#import <IOKit/ps/IOPowerSources.h>
#import <IOKit/ps/IOPSKeys.h>
@implementation AppDelegate
@synthesize aboutWindow, refreshTimer, checkUpdatesWindow, chartWindowController;
// Struct to take the cpu samples
struct cpusample {
uint64_t totalSystemTime;
uint64_t totalUserTime;
uint64_t totalIdleTime;
};
// The two samples
struct cpusample sample_one;
struct cpusample sample_two;
// On wake up reinstall the module if needed
- (void) receiveWakeNote: (NSNotification*) note
{
// Reload the module if the current status is on, since OSX enables turbo boost after an
// undetermined time on sleep / hibernation
if ([SystemCommands isModuleLoaded]) {
if (authorizationRef == NULL) {
OSStatus status = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&authorizationRef);
AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights rights = {1, &right};
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
if (status != errAuthorizationSuccess)
NSLog(@"Copy Rights Unsuccessful: %d", status);
}
[SystemCommands unLoadModuleWithAuthRef:authorizationRef];
[SystemCommands loadModuleWithAuthRef:authorizationRef];
}
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:0.5];
// Add another status bar refresh just to be sure, since depending on mac cpu load it can take a little longer
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:1.5];
}
// Suscribe to wake up notifications
- (void) fileNotifications
{
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(receiveWakeNote:)
name: NSWorkspaceDidWakeNotification object: NULL];
}
- (void) awakeFromNib {
// Init the cpu load samples
sample_one.totalIdleTime = 0;
sample_two.totalIdleTime = 0;
// Locale init
if ([StartupHelper currentLocale] == nil) {
// Get the current language
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
// Save it
[StartupHelper storeCurrentLocale:currentLanguage];
}
// Update languages menú
[self updateLanguageMenu];
// Init the check for updates helper
checkUpdatesHelper = [[CheckUpdatesHelper alloc] init];
// Item to show up on the status bar
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
statusImageOn = [NSImage imageNamed:@"icon"];
statusImageOff = [NSImage imageNamed:@"icon_off"];
[statusImageOn setTemplate:YES];
[statusImageOff setTemplate:YES];
[statusItem setToolTip:@"Turbo Boost Switcher"];
[statusItem setHighlightMode:YES];
[statusItem setImage:statusImageOn];
[statusItem setAction:@selector(statusItemClicked)];
[statusItem setTarget:self];
// Charting menu item
[chartsMenuItem setTitle:NSLocalizedString(@"menuCharting", nil)];
// Update open at login status
[checkOpenAtLogin setState:[StartupHelper isOpenAtLogin]];
[checkOpenAtLogin setTitle:NSLocalizedString(@"open_login", nil)];
// Update check monitoring
[checkMonitoring setState:[StartupHelper isMonitoringEnabled]];
// Update disable at login status
[checkDisableAtLaunch setState:[StartupHelper isDisableAtLaunch]];
[checkDisableAtLaunch setTitle:NSLocalizedString(@"disable_login", nil)];
// Update translations
[settingsLabel setTitleWithMnemonic:NSLocalizedString(@"settings", nil)];
[checkUpdatesItem setTitle:NSLocalizedString(@"updates", nil)];
[aboutItem setTitle:NSLocalizedString(@"about", nil)];
[exitItem setTitle:NSLocalizedString(@"quit", nil)];
// Status strings init
statusOnOff = [[NSMutableString alloc] initWithString:@""];
[checkOnOffText setState:[StartupHelper isStatusOnOffEnabled]];
[checkOnOffText setTitle:NSLocalizedString(@"onOffMenu", nil)];
[checkOnOffText setFont:[statusMenu font]];
// Update fonts
[settingsLabel setFont:[statusMenu font]];
[checkDisableAtLaunch setFont:[statusMenu font]];
[checkOpenAtLogin setFont:[statusMenu font]];
[checkMonitoring setFont:[statusMenu font]];
// Init the chart window controller
if (self.chartWindowController == nil) {
self.chartWindowController = [[ChartWindowController alloc] initWithWindowNibName:@"ChartWindowController"];
[self.chartWindowController initData];
}
// Disable at launch if enabled
if (([StartupHelper isDisableAtLaunch]) && (![SystemCommands isModuleLoaded])) {
[self disableTurboBoost];
}
// Refresh the status
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:1.0];
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:2.5];
// Initially refresh the sensor values
[self updateSensorValues];
[NSThread sleepForTimeInterval:0.1];
[self updateSensorValues];
// Timer to update the sensor readings (cpu & fan rpm) each 4 seconds
NSInteger refreshTimeValue = [StartupHelper sensorRefreshTime];
if (refreshTimeValue < 4) {
refreshTimeValue = 4;
}
[sliderRefreshTime setIntegerValue:refreshTimeValue];
[checkMonitoring setTitle:[NSString stringWithFormat:NSLocalizedString(@"sliderRefreshTimeLabel", nil), sliderRefreshTime.integerValue]];
self.refreshTimer = [NSTimer timerWithTimeInterval:refreshTimeValue target:self selector:@selector(updateSensorValues) userInfo:nil repeats:YES];
NSRunLoop * rl = [NSRunLoop mainRunLoop];
[rl addTimer:self.refreshTimer forMode:NSRunLoopCommonModes];
// Subscribe to sleep and wake up notifications
[self fileNotifications];
// Refresh the status item
[self updateStatus];
// Check for updates
if ([StartupHelper isCheckUpdatesOnStart]) {
[checkUpdatesHelper checkUpdatesWithDelegate:(id) self];
}
// Check run count and if mod 10, suggets going pro if the user don't answered "never shot this again" :).
if (![StartupHelper neverShowProMessage]) {
if (([StartupHelper runCount] % 10) == 0) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:NSLocalizedString(@"alert_later", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"alert_never_show_again", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"btn_pro",nil)];
[alert setMessageText:NSLocalizedString(@"alert_text", nil)];
[alert setInformativeText:NSLocalizedString(@"alert_informative_text", nil)];
[alert setAlertStyle:NSWarningAlertStyle];
NSModalResponse modalResponse = [alert runModal];
if (modalResponse == NSAlertSecondButtonReturn) {
// Never show again clicked
[StartupHelper storeNeverShowProMessage:YES];
} else if (modalResponse == NSAlertThirdButtonReturn) {
// Go pro!
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://gumroad.com/l/YeBQUF"]];
}
}
// Save the current count
int currentCount = (int)[StartupHelper runCount];
[StartupHelper storeRunCount:(currentCount + 1)];
}
// Refresh the status item
[self updateStatus];
// Configure sensors view
[self configureSensorsView];
// Update monitoring state depending on monitoring enabled / disabled
[self updateMonitoringState];
// Assign the menu
statusItem.menu = statusMenu;
}
// Invoked when the user clicks on the satus menu
- (void)statusItemClicked {
statusItem.menu = statusMenu;
[self updateStatus];
}
// Method to refresh the temperature image sensor depending on temperture
- (void) updateImageForTemperature:(int) temp {
if (temp <= 60) {
[temperatureImage setImage:[NSImage imageNamed:@"temperature_1.png"]];
} else if (temp < 70) {
[temperatureImage setImage:[NSImage imageNamed:@"temperature_2.png"]];
} else if (temp < 80) {
[temperatureImage setImage:[NSImage imageNamed:@"temperature_3.png"]];
} else if (temp < 90) {
[temperatureImage setImage:[NSImage imageNamed:@"temperature_4.png"]];
} else {
[temperatureImage setImage:[NSImage imageNamed:@"temperature_5.png"]];
}
}
// Refresh the GUI general status, including enable/disable options, on-off status, cpu & fan reads
- (void) updateStatus {
// Check other status
isTurboBoostEnabled= ![SystemCommands isModuleLoaded];
if (isTurboBoostEnabled) {
if ([StartupHelper isStatusOnOffEnabled]) {
[statusOnOff setString:@"On"];
} else {
[statusOnOff setString:@""];
}
[enableDisableItem setTitle:NSLocalizedString(@"disable_menu", nil)];
[statusItem setImage:statusImageOn];
} else {
if ([StartupHelper isStatusOnOffEnabled]) {
[statusOnOff setString:@"Off"];
} else {
[statusOnOff setString:@""];
}
[enableDisableItem setTitle:NSLocalizedString(@"enable_menu", nil)];
[statusItem setImage:statusImageOff];
}
// Refresh the title
[self refreshTitleString];
}
// Method to get the battery charging status
- (BOOL) isCharging {
CFTimeInterval timeInterval = IOPSGetTimeRemainingEstimate();
if (timeInterval == -2.0) {
return YES;
} else {
return NO;
}
}
// Update the CPU Temp & Fan speed
- (void) updateSensorValues {
// If monitoring is disabled, just exit
if (![StartupHelper isMonitoringEnabled]) {
return;
}
int fanSpeed = [SystemCommands readCurrentFanSpeed];
float cpuTemp = [SystemCommands readCurrentCpuTemp];
// Read the CPU temp
NSString *tempString = nil;
if (cpuTemp > 0) {
tempString = [NSString stringWithFormat:@"%.00f ºC", cpuTemp];
[txtCpuTemp setStringValue:tempString];
// Update temperature image
[self updateImageForTemperature:cpuTemp];
} else {
[txtCpuTemp setStringValue:@"N/A"];
}
// Read the fan speed
NSString *rpmData = nil;
if (fanSpeed > 0) {
rpmData = [NSString stringWithFormat:@"%d rpm", fanSpeed];
[txtCpuFan setStringValue:rpmData];
} else {
rpmData = @"N/A";
[txtCpuFan setStringValue:rpmData];
}
// Read the battery level and update info
double batteryLevel = [self currentBatteryLevel];
if (batteryLevel >= 0) {
// 12 levels graphically
int batteryLevelValue = ceil(batteryLevel * 0.12f);
[batteryLevelIndicator setIntegerValue:batteryLevelValue];
if ([self isCharging]) {
[lblBatteryInfo setStringValue:[NSString stringWithFormat:@"%d %% 🔌", (int) batteryLevel]];
} else {
[lblBatteryInfo setStringValue:[NSString stringWithFormat:@"%d %%", (int) batteryLevel]];
}
}
// Refresh the chart view if present
ChartDataEntry *fanEntry = [[ChartDataEntry alloc] init];
fanEntry.value = fanSpeed;
fanEntry.isTbEnabled = isTurboBoostEnabled;
ChartDataEntry *tempEntry = [[ChartDataEntry alloc] init];
tempEntry.value = cpuTemp;
tempEntry.isTbEnabled = isTurboBoostEnabled;
if (self.chartWindowController != nil) {
[self.chartWindowController addFanEntry:fanEntry withCurrentValue:rpmData];
[self.chartWindowController addTempEntry:tempEntry withCurrentValue:tempString];
}
// Get the CPU Load
if (sample_one.totalIdleTime == 0) {
sample(true);
} else {
sample(false);
struct cpusample delta;
delta.totalSystemTime = sample_two.totalSystemTime - sample_one.totalSystemTime;
delta.totalUserTime = sample_two.totalUserTime - sample_one.totalUserTime;
delta.totalIdleTime = sample_two.totalIdleTime - sample_one.totalIdleTime;
sample_one.totalSystemTime = sample_two.totalSystemTime;
sample_one.totalUserTime = sample_two.totalUserTime;
sample_one.totalIdleTime = sample_two.totalIdleTime;
uint64_t total = delta.totalSystemTime + delta.totalUserTime + delta.totalIdleTime;
double onePercent = total/100.0f;
double cpuIdleValue = (double)delta.totalIdleTime/(double)onePercent;
double cpuLoadValue = 100.0 - cpuIdleValue;
[txtCpuLoad setStringValue:[NSString stringWithFormat:@"CPU Load: %.01f%%", cpuLoadValue]];
}
// Refresh the title string
[self refreshTitleString];
}
// Take one cpu sample
void sample(bool isOne) {
kern_return_t kernelReturn;
mach_msg_type_number_t msgType;
host_cpu_load_info_data_t loadInfoData;
msgType = HOST_CPU_LOAD_INFO_COUNT;
kernelReturn = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (int *)&loadInfoData, &msgType);
if (kernelReturn != KERN_SUCCESS) {
printf("oops: %s\n", mach_error_string(kernelReturn));
return;
}
if (isOne) {
sample_one.totalSystemTime = loadInfoData.cpu_ticks[CPU_STATE_SYSTEM];
sample_one.totalUserTime = loadInfoData.cpu_ticks[CPU_STATE_USER] + loadInfoData.cpu_ticks[CPU_STATE_NICE];
sample_one.totalIdleTime = loadInfoData.cpu_ticks[CPU_STATE_IDLE];
} else {
sample_two.totalSystemTime = loadInfoData.cpu_ticks[CPU_STATE_SYSTEM];
sample_two.totalUserTime = loadInfoData.cpu_ticks[CPU_STATE_USER] + loadInfoData.cpu_ticks[CPU_STATE_NICE];
sample_two.totalIdleTime = loadInfoData.cpu_ticks[CPU_STATE_IDLE];
}
}
// Update language menu
- (void) updateLanguageMenu {
NSString *currentLocale = [StartupHelper currentLocale];
[spanishMenu setState:NSOffState];
[englishMenu setState:NSOffState];
[frenchMenu setState:NSOffState];
[chineseMenu setState:NSOffState];
[germanMenu setState:NSOffState];
[polishMenu setState:NSOffState];
[russianMenu setState:NSOffState];
[swedishMenu setState:NSOffState];
[czechMenu setState:NSOffState];
[italianMenu setState:NSOffState];
// TODO: Change this to a nsmutabledict
if ([currentLocale rangeOfString:@"es"].location != NSNotFound) {
[spanishMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"en"].location != NSNotFound) {
[englishMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"fr"].location != NSNotFound) {
[frenchMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"cn"].location != NSNotFound) {
[chineseMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"de"].location != NSNotFound) {
[germanMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"pl"].location != NSNotFound) {
[polishMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"ru"].location != NSNotFound) {
[russianMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"sv"].location != NSNotFound) {
[swedishMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"cs"].location != NSNotFound) {
[czechMenu setState:NSOnState];
} else if ([currentLocale rangeOfString:@"it"].location != NSNotFound) {
[italianMenu setState:NSOnState];
}
// Update language translations
[languageMenu setTitle:NSLocalizedString(@"language", nil)];
[spanishMenu setTitle:NSLocalizedString(@"language_es", nil)];
[englishMenu setTitle:NSLocalizedString(@"language_en", nil)];
[frenchMenu setTitle:NSLocalizedString(@"language_fr", nil)];
[chineseMenu setTitle:NSLocalizedString(@"language_zh", nil)];
[germanMenu setTitle:NSLocalizedString(@"language_de", nil)];
[polishMenu setTitle:NSLocalizedString(@"language_pl", nil)];
[russianMenu setTitle:NSLocalizedString(@"language_ru", nil)];
[swedishMenu setTitle:NSLocalizedString(@"language_sv", nil)];
[czechMenu setTitle:NSLocalizedString(@"language_cs", nil)];
[italianMenu setTitle:NSLocalizedString(@"language_it", nil)];
}
// Change language to
- (void) changeLanguageTo:(NSString *) value {
[StartupHelper storeCurrentLocale:value];
// AppleLanguages
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:value, nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// Language changed
- (IBAction) languageChanged:(id)sender {
// Asks for user confirmation
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert addButtonWithTitle:NSLocalizedString(@"btn_close", nil)];
[alert setMessageText:NSLocalizedString(@"language_change_confirmation", nil)];
[alert setInformativeText:NSLocalizedString(@"language_change_informative_text", nil)];
[alert setAlertStyle:NSWarningAlertStyle];
if ([alert runModal] == NSAlertFirstButtonReturn) {
// OK clicked... TODO: Change this to a nsmutabledict
if ([sender isEqualTo:spanishMenu]) {
[self changeLanguageTo:@"es"];
} else if ([sender isEqualTo:englishMenu]) {
[self changeLanguageTo:@"en"];
} else if ([sender isEqualTo:frenchMenu]) {
[self changeLanguageTo:@"fr"];
} else if ([sender isEqualTo:chineseMenu]) {
[self changeLanguageTo:@"zh"];
} else if ([sender isEqualTo:germanMenu]) {
[self changeLanguageTo:@"de"];
} else if ([sender isEqualTo:polishMenu]) {
[self changeLanguageTo:@"pl"];
} else if ([sender isEqualTo:russianMenu]) {
[self changeLanguageTo:@"ru"];
} else if ([sender isEqualTo:swedishMenu]) {
[self changeLanguageTo:@"sv"];
} else if ([sender isEqualTo:czechMenu]) {
[self changeLanguageTo:@"cs"];
} else if ([sender isEqualTo:italianMenu]) {
[self changeLanguageTo:@"it"];
}
[self updateLanguageMenu];
// Relaunch the app
[self relaunchAfterDelay:1];
}
}
// Method to switch between enabled and disables states
- (IBAction) enableTurboBoost:(id)sender {
BOOL isOn = ![SystemCommands isModuleLoaded];
if (isOn) {
[self disableTurboBoost];
} else {
[self enableTurboBoost];
}
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:1.0];
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:2.5];
// It seems that on some machines 2 seconds is not enough!
[self performSelector:@selector(updateStatus) withObject:nil afterDelay:5.0];
}
- (IBAction) exitItemEvent:(id)sender {
// Re-enable Turbo Boost before exit app
if ([SystemCommands isModuleLoaded]) {
[self enableTurboBoost];
}
[[NSApplication sharedApplication] terminate:self];
}
// Loads the kernel module disabling turbo boost feature
- (void) disableTurboBoost {
if (authorizationRef == NULL) {
OSStatus status = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&authorizationRef);
AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights rights = {1, &right};
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
if (status != errAuthorizationSuccess)
NSLog(@"Copy Rights Unsuccessful: %d", status);
}
[SystemCommands loadModuleWithAuthRef:authorizationRef];
}
// Unloads the kernel module enabling turbo boost feature
- (void) enableTurboBoost {
if (authorizationRef == NULL) {
OSStatus status = AuthorizationCreate(NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&authorizationRef);
AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights rights = {1, &right};
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
if (status != errAuthorizationSuccess)
NSLog(@"Copy Rights Unsuccessful: %d", status);
}
[SystemCommands unLoadModuleWithAuthRef:authorizationRef];
}
// Method to check for updates
- (IBAction) checkForUpdates:(id)sender {
// Download the update opening the CheckUpdates Window Controller
if (self.checkUpdatesWindow == nil) {
self.checkUpdatesWindow = [[CheckUpdatesWindowController alloc] initWithWindowNibName:@"CheckUpdatesWindowController"];
}
[self.checkUpdatesWindow.window center];
[self.checkUpdatesWindow showWindow:nil];
[self.checkUpdatesWindow checkVersion];
}
// Open about window
- (IBAction) about:(id)sender {
if (self.aboutWindow == nil) {
// Init the about window
self.aboutWindow = [[AboutWindowController alloc] initWithWindowNibName:@"AboutWindowController"];
}
[self.aboutWindow.window center];
[self.aboutWindow refreshDarkMode];
[self.aboutWindow showWindow:nil];
}
// Enables/disables the open at login status
- (IBAction) openAtLogin:(id)sender {
[StartupHelper setOpenAtLogin:![StartupHelper isOpenAtLogin]];
// Refresh open at login item status
[checkOpenAtLogin setState:[StartupHelper isOpenAtLogin]];
}
- (IBAction) disableAtLogin:(id)sender {
[StartupHelper setDisableAtLaunch:[checkDisableAtLaunch state]];
}
// Error
- (void) errorCheckingUpdate {
}
// Update available
- (void) updateAvailable {
// Download the update opening the CheckUpdates Window Controller
if (self.checkUpdatesWindow == nil) {
self.checkUpdatesWindow = [[CheckUpdatesWindowController alloc] initWithWindowNibName:@"CheckUpdatesWindowController"];
}
[self.checkUpdatesWindow.window center];
[self.checkUpdatesWindow showWindow:nil];
[self.checkUpdatesWindow updateAvailable];
}
// Update not available
- (void) updateNotAvailable {
}
// Method to refresh the status bar title string
- (void) refreshTitleString {
// Attributes for title string
NSFont *labelFont = [NSFont fontWithName:@"Helvetica" size:11];
// Final title string
NSMutableString *finalString = [[NSMutableString alloc] initWithString:@""];
[finalString appendString:statusOnOff];
// Refresh the title
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:finalString attributes:@{NSFontAttributeName : labelFont}];
[statusItem setAttributedTitle:attributedTitle];
}
// On / Off check click
- (IBAction) onOffClick:(id)sender {
[StartupHelper storeStatusOnOffEnabled:[checkOnOffText state] == NSOnState];
// Refresh the title string
[self updateStatus];
[self updateSensorValues];
}
- (void) terminate {
[[NSApplication sharedApplication] terminate:self];
}
// Relaunch after delay
- (void)relaunchAfterDelay:(float)seconds
{
NSTask *task = [[NSTask alloc] init];
NSMutableArray *args = [NSMutableArray array];
[args addObject:@"-c"];
[args addObject:[NSString stringWithFormat:@"sleep %f; open \"%@\"", seconds, [[NSBundle mainBundle] bundlePath]]];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:args];
[task launch];
[self terminate];
}
// Refresh time slider
- (IBAction) refreshTimeSliderChanged:(id)sender {
[checkMonitoring setTitle:[NSString stringWithFormat:NSLocalizedString(@"sliderRefreshTimeLabel", nil), sliderRefreshTime.integerValue]];
[self.refreshTimer invalidate];
NSRunLoop * rl = [NSRunLoop mainRunLoop];
// Timer to update the sensor readings (cpu & fan rpm) each 4 seconds
self.refreshTimer = [NSTimer timerWithTimeInterval:sliderRefreshTime.integerValue target:self selector:@selector(updateSensorValues) userInfo:nil repeats:YES];
[rl addTimer:self.refreshTimer forMode:NSRunLoopCommonModes];
[StartupHelper storeSensorRefreshTime:sliderRefreshTime.integerValue];
}
// Charts menu click
- (IBAction) chartsMenuClick:(id) sender {
// Bring window to front
[NSApp activateIgnoringOtherApps:YES];
if (self.chartWindowController == nil) {
self.chartWindowController = [[ChartWindowController alloc] initWithWindowNibName:@"ChartWindowController"];
[self.chartWindowController initData];
}
// Show!
[self.chartWindowController.window center];
[self.chartWindowController showWindow:nil];
self.chartWindowController.isOpen = YES;
}
// Get the current battery level
- (double) currentBatteryLevel
{
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
long numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) {
return -1.0f;
}
for (int i = 0 ; i < numOfSources ; i++)
{
pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
if (!pSource) {
return -1.0f;
}
psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));
int curCapacity = 0;
int maxCapacity = 0;
double percent;
// Gets the battery capacity
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
// Gets the max capacity
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
percent = ((double)curCapacity/(double)maxCapacity * 100.0f);
return percent;
}
return -1.0f;
}
// Method to configure the sensors view depending on battery available or not
- (void) configureSensorsView {
double batteryLevel = [self currentBatteryLevel];
if (batteryLevel < 0) {
// Hide battery sensor
NSRect f = sensorsView.frame;
f.size.height = 43;
sensorsView.frame = f;
[sensorsView setNeedsLayout:YES];
}
}
- (IBAction) checkMonitoringClick:(id) sender {
[StartupHelper storeMonitoringEnabled:[checkMonitoring state] == NSOnState];
[self updateMonitoringState];
}
// Update monitoring app state
- (void) updateMonitoringState {
BOOL isMonitoringEnabled = [StartupHelper isMonitoringEnabled];
if (isMonitoringEnabled) {
// Reenable timer
[self refreshTimeSliderChanged:nil];
// Refresh title string and status bar
[self updateSensorValues];
// Disable monitoring menu options
[temperatureImage setAlphaValue:1.0];
[cpuLoadImage setAlphaValue:1.0];
[cpuFanImage setAlphaValue:1.0];
[batteryImage setAlphaValue:1.0];
} else {
// Disable monitoring menu options
[temperatureImage setAlphaValue:0.2];
[cpuLoadImage setAlphaValue:0.2];
[cpuFanImage setAlphaValue:0.2];
[batteryImage setAlphaValue:0.2];
[txtCpuFan setStringValue:@""];
[txtCpuLoad setStringValue:@""];
[txtCpuTemp setStringValue:@""];
// Set battery level to 0
[batteryLevelIndicator setIntegerValue:0];
[lblBatteryInfo setStringValue:@""];
[self updateStatus];
// Invalidate timer
[self.refreshTimer invalidate];
}
// Enable/Disable charts
[chartsMenuItem setEnabled:isMonitoringEnabled];
// Deshabilitar / ocultar las opciones de monitorización
[sliderRefreshTime setEnabled:isMonitoringEnabled];
}
@end