-
Notifications
You must be signed in to change notification settings - Fork 56
/
AppController.m
644 lines (569 loc) · 21.4 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
//
// 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 "MZMetaSearcher.h"
#import "FakeSearchResult.h"
#import "SearchMeta.h"
#define MaxShortDescription 256
@interface AppController (Private)
- (void)updateSearchMenu;
@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];
}
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 remainingInShortDescription;
#pragma mark - initialization
+ (void)initialize
{
static BOOL initialized = NO;
/* Make sure code only gets executed once. */
if (initialized == YES) return;
initialized = YES;
NSArray* sendTypes = [NSArray arrayWithObjects:NSTIFFPboardType, nil];
NSArray* returnTypes = [NSArray arrayWithObjects:NSTIFFPboardType, nil];
[NSApp registerServicesMenuSendTypes:sendTypes
returnTypes:returnTypes];
NSBundle* bundle = [NSBundle mainBundle];
NSString* dictPath;
if (dictPath = [bundle pathForResource:@"FactorySettings" ofType:@"plist"]) {
NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
[dict release];
}
}
- (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];
[[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];
[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];
[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:
profile = [SearchProfile movieProfile];
break;
case MZTVShowVideoType:
profile = [SearchProfile tvShowProfile];
break;
default:
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];
[self startSearch:searchField];
//[searchField performClick:self];
//[[MZMetaSearcher sharedSearcher] clearResults];
}
#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)
{
[self updateSearchMenu];
}
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 {
[tabView selectTabViewItemWithIdentifier:@"advanced"];
}
- (IBAction)showChapterTab:(id)sender {
[tabView selectTabViewItemWithIdentifier:@"chapters"];
}
- (IBAction)showInfoTab:(id)sender {
[tabView selectTabViewItemWithIdentifier:@"info"];
}
- (IBAction)showSortTab:(id)sender {
[tabView selectTabViewItemWithIdentifier:@"sorting"];
}
- (IBAction)showVideoTab:(id)sender {
[tabView selectTabViewItemWithIdentifier:@"video"];
}
- (IBAction)startSearch:(id)sender;
{
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++;
[[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)revertChanges:(id)sender {
NSDictionary* dict = findBinding(window);
if(dict == nil)
{
NSLog(@"Could not find binding for revert.");
return;
}
id observed = [dict objectForKey:NSObservedObjectKey];
NSString* keyPath = [dict objectForKey:NSObservedKeyPathKey];
[observed setValue:[NSNumber numberWithBool:NO] forKeyPath:[keyPath stringByAppendingString:@"Changed"]];
}
- (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* utis = MZUTIFilenameExtension(fileTypes);
for(NSString* uti in utis)
{
NSLog(@"Found UTI %@", uti);
}
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setCanChooseFiles:YES];
[oPanel setCanChooseDirectories:NO];
[oPanel beginSheetForDirectory: nil
file: nil
types: fileTypes
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]];
[[presetsController window] setFrameUsingName:@"presetsPanel"];
[presetsController showWindow:self];
}
else
{
[presetsController retain];
[presetsController close];
[presetsController release];
}
}
#pragma mark - user interface validation
- (BOOL)validateUserInterfaceItem:(id < NSValidatedUserInterfaceItem >)anItem {
SEL action = [anItem action];
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];
return changed;
}
else
return NO;
}
if(action == @selector(showImageEditor:))
{
id value = [filesController protectedValueForKeyPath:@"selection.picture"];
return [value isKindOfClass:[NSData 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--;
NSLog(@"Finished search");
if(searches <= 0)
[searchIndicator stopAnimation:self];
}
- (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)openPanelDidEnd:(NSOpenPanel *)oPanel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSOKButton)
[[MZMetaLoader sharedLoader] loadFromFiles: [oPanel filenames]];
}
#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;
}
#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 *)theApplication openFile:(NSString *)filename
{
return [[MZMetaLoader sharedLoader] loadFromFile:filename];
}
- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
if([[MZMetaLoader sharedLoader] loadFromFiles: filenames])
[sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
else
[sender replyToOpenOrPrint:NSApplicationDelegateReplyCancel];
}
@end