forked from ImageOptim/ImageOptim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilesController.m
More file actions
528 lines (434 loc) · 15.6 KB
/
FilesController.m
File metadata and controls
528 lines (434 loc) · 15.6 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
//
// FilesController.m
//
// Created by porneL on 23.wrz.07.
//
#import "Backend/Job.h"
#import "FilesController.h"
#import "log.h"
#import "Backend/DirScanner.h"
#import "RevealButtonCell.h"
#import "ResultsDb.h"
#import "JobQueue.h"
#import "JobProxy.h"
@interface FilesController ()
@property (readonly, copy) NSArray *extensions;
@property (assign) BOOL isStoppable;
- (void)updateBusyState;
@end
NSString *const kJobQueueFinished = @"JobQueueFinished";
static NSString *kIMDraggedRowIndexesPboardType = @"com.imageoptim.rows";
@implementation FilesController {
JobQueue *jobQueue;
NSLock *queueWaitingLock;
NSTableView *tableView;
BOOL isEnabled, isBusy, isStoppable;
NSInteger nextInsertRow;
NSHashTable *seenPathHashes;
ResultsDb *db;
}
@synthesize isBusy, isStoppable;
- (void)configureWithTableView:(NSTableView *)inTableView {
tableView = inTableView;
seenPathHashes = [NSHashTable weakObjectsHashTable];
db = [ResultsDb new];
queueWaitingLock = [NSLock new];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
jobQueue = [[JobQueue alloc] initWithCPUs:[defs integerForKey:@"RunConcurrentFiles"]
dirs:[defs integerForKey:@"RunConcurrentDirscans"]
files:[defs integerForKey:@"RunConcurrentFileops"]
defaults:defs];
[jobQueue addObserver:self forKeyPath:@"isBusy" options:0 context:NULL];
[tableView registerForDraggedTypes:@[ NSFilenamesPboardType, kIMDraggedRowIndexesPboardType ]];
[self setSelectsInsertedObjects:NO];
isEnabled = YES;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"isBusy"]) {
[self updateBusyState];
}
}
- (void)setRow:(NSInteger)row {
nextInsertRow = row;
}
- (void)cleanup {
isEnabled = NO;
[jobQueue cleanup];
NSArray *content = [self content];
[content makeObjectsPerformSelector:@selector(cleanup)];
}
- (NSDragOperation)tableView:(NSTableView *)atableView
validateDrop:(id<NSDraggingInfo>)info
proposedRow:(NSInteger)row
proposedDropOperation:(NSTableViewDropOperation)operation {
if (!isEnabled) {
return NSDragOperationNone;
}
NSDragOperation dragOp = ([info draggingSource] == tableView) ? NSDragOperationMove : NSDragOperationCopy;
[atableView setDropRow:row dropOperation:NSTableViewDropAbove];
return dragOp;
}
- (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard {
if (!isEnabled) return NO;
NSArray *fileUrls = [[[self arrangedObjects] objectsAtIndexes:rowIndexes] valueForKey:@"filePath"];
NSUInteger count = [fileUrls count];
if (count) {
NSArray *types = @[NSFilenamesPboardType, kIMDraggedRowIndexesPboardType];
if (count == 1) {
types = [types arrayByAddingObject:NSURLPboardType];
}
[pboard declareTypes:types owner:nil];
if (count == 1) {
[[fileUrls firstObject] writeToPasteboard:pboard];
}
return [pboard setPropertyList:[fileUrls valueForKey:@"path"] forType:NSFilenamesPboardType] &&
[pboard setData:[NSKeyedArchiver archivedDataWithRootObject:rowIndexes]
forType:kIMDraggedRowIndexesPboardType];
}
return NO;
}
- (void)removeObjects:(NSArray *)objects {
[super removeObjects:objects];
[objects makeObjectsPerformSelector:@selector(cleanup)];
}
- (NSString *)tableView:(NSTableView *)aTableView toolTipForCell:(NSCell *)aCell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)aTableColumn row:(int)row mouseLocation:(NSPoint)mouseLocation {
NSArray *objs = [self arrangedObjects];
if (row < (signed)[objs count]) {
JobProxy *f = objs[row];
assert([f isKindOfClass:[JobProxy class]]);
if ([aCell isKindOfClass:[RevealButtonCell class]]) {
NSRect infoButtonRect = [((RevealButtonCell *)aCell) infoButtonRectForBounds:*rect];
BOOL mouseIsInside = NSMouseInRect(mouseLocation, infoButtonRect, [aTableView isFlipped]);
if (mouseIsInside) {
return f.filePath.path;
}
}
return [f statusText];
}
return nil;
}
// Better in NSArrayController class
- (NSUInteger)rowsAboveRow:(NSUInteger)row inIndexSet:(NSIndexSet *)indexSet {
NSUInteger currentIndex = [indexSet firstIndex];
NSUInteger i = 0;
while (currentIndex != NSNotFound) {
if (currentIndex < row) {
i++;
}
currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
}
return i;
}
- (NSUInteger)numberOfRowsInTableView:(NSTableView *)tableview {
return [[self arrangedObjects] count];
}
- (void)moveObjectsInArrangedObjectsFromIndexes:(NSIndexSet *)indexSet
toIndex:(NSUInteger)insertIndex {
NSArray *objects = [self arrangedObjects];
NSUInteger idx = [indexSet lastIndex];
NSUInteger aboveInsertIndexCount = 0;
id object;
NSUInteger removeIndex;
while (NSNotFound != idx) {
if (idx >= insertIndex) {
removeIndex = idx + aboveInsertIndexCount;
aboveInsertIndexCount += 1;
} else {
removeIndex = idx;
insertIndex -= 1;
}
object = objects[removeIndex];
[self removeObjectAtArrangedObjectIndex:removeIndex];
[self insertObject:object atArrangedObjectIndex:insertIndex];
idx = [indexSet indexLessThanIndex:idx];
}
}
- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation {
NSPasteboard *pboard = [info draggingPasteboard];
NSData *indexesArchived;
if ([info draggingSource] == aTableView && (indexesArchived = [pboard dataForType:kIMDraggedRowIndexesPboardType])) {
NSIndexSet *indexSet = [NSKeyedUnarchiver unarchiveObjectWithData:indexesArchived];
NSIndexSet *selection = [self selectionIndexes];
BOOL containsSelection = [selection containsIndexes:indexSet];
[self moveObjectsInArrangedObjectsFromIndexes:indexSet toIndex:row];
if (containsSelection) {
NSUInteger rowsAbove = [self rowsAboveRow:row inIndexSet:indexSet];
NSRange range = NSMakeRange(row - rowsAbove, [indexSet count]);
indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[self setSelectionIndexes:indexSet];
} else if (![selection count]) {
// non-empty selection seems to be preserved, but if there was no selection
// then tableview selects a row
[self setSelectedObjects:@[]];
}
return YES;
} else {
NSArray *paths = [pboard propertyListForType:NSFilenamesPboardType];
nextInsertRow = row;
[self performSelectorInBackground:@selector(addPaths:) withObject:paths];
}
[[aTableView window] makeKeyAndOrderFront:aTableView];
return YES;
}
/** selfLock must be locked before using this
That's a dumb linear search. Would be nice to replace NSArray with NSSet or NSHashTable.
*/
- (JobProxy *)findFileByPath:(NSURL *)path {
if (![seenPathHashes containsObject:path]) {
return nil;
}
NSString *pathString = path.path;
for (JobProxy *f in [self content]) {
assert([f isKindOfClass:[JobProxy class]]);
if ([pathString isEqualToString:f.filePath.path]) {
return f;
}
}
return nil;
}
- (void)addJobObjects:(NSArray<JobProxy *> *)files {
[[tableView undoManager] registerUndoWithTarget:self selector:@selector(removeObjects:) object:files];
[[tableView undoManager] setActionName:NSLocalizedString(@"Add", @"undo command name")];
@synchronized(self) {
if (nextInsertRow < 0 || nextInsertRow >= [[self arrangedObjects] count]) {
[self addObjects:files];
} else {
NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(nextInsertRow, [files count])];
[self insertObjects:files atArrangedObjectIndexes:set];
nextInsertRow += [files count];
}
}
}
- (void)addURLsBelowSelection:(NSArray<NSURL *> *)paths {
nextInsertRow = [self selectionIndex];
[self performSelectorInBackground:@selector(addURLs:) withObject:paths];
}
- (BOOL)addPaths:(NSArray<NSString *> *)paths {
NSMutableArray *urls = [NSMutableArray arrayWithCapacity:[paths count]];
for (NSString *path in paths) {
[urls addObject:[NSURL fileURLWithPath:path]];
}
return [self addURLs:urls filesOnly:NO];
}
- (BOOL)addURLs:(NSArray<NSURL *> *)paths {
return [self addURLs:paths filesOnly:NO];
}
/** filesOnly indicates that paths do not contain any directories or symlinks */
- (BOOL)addURLs:(NSArray<NSURL *> *)paths filesOnly:(BOOL)filesOnly {
if (!isEnabled) {
return NO;
}
NSMutableArray<JobProxy*> *toAdd = [NSMutableArray arrayWithCapacity:[paths count]];
BOOL allOK = YES;
NSFileManager *fm = filesOnly ? nil : [NSFileManager defaultManager];
for (NSURL *relpath in paths) {
NSURL *path;
BOOL isDir = NO;
if (!fm) {
path = relpath;
} else {
path = [relpath URLByResolvingSymlinksInPath];
if (![fm fileExistsAtPath:path.path isDirectory:&isDir]) {
IOWarn("%@ doesn't exist", path.path);
allOK = NO;
continue;
}
}
if (!isDir) {
JobProxy *old = [self findFileByPath:path];
if (old) {
if (![old isBusy]) {
[jobQueue addJob:old.job];
}
} else {
[seenPathHashes addObject:path]; // used by findFileByPath
Job *f = [[Job alloc] initWithFilePath:path resultsDatabase:db];
JobProxy *jobProxy = [[JobProxy alloc] initWithJob: f];
[toAdd addObject:jobProxy];
[jobQueue addJob:f];
}
} else {
DirScanner *w = [[DirScanner alloc] initWithPath:path filesController:self extensions:[self extensions]];
[jobQueue addDirScanner:w];
}
}
[self performSelectorOnMainThread:@selector(addJobObjects:) withObject:toAdd waitUntilDone:NO];
return allOK;
}
- (NSNumber *)queueCount {
return [jobQueue queueCount];
}
- (void)stopSelected {
for (JobProxy *f in self.selectedObjects) {
[f stop];
}
[self updateStoppableState];
}
- (void)revert {
BOOL beep = NO;
NSArray *array = [self selectedObjects];
for (JobProxy *f in array) {
if (![f revert]) {
beep = YES;
}
}
if (beep) {
NSBeep();
}
}
- (BOOL)canRevert {
NSArray *array = [self selectedObjects];
for (JobProxy *f in array) {
if ([f canRevert]) {
return YES;
}
}
return NO;
}
- (BOOL)canClearComplete {
for (JobProxy *f in [self arrangedObjects]) {
if (f.isDone) {
return YES;
}
}
return NO;
}
- (void)clearComplete {
NSUInteger i = 0;
NSMutableIndexSet *set = [NSMutableIndexSet new];
@synchronized(self) {
for (JobProxy *f in [self arrangedObjects]) {
if (f.isDone) {
[set addIndex:i];
}
i++;
}
if ([set count]) {
[self removeObjectsAtArrangedObjectIndexes:set];
}
}
[self setRow:-1];
}
- (BOOL)canStartAgainOptimized:(BOOL)optimized {
NSArray *array = [self selectedObjects];
if (![array count]) {
array = [self content];
}
for (JobProxy *f in array) {
if (!f.isBusy && (!optimized || f.isOptimized)) {
return YES;
}
}
return NO;
}
- (void)startAgainOptimized:(BOOL)optimized {
BOOL anyStarted = NO;
@synchronized(self) {
NSArray<JobProxy*> *jobs = [self selectedObjects];
NSInteger selectionCount = [jobs count];
// UI doesn't give a way to deselect all, so here's a substitute
// when selecting "again" on file that doesn't need it, deselect
if (1 == selectionCount) {
JobProxy *job = jobs[0];
if (job.isBusy || !job.isOptimized) {
jobs = [jobs copy];
[self setSelectedObjects:@[]];
}
} else if (!selectionCount) {
jobs = [self content];
}
for (JobProxy *f in jobs) {
if (!f.isBusy && (!optimized || f.isOptimized)) {
[jobQueue addJob:f.job];
anyStarted = YES;
}
}
}
if (!anyStarted) NSBeep();
}
- (void)updateBusyState {
BOOL currentlyBusy = [jobQueue isBusy];
if (isBusy != currentlyBusy) {
[self willChangeValueForKey:@"isBusy"];
isBusy = currentlyBusy;
[self didChangeValueForKey:@"isBusy"];
[self updateStoppableState];
}
if (!currentlyBusy) {
[[NSNotificationCenter defaultCenter] postNotificationName:kJobQueueFinished object:self];
}
}
- (void)updateStoppableState {
if (isBusy) {
NSArray *array = [self selectedObjects];
for(JobProxy *f in array) {
if ([f isStoppable]) {
self.isStoppable = YES;
return;
}
}
}
self.isStoppable = NO;
}
#define PNG_ENABLED 1
#define JPEG_ENABLED 2
#define GIF_ENABLED 4
#define SVG_ENABLED 8
- (int)typesEnabled {
int types = 0;
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
if ([defs boolForKey:@"PngCrush2Enabled"] || [defs boolForKey:@"PngOutEnabled"] ||
[defs boolForKey:@"OptiPngEnabled"] || [defs boolForKey:@"AdvPngEnabled"] || [defs boolForKey:@"ZopfliEnabled"]) {
types |= PNG_ENABLED;
}
if ([defs boolForKey:@"JpegOptimEnabled"] || [defs boolForKey:@"JpegTranEnabled"]) {
types |= JPEG_ENABLED;
}
if ([defs boolForKey:@"GifsicleEnabled"]) {
types |= GIF_ENABLED;
}
if ([defs boolForKey:@"SvgoEnabled"] || [defs boolForKey:@"SvgcleanerEnabled"]) {
types |= SVG_ENABLED;
}
if (!types) types = PNG_ENABLED; // will show error in the list
return types;
}
- (NSArray *)extensions {
int types = [self typesEnabled];
NSMutableArray *extensions = [NSMutableArray array];
if (types & PNG_ENABLED) {
[extensions addObject:@"png"];
[extensions addObject:@"PNG"];
}
if (types & JPEG_ENABLED) {
[extensions addObjectsFromArray:@[ @"jpg", @"JPG", @"jpeg", @"JPEG" ]];
}
if (types & GIF_ENABLED) {
[extensions addObject:@"gif"];
[extensions addObject:@"GIF"];
}
if (types & SVG_ENABLED) {
[extensions addObject:@"svg"];
}
return extensions;
}
- (NSArray *)fileTypes {
int types = [self typesEnabled];
NSMutableArray *fileTypes = [NSMutableArray array];
if (types & PNG_ENABLED) {
[fileTypes addObjectsFromArray:@[ @"png", @"PNG", NSFileTypeForHFSTypeCode('PNGf'), @"public.png", @"image/png" ]];
}
if (types & JPEG_ENABLED) {
[fileTypes addObjectsFromArray:@[ @"jpg", @"jpeg", @"JPG", @"JPEG", NSFileTypeForHFSTypeCode('JPEG'), @"public.jpeg", @"image/jpeg" ]];
}
if (types & GIF_ENABLED) {
[fileTypes addObjectsFromArray:@[ @"gif", @"GIF", NSFileTypeForHFSTypeCode('GIFf'), @"public.gif", @"image/gif" ]];
}
if (types & SVG_ENABLED) {
[fileTypes addObjectsFromArray:@[ @"svg", @"public.svg-image", @"image/svg" ]];
}
return fileTypes;
}
@end