-
Notifications
You must be signed in to change notification settings - Fork 4
/
IsoController.m
1162 lines (949 loc) · 31.9 KB
/
IsoController.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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// IsoController.m
// Isolator
//
// Created by Ben Willmore on 08/02/2007.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//
#import "Carbon/Carbon.h"
#import "HIToolbox/MacApplication.h"
#import "IsoController.h"
#ifndef NSAppKitVersionNumber10_4
#define NSAppKitVersionNumber10_4 824
#endif
#ifndef NSAppKitVersionNumber10_5
#define NSAppKitVersionNumber10_5 949
#endif
#ifndef NSAppKitVersionNumber10_6
#define NSAppKitVersionNumber10_6 1038
#endif
@implementation IsoController
static int kAppSwitched = 1;
static int kEnteredIsolateMode = 2;
//static kIsolatorModeChanged = 3;
static int kCentury = 100;
static NSString* kBetaFeedURL = @"http://willmore.eu/software/isolator/allversions.xml";
static NSString* kReleaseFeedURL = @"http://willmore.eu/software/isolator/releases.xml";
static IsoController *me;
pascal OSStatus appSwitched (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData)
// handle change in frontmost app
{
[me isolate:kAppSwitched];
return noErr;
}
OSStatus hotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData)
// handle hotkey press
{
EventHotKeyID hkCom;
GetEventParameter(theEvent,kEventParamDirectObject,typeEventHotKeyID,NULL,sizeof(hkCom),NULL,&hkCom);
int l = hkCom.id;
switch (l) {
case 1: // isolator hotkey
[me toggle:NO];
break;
case 2: // prefs win hotkey
[me openPrefs];
break;
case 3: // alternate hotkey
[me toggle:YES];
break;
}
return noErr;
}
-(id) init
{
[super init];
if (getenv("NSZombieEnabled") || getenv("NSAutoreleaseFreedObjectCheckEnabled")) {
NSLog(@"NSZombieEnabled/NSAutoreleaseFreedObjectCheckEnabled enabled!");
}
savedFrames = nil;
lastAppActivated = nil;
//sparkleUpdater = [[SUUpdater alloc] init];
// register for Carbon event on app switching
me = self;
EventTypeSpec eventType;
eventType.eventClass = kEventClassApplication;
eventType.eventKind = kEventAppFrontSwitched;
EventHandlerUPP handlerUPP = NewEventHandlerUPP(appSwitched);
InstallApplicationEventHandler (handlerUPP, 1, &eventType, self, NULL);
DisposeEventHandlerUPP(appSwitched);
// read preferences
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:@"StartupMode"])
[defaults setInteger:1 forKey:@"StartupMode"];
flipMode = NO;
suspended = NO;
if ([defaults integerForKey:@"StartupMode"]==0)
active = YES;
else
active = NO;
if (![defaults objectForKey:@"HideBackgroundApps"])
[defaults setInteger:NO forKey:@"HideBackgroundApps"];
if (![defaults objectForKey:@"SuspendWhenFinderIsActive"])
[defaults setBool:NO forKey:@"SuspendWhenFinderIsActive"];
if (![defaults objectForKey:@"HideOnMainScreenOnly"]) {
[defaults setBool:NO forKey:@"HideOnMainScreenOnly"];
}
else {
// there IS an object for this key. We can reasonably assume that the user has used Isolator before
// we will make sure the user isn't annoyed by the infoBox
// (even though the user hasn't actually seen the box because it wasn't introduced until 3.40beta)
[defaults setBool:YES forKey:@"InfoBoxHasBeenShown"];
}
if ((floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4) && ![defaults boolForKey:@"TigerTest"]) {
[defaults setBool:YES forKey:@"RunningOnLeopard"];
}
else {
[defaults setBool:NO forKey:@"RunningOnLeopard"];
}
if ((floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) && ![defaults boolForKey:@"TigerTest"]) {
[defaults setBool:YES forKey:@"RunningOnSnowLeopard"];
}
else {
[defaults setBool:NO forKey:@"RunningOnSnowLeopard"];
}
[self checkIfDisplaysAreHardwareAccelerated];
if (![defaults objectForKey:@"HideDock"])
[defaults setBool:NO forKey:@"HideDock"];
if ([defaults integerForKey:@"Hotkey"]==0) {
[defaults setInteger:34 forKey:@"Hotkey"]; // cmd-shift-i
[defaults setInteger:NSCommandKeyMask+NSShiftKeyMask forKey:@"HotkeyFlags"];
}
if ([defaults integerForKey:@"PrefsHotkey"]==0) {
[defaults setInteger:34 forKey:@"PrefsHotkey"]; // cmd-shift-option-i
[defaults setInteger:NSCommandKeyMask+NSShiftKeyMask+NSAlternateKeyMask forKey:@"PrefsHotkeyFlags"];
}
// don't set alternate hotkey by default, but it is used if the user sets it
if (![defaults objectForKey:@"ShowMenubarIcon"])
[defaults setBool:YES forKey:@"ShowMenubarIcon"];
if (![defaults objectForKey:@"MouseClickEffect"])
[defaults setInteger:1 forKey:@"MouseClickEffect"];
if (![defaults objectForKey:@"NumberOfTimesUsed"])
[defaults setInteger:0 forKey:@"NumberOfTimesUsed"];
if (![defaults objectForKey:@"SUScheduledCheckInterval"])
[defaults setInteger:86400 forKey:@"SUScheduledCheckInterval"];
if ( ![defaults objectForKey:@"MostRecentVersionUsed"] || ([defaults floatForKey:@"MostRecentVersionUsed"]<3.38) )
[self migratePrefsTo338];
[defaults setFloat:[[[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleVersion"] floatValue] forKey:@"MostRecentVersionUsed"];
// set up hotkey for prefs window
EventHotKeyID gMyHotKeyID;
eventType.eventClass=kEventClassKeyboard;
eventType.eventKind=kEventHotKeyPressed;
gMyHotKeyID.signature='htk2';
gMyHotKeyID.id=2;
int keyCode = 0;
unsigned int keyFlags = 0;
if ([defaults objectForKey:@"PrefsHotkey"] && [defaults objectForKey:@"PrefsHotkeyFlags"]) {
int keyCode = [defaults integerForKey:@"PrefsHotkey"];
unsigned int keyFlags = SRCocoaToCarbonFlags([defaults integerForKey:@"PrefsHotkeyFlags"]);
RegisterEventHotKey(keyCode, keyFlags, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}
if ([defaults objectForKey:@"AlternateHotkey"] && [defaults objectForKey:@"AlternateHotkeyFlags"]) {
keyCode = [defaults integerForKey:@"AlternateHotkey"];
keyFlags = SRCocoaToCarbonFlags([defaults integerForKey:@"AlternateHotkeyFlags"]);
gMyHotKeyID.signature='htk3';
gMyHotKeyID.id=3;
RegisterEventHotKey(keyCode, keyFlags, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}
shownCenturyMessage = NO;
if ([defaults integerForKey:@"NumberOfTimesUsed"]>=kCentury)
shownCenturyMessage = YES;
// startupitem
startupItemController = [[StartupItemController alloc] init];
// status bar control
//[self setupStatusItem]; // now in awakeFromNib because we need the infoBox to have awoken
gMyHotKeyRef = 0;
// value transformer
LessThanAboutOne *lessThanAboutOne;
lessThanAboutOne = [[[LessThanAboutOne alloc] init] autorelease];
[NSValueTransformer setValueTransformer:lessThanAboutOne forName:@"LessThanAboutOne"];
// register for notification on change of screen configuration
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationDidChangeScreenParameters:)
name:NSApplicationDidChangeScreenParametersNotification
object:nil];
[self setupAppleScripts];
infoBox = nil;
return self;
}
-(void) awakeFromNib
{
[self setupBlackWindows];
[self setKeyCombo];
[self setupStatusItem];
}
-(void) setKeyCombo
{
KeyCombo keyCombo;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
keyCombo.code = [defaults integerForKey:@"Hotkey"];
keyCombo.flags = [defaults integerForKey:@"HotkeyFlags"];
[shortcutRecorder setKeyCombo:keyCombo];
}
-(void) saveKeyCombo
{
KeyCombo keyCombo = [shortcutRecorder keyCombo];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:keyCombo.code forKey:@"Hotkey"];
[defaults setInteger:keyCombo.flags forKey:@"HotkeyFlags"];
[self syncDefaults:self];
}
-(void) setupStatusItem
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"ShowMenubarIcon"]==NO) {
if (statusItem) {
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
[statusItem release];
}
statusItem = nil;
return;
}
if (statusItem) {
return;
}
[self initStatusMenu];
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
if (!statusItem) {
NSLog(@"Could not create StatusItem");
return;
}
NSRect theFrame = NSZeroRect; // Seems to work. Correct?? I dunno.
IsoStatusItemView* siView = [[[IsoStatusItemView alloc] initWithFrame:theFrame isoController:self] autorelease];
[statusItem setView:siView];
[[statusItem view] setNeedsDisplay:YES];
[statusItem setHighlightMode:YES];
if (![defaults boolForKey:@"InfoBoxHasBeenShown"]) {
theFrame = [[siView window] frame];
NSPoint pt = NSMakePoint(NSMidX(theFrame), NSMinY(theFrame));
[self showInfoBoxAtPoint:pt];
}
}
-(NSStatusItem*) getStatusItem
{
return statusItem;
}
-(void) initStatusMenu
{
statusMenu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Isolator",nil)];
[statusMenu setDelegate:self];
if (active)
toggleMenuItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Turn Isolator Off",nil) action:@selector(toggle) keyEquivalent:@""];
else
toggleMenuItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Turn Isolator On",nil) action:@selector(toggle) keyEquivalent:@""];
[statusMenu insertItem:toggleMenuItem atIndex:0];
[statusMenu insertItem:[NSMenuItem separatorItem] atIndex:1];
NSMenuItem* prefsMenuItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Preferences...",nil) action:@selector(openPrefs) keyEquivalent:@""] autorelease];
[statusMenu insertItem:prefsMenuItem atIndex:2];
[statusMenu insertItem:[NSMenuItem separatorItem] atIndex:3];
NSMenuItem* updateMenuItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Check for updates...",nil) action:@selector(checkForUpdates:) keyEquivalent:@""] autorelease];
//[updateMenuItem setTarget:self];
[statusMenu insertItem:updateMenuItem atIndex:4];
NSMenuItem* aboutMenuItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"About Isolator",nil) action:@selector(openAboutPanel) keyEquivalent:@""] autorelease];
[statusMenu insertItem:aboutMenuItem atIndex:5];
NSMenuItem* quitMenuItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Quit",nil) action:@selector(exit) keyEquivalent:@""] autorelease];
[statusMenu insertItem:quitMenuItem atIndex:6];
}
-(NSMenu*)getStatusMenu
{
return statusMenu;
}
-(void)showStatusMenu
{
[self bringWindowsForward];
[statusItem popUpStatusItemMenu:statusMenu];
}
-(void) applicationDidChangeScreenParameters:(id)object
{
[self checkIfDisplaysAreHardwareAccelerated];
[self setupBlackWindows];
}
-(void) setupBlackWindows
{
int i;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray* frames = [[NSMutableArray alloc] init];
if ([defaults boolForKey:@"HideOnMainScreenOnly"]==YES) {
[frames addObject:[NSValue valueWithRect:[[NSScreen mainScreen] frame]]];
}
else {
for (i=0;i<[[NSScreen screens] count];i++) {
[frames addObject:[NSValue valueWithRect:[[[NSScreen screens] objectAtIndex:i] frame]]];
}
}
//NSLog(@"%@",frames);
BOOL framesActuallyChanged = NO;
if (!savedFrames) {
framesActuallyChanged = YES;
}
else {
if ([savedFrames count]!=[frames count]) {
framesActuallyChanged = YES;
}
else {
for (i=0;i<[frames count];i++) {
if ( !NSEqualRects([[frames objectAtIndex:i] rectValue],[[savedFrames objectAtIndex:i] rectValue]) )
framesActuallyChanged = YES;
}
}
}
if (savedFrames)
[savedFrames release];
savedFrames = [[NSArray alloc] initWithArray:frames copyItems:YES];
// then the black windows already exist, and the screens didn't change, we don't need to do anything
if (blackWindows&&(!framesActuallyChanged)) {
[frames release];
return;
}
if (blackWindows) {
NSEnumerator *blackEnumerator = [blackWindows objectEnumerator];
BlackWindow *blackWindow = nil;
while ( (blackWindow = [blackEnumerator nextObject]) ) {
[blackWindow close];
}
[blackWindows release];
}
blackWindows = [[NSMutableArray alloc] init];
NSEnumerator *enumerator = [frames objectEnumerator];
NSValue* frame;
BlackWindow* window;
while ( (frame = [enumerator nextObject]) ) {
window = [[BlackWindow alloc] initWithFrame:[frame rectValue]];
[blackWindows addObject:window];
}
if (active) {
[self enterIsolateMode:NO];
}
else {
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window orderOut:self];
}
}
[frames release];
}
-(void) checkIfDisplaysAreHardwareAccelerated
{
// actually, we're only going to set this to YES on Leopard
bool hwAccel;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:@"RunningOnLeopard"]) {
hwAccel = NO;
}
else {
NSScreen *screen = nil;
NSNumber *screenID = nil;
hwAccel = YES;
if ([defaults boolForKey:@"HideOnMainScreenOnly"]==YES) {
screen = [[NSScreen mainScreen] copy];
screenID = [[screen deviceDescription] objectForKey:@"NSScreenNumber"];
if (!CGDisplayUsesOpenGLAcceleration((CGDirectDisplayID)[screenID intValue]))
hwAccel = NO;
[screen release];
}
else {
NSArray* screens;
screens = [[NSScreen screens] copy];
NSEnumerator *screenEnumerator = [screens objectEnumerator];
NSScreen *screen = nil;
NSNumber *screenID = nil;
while ( (screen = [screenEnumerator nextObject]) ) {
screenID = [[screen deviceDescription] objectForKey:@"NSScreenNumber"];
if (!CGDisplayUsesOpenGLAcceleration((CGDirectDisplayID)[screenID intValue]))
hwAccel = NO;
}
[screens release];
}
}
[defaults setBool:hwAccel forKey:@"DisplaysAreHardwareAccelerated"];
}
-(void) toggle
{
[self toggle:NO];
}
-(void) toggle:(BOOL)shouldFlip
{
if (active)
[self leaveIsolateMode];
else
[self enterIsolateMode:shouldFlip];
}
-(void) enterIsolateMode:(BOOL)shouldFlip
{
// when isolate mode is turned on by hotkey or menu icon
if (!shownCenturyMessage) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
int numTimes = [defaults integerForKey:@"NumberOfTimesUsed"]+1;
[defaults setInteger:numTimes forKey:@"NumberOfTimesUsed"];
if (numTimes==kCentury) {
[self showCenturyMessage];
shownCenturyMessage = YES;
return;
}
}
active = YES;
suspended = NO;
flipMode = shouldFlip;
[[statusItem view] setNeedsDisplay:YES];
[toggleMenuItem setTitle:NSLocalizedString(@"Turn Isolator Off",nil)];
// level depends on whether we're hiding other apps or not
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window setLevelAsAppropriate:flipMode];
}
[self isolate:kEnteredIsolateMode];
didAffectDock = NO;
[self hideDockAsAppropriate];
}
-(void) isolate:(int) reason
{
if ( !active )
return;
// get details of the currently (newly?) active app
NSDictionary* activeApp = [[[NSWorkspace sharedWorkspace] activeApplication] copy];
int myPID = [[NSProcessInfo processInfo] processIdentifier];
if (reason==kAppSwitched) {
if ( ([[activeApp objectForKey:@"NSApplicationProcessIdentifier"] intValue]==myPID)
// then Isolator became frontmost. Ignore.
|| ([[activeApp objectForKey:@"NSApplicationProcessIdentifier"] isEqual:[lastAppActivated objectForKey:@"NSApplicationProcessIdentifier"]]) ) {
// then we got an app switched message, but the active app didn't actually change. Ignore.
[activeApp release];
activeApp = nil;
return;
}
}
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL fadingOut = NO;
BOOL fadingIn = NO;
if ( [defaults boolForKey:@"SuspendWhenFinderIsActive"] ) {
if ( [[activeApp objectForKey:@"NSApplicationBundleIdentifier"] isEqual:@"com.apple.finder"] ) {
[self fadeOutBlackWindows];
fadingOut = YES;
suspended = YES;
}
else if ( suspended ) {// [[lastAppActivated objectForKey:@"NSApplicationBundleIdentifier"] isEqual:@"com.apple.finder"] ) {
[self revealBlackWindows];
fadingIn = YES;
suspended = NO;
}
}
if ( (reason!=kAppSwitched) && (!fadingOut) && (!fadingIn) ) {
[self revealBlackWindows];
}
if (lastAppActivated)
[lastAppActivated release];
lastAppActivated = [activeApp retain];
if ( ([defaults boolForKey:@"HideBackgroundApps"]&&(!flipMode)) ||
((![defaults boolForKey:@"HideBackgroundApps"])&&flipMode) ) {
// then hide all the background apps
[self hideAppsExcept:activeApp];
// this kludge makes cmd-tabbing work correctly. without it, sometimes the frontmost application doesn't move to
// the left of the bar as it should
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(toggleFrontmostApp:) userInfo:activeApp repeats:NO];
}
else {
if (!fadingOut) {
// bring all windows of frontmost app in front of others, and position black windows behind
[self setFrontmostAppAndPositionBlackWindows:activeApp];
}
}
[activeApp release];
}
-(void)revealBlackWindows
{
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window fadeInOrOut:YES];
}
}
-(void) fadeOutBlackWindows
{
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window fadeInOrOut:NO];
}
}
-(void)hideAppsExcept:(NSDictionary*)excludeApp
{
NSNumber* excludePID = [excludeApp objectForKey:@"NSApplicationProcessIdentifier"];
NSArray* launchedApps = [[[NSWorkspace sharedWorkspace] launchedApplications] copy];
NSEnumerator* appEnum = [launchedApps objectEnumerator];
NSDictionary* app = nil;
NSNumber* pid = nil;
ProcessSerialNumber psn;
ProcessInfoRec info;
info.processInfoLength = sizeof(ProcessInfoRec);
info.processName = nil;
FSSpec tempFSSpec;
#ifdef __LP64__
info.processAppRef = (FSRefPtr)&tempFSSpec;
#else
info.processAppSpec = &tempFSSpec;
#endif
while ( (app = [appEnum nextObject]) ) {
pid = [app objectForKey:@"NSApplicationProcessIdentifier"];
if (![pid isEqual:excludePID]) {
psn.highLongOfPSN = [[app objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
psn.lowLongOfPSN = [[app objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
if (GetProcessInformation(&psn, &info) == noErr) {
ShowHideProcess(&psn,FALSE);
}
}
}
[launchedApps release];
}
-(void) toggleFrontmostApp:(id)sender
{
ProcessSerialNumber myPSN;
GetCurrentProcess(&myPSN);
SetFrontProcess(&myPSN);
ProcessSerialNumber activePSN;
activePSN.highLongOfPSN = [[[sender userInfo] objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
activePSN.lowLongOfPSN = [[[sender userInfo] objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
SetFrontProcess(&activePSN);
}
-(void) setFrontmostAppAndPositionBlackWindows:(id)sender
{
NSDictionary* theApp = nil;
int counter = -1;
if ( [sender isKindOfClass:[NSDictionary class]] ) {
// then it's the first time we've been called
theApp = sender;
counter = 0;
}
else {
// then we're being called by the timer
theApp = [sender userInfo];
counter = [[theApp objectForKey:@"counter"] intValue];
}
// check the relevant app is still frontmost (prevents infinite loops)
NSDictionary* activeApp = [[[NSWorkspace sharedWorkspace] activeApplication] copy];
if (![[theApp objectForKey:@"NSApplicationProcessIdentifier"] isEqual:[activeApp objectForKey:@"NSApplicationProcessIdentifier"]]) {
[activeApp release];
return;
}
[self setFrontmostApp:activeApp];
[self positionBlackWindows:activeApp];
counter++;
if (counter<=5) {
NSMutableDictionary* newActiveApp = [activeApp mutableCopy];
[newActiveApp setObject:[NSNumber numberWithInt:counter] forKey:@"counter"];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(setFrontmostAppAndPositionBlackWindows:) userInfo:newActiveApp repeats:NO];
[newActiveApp release];
}
[activeApp release];
}
-(void) setFrontmostApp:(id)sender
{
NSDictionary* activeApp = nil;
if ([sender isKindOfClass:[NSDictionary class]])
activeApp = sender;
else
activeApp = [sender userInfo];
ProcessSerialNumber activePSN;
activePSN.highLongOfPSN = [[activeApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
activePSN.lowLongOfPSN = [[activeApp objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
SetFrontProcess(&activePSN);
}
-(void) positionBlackWindows:(id)sender
{
NSDictionary* activeApp = nil;
if ([sender isKindOfClass:[NSDictionary class]])
activeApp = sender;
else
activeApp = [sender userInfo];
ProcessSerialNumber activePSN;
activePSN.highLongOfPSN = [[activeApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
activePSN.lowLongOfPSN = [[activeApp objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
CGSConnection cid;
CGSGetConnectionIDForPSN(0, &activePSN, &cid);
ProcessSerialNumber myPSN;
CGSConnection myCid;
GetCurrentProcess(&myPSN);
CGSGetConnectionIDForPSN(0, &myPSN, &myCid);
int nWindows;
CGSGetOnScreenWindowCount(myCid, cid, &nWindows);
CGSWindow list[nWindows];
if (nWindows != 0) {
CGSGetOnScreenWindowList(myCid, cid, nWindows, list, &nWindows);
}
// Find windows at level 0
int ii;
int level;
int nRelevantWindows = 0;
CGSWindow relevantList[nWindows];
OSStatus err;
for (ii=0;ii<nWindows;ii++) {
err = CGSGetWindowLevel(myCid, list[ii], &level);
if (err) {
continue;
}
if (level==0) {
relevantList[nRelevantWindows] = list[ii];
nRelevantWindows++;
}
}
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
if (nRelevantWindows==0)
[window orderFrontRegardless];
else
[window orderWindow:NSWindowBelow relativeTo:relevantList[nRelevantWindows-1]];
}
}
-(void) leaveIsolateMode
{
[lastAppActivated release];
lastAppActivated = nil;
active = NO;
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window fadeInOrOut:NO];
}
[self restoreDockAutohide];
[[statusItem view] setNeedsDisplay:YES];
[toggleMenuItem setTitle:NSLocalizedString(@"Turn Isolator On",nil)];
}
-(void) openPrefs
{
[prefWindow setAutodisplay:YES];
[self willChangeValueForKey:@"startupItemEnabled"];
[self didChangeValueForKey:@"startupItemEnabled"];
[NSApp activateIgnoringOtherApps:YES];
[prefWindow makeKeyAndOrderFront:self];
}
-(IBAction)setBackgroundColor:(id)sender
{
[self syncDefaults:self];
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window setColor];
}
[[statusItem view] setNeedsDisplay:YES];
}
-(IBAction)setOpacity:(id)sender
{
[self syncDefaults:self];
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window setOpacity];
}
[[statusItem view] setNeedsDisplay:YES];
}
-(IBAction)setBlur:(id)sender
{
[self syncDefaults:self];
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window enableBlurAsAppropriate:1.0];
}
}
-(IBAction)setClickThrough:(id)sender
{
[self syncDefaults:self];
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window setClickThrough];
}
}
-(IBAction)setMenuBarIcon:(id)sender
{
[self syncDefaults:self];
[self setupStatusItem];
}
-(IBAction)setHideBackgroundApps:(id)sender
{
[self syncDefaults:self];
[self leaveIsolateMode];
[self enterIsolateMode:flipMode];
}
-(IBAction)setSuspendWhenFinderIsActive:(id)sender
{
NSDictionary* activeApp = [[[NSWorkspace sharedWorkspace] activeApplication] copy];
if ( [[activeApp objectForKey:@"NSApplicationBundleIdentifier"] isEqual:@"com.apple.finder"] ) {
[self leaveIsolateMode];
[self enterIsolateMode:flipMode];
}
[activeApp release];
}
-(void)setUpdatesIncludeBetaVersions:(BOOL)flag
{
if (flag)
[sparkleUpdater setFeedURL:[NSURL URLWithString:kBetaFeedURL]];
else
[sparkleUpdater setFeedURL:[NSURL URLWithString:kReleaseFeedURL]];
}
-(BOOL)updatesIncludeBetaVersions
{
if ([[sparkleUpdater feedURL] isEqual:[NSURL URLWithString:kBetaFeedURL]])
return YES;
else
return NO;
}
-(void) setNilValueForKey:(NSString *)theKey;
{
if ([theKey isEqualToString:@"updatesIncludeBetaVersions"])
[sparkleUpdater setFeedURL:[NSURL URLWithString:kReleaseFeedURL]];
}
-(IBAction)setWindow:(id)sender
{
[self syncDefaults:self];
if (!active)
return;
NSEnumerator *enumerator = [blackWindows objectEnumerator];
BlackWindow* window;
while ( (window = [enumerator nextObject]) ) {
[window fadeInOrOut:YES];
}
}
-(void) registerHotkey:(KeyCombo)keyCombo
{
if (gMyHotKeyRef>0) {
UnregisterEventHotKey(gMyHotKeyRef);
}
// set up hotkey -- remember asynckeys for key codes
EventHotKeyID gMyHotKeyID;
EventTypeSpec eventType;
eventType.eventClass=kEventClassKeyboard;
eventType.eventKind=kEventHotKeyPressed;
InstallApplicationEventHandler(&hotKeyHandler,1,&eventType,NULL,NULL);
gMyHotKeyID.signature='htk1';
gMyHotKeyID.id=1;
RegisterEventHotKey([shortcutRecorder keyCombo].code, [shortcutRecorder cocoaToCarbonFlags:[shortcutRecorder keyCombo].flags],
gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}
- (void)shortcutRecorder:(SRRecorderControl *)aRecorder keyComboDidChange:(KeyCombo)newKeyCombo;
{
[self registerHotkey:newKeyCombo];
[self saveKeyCombo];
}
- (void)syncDefaults:(id)sender
{
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(BOOL)startupItemEnabled
{
return [startupItemController enabled];
}
-(void)setStartupItemEnabled:(BOOL)value
{
[startupItemController openAtLogin:value];
}
-(void)openAboutPanel
{
[NSApp orderFrontStandardAboutPanel:self];
[NSApp activateIgnoringOtherApps:YES];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
[[NSUserDefaults standardUserDefaults] synchronize];
[self restoreDockAutohide];
}
-(BOOL)isActive
{
return active;
}
-(void)showCenturyMessage {
NSAlert* alert = [[NSAlert alloc] init];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"You have used Isolator %d times.",nil),kCentury]];
[alert setInformativeText:NSLocalizedString(@"Please consider donating a few dollars to support its continued development. Either way, you won't see this message again.",nil)];
[alert addButtonWithTitle:NSLocalizedString(@"Go to Paypal donation page",nil)];
[alert addButtonWithTitle:NSLocalizedString(@"Don't donate",nil)];
int result = [alert runModal];
if (result==NSAlertFirstButtonReturn) {
NSString* urlString = @"https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=bdeb%40willmore%2eeu&item_name=Isolator&no_shipping=2&no_note=1&tax=0¤cy_code=GBP&bn=PP%2dDonationsBF&charset=UTF%2d8";
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:urlString]];
}
[alert release];
}
-(void)setupAppleScripts
{
// Dock preferences are only accessible by AppleScript on 10.5+
NSDictionary** errorInfo = NULL;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"RunningOnLeopard"]) {
getDockAutohideScript = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to tell dock preferences to set foo to autohide"];
[getDockAutohideScript compileAndReturnError:errorInfo];
setDockAutohideTrueScript = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to tell dock preferences to set autohide to true"];
[setDockAutohideTrueScript compileAndReturnError:errorInfo];
setDockAutohideFalseScript = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to tell dock preferences to set autohide to false"];
[setDockAutohideFalseScript compileAndReturnError:errorInfo];
}
if (!getDockAutohideScript || !setDockAutohideTrueScript || !setDockAutohideFalseScript) {
[getDockAutohideScript release];
getDockAutohideScript = nil;
[setDockAutohideTrueScript release];
setDockAutohideTrueScript = nil;
[setDockAutohideFalseScript release];
setDockAutohideFalseScript = nil;
}
}
-(void)saveDockAutohide
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:@"RunningOnLeopard"]) {
dockAutohide = NO;
return;
}
NSDictionary** errorInfo = nil;
NSAppleEventDescriptor* result;
if ( (result = [getDockAutohideScript executeAndReturnError:errorInfo]) )
dockAutohide = [result booleanValue];
}
-(void)restoreDockAutohide
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"HideDock"] && didAffectDock)
[self setDockAutohide:dockAutohide];
}
-(BOOL)getDockAutohide
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:@"RunningOnLeopard"])