-
Notifications
You must be signed in to change notification settings - Fork 1
/
MainWindowController.m
1750 lines (1483 loc) · 68.8 KB
/
MainWindowController.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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MainWindowController.m
//
// Created by Andrew Hodgkinson on 28/03/2010.
// Copyright 2010, 2011 Hipposoft. All rights reserved.
//
#import "MainWindowController.h"
#import "ApplicationSupport.h"
#import "Icons.h"
#import "CustomIconGenerator.h"
#import "SlipCoverSupport.h"
#import "GlobalConstants.h"
#import "GlobalSemaphore.h"
#import "ConcurrentCellProcessor.h"
#import "ConcurrentPathProcessor.h"
#import <Foundation/Foundation.h>
#define NSINDEXSET_ON_PBOARD @"NSIndexSetOnPboardType"
@interface MainWindowController()
@property NSOperationQueue * queue;
@end
@implementation MainWindowController
@synthesize iconStyleManager,
managedObjectContext,
managedObjectModel;
- ( void ) awakeFromNib
{
tableContents = [ [ NSMutableArray alloc ] init ];
self.queue = [ [ NSOperationQueue alloc ] init ];
/* Although documentation implies that the system should be left alone to
* set this up, in practice doing so causes very high system workload for
* large numbers of folders. Trying to cancel the operation takes a long
* time, because OS X appears to queue *all* operations extremely quickly,
* then has to cancel the whole lot.
*
* By restricting concurrency, this up-front queueing and latency comes
* under control. OS X may choose to use *less* than this of course, it's
* just a maximum. The value chosen here should soak CPUs on most machines
* but still (at least on the author's laptop at the time of writing)
* responds to cancellation quickly.
*
* This is entirely unscientific and unsatisfactory but given OS X's poor
* behaviour here (was OK on 10.6, got bad in 10.7, still bad in 10.10.2)
* there doesn't seem to be another way; though if anyone else other than
* me ever reads this and has suggestions, I'd love to hear them!
*/
self.queue.maxConcurrentOperationCount = 8;
[ self initOpenPanel ];
[ self initWindowContents ];
/* On OS X Yosemite (10.10.x) and later, the green 'zoom' window control
* changes to become 'full screen'. This is nonsensical for an application
* that really needs to live alongside Finder windows to be useful, even
* given split screen in OS X El Capitan (10.11.x).
*
* Setting the button behaviour to 'auxiliary' in the XIB file causes
* warnings about compatibility before OS X 10.7; we'd quite like to stay
* compatible with OS X 10.6 if possible. So instead, set this at run time
* if on OS X 10.10 or later.
*
* It just so happens that a high level interface to determine OS X version
* was introduced in 10.10 - so if this exists, we already know we're on a
* new enough version.
*/
if ( [ [ NSProcessInfo processInfo ] respondsToSelector: @selector( operatingSystemVersion ) ] )
{
self.window.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary;
}
}
/******************************************************************************\
* -initWithWindowNibName:
*
* Initialise the class, internally recording (and indeed creating, if need be)
* an icon style manager and associated data in passing.
*
* Upon initialisation, this controller will open its window, put it at the
* front of the normal stack and make it the key window.
*
* In: ( NSString * ) windowNibName
* Name of the NIB containing this controller's window.
*
* Out: ( id )
* This instance ("self").
\******************************************************************************/
- ( instancetype ) initWithWindowNibName: ( NSString * ) windowNibName
{
if ( ( self = [ super initWithWindowNibName: windowNibName ] ) )
{
iconStyleManager = [ IconStyleManager iconStyleManager ];
managedObjectContext = [ iconStyleManager managedObjectContext ];
managedObjectModel = [ iconStyleManager managedObjectModel ];
[ [ self window ] center ];
[ [ self window ] makeKeyAndOrderFront: nil ];
}
return self;
}
/******************************************************************************\
* -initWindowContents
*
* Initialise the window contents, such as the table view and action buttons.
*
* See also: -initWithWindowNibName:
* -awakeFromNib
\******************************************************************************/
- ( void ) initWindowContents
{
[ removeButton setEnabled: NO ];
[ stylesSubMenuItem setEnabled: NO ];
[ [ NSNotificationCenter defaultCenter ] addObserver: self
selector: @selector( folderListSelectionChanged: )
name: NSTableViewSelectionDidChangeNotification
object: folderList ];
[ folderListClipView setPostsBoundsChangedNotifications: YES ];
[ [ NSNotificationCenter defaultCenter ] addObserver: self
selector: @selector( scrollPositionChanged: )
name: NSViewBoundsDidChangeNotification
object: folderListClipView ];
/* Set up supported user interaction operations */
[ folderList registerForDraggedTypes: @[ NSFilenamesPboardType, NSINDEXSET_ON_PBOARD ] ];
[ folderList setDraggingSourceOperationMask: NSDragOperationLink forLocal: NO ];
[ folderList setDraggingSourceOperationMask: NSDragOperationMove forLocal: YES ];
[ folderList setAllowsColumnSelection: NO ];
/* Since we've a shared CoreData managed object context by now (see
* "-initWithWindowNibName:"), we can use it to listen for changes to
* the icon style list. If a style is deleted when in use, for example,
* the folder list table view breaks badly unless we change to another
* style. This can happen manually or because a user deletes a SlipCover
* case definition which was in use by a user-defined icon style.
*/
[ [ NSNotificationCenter defaultCenter ] addObserver: self
selector: @selector( iconStyleListChanged: )
name: NSManagedObjectContextObjectsDidChangeNotification
object: managedObjectContext ];
}
/******************************************************************************\
* -initOpenPanel
*
* Initialise the file dialogue box used to add folders to the table view
* in the main window. Store the initialised object in "openPanel". This
* object must be released when no longer required.
*
* See also: -addButtonPressed
\******************************************************************************/
- ( void ) initOpenPanel
{
NSString * home = [ @"~" stringByExpandingTildeInPath ];
openPanel = [ NSOpenPanel openPanel ];
[ openPanel setMessage: NSLocalizedString( @"Choose folders to be given new icons", @"Message shown in the Open Panel used for folder addition" ) ];
[ openPanel setPrompt: NSLocalizedString( @"Add", @"Button text in the Open Panel used for folder addition" ) ];
[ openPanel setCanChooseFiles: NO ];
[ openPanel setCanChooseDirectories: YES ];
[ openPanel setCanCreateDirectories: NO ];
[ openPanel setAllowsMultipleSelection: YES ];
[ openPanel setResolvesAliases: YES ];
[ openPanel setDirectoryURL: [ NSURL fileURLWithPath: home
isDirectory: YES ] ];
}
//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Task initiation and the modal progress panel
//------------------------------------------------------------------------------
/******************************************************************************\
* -showProgressPanelWithMessage:andAction:andData:
*
* Show a modal progress panel and perform some action in a thread. When the
* thread is cancelled or finishes its task, it MUST ask the main thread to
* call "[NSApp abortModal]" so that the modal run loop can exit, *AFTER* it
* has shut down its autorelease pool (if it created one).
*
* In: ( NSString * ) message
* String shown above the progress bar (e.g. "Adding folders...");
*
* ( SEL ) actionSelector
* Selector to invoke within the worker thread, which must be of the
* signature "- ( void ) actionSelector: ( id ) actionSelectorData";
*
* ( id ) actionSelectorData
* User data parameter passed to action selector.
\******************************************************************************/
- ( void ) showProgressPanelWithMessage: ( NSString * ) message
andAction: ( SEL ) actionSelector
andData: ( id ) actionSelectorData
{
/* Set up the progress indicator panel */
[ progressIndicatorLabel setStringValue: message ];
[ progressIndicator setIndeterminate: YES ];
[ progressIndicator startAnimation: self ];
[ progressStopButton setEnabled: YES ];
[ progressStopButton setTitle: NSLocalizedString( @"Stop", @"Title shown in progress panel 'stop' button when the progress panel is first shown" ) ];
/* Start the modal run loop before the worker thread, to avoid possible
* race conditions where the worker manages to finish before the panel
* has opened and/or the modal run loop been entered.
*/
[ NSApp beginSheet: progressIndicatorPanel
modalForWindow: [ self window ]
modalDelegate: nil
didEndSelector: nil
contextInfo: nil ];
/* Kick off the task in an independent thread so the GUI can still
* respond within its (modal) run loop. Almost nothing can happen to
* the GUI while this thread runs, avoiding most issues with reentrancy
* and thread safety.
*
* http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html%23//apple_ref/doc/uid/10000057i-CH12-SW1
*/
workerThread = [ [ NSThread alloc ] initWithTarget: self
selector: actionSelector
object: actionSelectorData ];
[ workerThread start ];
/* Now wait for the modal session to end either by the user clicking on
* the progress panel's 'Stop' button or via the task in the timer
* cancelling it. This call does not return as long as the modal run
* loop is running.
*/
[ NSApp runModalForWindow: progressIndicatorPanel ];
/* Once execution continues at this point, the modal run loop has been
* ended by the worker thread asking the main thread to send 'stopModal'
* to 'NSApp'.
*/
/* Close the progress panel */
[ NSApp endSheet: progressIndicatorPanel ];
[ progressIndicator stopAnimation: self ];
[ progressIndicatorPanel orderOut: self ];
/* Whether processing icons or adding subdirectories, the folder list can
* be updated; it's harmless to call this if not (just wastes CPU cycles at
* a very "non-critical" moment) and essential to call this if so.
*/
[ folderList reloadData ];
}
/******************************************************************************\
* -closeProgressPanel:
*
* Action sent by the 'Stop' button in the modal progress panel. Changes the
* button so it is no longer enabled and says 'Stopping...', then cancels the
* worker thread and does nothing else - the rest is up to the thread.
*
* In: ( id ) sender
* Sender of the message (ignored).
*
* See also: -showProgressPanelWithMessage:andAction:andData:
\******************************************************************************/
- ( IBAction ) closeProgressPanel: ( id ) sender
{
[ progressStopButton setEnabled: NO ];
[ progressStopButton setTitle: NSLocalizedString( @"Stopping...", @"Title shown in progress panel 'stop' button once the button has been clicked upon and worker thread cancellation is underway" ) ];
[ workerThread cancel ];
}
/******************************************************************************\
* -considerInsertingSubfoldersOf:
*
* If user defaults say that sub-folders should be added, then add them,
* showing a modal progress panel during the addition.
*
* To make sure that any existing modal operations have already finished, the
* operation is run on an NSTimer which fires as soon as possible after this
* method is invoked.
*
* In: ( NSDictionary * ) parentFolders
* A dictionary with a key of "urls", in which case the value is an
* NSArray of file URLs, *OR* a key of "strings", in which case the
* value is an NSArray of NSString values giving the POSIX path of
* each parent folder. If an additional key "firstIndex" is present,
* its value is as "unsigned long" in an NSNumber, giving the first
* index at which addition will commence (e.g. 0 would start at index
* 0, shuffling all other items below it downwards) - otherwise,
* folders are added to the end of the list;
*
* It is assumed that the parent folders are already added; only sub-
* folders will be added thereafter, excluding hidden items, packages
* (e.g. ".app" bundles) or package contents.
*
* See also: -startInsertingSubfoldersOnTimer:
\******************************************************************************/
- ( void ) considerInsertingSubfoldersOf: ( NSDictionary * ) parentFolders
{
if ( [ [ NSUserDefaults standardUserDefaults ] boolForKey: @"addSubFolders" ] == YES )
{
[ NSTimer scheduledTimerWithTimeInterval: 0
target: self
selector: @selector( insertSubfoldersOnTimer: )
userInfo: parentFolders
repeats: NO ];
}
}
/******************************************************************************\
* -startInsertingSubfoldersOnTimer:
*
* Start inserting sub-folders; see "-considerInsertingSubfoldersOf:" for
* details. Do not call directly.
*
* In: ( NSTimer * ) theTimer
* Timer used to invoke this method; its user info must be set to the
* dictionary as described for "-considerInsertingSubfoldersOf:".
*
* See also: -considerInsertingSubfoldersOf:
\******************************************************************************/
- ( void ) insertSubfoldersOnTimer: ( NSTimer * ) theTimer
{
[ self showProgressPanelWithMessage: NSLocalizedString( @"Adding sub-folders...", @"Message shown in progress panel when adding sub-folders" )
andAction: @selector( addSubFoldersOf: )
andData: [ theTimer userInfo ] ];
}
/******************************************************************************\
* -addSubFoldersOf:
*
* Worker thread suitable for use during a modal run loop. Adds sub-folders
* of a given array of parent folders to the end of the overall folder list.
*
* Invoke via NSThread's "-initWithTarget:selector:object" during modal run
* loops only.
*
* Conforms to the requirements described by
* "-showProgressPanelWithMessage:andAction:andData:" and correctly invoked
* through the actions of "-considerInsertingSubfoldersOf".
*
* When the thread finishes adding folders or is cancelled, it causes
* "-abortModal" to be sent to NSApp in the main thread.
*
* In: ( NSDictionary * ) parentFolders
* As described for "-considerInsertingSubfoldersOf:".
*
* See also: -showProgressPanelWithMessage:andAction:andData:
* -considerInsertingSubfoldersOf:
\******************************************************************************/
- ( void ) addSubFoldersOf: ( NSDictionary * ) parentFolders
{
@autoreleasepool
{
NSArray * parentFolderArray = parentFolders[ @"urls" ];
NSNumber * firstIndex = parentFolders[ @"firstIndex" ];
BOOL isURLs = YES;
NSUInteger startRow, currentRow;
if ( firstIndex != nil ) startRow = currentRow = [ firstIndex unsignedLongValue ];
else startRow = currentRow = [ tableContents count ];
if ( parentFolderArray == nil )
{
parentFolderArray = parentFolders[ @"strings" ];
isURLs = NO;
}
for ( id parentItem in parentFolderArray )
{
/* For convenience, the folder array can specify paths as POSIX path
* strings or URLs. Due to the NSFileManager API not providing a way
* to enumerate based on string with options, only by URL with options,
* we have to convert any strings into URLs.
*/
NSURL * parentPath;
if ( isURLs ) parentPath = ( NSURL * ) parentItem;
else parentPath = [ NSURL fileURLWithPath: ( NSString * ) parentItem
isDirectory: YES ];
/* We're not interested in enumerating package contents or hidden
* files; we do want to know if something is a directory.
*/
NSFileManager * fileManager = [ [ NSFileManager alloc ] init ]; /* Since [NSFileManager defaultManager] is not thread-safe; see Apple docs */
NSDirectoryEnumerator * dirEnum =
[
fileManager enumeratorAtURL: parentPath
includingPropertiesForKeys: @[ NSURLIsDirectoryKey, NSURLIsPackageKey ]
options: NSDirectoryEnumerationSkipsHiddenFiles |
NSDirectoryEnumerationSkipsPackageDescendants
errorHandler: nil
];
for ( NSURL * url in dirEnum )
{
/* Keep checking for thread cancellation in case the user hits
* the 'stop' button in the progress panel.
*/
if ( [ [ NSThread currentThread ] isCancelled ] == YES ) break;
/* Don't add packaged folders */
NSNumber * isDirectory;
NSNumber * isPackage;
NSError * error = nil;
[ url getResourceValue: &isPackage
forKey: NSURLIsPackageKey
error: &error ];
if ( error == nil && [ isPackage boolValue ] == YES )
{
continue;
}
/* Only add (not packaged, see above) folders */
[ url getResourceValue: &isDirectory
forKey: NSURLIsDirectoryKey
error: &error ];
if ( error == nil && [ isDirectory boolValue ] == YES )
{
/* Folder list additions can cause GUI updates and these
* are only truly 'safe' if done in the main thread.
*
* This slows things down a fair bit, but generally the
* bottleneck is still the filesystem, not the CPU.
*/
if ( firstIndex != nil )
{
NSDictionary * dictionary =
@{
@"path": [ url path ],
@"index": @( currentRow )
};
[ self performSelectorOnMainThread: @selector( insertFolderByDictionary: )
withObject: dictionary
waitUntilDone: YES ];
}
else
{
[ self performSelectorOnMainThread: @selector( addFolder: )
withObject: [ url path ]
waitUntilDone: YES ];
}
currentRow ++;
}
}
/* Keep checking for thread cancellation in this outer loop too, again
* in case the user hits the 'stop' button in the progress panel - we
* may have just dropped out of the inner loop above because of that.
*/
if ( [ [ NSThread currentThread ] isCancelled ] == YES ) break;
}
/* Build ranges for the array start to just before the insertion row;
* for the inserted rows; and for just after the inserted rows to the
* end of the array. Then amalgamate the first and last of those so
* we have an array of indices of 'old' and 'new' items.
*/
NSMutableIndexSet * beforeAddition = [ NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange( 0, startRow ) ];
NSIndexSet * duringAddition = [ NSIndexSet indexSetWithIndexesInRange: NSMakeRange( startRow, currentRow - startRow ) ];
NSIndexSet * afterAddition = [ NSIndexSet indexSetWithIndexesInRange: NSMakeRange( currentRow, [ tableContents count ] - currentRow ) ];
[ beforeAddition addIndexes: afterAddition ];
/* Use these results to call the duplicates removal routine, then tell
* the folder list table view about the changes.
*/
[ self removeDuplicatesFromIndices: beforeAddition
comparedAgainst: duringAddition ];
} // @autoreleasepool
/* Tell the main thread to finish modal operation. Since this is happening
* outside the modal window's modal run loop, we must use "abortModal"
* rather than "stopModal", else the modal session won't end in the way
* we expect (specifically the panel stays open until 'some event' causes
* it to "realise" it should have closed, e.g. waving the mouse over it).
*
* When the modal loop ends, the code will "-release" the object which
* represents this thread. We could be terminated at any point. Thus, that
* action must be the last thing we do here. But that in turn means the
* autorelease pool has to be dealt with first and so, we can't just do
* "[NSApp abortModal]" as this leads to various autorelease objects such
* as "NSEvent" being generated - which are thus warned about at the
* console and leaked, as there is no prevailing pool anymore.
*
* The solution is simple enough; just ask the main thread to do the work,
* as its autorelease pool is ready and waiting.
*/
[ NSApp performSelectorOnMainThread: @selector( abortModal )
withObject: nil
waitUntilDone: NO ];
}
/******************************************************************************\
* -startButtonPressed:
*
* Create and add icons for all folders in the folder list.
*
* In: ( id ) sender
* Object sending this message (ignored).
\******************************************************************************/
- ( IBAction ) startButtonPressed: ( id ) sender
{
( void ) sender;
[ self showProgressPanelWithMessage: NSLocalizedString( @"Adding folder icons...", @"Message shown in progress panel when adding custom folders icons" )
andAction: @selector( createFolderIcons: )
andData: tableContents ];
}
/******************************************************************************\
* -createFolderIcons:
*
* Worker thread suitable for use during a modal run loop. Creates and adds
* folder icons from a folder list.
*
* Invoke via NSThread's "-initWithTarget:selector:object" during modal run
* loops only.
*
* Conforms to the requirements described by
* "-showProgressPanelWithMessage:andAction:andData:" and correctly invoked
* through the actions of "-startButtonPressed".
*
* When the thread finishes adding icons or is cancelled, it causes
* "-abortModal" to be sent to NSApp in the main thread.
*
* In: ( NSArray * ) folderList
* Array of NSDictionary objects with key "path" giving the full
* POSIX path of the folder to process and "style" pointing to a
* IconStyle object which describes the style of icon to greate.
* Internally, a copy is used; the given array is not modified.
*
* See also: -showProgressPanelWithMessage:andAction:andData:
* -startButtonPressed:
\******************************************************************************/
- ( void ) createFolderIcons: ( NSArray * ) constArrayOfDictionaries
{
globalSemaphoreInit();
globalErrorFlag = NO;
for ( NSDictionary * folder in constArrayOfDictionaries )
{
NSString * fullPOSIXPath = folder[ @"path" ];
IconStyle * iconStyle = folder[ @"style" ];
ConcurrentPathProcessor * processThisPath =
[
[ ConcurrentPathProcessor alloc ] initWithIconStyle: iconStyle
forPOSIXPath: fullPOSIXPath
];
/* Set a completion block that runs whether the operation is successful,
* fails or is cancelled. In the event we can see that the worker thread
* is cancelled (via the modal progress panel's "Stop" button, tell the
* queue to cancel everything. Even though we'll repeat this over and
* over for all remaining in-flight operations on the queue, it's
* harmless to do so and keeps the code simple.
*/
[
processThisPath setCompletionBlock: ^
{
if ( [ self->workerThread isCancelled ] == YES )
{
[ self.queue cancelAllOperations ];
}
else
{
[ self performSelectorOnMainThread: @selector( advanceProgressBarFor: )
withObject: fullPOSIXPath
waitUntilDone: NO ];
}
}
];
/* Outside the completion block, here in the loop adding operations, we
* also need to check for thread cancellation and use that to cancel the
* queue operations before bailing out of the addition loop.
*/
if ( [ workerThread isCancelled ] == YES )
{
[ self.queue cancelAllOperations ];
break;
}
else
{
[ self.queue addOperation: processThisPath ];
}
}
[ self.queue waitUntilAllOperationsAreFinished ];
/* If things went wrong tell the user in a modal alert opened from within
* this modal loop, so the progress panel is still visible as an indication
* of continuity between the addition process and the alert.
*
* The ConcurrentPathProcessor code sets (thread-safely) a global error flag
* to let us know when something went wrong, albeit in a rather crude way.
*
* If things went *right*, ask the main thread to consider removing folders
* from the folder list (depending on preferences it may or may not do so).
*/
if ( globalErrorFlag )
{
[ self performSelectorOnMainThread: @selector( showAdditionFailureAlert )
withObject: nil
waitUntilDone: YES ];
}
else if ( [ [ NSThread currentThread ] isCancelled ] == NO )
{
[ self performSelectorOnMainThread: @selector( considerEmptyingFolderList )
withObject: nil
waitUntilDone: YES ];
}
/* See "-addSubFoldersOf:" for the rationale behind this next call */
[ NSApp performSelectorOnMainThread: @selector( abortModal )
withObject: nil
waitUntilDone: NO ];
}
/******************************************************************************\
* -advanceProgressBarFor:
*
* Note that a folder with the given full POSIX path has been processed
* successfully. The modal progress panel's progress indicator is advanced
* (and lazy-initialised to a determinate state on the first call).
*
* Invoke within the main processing thread only.
*
* In: ( NSString * ) fullPOSIXPath
* Full POSIX path of the folder which was successfully processed.
\******************************************************************************/
- ( void ) advanceProgressBarFor: ( NSString * ) fullPOSIXPath
{
( void ) fullPOSIXPath;
/* The progress indicator is only changed to a 'determinate' state when
* the first message arrives from the command line tool telling us about
* a folder that was processed.
*/
if ( [ progressIndicator isIndeterminate ] )
{
[ progressIndicator setIndeterminate: NO ];
[ progressIndicator setMinValue: 0 ];
[ progressIndicator setMaxValue: [ tableContents count ] ];
[ progressIndicator setDoubleValue: 0 ];
}
[ progressIndicator incrementBy: 1 ];
}
/******************************************************************************\
* -clearButtonPressed:
*
* Remove custom icons from all folders in the folder list.
*
* In: ( id ) sender
* Object sending this message (ignored).
\******************************************************************************/
- ( IBAction ) clearButtonPressed: ( id ) sender
{
( void ) sender;
NSAlert * alert =
[
NSAlert alertWithMessageText: NSLocalizedString( @"Really Remove Icons?", @"Title shown in alert asking if folder icons should really be removed" )
defaultButton: NSLocalizedString( @"Cancel", @"'Cancel' button in alert asking if folder icons should be removed" )
alternateButton: NSLocalizedString( @"Remove Icons", @"'Yes, remove icons' button shown in alert asking if folder icons should be removed" )
otherButton: nil
informativeTextWithFormat: NSLocalizedString( @"Are you sure you want to remove custom icons from the folders in the list?", @"Question shown in alert asking if folder icons should really be removed" )
];
/* Run the alert box and only add styles if asked to do so */
if ( [ alert runModal ] == NSAlertAlternateReturn )
{
[ self showProgressPanelWithMessage: NSLocalizedString( @"Removing folder icons...", @"Message shown in progress panel when removing custom folders icons" )
andAction: @selector( removeFolderIcons: )
andData: tableContents ];
}
}
/******************************************************************************\
* -removeFolderIcons:
*
* Worker thread suitable for use during a modal run loop. Removes custom
* folder icons from a folder list.
*
* Invoke via NSThread's "-initWithTarget:selector:object" during modal run
* loops only.
*
* Conforms to the requirements described by
* "-showProgressPanelWithMessage:andAction:andData:" and correctly invoked
* through the actions of "-clearButtonPressed".
*
* When the thread finishes removing icons or is cancelled, it causes
* "-abortModal" to be sent to NSApp in the main thread.
*
* In: ( NSArray * ) folderList
* Array of NSDictionary objects with key "path" giving the full
* POSIX path of the folder to process and "style" pointing to a
* IconStyle object which describes the style of icon to greate.
* Internally, a copy is used; the given array is not modified.
*
* See also: -showProgressPanelWithMessage:andAction:andData:
* -startButtonPressed:
\******************************************************************************/
- ( void ) removeFolderIcons: ( NSArray * ) constArrayOfDictionaries
{
@autoreleasepool
{
NSWorkspace * workspace = [ NSWorkspace sharedWorkspace ];
/* No attempt is made to run this in parallel as it isn't clear if
* NSWorkspace is sufficiently re-entrant/thread-safe and it runs
* very quickly anyway.
*/
for ( NSDictionary * folder in constArrayOfDictionaries )
{
NSString * path = folder[ @"path" ];
[ workspace setIcon: nil forFile: path options: 0 ];
if ( [ [ NSThread currentThread ] isCancelled ] == YES ) break;
[ self performSelectorOnMainThread: @selector( advanceProgressBarFor: )
withObject: path
waitUntilDone: YES ];
}
[ self performSelectorOnMainThread: @selector( considerEmptyingFolderList )
withObject: nil
waitUntilDone: YES ];
} // @autoreleasepool
/* See "-addSubFoldersOf:" for the rationale behind this next call */
[ NSApp performSelectorOnMainThread: @selector( abortModal )
withObject: nil
waitUntilDone: NO ];
}
/******************************************************************************\
* -considerEmptyingFolderList
*
* Call if folder processing has been successful. If the preferences say so the
* folder list table contents will be emptied. It is up to the caller to ask
* the folder list table view to reload its data ("[folderList reloadData]")
* in some appropriate context afterwards.
*
* In practice this is intended only to called from the main thread via the
* folder processing thread as part of the modal processing loop, which takes
* care of asking for a data reload in passing itself.
\******************************************************************************/
- ( void ) considerEmptyingFolderList
{
if ( [ [ NSUserDefaults standardUserDefaults ] boolForKey: @"emptyListIfSuccessful" ] == YES )
{
[ tableContents removeAllObjects ];
}
}
/******************************************************************************\
* -showAdditionFailureAlert
*
* Call if folder processing failed. Raises an NSAlert warning the user that
* something went wrong. This is done in a separate method so that a processing
* thread can ask to call here in the main thread, since NSAlert does not
* support being run from any other thread context.
\******************************************************************************/
- ( void ) showAdditionFailureAlert
{
NSString * title = NSLocalizedString( @"Icon Addition Failure", @"Title of alert reporting a failure to add all icons" );
NSString * message = NSLocalizedString( @"One or more of the folder addition attempts failed. You could try again with the existing folder list, clear the folder list and try with a new set of folders, or add fewer folders at a time.", @"Message shown in alert reporting a failure to add all icons ");
NSString * button = NSLocalizedString( @"Continue", @"Button shown in alert reporting a failure to add all icons" );
NSAlert * alert = [ [ NSAlert alloc ] init ];
alert.alertStyle = NSCriticalAlertStyle;
alert.messageText = title;
alert.informativeText = message;
[ alert addButtonWithTitle: button ];
[ alert runModal ];
}
//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Folder Selection Handling
//------------------------------------------------------------------------------
/******************************************************************************\
* -addFolder:
*
* Add the given path to the end of the table contents array with a default
* icon style. The path must be for a folder (this is not checked here).
*
* Duplicates removal is left up to the caller.
*
* In: ( NSString * ) path
* Path of folder to add.
*
* See also: -addFolder:withStyle:
* -insertFolder:atIndex
* -insertFolder:atIndex:withStyle:
* -removeDuplicatesFromIndices:comparedAgainst:
\******************************************************************************/
- ( void ) addFolder: ( NSString * ) path
{
[ self insertFolder: path
atIndex: [ tableContents count ] ];
}
/******************************************************************************\
* -addFolder:withStyle:
*
* Add the given path to the end of the table contents array with the given
* named icon style. The path must be for a folder (this is not checked here).
*
* Duplicates removal is left up to the caller.
*
* In: ( NSString * ) path
* Path of folder to add;
*
* ( IconStyle * ) style
* Icon style to assign to this folder.
*
* See also: -addFolder:
* -insertFolder:atIndex
* -insertFolder:atIndex:withStyle:
* -removeDuplicatesFromIndices:comparedAgainst:
\******************************************************************************/
- ( void ) addFolder: ( NSString * ) path withStyle: ( IconStyle * ) style
{
[ self insertFolder: path
atIndex: [ tableContents count ]
withStyle: style ];
}
/******************************************************************************\
* -insertFolder:atIndex:
*
* Insert the given path at the given index (any other items at or above this
* index being shuffled up one) with a default icon style. The path must be
* for a folder (this is not checked here).
*
* Duplicates removal is left up to the caller.
*
* In: ( NSString * ) path
* Path of folder to add;
*
* ( NSUInteger ) index
* Index at which to insert the new item.
*
* See also: -insertFolder:atIndex:WithStyle:
* -addFolder:
* -addFolder:withStyle:
* -removeDuplicatesFromIndices:comparedAgainst:
\******************************************************************************/
- ( void ) insertFolder: ( NSString * ) path atIndex: ( NSUInteger ) index
{
[ self insertFolder: path
atIndex: index
withStyle: [ iconStyleManager findDefaultIconStyle ] ];
}
/******************************************************************************\
* -insertFolder:atIndex:withStyle:
*
* Insert the given path at the given index (any other items at or above this
* index being shuffled up one) with the given named icon style. The path must
* be for a folder (this is not checked here).
*
* Duplicates removal is left up to the caller.
*
* In: ( NSString * ) path
* Path of folder to add;
*
* ( NSUInteger ) index
* Index at which to insert the new item.
*
* ( IconStyle * ) style
* Icon style to assign to this folder.
*
* See also: -insertFolder:atIndex:
* -addFolder:
* -addFolder:withStyle:
* -removeDuplicatesFromIndices:comparedAgainst:
\******************************************************************************/
- ( void ) insertFolder: ( NSString * ) path atIndex: ( NSUInteger ) index withStyle: ( IconStyle * ) style
{
NSMutableDictionary * record =
[
NSMutableDictionary dictionaryWithObjectsAndKeys: path, @"path",
style, @"style",
nil
];
[ tableContents insertObject: record atIndex: index ];
}
/******************************************************************************\
* -insertFolderByDictionary:
*
* As "-insertFolder:atIndex:", but the path and index are specified in a
* dictionary (see parameters list below). This is less efficient, but means
* the two parameters can be specified in a single argument - useful if being
* called from another thread by one of the "-performSelector..." family of
* messages, for example.
*
* Duplicates removal is left up to the caller.
*
* In: ( NSDictionary * ) dictionary
* Dictionary with an NSString pointer as the value for key "path",
* giving the path of the folder to add and an NSNumber pointer as
* the value for key "index", giving the index at which to insert the
* new item encoded into an NSNumber as an "unsigned long".
*
* See also: -insertFolder:atIndex:
* -insertFolder:atIndex:WithStyle:
* -removeDuplicatesFromIndices:comparedAgainst:
* -addSubfoldersOf:
\******************************************************************************/
- ( void ) insertFolderByDictionary: ( NSDictionary * ) dictionary
{
NSString * path = dictionary[ @"path" ];
NSNumber * index = dictionary[ @"index" ];
[ self insertFolder: path
atIndex: [ index unsignedLongValue ] ];
}
/******************************************************************************\
* -removeDuplicatesFromIndices:comparedAgainst: