/
FFResultsViewController.mm
699 lines (583 loc) · 24.6 KB
/
FFResultsViewController.mm
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
#import "FFResultsViewController.h"
#import "FFResultNode.h"
#import <document/OakDocument.h>
#import <OakAppKit/OakAppKit.h>
#import <OakAppKit/OakUIConstructionFunctions.h>
#import <OakAppKit/NSColor Additions.h>
static NSString* const kUserDefaultsSearchResultsFontNameKey = @"searchResultsFontName";
static NSString* const kUserDefaultsSearchResultsFontSizeKey = @"searchResultsFontSize";
static FFResultNode* NextNode (FFResultNode* node)
{
NSUInteger index = [node.parent.children indexOfObject:node] + 1;
return index < node.parent.children.count ? node.parent.children[index] : nil;
}
static FFResultNode* PreviousNode (FFResultNode* node)
{
NSUInteger index = [node.parent.children indexOfObject:node];
return index > 0 ? node.parent.children[index - 1] : nil;
}
@interface FFResultsViewController () <NSOutlineViewDataSource, NSOutlineViewDelegate>
{
NSView* _topDivider;
NSScrollView* _scrollView;
NSView* _bottomDivider;
NSFont* _searchResultsFont;
__weak id _eventMonitor;
BOOL _longPressedCommandModifier;
CGFloat _pendingColumnWidth;
FFResultNode* _lastSelectedResult;
}
@property (nonatomic) BOOL showKeyEquivalent;
@end
// ================================
// = OakSearchResultsCheckboxView =
// ================================
@interface OakSearchResultsCheckboxView : NSTableCellView
@property (nonatomic) NSButton* button;
@end
@implementation OakSearchResultsCheckboxView
- (id)initWithFrame:(NSRect)aFrame
{
NSButton* button = OakCreateCheckBox(nil);
[[button cell] setControlSize:NSControlSizeSmall];
[button sizeToFit];
[button setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
if((self = [super initWithFrame:button.frame]))
{
_button = button;
[self addSubview:_button];
[_button bind:NSEnabledBinding toObject:self withKeyPath:@"objectValue.readOnly" options:@{ NSValueTransformerNameBindingOption: NSNegateBooleanTransformerName }];
[_button bind:NSValueBinding toObject:self withKeyPath:@"objectValue.excluded" options:@{ NSValueTransformerNameBindingOption: NSNegateBooleanTransformerName }];
}
return self;
}
@end
// ====================
// = OakTableCellView =
// ====================
@interface OakTableCellView : NSTableCellView
{
BOOL _observingKeyPaths;
}
@property (nonatomic) FFResultsViewController* viewController;
@property (nonatomic) NSArray<NSString*>* observeKeyPaths;
@end
@implementation OakTableCellView
- (void)viewWillMoveToSuperview:(NSView*)aView
{
if(aView && _observingKeyPaths == NO)
{
for(NSString* keyPath in self.observeKeyPaths)
[_viewController addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionInitial context:nullptr];
_observingKeyPaths = YES;
}
else if(!aView && _observingKeyPaths == YES)
{
for(NSString* keyPath in self.observeKeyPaths)
[_viewController removeObserver:self forKeyPath:keyPath];
_observingKeyPaths = NO;
}
[super viewWillMoveToSuperview:aView];
}
- (void)observeValueForKeyPath:(NSString*)aKeyPath ofObject:(id)anObject change:(NSDictionary*)someChange context:(void*)context
{
if([self.observeKeyPaths containsObject:aKeyPath])
[self setValue:[anObject valueForKey:aKeyPath] forKey:aKeyPath];
else [super observeValueForKeyPath:aKeyPath ofObject:anObject change:someChange context:context];
}
@end
// =================================
// = OakSearchResultsMatchCellView =
// =================================
@interface OakSearchResultsMatchCellView : OakTableCellView
@property (nonatomic) NSString* replaceString;
@property (nonatomic) BOOL showReplacementPreviews;
@end
@implementation OakSearchResultsMatchCellView
+ (NSSet*)keyPathsForValuesAffectingExcerptString { return [NSSet setWithArray:@[ @"objectValue", @"objectValue.readOnly", @"objectValue.excluded", @"objectValue.replaceString", @"replaceString", @"showReplacementPreviews", @"backgroundStyle" ]]; }
- (id)initWithViewController:(FFResultsViewController*)viewController font:(NSFont*)font
{
if((self = [super initWithFrame:NSZeroRect]))
{
self.viewController = viewController;
self.observeKeyPaths = @[ @"replaceString", @"showReplacementPreviews" ];
NSTextField* textField = OakCreateLabel(@"", font);
[textField setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
[textField setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
NSDictionary* views = @{
@"textField": textField,
};
OakAddAutoLayoutViewsToSuperview(views.allValues, self);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textField]" options:0 metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textField]|" options:0 metrics:nil views:views]];
[textField bind:NSValueBinding toObject:self withKeyPath:@"excerptString" options:nil];
self.textField = textField;
}
return self;
}
- (NSAttributedString*)excerptString
{
FFResultNode* item = self.objectValue;
NSAttributedString* res = [item excerptWithReplacement:(item.isReadOnly || item.excluded || !_showReplacementPreviews ? item.replaceString : self.replaceString) font:self.textField.font];
if(self.backgroundStyle == NSBackgroundStyleDark)
{
NSMutableAttributedString* str = [res mutableCopy];
[str enumerateAttributesInRange:NSMakeRange(0, str.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary* attrs, NSRange range, BOOL* stop){
if(attrs[NSBackgroundColorAttributeName] != nil)
[str addAttribute:NSBackgroundColorAttributeName value:[NSColor tmMatchedTextSelectedBackgroundColor] range:range];
if(attrs[NSUnderlineColorAttributeName] != nil)
[str addAttribute:NSUnderlineColorAttributeName value:[NSColor tmMatchedTextSelectedUnderlineColor] range:range];
}];
[str addAttribute:NSForegroundColorAttributeName value:[NSColor alternateSelectedControlTextColor] range:NSMakeRange(0, [str length])];
res = str;
}
return res;
}
@end
// ==================================
// = OakSearchResultsHeaderCellView =
// ==================================
@interface OakSearchResultsHeaderCellView : OakTableCellView
@property (nonatomic) NSButton* countOfLeafsButton;
@property (nonatomic) NSButton* removeButton;
@property (nonatomic) BOOL showKeyEquivalent;
@property (nonatomic) BOOL observingKeyEquivalent;
@end
@implementation OakSearchResultsHeaderCellView
- (id)initWithViewController:(FFResultsViewController*)viewController
{
if((self = [super init]))
{
self.viewController = viewController;
self.observeKeyPaths = @[ @"showKeyEquivalent" ];
NSImageView* imageView = [NSImageView new];
NSTextField* textField = OakCreateLabel(@"", [NSFont controlContentFontOfSize:0]);
NSButton* countOfLeafs = [NSButton new];
[[countOfLeafs cell] setHighlightsBy:NSNoCellMask];
countOfLeafs.alignment = NSTextAlignmentCenter;
countOfLeafs.bezelStyle = NSInlineBezelStyle;
countOfLeafs.font = [NSFont labelFontOfSize:0];
countOfLeafs.identifier = @"countOfLeafs";
NSButton* remove = [NSButton new];
[[remove cell] setControlSize:NSControlSizeSmall];
remove.bezelStyle = NSRoundRectBezelStyle;
remove.buttonType = NSMomentaryPushInButton;
remove.image = [NSImage imageNamed:NSImageNameRemoveTemplate];
NSDictionary* views = @{ @"icon" : imageView, @"text" : textField, @"count" : countOfLeafs, @"remove" : remove };
OakAddAutoLayoutViewsToSuperview([views allValues], self);
[textField setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
[countOfLeafs setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(9)-[remove(==16)]-(6)-[icon(==16)]-(3)-[text]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[text]-(4)-[count]-(>=8)-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[icon(==16,==remove)]-(3)-|" options:0 metrics:nil views:views]];
[imageView bind:NSValueBinding toObject:self withKeyPath:@"objectValue.document.icon" options:nil];
[textField bind:NSValueBinding toObject:self withKeyPath:@"objectValue.displayPath" options:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outlineViewItemDidExpandCollapse:) name:NSOutlineViewItemDidExpandNotification object:viewController.outlineView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outlineViewItemDidExpandCollapse:) name:NSOutlineViewItemDidCollapseNotification object:viewController.outlineView];
self.imageView = imageView;
self.textField = textField;
self.countOfLeafsButton = countOfLeafs;
self.removeButton = remove;
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setShowKeyEquivalent:(BOOL)flag
{
if(_showKeyEquivalent == flag)
return;
_showKeyEquivalent = flag;
FFResultNode* item = self.objectValue;
if(_showKeyEquivalent)
{
NSUInteger index = [item.parent.children indexOfObject:item];
if(!item || index > 8)
return;
NSRect rect = NSUnionRect(self.imageView.bounds, NSMakeRect(0, 0, 16, 16));
NSColor* color = [NSColor grayColor];
NSImage* image = [[NSImage alloc] initWithSize:rect.size];
[image lockFocus];
CGFloat ptrn[] = { 2, 1 };
NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:NSIntegralRect(NSInsetRect(rect, 1, 1)) xRadius:2 yRadius:2];
[path setLineDash:ptrn count:sizeofA(ptrn) phase:0];
[path setLineWidth:1];
[color set];
[path stroke];
NSMutableParagraphStyle* pStyle = [NSMutableParagraphStyle new];
[pStyle setAlignment:NSTextAlignmentCenter];
NSDictionary* attributes = @{
NSFontAttributeName : [NSFont boldSystemFontOfSize:0],
NSForegroundColorAttributeName : color,
NSParagraphStyleAttributeName : pStyle,
};
NSAttributedString* str = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%lu", (index + 1) % 10] attributes:attributes];
NSSize size = [str size];
rect.origin.y = 0.5 * (NSHeight(rect) - size.height);
rect.size.height = size.height;
[str drawInRect:NSIntegralRect(rect)];
[image unlockFocus];
[self.imageView setImage:image];
}
else
{
self.imageView.image = item.document.icon;
}
}
- (void)outlineViewItemDidExpandCollapse:(NSNotification*)aNotification
{
NSOutlineView* outlineView = [aNotification object];
NSDictionary* userInfo = [aNotification userInfo];
FFResultNode* item = userInfo[@"NSObject"];
if(item == self.objectValue)
_countOfLeafsButton.hidden = [outlineView isItemExpanded:item];
}
- (void)outlineViewItemDidExpand:(NSNotification*)aNotification { [self outlineViewItemDidExpandCollapse:aNotification]; }
- (void)outlineViewItemDidCollapse:(NSNotification*)aNotification { [self outlineViewItemDidExpandCollapse:aNotification]; }
@end
// ===========================
// = FFResultsViewController =
// ===========================
@implementation FFResultsViewController
- (void)loadView
{
if(!_scrollView)
{
NSString* fontName = [[NSUserDefaults standardUserDefaults] stringForKey:kUserDefaultsSearchResultsFontNameKey];
CGFloat fontSize = [[NSUserDefaults standardUserDefaults] floatForKey:kUserDefaultsSearchResultsFontSizeKey] ?: 11.0;
_searchResultsFont = (fontName ? [NSFont fontWithName:fontName size:fontSize] : [NSFont controlContentFontOfSize:fontSize]);
NSTextField* label = OakCreateLabel(@"m", _searchResultsFont);
[label sizeToFit];
CGFloat lineHeight = std::max(NSHeight(label.frame), ceil(_searchResultsFont.ascender) + ceil(fabs(_searchResultsFont.descender)) + ceil(_searchResultsFont.leading));
_topDivider = OakCreateHorizontalLine([NSColor colorWithCalibratedWhite:0.500 alpha:1]);
_bottomDivider = OakCreateHorizontalLine([NSColor colorWithCalibratedWhite:0.500 alpha:1]);
_outlineView = [[NSOutlineView alloc] initWithFrame:NSZeroRect];
OakSetAccessibilityLabel(_outlineView, @"Results");
_outlineView.focusRingType = NSFocusRingTypeNone;
_outlineView.allowsMultipleSelection = YES;
_outlineView.autoresizesOutlineColumn = NO;
_outlineView.usesAlternatingRowBackgroundColors = YES;
_outlineView.headerView = nil;
_outlineView.rowHeight = std::max(lineHeight, 14.0);
_outlineView.columnAutoresizingStyle = NSTableViewNoColumnAutoresizing;
NSTableColumn* tableColumn = [[NSTableColumn alloc] initWithIdentifier:@"checkbox"];
tableColumn.width = 50;
[_outlineView addTableColumn:tableColumn];
[_outlineView setOutlineTableColumn:tableColumn];
tableColumn = [[NSTableColumn alloc] initWithIdentifier:@"match"];
[tableColumn setEditable:NO];
[_outlineView addTableColumn:tableColumn];
_scrollView = [[NSScrollView alloc] initWithFrame:NSZeroRect];
_scrollView.hasVerticalScroller = YES;
_scrollView.hasHorizontalScroller = YES;
_scrollView.autohidesScrollers = YES;
_scrollView.borderType = NSNoBorder;
_scrollView.documentView = _outlineView;
NSDictionary* views = @{
@"topDivider" : _topDivider,
@"scrollView" : _scrollView,
@"bottomDivider" : _bottomDivider,
};
NSView* containerView = [[NSView alloc] initWithFrame:NSZeroRect];
OakAddAutoLayoutViewsToSuperview([views allValues], containerView);
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topDivider][scrollView][bottomDivider]|" options:NSLayoutFormatAlignAllLeading|NSLayoutFormatAlignAllTrailing metrics:nil views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:nil views:views]];
self.view = containerView;
_outlineView.dataSource = self;
_outlineView.delegate = self;
_outlineView.target = self;
_outlineView.action = @selector(didSingleClick:);
_outlineView.doubleAction = @selector(didDoubleClick:);
_eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged handler:^NSEvent*(NSEvent* event){
NSUInteger modifierFlags = [_outlineView.window isKeyWindow] ? ([event modifierFlags] & (NSEventModifierFlagShift|NSEventModifierFlagControl|NSEventModifierFlagOption|NSEventModifierFlagCommand)) : 0;
if(_longPressedCommandModifier)
{
self.showKeyEquivalent = modifierFlags == NSEventModifierFlagCommand;
if(modifierFlags == 0)
_longPressedCommandModifier = NO;
}
else
{
if(modifierFlags == NSEventModifierFlagCommand)
[self performSelector:@selector(delayedLongPressedCommandModifier:) withObject:self afterDelay:0.2];
else [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayedLongPressedCommandModifier:) object:self];
}
return event;
}];
}
}
- (void)delayedLongPressedCommandModifier:(id)sender
{
_longPressedCommandModifier = YES;
self.showKeyEquivalent = YES;
}
- (void)dealloc
{
[NSEvent removeMonitor:_eventMonitor];
}
- (void)setResults:(FFResultNode*)someResults
{
[_outlineView sizeLastColumnToFit];
_results = someResults;
[_outlineView reloadData];
}
- (NSArray*)selectedResults
{
NSMutableArray* res = [NSMutableArray array];
NSIndexSet* selectedRows = [_outlineView numberOfSelectedRows] == 0 ? [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [_outlineView numberOfRows])] : [_outlineView selectedRowIndexes];
for(NSUInteger index = [selectedRows firstIndex]; index != NSNotFound; index = [selectedRows indexGreaterThanIndex:index])
{
FFResultNode* item = [_outlineView itemAtRow:index];
if([item.children count] == 0)
[res addObject:item];
}
return res;
}
- (void)setHideCheckBoxes:(BOOL)flag
{
if(_hideCheckBoxes == flag)
return;
_hideCheckBoxes = flag;
[[_outlineView tableColumnWithIdentifier:@"checkbox"] setHidden:flag];
[_outlineView setOutlineTableColumn:[_outlineView tableColumnWithIdentifier:flag ? @"match" : @"checkbox"]];
}
- (void)insertItemsAtIndexes:(NSIndexSet*)anIndexSet
{
[_outlineView beginUpdates];
[_outlineView insertItemsAtIndexes:anIndexSet inParent:nil withAnimation:0];
for(FFResultNode* item in [_results.children objectsAtIndexes:anIndexSet])
[_outlineView expandItem:item];
[_outlineView endUpdates];
}
- (void)showResultNode:(FFResultNode*)aResultNode
{
if(!aResultNode)
return;
if(![_outlineView isItemExpanded:aResultNode.parent])
[_outlineView expandItem:aResultNode.parent];
[_outlineView scrollRowToVisible:[_outlineView rowForItem:aResultNode.parent]];
NSInteger row = [_outlineView rowForItem:aResultNode];
if(row != -1)
{
[_outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
[_outlineView scrollRowToVisible:row];
[_outlineView.window makeFirstResponder:_outlineView];
}
}
// ==================
// = Action Methods =
// ==================
- (void)selectNextResultWrapAround:(BOOL)wrapAround
{
NSInteger row = [_outlineView selectedRow];
FFResultNode* item = row == -1 ? nil : [_outlineView itemAtRow:row];
item = item ? (NextNode(item) ?: NextNode(item.parent).firstResultNode) : _results.firstResultNode.firstResultNode;
if(!item && wrapAround)
item = _results.firstResultNode.firstResultNode;
[self showResultNode:item];
}
- (void)selectPreviousResultWrapAround:(BOOL)wrapAround
{
NSInteger row = [_outlineView selectedRow];
FFResultNode* item = row == -1 ? nil : [_outlineView itemAtRow:row];
item = item ? (PreviousNode(item) ?: PreviousNode(item.parent).lastResultNode) : _results.lastResultNode.lastResultNode;
if(!item && wrapAround)
item = _results.lastResultNode.lastResultNode;
[self showResultNode:item];
}
- (IBAction)toggleCollapsedState:(id)anArgument
{
if(self.isCollapsed)
[_outlineView expandItem:nil expandChildren:YES];
else [_outlineView collapseItem:nil collapseChildren:YES];
}
- (IBAction)selectNextDocument:(id)sender
{
NSInteger row = [_outlineView selectedRow];
FFResultNode* item = row == -1 ? nil : [_outlineView itemAtRow:row];
[self showResultNode:NextNode(item.parent).firstResultNode ?: _results.firstResultNode.firstResultNode];
}
- (IBAction)selectPreviousDocument:(id)sender
{
NSInteger row = [_outlineView selectedRow];
FFResultNode* item = row == -1 ? nil : [_outlineView itemAtRow:row];
[self showResultNode:PreviousNode(item.parent).firstResultNode ?: _results.lastResultNode.firstResultNode];
}
// ==================
// = Helper Methods =
// ==================
- (BOOL)isCollapsed
{
NSUInteger expanded = 0;
for(FFResultNode* parent in _results.children)
expanded += [_outlineView isItemExpanded:parent] ? 1 : 0;
return [_results.children count] && 2 * expanded <= [_results.children count];
}
// ========================
// = Table (Cell) Actions =
// ========================
- (void)toggleExcludedCheckbox:(NSButton*)sender
{
NSInteger row = [_outlineView rowForView:sender];
if(row != -1)
{
FFResultNode* item = [_outlineView itemAtRow:row];
BOOL toggleAllInGroup = OakIsAlternateKeyOrMouseEvent();
if(toggleAllInGroup)
item.parent.excluded = item.excluded;
if(_showReplacementPreviews)
{
NSRange range = NSMakeRange(row, 1);
if(toggleAllInGroup)
range = NSMakeRange([_outlineView rowForItem:item.parent.firstResultNode], item.parent.countOfLeafs);
[_outlineView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndexesInRange:range] columnIndexes:[NSIndexSet indexSetWithIndex:1]];
}
}
}
- (void)takeSearchResultToRemoveFrom:(NSButton*)sender
{
NSInteger row = [_outlineView rowForView:sender];
if(row != -1)
{
FFResultNode* item = [_outlineView itemAtRow:row];
NSUInteger index = [item.parent.children indexOfObject:item];
if(index != NSNotFound)
[_outlineView removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:index] inParent:nil withAnimation:NSTableViewAnimationEffectFade|NSTableViewAnimationSlideDown];
[item removeFromParent];
if(_removeResultAction)
[NSApp sendAction:_removeResultAction to:_target from:item];
}
}
- (void)didSelectResult:(FFResultNode*)resultNode
{
if(_lastSelectedResult == resultNode)
return;
// Prevent sending selectResultAction twice since mouse clicks sends both didSingleClick: and outlineViewSelectionDidChange:
_lastSelectedResult = resultNode;
dispatch_async(dispatch_get_main_queue(), ^{
_lastSelectedResult = nil;
});
if(_selectResultAction)
[NSApp sendAction:_selectResultAction to:_target from:resultNode];
}
- (void)didSingleClick:(id)sender
{
if(_outlineView.clickedRow != -1 && _outlineView.numberOfSelectedRows == 1)
[self didSelectResult:[_outlineView itemAtRow:_outlineView.clickedRow]];
}
- (void)didDoubleClick:(id)sender
{
if(_outlineView.clickedRow != -1 && _doubleClickResultAction)
{
[self didSelectResult:[_outlineView itemAtRow:_outlineView.clickedRow]];
[NSApp sendAction:_doubleClickResultAction to:_target from:[_outlineView itemAtRow:_outlineView.clickedRow]];
}
}
- (void)outlineViewSelectionDidChange:(NSNotification*)aNotification
{
if(_outlineView.numberOfSelectedRows == 1)
[self didSelectResult:[_outlineView itemAtRow:_outlineView.selectedRowIndexes.firstIndex]];
}
- (BOOL)outlineView:(NSOutlineView*)outlineView shouldSelectItem:(FFResultNode*)item
{
return ![self outlineView:outlineView isGroupItem:item];
}
// ============================
// = Outline view data source =
// ============================
- (NSInteger)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(FFResultNode*)item
{
return [(item ?: _results).children count];
}
- (BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(FFResultNode*)item
{
return [self outlineView:outlineView isGroupItem:item];
}
- (id)outlineView:(NSOutlineView*)outlineView child:(NSInteger)childIndex ofItem:(FFResultNode*)item
{
return [(item ?: _results).children objectAtIndex:childIndex];
}
- (BOOL)outlineView:(NSOutlineView*)outlineView isGroupItem:(FFResultNode*)item
{
return [outlineView levelForItem:item] == 0;
}
- (CGFloat)outlineView:(NSOutlineView*)outlineView heightOfRowByItem:(FFResultNode*)item
{
return [self outlineView:outlineView isGroupItem:item] ? 22 : item.lineSpan * [outlineView rowHeight];
}
- (void)commitPendingColumnWidth:(NSTableColumn*)tableColumn
{
if(_pendingColumnWidth)
{
tableColumn.minWidth = MIN(_pendingColumnWidth, tableColumn.minWidth);
tableColumn.maxWidth = MAX(_pendingColumnWidth, tableColumn.maxWidth);
tableColumn.width = _pendingColumnWidth;
_pendingColumnWidth = 0;
}
}
- (NSView*)outlineView:(NSOutlineView*)outlineView viewForTableColumn:(NSTableColumn*)tableColumn item:(FFResultNode*)item
{
NSString* identifier = tableColumn.identifier ?: @"group";
id res = [outlineView makeViewWithIdentifier:identifier owner:self];
if([identifier isEqualToString:@"checkbox"])
{
OakSearchResultsCheckboxView* cellView = res;
if(!cellView)
{
res = cellView = [[OakSearchResultsCheckboxView alloc] initWithFrame:NSZeroRect];
cellView.identifier = identifier;
cellView.button.action = @selector(toggleExcludedCheckbox:);
cellView.button.target = self;
}
cellView.objectValue = item;
}
else if([identifier isEqualToString:@"match"])
{
OakSearchResultsMatchCellView* cellView = res;
if(!cellView)
{
res = cellView = [[OakSearchResultsMatchCellView alloc] initWithViewController:self font:_searchResultsFont];
cellView.identifier = identifier;
}
cellView.objectValue = item;
[cellView layoutSubtreeIfNeeded];
CGFloat width = NSMaxX(cellView.textField.frame) + 32;
if(tableColumn.width < width && _pendingColumnWidth < width)
{
if(_pendingColumnWidth == 0)
[self performSelector:@selector(commitPendingColumnWidth:) withObject:tableColumn afterDelay:0];
_pendingColumnWidth = width;
}
}
else
{
OakSearchResultsHeaderCellView* cellView = res;
if(!cellView)
{
res = cellView = [[OakSearchResultsHeaderCellView alloc] initWithViewController:self];
cellView.identifier = identifier;
cellView.removeButton.action = @selector(takeSearchResultToRemoveFrom:);
cellView.removeButton.target = self;
}
cellView.objectValue = item;
cellView.countOfLeafsButton.title = [NSNumberFormatter localizedStringFromNumber:@(item.countOfLeafs) numberStyle:NSNumberFormatterDecimalStyle];
cellView.countOfLeafsButton.hidden = [outlineView isItemExpanded:item];
}
return res;
}
// ===================
// = Menu Validation =
// ===================
- (BOOL)validateMenuItem:(NSMenuItem*)aMenuItem
{
BOOL res = YES;
if(aMenuItem.action == @selector(toggleCollapsedState:))
{
[aMenuItem setTitle:self.isCollapsed ? @"Expand Results" : @"Collapse Results"];
res = _results.countOfLeafs != 0;
}
return res;
}
@end