-
Notifications
You must be signed in to change notification settings - Fork 56
/
AppController.m
863 lines (765 loc) · 29.9 KB
/
AppController.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
//
// AppController.m
// MetaZ
//
// Created by Brian Olsen on 06/09/09.
// Copyright 2009 Maven-Group. All rights reserved.
//
#import "AppController.h"
#import "UndoTableView.h"
#import "PosterView.h"
#import "MZWriteQueue.h"
#import "FilesTableView.h"
#import "Resources.h"
#import "MZMetaDataDocument.h"
#import "MZScriptingAdditions.h"
#import "MetaZApplication.h"
#define MaxShortDescription 256
NSResponder* findResponder(NSWindow* window) {
NSResponder* oldResponder = [window firstResponder];
if([oldResponder isKindOfClass:[NSTextView class]] && [window fieldEditor:NO forObject:nil] != nil)
{
id<NSTextViewDelegate> delegate = [((NSTextView*)oldResponder) delegate];
if([delegate isKindOfClass:[NSTextField class]])
oldResponder = (NSResponder*)delegate;
}
return oldResponder;
}
NSDictionary* findBinding(NSWindow* window) {
NSResponder* oldResponder = findResponder(window);
NSDictionary* dict = [oldResponder infoForBinding:NSValueBinding];
if(dict == nil)
dict = [oldResponder infoForBinding:NSDataBinding];
return dict;
}
@implementation AppController
@synthesize window;
@synthesize tabView;
@synthesize episodeFormatter;
@synthesize seasonFormatter;
@synthesize dateFormatter;
@synthesize purchaseDateFormatter;
@synthesize filesSegmentControl;
@synthesize filesController;
@synthesize undoController;
@synthesize resizeController;
@synthesize shortDescription;
@synthesize longDescription;
@synthesize imageView;
@synthesize chapterEditor;
@synthesize remainingInShortDescription;
@synthesize tvShow;
@synthesize tvSeason;
@synthesize picturesController;
@synthesize updater;
@synthesize loadingIndicator;
@synthesize usingiTunesTVStandard = usingiTunesTVStandard_;
#pragma mark - initialization
+ (void)initialize
{
if(self != [AppController class])
return;
NSArray* sendTypes = [NSArray arrayWithObjects:NSTIFFPboardType, nil];
NSArray* returnTypes = [NSArray arrayWithObjects:NSTIFFPboardType, nil];
[NSApp registerServicesMenuSendTypes:sendTypes
returnTypes:returnTypes];
}
- (id)init
{
self = [super init];
if(self)
{
remainingInShortDescription = MaxShortDescription;
}
return self;
}
-(void)awakeFromNib
{
[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-60*60*11]];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(removedEdit:)
name:MZMetaEditsDeallocating
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(startedLoading:)
name:MZMetaLoaderStartedNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(finishedLoading:)
name:MZMetaLoaderFinishedNotification
object:nil];
undoManager = [[NSUndoManager alloc] init];
[seasonFormatter setNilSymbol:@""];
[episodeFormatter setNilSymbol:@""];
[dateFormatter setLenient:YES];
[purchaseDateFormatter setLenient:YES];
[dateFormatter setDefaultDate:nil];
[purchaseDateFormatter setDefaultDate:nil];
[window setExcludedFromWindowsMenu:YES];
[filesController addObserver:self
forKeyPath:@"selection.title"
options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld|NSKeyValueObservingOptionInitial
context:nil];
[filesController addObserver:self
forKeyPath:@"selection.shortDescription"
options:0
context:nil];
[filesController addObserver:self
forKeyPath:@"selection.pure.videoType"
options:NSKeyValueChangeOldKey
context:nil];
[[NSUserDefaults standardUserDefaults] addObserver:self
forKeyPath:@"useiTunesTVFormat"
options:NSKeyValueChangeOldKey
context:nil];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SUFeedURL"];
updater.sendsSystemProfile = YES;
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[filesController removeObserver:self forKeyPath:@"selection.title"];
[window release];
[tabView release];
[episodeFormatter release];
[seasonFormatter release];
[dateFormatter release];
[purchaseDateFormatter release];
[filesSegmentControl release];
[filesController release];
[resizeController release];
[undoController release];
[shortDescription release];
[longDescription release];
[undoManager release];
[imageView release];
[imageEditController release];
[prefController release];
[presetsController release];
[chapterEditor release];
[fileNameEditor release];
[fileNameStorage release];
[picturesController release];
[updater release];
[super dealloc];
}
#pragma mark - as observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqual:@"selection.title"] && object == filesController)
{
id value = [object valueForKeyPath:keyPath];
if(value == NSMultipleValuesMarker ||
value == NSNotApplicableMarker ||
value == NSNoSelectionMarker ||
value == [NSNull null] ||
value == nil)
{
[window setTitle:@"MetaZ"];
}
else
{
[window setTitle:[NSString stringWithFormat:@"MetaZ - %@", value]];
}
if(value == NSNoSelectionMarker)
[filesSegmentControl setEnabled:NO forSegment:1];
else
[filesSegmentControl setEnabled:YES forSegment:1];
}
if([keyPath isEqual:@"selection.shortDescription"] && object == filesController)
{
NSInteger newRemain = 0;
id length = [filesController valueForKeyPath:@"selection.shortDescription.length"];
if([length respondsToSelector:@selector(integerValue)])
newRemain = [length integerValue];
[self willChangeValueForKey:@"remainingInShortDescription"];
remainingInShortDescription = MaxShortDescription-newRemain;
[self didChangeValueForKey:@"remainingInShortDescription"];
}
if( ([keyPath isEqual:@"selection.pure.videoType"] && object == filesController) ||
([keyPath isEqual:@"useiTunesTVFormat"] && object == [NSUserDefaults standardUserDefaults]) )
{
[self willChangeValueForKey:@"usingiTunesTVStandard"];
usingiTunesTVStandard_ = false;
NSUserDefaults* d = [NSUserDefaults standardUserDefaults];
if( [d boolForKey:@"useiTunesTVFormat"] )
{
id videoType = [filesController protectedValueForKeyPath:@"selection.pure.videoType"];
MZVideoType vt;
MZTag* tag = [MZTag tagForIdentifier:MZVideoTypeTagIdent];
[tag convertObject:videoType toValue:&vt];
if(vt == MZTVShowVideoType)
{
usingiTunesTVStandard_ = true;
}
}
[self didChangeValueForKey:@"usingiTunesTVStandard"];
}
}
#pragma mark - actions
- (IBAction)showAdvancedTab:(id)sender {
[window makeKeyAndOrderFront:sender];
[tabView selectTabViewItemWithIdentifier:@"advanced"];
}
- (IBAction)showChapterTab:(id)sender {
[window makeKeyAndOrderFront:sender];
[tabView selectTabViewItemWithIdentifier:@"chapters"];
}
- (IBAction)showInfoTab:(id)sender {
[window makeKeyAndOrderFront:sender];
[tabView selectTabViewItemWithIdentifier:@"info"];
}
- (IBAction)showSortTab:(id)sender {
[window makeKeyAndOrderFront:sender];
[tabView selectTabViewItemWithIdentifier:@"sorting"];
}
- (IBAction)showVideoTab:(id)sender {
[window makeKeyAndOrderFront:sender];
[tabView selectTabViewItemWithIdentifier:@"video"];
}
- (IBAction)segmentClicked:(id)sender {
NSInteger clickedSegment = [sender selectedSegment];
NSInteger clickedSegmentTag = [[sender cell] tagForSegment:clickedSegment];
if(clickedSegmentTag == 0)
[self openDocument:sender];
else
[filesController remove:sender];
}
- (IBAction)revertChanges:(id)sender {
NSDictionary* dict = findBinding(window);
if(dict == nil)
{
MZLoggerError(@"Could not find binding for revert.");
return;
}
id observed = [dict objectForKey:NSObservedObjectKey];
NSString* keyPath = [[dict objectForKey:NSObservedKeyPathKey] stringByAppendingString:@"Changed"];
NSNumber* num = [observed valueForKeyPath:keyPath];
num = [NSNumber numberWithBool:![num boolValue]];
[observed setValue:num forKeyPath:keyPath];
}
- (IBAction)searchForImages:(id)sender
{
NSString* title = [[filesController valueForKeyPath:@"selection.pure.title"]
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
id videoType = [filesController protectedValueForKeyPath:@"selection.pure.videoType"];
MZVideoType vt;
MZTag* tag = [MZTag tagForIdentifier:MZVideoTypeTagIdent];
[tag convertObject:videoType toValue:&vt];
NSString* query;
switch (vt) {
case MZTVShowVideoType:
{
NSString* show = [filesController valueForKeyPath:@"selection.pure.tvShow"];
if([show isKindOfClass:[NSString class]])
{
show = [show stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSNumber* season = [filesController valueForKeyPath:@"selection.pure.tvSeason"];
if([season isKindOfClass:[NSNumber class]])
query = [NSString stringWithFormat:@"\"%@\" season %ld", show, (long)[season integerValue]];
else
query = [NSString stringWithFormat:@"\"%@\"", show];
break;
}
}
default:
query = [NSString stringWithFormat:@"\"%@\"", title];
break;
}
// Escape even the "reserved" characters for URLs
// as defined in http://www.ietf.org/rfc/rfc2396.txt
query = [query stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
/*CFStringRef encodedValue = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)query,
NULL,
(CFStringRef)@";/?:@&=+$,",
kCFStringEncodingUTF8);
query = (NSString*)encodedValue;*/
NSString* str = [NSString stringWithFormat:
@"http://images.google.com/images?q=%@&gbv=2&svnum=10&safe=active&sa=G&imgsz=small%%7Cmedium%%7Clarge%%7Cxlarge",
query];
//CFRelease(encodedValue);
NSURL* url = [NSURL URLWithString:str];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)showImageEditor:(id)sender
{
if(!imageEditController)
imageEditController = [[ImageWindowController alloc] initWithImageView:imageView];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(imageEditorDidClose:)
name:NSWindowWillCloseNotification
object:[imageEditController window]];
[imageEditController showWindow:self];
}
- (IBAction)showPreferences:(id)sender
{
if(!prefController)
{
prefController = [[PreferencesWindowController alloc] init];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(preferencesDidClose:)
name:NSWindowWillCloseNotification
object:[prefController window]];
}
[prefController showWindow:self];
}
- (IBAction)openDocument:(id)sender {
NSArray *fileTypes = [[MZMetaLoader sharedLoader] types];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setCanChooseFiles:YES];
[oPanel setCanChooseDirectories:NO];
oPanel.allowedFileTypes = fileTypes;
[oPanel beginSheetModalForWindow:window completionHandler:^(NSInteger result) {
[self openPanelDidEnd:oPanel returnCode:result contextInfo:NULL];
}];
}
- (IBAction)showPresets:(id)sender
{
if(!presetsController)
{
presetsController = [[PresetsWindowController alloc] initWithController:filesController];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(presetsDidClose:)
name:NSWindowWillCloseNotification
object:[presetsController window]];
}
if(![[presetsController window] isVisible])
{
[[presetsController window] setFrameUsingName:@"presetsPanel"];
[presetsController showWindow:self];
}
else
[presetsController close];
}
- (IBAction)showReleaseNotes:(id)sender
{
NSURL* url = [NSURL URLWithString:@"http://griff.github.com/metaz/release-notes.html"];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)showHomepage:(id)sender
{
NSURL* url = [NSURL URLWithString:@"http://griff.github.com/metaz/"];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)showIssues:(id)sender
{
NSURL* url = [NSURL URLWithString:@"https://github.com/griff/metaz/issues"];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)reportIssue:(id)sender
{
NSURL* url = [NSURL URLWithString:@"https://github.com/griff/metaz/issues/new"];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)viewLog:(id)sender
{
NSFileManager *mgr = [NSFileManager manager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
for(NSString* dir in paths)
{
NSString* path = [[dir
stringByAppendingPathComponent:@"Logs"]
stringByAppendingPathComponent:@"MetaZ.log"];
if([mgr fileExistsAtPath:path])
{
[[NSWorkspace sharedWorkspace]
openFile:path
withApplication:@"Console"
andDeactivate:YES];
return;
}
}
}
- (IBAction)sendFeedback:(id)sender
{
}
#pragma mark - user interface validation
- (BOOL)validateUserInterfaceItem:(id < NSValidatedUserInterfaceItem >)anItem
{
SEL action = [anItem action];
if(action == @selector(revertChanges:))
{
NSDictionary* dict = findBinding(window);
if([[filesController selectedObjects] count] >= 1 && dict != nil)
{
id observed = [dict objectForKey:NSObservedObjectKey];
NSString* keyPath = [dict objectForKey:NSObservedKeyPathKey];
BOOL changed = [[observed valueForKeyPath:[keyPath stringByAppendingString:@"Changed"]] boolValue];
NSMenuItem* item = (NSMenuItem*)anItem;
if(changed)
[item setTitle:NSLocalizedString(@"Revert Changes", @"Revert changes menu item")];
else
[item setTitle:NSLocalizedString(@"Apply Changes", @"Apply changes menu item")];
return YES;
}
else
return NO;
}
if(action == @selector(showImageEditor:))
{
id value = [filesController protectedValueForKeyPath:@"selection.picture"];
return [value isKindOfClass:[NSData class]] || [value isKindOfClass:[RemoteData class]];
}
if(action == @selector(searchForImages:))
{
id videoType = [filesController protectedValueForKeyPath:@"selection.pure.videoType"];
MZVideoType vt;
MZTag* tag = [MZTag tagForIdentifier:MZVideoTypeTagIdent];
[tag convertObject:videoType toValue:&vt];
if(vt == MZTVShowVideoType)
{
id show = [filesController valueForKeyPath:@"selection.pure.tvShow"];
if([show isKindOfClass:[NSString class]])
return YES;
}
id title = [filesController valueForKeyPath:@"selection.pure.title"];
return [title isKindOfClass:[NSString class]];
}
return YES;
}
#pragma mark - callbacks
- (void)startedLoading:(NSNotification *)note
{
if(loadings == 0)
[loadingIndicator setDoubleValue:0.0];
loadings++;
[loadingIndicator setMaxValue:loadings];
[loadingIndicator setHidden:NO];
}
- (void)finishedLoading:(NSNotification *)note
{
[loadingIndicator incrementBy:1.0];
loadings--;
if(loadings == 0)
[loadingIndicator setHidden:YES];
}
- (void)imageEditorDidClose:(NSNotification *)note
{
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:NSWindowWillCloseNotification
object:[note object]];
[imageEditController release];
imageEditController = nil;
}
- (void)preferencesDidClose:(NSNotification *)note
{
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:NSWindowWillCloseNotification
object:[note object]];
[prefController release];
prefController = nil;
}
- (void)presetsDidClose:(NSNotification *)note
{
[[note object] saveFrameUsingName:@"presetsPanel"];
}
- (void)removedEdit:(NSNotification *)note
{
MetaEdits* other = [note object];
[other.undoManager removeAllActionsWithTarget:self];
}
- (void)openPanelDidEnd:(NSOpenPanel *)oPanel returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSModalResponseOK)
{
if([filesController commitEditing])
[[MZMetaLoader sharedLoader] loadFromFiles: [oPanel filenames]];
}
}
- (void)queueStatusChanged:(GTMKeyValueChangeNotification *)notification
{
if([[MZWriteQueue sharedQueue] status] == QueueStopped)
{
[[notification object] gtm_removeObserver:self forKeyPath:[notification keyPath] selector:_cmd];
[NSApp replyToApplicationShouldTerminate:YES];
}
}
#pragma mark - as window delegate
- (NSSize)windowWillResize:(NSWindow *)aWindow toSize:(NSSize)proposedFrameSize {
[[NSNotificationCenter defaultCenter] postNotificationName:MZNSWindowWillResizeNotification object:aWindow];
return [resizeController windowWillResize:aWindow toSize:proposedFrameSize];
}
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)aWindow {
NSResponder* responder = [aWindow firstResponder];
if(responder == shortDescription ||
responder == longDescription ||
[responder isKindOfClass:[UndoTableView class]] ||
[responder isKindOfClass:[PosterView class]])
{
NSUndoManager * man = [undoController undoManager];
if(man != nil)
return man;
}
return undoManager;
}
- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
{
if([client isKindOfClass:[FilesTableView class]])
{
if(!fileNameEditor)
{
fileNameStorage = [[MZFileNameTextStorage alloc] init];
NSLayoutManager *layoutManager;
layoutManager = [[NSLayoutManager alloc] init];
[fileNameStorage addLayoutManager:layoutManager];
[layoutManager release];
NSTextContainer *container;
container = [[NSTextContainer alloc]
initWithContainerSize:NSZeroSize];
[layoutManager addTextContainer:container];
[container release];
fileNameEditor = [[NSTextView alloc]
initWithFrame:NSZeroRect textContainer:container];
[fileNameEditor setFieldEditor:YES];
[fileNameEditor setRichText:NO];
}
return fileNameEditor;
}
return nil;
}
#pragma mark - as text delegate
- (void)textDidChange:(NSNotification *)aNotification
{
[self willChangeValueForKey:@"remainingInShortDescription"];
remainingInShortDescription = MaxShortDescription-[[shortDescription string] length];
[self didChangeValueForKey:@"remainingInShortDescription"];
}
#pragma mark - as application delegate
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename
{
[window makeKeyAndOrderFront:sender];
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[filename pathExtension], NULL);
if(UTTypeConformsTo(uti, kMZUTMetaZPlugin) ||
UTTypeEqual(uti, kMZUTAppleScriptText) || UTTypeConformsTo(uti, kMZUTAppleScriptText) ||
UTTypeEqual(uti, kMZUTAppleScript) || UTTypeConformsTo(uti, kMZUTAppleScript) ||
UTTypeEqual(uti, kMZUTAppleScriptBundle) || UTTypeConformsTo(uti, kMZUTAppleScriptBundle))
{
CFRelease(uti);
NSError* error = nil;
if(![[MZPluginController sharedInstance] installPlugin:[NSURL fileURLWithPath:filename] force:NO error:&error] && error)
return [NSApp presentError:error];
return YES;
}
else
{
CFRelease(uti);
return [[MZMetaLoader sharedLoader] loadFromFile:filename];
}
}
- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
[window makeKeyAndOrderFront:sender];
NSApplicationDelegateReply response = NSApplicationDelegateReplySuccess;
for(NSString* filename in filenames)
{
if(![self application:sender openFile: filename])
response = NSApplicationDelegateReplyCancel;
}
[sender replyToOpenOrPrint:response];
}
- (void)applicationWillFinishLaunching:(NSNotification *)notification;
{
[NSApp setServicesProvider:self];
// Load scriptability early to allow sdef open handler to override default AppKit handler.
[NSScriptSuiteRegistry sharedScriptSuiteRegistry];
[NSApp updateFeedURL: nil];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
BOOL changed = NO;
NSArray* arr = [[MZMetaLoader sharedLoader] files];
NSUInteger count = [arr count];
for(int i=0; i<count && !changed; i++)
{
MetaEdits* edit = [arr objectAtIndex:i];
changed = [edit changed];
}
NSModalResponse result = NSAlertFirstButtonReturn;
if(changed)
{
NSAlert* alert = [NSAlert new];
alert.messageText = NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil);
alert.informativeText = NSLocalizedString(@"You have files loaded with unsaved changes. Do you want to quit anyway?", nil);
[alert addButtonWithTitle:NSLocalizedString(@"Quit", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"Don't Quit", nil)];
result = [alert runModal];
}
else if([[MZWriteQueue sharedQueue] status] == QueueRunning)
{
NSAlert* alert = [NSAlert new];
alert.messageText = NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil);
alert.informativeText = NSLocalizedString(@"If you quit MetaZ your current jobs will be reloaded into your queue at next launch. Do you want to quit anyway?", nil);
[alert addButtonWithTitle:NSLocalizedString(@"Quit", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"Don't Quit", nil)];
result = [alert runModal];
}
// Warn if items still in the queue
else if([[[MZWriteQueue sharedQueue] pendingItems] count] > 0)
{
NSAlert* alert = [NSAlert new];
alert.messageText = NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil);
alert.informativeText = NSLocalizedString(@"There are pending jobs in your queue. Do you want to quit anyway?",nil);
[alert addButtonWithTitle:NSLocalizedString(@"Quit", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"Don't Quit", nil)];
result = [alert runModal];
}
if( result == NSAlertFirstButtonReturn )
{
if([[MZWriteQueue sharedQueue] status] == QueueRunning || [[MZWriteQueue sharedQueue] status] == QueueStopping)
{
[[MZWriteQueue sharedQueue] gtm_addObserver:self forKeyPath:@"status" selector:@selector(queueStatusChanged:) userInfo:nil options:0];
[[MZWriteQueue sharedQueue] stop];
return NSTerminateLater;
}
return NSTerminateNow;
}
return NSTerminateCancel;
}
-(void)doiTunesMetadata:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
NSDictionary* prop = [pboard propertyListForType:iTunesMetadataPboardType];
BOOL tv = NO;
if(!prop) {
prop = [pboard propertyListForType:TVAppMetadataPboardType];
tv = YES;
}
if(!prop)
prop = [pboard propertyListForType:iTunesPboardType];
if(prop)
{
NSMutableArray* names = [NSMutableArray array];
NSMutableArray* dataDicts = [NSMutableArray array];
NSDictionary* tracks = [prop objectForKey:@"Tracks"];
for(id track in [tracks allValues])
{
NSURL* location = [NSURL URLWithString:[track objectForKey:@"Location"]];
[names addObject:[location path]];
NSString* persistentId = [track objectForKey:@"Persistent ID"];
NSDictionary* data;
if (tv) {
data = [NSDictionary dictionaryWithObject:persistentId
forKey:MZTVAppPersistentIDTagIdent];
} else {
data = [NSDictionary dictionaryWithObject:persistentId
forKey:MZiTunesPersistentIDTagIdent];
}
[dataDicts addObject:data];
}
[[MZMetaLoader sharedLoader] loadFromFiles:names withMetaData:dataDicts];
}
}
-(void)doiTunes:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
[self doiTunes:@"Return iTunes selected"
tag:MZiTunesPersistentIDTagIdent
error:error];
}
-(void)doTVApp:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
[self doiTunes:@"Return TV app selected"
tag:MZTVAppPersistentIDTagIdent
error:error];
}
-(void)doiTunes:(NSString *)filename tag:(NSString *)tagName error:(NSString **)error {
NSString* path = [[NSBundle mainBundle] pathForResource:filename ofType:@"scptd"];
NSURL* url = [NSURL fileURLWithPath:path];
NSDictionary* errDict = nil;
NSAppleScript* script = [[[NSAppleScript alloc] initWithContentsOfURL:url error:&errDict] autorelease];
if(errDict)
{
NSError* err = [NSError errorWithAppleScriptError:errDict];
if(error)
*error = [err localizedDescription];
GTMLoggerError(@"Error loading script %@ %@", path, [err localizedDescription]);
return;
}
if(script)
{
NSAppleEventDescriptor* ret = [script executeAndReturnError:&errDict];
if(!ret)
{
NSError* err = [NSError errorWithAppleScriptError:errDict];
if(error)
*error = [err localizedDescription];
GTMLoggerError(@"Error running script %@ %@", path, [err localizedDescription]);
}
else
{
id obj = [ret objectValue];
if([obj isKindOfClass:[NSArray class]])
{
NSMutableArray* names = [NSMutableArray array];
NSMutableArray* dataDicts = nil;
for(id o in obj)
{
if([o isKindOfClass:[NSString class]])
{
[names addObject:o];
}
else if([o isKindOfClass:[NSDictionary class]])
{
[names addObject:[o objectForKey:@"mylocation"]];
if(!dataDicts)
dataDicts = [NSMutableArray array];
[dataDicts addObject:[NSDictionary dictionaryWithObject:[o objectForKey:@"myid"] forKey:tagName]];
}
else
{
NSString* err = [NSString stringWithFormat:@"Unsupported return type %@", o];
if(error)
*error = err;
else
GTMLoggerError(@"Selection array: %@", err);
return;
}
}
[[MZMetaLoader sharedLoader] loadFromFiles:names withMetaData:dataDicts];
}
else if([obj isKindOfClass:[NSString class]])
[[MZMetaLoader sharedLoader] loadFromFile:obj];
else if([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary* data = [NSDictionary dictionaryWithObject:[obj objectForKey:@"myid"]
forKey:tagName];
[[MZMetaLoader sharedLoader] loadFromFile:[obj objectForKey:@"mylocation"]
withMetaData:data];
}
else {
NSString* err = [NSString stringWithFormat:@"Unsupported return type %@", obj];
if(error)
*error = err;
else
GTMLoggerError(@"Selection: %@", err);
}
}
}
}
-(void)updateTV {
if( self.usingiTunesTVStandard )
{
NSString* show = tvShow.stringValue;
if( show != nil && show.length )
{
NSString* album = show;
NSString* season = tvSeason.stringValue;
if( season != nil && season.length )
{
album = [NSString stringWithFormat:@"%@, Season %@", show, season];
}
[filesController setValue:album forKeyPath:@"selection.album"];
[filesController setValue:show forKeyPath:@"selection.artist"];
[filesController setValue:show forKeyPath:@"selection.albumArtist"];
}
}
}
- (IBAction)tvSeasonChanged:(NSTextField *)sender {
[self updateTV];
}
- (IBAction)tvShowChanged:(NSTextField *)sender {
[self updateTV];
}
@end