forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiTermOpenQuicklyWindowController.m
475 lines (419 loc) · 18.6 KB
/
iTermOpenQuicklyWindowController.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
#import "iTermOpenQuicklyWindowController.h"
#import "ITAddressBookMgr.h"
#import "iTermApplication.h"
#import "iTermApplicationDelegate.h"
#import "iTermController.h"
#import "iTermHotKeyController.h"
#import "iTermProfileHotKey.h"
#import "iTermOpenQuicklyItem.h"
#import "iTermOpenQuicklyModel.h"
#import "iTermOpenQuicklyTableCellView.h"
#import "iTermOpenQuicklyTableRowView.h"
#import "iTermOpenQuicklyTextField.h"
#import "iTermScriptsMenuController.h"
#import "iTermSessionLauncher.h"
#import "iTermSnippetsMenuController.h"
#import "NSColor+iTerm.h"
#import "NSObject+iTerm.h"
#import "NSTextField+iTerm.h"
#import "NSWindow+iTerm.h"
#import "PseudoTerminal.h"
#import "PTYTab.h"
#import "SolidColorView.h"
#import "VT100RemoteHost.h"
@interface iTermOpenQuicklyWindowController () <
iTermOpenQuicklyTextFieldDelegate,
iTermOpenQuicklyModelDelegate,
NSTableViewDataSource,
NSTableViewDelegate,
NSWindowDelegate>
@property(nonatomic, retain) iTermOpenQuicklyModel *model;
@end
@implementation iTermOpenQuicklyWindowController {
// Text field where queries are entered
IBOutlet iTermOpenQuicklyTextField *_textField;
// Table that shows search results
IBOutlet NSTableView *_table;
IBOutlet NSScrollView *_scrollView;
IBOutlet SolidColorView *_divider;
}
+ (instancetype)sharedInstance {
static id instance;
static dispatch_once_t once;
dispatch_once(&once, ^{
instance = [[self alloc] init];
});
return instance;
}
- (instancetype)init {
self = [super initWithWindowNibName:@"iTermOpenQuicklyWindowController"];
if (self) {
_model = [[iTermOpenQuicklyModel alloc] init];
_model.delegate = self;
}
return self;
}
- (void)dealloc {
[_model release];
[super dealloc];
}
- (void)awakeFromNib {
// Initialize the table
#ifdef MAC_OS_X_VERSION_10_16
if (@available(macOS 10.16, *)) {
_table.style = NSTableViewStyleInset;
// Possibly a 10.16 beta bug? Using intercell spacing clips the selection rect.
_table.intercellSpacing = NSZeroSize;
}
#endif
[_table setDoubleAction:@selector(doubleClick:)];
// Initialize the window's contentView
SolidColorView *contentView = [self.window contentView];
// Initialize the window
[self.window setOpaque:NO];
if (@available(macOS 10.14, *)) {
_table.backgroundColor = [NSColor clearColor];
_table.enclosingScrollView.drawsBackground = NO;
contentView.color = [NSColor clearColor];
self.window.backgroundColor = [NSColor clearColor];
} else {
_table.backgroundColor = [NSColor controlColor];
self.window.backgroundColor = [NSColor clearColor];
contentView.color = [NSColor controlColor];
}
// Rounded corners for contentView
contentView.wantsLayer = YES;
contentView.layer.cornerRadius = 6;
contentView.layer.masksToBounds = YES;
contentView.layer.borderColor = [[NSColor colorWithCalibratedRed:0.66 green:0.66 blue:0.66 alpha:1] CGColor];
contentView.layer.borderWidth = 0.5;
_divider.color = [NSColor colorWithCalibratedRed:0.66 green:0.66 blue:0.66 alpha:1];
[self updateTextColorForAllRows];
}
- (void)presentWindow {
[_model removeAllItems];
[_table reloadData];
// Set the window's frame to be table-less initially.
[self.window setFrame:[self frame] display:YES animate:NO];
[_textField selectText:nil];
[self.window it_makeKeyAndOrderFront];
// After the window is rendered, call update which will animate to the new frame.
[self performSelector:@selector(update) withObject:nil afterDelay:0];
}
// Recompute the model and update the window frame.
- (void)update {
[self.model updateWithQuery:_textField.stringValue];
[_table reloadData];
// We have to set the scrollview's size before animating the window or else
// it happens only after the animation finishes. I couldn't get
// autoresizing to do this automatically.
NSRect frame = [self frame];
NSRect contentViewFrame = [self.window frameRectForContentRect:frame];
_divider.hidden = (self.model.items.count == 0);
_scrollView.frame = NSMakeRect(_scrollView.frame.origin.x,
_scrollView.frame.origin.y,
contentViewFrame.size.width,
contentViewFrame.size.height - 41);
// Select the first item.
if (self.model.items.count) {
[_table selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
[self tableViewSelectionDidChange:[NSNotification notificationWithName:NSTableViewSelectionDidChangeNotification
object:nil]];
}
[self performSelector:@selector(resizeWindowAnimatedToFrame:)
withObject:[NSValue valueWithRect:frame]
afterDelay:0];
}
- (void)resizeWindowAnimatedToFrame:(NSValue *)frame {
[self.window setFrame:frame.rectValue display:YES animate:YES];
}
// Returns the window frame. It's a fixed 170px below the top of the screen and
// its height is variable up to a limit of 170px above the bottom of the
// screen.
- (NSRect)frame {
NSScreen *screen = [[NSApp keyWindow] screen];
if (!screen) {
screen = [NSScreen mainScreen];
}
static const CGFloat kMarginAboveField = 10;
static const CGFloat kMarginBelowField = 6;
static const CGFloat kMarginAboveWindow = 170;
CGFloat maxHeight = screen.frame.size.height - kMarginAboveWindow * 2;
CGFloat nonTableSpace = kMarginAboveField + _textField.frame.size.height + kMarginBelowField;
int numberOfVisibleRowsDesired = MIN(self.model.items.count,
(maxHeight - nonTableSpace) / (_table.rowHeight + _table.intercellSpacing.height));
NSRect frame = self.window.frame;
NSSize contentSize = frame.size;
contentSize.height = nonTableSpace;
if (numberOfVisibleRowsDesired > 0) {
// Use the bottom of the last visible cell's frame for the height of the table view portion
// of the window. This is the most reliable way of getting its max-Y position.
NSRect frameOfLastVisibleCell = [_table frameOfCellAtColumn:0
row:numberOfVisibleRowsDesired - 1];
contentSize.height += NSMaxY(frameOfLastVisibleCell);
if (@available(macOS 10.16, *)) {
contentSize.height += 10;
}
}
frame.size.height = contentSize.height;
frame.origin.x = NSMinX(screen.frame) + floor((screen.frame.size.width - frame.size.width) / 2);
frame.origin.y = NSMaxY(screen.frame) - kMarginAboveWindow - frame.size.height;
return frame;
}
// Bound to the close button.
- (IBAction)close:(id)sender {
[self.window close];
}
// Switch to the session associated with the currently selected row, closing
// this window.
- (void)openSelectedRow {
NSInteger row = [_table selectedRow];
if (row >= 0) {
id object = [self.model objectAtIndex:row];
if ([object isKindOfClass:[PTYSession class]]) {
// Switch to session
PTYSession *session = object;
if (session) {
NSWindowController<iTermWindowController> *term = session.delegate.realParentWindow;
[term makeSessionActive:session];
}
} else if ([object isKindOfClass:[Profile class]]) {
// Create a new tab/window
Profile *profile = object;
iTermProfileHotKey *profileHotkey = [[iTermHotKeyController sharedInstance] profileHotKeyForGUID:profile[KEY_GUID]];
if (!profileHotkey || profileHotkey.windowController.weaklyReferencedObject) {
// Create a new non-hotkey window
[iTermSessionLauncher launchBookmark:profile
inTerminal:[[iTermController sharedInstance] currentTerminal]
withURL:nil
hotkeyWindowType:iTermHotkeyWindowTypeNone
makeKey:YES
canActivate:YES
respectTabbingMode:NO
command:nil
makeSession:nil
didMakeSession:nil
completion:nil];
} else {
// Create the hotkey window for this profile
[[iTermHotKeyController sharedInstance] showWindowForProfileHotKey:profileHotkey url:nil];
}
} else if ([object isKindOfClass:[iTermOpenQuicklyArrangementItem class]]) {
// Load window arrangement
iTermOpenQuicklyArrangementItem *item = (iTermOpenQuicklyArrangementItem *)object;
[[iTermController sharedInstance] loadWindowArrangementWithName:item.identifier asTabsInTerminal:item.inTabs ? [[iTermController sharedInstance] currentTerminal] : nil];
} else if ([object isKindOfClass:[iTermOpenQuicklyChangeProfileItem class]]) {
// Change profile
iTermOpenQuicklyChangeProfileItem *item = object;
PseudoTerminal *term = [[iTermController sharedInstance] currentTerminal];
PTYSession *session = term.currentSession;
NSString *guid = [item identifier];
Profile *profile = [[ProfileModel sharedInstance] bookmarkWithGuid:guid];
if (profile) {
[session setProfile:profile preservingName:YES];
// Make sure the OS doesn't pick some random window to make key
[term.window makeKeyAndOrderFront:nil];
}
} else if ([object isKindOfClass:[iTermOpenQuicklyHelpItem class]]) {
iTermOpenQuicklyHelpItem *item = object;
_textField.stringValue = [item identifier];
[self update];
return;
} else if ([object isKindOfClass:[iTermOpenQuicklyScriptItem class]]) {
iTermOpenQuicklyScriptItem *item = [iTermOpenQuicklyScriptItem castFrom:object];
[[[[iTermApplication sharedApplication] delegate] scriptsMenuController] launchScriptWithRelativePath:item.identifier
arguments:@[]
explicitUserAction:YES];
} else if ([object isKindOfClass:[iTermOpenQuicklyColorPresetItem class]]) {
iTermOpenQuicklyColorPresetItem *item = [iTermOpenQuicklyColorPresetItem castFrom:object];
PseudoTerminal *term = [[iTermController sharedInstance] currentTerminal];
PTYSession *session = term.currentSession;
[session setColorsFromPresetNamed:item.presetName];
} else if ([object isKindOfClass:[iTermOpenQuicklyActionItem class]]) {
iTermOpenQuicklyActionItem *item = [iTermOpenQuicklyActionItem castFrom:object];
PseudoTerminal *term = [[iTermController sharedInstance] currentTerminal];
PTYSession *session = term.currentSession;
[session applyAction:item.action];
} else if ([object isKindOfClass:[iTermOpenQuicklySnippetItem class]]) {
iTermOpenQuicklySnippetItem *item = [iTermOpenQuicklySnippetItem castFrom:object];
PseudoTerminal *term = [[iTermController sharedInstance] currentTerminal];
PTYSession *session = term.currentSession;
[session.textview sendSnippet:item];
}
}
[self close:nil];
}
// Returns an almost-black color. NSTableView treats actual black specially,
// and will actually draw white text if the background is not white. It won't
// mess with very, very dark gray though.
- (NSColor *)blackColor {
return [NSColor colorWithCalibratedWhite:0.01 alpha:1];
}
#pragma mark - NSTableViewDataSource and NSTableViewDelegate
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return _model.items.count;
}
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
iTermOpenQuicklyTableCellView *result = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
iTermOpenQuicklyItem *item = _model.items[row];
item.view = result;
result.imageView.image = item.icon;
result.textField.attributedStringValue =
item.title ?: [[[NSAttributedString alloc] initWithString:@"Untitled" attributes:@{}] autorelease];
[result.textField.cell setLineBreakMode:NSLineBreakByTruncatingTail];
if (item.detail) {
result.detailTextField.attributedStringValue = item.detail;
[result.detailTextField.cell setLineBreakMode:NSLineBreakByTruncatingTail];
} else {
result.detailTextField.stringValue = @"";
}
NSColor *color;
NSColor *detailColor;
if (@available(macOS 10.14, *)) {
color = [NSColor labelColor];
detailColor = [NSColor secondaryLabelColor];
} else {
if (row == tableView.selectedRow) {
color = [NSColor whiteColor];
} else {
color = [self blackColor];
}
detailColor = color;
}
result.textField.textColor = color;
result.detailTextField.textColor = detailColor;
return result;
}
- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row {
if (@available(macOS 10.16, *)) {
return [[[iTermOpenQuicklyTableRowView_BigSur alloc] init] autorelease];
} else {
return [[[iTermOpenQuicklyTableRowView alloc] init] autorelease];
}
}
- (void)updateTextColorForAllRows {
if (@available(macOS 10.14, *)) {
return;
}
NSInteger row = [_table selectedRow];
// Fix up text color for all items
for (int i = 0; i < _model.items.count; i++) {
iTermOpenQuicklyItem *item = _model.items[i];
NSColor *color;
if (@available(macOS 10.14, *)) {
if (i == _table.selectedRow) {
[[_table viewAtColumn:0 row:i makeIfNecessary:NO] setBackgroundStyle:NSBackgroundStyleEmphasized];
} else {
[[_table viewAtColumn:0 row:i makeIfNecessary:NO] setBackgroundStyle:NSBackgroundStyleNormal];
}
} else {
if (i == row) {
color = [NSColor whiteColor];
} else {
color = [self blackColor];
}
item.view.textField.textColor = color;
item.view.detailTextField.textColor = color;
}
}
}
- (void)tableViewSelectionIsChanging:(NSNotification *)notification {
[self updateTextColorForAllRows];
}
- (void)tableViewSelectionDidChange:(NSNotification *)notification {
[self updateTextColorForAllRows];
}
- (void)doubleClick:(id)sender {
[self openSelectedRow];
}
#pragma mark - NSWindowDelegate
- (void)windowDidResignKey:(NSNotification *)notification {
[self.window close];
}
#pragma mark - NSControlDelegate
// User changed query.
- (void)controlTextDidChange:(NSNotification *)notification {
[self update];
}
// User pressed enter (or something else we don't care about).
- (void)controlTextDidEndEditing:(NSNotification *)notification {
int move = [[[notification userInfo] objectForKey:@"NSTextMovement"] intValue];
switch (move) {
case NSReturnTextMovement: // Enter key
[self openSelectedRow];
break;
default:
break;
}
}
// This makes ^N and ^P work.
- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector {
BOOL result = NO;
if (commandSelector == @selector(moveUp:) || commandSelector == @selector(moveDown:)) {
NSInteger row = [_table selectedRow];
if (row < 0) {
row = 0;
} else if (commandSelector == @selector(moveUp:) && row > 0) {
row--;
} else if (commandSelector == @selector(moveDown:) && row + 1 < _table.numberOfRows) {
row++;
}
[_table selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
result = YES;
}
return result;
}
#pragma mark - iTermOpenQuicklyTextFieldDelegate
// Handle arrow keys while text field is key.
- (void)keyDown:(NSEvent *)theEvent {
static BOOL running;
if (!running) {
running = YES;
[_table keyDown:theEvent];
running = NO;
}
}
#pragma mark - iTermOpenQuicklyModelDelegate
- (id)openQuicklyModelDisplayStringForFeatureNamed:(NSString *)name
value:(NSString *)value
highlightedIndexes:(NSIndexSet *)highlight {
NSString *prefix;
if (name) {
prefix = [NSString stringWithFormat:@"%@: ", name];
} else {
prefix = @"";
}
NSMutableAttributedString *theString =
[[[NSMutableAttributedString alloc] initWithString:prefix
attributes:[self attributes]] autorelease];
[theString appendAttributedString:[self attributedStringFromString:value
byHighlightingIndices:highlight]];
return theString;
}
- (NSAttributedString *)openQuicklyModelAttributedStringForDetail:(NSString *)detail {
return [self attributedStringFromString:detail
byHighlightingIndices:nil];
}
#pragma mark - String Formatting
// Highlight and underline characters in |source| at indices in |indexSet|.
// This isn't really appropriate for the model to do but it's much simpler and
// more efficient this way.
- (NSAttributedString *)attributedStringFromString:(NSString *)source
byHighlightingIndices:(NSIndexSet *)indexSet {
NSMutableAttributedString *attributedString =
[[[NSMutableAttributedString alloc] initWithString:source attributes:[self attributes]] autorelease];
NSDictionary *highlight = @{ NSBackgroundColorAttributeName: [[NSColor yellowColor] colorWithAlphaComponent:0.4],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
NSUnderlineColorAttributeName: [NSColor yellowColor],
NSParagraphStyleAttributeName: [[self attributes] objectForKey:NSParagraphStyleAttributeName] };
[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
[attributedString setAttributes:highlight range:NSMakeRange(idx, 1)];
}];
return attributedString;
}
- (NSDictionary *)attributes {
NSMutableParagraphStyle *style = [[[NSMutableParagraphStyle alloc] init] autorelease];
style.lineBreakMode = NSLineBreakByTruncatingTail;
return @{ NSParagraphStyleAttributeName: style };
}
@end