forked from epalzeolithe/DisableMonitor-3.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisableMonitorAppDelegate.m
executable file
·899 lines (792 loc) · 31.9 KB
/
DisableMonitorAppDelegate.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
/**
* DisableMonitor, Disable Monitors on Mac
*
* Copyright (C) 2014 Tobias Salzmann
*
* DisableMonitor 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.
*
* DisableMonitor 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 DisableMonitor. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Tobias Salzmann
*/
#import "DisableMonitorAppDelegate.h"
#import <IOKit/i2c/IOI2CInterface.h>
#import <IOKit/graphics/IOGraphicsLib.h>
#import "DisplayData.h"
#import "ResolutionDataSource.h"
#import "ResolutionDataItem.h"
#import "OnlyIntegerValueFormatter.h"
#import "DisplayIDAndNameCondition.h"
#import "MonitorDataSource.h"
#import "NSImage+NegativeImage.h"
#include <stdlib.h>
@implementation DisableMonitorAppDelegate
@synthesize pref_window;
@synthesize pref_lblHeader;
@synthesize pref_btnClose;
@synthesize pref_lstResolutions;
@synthesize pref_chkDisableMonitor;
@synthesize pref_chkEnableMonitor;
@synthesize pref_lstDisableMonitors;
@synthesize pref_lstEnableMonitors;
@synthesize pref_tabView;
@synthesize window_display;
CFStringRef const kDisplayBrightness = CFSTR(kIODisplayBrightnessKey);
-(void)awakeFromNib{
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
[statusMenu setDelegate:self];
[statusItem setMenu:statusMenu];
[statusItem setLength:24.0];
NSImage *statusBarImage = [[NSApp applicationIconImage] copy];
[statusBarImage setSize:NSMakeSize(20.0, 20.0)];
statusItem.image = statusBarImage;
[self setupPreferencesWindow];
[statusItem setHighlightMode:YES];
CGDisplayRegisterReconfigurationCallback(displayReconfigurationCallBack, NULL);
}
#pragma mark Helper functions
- (BOOL)isInDarkMode
{
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
id style = [dict objectForKey:@"AppleInterfaceStyle"];
return ( style && [style isKindOfClass:[NSString class]] && NSOrderedSame == [style caseInsensitiveCompare:@"dark"] );
}
+(void)ShowError:(NSString*)error
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(ShowError:) withObject:error waitUntilDone:NO];
return;
}
NSAlert *alert = [[NSAlert alloc] init];
[alert setInformativeText:error];
[alert addButtonWithTitle:NSLocalizedString(@"ALERT_OK", NULL)];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert setMessageText:NSLocalizedString(@"ALERT_ERROR", NULL)];
[alert runModal];
[alert release];
}
#define ShowError(...) [DisableMonitorAppDelegate ShowError:[NSString stringWithFormat:__VA_ARGS__]];
/**
* move all windows from one display to another
*
* @param display source display
* @param todisplay destination display
*/
+(void)moveAllWindows:(CGDirectDisplayID) display to:(CGDirectDisplayID*)todisplay
{
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CGRect bounds = CGDisplayBounds(display);
CGRect dstbounds = CGDisplayBounds(todisplay);
for (NSDictionary *windowItem in ((NSArray *)windowList))
{
NSNumber *windowLayer = (NSNumber*)[windowItem objectForKey:(id)kCGWindowLayer];
if ([windowLayer intValue] == 0)
{
CGRect windowBounds;
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[windowItem objectForKey:(id)kCGWindowBounds], &windowBounds);
if (CGRectContainsPoint(bounds, windowBounds.origin))
{
NSNumber *windowNumber = (NSNumber*)[windowItem objectForKey:(id)kCGWindowNumber];
NSNumber *windowOwnerPid = (NSNumber*)[windowItem objectForKey:(id)kCGWindowOwnerPID];
AXUIElementRef appRef = AXUIElementCreateApplication([windowOwnerPid longValue]);
if (appRef != nil) {
CFArrayRef _windows;
if (AXUIElementCopyAttributeValues(appRef, kAXWindowsAttribute, 0, 100, &_windows) == kAXErrorSuccess)
{
for (int i = 0, len = CFArrayGetCount(_windows); i < len; i++)
{
AXUIElementRef _windowItem = CFArrayGetValueAtIndex(_windows,i);
CGWindowID windowID;
if (_AXUIElementGetWindow(_windowItem, &windowID) == kAXErrorSuccess)
{
if (windowID == windowNumber.longValue)
{
NSPoint tmpPos;
tmpPos.x = dstbounds.origin.x;
tmpPos.y = dstbounds.origin.y;
CFTypeRef _position = (CFTypeRef)(AXValueCreate(kAXValueCGPointType, (const void *)&tmpPos));
if(AXUIElementSetAttributeValue(_windowItem,kAXPositionAttribute,(CFTypeRef*)_position) != kAXErrorSuccess){
NSString* windowName = (NSString*)[windowItem objectForKey:(id)kCGWindowName];
NSLog(@"Could not move window %ld (%@) of %ld", windowNumber.longValue, windowName, windowOwnerPid.longValue);
}
}
}
}
}
CFRelease(appRef);
}
}
}
}
CFRelease(windowList);
}
/**
* get the currentstate of a display
*
* @param displayID display to check
*
* @return YES if the display is enabled
*/
+(bool)isDisplayEnabled:(CGDirectDisplayID)displayID
{
if (!CGDisplayIsOnline(displayID))
return NO;
// if the display is not active, it could be in a mirrorset
if (CGDisplayIsActive(displayID) == NO)
{
if (CGDisplayIsInMirrorSet(displayID))
return YES;
else
return NO;
}
return YES;
}
/**
* show warning if user is going to disable last monitor
*
* @return true if the user choses to abort
*/
+(bool) showErrorWarningIfLastMonitor:(CGDirectDisplayID)displayID
{
if ([DisableMonitorAppDelegate isDisplayEnabled:displayID] && displayID == CGDisplayPrimaryDisplay(displayID))
{
CGDirectDisplayID displays[0x10];
CGDisplayCount nDisplays = 0;
CGError err = CGGetActiveDisplayList(0x10, displays, &nDisplays);
if (err == 0 && nDisplays - 1 == 0)
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setInformativeText:NSLocalizedString(@"ALERT_LAST_MONITOR", NULL)];
[alert addButtonWithTitle:NSLocalizedString(@"ALERT_OK", NULL)];
[alert addButtonWithTitle:NSLocalizedString(@"ALERT_CANCEL", NULL)];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert setMessageText:NSLocalizedString(@"ALERT_WARNING", NULL)];
if ([alert runModal] != NSAlertFirstButtonReturn)
{
[alert release];
return true;
}
[alert release];
}
}
return false;
}
/**
* toggle a monitor state from disabled to enabled or reverse.
*
* @param displayID the display id of the monitor
* @param enabled should it be enabled or disabled?
*/
+(void)toggleMonitor:(CGDirectDisplayID)displayID enabled:(Boolean) enabled
{
CGError err;
CGDisplayConfigRef config;
@try {
if (enabled == false)
{
CGDirectDisplayID displays[0x10];
CGDisplayCount nDisplays = 0;
CGDisplayErr err = CGSGetDisplayList(0x10, displays, &nDisplays);
if (err == 0 && nDisplays > 0)
{
for (int i = 0; i < nDisplays; i++)
{
if (displays[i] == displayID)
continue;
if (!CGDisplayIsOnline(displays[i]))
continue;
if (!CGDisplayIsActive(displays[i]))
continue;
@try {
[self moveAllWindows:displayID to:displays[i]];
}
@catch (NSException *e)
{
NSLog(@"Problems in moving windows");
}
break;
}
}
}
usleep(1000*1000); // sleep 1000 ms
err = CGBeginDisplayConfiguration (&config);
if (err != 0)
{
ShowError(@"Error in CGBeginDisplayConfiguration: %d",err);
return;
}
bool mirror = CGDisplayIsInMirrorSet(displayID);
if (enabled == false && mirror)
{
CGConfigureDisplayMirrorOfDisplay(config, displayID, kCGNullDirectDisplay);
}
err = CGSConfigureDisplayEnabled(config, displayID, enabled);
if (err != 0)
{
ShowError(@"Error in CGSConfigureDisplayEnabled: %d", err);
return;
}
if (!mirror)
{
CGConfigureDisplayFadeEffect (config, 0, 0, 0, 0, 0);
io_registry_entry_t entry = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/IOResources/IODisplayWrangler");
if (entry)
{
// disabled blink method to work in catalina
/*
IORegistryEntrySetCFProperty(entry, CFSTR("IORequestIdle"), kCFBooleanTrue);
usleep(100*1000); // sleep 100 ms
IORegistryEntrySetCFProperty(entry, CFSTR("IORequestIdle"), kCFBooleanFalse);
IOObjectRelease(entry);
*/
}
}
err = CGCompleteDisplayConfiguration(config, kCGConfigurePermanently);
if (err != 0)
{
ShowError(@"Error in CGCompleteDisplayConfiguration: %d", err);
}
}
@catch (NSException *exception) {
NSLog(@"Exception:" );
NSLog(@"Name: %@", exception.name);
NSLog(@"Reason: %@", exception.reason );
}
}
-(void)setMonitorRes:(CGDirectDisplayID) display mode:(CGSDisplayMode) mode
{
CGError err;
CGDisplayConfigRef config;
err = CGBeginDisplayConfiguration (&config);
if (err != 0)
{
ShowError(@"Error in CGBeginDisplayConfiguration: %d\n", err);
return;
}
err = CGSConfigureDisplayMode(config, display, mode.modeNumber);
if (err != 0)
{
ShowError(@"Error in CGConfigureDisplayWithDisplayMode: %d\n", err);
return;
}
err = CGCompleteDisplayConfiguration(config, kCGConfigurePermanently);
if (err != 0)
{
ShowError(@"Error in CGCompleteDisplayConfiguration: %d\n", err);
return;
}
}
#pragma mark Menu actions
/**
* user clicked on enable / disable monitor
*
* @param sender menuItem
*/
-(void)monitorClicked:(id) sender
{
NSMenuItem * item = (NSMenuItem*)sender;
CGDirectDisplayID displayId = [(DisplayData*)[item representedObject] display];
if ([DisableMonitorAppDelegate showErrorWarningIfLastMonitor:displayId])
return;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[DisableMonitorAppDelegate toggleMonitor:displayId enabled:![DisableMonitorAppDelegate isDisplayEnabled:displayId]];
});
}
/**
* user clicked on a resolution that should be changed now
*
* @param sender menuItem
*/
-(void)monitorResolutionClicked:(id) sender
{
NSMenuItem *item = (NSMenuItem*)sender;
DisplayData *data = [item representedObject];
if (CGDisplayIsActive([data display]))
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self setMonitorRes:[data display] mode:[data mode]];
});
}
else
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setInformativeText:NSLocalizedString(@"ALERT_MONITOR_NOT_ACTIVE", NULL)];
[alert addButtonWithTitle:NSLocalizedString(@"ALERT_OK", NULL)];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert setMessageText:NSLocalizedString(@"ALERT_WARNING", NULL)];
[alert runModal];
[alert release];
}
}
/**
* user clicked on detect monitors
*
* @param sender menuItem
*/
-(void)detectMonitorsClicked:(id) sender
{
CGDirectDisplayID displays[0x10];
CGDisplayCount dspCount = 0;
CGDisplayErr err = CGSGetDisplayList(0x10, displays, &dspCount);
if (err == 0)
{
for(int i = 0; i < dspCount; i++)
{
io_service_t service = IOServicePortFromCGDisplayID(displays[i]);
if (service)
{
IOServiceRequestProbe(service, kIOFBUserRequestProbe);
}
}
}
}
#define MAX_DISPLAYS 10
#define SECONDARY_DISPLAY_COUNT 9
-(void)toggleMirror:(id) sender
{
CGDisplayCount numberOfTotalDspys = MAX_DISPLAYS;
CGDirectDisplayID activeDspys[MAX_DISPLAYS];
CGDirectDisplayID onlineDspys[MAX_DISPLAYS];
CGDirectDisplayID secondaryDspys[SECONDARY_DISPLAY_COUNT];
CGDisplayCount numberOfActiveDspys;
CGDisplayCount numberOfOnlineDspys;
CGDisplayErr activeError = CGGetActiveDisplayList(numberOfTotalDspys,activeDspys,&numberOfActiveDspys);
if (activeError!=0) {printf("Error in obtaining active diplay list: %d\n",activeError);return ;}
CGDisplayErr onlineError = CGGetOnlineDisplayList (numberOfTotalDspys,onlineDspys,&numberOfOnlineDspys);
if (onlineError!=0) {printf("Error in obtaining online diplay list: %d\n",onlineError); return ;}
if (numberOfOnlineDspys<2) {printf("No secondary display detected.\n");return;}
bool displaysMirrored = CGDisplayIsInMirrorSet(CGMainDisplayID());
int secondaryDisplayIndex = 0;
for (int displayIndex = 0; displayIndex<numberOfOnlineDspys; displayIndex++) {
if (onlineDspys[displayIndex] != CGMainDisplayID()) {
secondaryDspys[secondaryDisplayIndex] = onlineDspys[displayIndex];
secondaryDisplayIndex++;
}
}
CGDisplayConfigRef configRef;
CGError err = CGBeginDisplayConfiguration (&configRef);
if (displaysMirrored) {
err = kCGErrorSuccess;
for (int i = 0; i<numberOfOnlineDspys - 1; i++) {
err = err ?: CGConfigureDisplayMirrorOfDisplay(configRef, secondaryDspys[i], kCGNullDirectDisplay);
}
} else {
err = kCGErrorSuccess;
for (int i = 0; i<numberOfOnlineDspys - 1; i++) {
err = err ?: CGConfigureDisplayMirrorOfDisplay(configRef, secondaryDspys[i], CGMainDisplayID());
}
}
//if (err != 0) printf("Error configuring displays: %d\n",err);
// Apply the changes
err = CGCompleteDisplayConfiguration (configRef,kCGConfigurePermanently);
//if (err != 0) printf("Error applying configuration: %d\n",err);
//return err;
}
/**
* user clicked on turn off monitors
*
* @param sender menuItem
*/
-(void)turnOffMonitorsClicked:(id) sender
{
io_registry_entry_t entry = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/IOResources/IODisplayWrangler");
if (entry)
{
IORegistryEntrySetCFProperty(entry, CFSTR("IORequestIdle"), kCFBooleanTrue);
IOObjectRelease(entry);
}
else
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setInformativeText: NSLocalizedString(@"ERROR_TURNOFF", NULL)];
[alert addButtonWithTitle:NSLocalizedString(@"ALERT_OK", NULL)];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert setMessageText:NSLocalizedString(@"ALERT_ERROR",NULL)];
[alert runModal];
[alert release];
}
}
/**
* user clicked on quit
*
* @param sender menuItem
*/
-(void)quitClicked:(id) sender {
[NSApp terminate:nil];
}
/**
* user clicked on manage
*
* @param sender menuItem
*/
-(void)manageClicked:(id) sender
{
NSMenuItem * item = (NSMenuItem*)sender;
CGDirectDisplayID display = [(DisplayData*)[item representedObject] display];
if (CGDisplayIsOnline(display))
{
[self showPreferencesWindow:display name:[[item parentItem] title]];
}
}
# pragma mark NSMenuDelegates
/**
* NSMenuDelegate: menuNeedsUpdate
*
* @param menu menu
*/
- (void)menuNeedsUpdate:(NSMenu *)menu
{
[self releaseMenu:menu];
NSMutableArray *dict = [MonitorDataSource GetSortedDisplays];
if (dict == nil)
{
NSMenuItem *noDisplays = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"MENU_NO_MONITOS",NULL) action:nil keyEquivalent:@""];
[statusMenu addItem:noDisplays];
[noDisplays release];
}
else
{
for (DisplayIDAndName* idAndName in dict)
{
CGDirectDisplayID displayId = [idAndName id];
NSMenuItem *displayItem = [[NSMenuItem alloc] initWithTitle: [idAndName name] action:nil keyEquivalent:@""];
BOOL bActive = CGDisplayIsActive(displayId);
BOOL bMirror = NO;
if (bActive == NO)
{
bMirror = CGDisplayIsInMirrorSet(displayId);
if (bMirror)
{
bActive = YES;
}
}
if (bActive)
[displayItem setState:NSOnState];
else
[displayItem setState:NSOffState];
NSMenu *subMenu = [[NSMenu alloc] init];
NSMenuItem *subItem;
ResolutionDataSource *dataSource = [[ResolutionDataSource alloc] initWithDisplay:displayId];
int numberOfDisplayModes = [dataSource outlineView:nil numberOfChildrenOfItem:nil];
if (bActive && numberOfDisplayModes > 0 && bMirror == NO)
{
[subMenu addItem:[[NSMenuItem separatorItem] copy]];
int currentDisplayModeNumber;
CGSGetCurrentDisplayMode(displayId, ¤tDisplayModeNumber);
NSTableColumn *tableColumn = [[NSTableColumn alloc] init];
[tableColumn setIdentifier:@"Name"];
for (int j = 0; j < numberOfDisplayModes; j++)
{
ResolutionDataItem *dataItem = [dataSource outlineView:nil child:j ofItem:nil];
if ([dataItem visible])
{
subItem = [[NSMenuItem alloc] initWithTitle: @"" action:@selector(monitorResolutionClicked:) keyEquivalent:@""];
DisplayData *data = [[DisplayData alloc] init];
[data setMode:[dataItem mode]];
[data setDisplay:displayId];
[subItem setRepresentedObject: data];
if (currentDisplayModeNumber == dataItem.mode.modeNumber)
[subItem setState:NSOnState];
else
[subItem setState:NSOffState];
[subItem setAttributedTitle:[dataSource outlineView:nil objectValueForTableColumn:tableColumn byItem:dataItem]];
[subMenu addItem:subItem];
}
}
[tableColumn release];
}
[dataSource release];
if (bActive)
{
subItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"MENU_DISABLE",NULL) action:@selector(monitorClicked:) keyEquivalent:@""];
DisplayData *data = [[DisplayData alloc] init];
[data setDisplay:displayId];
[subItem setRepresentedObject: data];
[subMenu insertItem:subItem atIndex:0];
} else {
subItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"MENU_ENABLE",NULL) action:@selector(monitorClicked:) keyEquivalent:@""];
DisplayData *data = [[DisplayData alloc] init];
[data setDisplay:displayId];
[subItem setRepresentedObject: data];
[subMenu insertItem:subItem atIndex:0];
}
// disable buggy manage menu
/*
[subMenu insertItem:[[NSMenuItem separatorItem] copy] atIndex:[[subMenu itemArray] count]];
subItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"MENU_MANAGE",NULL) action:@selector(manageClicked:) keyEquivalent:@""];
DisplayData *data = [[DisplayData alloc] init];
[data setDisplay:displayId];
[subItem setRepresentedObject: data];
[subMenu insertItem:subItem atIndex:[[subMenu itemArray] count]];
*/
[displayItem setSubmenu:subMenu];
[statusMenu addItem:displayItem];
[idAndName release];
}
[dict release];
}
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"MENU_DETECT",NULL) action:@selector(detectMonitorsClicked:) keyEquivalent:@""];
[statusMenu addItem:menuItem];
menuItem = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"MENU_MIRROR",NULL) action:@selector(toggleMirror:) keyEquivalent:@""];
[statusMenu addItem:menuItem];
[statusMenu addItem:[[NSMenuItem separatorItem] copy]];
menuItem = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"MENU_ABOUT",NULL) action:@selector(showAboutWindow) keyEquivalent:@""];
[statusMenu addItem:menuItem];
menuItemQuit = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"MENU_QUIT",NULL) action:@selector(quitClicked:) keyEquivalent:@""];
[statusMenu addItem:menuItemQuit];
}
#pragma mark Menu Helpers
/**
* relase the current menu structure to build a new one.
*
* @param menu menu that should be released.
*/
- (void) releaseMenu:(NSMenu*)menu
{
NSArray *items = [menu itemArray];
if (items != NULL)
{
for (int i = [items count] - 1; i >= 0; --i)
{
NSMenuItem *item = [items objectAtIndex:i];
if ([item submenu] != NULL)
{
[self releaseMenu:[item submenu]];
[[item submenu] release];
}
id representedObject = [item representedObject];
if (representedObject != NULL)
{
[representedObject release];
}
[item release];
}
[menu removeAllItems];
}
}
#pragma mark rulset
/**
* check if there is a condition that matches a rule
*
* @param displayThatChanged display that changed
* @param isAdded was it added or removed?
* @param display displayID of the display which rules should be checked
* @param dict dict to the settings of the display
* @param listToUse which list should be used (in settings)
*
* @return if there is a rule that matches
*/
bool matchesConditions(CGDirectDisplayID displayThatChanged, bool isAdded, CGDirectDisplayID display, NSMutableDictionary *dict, NSString *listToUse)
{
NSMutableArray *items = [dict objectForKey:listToUse];
for (int i = [items count] - 1; i>= 0; --i)
{
DisplayIDAndNameCondition *store_item =[NSKeyedUnarchiver unarchiveObjectWithData:[items objectAtIndex:i]];
bool displayOnline;
if ([store_item id] == displayThatChanged)
displayOnline = isAdded;
else
displayOnline = CGDisplayIsOnline([store_item id]) && CGDisplayIsActive([store_item id]);
if (displayOnline && [store_item disabled])
return false;
if (!displayOnline && [store_item enabled])
return false;
}
return true;
}
/**
* trigger the rule that should be run if the specified display gets attached or removed.
*
* @param displayThatChanged displayID of the display that gets removed
* @param isAdded was it added or removed?
*/
void triggerRules(CGDirectDisplayID displayThatChanged, bool isAdded)
{
CGDirectDisplayID displays[0x10];
CGDisplayCount nDisplays = 0;
CGDisplayErr err = CGSGetDisplayList(0x10, displays, &nDisplays);
if (err == 0 && nDisplays > 0)
{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
for (int i = 0; i < nDisplays; i++)
{
if (CGDisplayIsOnline(displays[i]))
{
NSMutableDictionary *dict = [ResolutionDataSource getDictForDisplay:userDefaults display:displays[i]];
if ([dict count] == 0)
{
continue;
}
if ([[dict objectForKey:@"enable_rules"] boolValue] == true)
{
if (matchesConditions(displayThatChanged, isAdded, displays[i], dict, @"enable_ruleset"))
{
if (CGDisplayIsActive(displays[i]))
continue;
NSLog(@"ENABLE %u", displays[i]);
if (![DisableMonitorAppDelegate showErrorWarningIfLastMonitor:displays[i]])
{
CGDirectDisplayID displayID = displays[i];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[DisableMonitorAppDelegate toggleMonitor:displayID enabled:YES];
});
}
continue;
}
}
if ([[dict objectForKey:@"disable_rules"] boolValue] == true)
{
if (matchesConditions(displayThatChanged, isAdded, displays[i], dict, @"disable_ruleset"))
{
if (!CGDisplayIsActive(displays[i]))
continue;
NSLog(@"DISABLE %u", displays[i]);
if (![DisableMonitorAppDelegate showErrorWarningIfLastMonitor:displays[i]])
{
CGDirectDisplayID displayID = displays[i];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[DisableMonitorAppDelegate toggleMonitor:displayID enabled:NO];
});
}
continue;
}
}
}
}
}
}
/**
* called when a display gets attached or removed
*
* @param display displayID of the display
* @param flags flags
* @param userInfo userInfo
*/
void displayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *userInfo)
{
if ((flags & kCGDisplayAddFlag) == kCGDisplayAddFlag) {
triggerRules(display, true);
}
else if ((flags & kCGDisplayRemoveFlag) == kCGDisplayRemoveFlag) {
triggerRules(display, false);
}
}
#pragma mark General Window stuff
/**
* NSWindowDelegate: will be called when about or preferences window will be closed
*
* @param notification notification
*/
- (void)windowWillClose:(NSNotification *)notification {
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, 2 /*kProcessTransformToBackgroundApplication*/);
if ([notification object] == pref_window)
{
[[pref_lstResolutions dataSource] release];
[[pref_lstEnableMonitors dataSource] release];
[[pref_lstDisableMonitors dataSource] release];
}
}
#pragma mark About Window
/**
* show the about window
*/
-(void)showAboutWindow{
[NSApp orderFrontStandardAboutPanel:self];
}
#pragma mark Preferences Window
/**
* initializes the preferences window
*/
-(void)setupPreferencesWindow
{
[pref_window setLevel:NSFloatingWindowLevel];
[pref_window setDelegate:self];
[[pref_tabView tabViewItemAtIndex:0] setLabel:NSLocalizedString(@"PREF_TAB_RESOLUTIONS", NULL)];
[[pref_tabView tabViewItemAtIndex:1] setLabel:NSLocalizedString(@"PREF_TAB_RULES", NULL)];
// Rules are beta for now
{
NSView *view = [[pref_tabView tabViewItemAtIndex:1] view];
[view removeFromSuperview];
[[[pref_tabView tabViewItemAtIndex:0] view] addSubview:view];
[view setHidden:YES];
[pref_tabView removeTabViewItem:[pref_tabView tabViewItemAtIndex:1]];
}
[pref_btnClose setTitle:NSLocalizedString(@"PREF_CLOSE", NULL)];
[pref_btnClose sizeToFit];
[pref_btnClose setFrameOrigin: NSMakePoint(
[pref_window frame].size.width -
[pref_btnClose frame].size.width
- 13
, [pref_btnClose frame].origin.y)];
[pref_lblHeader setStringValue:NSLocalizedString(@"PREF_LABEL", NULL)];
[pref_chkEnableMonitor setTitle:NSLocalizedString(@"PREF_ENABLE_MONITOR", NULL)];
[pref_chkDisableMonitor setTitle:NSLocalizedString(@"PREF_DISABLE_MONITOR", NULL)];
}
/**
* shows the preferences window for a specific display
*
* @param displayID the displayID to be used
* @param name the name of the display
*/
-(void)showPreferencesWindow:(CGDirectDisplayID)displayID name:(NSString*)name
{
window_display = displayID;
[pref_window setTitle: name];
// Load Settings
[pref_lstResolutions setDataSource:[[ResolutionDataSource alloc] initWithDisplay:displayID]];
//[pref_lstResolutions setDelegate:self];
[pref_lstEnableMonitors setDataSource:[[MonitorDataSource alloc] initWithDisplay:displayID useEnableList:true]];
[pref_lstDisableMonitors setDataSource:[[MonitorDataSource alloc] initWithDisplay:displayID useEnableList:false]];
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [ResolutionDataSource getDictForDisplay:userDefaults display:displayID];
if ([[dict objectForKey:@"enable_rules"] boolValue] == true)
[pref_chkEnableMonitor setState:NSOnState];
else
[pref_chkEnableMonitor setState:NSOffState];
if ([[dict objectForKey:@"disable_rules"] boolValue] == true)
[pref_chkDisableMonitor setState:NSOnState];
else
[pref_chkDisableMonitor setState:NSOffState];
[self prefEnableDisableBoxChanged:nil];
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
[pref_window makeKeyAndOrderFront:self];
[pref_window makeFirstResponder: nil];
}
/**
* will be executed if the user enables / disables the ruleset
*
* @param sender checkbox
*/
- (IBAction)prefEnableDisableBoxChanged:(id)sender
{
[pref_lstEnableMonitors setEnabled: ([pref_chkEnableMonitor state] == NSOnState)];
[pref_lstDisableMonitors setEnabled: ([pref_chkDisableMonitor state] == NSOnState)];
if (sender != nil)
{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [ResolutionDataSource getDictForDisplay:userDefaults display:window_display];
[dict setObject:[NSNumber numberWithBool:([pref_chkEnableMonitor state] == NSOnState)] forKey:@"enable_rules"];
[dict setObject:[NSNumber numberWithBool:([pref_chkDisableMonitor state] == NSOnState)] forKey:@"disable_rules"];
[userDefaults setObject:dict forKey:[NSString stringWithFormat:@"%u", window_display]];
[userDefaults synchronize];
}
}
/**
* closes the preferences window
*
* @param sender sender
*/
- (IBAction)closePrefWindow:(id)sender
{
[pref_window close];
}
@end