-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathiTermGlobalSearchWindowController.m
More file actions
544 lines (487 loc) · 21.2 KB
/
Copy pathiTermGlobalSearchWindowController.m
File metadata and controls
544 lines (487 loc) · 21.2 KB
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
//
// iTermGlobalSearchWindowController.m
// iTerm2SharedARC
//
// Created by George Nachman on 8/22/20.
//
#import "iTermGlobalSearchWindowController.h"
#import "FindContext.h"
#import "iTerm2SharedARC-Swift.h"
#import "iTermController.h"
#import "NSAppearance+iTerm.h"
#import "iTermFocusReportingTextField.h"
#import "iTermGlobalSearchEngine.h"
#import "iTermGlobalSearchOutlineView.h"
#import "iTermGlobalSearchResult.h"
#import "iTermSearchFieldCell.h"
#import "iTermUserDefaults.h"
#import "NSArray+iTerm.h"
#import "NSDictionary+iTerm.h"
#import "NSTextField+iTerm.h"
#import "PTYSession.h"
#import "PTYTab.h"
#import "PseudoTerminal.h"
#import "SearchResult.h"
#import "VT100Screen.h"
@interface iTermGlobalSearchWindowController ()<
iTermFocusReportingSearchFieldDelegate,
NSOutlineViewDelegate,
NSOutlineViewDataSource,
NSWindowDelegate>
@end
@implementation iTermGlobalSearchWindowController {
iTermGlobalSearchEngine *_engine;
NSMutableDictionary<NSString *, NSMutableArray<id<iTermGlobalSearchResultProtocol>> *> *_results;
IBOutlet iTermFocusReportingSearchField *_searchField;
IBOutlet NSPopUpButton *_findType;
IBOutlet NSOutlineView *_outlineView;
IBOutlet NSPanel *_panel;
BOOL _ignoreClick;
// Fades out the progress indicator.
NSTimer *_animationTimer;
NSMutableDictionary<NSString *, NSNumber *> *_state;
}
- (instancetype)init {
self = [super initWithWindowNibName:@"iTermGlobalSearch"];
if (self) {
_state = [NSMutableDictionary dictionary];
}
return self;
}
- (void)windowDidLoad {
self.window.delegate = self;
self.window.level = NSFloatingWindowLevel;
PTYSession *session = [[iTermController sharedInstance] currentTerminal].currentSession;
self.window.appearance = [NSAppearance it_appearanceForCurrentSessionWithBackgroundColor:session.effectiveUnprocessedBackgroundColor];
[_outlineView expandItem:nil expandChildren:YES];
_panel.becomesKeyOnlyIfNeeded = YES;
[_findType selectItemWithTag:[iTermUserDefaults globalSearchMode]];
_outlineView.target = self;
_outlineView.action = @selector(didClick:);
// Make never-before-made-visible webviews load their URLs or interaction state so they will be searchable. This is a race
// because they won't be searchable until the document starts and they won't be usefully searchable until "enough" of the
// document loads (which could take infinite time, oh well)
[[[iTermController sharedInstance] terminals] enumerateObjectsUsingBlock:^(PseudoTerminal *term, NSUInteger idx, BOOL *stop) {
for (PTYSession *session in term.allSessions) {
if (session.isBrowserSession) {
[session.view.browserViewController performDeferredInitializationInWindow:term.window];
}
}
}];
}
- (void)windowWillClose:(NSNotification *)notification {
[self restoreAlternateScreensWithAnnouncement:YES];
}
- (void)dealloc {
[self restoreAlternateScreensWithAnnouncement:YES];
}
- (NSArray<PTYSession *> *)sessions {
return [[[iTermController sharedInstance] terminals] flatMapWithBlock:^NSArray *(PseudoTerminal *terminal) {
return [terminal.tabs flatMapWithBlock:^NSArray *(PTYTab *tab) {
return tab.sessions;
}];
}];
}
- (void)setFraction:(double)progress {
iTermSearchFieldCell *cell = [iTermSearchFieldCell castFrom:_searchField.cell];
if (round(progress * 100) != round(cell.fraction * 100)) {
[_searchField setNeedsDisplay:YES];
}
[cell setFraction:progress];
if (cell.needsAnimation && !_animationTimer) {
_animationTimer = [NSTimer scheduledTimerWithTimeInterval:1/60.0
target:self
selector:@selector(redrawSearchField:)
userInfo:nil
repeats:YES];
}
}
- (void)redrawSearchField:(NSTimer *)timer {
iTermSearchFieldCell *cell = [iTermSearchFieldCell castFrom:_searchField.cell];
[cell willAnimate];
if (!cell.needsAnimation) {
[_animationTimer invalidate];
_animationTimer = nil;
}
[_searchField setNeedsDisplay:YES];
}
- (void)addResults:(NSArray<id<iTermGlobalSearchResultProtocol>> *)results
forSession:(PTYSession *)session
progress:(double)progress {
if (!session) {
// Finished searching.
[self setFraction:1];
return;
}
[self setFraction:progress];
if (!results.count) {
return;
}
if (!_results) {
_results = [NSMutableDictionary dictionary];
}
NSMutableArray<id<iTermGlobalSearchResultProtocol>> *sessionResults = _results[session.guid];
[_outlineView beginUpdates];
BOOL isNew = (sessionResults == nil);
if (!sessionResults) {
sessionResults = [NSMutableArray array];
_results[(NSString * _Nonnull)session.guid] = sessionResults;
}
NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(sessionResults.count, results.count)];
[sessionResults addObjectsFromArray:results];
BOOL expand = NO;
if (isNew) {
const NSUInteger i = [self.sortedNonEmptyResultSessionGUIDs indexOfObject:session.guid];
if (i != NSNotFound) {
[_outlineView insertItemsAtIndexes:[NSIndexSet indexSetWithIndex:i]
inParent:nil
withAnimation:NO];
expand = YES;
}
}
[_outlineView insertItemsAtIndexes:indexes
inParent:session.guid
withAnimation:NO];
if (expand) {
[_outlineView expandItem:session.guid expandChildren:YES];
}
[_outlineView endUpdates];
[_searchField setNeedsDisplay:YES];
}
static double Square(double n) {
return n * n;
}
static double EuclideanDistance(NSPoint p1, NSPoint p2) {
return sqrt(Square(p1.x - p2.x) + Square(p1.y - p2.y));
}
- (void)revealSelection {
[_searchField setNeedsDisplay:YES];
id item = [_outlineView itemAtRow:_outlineView.selectedRow];
NSString *guid = [NSString castFrom:item];
if (guid) {
PTYSession *session = [[iTermController sharedInstance] sessionWithGUID:guid];
[self restoreAlternateScreensWithAnnouncement:YES];
[session reveal];
return;
}
id<iTermGlobalSearchResultProtocol> result;
if (![item conformsToProtocol:@protocol(iTermGlobalSearchResultProtocol)]) {
[self restoreAlternateScreensWithAnnouncement:YES];
return;
}
result = (id<iTermGlobalSearchResultProtocol>)item;
// If this is a fold group, just toggle expand — don't reveal/unfold.
if ([item isKindOfClass:[iTermGlobalSearchFoldGroup class]]) {
if ([_outlineView isItemExpanded:item]) {
[_outlineView collapseItem:item];
} else {
[_outlineView expandItem:item];
}
return;
}
[result.session reveal];
__weak __typeof(self) weakSelf = self;
[result revealWithState:_state completion:^(NSRect hull) {
if (hull.size.width > 0 && hull.size.height > 0) {
[weakSelf movePanelAwayFromRect:hull];
}
}];
}
- (void)movePanelAwayFromRect:(NSRect)hull {
const NSRect windowRect = _panel.frame;
if (!NSIntersectsRect(windowRect, hull)) {
return;
}
// Move it above, below, left, or right. Pick the option where the least amount of the
// window falls off the screen.
NSRect candidates[] = {
NSMakeRect(NSMinX(hull) - NSWidth(windowRect), // left
NSMinY(windowRect),
NSWidth(windowRect),
NSHeight(windowRect)),
NSMakeRect(NSMaxX(hull), // right
NSMinY(windowRect),
NSWidth(windowRect),
NSHeight(windowRect)),
NSMakeRect(NSMinX(windowRect), // down
NSMaxY(hull),
NSWidth(windowRect),
NSHeight(windowRect)),
NSMakeRect(NSMinX(windowRect), // up
NSMinY(hull) - NSHeight(windowRect),
NSWidth(windowRect),
NSHeight(windowRect)),
};
const NSRect screenFrame = _panel.screen.visibleFrame;
const CGFloat totalArea = NSWidth(_panel.frame) * NSHeight(_panel.frame);
CGFloat bestAreaOffScreen = INFINITY;
CGFloat bestDistance = INFINITY;
int bestIndex = -1;
for (int i = 0; i < sizeof(candidates) / sizeof(*candidates); i++) {
const NSRect onScreenRect = NSIntersectionRect(candidates[i], screenFrame);
const CGFloat areaOffScreen = totalArea - (onScreenRect.size.width * onScreenRect.size.height);
const CGFloat distance = EuclideanDistance(_panel.frame.origin, candidates[i].origin);
if (bestAreaOffScreen > areaOffScreen) {
bestAreaOffScreen = areaOffScreen;
bestDistance = distance;
bestIndex = i;
} else if (bestAreaOffScreen == areaOffScreen && bestDistance > distance) {
bestDistance = distance;
bestIndex = i;
}
}
if (bestIndex != -1) {
[_panel setFrame:candidates[bestIndex] display:YES animate:YES];
}
}
- (void)activate {
[self.window makeKeyAndOrderFront:nil];
[_searchField.window makeFirstResponder:_searchField];
}
- (IBAction)closeCurrentSession:(id)sender {
[self close];
}
- (void)closeWindow:(id)sender {
[self close];
}
- (BOOL)autoHidesHotKeyWindow {
return NO;
}
#pragma mark - NSWindowDelegate
- (void)windowDidBecomeKey:(NSNotification *)notification {
[self.window makeFirstResponder:_searchField];
}
#pragma mark - Actions
- (IBAction)modeDidChange:(id)sender {
[self search:nil];
[iTermUserDefaults setGlobalSearchMode:_findType.selectedTag];
}
- (iTermFindMode)mode {
return _findType.selectedTag;
}
- (IBAction)search:(id)sender {
[_engine stop];
_results = [NSMutableDictionary dictionary];
[self setFraction:0];
[_outlineView reloadData];
if (_searchField.stringValue.length == 0) {
return;
}
__weak __typeof(self) weakSelf = self;
_engine = [[iTermGlobalSearchEngine alloc] initWithQuery:_searchField.stringValue
sessions:self.sessions
mode:self.mode
handler:^(PTYSession *session,
NSArray<id<iTermGlobalSearchResultProtocol>> *results,
double progress) {
[weakSelf addResults:results forSession:session progress:progress];
}];
}
- (void)didClick:(id)sender {
if (_ignoreClick) {
return;
}
[self revealSelection];
}
#pragma mark - iTermFocusReportingSearchFieldDelegate
- (void)focusReportingSearchFieldWillBecomeFirstResponder:(iTermFocusReportingSearchField *)sender {
}
- (NSInteger)focusReportingSearchFieldNumberOfResults:(iTermFocusReportingSearchField *)sender {
__block NSInteger count = 0;
[_results enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSMutableArray<id<iTermGlobalSearchResultProtocol>> * _Nonnull obj, BOOL * _Nonnull stop) {
count += obj.count;
}];
return count;
}
- (NSInteger)focusReportingSearchFieldCurrentIndex:(iTermFocusReportingSearchField *)sender {
const NSInteger row = [_outlineView selectedRow];
if (row == NSNotFound) {
return 0;
}
id item = [_outlineView itemAtRow:row];
id<iTermGlobalSearchResultProtocol>result = [iTermGlobalSearchResult castFrom:item];
if (!result) {
return 0;
}
NSInteger i = 0;
for (NSString *guid in [self sortedNonEmptyResultSessionGUIDs]) {
if (![guid isEqualToString:result.session.guid]) {
i += _results[guid].count;
} else {
const NSInteger subindex = [_results[guid] indexOfObject:result];
if (subindex == NSNotFound) {
return 0;
}
i += subindex;
return i + 1;
}
}
return 0;
}
#pragma mark - NSOutlineViewDelegate
- (nullable NSView *)outlineView:(NSOutlineView *)outlineView
viewForTableColumn:(nullable NSTableColumn *)tableColumn
item:(id)item {
NSString *guid = [NSString castFrom:item];
if (guid) {
// Session
NSString *identifier = @"GlobalSearchSessionIdentifier";
NSTableCellView *view = [outlineView makeViewWithIdentifier:identifier owner:self];
if (!view) {
view = [[NSTableCellView alloc] init];
NSTextField *textField = [NSTextField it_textFieldForTableViewWithIdentifier:identifier];
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
view.textField = textField;
[view addSubview:textField];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[textField]-0-|"
options:0
metrics:nil
views:@{ @"textField": textField }]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:textField
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
textField.frame = view.bounds;
textField.autoresizingMask = (NSViewWidthSizable | NSViewHeightSizable);
}
view.textField.stringValue = [[[[iTermController sharedInstance] sessionWithGUID:guid] name] removingHTMLFromTabTitleIfNeeded] ?: @"Session";
return view;
}
iTermGlobalSearchFoldGroup *foldGroup = [iTermGlobalSearchFoldGroup castFrom:item];
if (foldGroup) {
NSString *identifier = @"GlobalSearchFoldGroupIdentifier";
NSTableCellView *view = [outlineView makeViewWithIdentifier:identifier owner:self];
if (!view) {
view = [[NSTableCellView alloc] init];
NSImageView *imageView = [NSImageView imageViewWithImage:[NSImage imageWithSystemSymbolName:@"rectangle.compress.vertical"
accessibilityDescription:@"Folded region"]];
imageView.translatesAutoresizingMaskIntoConstraints = NO;
imageView.contentTintColor = [NSColor secondaryLabelColor];
[imageView setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
view.imageView = imageView;
[view addSubview:imageView];
NSTextField *textField = [NSTextField it_textFieldForTableViewWithIdentifier:identifier];
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
view.textField = textField;
[view addSubview:textField];
NSDictionary *views = @{ @"icon": imageView, @"textField": textField };
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[icon]-4-[textField]-0-|"
options:0
metrics:nil
views:views]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:imageView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:textField
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
}
view.textField.attributedStringValue = foldGroup.snippet;
return view;
}
ITAssertWithMessage([item conformsToProtocol:@protocol(iTermGlobalSearchResultProtocol)], @"Bad item %@", item);
id<iTermGlobalSearchResultProtocol> result = item;
// Search result
NSString *identifier = @"GlobalSearchResultIdentifier";
NSTableCellView *view = [outlineView makeViewWithIdentifier:identifier owner:self];
if (!view) {
view = [[NSTableCellView alloc] init];
NSTextField *textField = [NSTextField it_textFieldForTableViewWithIdentifier:identifier];
textField.translatesAutoresizingMaskIntoConstraints = NO;
view.textField = textField;
[view addSubview:textField];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[textField]-0-|"
options:0
metrics:nil
views:@{ @"textField": textField }]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:textField
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
textField.frame = view.bounds;
textField.autoresizingMask = (NSViewWidthSizable | NSViewHeightSizable);
}
view.textField.attributedStringValue = result.snippet;
return view;
}
- (void)restoreAlternateScreensWithAnnouncement:(BOOL)announce {
[iTermGlobalSearchResult restoreAlternateScreensWithAnnouncement:announce state:_state];
}
- (void)outlineViewSelectionDidChange:(NSNotification *)notification {
_ignoreClick = YES;
dispatch_async(dispatch_get_main_queue(), ^{
self->_ignoreClick = NO;
});
[self revealSelection];
}
#pragma mark - NSOutlineViewDataSource
- (NSDictionary<NSString *, NSMutableArray<id<iTermGlobalSearchResultProtocol>> *> *)nonEmptyResults {
return [_results filteredWithBlock:^BOOL(NSString *key, NSMutableArray<id<iTermGlobalSearchResultProtocol>> *value) {
return value.count > 0;
}];
}
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(nullable id)item {
if (item == nil) {
return self.nonEmptyResults.count;
}
if ([item isKindOfClass:[NSString class]]) {
return [_results[item] count];
}
iTermGlobalSearchFoldGroup *group = [iTermGlobalSearchFoldGroup castFrom:item];
if (group) {
return group.results.count;
}
return 0;
}
- (NSArray<NSString *> *)sortedNonEmptyResultSessionGUIDs {
return [self.nonEmptyResults.allKeys sortedArrayUsingSelector:@selector(compare:)];
}
// An item is either nil (the root), a string (a session), a fold group, or a search result.
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(nullable id)item {
if (item == nil) {
NSArray<NSString *> *sortedKeys = self.sortedNonEmptyResultSessionGUIDs;
return sortedKeys[index];
}
if ([item isKindOfClass:[NSString class]]) {
NSArray<id<iTermGlobalSearchResultProtocol>> *results = _results[item];
assert(results);
assert(index >= 0);
assert(index < results.count);
return results[index];
}
iTermGlobalSearchFoldGroup *group = [iTermGlobalSearchFoldGroup castFrom:item];
if (group) {
return group.results[index];
}
assert(false);
return nil;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
if (item == nil) {
return YES;
}
if ([item isKindOfClass:[NSString class]]) {
return YES;
}
if ([item isKindOfClass:[iTermGlobalSearchFoldGroup class]]) {
return YES;
}
return NO;
}
@end