forked from binaryage/visor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Visor.m
1324 lines (1171 loc) · 52.4 KB
/
Visor.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
#import "Macros.h"
#import "JRSwizzle.h"
#import "CGSPrivate.h"
#import "Visor.h"
#import "GTMHotKeyTextField.h"
#import "QSBKeyMap.h"
#import "GTMCarbonEvent.h"
@interface NSEvent (Visor)
- (NSUInteger)qsbModifierFlags;
@end
@implementation NSEvent (QSBApplicationEventAdditions)
- (NSUInteger)qsbModifierFlags {
NSUInteger flags = ([self modifierFlags] & NSDeviceIndependentModifierFlagsMask);
// Ignore caps lock if it's set http://b/issue?id=637380
if (flags & NSAlphaShiftKeyMask) flags -= NSAlphaShiftKeyMask;
// Ignore numeric lock if it's set http://b/issue?id=637380
if (flags & NSNumericPadKeyMask) flags -= NSNumericPadKeyMask;
return flags;
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// main entry point
int main(int argc, char *argv[]) {
return NSApplicationMain(argc, (const char **) argv);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VisorScreenTransformer - helper class for properties dialog
@interface VisorScreenTransformer: NSValueTransformer {
}
@end
@implementation VisorScreenTransformer
+ (Class)transformedValueClass {
LOG(@"transformedValueClass");
return [NSNumber class];
}
+ (BOOL)allowsReverseTransformation {
LOG(@"allowsReverseTransformation");
return YES;
}
- (id)transformedValue:(id)value {
LOG(@"transformedValue %@", value);
return [NSString stringWithFormat: @"Screen %d", [value integerValue]];
}
- (id)reverseTransformedValue:(id)value {
LOG(@"reverseTransformedValue %@", value);
return [NSNumber numberWithInteger:[[value substringFromIndex:6] integerValue]];
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NSWindowController monkey patching
@implementation NSWindowController (Visor)
//------------------------------------------------------------
// TTAppPrefsController hacks
// Add Visor preference pane into Preferences window
- (void)Visor_TTAppPrefsController_windowDidLoad {
[self Visor_TTAppPrefsController_windowDidLoad];
LOG(@"Visor_TTAppPrefsController_windowDidLoad");
id visor = [Visor sharedInstance];
[visor enahanceTerminalPreferencesWindow];
}
- (void)Visor_TTAppPrefsController_selectVisorPane {
LOG(@"Visor_TTAppPrefsController_selectVisorPane");
id visor = [Visor sharedInstance]; // for some reason Visor_TTAppPrefsController_windowDidLoad may be not called in rare case we started visor and created Visor profile
[visor enahanceTerminalPreferencesWindow];
NSWindow* prefsWindow = [self window];
[prefsWindow setTitle:@"Visor"];
NSToolbar* toolbar = [prefsWindow toolbar];
[toolbar setSelectedItemIdentifier:@"Visor"];
NSTabView* tabView = [self valueForKey:@"tabView"];
[tabView selectTabViewItemWithIdentifier:@"VisorPane"];
}
- (id)Visor_TTAppPrefsController_toolbar:(id)arg1 itemForItemIdentifier:(id)arg2 willBeInsertedIntoToolbar:(BOOL)arg3 {
LOG(@"Visor_TTAppPrefsController_toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar => %@", arg2);
if ([arg2 isEqualToString:@"Visor"]) {
id visor = [Visor sharedInstance];
NSToolbarItem* toolbarItem = [visor getVisorToolbarItem];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(Visor_TTAppPrefsController_selectVisorPane)];
return toolbarItem;
}
return [self Visor_TTAppPrefsController_toolbar:arg1 itemForItemIdentifier:arg2 willBeInsertedIntoToolbar:arg3];
}
- (id) Visor_TTAppPrefsController_windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client {
if ([client isKindOfClass:[GTMHotKeyTextField class]]) {
LOG(@"Visor_TTAppPrefsController_windowWillReturnFieldEditor with GTMHotKeyTextField");
return [GTMHotKeyFieldEditor sharedHotKeyFieldEditor];
}
return [self Visor_TTAppPrefsController_windowWillReturnFieldEditor:sender toObject:client];
}
- (id) windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client {
return nil;
}
//------------------------------------------------------------
// TTWindowController hacks
- (void)Visor_TTWindowController_setCloseDialogExpected:(BOOL)fp8 {
LOG(@"Visor_TTWindowController_setCloseDialogExpected");
if (fp8) {
// THIS IS A MEGAHACK! (works for me on Leopard 10.5.6)
// the problem: beginSheet causes UI to lock for NSBorderlessWindowMask NSWindow which is in "closing mode"
//
// this hack tries to open sheet before window starts it's closing procedure
// we expect that setCloseDialogExpected is called by Terminal.app once BEFORE window gets into "closing mode"
// in this case we are able to open sheet before window starts closing and this works even for window with NSBorderlessWindowMask
// it works like a magic, took me few hours to figure out this random stuff
Visor* visor = [Visor sharedInstance];
[visor showVisor:false];
[self displayWindowCloseSheet:1];
}
}
- (NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect {
return rect;
}
- (NSRect)Visor_TTWindowController_window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect {
LOG(@"Visor_TTWindowController_window");
Visor* visor = [Visor sharedInstance];
[visor setupExposeTags:sheet];
return rect;
}
// swizzled function for original TTWindowController::newTabWithProfile
// this seems to be a good point to intercept new tab creation
// responsible for opening all tabs in Visored window with Visor profile (regardless of "default profile" setting)
- (id)Visor_TTWindowController_newTabWithProfile:(id)arg1 {
LOG(@"creating a new tab");
id this = self;
id visor = [Visor sharedInstance];
BOOL isVisoredWindow = [visor isVisoredWindow:[this window]];
if (isVisoredWindow) {
LOG(@" in visored window ... so apply visor profile");
id profileManagerClass = NSClassFromString(@"TTProfileManager");
id profileManager = [profileManagerClass sharedProfileManager];
id visorProfile = [profileManager profileWithName:@"Visor"];
if (visorProfile) {
arg1 = visorProfile;
} else {
LOG(@" ... unable to lookup Visor profile!");
}
}
return [self Visor_TTWindowController_newTabWithProfile:arg1];
}
// this is variant of the ^^^
// this seems to be an alternative point to intercept new tab creation
- (id)Visor_TTWindowController_newTabWithProfile:(id)arg1 command:(id)arg2 runAsShell:(BOOL)arg3 {
LOG(@"creating a new tab (with runAsShell)");
id this = self;
id visor = [Visor sharedInstance];
BOOL isVisoredWindow = [visor isVisoredWindow:[this window]];
if (isVisoredWindow) {
LOG(@" in visored window ... so apply visor profile");
id profileManager = [NSClassFromString(@"TTProfileManager") sharedProfileManager];
id visorProfile = [profileManager profileWithName:@"Visor"];
if (visorProfile) {
arg1 = visorProfile;
} else {
LOG(@" ... unable to lookup Visor profile!");
}
}
return [self Visor_TTWindowController_newTabWithProfile:arg1 command:arg2 runAsShell:arg3];
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NSApplication monkey patching
@implementation NSApplication (Visor)
- (void)Visor_sendEvent:(NSEvent *)theEvent {
NSUInteger type = [theEvent type];
if (type == NSFlagsChanged) {
Visor* visor = [Visor sharedInstance];
[visor modifiersChangedWhileActive:theEvent];
} else if (type == NSKeyDown || type == NSKeyUp) {
Visor* visor = [Visor sharedInstance];
[visor keysChangedWhileActive:theEvent];
}
[self Visor_sendEvent:theEvent];
}
- (BOOL)Visor_TTAplication_applicationShouldHandleReopen:(id)fp8 hasVisibleWindows:(BOOL)fp12 {
LOG(@"Visor_TTAplication_applicationShouldHandleReopen");
Visor* visor = [Visor sharedInstance];
[visor onReopenVisor];
return [self Visor_TTAplication_applicationShouldHandleReopen:fp8 hasVisibleWindows:(BOOL)fp12];
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NSWindow monkey patching
@implementation NSWindow (Visor)
- (id) Visor_initWithContentRect: (NSRect) contentRect styleMask: (unsigned int) aStyle backing: (NSBackingStoreType) bufferingType defer: (BOOL) flag {
LOG(@"Creating a new terminal window %@", [self class]);
Visor* visor = [Visor sharedInstance];
BOOL shouldBeVisorized = ![visor status];
if (shouldBeVisorized) {
aStyle = NSBorderlessWindowMask;
bufferingType = NSBackingStoreBuffered;
}
self = [self Visor_initWithContentRect:contentRect styleMask:aStyle backing:bufferingType defer:flag];
if (shouldBeVisorized) {
[visor adoptTerminal:self];
}
return self;
}
- (BOOL) Visor_canBecomeKeyWindow {
LOG(@"canBecomeKeyWindow");
return YES;
}
- (BOOL) Visor_canBecomeMainWindow {
LOG(@"canBecomeMainWindow");
return YES;
}
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Visor implementation
@implementation Visor
-(NSToolbarItem*)getVisorToolbarItem {
LOG(@"getVisorToolbarItem");
NSToolbar* sourceToolbar = [settingsWindow toolbar];
NSToolbarItem* toolbarItem = [[sourceToolbar items] objectAtIndex:0];
return toolbarItem;
}
- (void) enahanceTerminalPreferencesWindow {
static bool alreadyEnhanced = NO;
if (alreadyEnhanced) return;
alreadyEnhanced = YES;
LOG(@"enahanceTerminalPreferencesWindow");
id prefsController = [NSClassFromString(@"TTAppPrefsController") sharedPreferencesController];
NSTabView* tabView = [prefsController valueForKey:@"tabView"];
NSWindow* prefsWindow = [prefsController window];
NSToolbar* toolbar = [prefsWindow toolbar];
NSTabView* sourceTabView = [[[settingsWindow contentView] subviews] objectAtIndex:0];
NSTabViewItem* item = [sourceTabView tabViewItemAtIndex:0];
[toolbar insertItemWithItemIdentifier:@"Visor" atIndex:4];
[tabView addTabViewItem:item];
}
+ (Visor*) sharedInstance {
static Visor* plugin = nil;
if (plugin == nil)
plugin = [[Visor alloc] init];
return plugin;
}
+ (id) getOrCreateVisorProfile {
LOG(@"createVisorProfileIfNeeded");
id profileManager = [NSClassFromString(@"TTProfileManager") sharedProfileManager];
id visorProfile = [profileManager profileWithName:@"Visor"];
if (!visorProfile) {
LOG(@" ... initialising Visor profile");
// create visor profile in case it does not exist yet, use startup profile as a template
id startupProfile = [profileManager startupProfile];
visorProfile = [startupProfile copyWithZone:nil];
// apply Darwin's preferred Visor settings
Visor* visor = [Visor sharedInstance];
NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *path = [[NSBundle bundleForClass:[visor class]] pathForResource:@"VisorProfile" ofType:@"plist"];
plistData = [NSData dataWithContentsOfFile:path];
plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
LOG(@"Error reading plist from file '%s', error = '%s'", [path UTF8String], [error UTF8String]);
[error release];
}
[visorProfile setPropertyListRepresentation:plist];
// set profile into manager
[profileManager setProfile:visorProfile forName:@"Visor"];
[visorProfile release];
}
return visorProfile;
}
+ (void) closeExistingWindows {
id wins = [[NSClassFromString(@"TTApplication") sharedApplication] windows];
int winCount = [wins count];
for (int i=0; i<winCount; i++) {
id win = [wins objectAtIndex:i];
if (!win) continue;
if ([[win className] isEqualToString:@"TTWindow"]) {
[win close];
}
}
}
+ (void) install {
LOG(@"Visor installed");
[NSClassFromString(@"TTWindowController") jr_swizzleMethod:@selector(newTabWithProfile:) withMethod:@selector(Visor_TTWindowController_newTabWithProfile:) error:NULL];
[NSClassFromString(@"TTWindowController") jr_swizzleMethod:@selector(newTabWithProfile:command:runAsShell:) withMethod:@selector(Visor_TTWindowController_newTabWithProfile:command:runAsShell:) error:NULL];
[NSClassFromString(@"TTWindowController") jr_swizzleMethod:@selector(setCloseDialogExpected:) withMethod:@selector(Visor_TTWindowController_setCloseDialogExpected:) error:NULL];
[NSClassFromString(@"TTWindowController") jr_swizzleMethod:@selector(window:willPositionSheet:usingRect:) withMethod:@selector(Visor_TTWindowController_window:willPositionSheet:usingRect:) error:NULL];
[NSClassFromString(@"TTWindow") jr_swizzleMethod:@selector(initWithContentRect:styleMask:backing:defer:) withMethod:@selector(Visor_initWithContentRect:styleMask:backing:defer:) error:NULL];
[NSClassFromString(@"TTWindow") jr_swizzleMethod:@selector(canBecomeKeyWindow) withMethod:@selector(Visor_canBecomeKeyWindow) error:NULL];
[NSClassFromString(@"TTWindow") jr_swizzleMethod:@selector(canBecomeMainWindow) withMethod:@selector(Visor_canBecomeMainWindow) error:NULL];
[NSClassFromString(@"TTApplication") jr_swizzleMethod:@selector(sendEvent:) withMethod:@selector(Visor_sendEvent:) error:NULL];
[NSClassFromString(@"TTApplication") jr_swizzleMethod:@selector(applicationShouldHandleReopen:hasVisibleWindows:) withMethod:@selector(Visor_TTAplication_applicationShouldHandleReopen:hasVisibleWindows:) error:NULL];
[NSClassFromString(@"TTAppPrefsController") jr_swizzleMethod:@selector(windowDidLoad) withMethod:@selector(Visor_TTAppPrefsController_windowDidLoad) error:NULL];
[NSClassFromString(@"TTAppPrefsController") jr_swizzleMethod:@selector(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:) withMethod:@selector(Visor_TTAppPrefsController_toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:) error:NULL];
[NSClassFromString(@"TTAppPrefsController") jr_swizzleMethod:@selector(windowWillReturnFieldEditor:toObject:) withMethod:@selector(Visor_TTAppPrefsController_windowWillReturnFieldEditor:toObject:) error:NULL];
NSDictionary* defaults = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleForClass:[self class]]pathForResource:@"Defaults" ofType:@"plist"]];
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
[ud registerDefaults:defaults];
[self sanitizeDefaults:ud];
[self closeExistingWindows];
id visorProfile = [self getOrCreateVisorProfile];
id app = [NSClassFromString(@"TTApplication") sharedApplication];
id controller = [app newWindowControllerWithProfile:visorProfile];
Visor* visor = [Visor sharedInstance];
[visor resetWindowPlacement];
[controller release];
}
- (BOOL)status {
return !!window;
}
- (BOOL)isVisoredWindow:(id)win {
return window==win;
}
+ (void) load {
LOG(@"Visor loaded");
}
static const EventTypeSpec kModifierEventTypeSpec[] = { { kEventClassKeyboard, kEventRawKeyModifiersChanged } };
static const size_t kModifierEventTypeSpecSize = sizeof(kModifierEventTypeSpec) / sizeof(EventTypeSpec);
// Allows me to intercept the "control" double tap to activate QSB. There
// appears to be no way to do this from straight Cocoa.
- (void)startEventMonitoring {
GTMCarbonEventMonitorHandler *handler = [GTMCarbonEventMonitorHandler sharedEventMonitorHandler];
[handler registerForEvents:kModifierEventTypeSpec count:kModifierEventTypeSpecSize];
[handler setDelegate:self];
}
- (void)stopEventMonitoring {
GTMCarbonEventMonitorHandler *handler = [GTMCarbonEventMonitorHandler sharedEventMonitorHandler];
[handler unregisterForEvents:kModifierEventTypeSpec count:kModifierEventTypeSpecSize];
[handler setDelegate:nil];
}
- (OSStatus)gtm_eventHandler:(GTMCarbonEventHandler *)sender
receivedEvent:(GTMCarbonEvent *)event
handler:(EventHandlerCallRef)handler {
OSStatus status = eventNotHandledErr;
if ([event eventClass] == kEventClassKeyboard &&
[event eventKind] == kEventRawKeyModifiersChanged) {
UInt32 modifiers;
if ([event getUInt32ParameterNamed:kEventParamKeyModifiers data:&modifiers]) {
NSUInteger cocoaMods = GTMCarbonToCocoaKeyModifiers(modifiers);
NSEvent *nsEvent = [NSEvent keyEventWithType:NSFlagsChanged
location:[NSEvent mouseLocation]
modifierFlags:cocoaMods
timestamp:[event time]
windowNumber:0
context:nil
characters:nil
charactersIgnoringModifiers:nil
isARepeat:NO
keyCode:0];
[self modifiersChangedWhileInactive:nsEvent];
}
}
return status;
}
+ (void) sanitizeDefaults:(NSUserDefaults*) ud {
LOG(@"sanitizeDefaults");
if (![ud objectForKey:@"VisorShowStatusItem"]) {
[ud setBool:YES forKey:@"VisorShowStatusItem"];
}
if (![ud objectForKey:@"VisorShowOnReopen"]) {
[ud setBool:YES forKey:@"VisorShowOnReopen"];
}
if (![ud objectForKey:@"VisorCopyOnSelect"]) {
[ud setBool:NO forKey:@"VisorCopyOnSelect"];
}
if (![ud objectForKey:@"VisorScreen"]) {
[ud setInteger:0 forKey:@"VisorScreen"]; // use screen 0 by default
}
if (![ud objectForKey:@"VisorOnEverySpace"]) {
[ud setBool:YES forKey:@"VisorOnEverySpace"];
}
if (![ud objectForKey:@"VisorPosition"]) {
[ud setObject:@"Top-Stretch" forKey:@"VisorPosition"];
}
if (![ud objectForKey:@"VisorPosition"]) {
[ud setObject:@"Top-Stretch" forKey:@"VisorPosition"];
}
// by default enable HotKey as Control+` (CTRL+tilde)
if (![ud objectForKey:@"VisorHotKey"]) {
[ud setObject:[NSDictionary dictionaryWithObjectsAndKeys: \
[NSNumber numberWithUnsignedInt:NSControlKeyMask], \
kGTMHotKeyModifierFlagsKey, \
[NSNumber numberWithUnsignedInt:50], \
kGTMHotKeyKeyCodeKey, \
[NSNumber numberWithBool:NO], \
kGTMHotKeyDoubledModifierKey, \
nil]
forKey:@"VisorHotKey"];
}
// convert hot-key format from 2.0 -> 2.1
NSDictionary* hotkey = [ud objectForKey:@"VisorHotKey"];
NSNumber* keyCode = [hotkey objectForKey:@"keyCode"];
NSNumber* modifiers = [hotkey objectForKey:@"modifiers"];
if (keyCode && modifiers) {
LOG(@"-> conversion of hotkey from 2.0 format %@ %@ %@", hotkey, keyCode, modifiers);
[ud setObject:[NSDictionary dictionaryWithObjectsAndKeys: \
modifiers, \
kGTMHotKeyModifierFlagsKey, \
keyCode, \
kGTMHotKeyKeyCodeKey, \
[NSNumber numberWithBool:NO], \
kGTMHotKeyDoubledModifierKey, \
nil]
forKey:@"VisorHotKey"];
}
if (![ud objectForKey:@"VisorHotKeyEnabled"]) {
[ud setBool:YES forKey:@"VisorHotKeyEnabled"];
}
// by default disable HotKey2 but set it to double Control
if (![ud objectForKey:@"VisorHotKey2"]) {
[ud setObject:[NSDictionary dictionaryWithObjectsAndKeys: \
[NSNumber numberWithUnsignedInt:NSControlKeyMask], \
kGTMHotKeyModifierFlagsKey, \
[NSNumber numberWithUnsignedInt:0], \
kGTMHotKeyKeyCodeKey, \
[NSNumber numberWithBool:YES], \
kGTMHotKeyDoubledModifierKey, \
nil]
forKey:@"VisorHotKey2"];
}
if (![ud objectForKey:@"VisorHotKey2Enabled"]) {
[ud setBool:NO forKey:@"VisorHotKey2Enabled"];
}
}
- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
LOG(@"webView:decidePolicyForNavigationAction...");
if ([[actionInformation objectForKey:WebActionNavigationTypeKey] intValue] != WebNavigationTypeOther) {
[listener ignore];
[[NSWorkspace sharedWorkspace] openURL:[request URL]];
} else {
[listener use];
}
}
- (void) updateInfoLine {
LOG(@"updateInfoLine %@", infoLine);
[[infoLine mainFrame] loadHTMLString:@"<style>html {font-family: 'Lucida Grande', arial; font-size: 10px; cursor: default; color: #999;} a, a:visited { color: #66f; } a:hover {color: #22f}</style><center><b>Visor **VERSION**</b> (<a href=\"http://github.com/darwin/visor/commit/**SHA**\">**REVISION**</a>) by <a href=\"http://binaryage.com\">binaryage.com</a>, based on Visor 1.5 by <a href=\"http://blacktree.com\">blacktree.com</a></center>" baseURL:[NSURL URLWithString:@"http://visor.binaryage.com"]];
[infoLine setDrawsBackground:NO];
}
- (void)awakeFromNib {
LOG(@"awakeFromNib");
[self updateInfoLine];
}
- (id) init {
self = [super init];
if (!self) return self;
LOG(@"Visor init");
runningApplicationClass = NSClassFromString(@"NSRunningApplication"); // 10.6
NSString* path = [[NSBundle bundleForClass:[self class]] pathForResource:@"RestoreApp" ofType:@"scpt"];
restoreAppAppleScriptSource = [[NSString alloc] initWithContentsOfFile:path encoding:NSMacOSRomanStringEncoding error:NULL];
scriptError = [[NSDictionary alloc] init];
window = NULL;
activeIcon=[[NSImage alloc]initWithContentsOfFile:[[NSBundle bundleForClass:[self classForCoder]]pathForImageResource:@"VisorActive"]];
inactiveIcon=[[NSImage alloc]initWithContentsOfFile:[[NSBundle bundleForClass:[self classForCoder]]pathForImageResource:@"VisorInactive"]];
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
NSUserDefaultsController* udc = [NSUserDefaultsController sharedUserDefaultsController];
previouslyActiveAppPath = nil;
isHidden = true;
isMain = false;
isKey = false;
[NSBundle loadNibNamed:@"Visor" owner:self];
[self updateHotKeyRegistration];
[self updateEscapeHotKeyRegistration];
[self startEventMonitoring];
if ([ud boolForKey:@"VisorShowStatusItem"]) {
[self activateStatusMenu];
}
// watch for hotkey changes
[udc addObserver:self forKeyPath:@"values.VisorHotKey" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorHotKeyEnabled" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorHotKey2" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorHotKey2Enabled" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorUseFade" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorUseSlide" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorAnimationSpeed" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorShowStatusItem" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorScreen" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorPosition" options:0 context:nil];
[udc addObserver:self forKeyPath:@"values.VisorHideOnEscape" options:0 context:nil];
return self;
}
// credit: http://tonyarnold.com/entries/fixing-an-annoying-expose-bug-with-nswindows/
- (OSStatus)setupExposeTags:(NSWindow*)win {
CGSConnection cid;
CGSWindow wid;
CGSWindowTag tags[2];
bool showOnEverySpace = [[NSUserDefaults standardUserDefaults] boolForKey:@"VisorOnEverySpace"];
wid = [win windowNumber];
cid = _CGSDefaultConnection();
tags[0] = CGSTagSticky;
tags[1] = 0;
if (showOnEverySpace)
return CGSSetWindowTags(cid, wid, tags, 32);
else
return CGSClearWindowTags(cid, wid, tags, 32);
}
- (void)adoptTerminal:(id)win {
LOG(@"adoptTerminal window=%@", win);
if (window) {
LOG(@"adoptTerminal called when old window existed");
}
window = win;
[window setLevel:NSMainMenuWindowLevel-1];
[window setOpaque:NO];
NSNotificationCenter* dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(becomeKey:) name:NSWindowDidBecomeKeyNotification object:window];
[dnc addObserver:self selector:@selector(resignKey:) name:NSWindowDidResignKeyNotification object:window];
[dnc addObserver:self selector:@selector(becomeMain:) name:NSWindowDidBecomeMainNotification object:window];
[dnc addObserver:self selector:@selector(resignMain:) name:NSWindowDidResignMainNotification object:window];
[dnc addObserver:self selector:@selector(willClose:) name:NSWindowWillCloseNotification object:window];
[dnc addObserver:self selector:@selector(didChangeScreenScreenParameters:) name:NSApplicationDidChangeScreenParametersNotification object:nil];
[dnc addObserver:self selector:@selector(didResize:) name:NSWindowDidResizeNotification object:window];
justLaunched = true;
[self updateStatusMenu];
}
- (IBAction)pinAction:(id)sender {
LOG(@"pinAction %@", sender);
isPinned = !isPinned;
[self updateStatusMenu];
}
- (IBAction)toggleVisor:(id)sender {
LOG(@"toggleVisor %@ %d", sender, isHidden);
if (!window) {
LOG(@"visor is detached");
return;
}
if (isHidden) {
[self showVisor:false];
} else {
[self restorePreviouslyActiveApp];
[self hideVisor:false];
}
}
- (IBAction)showPrefs:(id)sender {
[NSApp activateIgnoringOtherApps:YES];
id terminalApp = [NSClassFromString(@"TTApplication") sharedApplication];
[terminalApp showPreferencesWindow:nil];
id prefsController = [NSClassFromString(@"TTAppPrefsController") sharedPreferencesController];
[prefsController Visor_TTAppPrefsController_selectVisorPane];
}
- (IBAction)visitHomepage:(id)sender {
LOG(@"visitHomepage");
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://visor.binaryage.com"]];
}
- (void)resetWindowPlacement {
lastPosition = nil;
if (!window) return;
float offset = 1.0f;
if (isHidden) offset = 0.0f;
LOG(@"resetWindowPlacement %@ %f", window, offset);
[self cacheScreen];
[self cachePosition];
[self applyWindowPositioning:window];
[self slideWindows:!isHidden fast:YES];
}
- (void)cachePosition {
cachedPosition = [[NSUserDefaults standardUserDefaults] stringForKey:@"VisorPosition"];
}
- (void)cacheScreen {
int screenIndex = [[NSUserDefaults standardUserDefaults]integerForKey:@"VisorScreen"];
NSArray* screens = [NSScreen screens];
if (!(screenIndex>0 && screenIndex<[screens count])) screenIndex = 0;
cachedScreen = [screens objectAtIndex:screenIndex];
LOG(@"Cached screen %d %@", screenIndex, cachedScreen);
}
// offset==0.0 means window is "hidden" above top screen edge
// offset==1.0 means window is visible right under top screen edge
- (void)placeWindow:(id)win offset:(float)offset {
NSScreen* screen=cachedScreen;
NSRect screenRect=[screen frame];
NSRect frame=[win frame];
int shift = 0; // see http://code.google.com/p/blacktree-visor/issues/detail?id=19
if (screen == [[NSScreen screens] objectAtIndex: 0]) shift = 21; // menu area
if ([cachedPosition hasPrefix:@"Top"]) {
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - round(offset*(NSHeight(frame)+shift));
}
if ([cachedPosition hasPrefix:@"Left"]) {
frame.origin.x = screenRect.origin.x - NSWidth(frame) + round(offset*NSWidth(frame));
}
if ([cachedPosition hasPrefix:@"Right"]) {
frame.origin.x = screenRect.origin.x + NSWidth(screenRect) - round(offset*NSWidth(frame));
}
if ([cachedPosition hasPrefix:@"Bottom"]) {
frame.origin.y = screenRect.origin.y - NSHeight(frame) + round(offset*NSHeight(frame));
}
[win setFrame:frame display:YES];
}
- (void)resetVisorWindowSize:(id)win {
LOG(@"resetVisorWindowSize");
// this block is needed to prevent "<NSSplitView>: the delegate <InterfaceController> was sent -splitView:resizeSubviewsWithOldSize: and left the subview frames in an inconsistent state" type of message
// http://cocoadev.com/forums/comments.php?DiscussionID=1092
// this issue is only on Snow Leopard (10.6), because it is newly using NSSplitViews
NSRect safeFrame;
safeFrame.origin.x = 0;
safeFrame.origin.y = 0;
safeFrame.size.width = 1;
safeFrame.size.height = 1;
[win setFrame:safeFrame display:NO];
// this is kind of a hack
// I'm using scripting API to update main window geometry according to profile settings
// note: this will resize all Terminal.app windows using "Visor" profile
// this should not be an issue because only Visor-ed window should use this profile
id profileManagerClass = NSClassFromString(@"TTProfileManager");
id profileManager = [profileManagerClass sharedProfileManager];
id visorProfile = [profileManager profileWithName:@"Visor"];
if (!visorProfile) {
LOG(@" ... unable to lookup Visor profile!");
return;
}
NSNumber* cols = [visorProfile scriptNumberOfColumns];
NSNumber* rows = [visorProfile scriptNumberOfRows];
[visorProfile setScriptNumberOfColumns:cols];
[visorProfile setScriptNumberOfRows:rows];
}
- (void)applyWindowPositioning:(id)win {
ignoreResizeNotifications = TRUE;
[self setupExposeTags:win];
NSScreen* screen = cachedScreen;
NSRect screenRect = [screen frame];
NSString* position = [[NSUserDefaults standardUserDefaults] stringForKey:@"VisorPosition"];
if (![position isEqualToString:lastPosition]) {
// note: cursor may jump during this operation, so do it only in rare cases when position changes
// for more info see http://github.com/darwin/visor/issues#issue/27
[self resetVisorWindowSize:win];
}
lastPosition = position;
LOG(@"applyWindowPositioning %@", position);
int shift = 0; // see http://code.google.com/p/blacktree-visor/issues/detail?id=19
if (screen == [[NSScreen screens] objectAtIndex: 0]) shift = 21; // menu area
if ([position isEqualToString:@"Top-Stretch"]) {
NSRect frame = [win frame];
frame.size.width = screenRect.size.width;
frame.origin.x = screenRect.origin.x;
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Top-Left"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x;
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Top-Right"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + NSWidth(screenRect) - NSWidth(frame);
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Top-Center"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + (NSWidth(screenRect)-NSWidth(frame))/2;
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Left-Stretch"]) {
NSRect frame = [win frame];
frame.size.height = screenRect.size.height - shift;
frame.origin.x = screenRect.origin.x - NSWidth(frame);
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - NSHeight(frame) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Left-Top"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x - NSWidth(frame);
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - NSHeight(frame) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Left-Bottom"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x - NSWidth(frame);
frame.origin.y = screenRect.origin.y;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Left-Center"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x - NSWidth(frame);
frame.origin.y = screenRect.origin.y + (NSHeight(screenRect)-NSHeight(frame))/2;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Right-Stretch"]) {
NSRect frame = [win frame];
frame.size.height = screenRect.size.height - shift;
frame.origin.x = screenRect.origin.x + NSWidth(screenRect);
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - NSHeight(frame) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Right-Top"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + NSWidth(screenRect);
frame.origin.y = screenRect.origin.y + NSHeight(screenRect) - NSHeight(frame) - shift;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Right-Bottom"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + NSWidth(screenRect);
frame.origin.y = screenRect.origin.y;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Right-Center"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + NSWidth(screenRect);
frame.origin.y = screenRect.origin.y + (NSHeight(screenRect)-NSHeight(frame))/2;
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Bottom-Stretch"]) {
NSRect frame = [win frame];
frame.size.width = screenRect.size.width;
frame.origin.x = screenRect.origin.x;
frame.origin.y = screenRect.origin.y - NSHeight(frame);
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Bottom-Left"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x;
frame.origin.y = screenRect.origin.y - NSHeight(frame);
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Bottom-Right"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + NSWidth(screenRect) - NSWidth(frame);
frame.origin.y = screenRect.origin.y - NSHeight(frame);
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Bottom-Center"]) {
NSRect frame = [win frame];
frame.origin.x = screenRect.origin.x + (NSWidth(screenRect)-NSWidth(frame))/2;
frame.origin.y = screenRect.origin.y - NSHeight(frame);
[win setFrame:frame display:YES];
}
if ([position isEqualToString:@"Full Screen"]) {
NSRect frame = [win frame];
frame.size.width = screenRect.size.width;
frame.size.height = screenRect.size.height - shift;
frame.origin.x = screenRect.origin.x;
frame.origin.y = screenRect.origin.y;
[win setFrame:frame display:YES];
}
ignoreResizeNotifications = FALSE;
}
- (void)storePreviouslyActiveApp {
LOG(@"storePreviouslyActiveApp");
if (!runningApplicationClass) {
// 10.5 path
NSDictionary *activeAppDict = [[NSWorkspace sharedWorkspace] activeApplication];
previouslyActiveAppPath = nil;
if ([[activeAppDict objectForKey:@"NSApplicationBundleIdentifier"] compare:@"com.apple.Terminal"]) {
previouslyActiveAppPath = [[NSString alloc] initWithString:[activeAppDict objectForKey:@"NSApplicationPath"]];
}
LOG(@" (10.5) -> %@", previouslyActiveAppPath);
} else {
// 10.6+ path
NSDictionary *activeAppDict = [[NSWorkspace sharedWorkspace] activeApplication];
previouslyActiveAppPID = nil;
if ([[activeAppDict objectForKey:@"NSApplicationBundleIdentifier"] compare:@"com.apple.Terminal"]) {
previouslyActiveAppPID = [activeAppDict objectForKey:@"NSApplicationProcessIdentifier"];
}
LOG(@" (10.6) -> %@", previouslyActiveAppPID);
}
}
- (void)restorePreviouslyActiveApp {
if (!runningApplicationClass) {
if (!previouslyActiveAppPath) return;
LOG(@"restorePreviouslyActiveApp %@", previouslyActiveAppPath);
// 10.5 path
// Visor crashes when trying to return focus to non-running application? (http://github.com/darwin/visor/issues#issue/12)
NSString* scriptSource = [[NSString alloc] initWithFormat:restoreAppAppleScriptSource, previouslyActiveAppPath];
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithSource:scriptSource];
[appleScript executeAndReturnError: &scriptError];
[appleScript release];
[scriptSource release];
previouslyActiveAppPath = nil;
} else {
// 10.6+ path
LOG(@"xrestorePreviouslyActiveApp %@", previouslyActiveAppPID);
if (!previouslyActiveAppPID) return;
LOG(@"restorePreviouslyActiveApp %@", previouslyActiveAppPID);
id app = [runningApplicationClass runningApplicationWithProcessIdentifier: [previouslyActiveAppPID intValue]];
if (app) {
LOG(@" ... activating %@", app);
[app activateWithOptions:0];
}
previouslyActiveAppPID = nil;
}
}
- (void)onReopenVisor {
bool showOnReopen = [[NSUserDefaults standardUserDefaults] boolForKey:@"VisorShowOnReopen"];
if (!showOnReopen) return;
[self showVisor:NO];
}
- (void)showVisor:(BOOL)fast {
if (!isHidden) return;
LOG(@"showVisor %d", fast);
isHidden = false;
[self updateStatusMenu];
[self cacheScreen]; // performs screen pointer caching at this point
[self cachePosition];
[self storePreviouslyActiveApp];
[NSApp activateIgnoringOtherApps:YES];
[window makeKeyAndOrderFront:self];
[window setHasShadow:YES];
[self applyWindowPositioning:window];
[window update];
[self slideWindows:1 fast:fast];
[window invalidateShadow];
[window update];
}
-(void)hideOnEscape {
LOG(@"hideOnEscape");
[self hideVisor:NO];
}
-(void)hideVisor:(BOOL)fast {
if (isHidden) return;
LOG(@"hideVisor %d", fast);
isHidden = true;
[self updateStatusMenu];
[window update];
[self slideWindows:0 fast:fast];
[window setHasShadow:NO];
[window invalidateShadow];
[window update];
}
#define SLIDE_EASING(x) sin(M_PI_2*(x))
#define ALPHA_EASING(x) (1.0f-(x))
#define SLIDE_DIRECTION(d,x) (d?(x):(1.0f-(x)))
#define ALPHA_DIRECTION(d,x) (d?(1.0f-(x)):(x))
- (void)slideWindows:(BOOL)direction fast:(bool)fast { // true == down
if (!fast) {
BOOL doSlide = [[NSUserDefaults standardUserDefaults]boolForKey:@"VisorUseSlide"];
BOOL doFade = [[NSUserDefaults standardUserDefaults]boolForKey:@"VisorUseFade"];
float animSpeed = [[NSUserDefaults standardUserDefaults]floatForKey:@"VisorAnimationSpeed"];
// animation loop
if (doFade || doSlide) {
if (!doSlide && direction) { // setup final slide position in case of no sliding
float offset = SLIDE_DIRECTION(direction, SLIDE_EASING(1));
[self placeWindow:window offset:offset];
}
if (!doFade && direction) { // setup final alpha state in case of no alpha
float alpha = ALPHA_DIRECTION(direction, ALPHA_EASING(1));
[window setAlphaValue: alpha];
}
NSTimeInterval t;
NSDate* date=[NSDate date];
while (animSpeed>(t=-[date timeIntervalSinceNow])) { // animation update loop
float k=t/animSpeed;
if (doSlide) {
float offset = SLIDE_DIRECTION(direction, SLIDE_EASING(k));
[self placeWindow:window offset:offset];
}
if (doFade) {
float alpha = ALPHA_DIRECTION(direction, ALPHA_EASING(k));
[window setAlphaValue:alpha];
}
usleep(5000); // 5ms
}
}
}
// apply final slide and alpha states
float offset = SLIDE_DIRECTION(direction, SLIDE_EASING(1));
[self placeWindow:window offset:offset];
float alpha = ALPHA_DIRECTION(direction, ALPHA_EASING(1));
[window setAlphaValue: alpha];
}
- (void)resignKey:(id)sender {
LOG(@"resignKey %@", sender);
isKey = false;
[self updateEscapeHotKeyRegistration];
if (!isPinned && !isMain && !isKey && !isHidden){
[self hideVisor:false];
}
}
- (void)resignMain:(id)sender {
LOG(@"resignMain %@", sender);
isMain = false;
if (!isPinned && !isMain && !isKey && !isHidden){
[self hideVisor:false];
}
}
- (void)becomeKey:(id)sender {
LOG(@"becomeKey %@", sender);
isKey = true;
[self updateEscapeHotKeyRegistration];
}
- (void)becomeMain:(id)sender {