-
Notifications
You must be signed in to change notification settings - Fork 1
/
AppController.m
769 lines (701 loc) · 28.9 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
//
// AppController.m
// Jumpcut
//
// Created by Steve Cook on 4/3/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
// This code is open-source software subject to the MIT License; see the homepage
// at <http://jumpcut.sourceforge.net/> for details.
#import "AppController.h"
#import "PTHotKey.h"
#import "PTHotKeyCenter.h"
#import "SRRecorderCell.h"
#define _DISPLENGTH 40
@interface NSWindow (NSWindowCollectionBehavior)
- (void)setCollectionBehavior:(NSWindowCollectionBehavior)behavior;
@end
@implementation AppController
- (id)init
{
if ( ! [[NSUserDefaults standardUserDefaults] floatForKey:@"lastRun"] || [[NSUserDefaults standardUserDefaults] floatForKey:@"lastRun"] < 0.6 ) {
// A decent starting value for the main hotkey is control-option-V
[mainRecorder setKeyCombo:SRMakeKeyCombo(9, 786432)];
// Something we'd really like is to transfer over info from 0.5x if we can get at it --
if ( [[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] ) {
// We need to pull out the relevant objects and stuff them in as proper preferences for the net.sf.Jumpcut domain
if ( [[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"displayNum"] != nil )
{
[[NSUserDefaults standardUserDefaults] setValue:[ [[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"displayNum"]
forKey:@"displayNum"];
}
if ( [[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"savePreference"] != nil )
{
if ( [[[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"savePreference"] isEqual:@"onChange"] )
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:2]
forKey:@"savePreference"];
}
else if ( [[[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"savePreference"] isEqual:@"onExit"] )
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1]
forKey:@"savePreference"];
}
else
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:0]
forKey:@"savePreference"];
} // End save preference test
} // End savePreference test
} // End if/then that deals with 0.5x preferences
} // End new-to-version check
// If we don't have preferences defined, let's set some default values:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:15],
@"displayNum",
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:9],[NSNumber numberWithInt:786432],nil] forKeys:[NSArray arrayWithObjects:@"keyCode",@"modifierFlags",nil]],
@"ShortcutRecorder mainHotkey",
[NSNumber numberWithInt:40],
@"rememberNum",
[NSNumber numberWithInt:1],
@"savePreference",
[NSNumber numberWithInt:0],
@"menuIcon",
[NSNumber numberWithFloat:.25],
@"bezelAlpha",
[NSNumber numberWithBool:NO],
@"stickyBezel",
[NSNumber numberWithBool:NO],
@"wraparoundBezel",
[NSNumber numberWithBool:NO],
@"launchOnStartup",
[NSNumber numberWithBool:YES],
@"menuSelectionPastes",
[NSNumber numberWithBool:YES],
@"bezelSelectionPastes",
[NSNumber numberWithBool:NO],
@"menuSelectionMovesToTop",
nil]
];
return [super init];
}
- (void)awakeFromNib
{
// Hotkey default value
if ( ! [[NSUserDefaults standardUserDefaults] floatForKey:@"lastRun"] || [[NSUserDefaults standardUserDefaults] floatForKey:@"lastRun"] < 0.6 ) {
// A decent starting value for the main hotkey is control-option-V
[mainRecorder setKeyCombo:SRMakeKeyCombo(9, 786432)];
if ( [[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] ) {
// We need to pull out the relevant objects and stuff them in as proper preferences for the net.sf.Jumpcut domain
if ( [[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"hotkeyModifiers"] != nil )
{
[mainRecorder setKeyCombo:SRMakeKeyCombo(9, [[[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"Jumpcut"] objectForKey:@"hotkeyModifiers"] intValue])];
}
}
}
// 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 JumpcutStore
clippingStore = [[JumpcutStore alloc] initRemembering:[[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"]
displaying:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"]
withDisplayLength:_DISPLENGTH];
// Set up the bezel window
NSSize windowSize = NSMakeSize(325.0, 325.0);
NSSize screenSize = [[NSScreen mainScreen] frame].size;
NSRect windowFrame = NSMakeRect( (screenSize.width - windowSize.width) / 2,
(screenSize.height - windowSize.height) / 3,
windowSize.width, windowSize.height );
bezel = [[BezelWindow alloc] initWithContentRect:windowFrame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[bezel setDelegate:self];
[bezel setDelegate:self];
// 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];
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"menuIcon"] == 1 ) {
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2704]];
} else if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"menuIcon"] == 2 ) {
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2702]];
} else {
[statusItem setImage:[NSImage imageNamed:@"net.sf.jumpcut.scissors_bw16.png"]];
}
[statusItem setMenu:jcMenu];
[statusItem setEnabled:YES];
// If our preferences indicate that we are saving, load the dictionary from the saved plist
// and use it to get everything set up.
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 1 ) {
[self loadEngineFromPList];
}
// Build our listener timer
pollPBTimer = [[NSTimer scheduledTimerWithTimeInterval:(1.0)
target:self
selector:@selector(pollPB:)
userInfo:nil
repeats:YES] retain];
// Finish up
srTransformer = [[SRKeyCodeTransformer alloc] init];
pbBlockCount = [[NSNumber numberWithInt:0] retain];
[pollPBTimer fire];
// Stack position starts @ 0 by default
stackPosition = 0;
// Make sure we only run the 0.5x transition once
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:0.6]
forKey:@"lastRun"];
NSOperatingSystemVersion systemInfo = [NSProcessInfo processInfo].operatingSystemVersion;
vMajor = systemInfo.majorVersion;
vMinor = systemInfo.minorVersion;
vBugFix = systemInfo.majorVersion;
[NSApp activateIgnoringOtherApps: YES];
}
-(IBAction) activateAndOrderFrontStandardAboutPanel:(id)sender
{
[[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) switchMenuIcon:(id)sender
{
if ([sender indexOfSelectedItem] == 1 ) {
[statusItem setImage:nil];
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2704]];
} else if ( [sender indexOfSelectedItem] == 2 ) {
[statusItem setImage:nil];
[statusItem setTitle:[NSString stringWithFormat:@"%C",0x2702]];
} else {
[statusItem setTitle:@""];
[statusItem setImage:[NSImage imageNamed:@"net.sf.jumpcut.scissors_bw16.png"]];
}
}
-(IBAction) setRememberNumPref:(id)sender
{
int choice;
int newRemember = [sender intValue];
if ( newRemember < [clippingStore jcListCount] &&
! issuedRememberResizeWarning &&
! [[NSUserDefaults standardUserDefaults] boolForKey:@"stifleRememberResizeWarning"]
) {
choice = NSRunAlertPanel(NSLocalizedString(@"Resize Stack", @"Alert panel - resize stack - title"),
NSLocalizedString(@"Resizing the stack to a value below its present size will cause clippings to be lost.", @"Alert panel - resize stack - message"),
NSLocalizedString(@"Resize", @"Alert panel - resize stack - action"), NSLocalizedString(@"Cancel", @"Alert panel - cancel"), NSLocalizedString(@"Don't Warn Me Again", @"Alert panel - don't warn me"));
if ( choice == NSAlertAlternateReturn ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:[clippingStore jcListCount]]
forKey:@"rememberNum"];
[self updateMenu];
return;
} else if ( choice == NSAlertOtherReturn ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES]
forKey:@"stifleRememberResizeWarning"];
} else {
issuedRememberResizeWarning = YES;
}
}
if ( newRemember < [[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"] ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:newRemember]
forKey:@"displayNum"];
}
[clippingStore setRememberNum:newRemember];
[self updateMenu];
}
-(IBAction) setDisplayNumPref:(id)sender
{
[self updateMenu];
}
-(IBAction) showPreferencePanel:(id)sender
{
int checkLoginRegistry;
if ( vMajor >= 10 && vMinor >= 5 ) {
checkLoginRegistry = [UKLoginItemRegistry indexForLoginItemWithPath:[[NSBundle mainBundle] bundlePath]];
} else {
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"];
}
if ([prefsPanel respondsToSelector:@selector(setCollectionBehavior:)])
[prefsPanel setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
[NSApp activateIgnoringOtherApps: YES];
[prefsPanel makeKeyAndOrderFront:self];
issuedRememberResizeWarning = NO;
}
-(IBAction)toggleLoadOnStartup:(id)sender {
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"loadOnStartup"] ) {
[UKLoginItemRegistry addLoginItemWithPath:[[NSBundle mainBundle] bundlePath] hideIt:NO];
} else {
[UKLoginItemRegistry removeLoginItemWithPath:[[NSBundle mainBundle] bundlePath]];
}
}
- (void)pasteFromStack
{
[self performSelector:@selector(hideApp) withObject:nil afterDelay:0.2];
if ( [clippingStore jcListCount] > stackPosition ) {
[self addClipToPasteboardFromCount:stackPosition movingToTop:NO];
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"bezelSelectionPastes"] ) {
[self performSelector:@selector(fakeCommandV) withObject:nil afterDelay:0.2];
}
}
}
- (void)metaKeysReleased
{
if ( ! isBezelPinned ) {
[self pasteFromStack];
}
}
-(void)fakeCommandV
/*" +fakeCommandV synthesizes keyboard events for Cmd-v Paste
shortcut. "*/
// Code from a Mark Mason post to Cocoadev-l
// What are the flaws in this approach?
// We don't know whether we can really accept the paste
// We have no way of judging whether it's gone through
// Simulating keypresses could have oddball consequences (for instance, if something else was trapping control v)
// Not all apps may take Command-V as a paste command (xemacs, for instance?)
// Some sort of AE-based (or System Events-based, or service-based) paste would be preferable in many circumstances.
// On the other hand, this doesn't require scripting support, should work for Carbon, etc.
// Ideally, in the future, we will be able to tell from what environment JC was passed the trigger
// and have different behavior from each.
{
NSNumber *keyCode = [srTransformer reverseTransformedValue:@"V"];
CGKeyCode veeCode = (CGKeyCode)[keyCode intValue];
CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, true ); // Command down
CGPostKeyboardEvent( (CGCharCode)'v', veeCode, true ); // V down
CGPostKeyboardEvent( (CGCharCode)'v', veeCode, false ); // V up
CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)55, false ); // Command up
}
-(void)pollPB:(NSTimer *)timer
{
NSString *type = [jcPasteboard availableTypeFromArray:[NSArray arrayWithObject:NSStringPboardType]];
if ( [pbCount intValue] != [jcPasteboard changeCount] ) {
// 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 ) {
NSString *contents = [jcPasteboard stringForType:type];
if ( contents == nil ) {
// NSLog(@"Contents: Empty");
} else {
if (( [clippingStore jcListCount] == 0 || ! [contents isEqualToString:[clippingStore clippingContentsAtPosition:0]])
&& ! [pbCount isEqualTo:pbBlockCount] ) {
[clippingStore addClipping:contents
ofType:type ];
// The below tracks our position down down down... Maybe as an option?
// if ( [clippingStore jcListCount] > 1 ) stackPosition++;
stackPosition = 0;
[self updateMenu];
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 2 ) {
[self saveEngine];
}
}
}
} else {
// NSLog(@"Contents: Non-string");
}
}
}
- (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];
switch ( pressed ) {
case 0x1B:
[self hideApp];
break;
case 0x3: case 0xD: // Enter or Return
[self pasteFromStack];
break;
case NSUpArrowFunctionKey:
case NSLeftArrowFunctionKey:
[self stackUp];
break;
case NSDownArrowFunctionKey:
case NSRightArrowFunctionKey:
[self stackDown];
break;
case NSHomeFunctionKey:
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = 0;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
break;
case NSEndFunctionKey:
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = [clippingStore jcListCount] - 1;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
break;
case NSPageUpFunctionKey:
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = stackPosition - 10; if ( stackPosition < 0 ) stackPosition = 0;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
break;
case NSPageDownFunctionKey:
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = stackPosition + 10; if ( stackPosition >= [clippingStore jcListCount] ) stackPosition = [clippingStore jcListCount] - 1;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
break;
case NSBackspaceCharacter: break;
case NSDeleteCharacter: 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 ( [clippingStore jcListCount] >= newStackPosition ) {
stackPosition = newStackPosition;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
break;
default: // It's not a navigation/application-defined thing, so let's figure out what to do with it.
// NSLog(@"PRESSED %d", pressed);
// NSLog(@"CODE %d", [mainRecorder keyCombo].code);
break;
}
}
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
//Create our hot key
[self toggleMainHotKey:[NSNull null]];
}
- (void) showBezel
{
if ( [clippingStore jcListCount] > 0 && [clippingStore jcListCount] > stackPosition ) {
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
if ([bezel respondsToSelector:@selector(setCollectionBehavior:)])
[bezel setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces]; [bezel makeKeyAndOrderFront:nil];
isBezelDisplayed = YES;
}
- (void) hideBezel
{
[bezel orderOut:nil];
[bezel setCharString:@""];
isBezelDisplayed = NO;
}
-(void)hideApp
{
[self hideBezel];
isBezelPinned = NO;
[NSApp hide:self];
}
- (void) applicationWillResignActive:(NSApplication *)app; {
// This should be hidden anyway, but just in case it's not.
[self hideBezel];
}
- (void)hitMainHotKey:(PTHotKey *)hotKey
{
if ( ! isBezelDisplayed ) {
[NSApp activateIgnoringOtherApps:YES];
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"stickyBezel"] ) {
isBezelPinned = YES;
}
[self showBezel];
} else {
[self stackDown];
}
}
- (IBAction)toggleMainHotKey:(id)sender
{
if (mainHotKey != nil)
{
[[PTHotKeyCenter sharedCenter] unregisterHotKey:mainHotKey];
[mainHotKey release];
mainHotKey = nil;
}
mainHotKey = [[PTHotKey alloc] initWithIdentifier:@"mainHotKey"
keyCombo:[PTKeyCombo keyComboWithKeyCode:[mainRecorder keyCombo].code
modifiers:[mainRecorder cocoaToCarbonFlags: [mainRecorder keyCombo].flags]]];
[mainHotKey setName: @"Activate Jumpcut HotKey"]; //This is typically used by PTKeyComboPanel
[mainHotKey setTarget: self];
[mainHotKey setAction: @selector(hitMainHotKey:)];
[[PTHotKeyCenter sharedCenter] registerHotKey:mainHotKey];
}
-(IBAction)clearClippingList:(id)sender {
int choice;
[NSApp activateIgnoringOtherApps:YES];
choice = NSRunAlertPanel(NSLocalizedString(@"Clear Clipping List", @"Alert panel - clear clippings list - title"),
NSLocalizedString(@"Do you want to clear all recent clippings?", @"Alert panel - clear clippings list - message"),
NSLocalizedString(@"Clear", @"Alert panel - clear clippings list - message"), NSLocalizedString(@"Cancel", @"Alert panel - cancel"), nil);
// on clear, zap the list and redraw the menu
if ( choice == NSAlertDefaultReturn ) {
[clippingStore clearList];
[self updateMenu];
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 1 ) {
[self saveEngine];
}
[bezel setText:@""];
}
}
- (void)updateMenu {
int passedSeparator = 0;
NSMenuItem *oldItem;
NSMenuItem *item;
NSString *pbMenuTitle;
NSArray *returnedDisplayStrings = [clippingStore previousDisplayStrings:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"]];
NSEnumerator *menuEnumerator = [[jcMenu itemArray] reverseObjectEnumerator];
NSEnumerator *clipEnumerator = [returnedDisplayStrings reverseObjectEnumerator];
//remove clippings from menu
while( oldItem = [menuEnumerator nextObject] ) {
if( [oldItem isSeparatorItem]) {
passedSeparator++;
} else if ( passedSeparator == 2 ) {
[jcMenu removeItem:oldItem];
}
}
while( pbMenuTitle = [clipEnumerator nextObject] ) {
item = [[NSMenuItem alloc] initWithTitle:pbMenuTitle
action:@selector(processMenuClippingSelection:)
keyEquivalent:@""];
[item setTarget:self];
[item setEnabled:YES];
[jcMenu insertItem:item atIndex:0];
// Way back in 0.2, failure to release the new item here was causing a quite atrocious memory leak.
[item release];
}
}
-(IBAction)processMenuClippingSelection:(id)sender
{
int index=[[sender menu] indexOfItem:sender];
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"menuSelectionMovesToTop"] ) {
[self addClipToPasteboardFromCount:index movingToTop:YES];
} else {
[self addClipToPasteboardFromCount:index movingToTop:NO];
}
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"menuSelectionPastes"] ) {
[self performSelector:@selector(hideApp) withObject:nil];
[self performSelector:@selector(fakeCommandV) withObject:nil afterDelay:0.2];
}
}
-(BOOL) isValidClippingNumber:(NSNumber *)number {
return ( ([number intValue] + 1) <= [clippingStore jcListCount] );
}
-(NSString *) clippingStringWithCount:(int)count {
if ( [self isValidClippingNumber:[NSNumber numberWithInt:count]] ) {
return [clippingStore clippingContentsAtPosition:count];
} else { // It fails -- we shouldn't be passed this, but...
NSLog(@"Asked for non-existant clipping count: %d");
return @"";
}
}
-(void) setPBBlockCount:(NSNumber *)newPBBlockCount
{
[newPBBlockCount retain];
[pbBlockCount release];
pbBlockCount = newPBBlockCount;
}
-(BOOL)addClipToPasteboardFromCount:(int)indexInt movingToTop:(bool)moveBool
{
NSString *pbFullText;
NSArray *pbTypes;
if ( (indexInt + 1) > [clippingStore jcListCount] ) {
// We're asking for a clipping that isn't there yet
// This only tends to happen immediately on startup when not saving, as the entire list is empty.
NSLog(@"Out of bounds request to jcList ignored.");
return false;
}
pbFullText = [self clippingStringWithCount:indexInt];
pbTypes = [NSArray arrayWithObjects:@"NSStringPboardType",NULL];
[jcPasteboard declareTypes:pbTypes owner:NULL];
[jcPasteboard setString:pbFullText forType:@"NSStringPboardType"];
if ( moveBool ) {
} else {
[self setPBBlockCount:[NSNumber numberWithInt:[jcPasteboard changeCount]]];
}
return true;
}
-(void) loadEngineFromPList
{
NSString *path = [[NSString stringWithString:@"~/Library/Application Support/Jumpcut/JCEngine.save"] stringByExpandingTildeInPath];
NSDictionary *loadDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSEnumerator *enumerator;
NSDictionary *aSavedClipping;
NSArray *savedJCList;
NSRange loadRange;
int rangeCap;
if ( loadDict != nil ) {
savedJCList = [loadDict objectForKey:@"jcList"];
if ( [savedJCList isKindOfClass:[NSArray class]] ) {
// There's probably a nicer way to prevent the range from going out of bounds, but this works.
rangeCap = [savedJCList count] < [[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"] ? [savedJCList count] : [[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"];
loadRange = NSMakeRange(0, rangeCap);
enumerator = [[savedJCList subarrayWithRange:loadRange] reverseObjectEnumerator];
while ( aSavedClipping = [enumerator nextObject] ) {
[clippingStore addClipping:[aSavedClipping objectForKey:@"Contents"]
ofType:[aSavedClipping objectForKey:@"Type"]];
}
} else {
NSLog(@"Not array");
}
[self updateMenu];
[loadDict release];
}
}
-(void) stackDown
{
stackPosition++;
if ( [clippingStore jcListCount] > stackPosition ) {
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
} else {
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"wraparoundBezel"] ) {
stackPosition = 0;
[bezel setCharString:[NSString stringWithFormat:@"%d", 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
} else {
stackPosition--;
}
}
}
-(void) stackUp
{
stackPosition--;
if ( stackPosition < 0 ) {
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"wraparoundBezel"] ) {
stackPosition = [clippingStore jcListCount] - 1;
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
} else {
stackPosition = 0;
}
}
if ( [clippingStore jcListCount] > stackPosition ) {
[bezel setCharString:[NSString stringWithFormat:@"%d", stackPosition + 1]];
[bezel setText:[clippingStore clippingContentsAtPosition:stackPosition]];
}
}
-(void) saveEngine
{
NSMutableDictionary *saveDict;
NSMutableArray *jcListArray = [NSMutableArray array];
int i;
BOOL isDir;
NSString *path;
path = [[NSString stringWithString:@"~/Library/Application Support/Jumpcut"] stringByExpandingTildeInPath];
if ( ![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] || ! isDir ) {
[[NSFileManager defaultManager] createDirectoryAtPath:path
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
@"NSFileModificationDate", [NSNull null],
@"NSFileOwnerAccountName", [NSNull null],
@"NSFileGroupOwnerAccountName", [NSNull null],
@"NSFilePosixPermissions", [NSNull null],
@"NSFileExtensionsHidden", [NSNull null],
nil]
];
}
saveDict = [NSMutableDictionary dictionaryWithCapacity:3];
[saveDict setObject:@"0.6" forKey:@"version"];
[saveDict setObject:[NSNumber numberWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"]]
forKey:@"rememberNum"];
[saveDict setObject:[NSNumber numberWithInt:_DISPLENGTH]
forKey:@"displayLen"];
[saveDict setObject:[NSNumber numberWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"displayNum"]]
forKey:@"displayNum"];
for ( i = 0 ; i < [clippingStore jcListCount]; i++) {
[jcListArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[clippingStore clippingContentsAtPosition:i], @"Contents",
[clippingStore clippingTypeAtPosition:i], @"Type",
[NSNumber numberWithInt:i], @"Position",
nil
]
];
}
[saveDict setObject:jcListArray forKey:@"jcList"];
}
- (void)setHotKeyPreferenceForRecorder:(SRRecorderControl *)aRecorder
{
if (aRecorder == mainRecorder)
{
[[NSUserDefaults standardUserDefaults] setObject:
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:[mainRecorder keyCombo].code],[NSNumber numberWithInt:[mainRecorder keyCombo].flags],nil] forKeys:[NSArray arrayWithObjects:@"keyCode",@"modifierFlags",nil]]
forKey:@"ShortcutRecorder mainHotkey"];
}
}
- (BOOL)shortcutRecorder:(SRRecorderControl *)aRecorder isKeyCode:(signed short)keyCode andFlagsTaken:(unsigned int)flags reason:(NSString **)aReason
{
if (aRecorder == mainRecorder)
{
BOOL isTaken = NO;
/* Delegate check would go here if we were using delegation */
return isTaken;
}
return NO;
}
- (void)shortcutRecorder:(SRRecorderControl *)aRecorder keyComboDidChange:(KeyCombo)newKeyCombo
{
if (aRecorder == mainRecorder)
{
[self toggleMainHotKey: aRecorder];
[self setHotKeyPreferenceForRecorder: aRecorder];
}
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 1 ) {
NSLog(@"Saving on exit");
[self saveEngine] ;
}
//Unregister our hot key (not required)
[[PTHotKeyCenter sharedCenter] unregisterHotKey: mainHotKey];
[mainHotKey release];
mainHotKey = nil;
[self hideBezel];
[[NSDistributedNotificationCenter defaultCenter]
removeObserver:self
name:@"AppleKeyboardPreferencesChangedNotification"
object:nil];
[[NSDistributedNotificationCenter defaultCenter]
removeObserver:self
name:@"AppleSelectedInputSourcesChangedNotification"
object:nil];
}
- (void) dealloc
{
[bezel release];
[srTransformer release];
[super dealloc];
}
@end