forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiTermOpenQuicklyModel.m
860 lines (777 loc) · 37.8 KB
/
iTermOpenQuicklyModel.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
#import "iTermOpenQuicklyModel.h"
#import "iTermActionsModel.h"
#import "iTermApplication.h"
#import "iTermApplicationDelegate.h"
#import "iTermColorPresets.h"
#import "iTermController.h"
#import "iTermLogoGenerator.h"
#import "iTermMinimumSubsequenceMatcher.h"
#import "iTermOpenQuicklyCommands.h"
#import "iTermOpenQuicklyItem.h"
#import "iTermScriptsMenuController.h"
#import "iTermSnippetsModel.h"
#import "iTermVariableScope.h"
#import "iTermVariableScope+Session.h"
#import "iTermVariableScope+Tab.h"
#import "NSArray+iTerm.h"
#import "NSDictionary+iTerm.h"
#import "NSObject+iTerm.h"
#import "PseudoTerminal.h"
#import "PTYSession+Scripting.h"
#import "VT100RemoteHost.h"
#import "WindowArrangements.h"
// It's nice for each of these to be unique so in degenerate cases (e.g., empty query) the detail
// uses the same feature for all items.
static const double kSessionBadgeMultiplier = 3;
static const double kSessionNameMultiplier = 2;
static const double kHostnameMultiplier = 1.2;
static const double kProfileNameMultiplier = 1.01;
static const double kUserDefinedVariableMultiplier = 1;
static const double kDirectoryMultiplier = 0.9;
static const double kCommandMultiplier = 0.8;
static const double kUsernameMultiplier = 0.5;
// Action items (as defined in Prefs > Shortcuts > Snippets)
static const double kActionMultiplier = 0.4;
// Snippet items (as defined in Prefs > Shortcuts > Snippets)
static const double kSnippetMultiplier = 0.3;
// Multipliers for arrangement items. Arrangements rank just above profiles
static const double kProfileNameMultiplierForArrangementItem = 0.11;
// Multipliers for profile items
static const double kProfileNameMultiplierForProfileItem = 0.1;
// Multiplier for color preset name. Rank between scripts and profiles.
static const double kProfileNameMultiplierForColorPresetItem = 0.095;
// Multipliers for script items. Ranks below profiles.
static const double kProfileNameMultiplierForScriptItem = 0.09;
@implementation iTermOpenQuicklyModel
#pragma mark - Commands
- (NSArray<Class> *)commands {
static NSArray<Class> *commands;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
commands = @[ [iTermOpenQuicklyWindowArrangementCommand class],
[iTermOpenQuicklySearchSessionsCommand class],
[iTermOpenQuicklySwitchProfileCommand class],
[iTermOpenQuicklyCreateTabCommand class],
[iTermOpenQuicklyColorPresetCommand class],
[iTermOpenQuicklyScriptCommand class],
[iTermOpenQuicklyActionCommand class]];
});
return commands;
}
- (Class)commandTypeWithAbbreviation:(NSString *)abbreviation {
for (Class commandClass in self.commands) {
if ([[commandClass command] isEqualToString:abbreviation]) {
return commandClass;
}
}
return nil;
}
- (id<iTermOpenQuicklyCommand>)commandForQuery:(NSString *)queryString {
if ([queryString hasPrefix:@"/"] && queryString.length > 1) {
NSString *command = [queryString substringWithRange:NSMakeRange(1, 1)];
NSString *text = [[queryString substringFromIndex:2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Class commandClass = [self commandTypeWithAbbreviation:command];
if (commandClass) {
id<iTermOpenQuicklyCommand> theCommand= [[commandClass alloc] init];
theCommand.text = text;
return theCommand;
}
}
id<iTermOpenQuicklyCommand> theCommand = [[iTermOpenQuicklyNoCommand alloc] init];
theCommand.text = queryString;
return theCommand;
}
#pragma mark - Utilities
// Returns an array of all sessions.
- (NSArray *)sessions {
NSArray *terminals = [[iTermController sharedInstance] terminals];
// sessions and scores are parallel.
NSMutableArray *sessions = [NSMutableArray array];
for (PseudoTerminal *term in terminals) {
[sessions addObjectsFromArray:term.allSessions];
}
return sessions;
}
#pragma mark - Add Items
- (void)addTipsToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items {
for (Class commandClass in self.commands) {
iTermOpenQuicklyHelpItem *item = [[iTermOpenQuicklyHelpItem alloc] init];
item.score = 0;
item.title = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:[commandClass tipTitle]
highlightedIndexes:nil];
item.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:[commandClass tipDetail]
highlightedIndexes:nil];
item.identifier = [NSString stringWithFormat:@"/%@ ", [commandClass command]];
[items addObject:item];
}
}
- (NSString *)documentForSession:(PTYSession *)session {
NSString *sessionName = session.name;
NSString *tabTitle = session.variablesScope.tab.tabTitleOverride;
NSString *tmuxWindowName = session.variablesScope.tab.tmuxWindowName;
if (tabTitle.length == 0) {
tabTitle = tmuxWindowName;
}
if (tabTitle.length == 0) {
return sessionName;
}
if ([tabTitle containsString:sessionName]) {
return tabTitle;
} else {
return [NSString stringWithFormat:@"%@ — %@", tabTitle, sessionName];
}
}
- (NSString *(^)(PTYSession *))detailFunctionForSessions:(NSArray<PTYSession *> *)sessions {
NSString *(^pwd)(PTYSession *) = ^NSString *(PTYSession *session) {
return session.variablesScope.path;
};
NSString *(^command)(PTYSession *) = ^NSString *(PTYSession *session) {
return session.commands.lastObject;
};
NSString *(^hostname)(PTYSession *) = ^NSString *(PTYSession *session) {
return session.currentHost.usernameAndHostname;
};
NSString *(^badge)(PTYSession *) = ^NSString *(PTYSession *session) {
return session.badgeLabel;
};
NSArray<NSString *(^)(PTYSession *)> *functions = @[ pwd, command, hostname, badge ];
NSMutableArray<NSMutableArray *> *functionValues = [NSMutableArray array];
[functions enumerateObjectsUsingBlock:^(NSString *(^ _Nonnull obj)(PTYSession *), NSUInteger idx, BOOL * _Nonnull stop) {
[functionValues addObject:[NSMutableArray array]];
}];
[sessions enumerateObjectsUsingBlock:^(PTYSession * _Nonnull session, NSUInteger sessionIndex, BOOL * _Nonnull stop) {
[functions enumerateObjectsUsingBlock:^(NSString *(^ _Nonnull f)(PTYSession *), NSUInteger functionIndex, BOOL * _Nonnull stop) {
NSString *value = f(session);
if (value) {
[functionValues[functionIndex] addObject:value];
}
}];
}];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
[functionValues enumerateObjectsUsingBlock:^(NSMutableArray * _Nonnull values, NSUInteger idx, BOOL * _Nonnull stop) {
if (values.count == sessions.count) {
[indexes addIndex:idx];
}
}];
NSMutableArray<NSString *(^)(PTYSession *)> *filteredFunctions = [NSMutableArray array];
NSMutableArray<NSMutableArray *> *filteredFunctionValues = [NSMutableArray array];
[indexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
[filteredFunctions addObject:functions[idx]];
[filteredFunctionValues addObject:functionValues[idx]];
}];
double (^variance)(NSArray<NSString *> *) = ^double(NSArray<NSString *> *strings) {
NSSet<NSString *> *set = [NSSet setWithArray:strings];
return set.count;
};
const NSUInteger best = [filteredFunctionValues indexOfMaxWithBlock:
^NSComparisonResult(NSMutableArray<NSString *> *obj1,
NSMutableArray<NSString *> *obj2) {
return [@(variance(obj1)) compare:@(variance(obj2))];
}];
if (best == NSNotFound) {
return nil;
}
return filteredFunctions[best];
}
- (void)addSessionLocationToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
NSString *(^detailFunction)(PTYSession *) = [self detailFunctionForSessions:self.sessions];
for (PTYSession *session in self.sessions) {
NSMutableArray *features = [NSMutableArray array];
iTermOpenQuicklySessionItem *item = [[iTermOpenQuicklySessionItem alloc] init];
item.logoGenerator.textColor = session.foregroundColor;
item.logoGenerator.backgroundColor = session.backgroundColor;
item.logoGenerator.tabColor = session.tabColor;
item.logoGenerator.cursorColor = session.cursorColor;
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
item.score = [self scoreForSession:session
matcher:matcher
features:features
attributedName:attributedName];
if (item.score > 0) {
item.detail = [self detailForSession:session features:features];
if (attributedName.length) {
item.title = attributedName;
} else {
item.title = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:[self documentForSession:session]
highlightedIndexes:nil];
}
item.identifier = session.guid;
if (detailFunction) {
item.detail = [self.delegate openQuicklyModelAttributedStringForDetail:detailFunction(session)];
}
[items addObject:item];
}
}
}
- (void)addCreateNewTabToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher
haveCurrentWindow:(BOOL)haveCurrentWindow {
for (Profile *profile in [[ProfileModel sharedInstance] bookmarks]) {
iTermOpenQuicklyProfileItem *newSessionWithProfileItem = [[iTermOpenQuicklyProfileItem alloc] init];
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
newSessionWithProfileItem.score = [self scoreForProfile:profile matcher:matcher attributedName:attributedName];
if (newSessionWithProfileItem.score > 0) {
NSString *theValue;
if (!haveCurrentWindow || [profile[KEY_PREVENT_TAB] boolValue]) {
theValue = @"Create a new window with this profile";
} else {
theValue = @"Create a new tab with this profile";
}
newSessionWithProfileItem.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:theValue
highlightedIndexes:nil];
newSessionWithProfileItem.title = attributedName;
newSessionWithProfileItem.identifier = profile[KEY_GUID];
[items addObject:newSessionWithProfileItem];
}
}
}
- (void)addChangeColorPresetToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
iTermColorPresetDictionary *allPresets = [iTermColorPresets allColorPresets];
NSColor *defaultColor = [NSColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1];
for (NSString *name in allPresets) {
iTermColorPreset *preset = allPresets[name];
iTermOpenQuicklyColorPresetItem *item = [[iTermOpenQuicklyColorPresetItem alloc] init];
item.presetName = name;
item.logoGenerator.textColor = [preset[KEY_FOREGROUND_COLOR] colorValue] ?: [NSColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:1];
item.logoGenerator.backgroundColor = [preset[KEY_BACKGROUND_COLOR] colorValue] ?: [NSColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1];
item.logoGenerator.tabColor = [preset[KEY_TAB_COLOR] colorValue] ?: defaultColor;
item.logoGenerator.cursorColor = [preset[KEY_CURSOR_COLOR] colorValue] ?: defaultColor;
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
item.score = [self scoreForColorPreset:name matcher:matcher attributedName:attributedName];
if (item.score > 0) {
NSString *value = [NSString stringWithFormat:@"Load color preset ”%@“", name];
item.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:value
highlightedIndexes:nil];
item.title = attributedName;
item.identifier = name;
[items addObject:item];
}
}
}
- (void)addChangeProfileToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
for (Profile *profile in [[ProfileModel sharedInstance] bookmarks]) {
iTermOpenQuicklyChangeProfileItem *changeProfileItem = [[iTermOpenQuicklyChangeProfileItem alloc] init];
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
changeProfileItem.score = [self scoreForProfile:profile matcher:matcher attributedName:attributedName];
if (changeProfileItem.score > 0) {
changeProfileItem.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:@"Change current session’s profile"
highlightedIndexes:nil];
changeProfileItem.title = attributedName;
changeProfileItem.identifier = profile[KEY_GUID];
[items addObject:changeProfileItem];
}
}
}
- (void)addActionsToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
[[[iTermActionsModel sharedInstance] actions] enumerateObjectsUsingBlock:^(iTermAction * _Nonnull action, NSUInteger idx, BOOL * _Nonnull stop) {
iTermOpenQuicklyActionItem *actionItem = [self actionItemForAction:action
matcher:matcher];
if (actionItem) {
[items addObject:actionItem];
}
}];
}
- (iTermOpenQuicklyActionItem *)actionItemForAction:(iTermAction *)action
matcher:(iTermMinimumSubsequenceMatcher *)matcher {
iTermOpenQuicklyActionItem *actionItem = [[iTermOpenQuicklyActionItem alloc] init];
actionItem.action = action;
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
actionItem.score = [self scoreForAction:action matcher:matcher attributedName:attributedName];
if (actionItem.score <= 0) {
return nil;
}
actionItem.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:action.displayString
highlightedIndexes:nil];
actionItem.title = attributedName;
actionItem.identifier = [@(action.identifier) stringValue];
return actionItem;
}
- (void)addSnippetsToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
[[[iTermSnippetsModel sharedInstance] snippets] enumerateObjectsUsingBlock:^(iTermSnippet * _Nonnull snippet, NSUInteger idx, BOOL * _Nonnull stop) {
iTermOpenQuicklySnippetItem *snippetItem = [self snippetItemForSnippet:snippet
matcher:matcher];
if (snippetItem) {
[items addObject:snippetItem];
}
}];
}
- (iTermOpenQuicklySnippetItem *)snippetItemForSnippet:(iTermSnippet *)snippet
matcher:(iTermMinimumSubsequenceMatcher *)matcher {
iTermOpenQuicklySnippetItem *snippetItem = [[iTermOpenQuicklySnippetItem alloc] init];
snippetItem.snippet = snippet;
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
snippetItem.score = [self scoreForSnippet:snippet matcher:matcher attributedName:attributedName];
if (snippetItem.score <= 0) {
return nil;
}
snippetItem.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:[NSString stringWithFormat:@"Send snippet “%@”", snippet.title]
highlightedIndexes:nil];
snippetItem.title = attributedName;
snippetItem.identifier = [@(snippet.identifier) stringValue];
return snippetItem;
}
- (iTermOpenQuicklyArrangementItem *)arrangementItemWithName:(NSString *)arrangementName
matcher:(iTermMinimumSubsequenceMatcher *)matcher
inTabs:(BOOL)inTabs {
iTermOpenQuicklyArrangementItem *item = [[iTermOpenQuicklyArrangementItem alloc] init];
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
item.score = [self scoreForArrangementWithName:arrangementName
matcher:matcher
attributedName:attributedName];
if (item.score > 0) {
item.inTabs = inTabs;
item.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:inTabs ? @"Restore window arrangement in tabs" : @"Restore window arrangement"
highlightedIndexes:nil];
item.title = attributedName;
item.identifier = arrangementName;
return item;
} else {
return nil;
}
}
- (iTermOpenQuicklyScriptItem *)scriptItemWithName:(NSString *)scriptName
matcher:(iTermMinimumSubsequenceMatcher *)matcher {
iTermOpenQuicklyScriptItem *item = [[iTermOpenQuicklyScriptItem alloc] init];
NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] init];
item.score = [self scoreForScriptWithName:scriptName
matcher:matcher
attributedName:attributedName];
if (item.score > 0) {
item.detail = [_delegate openQuicklyModelDisplayStringForFeatureNamed:nil
value:@"Run Script"
highlightedIndexes:nil];
item.title = attributedName;
item.identifier = scriptName;
return item;
} else {
return nil;
}
}
- (void)addOpenArrangementToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
for (NSString *arrangementName in [WindowArrangements allNames]) {
iTermOpenQuicklyArrangementItem *item;
item = [self arrangementItemWithName:arrangementName matcher:matcher inTabs:NO];
if (item) {
[items addObject:item];
}
item = [self arrangementItemWithName:arrangementName matcher:matcher inTabs:YES];
if (item) {
[items addObject:item];
}
}
}
- (void)addScriptToItems:(NSMutableArray<iTermOpenQuicklyItem *> *)items
withMatcher:(iTermMinimumSubsequenceMatcher *)matcher {
NSArray<NSString *> *allScripts = [[[[iTermApplication sharedApplication] delegate] scriptsMenuController] allScripts];
for (NSString *script in allScripts) {
iTermOpenQuicklyScriptItem *item;
item = [self scriptItemWithName:script matcher:matcher];
if (item) {
[items addObject:item];
}
}
}
#pragma mark - APIs
- (void)removeAllItems {
[_items removeAllObjects];
}
- (void)updateWithQuery:(NSString *)queryString {
id<iTermOpenQuicklyCommand> command = [self commandForQuery:[queryString lowercaseString]];
iTermMinimumSubsequenceMatcher *matcher =
[[iTermMinimumSubsequenceMatcher alloc] initWithQuery:command.text];
NSMutableArray *items = [NSMutableArray array];
if ([queryString isEqualToString:@"/"]) {
[self addTipsToItems:items];
}
if ([command supportsSessionLocation]) {
[self addSessionLocationToItems:items withMatcher:matcher];
}
BOOL haveCurrentWindow = [[iTermController sharedInstance] currentTerminal] != nil;
if ([command supportsCreateNewTab]) {
[self addCreateNewTabToItems:items withMatcher:matcher haveCurrentWindow:haveCurrentWindow];
}
if ([command supportsChangeProfile] && haveCurrentWindow) {
[self addChangeProfileToItems:items withMatcher:matcher];
}
if ([command supportsOpenArrangement]) {
[self addOpenArrangementToItems:items withMatcher:matcher];
}
if ([command supportsScript]) {
[self addScriptToItems:items withMatcher:matcher];
}
if ([command supportsColorPreset] && haveCurrentWindow) {
[self addChangeColorPresetToItems:items withMatcher:matcher];
}
if ([command supportsAction] && haveCurrentWindow) {
[self addActionsToItems:items withMatcher:matcher];
}
if ([command supportsSnippet] && haveCurrentWindow) {
[self addSnippetsToItems:items withMatcher:matcher];
}
// Sort from highest to lowest score.
[items sortUsingComparator:^NSComparisonResult(iTermOpenQuicklyItem *obj1,
iTermOpenQuicklyItem *obj2) {
return [@(obj2.score) compare:@(obj1.score)];
}];
// To avoid performance issues, only keep the 100 best.
static const int kMaxItems = 100;
if (items.count > kMaxItems) {
[items removeObjectsInRange:NSMakeRange(kMaxItems, items.count - kMaxItems)];
}
// Replace self.items with new items.
self.items = items;
}
- (id)objectAtIndex:(NSInteger)index {
iTermOpenQuicklyItem *item = _items[index];
if ([item isKindOfClass:[iTermOpenQuicklyProfileItem class]]) {
return [[ProfileModel sharedInstance] bookmarkWithGuid:item.identifier];
} else if ([item isKindOfClass:[iTermOpenQuicklyChangeProfileItem class]] ||
[item isKindOfClass:[iTermOpenQuicklyHelpItem class]]) {
return item;
} else if ([item isKindOfClass:[iTermOpenQuicklyArrangementItem class]]) {
return item;
} else if ([item isKindOfClass:[iTermOpenQuicklySessionItem class]]) {
NSString *guid = item.identifier;
for (PTYSession *session in [self sessions]) {
if ([session.guid isEqualTo:guid]) {
return session;
}
}
} else if ([item isKindOfClass:[iTermOpenQuicklyScriptItem class]]) {
return item;
} else if ([item isKindOfClass:[iTermOpenQuicklyColorPresetItem class]]) {
return item;
} else if ([item isKindOfClass:[iTermOpenQuicklyActionItem class]]) {
return item;
} else if ([item isKindOfClass:[iTermOpenQuicklySnippetItem class]]) {
return item;
}
return nil;
}
#pragma mark - Scoring
- (double)scoreForArrangementWithName:(NSString *)arrangementName
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ arrangementName ?: @"" ]
multiplier:kProfileNameMultiplierForArrangementItem
name:nil
features:nameFeature
limit:2 * kProfileNameMultiplierForArrangementItem];
if (score > 0 &&
[[WindowArrangements defaultArrangementName] isEqualToString:arrangementName]) {
// Make the default arrangement always be the highest-scored arrangement if it matches the query.
score += 0.2;
}
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
- (double)scoreForScriptWithName:(NSString *)arrangementName
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ arrangementName ?: @"" ]
multiplier:kProfileNameMultiplierForScriptItem
name:nil
features:nameFeature
limit:2 * kProfileNameMultiplierForScriptItem];
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
- (double)scoreForAction:(iTermAction *)action
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ action.title ?: @"" ]
multiplier:kActionMultiplier
name:nil
features:nameFeature
limit:2 * kActionMultiplier];
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
- (double)scoreForSnippet:(iTermSnippet *)snippet
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ snippet.title ?: @"",
[snippet trimmedValue:80] ?: @"" ]
multiplier:kSnippetMultiplier
name:nil
features:nameFeature
limit:2 * kSnippetMultiplier];
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
- (double)scoreForColorPreset:(NSString *)presetName
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ presetName ]
multiplier:kProfileNameMultiplierForColorPresetItem
name:nil
features:nameFeature
limit:2 * kProfileNameMultiplierForColorPresetItem];
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
- (double)scoreForProfile:(Profile *)profile
matcher:(iTermMinimumSubsequenceMatcher *)matcher
attributedName:(NSMutableAttributedString *)attributedName {
NSMutableArray *nameFeature = [NSMutableArray array];
double score = [self scoreUsingMatcher:matcher
documents:@[ profile[KEY_NAME] ]
multiplier:kProfileNameMultiplierForProfileItem
name:nil
features:nameFeature
limit:2 * kProfileNameMultiplierForProfileItem];
if (score > 0 &&
[[[ProfileModel sharedInstance] defaultBookmark][KEY_GUID] isEqualToString:profile[KEY_GUID]]) {
// Make the default profile always be the highest-scored profile if it matches the query.
score += 0.2;
}
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
return score;
}
// Returns the score for a session.
// session: The session to score against a query
// query: The search query (null terminate)
// length: The length of the query array
// features: An array that will be populated with tuples of (detail, score).
// The detail element is a suitable-for-display NSAttributedString*s
// describing features that matched the query, while the score element is the
// score assigned to that feature.
// attributedName: The session's name with matching characters highlighted
// (suitable for display) will be appended to this NSMutableAttributedString.
- (double)scoreForSession:(PTYSession *)session
matcher:(iTermMinimumSubsequenceMatcher *)matcher
features:(NSMutableArray *)features
attributedName:(NSMutableAttributedString *)attributedName {
double score = 0;
double maxScorePerFeature = 2 + matcher.query.length / 4;
if (session.name) {
NSMutableArray *nameFeature = [NSMutableArray array];
score += [self scoreUsingMatcher:matcher
documents:@[ [self documentForSession:session] ]
multiplier:kSessionNameMultiplier
name:nil
features:nameFeature
limit:maxScorePerFeature];
if (nameFeature.count) {
[attributedName appendAttributedString:nameFeature[0][0]];
}
}
if (session.badgeLabel) {
score += [self scoreUsingMatcher:matcher
documents:@[ session.badgeLabel ]
multiplier:kSessionBadgeMultiplier
name:@"Badge"
features:features
limit:maxScorePerFeature];
}
score += [self scoreUsingMatcher:matcher
documents:session.commands
multiplier:kCommandMultiplier
name:@"Command"
features:features
limit:maxScorePerFeature];
score += [self scoreUsingMatcher:matcher
documents:session.directories
multiplier:kDirectoryMultiplier
name:@"Directory"
features:features
limit:maxScorePerFeature];
score += [self scoreUsingMatcher:matcher
documents:[self hostnamesInHosts:session.hosts]
multiplier:kHostnameMultiplier
name:@"Host"
features:features
limit:maxScorePerFeature];
score += [self scoreUsingMatcher:matcher
documents:[self usernamesInHosts:session.hosts]
multiplier:kUsernameMultiplier
name:@"User"
features:features
limit:maxScorePerFeature];
score += [self scoreUsingMatcher:matcher
documents:@[ session.originalProfile[KEY_NAME] ?: @"" ]
multiplier:kProfileNameMultiplier
name:@"Profile"
features:features
limit:maxScorePerFeature];
NSDictionary<NSString *, NSString *> *userVariablesDict = [[session.variables discouragedValueForVariableName:@"user"] stringValuedDictionary];
for (NSString *name in userVariablesDict) {
score += [self scoreUsingMatcher:matcher
documents:@[ userVariablesDict[name] ]
multiplier:kUserDefinedVariableMultiplier
name:name
features:features
limit:maxScorePerFeature];
}
// TODO: add a bonus for:
// Doing lots of typing in a session
// Being newly created
// Recency of use
return score;
}
// Given an array of features which are a tuple of (detail, score), return the
// detail for the highest scoring one.
- (NSAttributedString *)detailForSession:(PTYSession *)session features:(NSArray *)features {
NSArray *sorted = [features sortedArrayUsingComparator:^NSComparisonResult(NSArray *tuple1, NSArray *tuple2) {
NSNumber *score1 = tuple1[1];
NSNumber *score2 = tuple2[1];
return [score1 compare:score2];
}];
return [sorted lastObject][0];
}
// Returns the total score for a query matching an array of documents. This
// should be called once per feature.
// query: The user-entered query
// documents: An array of NSString*s to search, ordered from least recent to
// most recent (less recent documents have their scores heavily discounted)
// multiplier: The sum of the documents' scores is multiplied by this value.
// name: The display name of the current feature.
// features: The highest-scoring document will have an NSAttributedString added
// to this array describing the match, suitable for display.
// limit: Upper bound for the returned score.
- (double)scoreUsingMatcher:(iTermMinimumSubsequenceMatcher *)matcher
documents:(NSArray *)documents
multiplier:(double)multiplier
name:(NSString *)name
features:(NSMutableArray *)features
limit:(double)limit {
if (multiplier == 0) {
// Feature is disabled. In the future, we might let users tweak multipliers.
return 0;
}
if (matcher.query.length == 0) {
// Trivially matches every document.
double score = 0.01;
for (NSString *document in documents) {
if (features) {
id displayString = [_delegate openQuicklyModelDisplayStringForFeatureNamed:name
value:document
highlightedIndexes:[NSIndexSet indexSet]];
[features addObject:@[ displayString, @(score) ]];
}
}
return score;
}
double score = 0;
double highestValue = 0;
NSString *bestFeature = nil;
NSIndexSet *bestIndexSet = nil;
int n = documents.count;
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSString *document in documents) {
[indexSet removeAllIndexes];
double value = [self qualityOfMatchWithMatcher:matcher
document:[document lowercaseString]
indexSet:indexSet];
// Discount older documents (which appear at the beginning of the list)
value /= n;
n--;
if (value > highestValue) {
highestValue = value;
bestFeature = document;
bestIndexSet = [indexSet copy];
}
score += value * multiplier;
if (score > limit) {
break;
}
}
if (bestFeature && features) {
id displayString = [_delegate openQuicklyModelDisplayStringForFeatureNamed:name
value:bestFeature
highlightedIndexes:bestIndexSet];
[features addObject:@[ displayString, @(score) ]];
}
return MIN(limit, score);
}
// Returns a value between 0 and 1 for how well a query matches a document.
// The passed-in indexSet will be populated with indices into documentString
// that were found to match query.
// The current implementation returns:
// 1.0 if query equals document.
// 0.9 if query is a prefix of document.
// 0.5 if query is a substring of document
// 0 < score < 0.5 if query is a subsequence of a document. Each gap of non-matching characters
// increases the penalty.
// 0.0 otherwise
- (double)qualityOfMatchWithMatcher:(iTermMinimumSubsequenceMatcher *)matcher
document:(NSString *)documentString
indexSet:(NSMutableIndexSet *)indexSet {
[indexSet addIndexes:[matcher indexSetForDocument:documentString]];
double score;
if (!indexSet.count) {
// No match
score = 0;
} else if (indexSet.firstIndex == 0 && indexSet.lastIndex == documentString.length - 1) {
// Exact equality
score = 1;
} else if (indexSet.firstIndex == 0) {
// Is a prefix
score = 0.9;
} else {
score = 0.5 / ([self numberOfGapsInIndexSet:indexSet] + 1);
}
return score;
}
- (NSInteger)numberOfGapsInIndexSet:(NSIndexSet *)indexSet {
__block NSInteger numRanges = 0;
[indexSet enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
++numRanges;
}];
return numRanges - 1;
}
#pragma mark - Feature Extraction
// Returns an array of hostnames from an array of VT100RemoteHost*s
- (NSArray *)hostnamesInHosts:(NSArray *)hosts {
NSMutableArray *names = [NSMutableArray array];
for (VT100RemoteHost *host in hosts) {
[names addObject:host.hostname];
}
return names;
}
// Returns an array of usernames from an array of VT100RemoteHost*s
- (NSArray *)usernamesInHosts:(NSArray *)hosts {
NSMutableArray *names = [NSMutableArray array];
for (VT100RemoteHost *host in hosts) {
[names addObject:host.username];
}
return names;
}
@end