/
Favorites.mm
406 lines (352 loc) · 14.9 KB
/
Favorites.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
#import "Favorites.h"
#import <OakFilterList/OakAbbreviations.h>
#import <OakAppKit/OakAppKit.h>
#import <OakAppKit/OakFileIconImage.h>
#import <OakAppKit/OakUIConstructionFunctions.h>
#import <OakAppKit/OakScopeBarView.h>
#import <OakAppKit/OakSound.h>
#import <OakFoundation/NSString Additions.h>
#import <OakFoundation/NSFileManager Additions.h>
#import <OakSystem/application.h>
#import <text/ranker.h>
#import <io/entries.h>
#import <text/case.h>
#import <text/ctype.h>
#import <io/path.h>
#import <ns/ns.h>
#import <kvdb/kvdb.h>
static NSString* const kUserDefaultsOpenProjectSourceIndex = @"openProjectSourceIndex";
static NSUInteger const kOakSourceIndexRecentProjects = 0;
static NSUInteger const kOakSourceIndexFavorites = 1;
@interface FavoriteChooser ()
{
NSMutableArray* _originalItems;
}
@property (nonatomic) NSInteger sourceIndex;
@property (nonatomic) NSArray* sourceListLabels;
@end
@implementation FavoriteChooser
+ (instancetype)sharedInstance
{
static FavoriteChooser* sharedInstance = [self new];
return sharedInstance;
}
+ (void)initialize
{
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
kUserDefaultsOpenProjectSourceIndex : @0,
}];
}
- (KVDB*)sharedProjectStateDB
{
NSString* appSupport = [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"TextMate"];
return [KVDB sharedDBUsingFile:@"RecentProjects.db" inDirectory:appSupport];
}
- (id)init
{
if((self = [super init]))
{
_sourceIndex = NSNotFound;
_sourceListLabels = @[ @"Recent Projects", @"Favorites" ];
self.window.title = @"Open Recent Project";
self.tableView.allowsTypeSelect = NO;
self.tableView.allowsMultipleSelection = YES;
self.tableView.refusesFirstResponder = NO;
self.tableView.rowHeight = 38;
self.window.nextResponder = nil;
NSResponder* nextResponder = self.tableView.nextResponder;
self.tableView.nextResponder = self;
self.nextResponder = nextResponder;
OakScopeBarView* scopeBar = [OakScopeBarView new];
scopeBar.labels = self.sourceListLabels;
OakBackgroundFillView* aboveScopeBarDark = OakCreateHorizontalLine([NSColor grayColor], [NSColor lightGrayColor]);
OakBackgroundFillView* aboveScopeBarLight = OakCreateHorizontalLine([NSColor colorWithCalibratedWhite:0.797 alpha:1], [NSColor colorWithCalibratedWhite:0.912 alpha:1]);
OakBackgroundFillView* topDivider = OakCreateHorizontalLine([NSColor darkGrayColor], [NSColor colorWithCalibratedWhite:0.551 alpha:1]);
OakBackgroundFillView* bottomDivider = OakCreateHorizontalLine([NSColor grayColor], [NSColor lightGrayColor]);
NSDictionary* views = @{
@"searchField" : self.searchField,
@"aboveScopeBarDark" : aboveScopeBarDark,
@"aboveScopeBarLight" : aboveScopeBarLight,
@"scopeBar" : scopeBar,
@"topDivider" : topDivider,
@"scrollView" : self.scrollView,
@"bottomDivider" : bottomDivider,
@"statusTextField" : self.statusTextField,
@"itemCountTextField" : self.itemCountTextField,
};
NSView* contentView = self.window.contentView;
OakAddAutoLayoutViewsToSuperview([views allValues], contentView);
OakSetupKeyViewLoop(@[ self.tableView, self.searchField, scopeBar ]);
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(8)-[searchField(>=50)]-(8)-|" options:0 metrics:nil views:views]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[aboveScopeBarDark(==aboveScopeBarLight)]|" options:0 metrics:nil views:views]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(8)-[scopeBar]-(>=8)-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:views]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView(==topDivider,==bottomDivider)]|" options:0 metrics:nil views:views]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[statusTextField]-[itemCountTextField]-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views]];
[contentView addConstraint:[NSLayoutConstraint constraintWithItem:aboveScopeBarLight attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[contentView addConstraint:[NSLayoutConstraint constraintWithItem:topDivider attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[contentView addConstraint:[NSLayoutConstraint constraintWithItem:bottomDivider attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(2)-[searchField]-(8)-[aboveScopeBarDark][aboveScopeBarLight]-(3)-[scopeBar]-(4)-[topDivider][scrollView(>=50)][bottomDivider]-(4)-[statusTextField]-(5)-|" options:0 metrics:nil views:views]];
self.sourceIndex = [[NSUserDefaults standardUserDefaults] integerForKey:kUserDefaultsOpenProjectSourceIndex];
[scopeBar bind:NSValueBinding toObject:self withKeyPath:@"sourceIndex" options:nil];
}
return self;
}
- (IBAction)selectNextTab:(id)sender { self.sourceIndex = (self.sourceIndex + 1) % self.sourceListLabels.count; }
- (IBAction)selectPreviousTab:(id)sender { self.sourceIndex = (self.sourceIndex + self.sourceListLabels.count - 1) % self.sourceListLabels.count; }
- (NSView*)tableView:(NSTableView*)aTableView viewForTableColumn:(NSTableColumn*)aTableColumn row:(NSInteger)row
{
NSTableCellView* res = [aTableView makeViewWithIdentifier:aTableColumn.identifier owner:self];
if(!res)
{
NSButton* removeButton = [NSButton new];
[[removeButton cell] setControlSize:NSControlSizeSmall];
removeButton.refusesFirstResponder = YES;
removeButton.bezelStyle = NSRoundRectBezelStyle;
removeButton.buttonType = NSMomentaryPushInButton;
removeButton.image = [NSImage imageNamed:NSImageNameRemoveTemplate];
removeButton.target = self;
removeButton.action = @selector(takeItemToRemoveFrom:);
res = [[OakFileTableCellView alloc] initWithCloseButton:removeButton];
res.identifier = aTableColumn.identifier;
[removeButton bind:NSHiddenBinding toObject:res withKeyPath:@"objectValue.isRemoveDisabled" options:nil];
}
res.objectValue = self.items[row];
return res;
}
- (void)setSourceIndex:(NSInteger)newIndex
{
if(_sourceIndex == newIndex)
return;
_sourceIndex = newIndex;
[self loadItems:self];
[self updateItems:self];
[[NSUserDefaults standardUserDefaults] setInteger:newIndex forKey:kUserDefaultsOpenProjectSourceIndex];
}
- (void)loadItems:(id)sender
{
NSMutableArray* items = [NSMutableArray new];
if(_sourceIndex == kOakSourceIndexRecentProjects)
{
std::vector<std::string> paths;
for(id pair in [[[self sharedProjectStateDB] allObjects] sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"value.lastRecentlyUsed" ascending:NO], [NSSortDescriptor sortDescriptorWithKey:@"key.lastPathComponent" ascending:YES selector:@selector(localizedCompare:)] ]])
{
if(access([pair[@"key"] fileSystemRepresentation], F_OK) == 0)
[items addObject:@{ @"path" : pair[@"key"] }];
}
}
else if(_sourceIndex == kOakSourceIndexFavorites)
{
std::string const favoritesPath = oak::application_t::support("Favorites");
for(auto const& entry : path::entries(favoritesPath))
{
if(entry->d_type == DT_LNK)
{
std::string const path = path::resolve(path::join(favoritesPath, entry->d_name));
if(strncmp("[DIR] ", entry->d_name, 6) == 0)
{
bool includeSymlinkName = path::name(path) != std::string(entry->d_name + 6);
for(auto const& subentry : path::entries(path))
{
if(subentry->d_type == DT_DIR)
{
NSMutableDictionary* item = [NSMutableDictionary dictionaryWithDictionary:@{
@"path" : [NSString stringWithCxxString:path::join(path, subentry->d_name)],
@"isRemoveDisabled" : @YES
}];
if(includeSymlinkName)
item[@"name"] = [NSString stringWithFormat:@"%s — %s", subentry->d_name, entry->d_name + 6];
[items addObject:item];
}
}
}
else
{
NSMutableDictionary* item = [NSMutableDictionary dictionaryWithDictionary:@{
@"path" : [NSString stringWithCxxString:path],
@"link" : [NSString stringWithCxxString:path::join(favoritesPath, entry->d_name)]
}];
if(path::name(path) != entry->d_name)
{
item[@"name"] = [NSString stringWithCxxString:entry->d_name];
item[@"folder"] = [item[@"path"] stringByAbbreviatingWithTildeInPath];
}
[items addObject:item];
}
}
}
}
_originalItems = [NSMutableArray new];
for(NSDictionary* item in items)
{
NSString* path = item[@"path"];
NSMutableDictionary* tmp = [item mutableCopy];
[tmp addEntriesFromDictionary:@{
@"icon" : [OakFileIconImage fileIconImageWithPath:path size:NSMakeSize(32, 32)],
@"name" : item[@"name"] ?: [NSString stringWithCxxString:path::display_name(to_s(path))],
@"folder" : item[@"folder"] ?: [[path stringByDeletingLastPathComponent] stringByAbbreviatingWithTildeInPath],
@"info" : [path stringByAbbreviatingWithTildeInPath]
}];
[_originalItems addObject:tmp];
}
if(_sourceIndex == kOakSourceIndexFavorites)
_originalItems = [[_originalItems sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCompare:)] ]] mutableCopy];
}
- (void)showWindow:(id)sender
{
if(![self.window isVisible])
{
self.filterString = @"";
[self loadItems:self];
[self updateItems:self];
if([self.tableView numberOfRows])
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
}
[super showWindow:sender];
}
- (void)updateItems:(id)sender
{
NSArray* bindings = [[OakAbbreviations abbreviationsForName:@"OakFavoriteChooserBindings"] stringsForAbbreviation:self.filterString];
std::string const filter = to_s([self.filterString decomposedStringWithCanonicalMapping]);
std::multimap<double, NSDictionary*> ranked;
for(NSDictionary* item in _originalItems)
{
NSString* name = item[@"name"];
double rank = ranked.size();
std::vector<std::pair<size_t, size_t>> ranges;
if(filter != NULL_STR && filter != "")
{
rank = oak::rank(filter, to_s(name), &ranges);
if(rank <= 0)
continue;
NSUInteger bindingIndex = [bindings indexOfObject:item[@"path"]];
if(bindingIndex != NSNotFound)
rank = -1.0 * (bindings.count - bindingIndex);
else rank = -rank;
}
NSMutableDictionary* entry = [item mutableCopy];
entry[@"name"] = CreateAttributedStringWithMarkedUpRanges(to_s(name), ranges, NSLineBreakByTruncatingTail);
entry[@"folder"] = CreateAttributedStringWithMarkedUpRanges(to_s(item[@"folder"]), { }, NSLineBreakByTruncatingHead);
ranked.emplace(rank, entry);
}
NSMutableArray* res = [NSMutableArray new];
for(auto const& pair : ranked)
[res addObject:pair.second];
self.items = res;
}
- (void)updateStatusText:(id)sender
{
if(self.tableView.selectedRow != -1)
{
NSDictionary* item = self.items[self.tableView.selectedRow];
self.statusTextField.stringValue = [item objectForKey:@"info"];
}
else
{
self.statusTextField.stringValue = @"";
}
}
- (void)accept:(id)sender
{
if(self.filterString)
{
for(NSDictionary* item in self.selectedItems)
[[OakAbbreviations abbreviationsForName:@"OakFavoriteChooserBindings"] learnAbbreviation:self.filterString forString:[item objectForKey:@"path"]];
}
for(NSDictionary* item in self.selectedItems)
{
if(NSMutableDictionary* tmp = [[[self sharedProjectStateDB] valueForKey:item[@"path"]] mutableCopy])
{
tmp[@"lastRecentlyUsed"] = [NSDate date];
[[self sharedProjectStateDB] setValue:tmp forKey:item[@"path"]];
}
}
[super accept:sender];
}
- (NSUInteger)removeItemsAtIndexes:(NSIndexSet*)anIndexSet
{
NSMutableArray* items = [self.items mutableCopy];
anIndexSet = [anIndexSet indexesPassingTest:^BOOL(NSUInteger idx, BOOL* stop){
return ![items[idx][@"isRemoveDisabled"] boolValue];
}];
for(NSDictionary* item in [items objectsAtIndexes:anIndexSet])
{
if(NSString* link = item[@"link"])
[[NSFileManager defaultManager] trashItemAtURL:[NSURL fileURLWithPath:link] resultingItemURL:nil error:nil];
else if(NSString* path = item[@"path"])
[[self sharedProjectStateDB] removeObjectForKey:path];
}
[self loadItems:self]; // update originalItems
return [super removeItemsAtIndexes:anIndexSet];
}
- (void)takeItemToRemoveFrom:(NSButton*)sender
{
NSInteger row = [self.tableView rowForView:sender];
if(row != -1)
[self removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:row]];
}
- (void)takeSourceIndexFrom:(id)sender
{
if([sender respondsToSelector:@selector(tag)])
self.sourceIndex = [sender tag];
}
- (void)updateSelectTabMenu:(NSMenu*)aMenu
{
if(self.window.isKeyWindow)
{
[[aMenu addItemWithTitle:@"Recent Projects" action:@selector(takeSourceIndexFrom:) keyEquivalent:@"1"] setTag:kOakSourceIndexRecentProjects];
[[aMenu addItemWithTitle:@"Favorites" action:@selector(takeSourceIndexFrom:) keyEquivalent:@"2"] setTag:kOakSourceIndexFavorites];
}
else
{
[aMenu addItemWithTitle:@"No Sources" action:@selector(nop:) keyEquivalent:@""];
}
}
- (BOOL)validateMenuItem:(NSMenuItem*)item
{
BOOL activate = YES;
if([item action] == @selector(takeSourceIndexFrom:))
[item setState:[item tag] == self.sourceIndex ? NSOnState : NSOffState];
return activate;
}
- (void)deleteForward:(id)sender
{
NSUInteger itemsRemoved = [self removeItemsAtIndexes:[self.tableView selectedRowIndexes]];
if(itemsRemoved == 0)
NSBeep();
}
- (void)deleteBackward:(id)sender
{
NSUInteger index = [[self.tableView selectedRowIndexes] firstIndex];
NSUInteger itemsRemoved = [self removeItemsAtIndexes:[self.tableView selectedRowIndexes]];
if(itemsRemoved == 0)
NSBeep();
else if(index && index != NSNotFound && self.tableView.numberOfRows)
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:index-1] byExtendingSelection:NO];
}
- (void)insertText:(id)aString
{
self.filterString = aString;
[self.window makeFirstResponder:self.searchField];
NSText* fieldEditor = (NSText*)[self.window firstResponder];
if([fieldEditor isKindOfClass:[NSText class]])
[fieldEditor setSelectedRange:NSMakeRange([[fieldEditor string] length], 0)];
}
- (void)doCommandBySelector:(SEL)aSelector
{
if([self respondsToSelector:aSelector])
{
[super doCommandBySelector:aSelector];
}
else
{
NSUInteger res = OakPerformTableViewActionFromSelector(self.tableView, aSelector);
if(res == OakMoveAcceptReturn)
[self accept:self];
else if(res == OakMoveCancelReturn)
[self cancel:self];
}
}
- (void)keyDown:(NSEvent*)anEvent { [self interpretKeyEvents:@[ anEvent ]]; }
- (void)insertTab:(id)sender { [self.window selectNextKeyView:self]; }
- (void)insertBacktab:(id)sender { [self.window selectPreviousKeyView:self]; }
@end