-
Notifications
You must be signed in to change notification settings - Fork 0
/
KFTypeSelectTableView.m
1273 lines (1073 loc) · 42.4 KB
/
KFTypeSelectTableView.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
//
// KFTypeSelectTableView.m
// KFTypeSelectTableView v1.0.4
//
// ------------------------------------------------------------------------
// Copyright (c) 2005, Ken Ferry All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// (3) Neither Ken Ferry's name nor the names of other contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
#import "KFTypeSelectTableView.h"
#import <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
static uint64_t SecondsToMachAbsolute(double seconds);
NSString *KFTypeSelectTableViewPatternDidChangeNotification = @"KFTypeSelectTableViewPatternDidChange";
/* NOTE - because of behavior detailed at cocoadev.com/index.pl?PosingWithCategoriesSuperGotcha,
* it's important that private methods be _implemented_ in the main implementation of the class,
* not in a category. It's okay for the declarations to be in a category, as below.
* (Summary of link: messages to super act like messages to self in categories on a posing class
* in system 10.3)
*/
@interface KFTypeSelectTableView (Private)
// responding to events
static BOOL KFKeyEventIsBeginFindEvent(NSEvent *keyEvent);
static BOOL KFKeyEventIsExtendFindEvent(NSEvent *keyEvent);
static BOOL KFKeyEventIsFindNextEvent(NSEvent *keyEvent);
static BOOL KFKeyEventIsFindPreviousEvent(NSEvent *keyEvent);
static BOOL KFKeyEventIsDeleteEvent(NSEvent *keyEvent);
static BOOL KFKeyEventIsCancelEvent(NSEvent *keyEvent);
// finding strings
- (void)kfFindPattern:(NSString *)pattern
initialRow:(int)initialRow
topToBottom:(BOOL)topToBottom
allowExtension:(BOOL)allowPatternExtension;
- (BOOL)kfWorkUnitGetMatch:(NSString **)match
range:(NSRange *)matchRange
lastSearchedRow:(int *)lastSearchedRow
forPattern:(NSString *)pattern
matchOptions:(unsigned)patternMatchOptions
initialRow:(int)initialRow
boundaryRow:(int)boundaryRow
rowIncrement:(int)rowIncrement
searchColumns:(NSArray *)searchColumns
timeout:(uint64_t)timeout;
- (BOOL)kfShouldAcceptMatch:(NSString *)match
range:(NSRange)matchedRange
inRow:(int)row;
- (BOOL)kfCanPerformTypeSelect;
- (BOOL)kfSelectionShouldChange;
- (BOOL)kfCanGetTableData;
- (NSString *)kfStringValueForTableColumn:(NSTableColumn *)column row:(int)row;
- (NSArray *)kfSearchColumns;
- (BOOL)kfSearchTopToBottom;
- (int)kfInitialRowForNewSearch;
// taking action
- (void)kfPatternDidChange:(id)sender;
- (void)kfDidFindMatch:(NSString *)match
range:(NSRange)matchedRange
inRow:(int)row;
- (void)kfDidFailToFindMatchSearchingToRow:(int)row;
- (void)kfResetSearch;
- (void)kfConfigureDelegateIfNeeded;
// utility
- (BOOL)kfRowIsVisible:(int)row;
- (void)kfScrollRectToCenter:(NSRect)aRect vertical:(BOOL)scrollVertical horizontal:(BOOL)scrollHorizontal;
// simulated ivars infrastructure
- (NSMutableDictionary *)kfSimulatedIvars;
- (id)kfIdentifier;
- (void)kfSetUpSimulatedIvars;
- (void)kfTearDownSimulatedIvars;
// accessors
- (int)kfSavedRowForExtensionSearch;
- (void)setKfSavedRowForExtensionSearch:(int)row;
- (NSString *)kfLastSuccessfullyMatchedPattern;
- (void)setKfLastSuccessfullyMatchedPattern:(NSString *)string;
- (BOOL)kfCanExtendFind;
- (void)setKfCanExtendFind:(BOOL)flag;
- (id)kfLastConfiguredDelegate;
- (void)setKfLastConfiguredDelegate:(id)anObject;
- (NSInvocation *)kfTimeoutInvocation;
- (void)setKfTimeoutInvocation:(NSInvocation *)anInvocation;
- (void)setPattern:(NSString *)pattern;
@end
@implementation KFTypeSelectTableView
#pragma mark -
#pragma mark SETUP/TEARDOWN
#pragma mark -
// Note: don't use init. Won't receive it for preexisting objects when posing.
- (void)dealloc
{
NSInvocation *timeoutInvocation = [self kfTimeoutInvocation];
[[timeoutInvocation class] cancelPreviousPerformRequestsWithTarget:[self kfTimeoutInvocation]
selector:@selector(invoke)
object:nil];
[self kfTearDownSimulatedIvars];
[super dealloc];
}
#pragma mark -
#pragma mark BODY
#pragma mark -
#pragma mark responding to events
- (void)keyDown:(NSEvent *)keyEvent
{
// Will we drop this event to super?
BOOL eatEvent = NO;
if ([self kfCanPerformTypeSelect] && ([[self window] firstResponder] == self))
{
BOOL canExtendFind = [self kfCanExtendFind];
if (canExtendFind && KFKeyEventIsExtendFindEvent(keyEvent))
{
NSText *fieldEditor = [[self window] fieldEditor:YES forObject:self];
[fieldEditor interpretKeyEvents:[NSArray arrayWithObject:keyEvent]];
[self kfFindPattern:[fieldEditor string]
initialRow:[self kfSavedRowForExtensionSearch]
topToBottom:[self kfSearchTopToBottom]
allowExtension:YES];
eatEvent = YES;
}
else if (KFKeyEventIsBeginFindEvent(keyEvent))
{
NSText *fieldEditor = [[self window] fieldEditor:YES forObject:self];
[fieldEditor setString:@""];
[fieldEditor interpretKeyEvents:[NSArray arrayWithObject:keyEvent]];
NSString *newPattern = [fieldEditor string];
if (![newPattern isEqualToString:@""])
{
[self kfFindPattern:[fieldEditor string]
initialRow:[self kfInitialRowForNewSearch]
topToBottom:[self kfSearchTopToBottom]
allowExtension:YES];
}
eatEvent = YES;
}
else if (canExtendFind && KFKeyEventIsDeleteEvent(keyEvent))
{
// User might expect us to knock a character off the pattern - that'd be dangerous.
// If the user mistimed he could trigger a table view delete action.
// Best to squelch the behavior by not doing anything useful.
eatEvent = YES;
}
else if (KFKeyEventIsFindNextEvent(keyEvent))
{
[self findNext:self];
eatEvent = YES;
}
else if (KFKeyEventIsFindPreviousEvent(keyEvent))
{
[self findPrevious:self];
eatEvent = YES;
}
else if (KFKeyEventIsCancelEvent(keyEvent))
{
// this is superfluous in 10.2 and 10.3, but may be useful on systems prior to
// 10.2. I haven't had a chance to find out.
[self cancelOperation:self];
eatEvent = YES;
}
}
if (!eatEvent)
{
// FIXME - hack
// I can't find a decent way to clear a hanging dead-key (i.e. option-e) in kfResetSearch.
// Sending an event following a dead key event through interpretKeyEvents is the
// only thing I've found to do it, so we make sure that any keyEvent that we don't understand
// goes through the field editor's interpretKeyEvents. It won't cause any damage because the field
// editor has no delegate and will be cleared before it's used again anyway.
// Without this workaround, entering "option-e, f" will stick this table in a state where all
// key-events start with character "´", which means type-select won't work. The state is only
// exited when a different control starts processing text.
//
// This workaround kills the above problem, but is suboptimal in that a dead-key never times out (besides just
// being nasty).
if([[keyEvent characters] characterAtIndex:0] != 27) // XeeEdited
{
NSText *fieldEditor = [[self window] fieldEditor:YES forObject:self];
[fieldEditor interpretKeyEvents:[NSArray arrayWithObject:keyEvent]];
}
// end hack
[self setKfCanExtendFind:NO];
[super keyDown:keyEvent];
}
}
- (void)cancelOperation:(id)sender
{
[self kfResetSearch];
}
// 10.2 private version of cancelOperation
// I'm not sure how far back this will work.
- (void)_cancelKey:(id)sender
{
[self cancelOperation:sender];
}
// an outline view catches control-down and control-up
// and uses them to select next and previous rows (same as plain up and down)
// We can catch the events by implementing moveDown and moveUp.
- (void)moveDown:(id)sender
{
NSEvent *currentEvent = [NSApp currentEvent];
if ([currentEvent type] == NSKeyDown && KFKeyEventIsFindNextEvent(currentEvent))
{
[self findNext:self];
}
}
- (void)moveUp:(id)sender
{
NSEvent *currentEvent = [NSApp currentEvent];
if ([currentEvent type] == NSKeyDown && KFKeyEventIsFindPreviousEvent(currentEvent))
{
[self findPrevious:self];
}
}
- (BOOL)resignFirstResponder
{
BOOL shouldResign = [super resignFirstResponder];
if (shouldResign)
{
[self setKfCanExtendFind:NO];
}
return shouldResign;
}
static unsigned int modifierFlagsICareAboutMask = NSCommandKeyMask | NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSFunctionKeyMask;
// yes if every character in the event is alphanumeric and no command, control or function modifiers
static BOOL KFKeyEventIsBeginFindEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
int numCharacters = [characters length];
if ((modifiers & (NSCommandKeyMask | NSControlKeyMask | NSFunctionKeyMask)) != 0)
{
return NO;
}
NSMutableCharacterSet *beginFindCharacterSet = [[[NSCharacterSet alphanumericCharacterSet] mutableCopy] autorelease];
//[beginFindCharacterSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]]; // XeeEdited
int i;
unichar character;
for (i = 0; i < numCharacters; i++)
{
character = [characters characterAtIndex:i];
if (![beginFindCharacterSet characterIsMember:character])
{
return NO;
}
}
return YES;
}
// yes if every character in the event is alphanumeric, punctuation or a space, and no command, control or function modifiers
static BOOL KFKeyEventIsExtendFindEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
int numCharacters = [characters length];
if ((modifiers & (NSCommandKeyMask | NSControlKeyMask | NSFunctionKeyMask)) != 0)
{
return NO;
}
NSMutableCharacterSet *extendFindCharacterSet = [[[NSCharacterSet alphanumericCharacterSet] mutableCopy] autorelease];
[extendFindCharacterSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[extendFindCharacterSet addCharactersInString:@" "];
int i;
unichar character;
for (i = 0; i < numCharacters; i++)
{
character = [characters characterAtIndex:i];
if (![extendFindCharacterSet characterIsMember:character])
{
return NO;
}
}
return YES;
}
static BOOL KFKeyEventIsFindNextEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
int numCharacters = [characters length];
if (numCharacters == 1 && [characters characterAtIndex:0] == NSDownArrowFunctionKey && modifiers == (NSControlKeyMask | NSFunctionKeyMask))
{
return YES;
}
return NO;
}
static BOOL KFKeyEventIsFindPreviousEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
int numCharacters = [characters length];
if (numCharacters == 1 && [characters characterAtIndex:0] == NSUpArrowFunctionKey && modifiers == (NSControlKeyMask | NSFunctionKeyMask))
{
return YES;
}
return NO;
}
static BOOL KFKeyEventIsDeleteEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
int numCharacters = [characters length];
if (numCharacters == 1 && [characters characterAtIndex:0] == NSDeleteCharacter && modifiers == 0)
{
return YES;
}
if (numCharacters == 1 && [characters characterAtIndex:0] == NSBackspaceCharacter && modifiers == 0)
{
return YES;
}
return NO;
}
static BOOL KFKeyEventIsCancelEvent(NSEvent *keyEvent)
{
unsigned int modifiers = [keyEvent modifierFlags] & modifierFlagsICareAboutMask;
NSString *characters = [keyEvent characters];
// int numCharacters = [characters length]; // XeeEdited
// const unichar EscapeKeyCharacter = 0x1b;
if ((modifiers == NSCommandKeyMask) && [characters isEqualToString:@"."])
{
return YES;
}
// if (numCharacters == 1 && [characters characterAtIndex:0] == EscapeKeyCharacter && modifiers == 0) // XeeEdited
// {
// return YES;
// }
return NO;
}
#pragma mark finding patterns
- (void)findNext:(id)sender
{
NSString *lastPattern = [self kfLastSuccessfullyMatchedPattern];
if (lastPattern == nil || ![self kfCanPerformTypeSelect])
{
NSBeep();
}
else
{
[self kfFindPattern:lastPattern
initialRow:[self selectedRow] + 1
topToBottom:YES
allowExtension:NO];
}
}
- (void)findPrevious:(id)sender
{
NSString *lastPattern = [self kfLastSuccessfullyMatchedPattern];
if (lastPattern == nil || ![self kfCanPerformTypeSelect])
{
NSBeep();
}
else
{
[self kfFindPattern:lastPattern
initialRow:[self selectedRow] - 1
topToBottom:NO
allowExtension:NO];
}
}
- (void)kfFindPattern:(NSString *)pattern
initialRow:(int)initialRow
topToBottom:(BOOL)topToBottom
allowExtension:(BOOL)allowPatternExtension
{
NSArray *searchColumns = [self kfSearchColumns];
BOOL shouldWrap = [self searchWraps];
unsigned patternMatchOptions;
NSDate *distantPast = [NSDate distantPast];
NSMutableArray *suspendedEvents = [NSMutableArray array];
const uint64_t eventCheckFrequency = SecondsToMachAbsolute(.01);
NSString *match = nil;
NSRange matchRange = {0,0};
// we'll translate topToBottom into these parameters
// so that we can use a single loop for both directions
int rowIncrement, boundaryRow;
if (topToBottom)
{
rowIncrement = 1;
boundaryRow = [self numberOfRows];
initialRow = (initialRow < boundaryRow) ? initialRow : boundaryRow;
initialRow = (initialRow > 0) ? initialRow : 0;
if (initialRow == 0)
shouldWrap = NO;
}
else
{
rowIncrement = -1;
boundaryRow = -1;
initialRow = (initialRow > boundaryRow) ? initialRow : boundaryRow;
initialRow = (initialRow < [self numberOfRows] - 1) ? initialRow : [self numberOfRows] - 1;
if (initialRow == [self numberOfRows] - 1)
shouldWrap = NO;
}
// keep ivars in sync
[self setPattern:pattern];
[self setKfCanExtendFind:allowPatternExtension];
// set up pattern match options
if ([self matchAlgorithm] == KFPrefixMatchAlgorithm)
{
patternMatchOptions = NSCaseInsensitiveSearch | NSAnchoredSearch;
}
else // substring match
{
patternMatchOptions = NSCaseInsensitiveSearch;
}
BOOL finished = NO;
int row = initialRow;
while (!finished)
{
// Mail generates 3MB in autoreleased objects in a search through 15000 rows
// there's a noticable pause when they're deallocated. We'll avoid it by using
// our own autorelease pool.
// (Update - implementing typeSelectTableView:stringValueForTableColumn:row: in the mail
// plugin dropped the number of allocations)
//
// Note: checking for new input no more often than 100 times a second drops time spent
// in -[NSApplication nextEventMatchingMask::::] from 30-60% of total function time to .2-.5%
// at a cost of < 1% for timing functions.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
finished = [self kfWorkUnitGetMatch:&match
range:&matchRange
lastSearchedRow:&row
forPattern:pattern
matchOptions:patternMatchOptions
initialRow:row
boundaryRow:boundaryRow
rowIncrement:rowIncrement
searchColumns:searchColumns
timeout:eventCheckFrequency];
[match retain];
[pool release];
[match autorelease];
if (!finished)
row += rowIncrement;
if (finished && match == nil && shouldWrap)
{
if (topToBottom)
row = 0;
else
row = [self numberOfRows] - 1;
boundaryRow = initialRow;
shouldWrap = NO;
finished = NO;
}
if (!finished)
{
NSEvent *keyEvent;
while ((keyEvent = [NSApp nextEventMatchingMask:NSKeyDownMask
untilDate:distantPast // means grab events that have already occurred
inMode:NSEventTrackingRunLoopMode
dequeue:YES]) != nil)
{
if (KFKeyEventIsCancelEvent(keyEvent))
{
[self kfResetSearch];
// we intentionally dump the suspended events in this case
return;
}
else if (allowPatternExtension && KFKeyEventIsExtendFindEvent(keyEvent))
{
NSText *fieldEditor = [[self window] fieldEditor:YES forObject:self];
[fieldEditor interpretKeyEvents:[NSArray arrayWithObject:keyEvent]];
pattern = [fieldEditor string];
[self setPattern:pattern];
}
else if (KFKeyEventIsDeleteEvent(keyEvent))
{
// eat the event, do nothing.
// User might expect us to knock a character off the pattern - that'd be dangerous.
// If the user mistimed he could trigger a table view delete action.
// Best to squelch the behavior by not doing anything useful.
}
else
{
[suspendedEvents addObject:keyEvent];
}
}
}
}
if (match != nil)
{
[self kfDidFindMatch:match
range:matchRange
inRow:row];
}
else
{
[self kfDidFailToFindMatchSearchingToRow:row];
}
int numSuspendedEvents, i;
numSuspendedEvents = [suspendedEvents count];
for (i = numSuspendedEvents-1; i >= 0; i--)
{
[NSApp postEvent:[suspendedEvents objectAtIndex:i] atStart:YES];
}
}
- (BOOL)kfWorkUnitGetMatch:(NSString **)match
range:(NSRange *)matchRange
lastSearchedRow:(int *)lastSearchedRow
forPattern:(NSString *)pattern
matchOptions:(unsigned)patternMatchOptions
initialRow:(int)initialRow
boundaryRow:(int)boundaryRow
rowIncrement:(int)rowIncrement
searchColumns:(NSArray *)searchColumns
timeout:(uint64_t)timeout // times are mach absolute times
{
int row, col;
int numCols = [searchColumns count];
NSString *candidateMatch;
NSRange rangeOfPattern;
uint64_t stopTime = mach_absolute_time() + timeout;
for (row = initialRow; row != boundaryRow; row += rowIncrement)
{
for (col = 0; col < numCols; col++)
{
candidateMatch = [self kfStringValueForTableColumn:[searchColumns objectAtIndex:col] row:row];
rangeOfPattern = [candidateMatch rangeOfString:pattern options:patternMatchOptions];
if ( (rangeOfPattern.location != NSNotFound)
&& [self kfShouldAcceptMatch:candidateMatch range:rangeOfPattern inRow:row])
{
*match = candidateMatch;
*matchRange = rangeOfPattern;
*lastSearchedRow = row;
return YES;
}
}
// think of this as part of the loop condition, but we want to make sure that
// the loop completes at least one iteration
if (mach_absolute_time() > stopTime)
{
row += rowIncrement;
break;
}
}
*match = nil;
*matchRange = NSMakeRange(NSNotFound, 0);
*lastSearchedRow = row - rowIncrement;
return row == boundaryRow;
}
- (BOOL)kfShouldAcceptMatch:(NSString *)match
range:(NSRange)matchedRange
inRow:(int)row
{
id delegate = [self delegate];
if ( [self isKindOfClass:[NSOutlineView class]]
&& [delegate respondsToSelector:@selector(outlineView:shouldSelectItem:)])
{
return [delegate outlineView:(NSOutlineView *)self shouldSelectItem:[(NSOutlineView *)self itemAtRow:row]];
}
else if ([delegate respondsToSelector:@selector(tableView:shouldSelectRow:)])
{
return [delegate tableView:self shouldSelectRow:row];
}
else
{
return YES;
}
}
- (NSTimeInterval)kfPatternTimeoutInterval
{
// from Dan Wood's 'Table Techniques Taught Tastefully', as pointed out by someone
// on cocoadev.com
// Timeout is two times the key repeat rate "InitialKeyRepeat" user default.
// (converted from sixtieths of a second to seconds), but no more than two seconds.
// This behavior is determined based on Inside Macintosh documentation on the List Manager.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int keyThreshTicks = [defaults integerForKey:@"InitialKeyRepeat"]; // undocumented key. Still valid in 10.3.
if (0 == keyThreshTicks) // missing value in defaults? Means user has never changed the default.
{
keyThreshTicks = 35; // apparent default value. translates to 1.17 sec timeout.
}
return MIN(2.0/60.0*keyThreshTicks, 2.0);
}
- (BOOL)kfCanPerformTypeSelect
{
return [self kfCanGetTableData] && [self kfSelectionShouldChange];
}
- (BOOL)kfSelectionShouldChange
{
id delegate = [self delegate];
if ( [self isKindOfClass:[NSOutlineView class]]
&& [delegate respondsToSelector:@selector(selectionShouldChangeInOutlineView:)])
{
return [delegate selectionShouldChangeInOutlineView:(NSOutlineView *)self];
}
else if ([delegate respondsToSelector:@selector(selectionShouldChangeInTableView:)])
{
return [delegate selectionShouldChangeInTableView:self];
}
else
{
return YES;
}
}
- (BOOL)kfCanGetTableData
{
// First case: datasource implements NSTableViewDataSource protocol. Usually not true when
// table view uses bindings or is actually an outline view.
// Second case: self is an outline view and datasource implements NSOutlineViewDataSource protocol. This could arise when using class posing.
// Third case: our delegate supplies the info we need.
return ([[self dataSource] respondsToSelector:@selector(tableView:objectValueForTableColumn:row:)] ||
([self isKindOfClass:[NSOutlineView class]] && [[self dataSource] respondsToSelector:@selector(outlineView:objectValueForTableColumn:byItem:)]) ||
[[self delegate] respondsToSelector:@selector(typeSelectTableView:stringValueForTableColumn:row:)]);
}
- (NSString *)kfStringValueForTableColumn:(NSTableColumn *)column row:(int)row
{
// There are three ways we can get this information: (1) our delegate supplies it, (2) our datasource
// supplies it like an NSTableViewDataSource, (3) our datasource supplies it like an NSOutlineViewDataSource
// could optimize by factoring into three separate methods and precomputing which one to call (from keyDown:).
// current sharking indicates this wouldn't help much.
id delegate = [self delegate];
NSString *stringValue = nil;
if ([delegate respondsToSelector:@selector(typeSelectTableView:stringValueForTableColumn:row:)])
{
stringValue = [delegate typeSelectTableView:self stringValueForTableColumn:column row:row];
}
else
{
id objectValue = nil;
id dataSource = [self dataSource];
// why do we check our own class? outline view is not bindings enabled, so datasource could be
// acting as a datasource for an outline while being a binding data source for us
if ([self isKindOfClass:[NSOutlineView class]]
&& [dataSource respondsToSelector:@selector(outlineView:objectValueForTableColumn:byItem:)])
{
objectValue = [dataSource outlineView:(NSOutlineView *)self
objectValueForTableColumn:column
byItem:[(NSOutlineView *)self itemAtRow:row]];
}
else if ([dataSource respondsToSelector:@selector(tableView:objectValueForTableColumn:row:)])
{
objectValue = [dataSource tableView:self objectValueForTableColumn:column row:row];
}
NSCell *dataCell = [column dataCellForRow:row];
[dataCell setObjectValue:objectValue];
// sometimes the delegate changes the cell value in tableView:willDisplayCell:forTableColumn:row:
if ([self isKindOfClass:[NSOutlineView class]]
&& [delegate respondsToSelector:@selector(outlineView:willDisplayCell:forTableColumn:item:)])
{
[delegate outlineView:(NSOutlineView *)self
willDisplayCell:dataCell
forTableColumn:column
item:[(NSOutlineView *)self itemAtRow:row]];
}
else if ([delegate respondsToSelector:@selector(tableView:willDisplayCell:forTableColumn:row:)])
{
[delegate tableView:self
willDisplayCell:dataCell
forTableColumn:column
row:row];
}
stringValue = [dataCell stringValue];
}
if (stringValue == nil)
{
stringValue = @"";
}
return stringValue;
}
- (NSArray *)kfSearchColumns
{
NSArray *searchColumns;
NSSet *searchColumnIdentifiers = [self searchColumnIdentifiers];
if (searchColumnIdentifiers != nil)
{
NSMutableArray *partialSearchColumns;
NSArray *candidateColumns = [self tableColumns];
NSTableColumn *column;
int numCols, col;
partialSearchColumns = [NSMutableArray array];
numCols = [candidateColumns count];
for (col = 0; col < numCols; col++)
{
column = [candidateColumns objectAtIndex:col];
if ([searchColumnIdentifiers containsObject:[column identifier]])
{
[partialSearchColumns addObject:column];
}
}
searchColumns = partialSearchColumns;
}
else
{
searchColumns = [self tableColumns];
}
return searchColumns;
}
- (BOOL)kfSearchTopToBottom
{
BOOL topToBottom = YES;
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(typeSelectTableViewSearchTopToBottom:)])
{
topToBottom = [delegate typeSelectTableViewSearchTopToBottom:self];
}
return topToBottom;
}
- (int)kfInitialRowForNewSearch
{
int row;
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(typeSelectTableViewInitialSearchRow:)])
{
row = [delegate typeSelectTableViewInitialSearchRow:self];
}
else
{
if ([self kfSearchTopToBottom])
{
row = 0;
}
else
{
row = [self numberOfRows] - 1;
}
}
return row;
}
#pragma mark taking action
-(void)kfPatternDidChange:(id)sender
{
NSInvocation *timeoutInvocation = [self kfTimeoutInvocation];
[[timeoutInvocation class] cancelPreviousPerformRequestsWithTarget:[self kfTimeoutInvocation]
selector:@selector(invoke)
object:nil];
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(typeSelectTableViewPatternDidChange:)])
[delegate typeSelectTableViewPatternDidChange:sender];
}
- (void)kfDidFindMatch:(NSString *)match
range:(NSRange)matchedRange
inRow:(int)row
{
NSString *pattern = [self pattern];
// update ivars
[self setKfLastSuccessfullyMatchedPattern:pattern];
if ([self kfCanExtendFind])
{
[self setKfSavedRowForExtensionSearch:row];
}
// select row
[self selectRow:row byExtendingSelection:NO];
if (![self kfRowIsVisible:row])
{
// this is what NSTextView does when it finds patterns, and it's what Mail does
// when moving through message table with up and down arrows
[self kfScrollRectToCenter:[self rectOfRow:row] vertical:YES horizontal:NO];
}
// start pattern timeout timer (see kfTimeoutInvocation for details)
[[self kfTimeoutInvocation] performSelector:@selector(invoke)
withObject:nil
afterDelay:[self kfPatternTimeoutInterval]
inModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, nil]];
// inform the delegate
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(typeSelectTableView:didFindMatch:range:forPattern:)])
{
[delegate typeSelectTableView:self didFindMatch:match range:matchedRange forPattern:pattern];
}
}
- (void)kfDidFailToFindMatchSearchingToRow:(int)row
{
if ([self kfCanExtendFind])
{
[self setKfSavedRowForExtensionSearch:row];
}
// start pattern timeout timer (see kfTimeoutInvocation for details)
[[self kfTimeoutInvocation] performSelector:@selector(invoke)
withObject:nil
afterDelay:[self kfPatternTimeoutInterval]
inModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, nil]];
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(typeSelectTableView:didFailToFindMatchForPattern:)])
{
[delegate typeSelectTableView:self didFailToFindMatchForPattern:[self pattern]];
}
else
{
NSBeep();
}
}
- (void)kfResetSearch
{
// note - doesn't clear hanging dead key. See keyDown for discussion and workaround.
[self setPattern:@""];
[self setKfCanExtendFind:NO];
}
// note: don't use setDelegate: to call this. NSOutlineView doesn't call through to
// -[NSTableView setDelegate:], so it messes us up when posing.
- (void)kfConfigureDelegateIfNeeded
{
id delegate = [self delegate];
if (delegate != [self kfLastConfiguredDelegate])
{
// order is important here
// We don't want to go into a recursion if the delegate tries to access a configurable value from
// configureTypeSelectTableView. The delegate is interested in the pre-configuration values anyway.
[self setKfLastConfiguredDelegate:delegate];
if ([delegate respondsToSelector:@selector(configureTypeSelectTableView:)])
[delegate configureTypeSelectTableView:self];
}
}
#pragma mark utility
- (BOOL)kfRowIsVisible:(int)row
{
NSScrollView *enclosingScrollView = [self enclosingScrollView];
if (enclosingScrollView == nil)
{
return NO;
}
else
{
NSRect visibleRect = [enclosingScrollView documentVisibleRect];
NSRect rowRect = [self rectOfRow:row];
// only care about whether we're onscreen vertically
return ( (NSMaxY(visibleRect) >= NSMaxY(rowRect))
&& (NSMinY(visibleRect) <= NSMinY(rowRect)));
}
}
- (void)kfScrollRectToCenter:(NSRect)aRect vertical:(BOOL)scrollVertical horizontal:(BOOL)scrollHorizontal
{
NSScrollView *scrollView = [self enclosingScrollView];
if (scrollView != nil)
{
NSRect newVisibleRect = [scrollView documentVisibleRect];
if (scrollVertical)
newVisibleRect.origin.y += NSMidY(aRect) - NSMidY([scrollView documentVisibleRect]);
if (scrollHorizontal)
newVisibleRect.origin.x += NSMidX(aRect) - NSMidX([scrollView documentVisibleRect]);
newVisibleRect = NSIntersectionRect(newVisibleRect,[self bounds]);
[self scrollRectToVisible:newVisibleRect];
}
}
#pragma mark -
#pragma mark ACCESSORS