-
Notifications
You must be signed in to change notification settings - Fork 48
/
AudioBinderWindowController.m
1171 lines (1005 loc) · 40.4 KB
/
AudioBinderWindowController.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
//
// Copyright (c) 2013-2016 Oleksandr Tymoshenko <[email protected]>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice unmodified, this list of conditions, and the following
// disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
#import "AudioBinder.h"
#import "AudioBookVolume.h"
#import "AudioBookVolume.h"
#import "AudioBinderWindowController.h"
#import "AudioBookBinderAppDelegate.h"
#import "AudioFile.h"
#import "Chapter.h"
#import "Chapter.h"
#import "ConfigNames.h"
#import "ExpandedPathToIconTransformer.h"
#import "ExpandedPathToPathTransformer.h"
#import "MP4File.h"
#import "MetaEditor.h"
#import "NSOutlineView_Extension.h"
#import "StatsManager.h"
#import "QueueController.h"
#import <QuartzCore/QuartzCore.h>
// localized strings
#define TEXT_CONVERSION_FAILED NSLocalizedString(@"Audiofile conversion failed", nil)
#define TEXT_BINDING_FAILED NSLocalizedString(@"Audiobook binding failed", nil)
#define TEXT_ADDING_TAGS NSLocalizedString(@"Adding artist/title tags", nil)
#define TEXT_ADDING_CHAPTERS NSLocalizedString(@"Adding chapter markers", nil)
#define TEXT_CONVERTING NSLocalizedString(@"Converting %@", nil)
#define TEXT_CANT_SPLIT NSLocalizedString(@"Failed to split audiobook into volumes", nil)
#define TEXT_MAXDURATION_VIOLATED NSLocalizedString(@"%s: duration (%d sec) is larger than the maximum volume duration (%lld sec.)", nil)
#define TEXT_FAILED_TO_PLAY NSLocalizedString(@"Failed to play", nil)
#define TEXT_CANT_PLAY NSLocalizedString(@"Failed to play: %@", nil)
#define TEXT_AUDIOBOOK NSLocalizedString(@"Audiobook", nil)
#define TEXT_AUDIOBOOKS NSLocalizedString(@"Audiobooks", nil)
#define TEXT_FILE_EXISTS NSLocalizedString(@"File exists", @"epub file exists")
#define TEXT_FILE_OVERWRITE NSLocalizedString(@"File %@ already exists, replace?", @"epub file exists")
#define TEXT_OVERWRITE NSLocalizedString(@"Replace", @"")
#define TEXT_CANCEL NSLocalizedString(@"Cancel", @"")
#define TEXT_BOOK_IS_READY NSLocalizedString(@"Audiobook is ready", @"")
#define ColumnsConfiguration @"ColumnsConfiguration"
#define KVO_CONTEXT_CANPLAY_CHANGED @"CanPlayChanged"
#define KVO_CONTEXT_HASFILES_CHANGED @"HasFilesChanged"
#define KVO_CONTEXT_COMMONAUTHOR_CHANGED @"CommonAuthorChanged"
#define KVO_CONTEXT_COMMONALBUM_CHANGED @"CommonAlbumChanged"
#ifdef APP_STORE_BUILD
extern BOOL requiresUpdateHack;
#endif
typedef struct
{
__unsafe_unretained NSString *id;
__unsafe_unretained NSString *title;
BOOL enabled;
} column_t;
column_t columnDefs[] = {
{COLUMNID_FILE, @"File", NO},
{COLUMNID_AUTHOR, @"Author", NO},
{COLUMNID_ALBUM, @"Album", NO},
{COLUMNID_TIME, @"Time", NO},
{nil, nil}
};
enum abb_form_fields {
ABBAuthor = 0,
ABBTitle,
};
@interface AudioBinderWindowController () {
NSURL *_destURL;
NSMutableArray *knownGenres;
BOOL autocompleting;
BOOL _playing;
NSString *outFile;
AudioBinder *_binder;
NSSound *_sound;
NSString *_playingFile;
NSImage *_playImg, *_stopImg;
BOOL _conversionResult;
AudioFileList *fileList;
// QueueOverlayView *_queueOverlay;
NSMutableArray *currentColumns;
NSUInteger _currentFileProgress;
NSUInteger _totalBookProgress;
NSUInteger _totalBookDuration;
BOOL _converting;
BOOL _enqueued;
}
- (void)playFailed;
- (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finishedPlaying;
@end
@implementation AudioBinderWindowController
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
[self updateWindowTitle];
}
return self;
}
- (void)dealloc
{
[fileList removeObserver:self forKeyPath:@"hasFiles"];
[fileList removeObserver:self forKeyPath:@"canPlay"];
[fileList removeObserver:self forKeyPath:@"commonAuthor"];
[fileList removeObserver:self forKeyPath:@"commonAlbum"];
}
- (void)windowDidLoad
{
[super windowDidLoad];
fileList = [[AudioFileList alloc] init];
[fileListView setDataSource:fileList];
[fileListView setDelegate:fileList];
[fileListView setAllowsMultipleSelection:YES];
[fileListView registerForDraggedTypes:[NSArray arrayWithObjects:NSStringPboardType, NSFilenamesPboardType, nil]];
[fileListView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
[fileListView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:NO];
[fileListView setAutoresizesOutlineColumn:NO];
// expand initial chapter if chapter mode is enabled
[fileListView expandItem:nil expandChildren:YES];
_binder = [[AudioBinder alloc] init];
_playing = NO;
_converting = NO;
_enqueued = NO;
NSString* img = [[NSBundle mainBundle] pathForResource:@"Play" ofType:@"png"];
NSURL* url = [NSURL fileURLWithPath:img];
_playImg = [[NSImage alloc] initWithContentsOfURL:url];
img = [[NSBundle mainBundle] pathForResource:@"Stop" ofType:@"png"];
url = [NSURL fileURLWithPath:img];
_stopImg = [[NSImage alloc] initWithContentsOfURL:url];
[playButton setImage:_playImg] ;
[playButton setEnabled:NO];
_playingFile = nil;
_destURL = nil;
_totalBookProgress = 0;
_totalBookDuration = 0;
_currentFileProgress = 0;
[fileList addObserver:self
forKeyPath:@"canPlay"
options:0
context:KVO_CONTEXT_CANPLAY_CHANGED];
[fileList addObserver:self
forKeyPath:@"hasFiles"
options:0
context:KVO_CONTEXT_HASFILES_CHANGED];
[fileList addObserver:self
forKeyPath:@"commonAuthor"
options:0
context:KVO_CONTEXT_COMMONAUTHOR_CHANGED];
[fileList addObserver:self
forKeyPath:@"commonAlbum"
options:0
context:KVO_CONTEXT_COMMONALBUM_CHANGED];
[self updateWindowTitle];
[self setupColumns];
[self setupGenres];
[bindButton setEnabled:FALSE];
AudioBookBinderAppDelegate *delegate = (AudioBookBinderAppDelegate*)[[NSApplication sharedApplication] delegate];
[self.window setDelegate:delegate];
// _queueOverlay = [[QueueOverlayView alloc] init];
}
- (void)setupColumns {
int idx;
// build table header context menu
NSArray *cols = [[NSUserDefaults standardUserDefaults] arrayForKey:ColumnsConfiguration];
// default case, add Name and Time columns
if (cols == nil) {
NSArray *tableColumns = [NSArray arrayWithArray:[fileListView tableColumns]];
NSTableColumn *column = [tableColumns objectAtIndex:0];
[column setIdentifier:COLUMNID_NAME];
column = [[NSTableColumn alloc] initWithIdentifier:COLUMNID_TIME];
[fileListView addTableColumn:column];
[column setWidth:150];
}
else
{
// load from saved state
NSDictionary *colinfo;
NSTableColumn *column;
NSArray *tableColumns = [NSArray arrayWithArray:[fileListView tableColumns]];
idx = 0;
for (colinfo in cols) {
NSString *identifier = [colinfo objectForKey:@"identifier"];
CGFloat width = [[colinfo objectForKey:@"width"] floatValue];
if (idx == 0) {
column = [tableColumns objectAtIndex:0];
[column setIdentifier:identifier];
[column setWidth:width];
}
else {
column = [[NSTableColumn alloc] initWithIdentifier:identifier];
[column setWidth:width];
[fileListView addTableColumn:column];
}
idx++;
}
}
// build table header context menu
NSMenu *tableHeaderContextMenu = [[NSMenu alloc] initWithTitle:@""];
[[fileListView headerView] setMenu:tableHeaderContextMenu];
NSArray *columns = [fileListView tableColumns];
for (NSTableColumn *c in columns) {
BOOL found = NO;
for (idx = 0; columnDefs[idx].id; idx++)
{
if ([columnDefs[idx].id isEqualToString:c.identifier]) {
columnDefs[idx].enabled = YES;
[[c headerCell] setStringValue:NSLocalizedString(columnDefs[idx].title, nil)];
found = YES;
break;
}
}
// Name column is special. It can't be removed from view
if (!found && ([c.identifier isEqualToString:COLUMNID_NAME])) {
[[c headerCell] setStringValue:NSLocalizedString(@"Name", nil)];
// make sure outline column is NameColumn
[fileListView setOutlineTableColumn:c];
}
}
for (idx = 0; columnDefs[idx].id; idx++)
{
NSString *title = NSLocalizedString(columnDefs[idx].title, nil);
NSMenuItem *item = [tableHeaderContextMenu addItemWithTitle:title action:@selector(contextMenuSelected:) keyEquivalent:@""];
[item setTarget:self];
[item setRepresentedObject:columnDefs[idx].id];
[item setState:columnDefs[idx].enabled?NSOnState:NSOffState];
}
// listen for changes so know when to save
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveTableColumns) name:NSOutlineViewColumnDidMoveNotification object:fileListView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveTableColumns) name:NSOutlineViewColumnDidResizeNotification object:fileListView];
// [self.window setFrameAutosaveName:@"AudioBookbinderWindow"]; // Specify the autosave name for the window.
}
- (void) setupGenres {
[genresField setStringValue:TEXT_AUDIOBOOKS];
knownGenres = [[NSMutableArray alloc] initWithObjects:@"Art",
@"Biography",
@"Business",
@"Chick Lit",
@"Children's",
@"Christian",
@"Classics",
@"Comics",
@"Contemporary",
@"Cookbooks",
@"Crime",
@"Ebooks",
@"Fantasy",
@"Fiction",
@"Gay And Lesbian",
@"Historical Fiction",
@"History",
@"Horror",
@"Humor And Comedy",
@"Memoir",
@"Music",
@"Mystery",
@"Non Fiction",
@"Paranormal",
@"Philosophy",
@"Poetry",
@"Psychology",
@"Religion",
@"Romance",
@"Science",
@"Science Fiction",
@"Self Help",
@"Suspense",
@"Spirituality",
@"Sports",
@"Thriller",
@"Travel",
@"Young Adult",
nil];
[genresButton removeAllItems];
[genresButton addItemsWithTitles:knownGenres];
#ifdef notyet
[[genresButton menu] addItem:[NSMenuItem separatorItem]];
[genresButton addItemWithTitle:@"Edit genres"];
[[genresButton lastItem] setTag:-1];
#endif
[genresButton setTarget:self];
[genresButton setAction:@selector(genresButtonChanged:)];
autocompleting = NO;
[genresField setDelegate:self];
}
- (void)saveTableColumns {
NSMutableArray *cols = [NSMutableArray array];
NSEnumerator *enumerator = [[fileListView tableColumns] objectEnumerator];
NSTableColumn *column;
while((column = [enumerator nextObject])) {
[cols addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[column identifier], @"identifier",
[NSNumber numberWithFloat:[column width]], @"width",
nil]];
}
[[NSUserDefaults standardUserDefaults] setObject:cols forKey:ColumnsConfiguration];
}
- (IBAction) addFiles: (id)sender
{
// Create the File Open Dialog class.
NSOpenPanel *openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];
[openDlg setAllowsMultipleSelection:YES];
if ( [openDlg runModal] == NSOKButton )
{
BOOL sortFiles = [[NSUserDefaults standardUserDefaults] boolForKey:kConfigSortAudioFiles];
NSArray *urls;
if (sortFiles)
urls = [[openDlg URLs] sortedArrayUsingComparator:^(id a, id b) {return [[a path] compare:[b path]];}];
else
urls = [openDlg URLs];
for(NSURL *url in urls)
{
NSString* fileName = [url path];
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:&isDir])
{
if (isDir)
// add file recursively
[fileList addFilesInDirectory:fileName];
else
[fileList addFile:fileName];
}
}
[fileList tryGuessingAuthorAndAlbum];
[fileListView reloadData];
}
}
- (IBAction) delFiles: (id)sender
{
[fileList deleteSelected:fileListView];
}
- (IBAction) bind: (id)sender
{
NSString *author = [authorField stringValue];
NSString *title = [titleField stringValue];
NSMutableString *filename = [NSMutableString string];
if (![author isEqualToString:@""])
[filename appendString:
[[author stringByReplacingOccurrencesOfString:@"/" withString:@" "] stringByReplacingOccurrencesOfString:@":" withString:@" -"]];
if (![title isEqualToString:@""]) {
if (![filename isEqualToString:@""])
[filename appendString:@" - "];
[filename appendString:
[[title stringByReplacingOccurrencesOfString:@"/" withString:@" "] stringByReplacingOccurrencesOfString:@":" withString:@" -"]];
}
if ([filename isEqualToString:@""])
[filename setString:@"audiobook"];
[filename appendString:@".m4b"];
#ifdef APP_STORE_BUILD
saveAsFilename.stringValue = filename;
[NSApp beginSheet:saveAsPanel modalForWindow:self.window
modalDelegate:self didEndSelector:NULL contextInfo:nil];
#else
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setAccessoryView: nil];
// [savePanel setAllowedFileTypes:[NSArray arrayWithObjects:@"m4a", @"m4b", nil]];
NSString *dir = [[NSUserDefaults standardUserDefaults] stringForKey:kConfigDestinationFolder];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:dir]];
[savePanel setNameFieldStringValue:filename];
NSInteger choice = [savePanel runModal];
/* if successful, save file under designated name */
if (choice == NSOKButton)
{
[bindButton setEnabled:FALSE];
outFile = [[savePanel URL] path];
_converting = YES;
[NSThread detachNewThreadSelector:@selector(bindToFileThread:) toTarget:self withObject:nil];
}
#endif
}
- (IBAction) saveAsOk:(id)sender
{
[NSApp endSheet:saveAsPanel];
[saveAsPanel orderOut:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *destPath;
_destURL = [NSURL URLByResolvingBookmarkData:[defaults objectForKey:kConfigDestinationFolderBookmark] options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:nil];
if (_destURL == nil) {
#ifdef APP_STORE_BUILD
if (requiresUpdateHack) {
NSString *currentDest = [defaults stringForKey:kConfigDestinationFolder];
NSOpenPanel * panel = [NSOpenPanel openPanel];
[panel setPrompt: NSLocalizedString(@"Select", nil)];
[panel setAllowsMultipleSelection: NO];
[panel setCanChooseFiles: NO];
[panel setCanChooseDirectories: YES];
[panel setCanCreateDirectories: YES];
[panel setDirectoryURL:[NSURL fileURLWithPath:currentDest]];
NSInteger result = [panel runModal];
if (result == NSOKButton)
{
_destURL = [panel URL];
destPath = [_destURL path];
}
else
return;
}
else
destPath = [defaults stringForKey:kConfigDestinationFolder];
#else
// standard Music directory
destPath = [defaults stringForKey:kConfigDestinationFolder];
#endif
}
else {
destPath = [_destURL path];
[_destURL startAccessingSecurityScopedResource];
}
outFile = [destPath stringByAppendingPathComponent:[saveAsFilename stringValue]];
if ([[NSFileManager defaultManager] fileExistsAtPath:outFile]) {
NSAlert *a = [[NSAlert alloc] init];
[a addButtonWithTitle:TEXT_OVERWRITE];
[a addButtonWithTitle:TEXT_CANCEL];
[a setMessageText:TEXT_FILE_EXISTS];
[a setAlertStyle:NSWarningAlertStyle];
[a setInformativeText: [NSString stringWithFormat:TEXT_FILE_OVERWRITE, outFile]];
NSInteger result = [a runModal];
if (result == NSAlertSecondButtonReturn) {
return;
}
}
[bindButton setEnabled:FALSE];
_converting = YES;
[NSThread detachNewThreadSelector:@selector(bindToFileThread:) toTarget:self withObject:nil];
}
- (IBAction) saveAsCancel:(id)sender
{
[NSApp endSheet:saveAsPanel];
[saveAsPanel orderOut:nil];
}
- (IBAction) setCover: (id)sender
{
// Create the File Open Dialog class.
NSOpenPanel *openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowsMultipleSelection:NO];
if ( [openDlg runModal] == NSOKButton )
{
NSURL *url = [openDlg URL];
NSString* fileName = [url path];
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:&isDir])
{
if (!isDir) // just sanity check
{
coverImageView.coverImageFilename = fileName;
[tabs selectTabViewItemAtIndex:1];
}
}
[fileListView reloadData];
}
}
- (IBAction) toggleChapters: (id)sender
{
[fileList switchChapterMode];
[fileListView reloadData];
[fileListView expandItem:nil expandChildren:YES];
}
- (IBAction) renumberChapters: (id)sender
{
[fileList renumberChapters];
[fileListView reloadData];
}
- (IBAction) joinFiles: (id)sender
{
[fileList joinSelectedFiles:fileListView];
}
- (IBAction) splitFiles: (id)sender
{
[fileList splitSelectedFiles:fileListView];
}
- (IBAction) resetToDefaults: (id)sender
{
[authorField setStringValue:@""];
[titleField setStringValue:@""];
[actorField setStringValue:@""];
[genresField setStringValue:@"Audiobooks"];
[fileList removeAllFiles:fileListView];
[coverImageView resetImage];
}
- (void) bindingThreadIsDone:(id)sender
{
_converting = NO;
#ifdef APP_STORE_BUILD
if (_destURL) {
[_destURL startAccessingSecurityScopedResource];
_destURL = nil;
}
#endif
BOOL notificationCenterIsAvailable = (NSClassFromString(@"NSUserNotificationCenter")!=nil);
if (_conversionResult && notificationCenterIsAvailable) {
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = TEXT_BOOK_IS_READY;
notification.subtitle = [outFile lastPathComponent];
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}
[bindButton setEnabled:TRUE];
}
- (void) showProgressPanel: (id) sender
{
[NSApp beginSheet:progressPanel modalForWindow:self.window
modalDelegate:self didEndSelector:NULL contextInfo:nil];
}
- (void) hideProgressPanel: (id) sender
{
[NSApp endSheet:progressPanel];
[progressPanel orderOut:nil];
}
- (void)bindToFileThread:(id)object
{
NSString *coverImageFilename = nil;
NSImage *coverImage = coverImageView.coverImage;
UInt64 maxVolumeDuration = 0;
NSInteger hours = [[NSUserDefaults standardUserDefaults] integerForKey:kConfigMaxVolumeSize];
if ((hours > 0) && (hours < 25))
maxVolumeDuration = hours * 3600;
NSLog(@"maxVolumeDuration == %lld", maxVolumeDuration);
_conversionResult = NO;
[_binder reset];
[_binder setDelegate:self];
// split output filename to base and extension in order to get
// filenames for consecutive volume files
NSString *outFileBase = [outFile stringByDeletingPathExtension];
NSString *outFileExt = [outFile pathExtension];
NSArray *files = [fileList files];
NSMutableArray *inputFiles = [[NSMutableArray alloc] init];
UInt64 estVolumeDuration = 0;
NSString *currentVolumeName = [outFile copy];
NSMutableArray *volumeChapters = [[NSMutableArray alloc] init];
NSArray *chapters = nil;
NSMutableArray *curChapters = [[NSMutableArray alloc] init];
Chapter *curChapter = nil;
int chapterIdx = 0;
BOOL hasChapters = [fileList chapterMode];
if (hasChapters) {
chapters = [fileList chapters];
curChapter = [[chapters objectAtIndex:chapterIdx] copy];
chapterIdx++;
[curChapters addObject:curChapter];
}
int totalVolumes = 0;
_currentFileProgress = 0;
_totalBookDuration = 0;
_totalBookProgress = 0;
self.currentProgress = 0;
[[StatsManager sharedInstance] updateConverter:self];
BOOL onChapterBoundary = YES;
for (AudioFile *file in files) {
if (hasChapters) {
if (![curChapter containsFile:file]) {
NSLog(@"%@ -> next chapter", file.filePath);
curChapter = [[chapters objectAtIndex:chapterIdx] copy];
chapterIdx++;
onChapterBoundary = YES;
[curChapters addObject:curChapter];
}
}
if (maxVolumeDuration) {
if ((estVolumeDuration + [file.duration intValue]) > maxVolumeDuration*1000) {
if ([inputFiles count] > 0) {
[_binder addVolume:currentVolumeName files:inputFiles];
[inputFiles removeAllObjects];
estVolumeDuration = 0;
totalVolumes++;
currentVolumeName = [[NSString alloc] initWithFormat:@"%@-%d.%@",
outFileBase, totalVolumes, outFileExt];
if (hasChapters) {
[volumeChapters addObject:curChapters];
if (!onChapterBoundary) {
curChapter = [curChapter splitAtFile:file];
NSLog(@"Splitting chapter %@ on file %@", curChapter.name, file.filePath);
}
curChapters = [[NSMutableArray alloc] init];
[curChapters addObject:curChapter];
}
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert *alert = [[NSAlert alloc] init];
NSString *msg = [NSString stringWithFormat:TEXT_MAXDURATION_VIOLATED,
[file.filePath UTF8String], [file.duration intValue]/1000, maxVolumeDuration];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:TEXT_CANT_SPLIT];
[alert setInformativeText:msg];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
});
return;
}
}
}
onChapterBoundary = NO;
[inputFiles addObject:file];
estVolumeDuration += [file.duration intValue];
_totalBookDuration += [file.duration intValue];
}
[_binder addVolume:currentVolumeName files:inputFiles];
[volumeChapters addObject:curChapters];
// make sure that at this point we have valid bitrate in settings
// setup channels/samplerate
_binder.channels = (UInt32)[[NSUserDefaults standardUserDefaults] integerForKey:kConfigChannels];
_binder.sampleRate = [[NSUserDefaults standardUserDefaults] floatForKey:kConfigSampleRate];
_binder.bitrate = (UInt32)[[NSUserDefaults standardUserDefaults] integerForKey:kConfigBitrate];
[self performSelectorOnMainThread:@selector(showProgressPanel:) withObject:nil waitUntilDone:NO];
[self updateProgress:0 total:100];
dispatch_async(dispatch_get_main_queue(), ^{
[self->fileProgress displayIfNeeded];
});
if (!(_conversionResult = [_binder convert]))
{
NSLog(@"Conversion failed");
}
else
{
if (![self.author isEqualToString:@""] ||
![self.title isEqualToString:@""] || (coverImage != nil))
{
NSLog(@"Adding metadata, it may take a while...");
@try {
[self updateProgressString:TEXT_ADDING_TAGS];
BOOL temporaryFile = NO;
if ([coverImageView haveCover]) {
if ([coverImageView shouldConvert]) {
NSString *tempFileTemplate =
[NSTemporaryDirectory() stringByAppendingPathComponent:@"coverimg.XXXXXX"];
const char *tempFileTemplateCString =
[tempFileTemplate fileSystemRepresentation];
char *tempFileNameCString = (char *)malloc(strlen(tempFileTemplateCString) + 1);
strcpy(tempFileNameCString, tempFileTemplateCString);
if (mktemp(tempFileNameCString)) {
coverImageFilename = [NSString stringWithCString:tempFileNameCString encoding:NSUTF8StringEncoding];
NSData *imgData = [coverImage TIFFRepresentation];
NSDictionary *dict = [[NSDictionary alloc] init];
[[[NSBitmapImageRep imageRepWithData:imgData]
representationUsingType:NSPNGFileType properties:dict]
writeToFile:coverImageFilename atomically:YES];
temporaryFile = YES;
}
else {
NSLog(@"Failed to generate tmp filename");
}
}
else {
coverImageFilename = coverImageView.coverImageFilename;
}
}
int track = 1;
NSArray *volumes = [_binder volumes];
for (AudioBookVolume *v in volumes) {
NSString *volumeName = v.filename;
MP4File *mp4 = [[MP4File alloc] initWithFileName:volumeName];
mp4.artist = self.author;
if ([volumes count] > 1) {
mp4.title = [NSString stringWithFormat:@"%@ #%02d", self.title, track];
mp4.gaplessPlay = YES;
}
else
mp4.title = self.title;
mp4.narrator = self.actor;
mp4.album = self.title;
mp4.genre = self.genre;
if (coverImageFilename)
[mp4 setCoverFile:coverImageFilename];
mp4.track = track;
mp4.tracksTotal = [volumes count];
[mp4 updateFile];
track ++;
}
if ((coverImageFilename != nil) && temporaryFile) {
NSLog(@"Unlink %@", coverImageFilename);
[[NSFileManager defaultManager] removeItemAtPath:coverImageFilename
error:nil];
}
if ([fileList chapterMode]) {
[self updateProgressString:TEXT_ADDING_CHAPTERS];
int idx = 0;
for (AudioBookVolume *v in volumes) {
addChapters([v.filename UTF8String], [volumeChapters objectAtIndex:idx]);
idx++;
}
}
[self updateProgressString:@"Done"];
}
@catch (NSException *e) {
NSLog(@"Something went wrong");
}
}
// write chapters
}
[[StatsManager sharedInstance] removeConverter:self];
[self performSelectorOnMainThread:@selector(hideProgressPanel:) withObject:nil waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(bindingThreadIsDone:) withObject:nil waitUntilDone:NO];
}
//
// AudioBinderDelegate methods
//
-(void) conversionStart: (AudioFile*)file
format: (AudioStreamBasicDescription*)asbd
formatDescription: (NSString*)description
length: (UInt64)frames
{
[self updateProgressString:[NSString stringWithFormat:TEXT_CONVERTING,
[file filePath]]];
[self updateProgress:0 total:frames];
}
- (void)recalculateProgress
{
NSUInteger newProgress = 0;
if (_totalBookDuration > 0)
newProgress = floor((_currentFileProgress + _totalBookProgress)*100./_totalBookDuration);
if (newProgress != self.currentProgress) {
self.currentProgress = newProgress;
[[StatsManager sharedInstance] updateConverter:self];
}
}
- (void) updateProgressString: (NSString*)message
{
dispatch_async(dispatch_get_main_queue(), ^{
[self->currentFile setStringValue:message];
});
}
- (void) updateProgress: (double)handledFrames total:(double)totalFrames
{
dispatch_async(dispatch_get_main_queue(), ^{
[self->fileProgress setMaxValue:(double)totalFrames];
[self->fileProgress setDoubleValue:(double)handledFrames];
});
}
-(void) updateStatus: (AudioFile *)file handled:(UInt64)handledFrames total:(UInt64)totalFrames
{
[self updateProgress:handledFrames total:totalFrames];
if (totalFrames > 0) {
_currentFileProgress = [file.duration intValue]*handledFrames/totalFrames;
[self recalculateProgress];
}
}
-(BOOL) continueFailedConversion:(AudioFile*)file reason:(NSString*)reason
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:TEXT_CONVERSION_FAILED];
[alert setInformativeText:reason];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
});
return NO;
}
-(void) volumeFailed:(NSString*)filename reason:(NSString*)reason
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:TEXT_BINDING_FAILED];
[alert setInformativeText:reason];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
});
}
-(void) conversionFinished:(AudioFile*)file duration:(UInt32)milliseconds
{
dispatch_sync(dispatch_get_main_queue(), ^{
[self->fileProgress setDoubleValue:[self->fileProgress doubleValue]];
});
file.valid = YES;
file.duration = [[NSNumber alloc] initWithInt:milliseconds];
if (_totalBookDuration > 0) {
_totalBookProgress += [file.duration intValue];
_currentFileProgress = 0;
[self recalculateProgress];
}
}
-(void) volumeReady:(NSString*)filename duration: (UInt32)seconds
{
}
-(void) audiobookReady:(UInt32)seconds
{
}
- (IBAction) cancel: (id)sender
{
[_binder cancel];
}
- (IBAction) playStop: (id)sender
{
if ((_sound != nil) && [_sound isPlaying]) {
[_sound stop];
return;
}
if ([[fileListView selectedItems] count] != 1)
return;
id item = [[fileListView selectedItems] objectAtIndex:0];
if ([item isKindOfClass:[AudioFile class]]) {
AudioFile *file = (AudioFile *)item;
[playButton setImage:_stopImg] ;
_playingFile = [file.filePath copy];
_sound = [[NSSound alloc] initWithContentsOfFile:file.filePath byReference:NO];
[_sound setDelegate:self];
if (![_sound play]) {
[playButton setImage:_playImg] ;
_sound = nil;
[playButton setEnabled:fileList.canPlay];
[self playFailed];
}
}
}
- (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finishedPlaying
{
[playButton setImage:_playImg] ;
_sound = nil;
[playButton setEnabled:fileList.canPlay];
}
- (void) playFailed
{
NSAlert *alert = [[NSAlert alloc] init];
NSString *msg = [NSString stringWithFormat:TEXT_CANT_PLAY, _playingFile];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:TEXT_FAILED_TO_PLAY];
[alert setInformativeText:msg];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
}
- (void)contextMenuSelected:(id)sender
{
NSMenuItem *item = sender;
if (item.state == NSOffState) {
[item setState:NSOnState];
BOOL found = NO;
int idx;
for (idx = 0; columnDefs[idx].id; idx++)
{
if ([columnDefs[idx].id isEqualToString:[item representedObject]]) {
found = YES;
break;
}
}
if (found) {
NSTableColumn *c = [[NSTableColumn alloc] initWithIdentifier:columnDefs[idx].id];
[fileListView addTableColumn:c];
[[c headerCell] setStringValue:NSLocalizedString(columnDefs[idx].title, nil)];
}
}