-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
AppController.m
executable file
·1495 lines (1310 loc) · 56.8 KB
/
AppController.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
//
// AppController.m
// Flycut
//
// Flycut by Gennadiy Potapov and contributors. Based on Jumpcut by Steve Cook.
// Copyright 2011 General Arcade. All rights reserved.
//
// This code is open-source software subject to the MIT License; see the homepage
// at <https://github.com/TermiT/Flycut> for details.
//
// AppController owns and interacts with the FlycutOperator, providing a user
// interface and platform-specific mechanisms.
#import "AppController.h"
#import "SGHotKey.h"
#import "SGHotKeyCenter.h"
#import "SRRecorderCell.h"
#import "UKLoginItemRegistry.h"
#import "NSWindow+TrueCenter.h"
#import "NSWindow+ULIZoomEffect.h"
#import "MJCloudKitUserDefaultsSync/MJCloudKitUserDefaultsSync.h"
#import <ApplicationServices/ApplicationServices.h>
#import <CoreFoundation/CoreFoundation.h>
#import <ServiceManagement/ServiceManagement.h>
@implementation AppController
/// Determines, through a hack of sorts, if the app is running sandboxed. The SANDBOXING define has no direct connection to being sandboxed, but this method identifies the state by looking for a directory which will have at least eight path components if sandboxed and is quite unlikely to have that many if not sandboxed. Of course, if this doesn't work for your unique case, just do a custom build with this method returning NO.
+ (BOOL)isAppSandboxed {
// Get the Desktop directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory = [paths objectAtIndex:0];
return ((NSArray*)[desktopDirectory componentsSeparatedByString:@"/"]).count >= 8;
}
- (id)init
{
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:9],[NSNumber numberWithLong:1179648],nil] forKeys:[NSArray arrayWithObjects:@"keyCode",@"modifierFlags",nil]],
@"ShortcutRecorder mainHotkey",
[NSNumber numberWithInt:10],
@"displayNum",
[NSNumber numberWithInt:40],
@"displayLen",
[NSNumber numberWithInt:0],
@"menuIcon",
[NSNumber numberWithFloat:.25],
@"bezelAlpha",
[NSNumber numberWithBool:NO],
@"stickyBezel",
[NSNumber numberWithBool:NO],
@"wraparoundBezel",
[NSNumber numberWithBool:NO],// No by default
@"loadOnStartup",
[NSNumber numberWithBool:YES],
@"menuSelectionPastes",
// Flycut new options
[NSNumber numberWithFloat:500.0],
@"bezelWidth",
[NSNumber numberWithFloat:320.0],
@"bezelHeight",
[NSNumber numberWithBool:NO],
@"popUpAnimation",
[NSNumber numberWithBool:YES],
@"displayClippingSource",
[NSNumber numberWithBool:NO],
@"saveForgottenClippings",
#ifdef SANDBOXING
[NSNumber numberWithBool:NO],
#else
[NSNumber numberWithBool:YES],
#endif
@"saveForgottenFavorites",
[NSNumber numberWithBool:NO],
@"suppressAccessibilityAlert",
nil]];
/* For testing, the ability to force initial values of the sync settings:
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO]
forKey:@"syncSettingsViaICloud"];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO]
forKey:@"syncClippingsViaICloud"];*/
settingsSyncList = @[@"displayNum",
@"displayLen",
@"menuIcon",
@"bezelAlpha",
@"stickyBezel",
@"wraparoundBezel",
@"loadOnStartup",
@"menuSelectionPastes",
@"bezelWidth",
@"bezelHeight",
@"popUpAnimation",
@"displayClippingSource",
@"saveForgottenClippings",
@"saveForgottenFavorites",
@"suppressAccessibilityAlert",
];
[settingsSyncList retain];
menuQueue = dispatch_queue_create(@"com.Flycut.menuUpdateQueue", DISPATCH_QUEUE_SERIAL);
return [super init];
}
- (void)registerOrDeregisterICloudSync
{
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"syncSettingsViaICloud"] ) {
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationChanges forTarget:self];
[[MJCloudKitUserDefaultsSync sharedSync] addNotificationFor:MJSyncNotificationChanges withSelector:@selector(checkPreferencesChanges:) withTarget: self];
// Not registering for conflict notifications, since we just sync settings, and if the settings are conflictingly adjusted simultaneously on two systems there is nothing to say which setting is better.
[[MJCloudKitUserDefaultsSync sharedSync] startWithKeyMatchList:settingsSyncList
withContainerIdentifier:kiCloudId];
}
else {
[[MJCloudKitUserDefaultsSync sharedSync] stopForKeyMatchList:settingsSyncList];
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationChanges forTarget:self];
}
[flycutOperator registerOrDeregisterICloudSync];
}
- (void)showAccessibilityAlert {
BOOL suppressAlert = [[NSUserDefaults standardUserDefaults] boolForKey:@"suppressAccessibilityAlert"];
NSDictionary* options = @{(id) (kAXTrustedCheckOptionPrompt): @NO};
if (!suppressAlert && AXIsProcessTrustedWithOptions != NULL && !AXIsProcessTrustedWithOptions((CFDictionaryRef) (options))) {
NSAlert *alert = [NSAlert alertWithMessageText:@"Flycut" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"For correct functioning of the app please tick Flycut in Accessibility apps list"];
alert.showsSuppressionButton = YES;
[alert runModal];
if (alert.suppressionButton.state == NSOnState) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES]
forKey:@"suppressAccessibilityAlert"];
}
NSString *urlString = @"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:urlString]];
}
}
- (void)showOldOSXAlert {
// FIXME: Should ask Gennadii if the "#ifdef SANDBOXING" should be removed and replaced with "if (![AppController isAppSandboxed]) { return; }"
#ifdef SANDBOXING
NSOperatingSystemVersion ver = [[NSProcessInfo processInfo] operatingSystemVersion];
if (ver.majorVersion == 10 && ver.minorVersion <= 13) {
BOOL suppressAlert = [[NSUserDefaults standardUserDefaults] boolForKey:@"suppressOldOSXAlert"];
if (!suppressAlert) {
NSAlert *alert = [NSAlert alertWithMessageText:@"Flycut" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"Unfortunatly due to some app sandbox security restrictions from Apple Flycut may not correctly function on MacOSX 10.13 or lower. You can download non sandboxed version here: https://github.com/TermiT/Flycut/releases"];
alert.showsSuppressionButton = YES;
[alert runModal];
if (alert.suppressionButton.state == NSOnState) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES]
forKey:@"suppressOldOSXAlert"];
}
}
}
#endif
}
- (void)awakeFromNib
{
[self buildAppearancesPreferencePanel];
// We no longer get autosave from ShortcutRecorder, so let's set the recorder by hand
if ( [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"ShortcutRecorder mainHotkey"] ) {
[mainRecorder setKeyCombo:SRMakeKeyCombo([[[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"ShortcutRecorder mainHotkey"] objectForKey:@"keyCode"] intValue],
[[[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"ShortcutRecorder mainHotkey"] objectForKey:@"modifierFlags"] intValue] )
];
};
// Initialize the FlycutOperator
flycutOperator = [[FlycutOperator alloc] init];
flycutOperator.delegate = self;
[flycutOperator setClippingsStoreDelegate:self];
[flycutOperator setFavoritesStoreDelegate:self];
[flycutOperator awakeFromNibDisplaying:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"]
withDisplayLength:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayLen"]
withSaveSelector:@selector(savePreferencesOnDict:)
forTarget:self];
[bezel setColor:NO];
// Set up the bezel window
[self setupBezel:nil];
// Set up the bezel date formatter
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE, MMMM dd 'at' h:mm a"];
// Create our pasteboard interface
jcPasteboard = [NSPasteboard generalPasteboard];
[jcPasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
pbCount = [[NSNumber numberWithInt:[jcPasteboard changeCount]] retain];
// Build the statusbar menu
statusItem = [[[NSStatusBar systemStatusBar]
statusItemWithLength:NSVariableStatusItemLength] retain];
[statusItem setHighlightMode:YES];
[self switchMenuIconTo: [[NSUserDefaults standardUserDefaults] integerForKey:@"menuIcon"]];
[statusItem setMenu:jcMenu];
[jcMenu setDelegate:self];
jcMenuBaseItemsCount = [[[[jcMenu itemArray] reverseObjectEnumerator] allObjects] count];
[statusItem setEnabled:YES];
// If our preferences indicate that we are saving, we may have loaded the dictionary from the
// saved plist and should update the menu.
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 1 ) {
[self updateMenu];
}
// Build our listener timer
NSDate *oneSecondFromNow = [NSDate dateWithTimeIntervalSinceNow:1.0];
pollPBTimer = [[NSTimer alloc] initWithFireDate:oneSecondFromNow
interval:(1.0)
target:self
selector:@selector(pollPB:)
userInfo:nil
repeats:YES];
// Assign it to NSRunLoopCommonModes so that it will still poll while the menu is open. Using a simple NSTimer scheduledTimerWithTimeInterval: would result in polling that stops while the menu is active. In the past this was okay but with Universal Clipboard a new clipping an arrive while the user has the menu open.
[[NSRunLoop currentRunLoop] addTimer:pollPBTimer forMode:NSRunLoopCommonModes];
// Finish up
srTransformer = [[[SRKeyCodeTransformer alloc] init] retain];
pbBlockCount = [[NSNumber numberWithInt:0] retain];
[pollPBTimer fire];
// The load-on-startup check can be really slow, so this will be dispatched out so our thread isn't blocked.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// FIXME: Should ask Gennadii if the "#ifdef SANDBOXING" should be removed and replaced with "if ([AppController isAppSandboxed])"
#ifdef SANDBOXING
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bundleIdentifier == %@", kFlycutHelperId];
NSArray *helperApp = [[[NSWorkspace sharedWorkspace] runningApplications] filteredArrayUsingPredicate:predicate];
BOOL helperLaunched = ([helperApp count] != 0);
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:helperLaunched]
forKey:@"loadOnStartup"];
#else
// This can take five seconds, perhaps more, so do it in the background instead of holding up opening of the preference panel.
int checkLoginRegistry = [UKLoginItemRegistry indexForLoginItemWithPath:[[NSBundle mainBundle] bundlePath]];
if ( checkLoginRegistry >= 1 ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES]
forKey:@"loadOnStartup"];
} else {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO]
forKey:@"loadOnStartup"];
}
#endif
});
[self registerOrDeregisterICloudSync];
[NSApp activateIgnoringOtherApps: YES];
// Check if the app has Accessibility permission
[self showAccessibilityAlert];
[self showOldOSXAlert];
}
-(void)savePreferencesOnDict:(NSMutableDictionary *)saveDict
{
[saveDict setObject:[NSNumber numberWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayLen"]]
forKey:@"displayLen"];
[saveDict setObject:[NSNumber numberWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"]]
forKey:@"displayNum"];
}
-(void)menuWillOpen:(NSMenu *)menu
{
NSEvent *event = [NSApp currentEvent];
if([event modifierFlags] & NSAlternateKeyMask) {
[menu cancelTracking];
bool disableStore = [self toggleMenuIconDisabled];
if (!disableStore)
{
// Update the pbCount so we don't enable and have it immediately copy the thing the user was trying to avoid.
// Code copied from pollPB, which is disabled at this point, so the "should be okay" should still be okay.
// Reload pbCount with the current changeCount
// Probably poor coding technique, but pollPB should be the only thing messing with pbCount, so it should be okay
[pbCount release];
pbCount = [[NSNumber numberWithInt:[jcPasteboard changeCount]] retain];
}
[flycutOperator setDisableStoreTo:disableStore];
}
else
{
// We need to do a little trick to get the search box functional. Figure out what is currently active.
NSString *currRunningApp = @"";
NSRunningApplication *currApp = nil;
for (currApp in [[NSWorkspace sharedWorkspace] runningApplications])
if ([currApp isActive])
{
currRunningApp = [currApp localizedName];
break;
}
if ( [currRunningApp rangeOfString:@"Flycut"].location == NSNotFound )
{
// We haven't activated Flycut yet.
currentRunningApplication = [currApp retain]; // Remember what app we came from.
menuOpenEvent = [event retain]; // So we can send it again to open the menu.
[menu cancelTracking]; // Prevent the menu from displaying, since activateIgnoringOtherApps would close it anyway.
[NSApp activateIgnoringOtherApps: YES]; // Required to make the search field firstResponder any good.
[self performSelector:@selector(reopenMenu) withObject:nil afterDelay:0.2 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; // Because we really do want the menu open.
}
else
{
// Flycut is now active, so set the first responder once the menu opens.
[self performSelector:@selector(activateSearchBox) withObject:nil afterDelay:0.2 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
}
}
-(void)menuDidClose:(NSMenu *)menu
{
// The method the menu triggers may clear currentRunningApplication, but that method won't be called until after the menu has closed. Queue a call to the reactivate method that will come up after the method resulting from the menu.
[self performSelector:@selector(reactivateCurrentRunningApplication) withObject:nil afterDelay:0.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
-(void)reactivateCurrentRunningApplication
{
// Return focus to application that the menu search box stole from.
if ( nil != currentRunningApplication )
{
// But only if the bezel hasn't opened since the menu closed. This happens if the bezel hotkey is pressed while the menu is open. The bezel won't display until the menu closes, but will then display.
if (!isBezelDisplayed)
[currentRunningApplication activateWithOptions: NSApplicationActivateIgnoringOtherApps];
// Paste from the bezel in this scenario works fine, so release and forget this resource in both cases.
[currentRunningApplication release];
currentRunningApplication = nil;
}
}
-(bool)toggleMenuIconDisabled
{
// Toggles the "disabled" look of the menu icon. Returns if the icon looks disabled or not, allowing the caller to decide if anything is actually being disabled or if they just wanted the icon to be a status display.
if (nil == statusItemText)
{
statusItemText = [statusItem title];
statusItemImage = [statusItem image];
[statusItem setTitle: @""];
[statusItem setImage: [NSImage imageNamed:@"com.generalarcade.flycut.xout.16.png"]];
return true;
}
else
{
[statusItem setTitle: statusItemText];
[statusItem setImage: statusItemImage];
statusItemText = nil;
statusItemImage = nil;
}
return false;
}
- (void)reopenMenu
{
[NSApp sendEvent:menuOpenEvent];
[menuOpenEvent release];
menuOpenEvent = nil;
}
- (void)activateSearchBox
{
menuFirstResponder = [[searchBox window] firstResponder]; // So we can return control to normal menu function if the user presses an arrow key.
[[searchBox window] makeFirstResponder:searchBox]; // So the search box works.
}
-(IBAction) activateAndOrderFrontStandardAboutPanel:(id)sender
{
[currentRunningApplication release];
currentRunningApplication = nil; // So it doesn't get pulled foreground atop the about panel.
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
[[NSApplication sharedApplication] orderFrontStandardAboutPanel:sender];
}
-(IBAction) setBezelAlpha:(id)sender
{
// In a masterpiece of poorly-considered design--because I want to eventually
// allow users to select from a variety of bezels--I've decided to create the
// bezel programatically, meaning that I have to go through AppController as
// a cutout to allow the user interface to interact w/the bezel.
[bezel setAlpha:[sender floatValue]];
}
-(IBAction) setBezelWidth:(id)sender
{
NSSize bezelSize = NSMakeSize([sender floatValue], bezel.frame.size.height);
NSRect windowFrame = NSMakeRect( 0, 0, bezelSize.width, bezelSize.height);
[bezel setFrame:windowFrame display:NO];
[bezel trueCenter];
}
-(IBAction) setBezelHeight:(id)sender
{
NSSize bezelSize = NSMakeSize(bezel.frame.size.width, [sender floatValue]);
NSRect windowFrame = NSMakeRect( 0, 0, bezelSize.width, bezelSize.height);
[bezel setFrame:windowFrame display:NO];
[bezel trueCenter];
}
-(IBAction) setupBezel:(id)sender
{
NSRect windowFrame = NSMakeRect(0, 0,
[[NSUserDefaults standardUserDefaults] floatForKey:@"bezelWidth"],
[[NSUserDefaults standardUserDefaults] floatForKey:@"bezelHeight"]);
bezel = [[BezelWindow alloc] initWithContentRect:windowFrame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO
showSource:[[NSUserDefaults standardUserDefaults] boolForKey:@"displayClippingSource"]];
[bezel trueCenter];
[bezel setDelegate:self];
}
-(IBAction) switchMenuIcon:(id)sender
{
[self switchMenuIconTo: [sender indexOfSelectedItem]];
}
-(void) switchMenuIconTo:(int)number
{
if (number == 1 ) {
[statusItem setTitle:@""];
[statusItem setImage:[NSImage imageNamed:@"com.generalarcade.flycut.black.16.png"]];
} else if (number == 2 ) {
[statusItem setImage:nil];
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2704]];
} else if ( number == 3 ) {
[statusItem setImage:nil];
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2702]];
} else {
[statusItem setTitle:@""];
[statusItem setImage:[NSImage imageNamed:@"com.generalarcade.flycut.16.png"]];
}
}
-(NSDictionary*) checkPreferencesChanges:(NSDictionary*)changes
{
if ( [changes valueForKey:@"rememberNum"] )
[self checkRememberNumPref:[[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"]
forPrimaryStore:YES];
if ( [changes valueForKey:@"favoritesRememberNum"] )
[self checkFavoritesRememberNumPref:[[NSUserDefaults standardUserDefaults] integerForKey:@"favoritesRememberNum"]];
return nil;
}
-(IBAction) setRememberNumPref:(id)sender
{
[self checkRememberNumPref:[sender intValue] forPrimaryStore:YES];
}
-(int) checkRememberNumPref:(int)newRemember forPrimaryStore:(BOOL) isPrimaryStore
{
int oldRemember = [flycutOperator rememberNum];
int setRemember = [flycutOperator setRememberNum:newRemember forPrimaryStore:YES];
if ( isPrimaryStore )
{
if ( setRemember == oldRemember )
{
[self updateMenu];
}
else if ( setRemember < oldRemember )
{
// Trim down the number displayed in the menu if it is greater than the new
// number to remember.
if ( isPrimaryStore ) {
if ( setRemember < [[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"] ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:setRemember]
forKey:@"displayNum"];
[self updateMenu];
}
}
}
}
}
-(IBAction) setFavoritesRememberNumPref:(id)sender
{
[self checkFavoritesRememberNumPref:[sender intValue]];
}
-(void) checkFavoritesRememberNumPref:(int)newRemember
{
[flycutOperator switchToFavoritesStore];
[self checkRememberNumPref:newRemember forPrimaryStore:NO];
[flycutOperator restoreStashedStore];
}
-(IBAction) setDisplayNumPref:(id)sender
{
[self updateMenu];
}
-(NSTextField*) preferencePanelSliderLabelForText:(NSString*)text aligned:(NSTextAlignment)alignment andFrame:(NSRect)frame
{
NSTextField *newLabel = [[NSTextField alloc] initWithFrame:frame];
newLabel.editable = NO;
[newLabel setAlignment:alignment];
[newLabel setBordered:NO];
[newLabel setDrawsBackground:NO];
[newLabel setFont:[NSFont labelFontOfSize:10]];
[newLabel setStringValue:text];
return newLabel;
}
-(NSBox*) preferencePanelSliderRowForText:(NSString*)title withTicks:(int)ticks minText:(NSString*)minText maxText:(NSString*)maxText minValue:(double)min maxValue:(double)max frameMaxY:(int)frameMaxY binding:(NSString*)keyPath action:(SEL)action
{
NSRect panelFrame = [appearancePanel frame];
if ( frameMaxY < 0 )
frameMaxY = panelFrame.size.height-8;
int height = 63;
NSBox *newRow = [[NSBox alloc] initWithFrame:NSMakeRect(0, frameMaxY-height, panelFrame.size.width-10, height)];
[newRow setTitlePosition:NSNoTitle];
[newRow setBorderType:NSNoBorder];
[newRow addSubview:[self preferencePanelSliderLabelForText:title aligned:NSNaturalTextAlignment andFrame:NSMakeRect(8, 25, 100, 25)]];
[newRow addSubview:[self preferencePanelSliderLabelForText:minText aligned:NSLeftTextAlignment andFrame:NSMakeRect(113, 0, 151, 25)]];
[newRow addSubview:[self preferencePanelSliderLabelForText:maxText aligned:NSRightTextAlignment andFrame:NSMakeRect(109+310-151-4, 0, 151, 25)]];
NSSlider *newControl = [[NSSlider alloc] initWithFrame:NSMakeRect(109, 29, 310, 25)];
newControl.numberOfTickMarks=ticks;
[newControl setMinValue:min];
[newControl setMaxValue:max];
[self setBinding:@"value" forKey:keyPath andOrAction:action on:newControl];
[newRow addSubview:newControl];
return newRow;
}
-(NSBox*) preferencePanelPopUpRowForText:(NSString*)title items:(NSArray*)items frameMaxY:(int)frameMaxY binding:(NSString*)keyPath action:(SEL)action
{
NSRect panelFrame = [appearancePanel frame];
if ( frameMaxY < 0 )
frameMaxY = panelFrame.size.height-8;
int height = 40;
NSBox *newRow = [[NSBox alloc] initWithFrame:NSMakeRect(0, frameMaxY-height+5, panelFrame.size.width-10, height)];
[newRow setTitlePosition:NSNoTitle];
[newRow setBorderType:NSNoBorder];
[newRow addSubview:[self preferencePanelSliderLabelForText:title aligned:NSNaturalTextAlignment andFrame:NSMakeRect(8, -2, 100, 25)]];
NSPopUpButton *newControl = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(109, 4, 150, 25) pullsDown:NO];
[newControl addItemsWithTitles:items];
[self setBinding:@"selectedIndex" forKey:keyPath andOrAction:action on:newControl];
[newRow addSubview:newControl];
return newRow;
}
-(NSBox*) preferencePanelCheckboxRowForText:(NSString*)title frameMaxY:(int)frameMaxY binding:(NSString*)keyPath action:(SEL)action
{
NSRect panelFrame = [appearancePanel frame];
if ( frameMaxY < 0 )
frameMaxY = panelFrame.size.height-8;
int height = 40;
NSBox *newRow = [[NSBox alloc] initWithFrame:NSMakeRect(0, frameMaxY-height+5, panelFrame.size.width-10, height)];
[newRow setTitlePosition:NSNoTitle];
[newRow setBorderType:NSNoBorder];
NSButton *newControl = [[NSButton alloc] initWithFrame:NSMakeRect(8, 4, panelFrame.size.width-20, 25)];
[newControl setButtonType:NSSwitchButton];
[newControl setTitle:title];
[self setBinding:@"value" forKey:keyPath andOrAction:action on:newControl];
[newRow addSubview:newControl];
return newRow;
}
-(void)setBinding:(NSString*)binding forKey:(NSString*)keyPath andOrAction:(SEL)action on:(NSControl*)newControl
{
[newControl bind:binding
toObject:[NSUserDefaults standardUserDefaults]
withKeyPath:keyPath
options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:@"NSContinuouslyUpdatesValue"]];
if ( nil != action )
{
[newControl setTarget:self];
[newControl setAction:action];
}
}
-(void) buildAppearancesPreferencePanel
{
NSRect screenFrame = [[NSScreen mainScreen] frame];
int nextYMax = -1;
NSView *row = [self preferencePanelSliderRowForText:@"Bezel transparency"
withTicks:16
minText:@"Lighter"
maxText:@"Darker"
minValue:0.1
maxValue:0.9
frameMaxY:nextYMax
binding:@"bezelAlpha"
action:@selector(setBezelAlpha:)];
[appearancePanel addSubview:row];
nextYMax = row.frame.origin.y;
row = [self preferencePanelSliderRowForText:@"Bezel width"
withTicks:50
minText:@"Smaller"
maxText:@"Bigger"
minValue:200
maxValue:screenFrame.size.width
frameMaxY:nextYMax
binding:@"bezelWidth"
action:@selector(setBezelWidth:)];
[appearancePanel addSubview:row];
nextYMax = row.frame.origin.y;
row = [self preferencePanelSliderRowForText:@"Bezel height"
withTicks:50
minText:@"Smaller"
maxText:@"Bigger"
minValue:200
maxValue:screenFrame.size.height
frameMaxY:nextYMax
binding:@"bezelHeight"
action:@selector(setBezelHeight:)];
[appearancePanel addSubview:row];
nextYMax = row.frame.origin.y;
row = [self preferencePanelPopUpRowForText:@"Menu item icon"
items:[NSArray arrayWithObjects:
@"Flycut icon",
@"Black Flycut icon",
@"White scissors",
@"Black scissors",nil]
frameMaxY:nextYMax
binding:@"menuIcon"
action:@selector(switchMenuIcon:)];
[appearancePanel addSubview:row];
nextYMax = row.frame.origin.y;
// row = [self preferencePanelCheckboxRowForText:@"Animate bezel appearance"
// frameMaxY:nextYMax
// binding:@"popUpAnimation"
// action:nil];
// [appearancePanel addSubview:row];
// nextYMax = row.frame.origin.y;
row = [self preferencePanelCheckboxRowForText:@"Show clipping source app and time"
frameMaxY:nextYMax
binding:@"displayClippingSource"
action:@selector(setupBezel:)];
[appearancePanel addSubview:row];
nextYMax = row.frame.origin.y;
#ifdef SANDBOXING
// Hide the Save Clippings preferences. These work fine when sandboxed. They just save to somwehere under ~/Library/Containers. If SANDBOXING isn't set, automatic saving of forgotten clippings will go somewhere under ~/Library/Containers while manual saving (s or S in the bezel) will open an NSSavePanel to prompt the user to pick.
forgottenItemLabel.hidden = YES;
forgottenClippingsCheckbox.hidden = YES;
forgottenFavoritesCheckbox.hidden = YES;
savingSectionLabel.hidden = YES;
saveToLocationButton.hidden = YES;
autoSaveToLocationButton.hidden = YES;
saveFromBezelToLabel.hidden = YES;
#endif
if ([AppController isAppSandboxed]) {
// Saving to a prior-selected location while sandboxed would be unpleasant, so these really should be disabled always when sandboxed but can still show where the saves happen so the user knows what to expect.
saveToLocationButton.enabled = NO;
[saveToLocationButton setTitle:@"Ask User"];
autoSaveToLocationButton.enabled = NO;
[autoSaveToLocationButton setTitle:@"App Sandbox"];
}
}
-(IBAction) showPreferencePanel:(id)sender
{
[currentRunningApplication release];
currentRunningApplication = nil; // So it doesn't get pulled foreground atop the preference panel.
if ([prefsPanel respondsToSelector:@selector(setCollectionBehavior:)])
[prefsPanel setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
[NSApp activateIgnoringOtherApps: YES];
[prefsPanel makeKeyAndOrderFront:self];
NSString *fileRoot = [[NSBundle mainBundle] pathForResource:@"acknowledgements" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:fileRoot
encoding:NSUTF8StringEncoding
error:NULL];
[acknowledgementsView setString:contents];
if (![AppController isAppSandboxed]) {
NSURL* saveToLocation = [[NSUserDefaults standardUserDefaults] URLForKey:@"saveToLocation"];
if (saveToLocation) {
[saveToLocationButton setTitle:[saveToLocation lastPathComponent]];
}
NSURL* autoSaveToLocation = [[NSUserDefaults standardUserDefaults] URLForKey:@"autoSaveToLocation"];
if (autoSaveToLocation) {
[autoSaveToLocationButton setTitle:[autoSaveToLocation lastPathComponent]];
}
}
[flycutOperator willShowPreferences];
}
-(IBAction)toggleLoadOnStartup:(id)sender {
// Since the control in Interface Builder is bound to User Defaults and sends this action, this method is called after User Defaults already reflects the newly-selected state and merely conveys that value to the relevant mechanisms rather than acting to negate the User Defaults state.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"loadOnStartup"] ) {
// FIXME: Should ask Gennadii if the "#ifdef SANDBOXING" should be removed and replaced with "if ([AppController isAppSandboxed])"
#ifdef SANDBOXING
SMLoginItemSetEnabled((__bridge CFStringRef)kFlycutHelperId, YES);
#else
[UKLoginItemRegistry addLoginItemWithPath:[[NSBundle mainBundle] bundlePath] hideIt:NO];
#endif
} else {
// FIXME: Should ask Gennadii if the "#ifdef SANDBOXING" should be removed and replaced with "if ([AppController isAppSandboxed])"
#ifdef SANDBOXING
SMLoginItemSetEnabled((__bridge CFStringRef)kFlycutHelperId, NO);
#else
[UKLoginItemRegistry removeLoginItemWithPath:[[NSBundle mainBundle] bundlePath]];
#endif
}
}
- (void)restoreStashedStoreAndUpdate
{
if ([flycutOperator restoreStashedStore])
{
[bezel setColor:NO];
[self updateBezel];
}
}
- (void)pasteFromStack
{
NSString *content = [flycutOperator getPasteFromStackPosition];
if ( nil != content ) {
[self addClipToPasteboard:content];
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
[self performSelector:@selector(fakeCommandV) withObject:nil afterDelay:0.2];
} else {
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
}
[self restoreStashedStoreAndUpdate];
}
- (void)moveItemAtStackPositionToTopOfStack
{
if ( [flycutOperator stackPositionIsInBounds] ) {
[self pasteIndexAndUpdate: [flycutOperator stackPosition]];
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
} else {
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
}
}
- (void)pasteIndexAndUpdate:(int) position {
// If there is an active search, we need to map the menu index to the stack position.
NSString* search = [searchBox stringValue];
if ( nil != search && 0 != search.length )
{
NSArray *mapping = [flycutOperator previousIndexes:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"] containing:search];
position = [mapping[position] intValue];
}
NSString *content = [flycutOperator getPasteFromIndex: position];
if ( nil != content )
{
[self addClipToPasteboard:content];
[self updateMenu];
}
}
- (void)metaKeysReleased
{
if ( ! isBezelPinned ) {
[self pasteFromStack];
}
}
- (void)windowDidResignKey:(NSNotification *)notification {
if ( isBezelPinned ) {
[self hideApp];
}
}
-(void)fakeKey:(NSNumber*) keyCode withCommandFlag:(BOOL) setFlag
/*" +fakeKey synthesizes keyboard events. "*/
{
CGEventSourceRef sourceRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
if (!sourceRef)
{
DLog(@"No event source");
return;
}
CGKeyCode veeCode = (CGKeyCode)[keyCode intValue];
CGEventRef eventDown = CGEventCreateKeyboardEvent(sourceRef, veeCode, true);
if ( setFlag )
CGEventSetFlags(eventDown, kCGEventFlagMaskCommand|0x000008); // some apps want bit set for one of the command keys
CGEventRef eventUp = CGEventCreateKeyboardEvent(sourceRef, veeCode, false);
CGEventPost(kCGHIDEventTap, eventDown);
CGEventPost(kCGHIDEventTap, eventUp);
CFRelease(eventDown);
CFRelease(eventUp);
CFRelease(sourceRef);
}
/*" +fakeCommandV synthesizes keyboard events for Cmd-v Paste shortcut. "*/
-(void)fakeCommandV { [self fakeKey:[srTransformer reverseTransformedValue:@"V"] withCommandFlag:TRUE]; }
/*" +fakeDownArrow synthesizes keyboard events for the down-arrow key. "*/
-(void)fakeDownArrow { [self fakeKey:@125 withCommandFlag:FALSE]; }
/*" +fakeUpArrow synthesizes keyboard events for the up-arrow key. "*/
-(void)fakeUpArrow { [self fakeKey:@126 withCommandFlag:FALSE]; }
// Perform the search and display updated results when the user types.
-(void)controlTextDidChange:(NSNotification *)aNotification
{
NSString* search = [searchBox stringValue];
[self updateMenuContaining:search];
}
// Perform the search and display updated results when the search field performs its action.
-(IBAction)searchItems:(id)sender
{
NSString* search = [searchBox stringValue];
[self updateMenuContaining:search];
}
// Catch keystrokes in the search field and look for arrows.
-(BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
{
if( commandSelector == @selector(moveUp:) )
{
[[searchBox window] makeFirstResponder:menuFirstResponder];
[self fakeUpArrow];
return YES; // We handled this command; don't pass it on
}
if( commandSelector == @selector(moveDown:) )
{
[[searchBox window] makeFirstResponder:menuFirstResponder];
[self fakeDownArrow];
return YES; // We handled this command; don't pass it on
}
return NO; // Default handling of the command
}
-(void)pollPB:(NSTimer *)timer
{
NSString *type = [jcPasteboard availableTypeFromArray:[NSArray arrayWithObject:NSStringPboardType]];
if ( [pbCount intValue] != [jcPasteboard changeCount] && ![flycutOperator storeDisabled] ) {
// Reload pbCount with the current changeCount
// Probably poor coding technique, but pollPB should be the only thing messing with pbCount, so it should be okay
[pbCount release];
pbCount = [[NSNumber numberWithInt:[jcPasteboard changeCount]] retain];
if ( type != nil ) {
NSRunningApplication *currRunningApp = nil;
for (NSRunningApplication *currApp in [[NSWorkspace sharedWorkspace] runningApplications])
if ([currApp isActive])
currRunningApp = currApp;
bool largeCopyRisk = nil != currRunningApp && [[currRunningApp localizedName] rangeOfString:@"Remote Desktop Connection"].location != NSNotFound;
// Microsoft's Remote Desktop Connection has an issue with large copy actions, which appears to be in the time it takes to transer them over the network. The copy starts being registered with OS X prior to completion of the transfer, and if the active application changes during the transfer the copy will be lost. Indicate this time period by toggling the menu icon at the beginning of all RDC trasfers and back at the end. Apple's Screen Sharing does not demonstrate this problem.
if (largeCopyRisk)
[self toggleMenuIconDisabled];
// In case we need to do a status visual, this will be dispatched out so our thread isn't blocked.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// This operation blocks until the transfer is complete, though it was was here before the RDC issue was discovered. Convenient.
NSString *contents = [jcPasteboard stringForType:type];
// Toggle back if dealing with the RDC issue.
if (largeCopyRisk)
[self toggleMenuIconDisabled];
if ( contents == nil || [flycutOperator shouldSkip:contents ofType:[jcPasteboard availableTypeFromArray:[NSArray arrayWithObject:NSStringPboardType]] fromAvailableTypes:[jcPasteboard types]] ) {
DLog(@"Contents: Empty or skipped");
} else if ( ! [pbCount isEqualTo:pbBlockCount] ) {
[flycutOperator addClipping:contents ofType:type fromApp:[currRunningApp localizedName] withAppBundleURL:currRunningApp.bundleURL.path target:self clippingAddedSelector:@selector(updateMenu)];
}
});
}
}
}
- (void)processBezelKeyDown:(NSEvent *)theEvent {
int newStackPosition;
// AppControl should only be getting these directly from bezel via delegation
if ([theEvent type] == NSKeyDown) {
if ([theEvent keyCode] == [mainRecorder keyCombo].code ) {
if ([theEvent modifierFlags] & NSShiftKeyMask) [self stackUp];
else [self stackDown];
return;
}
unichar pressed = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
NSUInteger modifiers = [theEvent modifierFlags];
switch (pressed) {
case 0x1B:
[self hideApp];
break;
case 0xD: // Enter or Return
[self pasteFromStack];
break;
case 0x3:
[self moveItemAtStackPositionToTopOfStack];
break;
case 0x2C: // Comma
if ( modifiers & NSCommandKeyMask ) {
[self showPreferencePanel:nil];
}
break;
case NSUpArrowFunctionKey:
case NSLeftArrowFunctionKey:
case 0x6B: // k
[self stackUp];
break;
case NSDownArrowFunctionKey:
case NSRightArrowFunctionKey:
case 0x6A: // j
[self stackDown];
break;
case NSHomeFunctionKey:
if ( [flycutOperator setStackPositionToFirstItem] ) {
[self updateBezel];
}
break;
case NSEndFunctionKey:
if ( [flycutOperator setStackPositionToLastItem] ) {
[self updateBezel];
}
break;
case NSPageUpFunctionKey:
if ( [flycutOperator setStackPositionToTenMoreRecent] ) {
[self updateBezel];
}
break;
case NSPageDownFunctionKey:
if ( [flycutOperator setStackPositionToTenLessRecent] ) {
[self updateBezel];
}
break;
case NSBackspaceCharacter:
case NSDeleteCharacter:
if ( [flycutOperator clearItemAtStackPosition] ) {
[self updateBezel];
[self updateMenu];
}
break;
case NSDeleteFunctionKey: break;
case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // Numeral
case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
// We'll currently ignore the possibility that the user wants to do something with shift.
// First, let's set the new stack count to "10" if the user pressed "0"
newStackPosition = pressed == 0x30 ? 9 : [[NSString stringWithCharacters:&pressed length:1] intValue] - 1;
if ( [flycutOperator setStackPositionTo: newStackPosition] ) {
[self fillBezel];
}
break;
case 's': case 'S': // Save / Save-and-delete
{
bool success = [flycutOperator saveFromStack];
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
[self restoreStashedStoreAndUpdate];
if ( success ) {
if ( modifiers & NSShiftKeyMask ) {
[flycutOperator clearItemAtStackPosition];
[self updateBezel];
[self updateMenu];
}
}
}
break;
case 'f':
[flycutOperator toggleToFromFavoritesStore];
[bezel setColor:[flycutOperator favoritesStoreIsSelected]];
[self updateBezel];
[self hideBezel];
[self showBezel];
break;