forked from sbooth/Tag
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTagEditor.m
More file actions
1279 lines (1061 loc) · 40.9 KB
/
Copy pathTagEditor.m
File metadata and controls
1279 lines (1061 loc) · 40.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
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
/*
* $Id$
*
* Copyright (C) 2005, 2006 Stephen F. Booth <me@sbooth.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#import "TagEditor.h"
#import "KeyValueTaggedFile.h"
#import "Genres.h"
#import "AddTagSheet.h"
#import "GuessTagsSheet.h"
#import "RenameFilesSheet.h"
#import "FileSelectionSheet.h"
#import "UKKQueue.h"
static TagEditor *sharedEditor = nil;
@interface TagEditor (Private)
- (BOOL) addOneFile:(NSString *)filename atIndex:(unsigned)index;
- (void) alertDidEnd:(NSAlert *)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo;
- (void) tagsChanged;
- (void) undoManagerNotification:(NSNotification *)aNotification;
- (void) openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo;
@end
@implementation TagEditor
+ (void) initialize
{
NSArray *defaultValues;
NSArray *defaultKeys;
NSArray *predefinedPatterns;
predefinedPatterns = [NSArray arrayWithObjects:
@"{artist} - {title}",
@"{artist}/{album}/{trackNumber} {title}",
@"Compilations/{album}/{discNumber}-{trackNumber} {title}",
nil];
defaultValues = [NSArray arrayWithObjects:predefinedPatterns, predefinedPatterns, nil];
defaultKeys = [NSArray arrayWithObjects:@"guessTagsPatterns", @"renameFilesPatterns", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjects:defaultValues forKeys:defaultKeys]];
}
+ (TagEditor *) sharedEditor
{
@synchronized(self) {
if(nil == sharedEditor) {
sharedEditor = [[self alloc] init];
}
}
return sharedEditor;
}
+ (id) allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if(nil == sharedEditor) {
return [super allocWithZone:zone];
}
}
return sharedEditor;
}
- (id) init
{
if((self = [super initWithWindowNibName:@"TagEditor"])) {
_validKeys = [[NSArray arrayWithObjects:@"title", @"artist", @"album", @"year", @"genre", @"composer", @"MCN", @"ISRC", @"encoder", @"comment", @"trackNumber", @"trackTotal", @"discNumber", @"discTotal", @"compilation", @"custom", nil] retain];
_files = [[NSMutableArray arrayWithCapacity:20] retain];
[[UKKQueue sharedFileWatcher] setDelegate:self];
return self;
}
return nil;
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSUndoManagerDidUndoChangeNotification object:[self undoManager]];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSUndoManagerDidRedoChangeNotification object:[self undoManager]];
[_validKeys release];
[_files release];
[super dealloc];
}
- (id) copyWithZone:(NSZone *)zone { return self; }
- (id) retain { return self; }
- (unsigned) retainCount { return UINT_MAX; /* denotes an object that cannot be released */ }
- (void) release { /* do nothing */ }
- (id) autorelease { return self; }
- (NSArray *) genres { return [Genres sharedGenres]; }
- (NSWindow *) windowForSheet { return [self window]; }
- (IBAction) toggleFilesDrawer:(id)sender { [_filesDrawer toggle:sender]; }
- (IBAction) openFilesDrawer:(id)sender { [_filesDrawer open:sender]; }
- (IBAction) closeFilesDrawer:(id)sender { [_filesDrawer close:sender]; }
- (unsigned) countOfFiles { return [_files count]; }
- (unsigned) countOfSelectedFiles { return [[_filesController selectedObjects] count]; }
- (KeyValueTaggedFile *) objectInFilesAtIndex:(unsigned)idx { return [_files objectAtIndex:idx]; }
- (IBAction) selectNextFile:(id)sender { [_filesController selectNext:sender]; }
- (IBAction) selectPreviousFile:(id)sender { [_filesController selectPrevious:sender]; }
- (IBAction) selectAllFiles:(id)sender { [_filesController setSelectionIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self countOfFiles])]]; }
- (IBAction) selectBasicTab:(id)sender { [_tabView selectTabViewItemAtIndex:kBasicTabViewItemIndex]; }
- (IBAction) selectAdvancedTab:(id)sender { [_tabView selectTabViewItemAtIndex:kAdvancedTabViewItemIndex]; }
- (IBAction) selectTabularTab:(id)sender { [_tabView selectTabViewItemAtIndex:kTabularTabViewItemIndex]; }
- (NSUndoManager *) undoManager { return [[self window] undoManager]; }
- (void) undoManagerNotification:(NSNotification *)aNotification
{
NSString *name = [aNotification name];
if([name isEqualToString:NSUndoManagerDidUndoChangeNotification]) {
[self tagsChanged];
}
else if([name isEqualToString:NSUndoManagerDidRedoChangeNotification]) {
[self tagsChanged];
}
}
- (BOOL) applicationShouldTerminate
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSAlert *alert;
int result;
if(0 == [self countOfFiles] || NO == [self dirty]) {
return YES;
}
else {
enumerator = [[_filesController arrangedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if(YES == [current dirty]) {
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Cancel", @"General", @"")];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Don't Save", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Do you want to save the changes you made in the document \"%@\"?", @"General", @""), [current displayName]]];
[alert setInformativeText:NSLocalizedStringFromTable(@"Your changes will be lost if you don't save them.", @"General", @"")];
[alert setAlertStyle:NSInformationalAlertStyle];
result = [alert runModal];
switch(result) {
case NSAlertFirstButtonReturn: [current save]; break;
case NSAlertSecondButtonReturn: return NO; break;
case NSAlertThirdButtonReturn: ; break;
}
}
}
return YES;
}
}
- (void) awakeFromNib
{
[_tagsTable setAutosaveTableColumns:YES];
[_tabularTagsTable setAutosaveTableColumns:YES];
[_sortFilesPopUpButton selectItemWithTag:kSortByFilenameMenuItemTag];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerNotification:) name:NSUndoManagerDidUndoChangeNotification object:[self undoManager]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerNotification:) name:NSUndoManagerDidRedoChangeNotification object:[self undoManager]];
[_tagsController setSortDescriptors:[NSArray arrayWithObjects:
[[[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES] autorelease],
[[[NSSortDescriptor alloc] initWithKey:@"value" ascending:YES] autorelease],
nil]];
[_filesController setSortDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"filename" ascending:YES] autorelease]]];
[_selectedFilesController setSortDescriptors:[NSArray arrayWithObjects:
[[[NSSortDescriptor alloc] initWithKey:@"artist" ascending:YES] autorelease],
[[[NSSortDescriptor alloc] initWithKey:@"album" ascending:YES] autorelease],
[[[NSSortDescriptor alloc] initWithKey:@"trackNumber" ascending:YES] autorelease],
nil]];
}
- (void) windowDidLoad
{
[self setShouldCascadeWindows:NO];
[self setWindowFrameAutosaveName:@"Editor"];
[[self window] setExcludedFromWindowsMenu:YES];
}
- (BOOL) dirty
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
enumerator = [[_filesController arrangedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if([current dirty]) {
return YES;
}
}
return NO;
}
- (BOOL) selectionDirty
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if([current dirty]) {
return YES;
}
}
return NO;
}
- (void) openFilesDrawerIfNeeded
{
if(1 < [self countOfFiles]) {
[_filesController rearrangeObjects];
[self openFilesDrawer:self];
}
}
#pragma mark File Manipulation
- (IBAction) sortFiles:(id)sender
{
NSArray *sortDescriptors;
NSString *sortKey;
BOOL ascending;
sortDescriptors = [_filesController sortDescriptors];
sortKey = (0 < [sortDescriptors count] ? [[sortDescriptors objectAtIndex:0] key] : @"filename");
ascending = (0 < [sortDescriptors count] ? [[sortDescriptors objectAtIndex:0] ascending] : YES);
if([sender isKindOfClass:[NSPopUpButton class]]) {
switch([[(NSPopUpButton *)sender selectedItem] tag]) {
case kSortByFilenameMenuItemTag: sortKey = @"filename"; break;
case kSortByTitleMenuItemTag: sortKey = @"title"; break;
case kSortByArtistMenuItemTag: sortKey = @"artist"; break;
case kSortByAlbumMenuItemTag: sortKey = @"album"; break;
case kSortByYearMenuItemTag: sortKey = @"year"; break;
case kSortByGenreMenuItemTag: sortKey = @"genre"; break;
case kSortByComposerMenuItemTag: sortKey = @"composer"; break;
case kSortByTrackNumberMenuItemTag: sortKey = @"trackNumber"; break;
case kSortByDiscNumberMenuItemTag: sortKey = @"discNumber"; break;
default: sortKey = @"filename"; break;
}
}
else if([sender isKindOfClass:[NSButton class]]) {
ascending = (NSOnState == [(NSButton *)sender state]);
}
[_filesController setSortDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending] autorelease]]];
}
- (IBAction) openDocument:(id)sender
{
BOOL success = YES;
NSOpenPanel *panel = [NSOpenPanel openPanel];
NSArray *allowedTypes = [NSArray arrayWithObjects:@"flac", @"ogg", @"ape", @"wv", nil];
NSEnumerator *enumerator;
NSString *filename;
NSMutableArray *newFiles;
KeyValueTaggedFile *file;
int returnCode;
[panel setAllowsMultipleSelection:YES];
[panel setCanChooseDirectories:YES];
returnCode = [panel runModalForTypes:allowedTypes];
if(NSOKButton == returnCode) {
newFiles = [NSMutableArray arrayWithCapacity:10];
enumerator = [[panel filenames] objectEnumerator];
while((filename = [enumerator nextObject])) {
success &= [self addFile:filename];
if(success) {
file = [_filesController findFile:filename];
if(nil != file) {
[newFiles addObject:file];
}
}
}
if(1 < [[panel filenames] count] && success) {
[_filesController setSelectedObjects:newFiles];
}
[self openFilesDrawerIfNeeded];
}
}
- (IBAction) performClose:(id)sender
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSString *key;
[self willChangeValueForKey:@"tags"];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if(YES == [current dirty]) {
NSAlert *alert;
int result;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Cancel", @"General", @"")];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Don't Save", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Do you want to save the changes you made in the document \"%@\"?", @"General", @""), [current displayName]]];
[alert setInformativeText:NSLocalizedStringFromTable(@"Your changes will be lost if you don't save them.", @"General", @"")];
[alert setAlertStyle:NSInformationalAlertStyle];
result = [alert runModal];
switch(result) {
case NSAlertFirstButtonReturn: [current save]; break;
case NSAlertSecondButtonReturn: continue; break;
case NSAlertThirdButtonReturn: ; break;
}
}
[_filesController removeObject:current];
[[UKKQueue sharedFileWatcher] removePath:[current filename]];
}
[self didChangeValueForKey:@"tags"];
enumerator = [_validKeys objectEnumerator];
while((key = [enumerator nextObject])) {
[self willChangeValueForKey:key];
[self didChangeValueForKey:key];
}
if(1 >= [self countOfFiles]) {
[self closeFilesDrawer:self];
}
}
- (IBAction) saveDocument:(id)sender
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if([current dirty]) {
@try {
[[UKKQueue sharedFileWatcher] removePath:[current filename]];
[current save];
[[UKKQueue sharedFileWatcher] addPath:[current filename]];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"An error occurred while saving the document \"%@\".", @"Errors", @""), [current displayName]]];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}
}
}
}
- (IBAction) revertDocumentToSaved:(id)sender
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSString *key;
[self willChangeValueForKey:@"tags"];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
if(YES == [current dirty]) {
NSAlert *alert;
int result;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Revert", @"General", @"")];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"Cancel", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Do you want to revert to the most recently saved revision of the document \"%@\"?", @"General", @""), [current displayName]]];
[alert setInformativeText:NSLocalizedStringFromTable(@"Your changes will be lost if you don't save them.", @"General", @"")];
[alert setAlertStyle:NSInformationalAlertStyle];
result = [alert runModal];
switch(result) {
case NSAlertFirstButtonReturn:
@try {
[[UKKQueue sharedFileWatcher] removePath:[current filename]];
[current revert];
[[UKKQueue sharedFileWatcher] addPath:[current filename]];
}
@catch(NSException *exception) {
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"An error occurred while reverting the document \"%@\".", @"Errors", @""), [current displayName]]];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}
break;
case NSAlertSecondButtonReturn: continue; break;
}
}
}
[self didChangeValueForKey:@"tags"];
enumerator = [_validKeys objectEnumerator];
while((key = [enumerator nextObject])) {
[self willChangeValueForKey:key];
[self didChangeValueForKey:key];
}
}
- (BOOL) addFile:(NSString *)filename
{
return [self addFile:filename atIndex:/*[[_filesController arrangedObjects] count]*/NSNotFound];
}
- (BOOL) addFile:(NSString *)filename atIndex:(unsigned)index
{
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *allowedTypes = [NSArray arrayWithObjects:@"flac", @"ogg", @"ape", @"wv", nil];
NSMutableArray *newFiles;
KeyValueTaggedFile *file;
NSArray *subpaths;
BOOL isDir;
NSEnumerator *enumerator;
NSString *subpath;
NSString *composedPath;
BOOL success = YES;
if([manager fileExistsAtPath:filename isDirectory:&isDir]) {
newFiles = [NSMutableArray arrayWithCapacity:10];
if(isDir) {
subpaths = [manager subpathsAtPath:filename];
enumerator = [subpaths objectEnumerator];
while((subpath = [enumerator nextObject])) {
composedPath = [NSString stringWithFormat:@"%@/%@", filename, subpath];
// Ignore dotfiles
if([[subpath lastPathComponent] hasPrefix:@"."]) {
continue;
}
// Ignore files that don't have our extensions
else if(NO == [allowedTypes containsObject:[subpath pathExtension]]) {
continue;
}
// Ignore directories
if([manager fileExistsAtPath:composedPath isDirectory:&isDir] && NO == isDir) {
success &= [self addOneFile:composedPath atIndex:(unsigned)index];
}
if(success) {
file = [_filesController findFile:composedPath];
if(nil != file) {
[newFiles addObject:file];
}
}
}
if(success) {
[_filesController setSelectedObjects:newFiles];
}
}
else {
success &= [self addOneFile:filename atIndex:(unsigned)index];
if(success) {
[_filesController selectFile:filename];
}
}
}
else {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"An error occurred while opening the document \"%@\".", @"Errors", @""), [filename lastPathComponent]]];
[alert setInformativeText:NSLocalizedStringFromTable(@"The file was not found.", @"Errors", @"")];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
success = NO;
}
return success;
}
- (BOOL) addOneFile:(NSString *)filename atIndex:(unsigned)index
{
BOOL success = YES;
@try {
if([_filesController containsFile:filename]) {
return YES;
}
if(NSNotFound == index) {
[_filesController addObject:[KeyValueTaggedFile parseFile:filename]];
}
else {
[_filesController insertObject:[KeyValueTaggedFile parseFile:filename] atArrangedObjectIndex:index];
}
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:filename]];
[[UKKQueue sharedFileWatcher] addPath:filename];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedStringFromTable(@"An error occurred while opening the document \"%@\".", @"Errors", @""), [filename lastPathComponent]]];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
success = NO;
}
return success;
}
#pragma mark Tag Manipulation
- (void) tagsChanged
{
[self willChangeValueForKey:@"tags"];
[self didChangeValueForKey:@"tags"];
}
- (IBAction) newTag:(id)sender
{
AddTagSheet *sheet;
@try {
sheet = [[AddTagSheet alloc] init];
[sheet setDelegate:self];
[sheet showSheet];
// TODO: How do I avoid a memory leak here? For some reason sheet is being autoreleased while it is being displayed
//[sheet autorelease];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:NSLocalizedStringFromTable(@"Your Tag installation appears to be incomplete.", @"Errors", @"")];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}
}
- (IBAction) addTagsFromFile:(id)sender
{
NSOpenPanel *panel = [NSOpenPanel openPanel];
NSArray *allowedTypes = [NSArray arrayWithObjects:@"flac", @"ogg", @"ape", @"wv", nil];
[panel setAllowsMultipleSelection:YES];
[panel setCanChooseDirectories:YES];
[panel beginSheetForDirectory:nil file:nil types:allowedTypes modalForWindow:[self window] modalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
}
- (void) openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
NSEnumerator *enumerator;
NSString *filename;
KeyValueTaggedFile *file;
unsigned i;
NSDictionary *tag;
if(NSOKButton == returnCode) {
enumerator = [[panel filenames] objectEnumerator];
while((filename = [enumerator nextObject])) {
file = [KeyValueTaggedFile parseFile:filename];
if(nil != file) {
for(i = 0; i < [file countOfTags]; ++i) {
tag = [file objectInTagsAtIndex:i];
[self addValue:[tag objectForKey:@"value"] forTag:[tag objectForKey:@"key"]];
}
}
}
}
}
- (IBAction) renameFiles:(id)sender
{
RenameFilesSheet *sheet;
@try {
sheet = [[RenameFilesSheet alloc] init];
[sheet setDelegate:self];
[sheet showSheet];
// TODO: How do I avoid a memory leak here? For some reason sheet is being autoreleased while it is being displayed
//[sheet autorelease];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:NSLocalizedStringFromTable(@"Your Tag installation appears to be incomplete.", @"Errors", @"")];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}}
- (IBAction) delete:(id)sender { [self deleteTag:sender]; }
- (IBAction) deleteTag:(id)sender
{
NSEnumerator *enumerator;
NSArray *selectedTags;
unsigned i;
KeyValueTaggedFile *current;
NSDictionary *tag;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
selectedTags = [_tagsController selectedObjects];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
for(i = 0; i < [selectedTags count]; ++i) {
tag = [selectedTags objectAtIndex:i];
[current updateTag:[tag valueForKey:@"key"] withValue:[tag valueForKey:@"value"] toValue:nil];
}
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (IBAction) guessTags:(id)sender
{
GuessTagsSheet *sheet;
@try {
sheet = [[GuessTagsSheet alloc] init];
[sheet setDelegate:self];
[sheet showSheet];
// TODO: How do I avoid a memory leak here? For some reason sheet is being autoreleased while it is being displayed
//[sheet autorelease];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:NSLocalizedStringFromTable(@"Your Tag installation appears to be incomplete.", @"Errors", @"")];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}
}
- (IBAction) copySelectedTags:(id)sender
{
FileSelectionSheet *sheet = nil;
NSMutableArray *files = nil;
NSArray *selectedFiles = nil;
KeyValueTaggedFile *file = nil;
unsigned i;
@try {
files = [NSMutableArray array];
selectedFiles = [_filesController selectedObjects];
for(i = 0; i < [self countOfFiles]; ++i) {
file = [self objectInFilesAtIndex:i];
if(NO == [selectedFiles containsObject:file]) {
[files addObject:file];
}
}
sheet = [[FileSelectionSheet alloc] init];
[sheet setDelegate:self];
[sheet setValue:files forKey:@"files"];
[sheet showSheet];
// TODO: How do I avoid a memory leak here? For some reason sheet is being autoreleased while it is being displayed
//[sheet autorelease];
}
@catch(NSException *exception) {
NSAlert *alert;
alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:NSLocalizedStringFromTable(@"OK", @"General", @"")];
[alert setMessageText:NSLocalizedStringFromTable(@"Your Tag installation appears to be incomplete.", @"Errors", @"")];
[alert setInformativeText:[exception reason]];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert runModal];
}
}
- (void) setValue:(NSString *)value forTag:(NSString *)tag
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
[current setValue:value forTag:tag];
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (void) addValue:(NSString *)value forTag:(NSString *)tag
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
[current addValue:value forTag:tag];
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (void) updateTag:(NSString *)tag withValue:(NSString *)currentValue toValue:(NSString *)newValue
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
[current updateTag:tag withValue:currentValue toValue:newValue];
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (void) renameTag:(NSString *)currentTag withValue:(NSString *)currentValue toTag:(NSString *)newTag
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
[current renameTag:currentTag withValue:currentValue toTag:newTag];
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (void) guessTagsUsingPattern:(NSString *)pattern
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSUndoManager *undoManager = [self undoManager];
[self willChangeValueForKey:@"tags"];
[undoManager beginUndoGrouping];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
[current guessTagsUsingPattern:pattern];
}
[undoManager endUndoGrouping];
[self didChangeValueForKey:@"tags"];
}
- (void) renameFilesUsingPattern:(NSString *)pattern
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
NSString *key;
[self willChangeValueForKey:@"tags"];
enumerator = [[_filesController selectedObjects] objectEnumerator];
while((current = [enumerator nextObject])) {
// Remove the file from our list of open files
[_filesController removeObject:current];
[[UKKQueue sharedFileWatcher] removePath:[current filename]];
// Rename the file
[current renameFileUsingPattern:pattern];
// Add it back to our list of open files
[_filesController addObject:current];
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:[current filename]]];
[[UKKQueue sharedFileWatcher] addPath:[current filename]];
}
[self didChangeValueForKey:@"tags"];
enumerator = [_validKeys objectEnumerator];
while((key = [enumerator nextObject])) {
[self willChangeValueForKey:key];
[self didChangeValueForKey:key];
}
}
- (void) copySelectedTagsToFiles:(NSArray *)files
{
NSArray *selectedTags = [_tagsController selectedObjects];
NSUndoManager *undoManager = [self undoManager];
KeyValueTaggedFile *file = nil;
NSDictionary *tag = nil;
unsigned i, j;
[undoManager beginUndoGrouping];
for(i = 0; i < [files count]; ++i) {
file = [files objectAtIndex:i];
if([_files containsObject:file]) {
for(j = 0; j < [selectedTags count]; ++j) {
tag = [selectedTags objectAtIndex:j];
[file addValue:[tag objectForKey:@"value"] forTag:[tag objectForKey:@"key"]];
}
}
}
[undoManager endUndoGrouping];
}
- (void) cutSelectedTagsToPasteboard
{
[self copySelectedTagsToPasteboard];
[self deleteTag:self];
}
- (void) copySelectedTagsToPasteboard
{
NSPasteboard *pboard = [NSPasteboard generalPasteboard];
[pboard declareTypes:[NSArray arrayWithObject:@"org.sbooth.Tag.TagItem"] owner:self];
[pboard setPropertyList:[_tagsController selectedObjects] forType:@"org.sbooth.Tag.TagItem"];
}
- (void) pasteTagsFromPasteboard
{
NSUndoManager *undoManager = [self undoManager];
NSPasteboard *pboard = [NSPasteboard generalPasteboard];
NSArray *tags = [pboard propertyListForType:@"org.sbooth.Tag.TagItem"];
NSDictionary *tag = nil;
unsigned i = 0;
[undoManager beginUndoGrouping];
for(i = 0; i < [tags count]; ++i) {
tag = [tags objectAtIndex:i];
[self addValue:[tag objectForKey:@"value"] forTag:[tag objectForKey:@"key"]];
}
[undoManager endUndoGrouping];
}
- (void) tableViewSelectionDidChange:(NSNotification *)aNotification
{
NSEnumerator *enumerator;
NSString *key;
NSArray *selectedObjects;
// Update window title with filename if only one file is being edited
selectedObjects = [_filesController selectedObjects];
[[self window] setTitle:(1 == [selectedObjects count] ? [[selectedObjects objectAtIndex:0] displayName] : @"Tag")];
[self tagsChanged];
enumerator = [_validKeys objectEnumerator];
while((key = [enumerator nextObject])) {
[self willChangeValueForKey:key];
[self didChangeValueForKey:key];
}
}
- (id) valueForKey:(NSString *)key
{
NSEnumerator *enumerator;
KeyValueTaggedFile *current;
if([_validKeys containsObject:key]) {
NSArray *reverseMappedKeys;
NSString *currentValue;
NSString *lastValue;
NSColor *markerColor;
BOOL firstTime;
enumerator = [[_filesController selectedObjects] objectEnumerator];
currentValue = nil;
lastValue = nil;
firstTime = YES;
while((current = [enumerator nextObject])) {
reverseMappedKeys = [[current tagMapping] allKeysForObject:key];
if(0 < [reverseMappedKeys count]) {
currentValue = [current valueForTag:[reverseMappedKeys objectAtIndex:0]];
if(NO == firstTime && ((nil != currentValue || nil != lastValue) && NO == [currentValue isEqualToString:lastValue])) {
// Special case for non-text field
if([key isEqualToString:@"compilation"]) {
return [NSNumber numberWithInt:NSMixedState];
}
return NSMultipleValuesMarker;
}
lastValue = currentValue;
firstTime = NO;
}
}
return lastValue;
}
else if([key isEqualToString:@"tags"]) {
NSEnumerator *tagEnumerator;
NSDictionary *currentTag;
NSArray *currentValue;
NSArray *lastValue;
NSMutableArray *result;
BOOL firstTime;
enumerator = [[_filesController selectedObjects] objectEnumerator];
currentValue = nil;
lastValue = nil;
result = nil;
firstTime = YES;
while((current = [enumerator nextObject])) {
currentValue = [current valueForKey:@"tags"];
if(firstTime) {
// Make a deep copy so the actual file's tags are not modified
result = [[NSMutableArray alloc] initWithCapacity:[currentValue count]];
tagEnumerator = [currentValue objectEnumerator];
while((currentTag = [tagEnumerator nextObject])) {
[result addObject:[[currentTag mutableCopy] autorelease]];
}
}
if(NO == firstTime && NO == [currentValue isEqual:lastValue]) {
// Winnow the result to contain only tags that match in every file
tagEnumerator = [result objectEnumerator];
while((currentTag = [tagEnumerator nextObject])) {
if(NO == [currentValue containsObject:currentTag]) {
[result removeObject:currentTag];
}
}
}
lastValue = currentValue;
firstTime = NO;
}