Icon swap
[MenuTunes.git] / PreferencesController.m
1 #import "PreferencesController.h"
2 #import "MainController.h"
3 #import "HotKeyCenter.h"
4
5 /*************************************************************************/
6 #pragma mark -
7 #pragma mark PRIVATE INTERFACE
8 /*************************************************************************/
9
10 @interface PreferencesController (Private)
11 - (void)setupWindow;
12 - (void)setupCustomizationTables;
13 - (void)setupMenuItems;
14 - (void)setupUI;
15 @end
16
17
18 @implementation PreferencesController
19
20
21 /*************************************************************************/
22 #pragma mark -
23 #pragma mark STATIC VARIABLES
24 /*************************************************************************/
25
26 static PreferencesController *prefs = nil;
27
28
29 /*************************************************************************/
30 #pragma mark -
31 #pragma mark INITIALIZATION METHODS
32 /*************************************************************************/
33
34 + (PreferencesController *)sharedPrefs;
35 {
36     if (! prefs) {
37         prefs = [[self alloc] init];
38     }
39     return prefs;
40 }
41
42 - (id)init
43 {
44     if ( (self = [super init]) ) {
45         df = [[NSUserDefaults standardUserDefaults] retain];
46         controller = nil;
47     }
48     return self;
49 }
50
51
52 /*************************************************************************/
53 #pragma mark -
54 #pragma mark ACCESSOR METHODS
55 /*************************************************************************/
56
57 - (id)controller
58 {
59     return controller;
60 }
61
62 - (void)setController:(id)object
63 {
64 NSLog(@"foo");
65     [controller autorelease];
66     controller = [object retain];
67 NSLog(@"bar");
68 }
69
70
71 /*************************************************************************/
72 #pragma mark -
73 #pragma mark INSTANCE METHODS
74 /*************************************************************************/
75
76
77 - (IBAction)showPrefsWindow:(id)sender
78 {
79     if (! window) {  // If window does not exist yet, then the nib hasn't been loaded.
80         [self setupWindow];  // Load in the nib, and perform any initial setup.
81         [self setupCustomizationTables];  // Setup the DnD manu config tables.
82         [self setupMenuItems];  // Setup the arrays of menu items
83         [self setupUI]; // Sets up additional UI
84         [window setDelegate:self];
85     }
86     
87     [window setLevel:NSStatusWindowLevel];
88     [window center];
89     [window makeKeyAndOrderFront:self];
90     [NSApp activateIgnoringOtherApps:YES];
91 }
92
93 - (IBAction)apply:(id)sender
94 {
95     [df setObject:myItems forKey:@"menu"];
96     
97     //Set key combos
98     [df setKeyCombo:playPauseCombo forKey:@"PlayPause"];
99     [df setKeyCombo:nextTrackCombo forKey:@"NextTrack"];
100     [df setKeyCombo:prevTrackCombo forKey:@"PrevTrack"];
101     [df setKeyCombo:trackInfoCombo forKey:@"TrackInfo"];
102     [df setKeyCombo:upcomingSongsCombo forKey:@"UpcomingSongs"];
103     
104     //Set info checkboxes
105     [df setBool:[albumCheckbox state] forKey:@"showAlbum"];
106     [df setBool:[nameCheckbox state] forKey:@"showName"];
107     [df setBool:[artistCheckbox state] forKey:@"showArtist"];
108     [df setBool:[trackTimeCheckbox state] forKey:@"showTime"];
109     
110     //Here we set whether we will launch at login by modifying loginwindow.plist
111     if ([launchAtLoginCheckbox state] == NSOnState) {
112         NSMutableDictionary *loginwindow;
113         NSMutableArray *loginarray;
114         ComponentInstance temp = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);;
115         int i;
116         BOOL skip = NO;
117         
118         [df synchronize];
119         loginwindow = [[df persistentDomainForName:@"loginwindow"] mutableCopy];
120         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
121         
122         for (i = 0; i < [loginarray count]; i++) {
123             NSDictionary *tempDict = [loginarray objectAtIndex:i];
124             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
125                 skip = YES;
126             }
127         }
128         
129         if (!skip) {
130             AEDesc scriptDesc, resultDesc;
131             NSString *script = [NSString stringWithFormat:@"tell application \"System Events\"\nmake new login item at end of login items with properties {path:\"%@\", kind:\"APPLICATION\"}\nend tell", [[NSBundle mainBundle] bundlePath]];
132             
133             AECreateDesc(typeChar, [script cString], [script cStringLength], 
134         &scriptDesc);
135             
136             OSADoScript(temp, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
137             
138             AEDisposeDesc(&scriptDesc);
139             AEDisposeDesc(&resultDesc);
140             CloseComponent(temp);
141         }
142     } else {
143         NSMutableDictionary *loginwindow;
144         NSMutableArray *loginarray;
145         int i;
146         
147         [df synchronize];
148         loginwindow = [[df persistentDomainForName:@"loginwindow"] mutableCopy];
149         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
150         
151         for (i = 0; i < [loginarray count]; i++) {
152             NSDictionary *tempDict = [loginarray objectAtIndex:i];
153             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
154                 [loginarray removeObjectAtIndex:i];
155                 [df setPersistentDomain:loginwindow forName:@"loginwindow"];
156                 [df synchronize];
157                 break;
158             }
159         }
160     }
161     
162     //Set songs in advance
163     if ([songsInAdvance intValue]) {
164         [df setInteger:[songsInAdvance intValue] forKey:@"SongsInAdvance"];
165     } else {
166         [df setInteger:5 forKey:@"SongsInAdvance"];
167     }
168     
169     /*{
170         NSArray *apps = [[NSWorkspace sharedWorkspace] launchedApplications];
171         int i;
172         
173         for (i = 0; i < [apps count]; i++) {
174             if ([[[apps objectAtIndex:i] objectForKey:@"NSApplicationName"]
175                     isEqualToString:@"iTunes"]) {
176                 [controller rebuildMenu];
177             }
178         }
179     }*/
180     [controller clearHotKeys];
181 }
182
183 - (IBAction)cancelHotKey:(id)sender
184 {
185     [[NSNotificationCenter defaultCenter] removeObserver:self];
186     [NSApp endSheet:keyComboPanel];
187     [keyComboPanel orderOut:nil];
188 }
189
190 - (IBAction)clearHotKey:(id)sender
191 {
192     [self setKeyCombo:[KeyCombo clearKeyCombo]];
193 }
194
195 - (IBAction)okHotKey:(id)sender
196 {
197     NSString *string = [combo userDisplayRep];
198     
199     if (string == nil) {
200         string = @"";
201     }
202     if ([setHotKey isEqualToString:@"PlayPause"]) {
203         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
204             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) &&
205             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
206             
207             [window setLevel:NSNormalWindowLevel];
208             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
209             [window setLevel:NSStatusWindowLevel];
210             return;
211         }
212         playPauseCombo = [combo copy];
213         [playPauseButton setTitle:string];
214     } else if ([setHotKey isEqualToString:@"NextTrack"]) {
215         if (([combo isEqual:playPauseCombo] || [combo isEqual:prevTrackCombo] ||
216             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) && 
217             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
218             
219             [window setLevel:NSNormalWindowLevel];
220             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
221             [window setLevel:NSStatusWindowLevel];
222             return;
223         }
224         nextTrackCombo = [combo copy];
225         [nextTrackButton setTitle:string];
226     } else if ([setHotKey isEqualToString:@"PrevTrack"]) {
227         if (([combo isEqual:nextTrackCombo] || [combo isEqual:playPauseCombo] ||
228             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) && 
229             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
230             
231             [window setLevel:NSNormalWindowLevel];
232             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
233             [window setLevel:NSStatusWindowLevel];
234             return;
235         }
236         prevTrackCombo = [combo copy];
237         [previousTrackButton setTitle:string];
238     } else if ([setHotKey isEqualToString:@"TrackInfo"]) {
239         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
240             [combo isEqual:playPauseCombo] || [combo isEqual:upcomingSongsCombo]) && 
241             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
242             
243             [window setLevel:NSNormalWindowLevel];
244             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
245             [window setLevel:NSStatusWindowLevel];
246             return;
247         }
248         trackInfoCombo = [combo copy];
249         [trackInfoButton setTitle:string];
250     } else if ([setHotKey isEqualToString:@"UpcomingSongs"]) {
251         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
252             [combo isEqual:trackInfoCombo] || [combo isEqual:playPauseCombo]) && 
253             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
254             
255             [window setLevel:NSNormalWindowLevel];
256             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
257             [window setLevel:NSStatusWindowLevel];
258             return;
259         }
260         upcomingSongsCombo = [combo copy];
261         [upcomingSongsButton setTitle:string];
262     }
263     [self cancelHotKey:sender];
264 }
265
266 - (IBAction)setCurrentTrackInfo:(id)sender
267 {
268     [self setKeyCombo:trackInfoCombo];
269     [self setHotKey:@"TrackInfo"];
270 }
271
272 - (IBAction)setNextTrack:(id)sender
273 {
274     [self setKeyCombo:nextTrackCombo];
275     [self setHotKey:@"NextTrack"];
276 }
277
278 - (IBAction)setPlayPause:(id)sender
279 {
280     [self setKeyCombo:playPauseCombo];
281     [self setHotKey:@"PlayPause"];
282 }
283
284 - (IBAction)setPreviousTrack:(id)sender
285 {
286     [self setKeyCombo:prevTrackCombo];
287     [self setHotKey:@"PrevTrack"];
288 }
289
290 - (IBAction)setUpcomingSongs:(id)sender
291 {
292     [self setKeyCombo:upcomingSongsCombo];
293     [self setHotKey:@"UpcomingSongs"];
294 }
295
296
297 /*************************************************************************/
298 #pragma mark -
299 #pragma mark HOTKEY SUPPORT METHODS
300 /*************************************************************************/
301
302 - (void)setHotKey:(NSString *)key
303 {
304     setHotKey = key;
305     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyEvent:) name:@"KeyBroadcasterEvent" object:nil];
306     [NSApp beginSheet:keyComboPanel modalForWindow:window modalDelegate:self didEndSelector:nil contextInfo:nil];
307 }
308
309 - (void)keyEvent:(NSNotification *)note
310 {
311     NSDictionary *info = [note userInfo];
312     short keyCode;
313     long modifiers;
314     KeyCombo *newCombo;
315     
316     keyCode = [[info objectForKey:@"KeyCode"] shortValue];
317     modifiers = [[info objectForKey:@"Modifiers"] longValue];
318     
319     newCombo = [[KeyCombo alloc] initWithKeyCode:keyCode andModifiers:modifiers];
320     [self setKeyCombo:newCombo];
321 }
322
323 - (void)setKeyCombo:(KeyCombo *)newCombo
324 {
325     NSString *string;
326     [combo release];
327     combo = [newCombo copy];
328     
329     string = [combo userDisplayRep];
330     if (string == nil) {
331         string = @"";
332     }
333     [keyComboField setStringValue:string];
334 }
335
336
337 /*************************************************************************/
338 #pragma mark -
339 #pragma mark PRIVATE METHOD IMPLEMENTATIONS
340 /*************************************************************************/
341
342 - (void)setupWindow
343 {
344     if ( ! [NSBundle loadNibNamed:@"Preferences" owner:self] ) {
345         NSLog( @"Failed to load Preferences.nib" );
346         NSBeep();
347         return;
348     }
349 }
350
351 - (void)setupCustomizationTables
352 {
353     NSImageCell *imgCell = [[[NSImageCell alloc] initImageCell:nil] autorelease];
354     
355     // Set the table view cells up
356     [imgCell setImageScaling:NSScaleNone];
357     [[menuTableView tableColumnWithIdentifier:@"submenu"] setDataCell:imgCell];
358     [[allTableView tableColumnWithIdentifier:@"submenu"] setDataCell:imgCell];
359
360     // Register for drag and drop
361     [menuTableView registerForDraggedTypes:[NSArray arrayWithObjects:
362         @"MenuTableViewPboardType",
363         @"AllTableViewPboardType",
364         nil]];
365     [allTableView registerForDraggedTypes:[NSArray arrayWithObjects:
366         @"MenuTableViewPboardType",
367         @"AllTableViewPboardType",
368         nil]];
369 }
370
371 - (void)setupMenuItems
372 {
373     NSEnumerator *itemEnum;
374     id            anItem;
375     // Set the list of items you can have.
376     availableItems = [[NSMutableArray alloc] initWithObjects:
377         @"Current Track Info",
378         @"Upcoming Songs",
379         @"Playlists",
380         @"EQ Presets",
381         @"Song Rating",
382         @"Play/Pause",
383         @"Next Track",
384         @"Previous Track",
385         @"Fast Forward",
386         @"Rewind",
387         @"<separator>",
388         nil];
389     
390     // Get our preferred menu
391     myItems = [[df arrayForKey:@"menu"] mutableCopy];
392     
393     // Delete items in the availableItems array that are already part of the menu
394     itemEnum = [myItems objectEnumerator];
395     while ( (anItem = [itemEnum nextObject]) ) {
396         if ( ! [anItem isEqualToString:@"<separator>"] ) {
397             [availableItems removeObject:anItem];
398         }
399     }
400     
401     // Items that show should a submenu image
402     submenuItems = [[NSArray alloc] initWithObjects:
403         @"Upcoming Songs",
404         @"Playlists",
405         @"EQ Presets",
406         @"Song Rating",
407         nil];
408 }
409
410 - (void)setupUI
411 {
412     NSMutableDictionary *loginwindow;
413     NSMutableArray *loginarray;
414     NSEnumerator *loginEnum;
415     id anItem;
416
417     // Fill in the number of songs in advance to show field
418     [songsInAdvance setIntValue:[df integerForKey:@"SongsInAdvance"]];
419     
420     // Fill in hot key buttons
421     if ([df objectForKey:@"PlayPause"]){
422         playPauseCombo = [df keyComboForKey:@"PlayPause"];
423         [playPauseButton setTitle:[playPauseCombo userDisplayRep]];
424     } else {
425         playPauseCombo = [[KeyCombo alloc] init];
426     }
427
428     if ([df objectForKey:@"NextTrack"]) {
429         nextTrackCombo = [df keyComboForKey:@"NextTrack"];
430         [nextTrackButton setTitle:[nextTrackCombo userDisplayRep]];
431     } else {
432         nextTrackCombo = [[KeyCombo alloc] init];
433     }
434
435     if ([df objectForKey:@"PrevTrack"]) {
436         prevTrackCombo = [df keyComboForKey:@"PrevTrack"];
437         [previousTrackButton setTitle:[prevTrackCombo userDisplayRep]];
438     } else {
439         prevTrackCombo = [[KeyCombo alloc] init];
440     }
441
442     if ([df objectForKey:@"TrackInfo"]) {
443         trackInfoCombo = [df keyComboForKey:@"TrackInfo"];
444         [trackInfoButton setTitle:[trackInfoCombo userDisplayRep]];
445     } else {
446         trackInfoCombo = [[KeyCombo alloc] init];
447     }
448
449     if ([df objectForKey:@"UpcomingSongs"]) {
450         upcomingSongsCombo = [df keyComboForKey:@"UpcomingSongs"];
451         [upcomingSongsButton setTitle:[upcomingSongsCombo userDisplayRep]];
452     } else {
453         upcomingSongsCombo = [[KeyCombo alloc] init];
454     }
455     
456     // Check current track info buttons
457     [albumCheckbox setState:[df boolForKey:@"showAlbum"] ? NSOnState : NSOffState];
458     [nameCheckbox setState:[df boolForKey:@"showName"] ? NSOnState : NSOffState];
459     [artistCheckbox setState:[df boolForKey:@"showArtist"] ? NSOnState : NSOffState];
460     [trackTimeCheckbox setState:[df boolForKey:@"showTime"] ? NSOnState : NSOffState];
461     
462     // Set the launch at login checkbox state
463     [df synchronize];
464     loginwindow = [[df persistentDomainForName:@"loginwindow"] mutableCopy];
465     loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
466
467     loginEnum = [loginarray objectEnumerator];
468     while ( (anItem = [loginEnum nextObject]) ) {
469         if ([[[anItem objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
470             [launchAtLoginCheckbox setState:NSOnState];
471         }
472     }
473 }
474
475
476 /*************************************************************************/
477 #pragma mark -
478 #pragma mark NSWindow DELEGATE METHODS
479 /*************************************************************************/
480
481 - (void)windowWillClose:(NSNotification *)note
482 {
483     [(MainController *)controller closePreferences]; 
484 }
485
486
487 /*************************************************************************/
488 #pragma mark -
489 #pragma mark NSTableView DATASOURCE METHODS
490 /*************************************************************************/
491
492 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
493 {
494     if (aTableView == menuTableView) {
495         return [myItems count];
496     } else {
497         return [availableItems count];
498     }
499 }
500
501 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
502 {
503     if (aTableView == menuTableView) {
504         if ([[aTableColumn identifier] isEqualToString:@"name"]) {
505             return [myItems objectAtIndex:rowIndex];
506         } else {
507             if ([submenuItems containsObject:[myItems objectAtIndex:rowIndex]])
508             {
509                 return [NSImage imageNamed:@"submenu"];
510             } else {
511                 return nil;
512             }
513         }
514     } else {
515         if ([[aTableColumn identifier] isEqualToString:@"name"]) {
516             return [availableItems objectAtIndex:rowIndex];
517         } else {
518             if ([submenuItems containsObject:[availableItems objectAtIndex:rowIndex]]) {
519                 return [NSImage imageNamed:@"submenu"];
520             } else {
521                 return nil;
522             }
523         }
524     }
525 }
526
527 - (BOOL)tableView:(NSTableView *)tableView writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard
528 {
529     if (tableView == menuTableView) {
530         [pboard declareTypes:[NSArray arrayWithObjects:@"MenuTableViewPboardType", nil] owner:self];
531         [pboard setString:[[rows objectAtIndex:0] stringValue] forType:@"MenuTableViewPboardType"];
532         return YES;
533     }
534     
535     if (tableView == allTableView) {
536         [pboard declareTypes:[NSArray arrayWithObjects:@"AllTableViewPboardType", nil] owner:self];
537         [pboard setString:[[rows objectAtIndex:0] stringValue] forType:@"AllTableViewPboardType"];
538         return YES;
539     }
540     return NO;
541 }
542
543 - (BOOL)tableView:(NSTableView*)tableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation
544 {
545     NSPasteboard *pb;
546     int dragRow;
547     NSString *dragData, *temp;
548     
549     pb = [info draggingPasteboard];
550     
551     if ([[pb types] containsObject:@"MenuTableViewPboardType"]) {
552         dragData = [pb stringForType:@"MenuTableViewPboardType"];
553         dragRow = [dragData intValue];
554         temp = [myItems objectAtIndex:dragRow];
555         [myItems removeObjectAtIndex:dragRow];
556         
557         if (tableView == menuTableView) {
558             if (row > dragRow) {
559                 [myItems insertObject:temp atIndex:row - 1];
560             } else {
561                 [myItems insertObject:temp atIndex:row];
562             }
563         } else {
564             if (![temp isEqualToString:@"<separator>"]) {
565                 [availableItems addObject:temp];
566             }
567         }
568     } else if ([[pb types] containsObject:@"AllTableViewPboardType"]) {
569         dragData = [pb stringForType:@"AllTableViewPboardType"];
570         dragRow = [dragData intValue];
571         temp = [availableItems objectAtIndex:dragRow];
572         
573         if (![temp isEqualToString:@"<separator>"]) {
574             [availableItems removeObjectAtIndex:dragRow];
575         }
576         [myItems insertObject:temp atIndex:row];
577     }
578     
579     [menuTableView reloadData];
580     [allTableView reloadData];
581     return YES;
582 }
583
584 - (NSDragOperation)tableView:(NSTableView*)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)operation
585 {
586     if (tableView == allTableView) {
587         if ([[[info draggingPasteboard] types] containsObject:@"AllTableViewPboardType"]) {
588             return NSDragOperationNone;
589         }
590         
591         if ([[[info draggingPasteboard] types] containsObject:@"MenuTableViewPboardType"]) {
592             NSString *item = [myItems objectAtIndex:[[[info draggingPasteboard] stringForType:@"MenuTableViewPboardType"] intValue]];
593             if ([item isEqualToString:@"PreferencesÉ"] || [item isEqualToString:@"Quit"]) {
594                 return NSDragOperationNone;
595             }
596         }
597         
598         [tableView setDropRow:-1 dropOperation:NSTableViewDropOn];
599         return NSDragOperationGeneric;
600     }
601     
602     if (operation == NSTableViewDropOn || row == -1)
603     {
604         return NSDragOperationNone;
605     }
606     
607     return NSDragOperationGeneric;
608 }
609
610
611 /*************************************************************************/
612 #pragma mark -
613 #pragma mark DEALLOCATION METHODS
614 /*************************************************************************/
615
616 - (void)dealloc
617 {
618     [self setKeyCombo:nil];
619     [playPauseCombo release];
620     [nextTrackCombo release];
621     [prevTrackCombo release];
622     [trackInfoCombo release];
623     [upcomingSongsCombo release];
624     [keyComboPanel release];
625     [menuTableView setDataSource:nil];
626     [allTableView setDataSource:nil];
627     [controller release];
628     [availableItems release];
629     [submenuItems release];
630     [myItems release];
631     [df release];
632 }
633
634
635 @end