forked from gonzoua/AudioBookBinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AudioFileList.m
786 lines (667 loc) · 22.4 KB
/
AudioFileList.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
//
// AudioFileList.m
// AudioBookBinder
//
// Created by Oleksandr Tymoshenko on 10-02-05.
// Copyright 2010 Bluezbox Software. All rights reserved.
//
#import "AudioFileList.h"
#import "AudioFile.h"
#include "NSOutlineView_Extension.h"
#import "Chapter.h"
#import "AudioBookBinderAppDelegate.h"
// It is best to #define strings to avoid making typing errors
#define SIMPLE_BPOARD_TYPE @"MyCustomOutlineViewPboardType"
#define TEXT_CHAPTER \
NSLocalizedString(@"Chapter", nil)
#define TEXT_CHAPTER_N \
NSLocalizedString(@"Chapter %d", nil)
@implementation AudioFileList
- (id) init
{
if ((self = [super init]))
{
_files = [[[NSMutableArray alloc] init] retain];
_chapters = [[[NSMutableArray alloc] init] retain];
_topDir = nil;
_chapterMode = YES;
id modeObj = [[NSUserDefaults standardUserDefaults] objectForKey:@"ChaptersEnabled"];
if (modeObj != nil)
_chapterMode = [modeObj boolValue];
_canPlay = NO;
_sortAscending = YES;
_sortKey = nil;
}
return self;
}
- (void) dealloc
{
[_files release];
[_topDir release];
[_chapters release];
[super dealloc];
}
@synthesize chapterMode = _chapterMode;
- (void) addFile:(NSString*)fileName
{
AudioFile *file = [[AudioFile alloc] initWithPath:fileName];
[self willChangeValueForKey:@"hasFiles"];
if (file.valid) {
[_files addObject:file];
if (_chapterMode) {
Chapter *chapter = [[Chapter alloc] init];
chapter.name = file.name;
[_chapters addObject:chapter];
[chapter addFile:file];
}
}
else
[file release];
[self didChangeValueForKey:@"hasFiles"];
}
- (NSArray*) chapters
{
NSArray *result;
result = [[NSArray arrayWithArray:_chapters] retain];
return result;
}
- (NSArray*) files
{
NSMutableArray *result;
if (_chapterMode) {
result = [[NSMutableArray alloc] init];
for (Chapter *ch in _chapters)
[result addObjectsFromArray:[ch files]];
}
else {
result = [[NSArray arrayWithArray:_files] retain];
}
return result;
}
- (BOOL) hasFiles
{
if ([_files count] > 0)
return YES;
return NO;
}
- (void) addFilesInDirectory:(NSString*)dirName
{
NSString *currentFile;
NSMutableArray *files = [[NSMutableArray alloc] init];
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:dirName];
while ((currentFile = [dirEnum nextObject]))
{
[files addObject:currentFile];
}
// Should be OK for most cases
NSArray *orderedFiles = [files sortedArrayUsingComparator:^(id a, id b) {return [a compare:b];}];
for (currentFile in orderedFiles) {
NSString *currentPath = [dirName stringByAppendingPathComponent:currentFile];
[self addFile:currentPath];
}
}
- (void) switchChapterMode
{
// this function is called before _chapterMode is changed by binding
if (!_chapterMode) {
if ([_files count]) {
// put all files in one folder
Chapter *newChapter = [[Chapter alloc] init];
newChapter.name = TEXT_CHAPTER;
[_chapters removeAllObjects];
for (AudioFile *file in _files) {
[newChapter addFile:file];
}
[_chapters addObject:newChapter];
}
// change explicitely because we need to update outlineView in new mode
_chapterMode = YES;
} else
{
// flatten chapter tree
[_files removeAllObjects];
for (Chapter *ch in _chapters) {
for (AudioFile *f in [ch files])
[_files addObject:f];
}
// change explicitely because we need to update outlineView in new mode
_chapterMode = NO;
}
[[NSUserDefaults standardUserDefaults] setBool:_chapterMode forKey:@"ChaptersEnabled"];
}
- (void) renumberChapters
{
if (_chapterMode) {
int idx = 1;
for (Chapter *ch in _chapters) {
ch.name = [NSString stringWithFormat:TEXT_CHAPTER_N, idx];
idx++;
}
}
}
// The NSOutlineView uses 'nil' to indicate the root item. We return our root tree node for that case.
- (NSArray *)childrenForItem:(id)item {
if (item == nil) {
if (_chapterMode)
return _chapters;
else
return _files;
}
else {
if ([item isKindOfClass:[Chapter class]]) {
return [(Chapter*)item files];
}
}
return nil;
}
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
if (item == nil) {
if (_chapterMode)
return [_chapters count];
else
return [_files count];
}
else {
if ([item isKindOfClass:[Chapter class]])
return [item totalFiles];
}
return 0;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
if ([item isKindOfClass:[Chapter class]])
return YES;
else
return NO;
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
{
if (item == nil) {
if (_chapterMode)
return [_chapters objectAtIndex:index];
else
return [_files objectAtIndex:index];
}
if ([item isKindOfClass:[Chapter class]])
return [item fileAtIndex:index];
return nil;
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
id objectValue = nil;
if (item == nil)
return nil;
if ([item isKindOfClass:[AudioFile class]])
{
AudioFile *file = item;
if ([tableColumn.identifier isEqualToString:COLUMNID_FILE])
objectValue = file.file;
else if ([tableColumn.identifier isEqualToString:COLUMNID_NAME])
objectValue = file.name;
else if ([tableColumn.identifier isEqualToString:COLUMNID_AUTHOR])
objectValue = file.artist;
else if ([tableColumn.identifier isEqualToString:COLUMNID_ALBUM])
objectValue = file.album;
else if ([tableColumn.identifier isEqualToString:COLUMNID_TIME])
{
UInt32 duration = [file.duration intValue];
duration /= 1000;
int hours = duration / 3600;
int minutes = (duration - (hours * 3600)) / 60;
int seconds = duration % 60;
if (hours > 0)
objectValue = [[NSString stringWithFormat:@"%d:%02d:%02d",
hours, minutes, seconds] retain];
else
objectValue = [[NSString stringWithFormat:@"%d:%02d",
minutes, seconds] retain];
}
else
objectValue = @"";
return objectValue;
}
else {
Chapter *chapter = item;
if ([tableColumn.identifier isEqualToString:COLUMNID_NAME])
return [chapter name];
else if ([tableColumn.identifier isEqualToString:COLUMNID_TIME])
{
UInt32 duration = [chapter totalDuration];
duration /= 1000;
int hours = duration / 3600;
int minutes = (duration - (hours * 3600)) / 60;
int seconds = duration % 60;
if (hours > 0)
objectValue = [[NSString stringWithFormat:@"%d:%02d:%02d",
hours, minutes, seconds] retain];
else
objectValue = [[NSString stringWithFormat:@"%d:%02d",
minutes, seconds] retain];
return objectValue;
}
else
return @"";
}
return nil;
}
// We can return a different cell for each row, if we want
- (NSCell *)outlineView:(NSOutlineView *)outlineView
dataCellForTableColumn:(NSTableColumn *)tableColumn
item:(id)item
{
// If we return a cell for the 'nil' tableColumn, it will be used
// as a "full width" cell and span all the columns
return [tableColumn dataCell];
}
//
// optional methods for content editing
//
- (BOOL) outlineView:(NSOutlineView *)outlineView
shouldEditTableColumn:(NSTableColumn *)tableColumn
item:(id)item {
if ([item isKindOfClass:[Chapter class]])
if ([tableColumn.identifier isEqualToString:COLUMNID_NAME])
return YES;
// [outline editColumn:0 row:[outline selectedRow] withEvent:[NSApp currentEvent] select:YES];
return NO;
}
- (void)outlineView:(NSOutlineView *)outlineView
setObjectValue:(id)object
forTableColumn:(NSTableColumn *)tableColumn
byItem:(id)item
{
Chapter *chapter = item;
if ([item isKindOfClass:[Chapter class]])
if ([tableColumn.identifier isEqualToString:COLUMNID_NAME])
chapter.name = object;
}
// To get the "group row" look, we implement this method.
- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item
{
return ([item isKindOfClass:[Chapter class]]);
}
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
{
return ([item isKindOfClass:[Chapter class]]);
}
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item
{
return YES;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView
writeItems:(NSArray *)items
toPasteboard:(NSPasteboard *)pboard
{
// we have stale _draggedNodes, release them
if (_draggedNodes) {
[_draggedNodes release];
_draggedNodes = nil;
}
_draggedNodes = [items copy];
// Provide data for our custom type, and simple NSStrings.
[pboard declareTypes:[NSArray arrayWithObjects:SIMPLE_BPOARD_TYPE, NSStringPboardType, NSFilesPromisePboardType, nil]
owner:self];
// the actual data doesn't matter since SIMPLE_BPOARD_TYPE drags aren't recognized by anyone but us!.
[pboard setData:[NSData data] forType:SIMPLE_BPOARD_TYPE];
// Put string data on the pboard... notice you can drag into TextEdit!
[pboard setString:[_draggedNodes description] forType:NSStringPboardType];
// Put the promised type we handle on the pasteboard.
[pboard setPropertyList:[NSArray arrayWithObjects:@"txt", nil] forType:NSFilesPromisePboardType];
return YES;
}
- (NSDragOperation) outlineView:(NSOutlineView *)outlineView
validateDrop:(id <NSDraggingInfo>)info
proposedItem:(id)item
proposedChildIndex:(NSInteger)childIndex
{
NSDragOperation result = NSDragOperationGeneric;
//
// check if we drop 'on' or 'between' something
//
if (childIndex == NSOutlineViewDropOnItemIndex)
result = NSDragOperationNone;
if ([info draggingSource] == outlineView) {
if (_chapterMode) {
BOOL draggingChapters = YES;
for (id audioItem in _draggedNodes) {
if ([audioItem isKindOfClass:[AudioFile class]]) {
draggingChapters = NO;
break;
}
}
// only chapters could be dropped on root item
if ((item == nil) && !draggingChapters)
result = NSDragOperationNone;
else {
// prevent chapter from being dropped on itself
for (id audioItem in _draggedNodes) {
if (audioItem == item) {
result = NSDragOperationNone;
break;
}
}
}
}
}
else
{
// we have stale _draggedNodes, release them
if (_draggedNodes) {
[_draggedNodes release];
_draggedNodes = nil;
}
}
return result;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView
acceptDrop:(id <NSDraggingInfo>)info
item:(id)item childIndex:(NSInteger)childIndex
{
NSMutableArray *newSelectedItems = [NSMutableArray array];
if ([info draggingSource] == outlineView)
{
if (_chapterMode) {
Chapter *dropChapter = item;
if (dropChapter != nil) {
for (id audioItem in _draggedNodes) {
if ([audioItem isKindOfClass:[Chapter class]]) {
for (AudioFile *file in [audioItem files]) {
[dropChapter insertFile:file atIndex:childIndex];
childIndex++;
}
[_chapters removeObject:audioItem];
}
else {
[self orphanFile:audioItem];
[dropChapter insertFile:audioItem atIndex:childIndex];
childIndex++;
}
}
}
else {
// reorder chapters, validateDrop will ensure there are
// only Chapter nodes are dropped
for (Chapter *ch in _draggedNodes) {
[_chapters removeObject:ch];
[_chapters insertObject:ch atIndex:childIndex];
childIndex++;
}
}
[self cleanupChapters];
}
else {
// Go ahead and move things.
for (AudioFile *file in _draggedNodes) {
// Remove the node from its old location
NSInteger oldIndex = [_files indexOfObject:file];
NSInteger newIndex = childIndex;
if (oldIndex != NSNotFound) {
[_files removeObjectAtIndex:oldIndex];
if (childIndex > oldIndex) {
newIndex--; // account for the remove
}
}
[_files insertObject:file atIndex:newIndex];
newIndex++;
[newSelectedItems addObject:file];
}
}
if (_draggedNodes) {
[_draggedNodes release];
_draggedNodes = nil;
}
}
else {
// drop from external source
NSPasteboard *paste = [info draggingPasteboard]; //gets the dragging-specific pasteboard from the sender
NSArray *types = [NSArray arrayWithObjects: NSFilenamesPboardType, nil];
//a list of types that we can accept
NSString *desiredType = [paste availableTypeFromArray:types];
NSData *carriedData = [paste dataForType:desiredType];
if (nil == carriedData)
return NSDragOperationNone;
if ([desiredType isEqualToString:NSFilenamesPboardType])
{
BOOL tryGuess = ![self hasFiles];
//we have a list of file names in an NSData object
NSArray *fileArray = [[paste propertyListForType:@"NSFilenamesPboardType"] sortedArrayUsingComparator:^(id a, id b) {return [a compare:b];}];
for (NSString *s in fileArray) {
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:s isDirectory:&isDir])
{
if (isDir)
// add file recursively
[self addFilesInDirectory:s];
else
[self addFile:s];
}
}
if (tryGuess)
{
AudioBookBinderAppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
[appDelegate updateGuiWithGuessedData];
}
}
}
[outlineView reloadData];
// Reselect old items.
[outlineView setSelectedItems:newSelectedItems];
return YES;
}
- (void)delKeyDown:(NSOutlineView *)outlineView
{
[self deleteSelected:outlineView];
}
- (void)enterKeyDown:(NSOutlineView *)outlineView
{
[self joinSelectedFiles:outlineView];
}
- (BOOL)deleteSelected:(NSOutlineView *)outlineView
{
// Go ahead and move things.
[self willChangeValueForKey:@"hasFiles"];
for (id item in [outlineView selectedItems]) {
if ([item isKindOfClass:[Chapter class]]) {
Chapter *ch = item;
[_chapters removeObject:ch];
}
else {
AudioFile *file = item;
// Remove the node from its old location
NSInteger oldIndex = [_files indexOfObject:file];
if (oldIndex != NSNotFound) {
[_files removeObjectAtIndex:oldIndex];
}
for (Chapter *ch in _chapters) {
if ([ch containsFile:file])
[ch removeFile:file];
}
}
}
[self cleanupChapters];
[self didChangeValueForKey:@"hasFiles"];
[outlineView deselectAll:self];
[outlineView reloadData];
return YES;
}
- (BOOL)joinSelectedFiles:(NSOutlineView *)outlineView
{
if (!_chapterMode)
return NO;
if (![[outlineView selectedItems] count])
return NO;
Chapter *newChapter = [[Chapter alloc] init];
Chapter *ch;
id item = [[outlineView selectedItems] objectAtIndex:0];
NSInteger chapterIndex;
if ([item isKindOfClass:[Chapter class]]) {
chapterIndex = [_chapters indexOfObject:item];
ch = (Chapter*)item;
newChapter.name = ch.name;
}
else {
AudioFile *file = item;
newChapter.name = file.name;
for (ch in _chapters) {
if ([ch containsFile:file]) {
break;
}
}
chapterIndex = [_chapters indexOfObject:ch];
}
for (item in [outlineView selectedItems]) {
if ([item isKindOfClass:[Chapter class]]) {
// copy all files
for (AudioFile *f in [item files]) {
if (![newChapter containsFile:f])
[newChapter addFile:f];
}
[_chapters removeObject:item];
}
else {
if (![newChapter containsFile:item]) {
[self orphanFile:item];
[newChapter addFile:item];
}
}
}
[_chapters insertObject:newChapter atIndex:chapterIndex];
[self cleanupChapters];
[outlineView deselectAll:self];
[outlineView reloadData];
[outlineView setSelectedItem:newChapter];
[outlineView expandItem:newChapter];
return YES;
}
- (BOOL)splitSelectedFiles:(NSOutlineView *)outlineView
{
if (!_chapterMode)
return NO;
if (![[outlineView selectedItems] count])
return NO;
NSMutableArray *newChapters = [[NSMutableArray alloc] init];
for (id item in [outlineView selectedItems]) {
if (![item isKindOfClass:[Chapter class]])
continue;
Chapter *ch = item;
int chapterIndex = [_chapters indexOfObject:ch]+1;
for (AudioFile *file in [ch files]) {
Chapter *newChapter = [[Chapter alloc] init];
newChapter.name = file.name;
[newChapter addFile:file];
[_chapters insertObject:newChapter atIndex:chapterIndex];
chapterIndex++;
[newChapters addObject:newChapter];
}
[_chapters removeObject:ch];
}
[self cleanupChapters];
[outlineView deselectAll:self];
[outlineView reloadData];
for (id item in newChapters)
[outlineView expandItem:item];
if ([newChapters count])
[outlineView setSelectedItem:[newChapters objectAtIndex:0]];
[newChapters release];
return YES;
}
- (void) orphanFile:(AudioFile*)file
{
for (Chapter *ch in _chapters) {
if ([ch containsFile:file])
[ch removeFile:file];
}
}
- (void) cleanupChapters
{
int index = 0;
while (index < [_chapters count]) {
Chapter *ch = [_chapters objectAtIndex:index];
if (([ch totalFiles] == 0) && ([_chapters count] > 1))
[_chapters removeObject:ch];
else
index++;
}
}
- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
BOOL canPlay = NO;
NSOutlineView *view = [notification object];
if ([[view selectedItems] count] == 1) {
id item = [[view selectedItems] objectAtIndex:0];
if ([item isKindOfClass:[AudioFile class]])
canPlay = YES;
}
// do not spam AppDelegate
if (_canPlay != canPlay) {
AudioBookBinderAppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
_canPlay = canPlay;
[appDelegate setCanPlay:_canPlay];
}
}
- (void) outlineView:(NSOutlineView *) outlineView
didClickTableColumn:(NSTableColumn *) tableColumn
{
NSArray *columns = [outlineView tableColumns];
if (_sortKey != nil) {
for (NSTableColumn *c in columns) {
[outlineView setIndicatorImage:nil
inTableColumn:c];
}
if ([_sortKey isEqualToString:[tableColumn identifier]])
_sortAscending = !_sortAscending;
else
_sortAscending = YES;
}
_sortKey = [tableColumn identifier];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:_sortKey ascending:_sortAscending];
if (_chapterMode) {
for (Chapter *c in _chapters) {
[c sortUsingDecriptor:sortDescriptor];
}
}
else
[_files sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
[outlineView setIndicatorImage:(_sortAscending ?
[NSImage imageNamed:@"NSAscendingSortIndicator"] :
[NSImage imageNamed:@"NSDescendingSortIndicator"])
inTableColumn:tableColumn];
[outlineView reloadData];
}
- (NSString *)commonAuthor
{
if ([_files count] == 0)
return nil;
NSString *author = [[_files objectAtIndex:0] artist];
for (AudioFile *f in _files) {
if (![author isEqualToString:f.artist])
return nil;
}
return author;
}
- (NSString *)commonAlbum
{
if ([_files count] == 0)
return nil;
NSString *album = [[_files objectAtIndex:0] album];
for (AudioFile *f in _files) {
if (![album isEqualToString:f.album])
return nil;
}
return album;
}
- (void) removeAllFiles:(NSOutlineView*)outlineView;
{
Chapter *newChapter = nil;
[self willChangeValueForKey:@"hasFiles"];
[_files removeAllObjects];
[_chapters removeAllObjects];
[outlineView deselectAll:self];
[outlineView reloadData];
if (_chapterMode)
[outlineView expandItem:newChapter];
[self didChangeValueForKey:@"hasFiles"];
}
@end