-
-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathBundledFilesController.m
More file actions
474 lines (392 loc) · 15.9 KB
/
Copy pathBundledFilesController.m
File metadata and controls
474 lines (392 loc) · 15.9 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
/*
Copyright (c) 2003-2025, Sveinbjorn Thordarson <sveinbjorn@sveinbjorn.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#import "BundledFilesController.h"
#import "VDKQueue.h"
#import "EditorController.h"
#import "NSWorkspace+Additions.h"
#import "Alerts.h"
#import "Common.h"
@interface BundledFilesController()
{
IBOutlet NSButton *removeFileButton;
IBOutlet NSButton *editFileButton;
IBOutlet NSButton *revealFileButton;
IBOutlet NSButton *clearFileListButton;
IBOutlet NSTableView *tableView;
IBOutlet NSTextField *bundleSizeTextField;
NSMutableArray <NSDictionary *> *files;
VDKQueue *fileWatcherQueue;
NSWindow *window;
}
@end
@implementation BundledFilesController
- (instancetype)init {
self = [super init];
if (self) {
files = [[NSMutableArray alloc] init];
fileWatcherQueue = [[VDKQueue alloc] init];
}
return self;
}
- (void)awakeFromNib {
window = [tableView window];
[tableView registerForDraggedTypes:@[NSFilenamesPboardType]];
[tableView setTarget:self];
[tableView setDoubleAction:@selector(itemDoubleClicked:)];
[tableView setDraggingSourceOperationMask:NSDragOperationCopy | NSDragOperationMove forLocal:NO];
// We list ourself as an observer of file system changes for items in file watcher queue
[[WORKSPACE notificationCenter] addObserver:self selector:@selector(trackedFileDidChange) name:VDKQueueRenameNotification object:nil];
[[WORKSPACE notificationCenter] addObserver:self selector:@selector(trackedFileDidChange) name:VDKQueueDeleteNotification object:nil];
}
#pragma mark -
- (void)trackedFileDidChange {
[tableView reloadData];
}
- (void)addFiles:(NSArray *)filePaths {
if (filePaths == nil) {
return;
}
BOOL addedFile = NO;
for (NSString *filePath in filePaths) {
if ([self hasFilePath:filePath]) {
continue;
}
if ([self hasFileName:[filePath lastPathComponent]]) {
[Alerts alert:@"File name duplicate"
subTextFormat:@"You have already added a file or folder named \"%@\". Please rename the file to add it.", [filePath lastPathComponent]];
continue;
}
NSImage *icon = [WORKSPACE iconForFile:filePath];
[icon setSize:NSMakeSize(16, 16)];
NSDictionary *fileInfoDict = @{ @"Icon":icon, @"Path":filePath };
[files addObject:fileInfoDict];
addedFile = YES;
}
if (addedFile) {
[self updateUI];
}
}
- (void)updateUI {
[tableView reloadData];
[self updateButtonStatus];
[self updateQueueWatch];
[self updateFileSizeField];
}
- (void)updateQueueWatch {
[fileWatcherQueue removeAllPaths];
for (NSDictionary *fileItem in files) {
[fileWatcherQueue addPath:fileItem[@"Path"]];
}
}
- (void)updateButtonStatus {
BOOL hasSelection = [[tableView selectedRowIndexes] count];
[removeFileButton setEnabled:hasSelection];
[revealFileButton setEnabled:hasSelection];
[editFileButton setEnabled:hasSelection && [[tableView selectedRowIndexes] count] == 1];
[clearFileListButton setEnabled:([files count] != 0)];
}
- (void)updateFileSizeField {
// If there are no items
if ([files count] == 0) {
_totalSizeOfFiles = 0;
[bundleSizeTextField setStringValue:@""];
[[NSNotificationCenter defaultCenter] postNotificationName:PLATYPUS_APP_SIZE_CHANGED_NOTIFICATION object:nil];
return;
}
// Otherwise, loop through all files, calculate size in a separate queue
[bundleSizeTextField setStringValue:@"Calculating size..."];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^(void){
UInt64 size = 0;
for (NSDictionary *fileInfoDict in files) {
size += [WORKSPACE fileOrFolderSize:fileInfoDict[@"Path"]];
}
NSString *totalSizeString = [WORKSPACE fileSizeAsHumanReadableString:size];
NSString *pluralS = ([files count] > 1) ? @"s" : @"";
NSString *itemsSizeString = [NSString stringWithFormat:@"%lu item%@, %@", (unsigned long)[files count], pluralS, totalSizeString];
NSString *tooltipString = [NSString stringWithFormat:@"%lu item%@ (%llu bytes)", (unsigned long)[files count], pluralS, size];
_totalSizeOfFiles = size;
//run UI updates on main thread
dispatch_async(dispatch_get_main_queue(), ^(void){
[[NSNotificationCenter defaultCenter] postNotificationName:PLATYPUS_APP_SIZE_CHANGED_NOTIFICATION object:nil];
[bundleSizeTextField setStringValue:itemsSizeString];
[bundleSizeTextField setToolTip:tooltipString];
});
});
}
- (BOOL)hasFilePath:(NSString *)filePath {
for (NSDictionary *fileInfoDict in files) {
if ([fileInfoDict[@"Path"] isEqualToString:filePath]) {
return YES;
}
}
return NO;
}
- (BOOL)hasFileName:(NSString *)filename {
for (NSDictionary *fileInfoDict in files) {
NSString *fn = [fileInfoDict[@"Path"] lastPathComponent];
if ([fn isEqualToString:filename]) {
return YES;
}
}
return NO;
}
- (BOOL)hasRegularFileNamed:(NSString *)filename {
for (NSDictionary *fileInfoDict in files) {
NSString *path = fileInfoDict[@"Path"];
NSString *fn = [path lastPathComponent];
if ([fn isEqualToString:filename]) {
BOOL isDir;
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] || isDir) {
continue;
}
return YES;
}
}
return NO;
}
- (BOOL)hasRelativePath:(NSString *)relPath {
for (NSDictionary *fileInfoDict in files) {
NSString *path = fileInfoDict[@"Path"];
BOOL isDir;
// Doesn't exist?
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
continue;
}
// It's a regular file and it does exist
if (!isDir) {
return YES;
}
// OK, it's a directory. Try to resolve relative path.
NSString *parentDir = [path stringByDeletingLastPathComponent];
NSString *absPath = [parentDir stringByAppendingPathComponent:relPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:absPath isDirectory:&isDir] && !isDir) {
return YES;
}
}
return NO;
}
- (NSArray <NSString *> *)filePaths {
NSMutableArray <NSString *> *filePaths = [NSMutableArray array];
for (NSDictionary *item in files) {
[filePaths addObject:item[@"Path"]];
}
return [filePaths copy];
}
- (void)setFilePaths:(NSArray <NSString *> *)filePaths {
[files removeAllObjects];
[self addFiles:filePaths];
}
- (IBAction)setToDefaults:(id)sender {
[self clearFileList:self];
}
#pragma mark - Interface actions
- (void)itemDoubleClicked:(id)sender {
BOOL commandKeyDown = (([[NSApp currentEvent] modifierFlags] & NSEventModifierFlagCommand) == NSEventModifierFlagCommand);
if (commandKeyDown) {
[self revealInFinder:[tableView clickedRow]];
} else {
[self openInFinder:[tableView clickedRow]];
}
}
- (void)revealInFinder:(NSInteger)index {
[WORKSPACE selectFile:files[index][@"Path"] inFileViewerRootedAtPath:@""];
}
- (void)openInFinder:(NSInteger)index {
[WORKSPACE openFile:files[index][@"Path"]];
}
- (void)openInEditor:(int)index {
NSString *defaultEditor = [DEFAULTS stringForKey:DefaultsKey_DefaultEditor];
NSString *path = files[index][@"Path"];
if ([defaultEditor isEqualToString:DEFAULT_EDITOR] == NO) {
// Open it in the external application
if ([WORKSPACE fullPathForApplication:defaultEditor] == nil) {
[Alerts alert:@"Editor not found" subTextFormat:@"The application '%@' could not be found. Reverting to the built-in editor.", defaultEditor];
[DEFAULTS setObject:DEFAULT_EDITOR forKey:DefaultsKey_DefaultEditor];
} else {
[WORKSPACE openFile:path withApplication:defaultEditor];
return;
}
}
// Open in built-in editor
[window setTitle:[NSString stringWithFormat:@"%@ - Editing %@", PROGRAM_NAME, [path lastPathComponent]]];
EditorController *editorController = [[EditorController alloc] init];
[editorController showModalEditorSheetForFile:path window:window];
[window setTitle:PROGRAM_NAME];
}
- (IBAction)copyFilenames:(id)sender {
[self copyFilenamesToPasteboard:YES];
}
- (IBAction)copyPaths:(id)sender {
[self copyFilenamesToPasteboard:NO];
}
- (void)copyFilenamesToPasteboard:(BOOL)basenameOnly {
NSMutableString *copyStr = [[NSMutableString alloc] initWithString:@""];
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (int i = 0; i < [files count]; i++) {
if ([selectedItems containsIndex:i]) {
NSDictionary *fileInfoDict = files[i];
NSString *name = basenameOnly ? fileInfoDict[@"Path"] : [fileInfoDict[@"Path"] lastPathComponent];
[copyStr appendString:[NSString stringWithFormat:@"%@ ", name]];
}
}
[[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:self];
[[NSPasteboard generalPasteboard] setString:copyStr forType:NSPasteboardTypeString];
}
- (IBAction)addFilesToList:(id)sender {
[window setTitle:[NSString stringWithFormat:@"%@ - Select files or folders to add", PROGRAM_NAME]];
// Create open panel
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setPrompt:@"Add"];
[oPanel setCanChooseDirectories:YES];
[oPanel setAllowsMultipleSelection:YES];
// Run as sheet
[oPanel beginSheetModalForWindow:window completionHandler:^(NSInteger result) {
[window setTitle:PROGRAM_NAME];
if (result != NSModalResponseOK) {
return;
}
// Convert NSURLs to paths
NSMutableArray *filePaths = [NSMutableArray array];
for (NSURL *url in [oPanel URLs]) {
[filePaths addObject:[url path]];
}
[self addFiles:filePaths];
}];
}
- (IBAction)clearFileList:(id)sender {
[files removeAllObjects];
[self updateUI];
}
- (IBAction)revealSelectedFilesInFinder:(id)sender {
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (int i = 0; i < [files count]; i++) {
if ([selectedItems containsIndex:i]) {
[self revealInFinder:i];
}
}
}
- (IBAction)openSelectedFiles:(id)sender {
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (int i = 0; i < [files count]; i++) {
if ([selectedItems containsIndex:i]) {
[self openInFinder:i];
}
}
}
- (IBAction)editSelectedFile:(id)sender {
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (int i = 0; i < [files count]; i++) {
if ([selectedItems containsIndex:i]) {
[self openInEditor:i];
return;
}
}
}
- (IBAction)removeSelectedFiles:(id)sender {
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (NSInteger i = [files count]; i >= 0; i--) {
if ([selectedItems containsIndex:i]) {
[files removeObjectAtIndex:i];
}
}
if ([tableView numberOfRows]) {
NSInteger rowToSelect = [selectedItems firstIndex] - 1;
[tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:rowToSelect] byExtendingSelection:NO];
}
[self updateUI];
}
#pragma mark - NSTableViewDelegate/DataSource
- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView {
return [files count];
}
- (NSView *)tableView:(NSTableView *)tv viewForTableColumn:(NSTableColumn *)tc row:(NSInteger)row {
NSTableCellView *cellView = [tv makeViewWithIdentifier:@"MainCell" owner:self];
cellView.textField.stringValue = [files[row][@"Path"] lastPathComponent];
cellView.textField.textColor = [FILEMGR fileExistsAtPath:files[row][@"Path"]] ? [NSColor controlTextColor] : [NSColor redColor];
cellView.imageView.objectValue = files[row][@"Icon"];
return cellView;
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
[self updateButtonStatus];
}
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pb {
NSMutableArray *filenames = [NSMutableArray arrayWithCapacity:[rowIndexes count]];
NSInteger index = [rowIndexes firstIndex];
while (NSNotFound != index) {
[filenames addObject:files[index][@"Path"]];
index = [rowIndexes indexGreaterThanIndex:index];
}
[pb declareTypes:@[NSFilenamesPboardType] owner:nil];
[pb setPropertyList:filenames forType:NSFilenamesPboardType];
return YES;
}
- (BOOL)tableView:(NSTableView *)tv acceptDrop:(id <NSDraggingInfo> )info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation {
NSPasteboard *pboard = [info draggingPasteboard];
NSArray *draggedFiles = [pboard propertyListForType:NSFilenamesPboardType];
[self addFiles:draggedFiles];
return YES;
}
- (NSDragOperation)tableView:(NSTableView *)tv validateDrop:(id <NSDraggingInfo> )info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation {
return NSDragOperationLink;
}
- (CGFloat)tableView:(NSTableView *)theTableView heightOfRow:(NSInteger)row {
return 18;
}
#pragma mark - Menu delegate
- (void)menuWillOpen:(NSMenu *)menu {
// Dynamically generate Open With submenu for item
NSString *path = nil;
NSUInteger idx = [tableView clickedRow];
if (idx != -1) {
path = files[idx][@"Path"];
}
[WORKSPACE openWithMenuForFile:path target:nil action:nil menu:menu];
}
- (BOOL)validateMenuItem:(NSMenuItem *)anItem {
SEL selector = [anItem action];
if (selector == @selector(addFilesToList:)) {
return YES;
}
if (selector == @selector(clearFileList:) && [files count] >= 1) {
return YES;
}
// Folders are never editable
if (selector == @selector(openInEditor:)) {
NSIndexSet *selectedItems = [tableView selectedRowIndexes];
for (int i = 0; i < [files count]; i++) {
if ([selectedItems containsIndex:i]) {
NSString *filename = files[i][@"Path"];
BOOL isFolder;
[FILEMGR fileExistsAtPath:filename isDirectory:&isFolder];
return !isFolder;
}
}
}
if ([tableView selectedRow] == -1) {
return NO;
}
return YES;
}
@end