-
Notifications
You must be signed in to change notification settings - Fork 1
/
IconStyleManager.m
905 lines (736 loc) · 34.9 KB
/
IconStyleManager.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
//
// IconStyleManager.m
// Add Folder Icons
//
// Created by Andrew Hodgkinson on 24/01/2011.
// Copyright 2011 Hipposoft. All rights reserved.
//
// Handles Core Data storage, including storage or retrieval of IconStyle
// instances and establishing default styles if the Core Data store is empty.
// Monitoring for changes in the SlipCover case design collection is also
// done here; the Core Data store contents are automatically updated.
//
// Always use "+iconStyleManager" to obtain references to instances of this
// class.
//
#import "IconStyleManager.h"
#import "IconStyle.h"
#import "ApplicationSupport.h"
#import "SlipCoverSupport.h"
@interface IconStyleManager ()
- ( void ) checkIconStylesForValidity;
@end
@implementation IconStyleManager
@synthesize persistentStoreCoordinator,
managedObjectContext,
managedObjectModel,
slipCoverDefinitions;
/******************************************************************************\
* +iconStyleManager
*
* Obtain a reference to a singleton instance of the icon style manager,
* creating and initialising that object in passing if required. Always use
* this method to obtain references to the icon style manager.
*
* Out: ( id )
* Value of "self".
\******************************************************************************/
+ ( IconStyleManager * ) iconStyleManager
{
static dispatch_once_t onceToken;
static IconStyleManager * iconStyleManagerSingletonInstance;
dispatch_once( &onceToken, ^{
iconStyleManagerSingletonInstance = [ [ self alloc ] init ];
} );
return iconStyleManagerSingletonInstance;
}
/******************************************************************************\
* -init
*
* Initialise the icon style manager, waking up CoreData and making sure that
* the basic presets are estabilshed in the database in passing.
*
* Do not manually "alloc" an instance of the style manager and then call here.
* Instead, always use "+iconStyleManager".
*
* Out: ( id )
* Value of "self".
\******************************************************************************/
- ( instancetype ) init
{
if ( ( self = [ super init ] ) )
{
/* Register the CoreData managed object ID <=> string value transformer
* and tell it about the persistent store coordinator so it can do its
* work.
*/
coreDataObjectIDTransformer = [ [ CoreDataObjectIDTransformer alloc ] init ];
[ NSValueTransformer setValueTransformer: coreDataObjectIDTransformer
forName: CORE_DATA_OBJECT_ID_TRANSFORMER_NAME ];
[ coreDataObjectIDTransformer setPersistentStoreCoordinator: [ self persistentStoreCoordinator ] ];
/* Make sure the presets are set up; this call is synchronous */
[ self establishPresetIconStyles ];
/* Establish SlipCover preset styles if present and watch for any
* changes, if need be. THIS CALL IS ASYNCHRONOUS - at the point the
* method returns, styles may not yet be defined.
*/
[ self establishSlipCoverIconStyles ];
}
return self;
}
/******************************************************************************\
* -dealloc
*
* If the IconStyleManager singleton is deallocated, it must stop watching for
* any SlipCover case design collection changes.
\******************************************************************************/
- ( void ) dealloc
{
[ slipCoverCaseFolderWatcher stopWatchingPaths ];
}
/******************************************************************************\
* -managedObjectModel
*
* Boilerplate Core Data material generated by Interface Builder 3.2.5.
*
* Creates, retains and returns the managed object model for the application
* by merging all of the models found in the application bundle.
\******************************************************************************/
- ( NSManagedObjectModel * ) managedObjectModel
{
if ( managedObjectModel ) return managedObjectModel;
managedObjectModel = [ NSManagedObjectModel mergedModelFromBundles: nil ];
return managedObjectModel;
}
/******************************************************************************\
* -persistentStoreCoordinator
*
* Boilerplate Core Data material generated by Interface Builder 3.2.5.
*
* Returns the persistent store coordinator for the application. This
* implementation will create and return a coordinator, having added the
* store for the application to it. The directory for the store is created,
* if necessary.
\******************************************************************************/
- ( NSPersistentStoreCoordinator * ) persistentStoreCoordinator
{
if ( persistentStoreCoordinator ) return persistentStoreCoordinator;
NSManagedObjectModel * mom = [ self managedObjectModel ];
if ( ! mom )
{
NSAssert( NO, @"Managed Object Model is nil" );
NSLog ( @"%@:%s No model to generate a store from", [ self class ], sel_getName( _cmd ) );
return nil;
}
NSFileManager * fileManager = [ NSFileManager defaultManager ];
NSString * applicationSupportDirectory = [ ApplicationSupport applicationSupportDirectory ];
NSError * error = nil;
if ( ! [ fileManager fileExistsAtPath: applicationSupportDirectory isDirectory: NULL] )
{
if ( ! [ fileManager createDirectoryAtPath: applicationSupportDirectory withIntermediateDirectories: NO attributes: nil error: &error ] )
{
NSAssert(
NO,
(
[
NSString stringWithFormat: @"Failed to create Application Support directory %@ : %@",
applicationSupportDirectory,
error
]
)
);
NSLog( @"Error creating Application Support directory at %@ : %@", applicationSupportDirectory, error );
return nil;
}
}
NSURL * url = [ NSURL fileURLWithPath: [ applicationSupportDirectory stringByAppendingPathComponent: CORE_DATA_STORE_FILENAME ] ];
persistentStoreCoordinator = [ [ NSPersistentStoreCoordinator alloc ] initWithManagedObjectModel: mom ];
if ( ! [ persistentStoreCoordinator addPersistentStoreWithType: NSXMLStoreType
configuration: nil
URL: url
options: nil
error: &error ] )
{
[ NSApp presentError: error ];
persistentStoreCoordinator = nil;
return nil;
}
return persistentStoreCoordinator;
}
/******************************************************************************\
* -managedObjectContext
*
* Boilerplate Core Data material generated by Interface Builder 3.2.5.
*
* Returns the managed object context for the application (which is already
* bound to the persistent store coordinator for the application.)
\******************************************************************************/
- ( NSManagedObjectContext * ) managedObjectContext
{
if ( managedObjectContext ) return managedObjectContext;
NSPersistentStoreCoordinator * coordinator = [ self persistentStoreCoordinator ];
if ( ! coordinator )
{
NSMutableDictionary * dict = [ NSMutableDictionary dictionary ];
[ dict setValue: @"Failed to initialize the styles store" forKey: NSLocalizedDescriptionKey ];
[ dict setValue: @"There was an error building up the data file." forKey: NSLocalizedFailureReasonErrorKey ];
NSError * error = [ NSError errorWithDomain: @"UkOrgPondAddFolderIconsErrorDomain" code: 9999 userInfo: dict ];
[ NSApp presentError: error ];
return nil;
}
managedObjectContext = [ [ NSManagedObjectContext alloc ] init ];
[ managedObjectContext setPersistentStoreCoordinator: coordinator ];
return managedObjectContext;
}
/******************************************************************************\
* -establishDefaultIconStyles
*
* Set up the default collection of preset icon styles if the database is
* empty, else leaves it alone.
*
* Called from "-init", so other instance methods can rely on the presets being
* present in the database.
\******************************************************************************/
- ( void ) establishPresetIconStyles
{
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
IconStyle * newStyle;
/* Is the icon style collection empty? */
NSError * error = nil;
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
[ request setEntity: styleEntity ];
[ request setIncludesSubentities: NO ];
NSUInteger count = [ moc countForFetchRequest: request error: &error ];
/* Early exit points */
if ( error != nil )
{
[ NSApp presentError: error ];
return;
}
else if ( count != 0 )
{
return;
}
/* "Preset: Classic thumbnails" - defaults are mostly fine */
newStyle = [ [ IconStyle alloc ] initWithEntity: styleEntity
insertIntoManagedObjectContext: moc ];
[ newStyle setIsPreset: @YES ];
[ newStyle setUsesSlipCover: @NO ];
[ newStyle setCreatedAt: [ NSDate date ] ];
[ newStyle setName: DEFAULT_ICON_STYLE_NAME ];
/* "Preset: Square covers (e.g. CDs) - a few more changes */
newStyle = [ [ IconStyle alloc ] initWithEntity: styleEntity
insertIntoManagedObjectContext: moc ];
[ newStyle setIsPreset: @YES ];
[ newStyle setUsesSlipCover: @NO ];
[ newStyle setCreatedAt: [ NSDate date ] ];
[ newStyle setName: NSLocalizedString( ICON_STYLE_PRESET_PREFIX @"Square covers (e.g. CDs)", @"Name of 'CD cover' preset icon style" ) ];
[ newStyle setWhiteBackground: @NO ];
[ newStyle setRandomRotation: @NO ];
[ newStyle setOnlyUseCoverArt: @YES ];
[ newStyle setShowFolderInBackground: @( StyleShowFolderInBackgroundNever ) ];
/* "Preset: Rectangular covers (e.g. DVDs) - the most changes */
newStyle = [ [ IconStyle alloc ] initWithEntity: styleEntity
insertIntoManagedObjectContext: moc ];
[ newStyle setIsPreset: @YES ];
[ newStyle setUsesSlipCover: @NO ];
[ newStyle setCreatedAt: [ NSDate date ] ];
[ newStyle setName: NSLocalizedString( ICON_STYLE_PRESET_PREFIX @"Rectangular covers (e.g. DVDs)", @"Name of 'DVD cover' preset icon style" ) ];
[ newStyle setCropToSquare: @NO ];
[ newStyle setWhiteBackground: @NO ];
[ newStyle setRandomRotation: @NO ];
[ newStyle setOnlyUseCoverArt: @YES ];
[ newStyle setShowFolderInBackground: @( StyleShowFolderInBackgroundNever ) ];
/* Save the presets */
error = nil;
if ( ! [ moc save: &error ] ) [ NSApp presentError: error ];
}
/******************************************************************************\
* -establishSlipCoverIconStyles
*
* Set up any icon styles derived from SlipCover case definitions.
*
* - The user may be prompted one or more times for outside-sandbox access
* - Compares any discovered SlipCover case definitions against current
* styles in the database
* - Warns the user if existing styles must be deleted or asks the user for
* permission if new styles should be added
*
* Called from "-init", but RUNS ASYNCHRONOUSLY. On exit, the SlipCover styles
* will definitely not yet have been established in the database.
\******************************************************************************/
- ( void ) establishSlipCoverIconStyles
{
slipCoverDefinitions = [ [ NSMutableArray alloc ] init ];
[ SlipCoverSupport enumerateSlipCoverDefinitionsInto: slipCoverDefinitions
thenCall: self
with: @selector( checkIconStylesForValidity ) ];
/* Watch SlipCover paths to make sure definitions don't change */
NSMutableArray * watchPaths = [ SlipCoverSupport searchPathsForCovers ];
if ( watchPaths != nil )
{
slipCoverCaseFolderWatcher = [ [ SCEvents alloc ] init ];
[ slipCoverCaseFolderWatcher setDelegate: self ];
[ slipCoverCaseFolderWatcher startWatchingPaths: watchPaths ];
}
}
/******************************************************************************\
* -findSlipCoverStyles
*
* Returns an array of Icon Style objects which all use SlipCover case designs.
* If an error occurs internally, it is reported and 'nil' will be returned.
*
* You should only call this if -establishSlipCoverIconStyles has previously
* run to completion.
*
* Out: ( NSArray * )
* Autoreleased array of pointers to IconStyle structures for each style
* that uses SlipCover. May be empty if there are none, or 'nil' on error.
\******************************************************************************/
- ( NSArray * ) findSlipCoverStyles
{
NSError * error = nil;
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
NSPredicate * predicate = [ NSPredicate predicateWithFormat: @"usesSlipCover == YES" ];
[ request setEntity: styleEntity ];
[ request setIncludesSubentities: NO ];
[ request setPredicate: predicate ];
NSArray * results = [ moc executeFetchRequest: request error: &error ];
if ( error != nil ) [ NSApp presentError: error ];
return results; /* Not 'autoreleased' as we don't "own" the object, according to naming conventions; the framework (must have) dealt with it */
}
/******************************************************************************\
* -checkIconStylesForValidity
*
* Icon styles may become invalid if they use SlipCover case designs and one or
* more of those used designs disappear. Call here to check for such styles and
* delete them, warning the user about the problem in passing.
*
* You should only call this via -establishSlipCoverIconStyles's callback.
\******************************************************************************/
- ( void ) checkIconStylesForValidity
{
NSManagedObjectContext * moc = [ self managedObjectContext ];
/* Find all styles that currently use SlipCover, and all known case names
* in whatever a prior call to -establishSlipCoverIconStyles determined are
* now accessible / available.
*/
NSArray * slipCoverStyles = [ self findSlipCoverStyles ];
NSArray * caseNames = [ slipCoverDefinitions valueForKeyPath: @"@unionOfObjects.name" ]; /* http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html#//apple_ref/doc/uid/20002176-SW2 */
/* Make sure that all styles use valid names */
NSMutableArray * impossibleStyles = [ NSMutableArray arrayWithCapacity: 0 ];
for ( IconStyle * style in slipCoverStyles )
{
if ( [ caseNames containsObject: [ style slipCoverName ] ] == NO )
{
[ impossibleStyles addObject: style ];
}
}
/* Do we have to delete some styles? */
size_t count = [ impossibleStyles count ];
if ( count > 0 )
{
/* First delete them. If this fails there's not much we can really do
* except grin and bear it, so errors are ignored. The rest of the
* application is resilient; the 'Edit Style' panel's menu of styles
* shows the SlipCover case name stored in the IconStyle object but if
* any other menu entry is selected, the 'phantom' case design will not
* be visible when the menu is next shown (that's the way bindings
* behave when a string doesn't match the bound collection). The
* command line tool exits indicating 'failed' if it is given a case
* name which isn't recognised.
*/
for ( IconStyle * style in impossibleStyles )
{
[ moc deleteObject: style ];
}
/* Upon saving, the things directly bound to CoreData take care of
* themselves. MainWindowController updates folder list entries which
* use deleted styles by an observer it added to the styles collection
* and ApplicationSpecificPreferencesWindowController takes care of
* updating the configured default style in the same way, if need be.
*/
[ moc processPendingChanges ];
/* Regardless, warn the user about the event */
NSString * title;
NSString * message;
if ( count == 1 )
{
title = NSLocalizedString(
@"Icon Style Deleted",
@"Title of the message shown when one style becomes invalid because SlipCover cases disappear for any reason"
);
message = NSLocalizedString(
@"One of your Add Folder Icons styles used a SlipCover case design which is no longer available. Since the style is now invalid, it has been deleted.",
@"Message shown when one style becomes invalid because SlipCover cases disappear for any reason"
);
}
else
{
title = NSLocalizedString(
@"Icon Styles Deleted",
@"Title of the message shown when several styles become invalid because SlipCover cases disappear for any reason"
);
message = NSLocalizedString(
@"%u of your Add Folder Icons styles used SlipCover case designs which are no longer available. Since the styles are now invalid, they have been deleted.",
@"Message shown when several styles become invalid because SlipCover cases disappear for any reason"
);
}
NSAlert * alert =
[
NSAlert alertWithMessageText: title
defaultButton: NSLocalizedString(
@"Continue",
@"Button in the alert shown when one or more styles become invalid because SlipCover cases disappear for any reason"
)
alternateButton: nil
otherButton: nil
informativeTextWithFormat: message, count
];
/* Must be run async to allow the main window to open and avoid issues
* with the 'grant permission to read SlipCover styles' panel trying to
* show itself as a modal sheet.
*/
dispatch_after
(
dispatch_time( DISPATCH_TIME_NOW, 1 ),
dispatch_get_main_queue(),
^{
[ alert setShowsHelp: YES ];
[ alert setHelpAnchor: @"slipcover" ];
[ alert runModal ];
}
);
}
/* Never mind deleting things - should we ask to add some styles if
* there are case names that *aren't* used by styles?
*/
NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ];
NSString * suppressionKey = @"neverAskAboutSlipCoverAutoAdd";
if ( [ defaults boolForKey: suppressionKey ] != YES )
{
/* 'Re-find' SlipCover styles as code above may have deleted some */
slipCoverStyles = [ self findSlipCoverStyles ];
/* For every style in the results, delete used names from a copy of
* caseNames so that we're left with names which have no corresponding
* icon style definition.
*/
NSMutableArray * unusedCaseNames = [ NSMutableArray arrayWithArray: caseNames ];
for ( IconStyle * style in slipCoverStyles )
{
NSUInteger index = [ unusedCaseNames indexOfObject: [ style slipCoverName ] ];
if ( index != NSNotFound /* Should never happen, but... */ )
{
[ unusedCaseNames removeObjectAtIndex: index ];
}
}
/* Are there any unused names? */
if ( [ unusedCaseNames count ] > 0 )
{
/* Create the alert box */
NSAlert * alert =
[
NSAlert alertWithMessageText: NSLocalizedString( @"Create SlipCover Styles?", @"Title shown in alert asking if SlipCover cases should be automatically added as styles" )
defaultButton: NSLocalizedString( @"Create Styles", @"'Yes, add them' button in alert asking if SlipCover cases should be automatically added as styles" )
alternateButton: NSLocalizedString( @"Cancel", @"'Cancel' button shown in alert asking if SlipCover cases should be automatically added as styles" )
otherButton: nil
informativeTextWithFormat: NSLocalizedString( @"One or more SlipCover case designs not yet used by Add Folder Icons have been found. Would you like to create Add Folder Icons styles for each of those case designs?", @"Question shown in alert asking if SlipCover cases should be automatically added as styles" )
];
/* Must be run async to allow the main window to open and avoid
* issues with the 'grant permission to read SlipCover styles'
* panel trying to show itself as a modal sheet.
*/
dispatch_after
(
dispatch_time( DISPATCH_TIME_NOW, 1 ),
dispatch_get_main_queue(),
^{
[ alert setShowsSuppressionButton: YES ];
[ alert setShowsHelp: YES ];
[ alert setHelpAnchor: @"slipcover" ];
/* Run the alert box and only add styles if asked to do so */
if ( [ alert runModal ] == NSAlertDefaultReturn )
{
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
IconStyle * newStyle;
/* Loop over unused case names and created styles for each */
for ( NSString * unusedCaseName in unusedCaseNames )
{
NSString * styleName =
[
NSString stringWithFormat: NSLocalizedString( @"SlipCover: %@", @"Name of an auto-defined style created for a SlipCover case"),
unusedCaseName
];
newStyle = [ [ IconStyle alloc ] initWithEntity: styleEntity
insertIntoManagedObjectContext: moc ];
[ newStyle setIsPreset: @NO ];
[ newStyle setUsesSlipCover: @YES ];
[ newStyle setSlipCoverName: unusedCaseName ];
[ newStyle setCreatedAt: [ NSDate date ] ];
[ newStyle setName: styleName ];
}
/* Save the results */
NSError * error = nil;
if ( ! [ moc save: &error ] ) [ NSApp presentError: error ];
}
/* Whatever happens, make sure that "do not show again" is honoured */
if ( [ [ alert suppressionButton ] state ] == NSOnState )
{
[ defaults setBool: YES forKey: suppressionKey ];
}
}
);
}
}
}
/******************************************************************************\
* -findStyleByName:
*
* Return an IconStyle instance given a name which matches one of them.
*
* In: ( NSSring * ) name
* Name of the style to find. It must match precisely.
*
* Out: ( IconStyle * )
* Pointer to the icon style, a managed autoreleased object; or "nil" if
* no style with the given name can be found.
\******************************************************************************/
- ( IconStyle * ) findStyleByName: ( NSString * ) name
{
IconStyle * foundStyle = nil;
NSError * error = nil;
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
NSPredicate * predicate =
[
NSPredicate predicateWithFormat: @"(name == %@)",
name
];
[ request setEntity: styleEntity ];
[ request setIncludesSubentities: NO ];
[ request setPredicate: predicate ];
NSArray * results = [ moc executeFetchRequest: request error: &error ];
if ( error != nil )
{
[ NSApp presentError: error ];
[ NSApp terminate: nil ];
}
if ( [ results count ] == 1 ) foundStyle = results[ 0 ];
return foundStyle;
}
/******************************************************************************\
* -findDefaultIconStyle
*
* Return the configured defaulticon style. If there are problems retrieving
* this, or if it can be retrieved but it is marked as deleted, then the
* standard preset 'Classic' style will be returned instead. In short, the
* method guarantees a valid returned style, unless the presets are broken
* (in that case all bets are off throughout the whole application anyway!).
*
* Out: ( IconStyle * )
* Pointer to the icon style, a managed autoreleased object. Never "nil".
\******************************************************************************/
- ( IconStyle * ) findDefaultIconStyle
{
NSUserDefaults * userDefaults = [ NSUserDefaults standardUserDefaults ];
NSString * objIDString = [ userDefaults stringForKey: PREFERENCES_DEFAULT_STYLE_KEY ];
IconStyle * allElseFails = [ self findClassicIconStyle ];
/* Turn the object ID string into a "real" object ID */
CoreDataObjectIDTransformer * vt = ( CoreDataObjectIDTransformer * )
[
NSValueTransformer valueTransformerForName: CORE_DATA_OBJECT_ID_TRANSFORMER_NAME
];
NSManagedObjectID * objID = [ vt transformedValue: objIDString ];
/* Note - possible early exit; use the default 'Classic' preset if all
* else fails.
*/
if ( objID == nil ) return allElseFails;
/* Adapted from and with thanks to:
* http://cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html
*/
IconStyle * obj = ( IconStyle * ) [ [ self managedObjectContext ] objectWithID: objID ];
/* Have to work harder if this item is a fault; need to fetch it */
if ( [ obj isFault ] == YES )
{
/* If we reach here, the related object may or may not be in memory and
* might not even exist in the persistent store. Try to fetch it now.
*/
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
NSPredicate * predicate =
[
NSPredicate predicateWithFormat: @"SELF = %@",
obj
];
[ request setEntity: [ objID entity ] ];
[ request setPredicate: predicate ];
/* Return either the first found result or the default 'Classic' preset
* if nothing is found or there was an error (when 'results' will be nil,
* so '[results count]' will evaluate to zero).
*/
NSArray * results = [ [ self managedObjectContext ] executeFetchRequest: request
error: nil ];
if ( [ results count ] > 0 ) obj = results[ 0 ];
else obj = allElseFails;
}
/* One final check - code handling changes to the icon style database
* calls here to obtain a valid configured default style for various
* reasons. It's possible that the configured style is the one which
* is being deleted, so always check this and return the 'Classic'
* preset if need be.
*/
if ( [ obj isDeleted ] == NO ) return obj;
else return allElseFails;
}
/******************************************************************************\
* -findClassicIconStyle
*
* Return the preset 'Classic' icon style.
*
* Out: ( IconStyle * )
* Pointer to the icon style, a managed autoreleased object. Never "nil".
\******************************************************************************/
- ( IconStyle * ) findClassicIconStyle
{
IconStyle * foundStyle;
NSError * error = nil;
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
NSPredicate * predicate =
[
NSPredicate predicateWithFormat: @"(isPreset == YES) AND (name == %@)",
DEFAULT_ICON_STYLE_NAME
];
[ request setEntity: styleEntity ];
[ request setIncludesSubentities: NO ];
[ request setPredicate: predicate ];
NSArray * results = [ moc executeFetchRequest: request error: &error ];
if ( error != nil )
{
[ NSApp presentError: error ];
[ NSApp terminate: nil ];
}
assert( [ results count ] == 1 );
foundStyle = results[ 0 ];
assert( foundStyle != nil );
return foundStyle;
}
/******************************************************************************\
* -getStyles
*
* Get an array of all IconStyles, ordered by name.
*
* Out: ( NSArray * )
* Array of IconStyle instances retrieved from Core Data.
\******************************************************************************/
- ( NSArray * ) getStyles
{
NSError * error = nil;
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
NSFetchRequest * request = [ [ NSFetchRequest alloc ] init ];
NSSortDescriptor * sort = [ [ NSSortDescriptor alloc ] initWithKey: @"name" ascending: YES ];
[ request setEntity: styleEntity ];
[ request setIncludesSubentities: NO ];
[ request setSortDescriptors: @[ sort ] ];
NSArray * results = [ moc executeFetchRequest: request error: &error ];
if ( error != nil ) return nil;
else return results;
}
/******************************************************************************\
* -insertBlankUserStyleAndProcessChanges
*
* Create a user (non-preset) icon style with a date-based "undefined..." name
* and insert it into the managed object context, telling the context to
* process changes afterwards, but not saving it. The object will be temporary
* until "-save" is called on the managed object context. If the caller may
* want to undo this insertion, then the caller is responsible for creating
* and managing an undo group.
*
* Out: ( IconStyle * )
* Pointer to the icon style, a managed autoreleased object. Might be nil
* if things go wrong (e.g. out of memory).
\******************************************************************************/
- ( IconStyle * ) insertBlankUserStyleAndProcessChanges
{
NSManagedObjectContext * moc = [ self managedObjectContext ];
NSManagedObjectModel * mom = [ self managedObjectModel ];
NSEntityDescription * styleEntity = [ mom entitiesByName ][ @"IconStyle" ];
IconStyle * newStyle =
[
[ IconStyle alloc ] initWithEntity: styleEntity
insertIntoManagedObjectContext: moc
];
NSString * name =
[
NSString stringWithFormat: NSLocalizedString( @"Untitled %@", "Format string used for untitled, new icon styles; the '%@' field must be included and will be filled in with the current date" ),
[ NSDate date ]
];
[ newStyle setCreatedAt: [ NSDate date ] ];
[ newStyle setName: name ];
/* To avoid having a 'No Value' default selection in the SlipCover list of
* case names, we need to try and find at least one case definition. If
* SlipCover isn't present, 'No Value' is fine.
*/
if ( [ slipCoverDefinitions count ] > 0 )
{
[ newStyle setSlipCoverName: [ slipCoverDefinitions[ 0 ] name ] ];
}
/* OK, tell CoreData to process the new object and return the result */
[ moc processPendingChanges ];
return newStyle;
}
/******************************************************************************\
* -pathWatcher:eventOccurred:
*
* SCEventListenerProtocol: A watched folder has changed.
*
* In: ( SCEvents * ) pathWatcher
* The object that has been watching the changed folder.
*
* ( SCEvent * ) event
* Pointer to an event describing the change (see "SCEvent.h").
\******************************************************************************/
- ( void ) pathWatcher: ( SCEvents * ) pathWatcher eventOccurred: ( SCEvent * ) event
{
( void ) pathWatcher;
( void ) event;
[ self establishSlipCoverIconStyles ];
}
/******************************************************************************\
* -alertShowHelp:
*
* NSAlertDelegate: Show help for the alert. Without this, an alert's help
* button uses its anchor and a nil book. We want to be more specific. Read
* the help anchor and specify our particular help book.
*
* In: ( NSAlert * ) alert
* Alert in question.
*
* Out: If the alert seems to have no help anchor set, NO; else YES.
\******************************************************************************/
- ( BOOL ) alertShowHelp: ( NSAlert * ) alert
{
NSString * anchor = [ alert helpAnchor ];
if ( anchor == nil )
{
return NO;
}
else
{
NSString * book = [ [ NSBundle mainBundle ] objectForInfoDictionaryKey: @"CFBundleHelpBookName" ];
[ [ NSHelpManager sharedHelpManager ] openHelpAnchor: anchor inBook: book ];
return YES;
}
}
@end