-
Notifications
You must be signed in to change notification settings - Fork 56
/
AppController.m
969 lines (858 loc) · 32 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
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
//
// AppController.m
// MetaZ
//
// Created by Brian Olsen on 06/09/09.
// Copyright 2009 Maven-Group. All rights reserved.
//
#import <Growl/Growl.h>
#import "AppController.h"
#import "UndoTableView.h"
#import "PosterView.h"
#import "MZMetaSearcher.h"
#import "MZWriteQueue.h"
#import "FakeSearchResult.h"
#import "SearchMeta.h"
#import "FilesTableView.h"
#define MaxShortDescription 256
@interface AppController ()
- (void)updateSearchMenu;
- (void)registerUndoName:(NSUndoManager *)manager;
@end
NSArray* MZUTIFilenameExtension(NSArray* utis)
{
NSMutableArray* ret = [NSMutableArray arrayWithCapacity:utis.count];
for(NSString* uti in utis)
{
NSDictionary* dict = (NSDictionary*)UTTypeCopyDeclaration((CFStringRef)uti);
//[dict writeToFile:[NSString stringWithFormat:@"/Users/bro/Documents/Maven-Group/MetaZ/%@.plist", uti] atomically:NO];
NSDictionary* tags = [dict objectForKey:(NSString*)kUTTypeTagSpecificationKey];
NSArray* extensions = [tags objectForKey:(NSString*)kUTTagClassFilenameExtension];
[ret addObjectsFromArray:extensions];
[dict release];
}
return ret;
}
NSResponder* findResponder(NSWindow* window) {
NSResponder* oldResponder = [window firstResponder];
if([oldResponder isKindOfClass:[NSTextView class]] && [window fieldEditor:NO forObject:nil] != nil)
{
NSResponder* delegate = [((NSTextView*)oldResponder) delegate];
if([delegate isKindOfClass:[NSTextField class]])
oldResponder = 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 searchIndicator;
@synthesize searchController;
@synthesize searchField;
@synthesize chapterEditor;
@synthesize remainingInShortDescription;
@synthesize loadingIndicator;
#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;
activeProfile = [[SearchProfile unknownTypeProfile] retain];
[activeProfile addObserver:self forKeyPath:@"searchTerms" options:0 context:NULL];
}
return self;
}
-(void)awakeFromNib
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(finishedSearch:)
name:MZSearchFinishedNotification
object:nil];
[[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];
[[MZPluginController sharedInstance] setDelegate:self];
[[MZMetaSearcher sharedSearcher] setFakeResult:[FakeSearchResult resultWithController:filesController]];
[self updateSearchMenu];
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.pure.videoType"
options:0
context:nil];
[filesController addObserver:self
forKeyPath:@"selection.shortDescription"
options:0
context:nil];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[activeProfile removeObserver:self forKeyPath:@"searchTerms"];
[filesController removeObserver:self forKeyPath:@"selection.title"];
[filesController removeObserver:self forKeyPath:@"selection.pure.videoType"];
[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];
[searchIndicator release];
[searchController release];
[searchField release];
[activeProfile release];
[chapterEditor release];
[fileNameEditor release];
[fileNameStorage release];
[super dealloc];
}
#pragma mark - private
- (void)updateSearchMenu
{
SearchProfile* profile;
id videoType = [filesController protectedValueForKeyPath:@"selection.pure.videoType"];
MZVideoType vt;
MZTag* tag = [MZTag tagForIdentifier:MZVideoTypeTagIdent];
[tag convertObject:videoType toValue:&vt];
switch (vt) {
case MZMovieVideoType:
if([[activeProfile identifier] isEqual:@"movie"])
profile = [[activeProfile retain] autorelease];
else
profile = [SearchProfile movieProfile];
break;
case MZTVShowVideoType:
if([[activeProfile identifier] isEqual:@"tvShow"])
profile = [[activeProfile retain] autorelease];
else
profile = [SearchProfile tvShowProfile];
break;
default:
if([[activeProfile identifier] isEqual:@"unknown"])
profile = [[activeProfile retain] autorelease];
else
profile = [SearchProfile unknownTypeProfile];
break;
}
/*
if([activeProfile.identifier isEqual:profile.identifier])
return;
*/
[activeProfile removeObserver:self forKeyPath:@"searchTerms"];
[activeProfile release];
activeProfile = [profile retain];
[activeProfile setCheckObject:filesController withPrefix:@"selection.pure."];
[activeProfile addObserver:self forKeyPath:@"searchTerms" options:0 context:NULL];
NSMenu* menu = [[NSMenu alloc] initWithTitle:
NSLocalizedString(@"Search terms", @"Search menu title")];
[menu addItemWithTitle:[menu title] action:nil keyEquivalent:@""];
/*
if([profile mainTag])
{
MZTag* tag = [MZTag tagForIdentifier:[profile mainTag]];
NSMenuItem* mainItem = [menu addItemWithTitle:[tag localizedName] action:NULL keyEquivalent:@""];
[mainItem setState:NSOnState];
[mainItem setIndentationLevel:1];
}
*/
NSInteger i = 0;
for(NSString* tagId in [profile tags])
{
if(![tagId isEqual:MZVideoTypeTagIdent])
{
MZTag* tag = [MZTag tagForIdentifier:tagId];
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:[tag localizedName]
action:@selector(switchItem:) keyEquivalent:@""];
[item setTarget:profile];
[item setTag:i];
[item setState:NSOnState];
[item setIndentationLevel:1];
[menu addItem:item];
[item release];
}
i++;
}
id searchCell = [searchField cell];
[searchCell setSearchMenuTemplate:menu];
[menu release];
NSString* prefix = @"selection.pure.";
id mainValue = @"";
if([profile mainTag])
{
mainValue = [filesController protectedValueForKeyPath:
[prefix stringByAppendingString:[profile mainTag]]];
if(mainValue == nil || mainValue == [NSNull null] || mainValue == NSMultipleValuesMarker ||
mainValue == NSNoSelectionMarker || mainValue == NSNotApplicableMarker)
{
mainValue = @"";
}
}
[searchField setStringValue:mainValue];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"autoSearch"])
{
//[[MZMetaSearcher sharedSearcher] clearResults];
[self startSearch:searchField];
}
}
- (void)registerUndoName:(NSUndoManager *)manager
{
[manager setActionName:NSLocalizedString(@"Apply Search", @"Apply search undo name")];
[manager registerUndoWithTarget:self
selector:@selector(registerUndoName:)
object:manager];
}
#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.pure.videoType"] && object == filesController)
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateSearchMenu) object:nil];
[self performSelector:@selector(updateSearchMenu) withObject:nil afterDelay:0.001];
}
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:@"searchTerms"] && object == activeProfile)
[self startSearch:self];
}
#pragma mark - as MZPluginControllerDelegate
- (id<MetaData>)pluginController:(MZPluginController *)controller
extraMetaDataForProvider:(id<MZDataProvider>)provider
loaded:(MetaLoaded*)loaded
{
return [[[SearchMeta alloc] initWithProvider:loaded controller:searchController] autorelease];
}
#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)startSearch:(id)sender;
{
NSResponder* oldResponder = findResponder(window);
if([filesController commitEditing])
{
NSResponder* currentResponder = findResponder(window);
if(oldResponder != currentResponder)
[window makeFirstResponder:oldResponder];
}
NSString* term = [[searchField stringValue]
stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSMutableDictionary* dict = [activeProfile searchTerms:term];
//[dict setObject:term forKey:[activeProfile mainTag]];
[searchIndicator startAnimation:searchField];
[searchController setSortDescriptors:nil];
searches++;
MZLoggerInfo(@"Starting search %d", searches);
[[MZMetaSearcher sharedSearcher] startSearchWithData:dict];
}
- (IBAction)segmentClicked:(id)sender {
int clickedSegment = [sender selectedSegment];
int clickedSegmentTag = [[sender cell] tagForSegment:clickedSegment];
if(clickedSegmentTag == 0)
[self openDocument:sender];
else
[filesController remove:sender];
}
- (IBAction)selectNextFile:(id)sender {
NSResponder* oldResponder = findResponder(window);
if([filesController commitEditing])
{
NSResponder* currentResponder = findResponder(window);
if(oldResponder != currentResponder)
[window makeFirstResponder:oldResponder];
}
[filesController selectNext:sender];
}
- (IBAction)selectPreviousFile:(id)sender {
NSResponder* oldResponder = findResponder(window);
if([filesController commitEditing])
{
NSResponder* currentResponder = findResponder(window);
if(oldResponder != currentResponder)
[window makeFirstResponder:oldResponder];
}
[filesController selectPrevious:sender];
}
- (IBAction)selectNextResult:(id)sender {
NSResponder* oldResponder = findResponder(window);
if([filesController commitEditing])
{
NSResponder* currentResponder = findResponder(window);
if(oldResponder != currentResponder)
[window makeFirstResponder:oldResponder];
}
[searchController selectNext:sender];
}
- (IBAction)selectPreviousResult:(id)sender {
NSResponder* oldResponder = findResponder(window);
if([filesController commitEditing])
{
NSResponder* currentResponder = findResponder(window);
if(oldResponder != currentResponder)
[window makeFirstResponder:oldResponder];
}
[searchController selectPrevious: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 %d", show, [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
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];
NSArray* extensions = MZUTIFilenameExtension(fileTypes);
for(NSString* ext in extensions)
{
MZLoggerDebug(@"Found extention %@", ext);
}
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setCanChooseFiles:YES];
[oPanel setCanChooseDirectories:NO];
[oPanel beginSheetForDirectory: nil
file: nil
types: extensions
modalForWindow: window
modalDelegate: self
didEndSelector: @selector(openPanelDidEnd:returnCode:contextInfo:)
contextInfo: nil];
}
- (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)applySearchEntry:(id)sender
{
id selection = [searchController valueForKeyPath:@"selection.self"];
if(![selection isKindOfClass:[MZSearchResult class]])
return;
NSDictionary* result = [selection values];
for(NSString* key in [result allKeys])
{
id value = [result objectForKey:key];
if([value isKindOfClass:[MZRemoteData class]])
{
if(![value isLoaded])
return;
}
}
NSArray* edits = [filesController selectedObjects];
for(MetaEdits* edit in edits)
{
[self registerUndoName:edit.undoManager];
}
for(MetaEdits* edit in edits)
{
NSArray* providedTags = [edit providedTags];
for(MZTag* tag in providedTags)
{
if(![edit getterChangedForKey:[tag identifier]])
{
id value = [result objectForKey:[tag identifier]];
if([[tag identifier] isEqual:MZChapterNamesTagIdent])
{
if(value)
{
[chapterEditor setChapterNames:value];
[chapterEditor setChanged:[NSNumber numberWithBool:YES]];
}
}
else
{
if([value isKindOfClass:[MZRemoteData class]])
value = [value data];
if(value)
[edit setterValue:value forKey:[tag identifier]];
}
}
}
[self registerUndoName:edit.undoManager];
}
}
- (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:@"http://metaz.lighthouseapp.com/projects/43700-metaz/tickets/bins/95786"];
[[NSWorkspace sharedWorkspace] openURL:url];
}
- (IBAction)reportIssue:(id)sender
{
NSURL* url = [NSURL URLWithString:@"http://metaz.lighthouseapp.com/projects/43700-metaz/tickets/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(applySearchEntry:))
{
id selection = [searchController protectedValueForKeyPath:@"selection.self"];
if(![selection isKindOfClass:[MZSearchResult class]])
return NO;
NSDictionary* values = [selection values];
for(NSString* key in [values allKeys])
{
id value = [values objectForKey:key];
if([value isKindOfClass:[MZRemoteData class]])
{
if(![value isLoaded])
return NO;
}
}
if(presetsController && [[presetsController window] isKeyWindow])
return NO;
return YES;
}
if(action == @selector(selectNextFile:))
return [filesController canSelectNext];
if(action == @selector(selectPreviousFile:))
return [filesController canSelectPrevious];
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:[MZRemoteData 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)finishedSearch:(NSNotification *)note
{
searches--;
MZLoggerDebug(@"Finished search %d", searches);
if(searches <= 0)
[searchIndicator stopAnimation:self];
}
- (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"];
/*
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:NSWindowWillCloseNotification
object:[note object]];
[presetsController release];
presetsController = nil;
*/
}
- (void)removedEdit:(NSNotification *)note
{
MetaEdits* other = [note object];
[other.undoManager removeAllActionsWithTarget:self];
}
- (void)openPanelDidEnd:(NSOpenPanel *)oPanel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSOKButton)
{
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 {
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];
return [[MZMetaLoader sharedLoader] loadFromFile:filename];
}
- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
[window makeKeyAndOrderFront:sender];
if([[MZMetaLoader sharedLoader] loadFromFiles: filenames])
[sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
else
[sender replyToOpenOrPrint:NSApplicationDelegateReplyCancel];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
BOOL changed = NO;
NSArray* arr = [[MZMetaLoader sharedLoader] files];
int count = [arr count];
for(int i=0; i<count && !changed; i++)
{
MetaEdits* edit = [arr objectAtIndex:i];
changed = [edit changed];
}
int result = NSAlertDefaultReturn;
if(changed)
{
result = NSRunCriticalAlertPanel(
NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil),
NSLocalizedString(@"You have files loaded with unsaved changes. Do you want to quit anyway?", nil),
NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
}
else if([[MZWriteQueue sharedQueue] status] == QueueRunning)
{
result = NSRunCriticalAlertPanel(
NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil),
NSLocalizedString(@"If you quit MetaZ your current jobs will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
}
// Warn if items still in the queue
else if([[[MZWriteQueue sharedQueue] pendingItems] count] > 0)
{
result = NSRunCriticalAlertPanel(
NSLocalizedString(@"Are you sure you want to quit MetaZ?", nil),
NSLocalizedString(@"There are pending jobs in your queue. Do you want to quit anyway?",nil),
NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
}
if( result == NSAlertDefaultReturn )
{
if([[MZWriteQueue sharedQueue] status] == QueueRunning)
{
[[MZWriteQueue sharedQueue] gtm_addObserver:self forKeyPath:@"status" selector:@selector(queueStatusChanged:) userInfo:nil options:0];
[[MZWriteQueue sharedQueue] stop];
return NSTerminateLater;
}
return NSTerminateNow;
}
return NSTerminateCancel;
}
@end