-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSRRecorderCell.m
1340 lines (1067 loc) · 41.8 KB
/
SRRecorderCell.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
//
// SRRecorderCell.m
// ShortcutRecorder
//
// Copyright 2006-2007 Contributors. All rights reserved.
//
// License: BSD
//
// Contributors:
// David Dauer
// Jesper
// Jamie Kirkpatrick
#import "SRRecorderCell.h"
#import "SRRecorderControl.h"
#import "SRKeyCodeTransformer.h"
#import "SRValidator.h"
@interface SRRecorderCell (Private)
- (void)_privateInit;
- (void)_createGradient;
- (void)_setJustChanged;
- (void)_startRecordingTransition;
- (void)_endRecordingTransition;
- (void)_transitionTick;
- (void)_startRecording;
- (void)_endRecording;
- (BOOL)_effectiveIsAnimating;
- (BOOL)_supportsAnimation;
- (NSString *)_defaultsKeyForAutosaveName:(NSString *)name;
- (void)_saveKeyCombo;
- (void)_loadKeyCombo;
- (NSRect)_removeButtonRectForFrame:(NSRect)cellFrame;
- (NSRect)_snapbackRectForFrame:(NSRect)cellFrame;
- (NSUInteger)_filteredCocoaFlags:(NSUInteger)flags;
- (NSUInteger)_filteredCocoaToCarbonFlags:(NSUInteger)cocoaFlags;
- (BOOL)_validModifierFlags:(NSUInteger)flags;
- (BOOL)_isEmpty;
@end
#pragma mark -
@implementation SRRecorderCell
- (id)init
{
self = [super init];
[self _privateInit];
return self;
}
- (void)dealloc
{
[validator release];
[keyCharsIgnoringModifiers release];
[keyChars release];
[recordingGradient release];
[autosaveName release];
[cancelCharacterSet release];
[super dealloc];
}
#pragma mark *** Coding Support ***
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder: aDecoder];
[self _privateInit];
if ([aDecoder allowsKeyedCoding]) {
autosaveName = [[aDecoder decodeObjectForKey: @"autosaveName"] retain];
keyCombo.code = [[aDecoder decodeObjectForKey: @"keyComboCode"] shortValue];
keyCombo.flags = [[aDecoder decodeObjectForKey: @"keyComboFlags"] unsignedIntegerValue];
if ([aDecoder containsValueForKey:@"keyChars"]) {
hasKeyChars = YES;
keyChars = (NSString *)[aDecoder decodeObjectForKey: @"keyChars"];
keyCharsIgnoringModifiers = (NSString *)[aDecoder decodeObjectForKey: @"keyCharsIgnoringModifiers"];
}
allowedFlags = [[aDecoder decodeObjectForKey: @"allowedFlags"] unsignedIntegerValue];
requiredFlags = [[aDecoder decodeObjectForKey: @"requiredFlags"] unsignedIntegerValue];
allowsKeyOnly = [[aDecoder decodeObjectForKey:@"allowsKeyOnly"] boolValue];
escapeKeysRecord = [[aDecoder decodeObjectForKey:@"escapeKeysRecord"] boolValue];
isAnimating = [[aDecoder decodeObjectForKey:@"isAnimating"] boolValue];
style = [[aDecoder decodeObjectForKey:@"style"] shortValue];
} else {
autosaveName = [[aDecoder decodeObject] retain];
keyCombo.code = [[aDecoder decodeObject] shortValue];
keyCombo.flags = [[aDecoder decodeObject] unsignedIntegerValue];
allowedFlags = [[aDecoder decodeObject] unsignedIntegerValue];
requiredFlags = [[aDecoder decodeObject] unsignedIntegerValue];
}
allowedFlags |= NSFunctionKeyMask;
[self _loadKeyCombo];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[super encodeWithCoder: aCoder];
if ([aCoder allowsKeyedCoding]) {
[aCoder encodeObject:[self autosaveName] forKey:@"autosaveName"];
[aCoder encodeObject:[NSNumber numberWithShort: keyCombo.code] forKey:@"keyComboCode"];
[aCoder encodeObject:[NSNumber numberWithUnsignedInteger:keyCombo.flags] forKey:@"keyComboFlags"];
[aCoder encodeObject:[NSNumber numberWithUnsignedInteger:allowedFlags] forKey:@"allowedFlags"];
[aCoder encodeObject:[NSNumber numberWithUnsignedInteger:requiredFlags] forKey:@"requiredFlags"];
if (hasKeyChars) {
[aCoder encodeObject:keyChars forKey:@"keyChars"];
[aCoder encodeObject:keyCharsIgnoringModifiers forKey:@"keyCharsIgnoringModifiers"];
}
[aCoder encodeObject:[NSNumber numberWithBool: allowsKeyOnly] forKey:@"allowsKeyOnly"];
[aCoder encodeObject:[NSNumber numberWithBool: escapeKeysRecord] forKey:@"escapeKeysRecord"];
[aCoder encodeObject:[NSNumber numberWithBool: isAnimating] forKey:@"isAnimating"];
[aCoder encodeObject:[NSNumber numberWithShort:style] forKey:@"style"];
} else {
// Unkeyed archiving and encoding is deprecated and unsupported. Use keyed archiving and encoding.
[aCoder encodeObject: [self autosaveName]];
[aCoder encodeObject: [NSNumber numberWithShort: keyCombo.code]];
[aCoder encodeObject: [NSNumber numberWithUnsignedInteger: keyCombo.flags]];
[aCoder encodeObject: [NSNumber numberWithUnsignedInteger:allowedFlags]];
[aCoder encodeObject: [NSNumber numberWithUnsignedInteger:requiredFlags]];
}
}
- (id)copyWithZone:(NSZone *)zone
{
SRRecorderCell *cell;
cell = (SRRecorderCell *)[super copyWithZone: zone];
cell->recordingGradient = [recordingGradient retain];
cell->autosaveName = [autosaveName retain];
cell->isRecording = isRecording;
cell->mouseInsideTrackingArea = mouseInsideTrackingArea;
cell->mouseDown = mouseDown;
cell->removeTrackingRectTag = removeTrackingRectTag;
cell->snapbackTrackingRectTag = snapbackTrackingRectTag;
cell->keyCombo = keyCombo;
cell->allowedFlags = allowedFlags;
cell->requiredFlags = requiredFlags;
cell->recordingFlags = recordingFlags;
cell->allowsKeyOnly = allowsKeyOnly;
cell->escapeKeysRecord = escapeKeysRecord;
cell->isAnimating = isAnimating;
cell->style = style;
cell->cancelCharacterSet = [cancelCharacterSet retain];
cell->delegate = delegate;
return cell;
}
#pragma mark *** Drawing ***
+ (BOOL)styleSupportsAnimation:(SRRecorderStyle)style {
return (style == SRGreyStyle);
}
- (BOOL)animates {
return isAnimating;
}
- (void)setAnimates:(BOOL)an {
isAnimating = an;
}
- (SRRecorderStyle)style {
return style;
}
- (void)setStyle:(SRRecorderStyle)nStyle {
switch (nStyle) {
case SRGreyStyle:
style = SRGreyStyle;
break;
case SRGradientBorderStyle:
default:
style = SRGradientBorderStyle;
break;
}
}
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
CGFloat radius = 0;
if (style == SRGradientBorderStyle) {
NSRect whiteRect = cellFrame;
NSBezierPath *roundedRect;
// Draw gradient when in recording mode
if (isRecording)
{
radius = NSHeight(cellFrame) / 2.0f;
roundedRect = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:radius yRadius:radius];
// Fill background with gradient
[[NSGraphicsContext currentContext] saveGraphicsState];
[roundedRect addClip];
[recordingGradient drawInRect:cellFrame angle:90.0f];
[[NSGraphicsContext currentContext] restoreGraphicsState];
// Highlight if inside or down
if (mouseInsideTrackingArea)
{
[[[NSColor blackColor] colorWithAlphaComponent: (mouseDown ? 0.4f : 0.2f)] set];
[roundedRect fill];
}
// Draw snapback image
NSImage *snapBackArrow = SRResIndImage(@"SRSnapback");
[snapBackArrow dissolveToPoint:[self _snapbackRectForFrame: cellFrame].origin fraction:1.0f];
// Because of the gradient and snapback image, the white rounded rect will be smaller
whiteRect = NSInsetRect(cellFrame, 9.5f, 2.0f);
whiteRect.origin.x -= 7.5f;
}
// Draw white rounded box
radius = NSHeight(whiteRect) / 2.0f;
roundedRect = [NSBezierPath bezierPathWithRoundedRect:whiteRect xRadius:radius yRadius:radius];
[[NSGraphicsContext currentContext] saveGraphicsState];
[roundedRect addClip];
[[NSColor whiteColor] set];
[NSBezierPath fillRect: whiteRect];
// Draw border and remove badge if needed
if (!isRecording)
{
[[NSColor windowFrameColor] set];
[roundedRect stroke];
// If key combination is set and valid, draw remove image
if (![self _isEmpty] && [self isEnabled])
{
NSString *removeImageName = [NSString stringWithFormat: @"SRRemoveShortcut%@", (mouseInsideTrackingArea ? (mouseDown ? @"Pressed" : @"Rollover") : (mouseDown ? @"Rollover" : @""))];
NSImage *removeImage = SRResIndImage(removeImageName);
[removeImage dissolveToPoint:[self _removeButtonRectForFrame: cellFrame].origin fraction:1.0f];
}
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
// Draw text
NSMutableParagraphStyle *mpstyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[mpstyle setLineBreakMode: NSLineBreakByTruncatingTail];
[mpstyle setAlignment: NSCenterTextAlignment];
// Only the KeyCombo should be black and in a bigger font size
BOOL recordingOrEmpty = (isRecording || [self _isEmpty]);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: mpstyle, NSParagraphStyleAttributeName,
[NSFont systemFontOfSize: (recordingOrEmpty ? [NSFont labelFontSize] : [NSFont smallSystemFontSize])], NSFontAttributeName,
(recordingOrEmpty ? [NSColor disabledControlTextColor] : [NSColor blackColor]), NSForegroundColorAttributeName,
nil];
NSString *displayString;
if (isRecording)
{
// Recording, but no modifier keys down
if (![self _validModifierFlags: recordingFlags])
{
if (mouseInsideTrackingArea)
{
// Mouse over snapback
displayString = SRLoc(@"Use old shortcut");
}
else
{
// Mouse elsewhere
displayString = SRLoc(@"Type shortcut");
}
}
else
{
// Display currently pressed modifier keys
displayString = SRStringForCocoaModifierFlags( recordingFlags );
// Fall back on 'Type shortcut' if we don't have modifier flags to display; this will happen for the fn key depressed
if (![displayString length])
{
displayString = SRLoc(@"Type shortcut");
}
}
}
else
{
// Not recording...
if ([self _isEmpty])
{
displayString = SRLoc(@"Click to record shortcut");
}
else
{
// Display current key combination
displayString = [self keyComboString];
}
}
// Calculate rect in which to draw the text in...
NSRect textRect = cellFrame;
textRect.size.width -= 6;
textRect.size.width -= ((!isRecording && [self _isEmpty]) ? 6 : (isRecording ? [self _snapbackRectForFrame: cellFrame].size.width : [self _removeButtonRectForFrame: cellFrame].size.width) + 6);
textRect.origin.x += 6;
textRect.origin.y = -(NSMidY(cellFrame) - [displayString sizeWithAttributes: attributes].height/2);
// Finally draw it
[displayString drawInRect:textRect withAttributes:attributes];
// draw a focus ring...?
if ( [self showsFirstResponder] )
{
[NSGraphicsContext saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
radius = NSHeight(cellFrame) / 2.0f;
[[NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:radius yRadius:radius] fill];
[NSGraphicsContext restoreGraphicsState];
}
} else {
// NSRect rawCellFrame = cellFrame;
cellFrame = NSInsetRect(cellFrame,0.5f,0.5f);
NSRect whiteRect = cellFrame;
NSBezierPath *roundedRect;
BOOL isVaguelyRecording = isRecording;
CGFloat xanim = 0.0f;
if (isAnimatingNow) {
// NSLog(@"tp: %f; xanim: %f", transitionProgress, xanim);
xanim = (SRAnimationEaseInOut(transitionProgress));
// NSLog(@"tp: %f; xanim: %f", transitionProgress, xanim);
}
CGFloat alphaRecording = 1.0f; CGFloat alphaView = 1.0f;
if (isAnimatingNow && !isAnimatingTowardsRecording) { alphaRecording = 1.0f - xanim; alphaView = xanim; }
if (isAnimatingNow && isAnimatingTowardsRecording) { alphaView = 1.0f - xanim; alphaRecording = xanim; }
if (isAnimatingNow) {
//NSLog(@"animation step: %f, effective: %f, alpha recording: %f, view: %f", transitionProgress, xanim, alphaRecording, alphaView);
}
if (isAnimatingNow && isAnimatingTowardsRecording) {
isVaguelyRecording = YES;
}
// NSAffineTransform *transitionMovement = [NSAffineTransform transform];
NSAffineTransform *viewportMovement = [NSAffineTransform transform];
// Draw gradient when in recording mode
if (isVaguelyRecording)
{
if (isAnimatingNow) {
// [transitionMovement translateXBy:(isAnimatingTowardsRecording ? -(NSWidth(cellFrame)*(1.0-xanim)) : +(NSWidth(cellFrame)*xanim)) yBy:0.0];
if (SRAnimationAxisIsY) {
// [viewportMovement translateXBy:0.0 yBy:(isAnimatingTowardsRecording ? -(NSHeight(cellFrame)*(xanim)) : -(NSHeight(cellFrame)*(1.0-xanim)))];
[viewportMovement translateXBy:0.0f yBy:(isAnimatingTowardsRecording ? NSHeight(cellFrame)*(xanim) : NSHeight(cellFrame)*(1.0f-xanim))];
} else {
[viewportMovement translateXBy:(isAnimatingTowardsRecording ? -(NSWidth(cellFrame)*(xanim)) : -(NSWidth(cellFrame)*(1.0f-xanim))) yBy:0.0f];
}
} else {
if (SRAnimationAxisIsY) {
[viewportMovement translateXBy:0.0f yBy:NSHeight(cellFrame)];
} else {
[viewportMovement translateXBy:-(NSWidth(cellFrame)) yBy:0.0f];
}
}
}
// Draw white rounded box
radius = NSHeight(whiteRect) / 2.0f;
roundedRect = [NSBezierPath bezierPathWithRoundedRect:whiteRect xRadius:radius yRadius:radius];
[[NSColor whiteColor] set];
[[NSGraphicsContext currentContext] saveGraphicsState];
[roundedRect fill];
[[NSColor windowFrameColor] set];
[roundedRect stroke];
[roundedRect addClip];
// if (isVaguelyRecording)
{
NSRect snapBackRect = SRAnimationOffsetRect([self _snapbackRectForFrame: cellFrame],cellFrame);
// NSLog(@"snapbackrect: %@; offset: %@", NSStringFromRect([self _snapbackRectForFrame: cellFrame]), NSStringFromRect(snapBackRect));
NSPoint correctedSnapBackOrigin = [viewportMovement transformPoint:snapBackRect.origin];
NSRect correctedSnapBackRect = snapBackRect;
// correctedSnapBackRect.origin.y = NSMinY(whiteRect);
correctedSnapBackRect.size.height = NSHeight(whiteRect);
correctedSnapBackRect.size.width *= 1.3f;
correctedSnapBackRect.origin.y -= 5.0f;
correctedSnapBackRect.origin.x -= 1.5f;
correctedSnapBackOrigin.x -= 0.5f;
correctedSnapBackRect.origin = [viewportMovement transformPoint:correctedSnapBackRect.origin];
NSBezierPath *snapBackButton = [NSBezierPath bezierPathWithRect:correctedSnapBackRect];
[[[[NSColor windowFrameColor] shadowWithLevel:0.2f] colorWithAlphaComponent:alphaRecording] set];
[snapBackButton stroke];
// NSLog(@"stroked along path of %@", NSStringFromRect(correctedSnapBackRect));
NSGradient *gradient = nil;
if (mouseDown && mouseInsideTrackingArea) {
gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.60f alpha:alphaRecording]
endingColor:[NSColor colorWithCalibratedWhite:0.75f alpha:alphaRecording]];
}
else {
gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.75f alpha:alphaRecording]
endingColor:[NSColor colorWithCalibratedWhite:0.90f alpha:alphaRecording]];
}
CGFloat insetAmount = -([snapBackButton lineWidth]/2.0f);
[gradient drawInRect:NSInsetRect(correctedSnapBackRect, insetAmount, insetAmount) angle:90.0f];
[gradient release];
/*
// Highlight if inside or down
if (mouseInsideTrackingArea)
{
[[[NSColor blackColor] colorWithAlphaComponent: alphaRecording*(mouseDown ? 0.15 : 0.1)] set];
[snapBackButton fill];
}*/
// Draw snapback image
NSImage *snapBackArrow = SRResIndImage(@"SRSnapback");
[snapBackArrow dissolveToPoint:correctedSnapBackOrigin fraction:1.0f*alphaRecording];
}
// Draw border and remove badge if needed
/* if (!isVaguelyRecording)
{
*/
// If key combination is set and valid, draw remove image
if (![self _isEmpty] && [self isEnabled])
{
NSString *removeImageName = [NSString stringWithFormat: @"SRRemoveShortcut%@", (mouseInsideTrackingArea ? (mouseDown ? @"Pressed" : @"Rollover") : (mouseDown ? @"Rollover" : @""))];
NSImage *removeImage = SRResIndImage(removeImageName);
[removeImage dissolveToPoint:[viewportMovement transformPoint:([self _removeButtonRectForFrame: cellFrame].origin)] fraction:alphaView];
//NSLog(@"drew removeImage with alpha %f", alphaView);
}
// }
// Draw text
NSMutableParagraphStyle *mpstyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[mpstyle setLineBreakMode: NSLineBreakByTruncatingTail];
[mpstyle setAlignment: NSCenterTextAlignment];
CGFloat alphaCombo = alphaView;
CGFloat alphaRecordingText = alphaRecording;
if (comboJustChanged) {
alphaCombo = 1.0f;
alphaRecordingText = 0.0f;//(alphaRecordingText/2.0);
}
NSString *displayString;
{
// Only the KeyCombo should be black and in a bigger font size
BOOL recordingOrEmpty = (isVaguelyRecording || [self _isEmpty]);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: mpstyle, NSParagraphStyleAttributeName,
[NSFont systemFontOfSize: (recordingOrEmpty ? [NSFont labelFontSize] : [NSFont smallSystemFontSize])], NSFontAttributeName,
[(recordingOrEmpty ? [NSColor disabledControlTextColor] : [NSColor blackColor]) colorWithAlphaComponent:alphaRecordingText], NSForegroundColorAttributeName,
nil];
// Recording, but no modifier keys down
if (![self _validModifierFlags: recordingFlags])
{
if (mouseInsideTrackingArea)
{
// Mouse over snapback
displayString = SRLoc(@"Use old shortcut");
}
else
{
// Mouse elsewhere
displayString = SRLoc(@"Type shortcut");
}
}
else
{
// Display currently pressed modifier keys
displayString = SRStringForCocoaModifierFlags( recordingFlags );
// Fall back on 'Type shortcut' if we don't have modifier flags to display; this will happen for the fn key depressed
if (![displayString length])
{
displayString = SRLoc(@"Type shortcut");
}
}
// Calculate rect in which to draw the text in...
NSRect textRect = SRAnimationOffsetRect(cellFrame,cellFrame);
//NSLog(@"draw record text in rect (preadjusted): %@", NSStringFromRect(textRect));
textRect.origin.y -= 3.0f;
textRect.origin = [viewportMovement transformPoint:textRect.origin];
//NSLog(@"draw record text in rect: %@", NSStringFromRect(textRect));
// Finally draw it
[displayString drawInRect:textRect withAttributes:attributes];
}
{
// Only the KeyCombo should be black and in a bigger font size
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: mpstyle, NSParagraphStyleAttributeName,
[NSFont systemFontOfSize: ([self _isEmpty] ? [NSFont labelFontSize] : [NSFont smallSystemFontSize])], NSFontAttributeName,
[([self _isEmpty] ? [NSColor disabledControlTextColor] : [NSColor blackColor]) colorWithAlphaComponent:alphaCombo], NSForegroundColorAttributeName,
nil];
// Not recording...
if ([self _isEmpty])
{
displayString = SRLoc(@"Click to record shortcut");
}
else
{
// Display current key combination
displayString = [self keyComboString];
}
// Calculate rect in which to draw the text in...
NSRect textRect = cellFrame;
/* textRect.size.width -= 6;
textRect.size.width -= (([self _removeButtonRectForFrame: cellFrame].size.width) + 6);
// textRect.origin.x += 6;*/
//NSFont *f = [attributes objectForKey:NSFontAttributeName];
//double lineHeight = [[[NSLayoutManager alloc] init] defaultLineHeightForFont:f];
// textRect.size.height = lineHeight;
if (!comboJustChanged) {
//NSLog(@"draw view text in rect (pre-adjusted): %@", NSStringFromRect(textRect));
textRect.origin = [viewportMovement transformPoint:textRect.origin];
}
textRect.origin.y = NSMinY(textRect)-3.0f;// - ((lineHeight/2.0)+([f descender]/2.0));
//NSLog(@"draw view text in rect: %@", NSStringFromRect(textRect));
// Finally draw it
[displayString drawInRect:textRect withAttributes:attributes];
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
// draw a focus ring...?
if ( [self showsFirstResponder] )
{
[NSGraphicsContext saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
radius = NSHeight(cellFrame) / 2.0f;
[[NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:radius yRadius:radius] fill];
[NSGraphicsContext restoreGraphicsState];
}
}
}
#pragma mark *** Mouse Tracking ***
- (void)resetTrackingRects
{
SRRecorderControl *controlView = (SRRecorderControl *)[self controlView];
NSRect cellFrame = [controlView bounds];
NSPoint mouseLocation = [controlView convertPoint:[[NSApp currentEvent] locationInWindow] fromView:nil];
// We're not to be tracked if we're not enabled
if (![self isEnabled])
{
if (removeTrackingRectTag != 0) [controlView removeTrackingRect: removeTrackingRectTag];
if (snapbackTrackingRectTag != 0) [controlView removeTrackingRect: snapbackTrackingRectTag];
return;
}
// We're either in recording or normal display mode
if (!isRecording)
{
// Create and register tracking rect for the remove badge if shortcut is not empty
NSRect removeButtonRect = [self _removeButtonRectForFrame: cellFrame];
BOOL mouseInside = [controlView mouse:mouseLocation inRect:removeButtonRect];
if (removeTrackingRectTag != 0) [controlView removeTrackingRect: removeTrackingRectTag];
removeTrackingRectTag = [controlView addTrackingRect:removeButtonRect owner:self userData:nil assumeInside:mouseInside];
if (mouseInsideTrackingArea != mouseInside) mouseInsideTrackingArea = mouseInside;
}
else
{
// Create and register tracking rect for the snapback badge if we're in recording mode
NSRect snapbackRect = [self _snapbackRectForFrame: cellFrame];
BOOL mouseInside = [controlView mouse:mouseLocation inRect:snapbackRect];
if (snapbackTrackingRectTag != 0) [controlView removeTrackingRect: snapbackTrackingRectTag];
snapbackTrackingRectTag = [controlView addTrackingRect:snapbackRect owner:self userData:nil assumeInside:mouseInside];
if (mouseInsideTrackingArea != mouseInside) mouseInsideTrackingArea = mouseInside;
}
}
- (void)mouseEntered:(NSEvent *)theEvent
{
NSView *view = [self controlView];
if ([[view window] isKeyWindow] || [view acceptsFirstMouse: theEvent])
{
mouseInsideTrackingArea = YES;
[view display];
}
}
- (void)mouseExited:(NSEvent*)theEvent
{
NSView *view = [self controlView];
if ([[view window] isKeyWindow] || [view acceptsFirstMouse: theEvent])
{
mouseInsideTrackingArea = NO;
[view display];
}
}
- (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(SRRecorderControl *)controlView untilMouseUp:(BOOL)flag
{
NSEvent *currentEvent = theEvent;
NSPoint mouseLocation;
NSRect trackingRect = (isRecording ? [self _snapbackRectForFrame: cellFrame] : [self _removeButtonRectForFrame: cellFrame]);
NSRect leftRect = cellFrame;
// Determine the area without any badge
if (!NSEqualRects(trackingRect,NSZeroRect)) leftRect.size.width -= NSWidth(trackingRect) + 4;
do {
mouseLocation = [controlView convertPoint: [currentEvent locationInWindow] fromView:nil];
switch ([currentEvent type])
{
case NSLeftMouseDown:
{
// Check if mouse is over remove/snapback image
if ([controlView mouse:mouseLocation inRect:trackingRect])
{
mouseDown = YES;
[controlView setNeedsDisplayInRect: cellFrame];
}
break;
}
case NSLeftMouseDragged:
{
// Recheck if mouse is still over the image while dragging
mouseInsideTrackingArea = [controlView mouse:mouseLocation inRect:trackingRect];
[controlView setNeedsDisplayInRect: cellFrame];
break;
}
default: // NSLeftMouseUp
{
mouseDown = NO;
mouseInsideTrackingArea = [controlView mouse:mouseLocation inRect:trackingRect];
if (mouseInsideTrackingArea)
{
if (isRecording)
{
// Mouse was over snapback, just redraw
[self _endRecordingTransition];
}
else
{
// Mouse was over the remove image, reset all
[self setKeyCombo: SRMakeKeyCombo(ShortcutRecorderEmptyCode, ShortcutRecorderEmptyFlags)];
}
}
else if ([controlView mouse:mouseLocation inRect:leftRect] && !isRecording)
{
if ([self isEnabled])
{
[self _startRecordingTransition];
}
/* maybe beep if not editable?
else
{
NSBeep();
}
*/
}
// Any click inside will make us firstResponder
if ([self isEnabled]) [[controlView window] makeFirstResponder: controlView];
// Reset tracking rects and redisplay
[self resetTrackingRects];
[controlView setNeedsDisplayInRect: cellFrame];
return YES;
}
}
} while ((currentEvent = [[controlView window] nextEventMatchingMask:(NSLeftMouseDraggedMask | NSLeftMouseUpMask) untilDate:[NSDate distantFuture] inMode:NSEventTrackingRunLoopMode dequeue:YES]));
return YES;
}
#pragma mark *** Delegate ***
- (id)delegate
{
return delegate;
}
- (void)setDelegate:(id)aDelegate
{
delegate = aDelegate;
}
#pragma mark *** Responder Control ***
- (BOOL) becomeFirstResponder;
{
// reset tracking rects and redisplay
[self resetTrackingRects];
[[self controlView] display];
return YES;
}
- (BOOL)resignFirstResponder;
{
if (isRecording) {
[self _endRecordingTransition];
}
[self resetTrackingRects];
[[self controlView] display];
return YES;
}
#pragma mark *** Key Combination Control ***
- (BOOL) performKeyEquivalent:(NSEvent *)theEvent
{
NSUInteger flags = [self _filteredCocoaFlags: [theEvent modifierFlags]];
NSNumber *keyCodeNumber = [NSNumber numberWithUnsignedShort: [theEvent keyCode]];
BOOL snapback = [cancelCharacterSet containsObject: keyCodeNumber];
BOOL validModifiers = [self _validModifierFlags: (snapback) ? [theEvent modifierFlags] : flags]; // Snapback key shouldn't interfer with required flags!
// Special case for the space key when we aren't recording...
if (!isRecording && [[theEvent characters] isEqualToString:@" "]) {
[self _startRecordingTransition];
return YES;
}
// Do something as long as we're in recording mode and a modifier key or cancel key is pressed
if (isRecording && (validModifiers || snapback)) {
if (!snapback || validModifiers) {
BOOL goAhead = YES;
// Special case: if a snapback key has been entered AND modifiers are deemed valid...
if (snapback && validModifiers) {
// ...AND we're set to allow plain keys
if (allowsKeyOnly) {
// ...AND modifiers are empty, or empty save for the Function key
// (needed, since forward delete is fn+delete on laptops)
if (flags == ShortcutRecorderEmptyFlags || flags == (ShortcutRecorderEmptyFlags | NSFunctionKeyMask)) {
// ...check for behavior in escapeKeysRecord.
if (!escapeKeysRecord) {
goAhead = NO;
}
}
}
}
if (goAhead) {
NSString *character = [[theEvent charactersIgnoringModifiers] uppercaseString];
// accents like "´" or "`" will be ignored since we don't get a keycode
if ([character length]) {
NSError *error = nil;
// Check if key combination is already used or not allowed by the delegate
if ( [validator isKeyCode:[theEvent keyCode]
andFlagsTaken:[self _filteredCocoaToCarbonFlags:flags]
error:&error] ) {
// display the error...
NSAlert *alert = [NSAlert alertWithNonRecoverableError:error];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert runModal];
// Recheck pressed modifier keys
[self flagsChanged: [NSApp currentEvent]];
return YES;
} else {
// All ok, set new combination
keyCombo.flags = flags;
keyCombo.code = [theEvent keyCode];
hasKeyChars = YES;
keyChars = [[theEvent characters] retain];
keyCharsIgnoringModifiers = [[theEvent charactersIgnoringModifiers] retain];
// NSLog(@"keychars: %@, ignoringmods: %@", keyChars, keyCharsIgnoringModifiers);
// NSLog(@"calculated keychars: %@, ignoring: %@", SRStringForKeyCode(keyCombo.code), SRCharacterForKeyCodeAndCocoaFlags(keyCombo.code,keyCombo.flags));
// Notify delegate
if (delegate != nil && [delegate respondsToSelector: @selector(shortcutRecorderCell:keyComboDidChange:)])
[delegate shortcutRecorderCell:self keyComboDidChange:keyCombo];
// Save if needed
[self _saveKeyCombo];
[self _setJustChanged];
}
} else {
// invalid character
NSBeep();
}
}
}
// reset values and redisplay
recordingFlags = ShortcutRecorderEmptyFlags;
[self _endRecordingTransition];
[self resetTrackingRects];
[[self controlView] display];
return YES;
} else {
//Start recording when the spacebar is pressed while the control is first responder
if (([[[self controlView] window] firstResponder] == [self controlView]) &&
([[theEvent characters] length] && [[theEvent characters] characterAtIndex:0] == 32) &&
([self isEnabled]))
{
[self _startRecordingTransition];
}
}
return NO;
}
- (void)flagsChanged:(NSEvent *)theEvent
{
if (isRecording)
{
recordingFlags = [self _filteredCocoaFlags: [theEvent modifierFlags]];
[[self controlView] display];
}
}
#pragma mark -
- (NSUInteger)allowedFlags
{
return allowedFlags;
}
- (void)setAllowedFlags:(NSUInteger)flags
{
allowedFlags = flags;
// filter new flags and change keycombo if not recording
if (isRecording)
{
recordingFlags = [self _filteredCocoaFlags: [[NSApp currentEvent] modifierFlags]];;
}
else
{
NSUInteger originalFlags = keyCombo.flags;
keyCombo.flags = [self _filteredCocoaFlags: keyCombo.flags];
if (keyCombo.flags != originalFlags && keyCombo.code > ShortcutRecorderEmptyCode)
{
// Notify delegate if keyCombo changed
if (delegate != nil && [delegate respondsToSelector: @selector(shortcutRecorderCell:keyComboDidChange:)])
[delegate shortcutRecorderCell:self keyComboDidChange:keyCombo];
// Save if needed
[self _saveKeyCombo];
}
}
[[self controlView] display];
}
- (BOOL)allowsKeyOnly {
return allowsKeyOnly;
}
- (BOOL)escapeKeysRecord {
return escapeKeysRecord;
}
- (void)setAllowsKeyOnly:(BOOL)nAllowsKeyOnly escapeKeysRecord:(BOOL)nEscapeKeysRecord {
allowsKeyOnly = nAllowsKeyOnly;
escapeKeysRecord = nEscapeKeysRecord;
}
- (NSUInteger)requiredFlags
{
return requiredFlags;
}
- (void)setRequiredFlags:(NSUInteger)flags
{
requiredFlags = flags;
// filter new flags and change keycombo if not recording
if (isRecording)
{
recordingFlags = [self _filteredCocoaFlags: [[NSApp currentEvent] modifierFlags]];
}
else
{
NSUInteger originalFlags = keyCombo.flags;
keyCombo.flags = [self _filteredCocoaFlags: keyCombo.flags];
if (keyCombo.flags != originalFlags && keyCombo.code > ShortcutRecorderEmptyCode)
{
// Notify delegate if keyCombo changed
if (delegate != nil && [delegate respondsToSelector: @selector(shortcutRecorderCell:keyComboDidChange:)])
[delegate shortcutRecorderCell:self keyComboDidChange:keyCombo];
// Save if needed
[self _saveKeyCombo];
}
}
[[self controlView] display];
}
- (KeyCombo)keyCombo
{
return keyCombo;
}
- (void)setKeyCombo:(KeyCombo)aKeyCombo
{
keyCombo = aKeyCombo;
keyCombo.flags = [self _filteredCocoaFlags: aKeyCombo.flags];
hasKeyChars = NO;
// Notify delegate
if (delegate != nil && [delegate respondsToSelector: @selector(shortcutRecorderCell:keyComboDidChange:)])
[delegate shortcutRecorderCell:self keyComboDidChange:keyCombo];
// Save if needed
[self _saveKeyCombo];
[[self controlView] display];
}
- (BOOL)canCaptureGlobalHotKeys
{
return globalHotKeys;
}
- (void)setCanCaptureGlobalHotKeys:(BOOL)inState
{
globalHotKeys = inState;
}