Um, yeah. Started working on this and did some work getting everything on the same...
[MenuTunes.git] / PreferencesController.m
1 #import "PreferencesController.h"
2 #import "MenuTunes.h"
3 #import "HotKeyCenter.h"
4
5 @implementation PreferencesController
6
7 - (id)initWithMenuTunes:(MenuTunes *)tunes;
8 {
9     if ( (self = [super init]) ) {
10         int i;
11         NSImageCell *imgCell = [[[NSImageCell alloc] init] autorelease];
12         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
13         NSString *temp;
14         
15         mt = [tunes retain];
16         
17         //Load the nib
18         [NSBundle loadNibNamed:@"Preferences" owner:self];
19         
20         //Show our window
21         [window setLevel:NSStatusWindowLevel];
22         [window center];
23         [window makeKeyAndOrderFront:nil];
24         
25         //Set the table view cells up
26         [imgCell setImageScaling:NSScaleNone];
27         [[menuTableView tableColumnWithIdentifier:@"submenu"] setDataCell:imgCell];
28         [[allTableView tableColumnWithIdentifier:@"submenu"] setDataCell:imgCell];
29         
30         //Register for drag and drop
31         [menuTableView registerForDraggedTypes:[NSArray arrayWithObjects:@"MenuTableViewPboardType", @"AllTableViewPboardType", nil]];
32         [allTableView registerForDraggedTypes:[NSArray arrayWithObjects:@"MenuTableViewPboardType", @"AllTableViewPboardType", nil]];
33         
34         //Set the list of items you can have.
35         availableItems = [[NSMutableArray alloc] initWithObjects:@"Current Track Info",  @"Upcoming Songs", @"Playlists", @"EQ Presets", @"Play/Pause", @"Next Track", @"Previous Track", @"Fast Forward", @"Rewind", @"<separator>", nil];
36         
37         //Get our preferred menu
38         myItems = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"] mutableCopy];
39         if (myItems == nil)
40         {
41             myItems = [[NSMutableArray alloc] initWithObjects:@"Play/Pause", @"Next Track", @"Previous Track", @"Fast Forward", @"Rewind", @"<separator>", @"Upcoming Songs", @"Playlists", @"EQ Presets", @"<separator>", @"PreferencesÉ", @"Quit", @"<separator>", @"Current Track Info", nil];
42             [[NSUserDefaults standardUserDefaults] setObject:myItems forKey:@"menu"];
43         }
44         
45         //Delete items in the availableItems array that are already part of the menu
46         for (i = 0; i < [myItems count]; i++) {
47             NSString *item = [myItems objectAtIndex:i];
48             if (![item isEqualToString:@"<separator>"])
49             {
50                 [availableItems removeObject:item];
51             }
52         }
53         
54         //Items that show should a submenu image
55         submenuItems = [[NSArray alloc] initWithObjects:@"Upcoming Songs", @"Playlists", @"EQ Presets", nil];
56         
57         //Fill in the number of songs in advance to show field
58         if ([defaults integerForKey:@"SongsInAdvance"]) {
59             [songsInAdvance setIntValue:[defaults integerForKey:@"SongsInAdvance"]];
60         } else {
61             [songsInAdvance setIntValue:5];
62         }
63         
64         //Fill in hot key buttons
65         if ([defaults objectForKey:@"PlayPause"]){
66             playPauseCombo = [defaults keyComboForKey:@"PlayPause"];
67             [playPauseButton setTitle:[playPauseCombo userDisplayRep]];
68         } else {
69             playPauseCombo = [[KeyCombo alloc] init];
70         }
71         
72         if ([defaults objectForKey:@"NextTrack"]) {
73             nextTrackCombo = [defaults keyComboForKey:@"NextTrack"];
74             [nextTrackButton setTitle:[nextTrackCombo userDisplayRep]];
75         } else {
76             nextTrackCombo = [[KeyCombo alloc] init];
77         }
78         
79         if ([defaults objectForKey:@"PrevTrack"]) {
80             prevTrackCombo = [defaults keyComboForKey:@"PrevTrack"];
81             [previousTrackButton setTitle:[prevTrackCombo userDisplayRep]];
82         } else {
83             prevTrackCombo = [[KeyCombo alloc] init];
84         }
85         
86         if ([defaults objectForKey:@"TrackInfo"]) {
87             trackInfoCombo = [defaults keyComboForKey:@"TrackInfo"];
88             [trackInfoButton setTitle:[trackInfoCombo userDisplayRep]];
89         } else {
90             trackInfoCombo = [[KeyCombo alloc] init];
91         }
92         
93         if ([defaults objectForKey:@"UpcomingSongs"]) {
94             upcomingSongsCombo = [defaults keyComboForKey:@"UpcomingSongs"];
95             [upcomingSongsButton setTitle:[upcomingSongsCombo userDisplayRep]];
96         } else {
97             upcomingSongsCombo = [[KeyCombo alloc] init];
98         }
99         
100         //Check current track info buttons
101         
102         //Album and name get special treatment because they are defaults
103         if ( (temp = [defaults stringForKey:@"showAlbum"]) ) {
104             if ((temp == nil) || [temp isEqualToString:@"1"]) {
105                 [albumCheckbox setState:NSOnState];
106             } else {
107                 [albumCheckbox setState:NSOffState];
108             }
109         }
110         
111         if ( (temp = [defaults stringForKey:@"showName"]) ) {
112             if ((temp == nil) || [temp isEqualToString:@"1"]) {
113                 [nameCheckbox setState:NSOnState];
114             } else {
115                 [nameCheckbox setState:NSOffState];
116             }
117         }
118         
119         [artistCheckbox setState:[defaults boolForKey:@"showArtist"] ? NSOnState : NSOffState];
120         [trackTimeCheckbox setState:[defaults boolForKey:@"showTime"] ? NSOnState : NSOffState];
121         
122         //Set the launch at login checkbox state
123         {
124             NSMutableDictionary *loginwindow;
125             NSMutableArray *loginarray;
126             int i;
127             
128             [defaults synchronize];
129             loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
130             loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
131             
132             for (i = 0; i < [loginarray count]; i++) {
133                 NSDictionary *tempDict = [loginarray objectAtIndex:i];
134                 
135                 //Here we are seeing if our program is already in loginwindow.plist.
136                 //See the problem below for this problem here. We will do the same thing.
137                 
138                 if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:@"VocabularyBuilder.app"]) {
139                     [launchAtLoginCheckbox setState:NSOnState];
140                 }
141             }
142         }
143     }
144     return self;
145 }
146
147 - (void)dealloc
148 {
149     [self setKeyCombo:nil];
150     [playPauseCombo release];
151     [nextTrackCombo release];
152     [prevTrackCombo release];
153     [trackInfoCombo release];
154     [upcomingSongsCombo release];
155     [keyComboPanel release];
156     [menuTableView setDataSource:nil];
157     [allTableView setDataSource:nil];
158     [mt release];
159     [availableItems release];
160     [submenuItems release];
161     [myItems release];
162 }
163
164 - (IBAction)apply:(id)sender
165 {
166     ProcessSerialNumber psn;
167     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
168     [defaults setObject:myItems forKey:@"menu"];
169     
170     //Set key combos
171     [defaults setKeyCombo:playPauseCombo forKey:@"PlayPause"];
172     [defaults setKeyCombo:nextTrackCombo forKey:@"NextTrack"];
173     [defaults setKeyCombo:prevTrackCombo forKey:@"PrevTrack"];
174     [defaults setKeyCombo:trackInfoCombo forKey:@"TrackInfo"];
175     [defaults setKeyCombo:upcomingSongsCombo forKey:@"UpcomingSongs"];
176     
177     //Set info checkboxes
178     [defaults setBool:[albumCheckbox state] forKey:@"showAlbum"];
179     [defaults setBool:[nameCheckbox state] forKey:@"showName"];
180     [defaults setBool:[artistCheckbox state] forKey:@"showArtist"];
181     [defaults setBool:[trackTimeCheckbox state] forKey:@"showTime"];
182     
183     //Here we set whether we will launch at login by modifying loginwindow.plist
184     if ([launchAtLoginCheckbox state] == NSOnState) {
185         NSMutableDictionary *loginwindow;
186         NSMutableArray *loginarray;
187         int i;
188         BOOL skip = NO;
189         
190         [defaults synchronize];
191         loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
192         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
193         
194         for (i = 0; i < [loginarray count]; i++) {
195             NSDictionary *tempDict = [loginarray objectAtIndex:i];
196             
197             //Here we are seeing if our program is already in loginwindow.plist.
198             //See the problem below for this problem here. We will do the same thing.
199             
200             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:@"VocabularyBuilder.app"]) {
201                 skip = YES;
202             }
203         }
204         
205         if (!skip) {
206             [loginarray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], @"Hide", [[NSBundle mainBundle] bundlePath], @"Path", nil]];
207             
208             [defaults setPersistentDomain:loginwindow forName:@"loginwindow"];
209             [defaults synchronize];
210         }
211     } else {
212         NSMutableDictionary *loginwindow;
213         NSMutableArray *loginarray;
214         int i;
215         
216         [[NSUserDefaults standardUserDefaults] synchronize];
217         loginwindow = [[[NSUserDefaults standardUserDefaults] persistentDomainForName:@"loginwindow"] mutableCopy];
218         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
219         
220         for (i = 0; i < [loginarray count]; i++) {
221             NSDictionary *tempDict = [loginarray objectAtIndex:i];
222             
223             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:@"VocabularyBuilder.app"]) {
224                 [loginarray removeObjectAtIndex:i];
225                 [defaults setPersistentDomain:loginwindow forName:@"loginwindow"];
226                 [defaults synchronize];
227                 break;
228             }
229         }
230     }
231     
232     //Set songs in advance
233     if ([songsInAdvance intValue]) {
234         [defaults setInteger:[songsInAdvance intValue] forKey:@"SongsInAdvance"];
235     } else {
236         [defaults setInteger:5 forKey:@"SongsInAdvance"];
237     }
238     
239     psn = [mt iTunesPSN];
240     if (!((psn.highLongOfPSN == kNoProcess) && (psn.lowLongOfPSN == 0))) {
241         [mt rebuildMenu];
242     }
243     [mt clearHotKeys];
244 }
245
246 - (IBAction)cancel:(id)sender
247 {
248     [window close];
249     [mt closePreferences];
250 }
251
252 - (IBAction)cancelHotKey:(id)sender
253 {
254     [[NSNotificationCenter defaultCenter] removeObserver:self];
255     [NSApp endSheet:keyComboPanel];
256     [keyComboPanel orderOut:nil];
257 }
258
259 - (IBAction)clearHotKey:(id)sender
260 {
261     [self setKeyCombo:[KeyCombo clearKeyCombo]];
262 }
263
264 - (IBAction)okHotKey:(id)sender
265 {
266     NSString *string;
267     if (([combo modifiers] <= 0) && ([combo keyCode] >= 0)) {
268         [window setLevel:NSNormalWindowLevel];
269         NSRunAlertPanel(@"Bad Key Combo", @"Please enter a valid key combo. A valid combo must have a modifier key in it. (Command, option, shift, control).", @"OK", nil, nil, nil);
270         [window setLevel:NSStatusWindowLevel];
271         return;
272     }
273     
274     string = [combo userDisplayRep];
275     
276     if (string == nil) {
277         string = @"None";
278     }
279     if ([setHotKey isEqualToString:@"PlayPause"]) {
280         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
281             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) &&
282             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
283             
284             [window setLevel:NSNormalWindowLevel];
285             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
286             [window setLevel:NSStatusWindowLevel];
287             return;
288         }
289         playPauseCombo = [combo copy];
290         [playPauseButton setTitle:string];
291     }
292     else if ([setHotKey isEqualToString:@"NextTrack"])
293     {
294         if (([combo isEqual:playPauseCombo] || [combo isEqual:prevTrackCombo] ||
295             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) && 
296             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
297             
298             [window setLevel:NSNormalWindowLevel];
299             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
300             [window setLevel:NSStatusWindowLevel];
301             return;
302         }
303         nextTrackCombo = [combo copy];
304         [nextTrackButton setTitle:string];
305     }
306     else if ([setHotKey isEqualToString:@"PrevTrack"])
307     {
308         if (([combo isEqual:nextTrackCombo] || [combo isEqual:playPauseCombo] ||
309             [combo isEqual:trackInfoCombo] || [combo isEqual:upcomingSongsCombo]) && 
310             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
311             
312             [window setLevel:NSNormalWindowLevel];
313             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
314             [window setLevel:NSStatusWindowLevel];
315             return;
316         }
317         prevTrackCombo = [combo copy];
318         [previousTrackButton setTitle:string];
319     }
320     else if ([setHotKey isEqualToString:@"TrackInfo"])
321     {
322         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
323             [combo isEqual:playPauseCombo] || [combo isEqual:upcomingSongsCombo]) && 
324             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
325             
326             [window setLevel:NSNormalWindowLevel];
327             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
328             [window setLevel:NSStatusWindowLevel];
329             return;
330         }
331         trackInfoCombo = [combo copy];
332         [trackInfoButton setTitle:string];
333     }
334     else if ([setHotKey isEqualToString:@"UpcomingSongs"])
335     {
336         if (([combo isEqual:nextTrackCombo] || [combo isEqual:prevTrackCombo] ||
337             [combo isEqual:trackInfoCombo] || [combo isEqual:playPauseCombo]) && 
338             !(([combo modifiers] == -1) && ([combo keyCode] == -1))) {
339             
340             [window setLevel:NSNormalWindowLevel];
341             NSRunAlertPanel(@"Duplicate Key Combo", @"Please choose a unique key combo.", @"OK", nil, nil, nil);
342             [window setLevel:NSStatusWindowLevel];
343             return;
344         }
345         upcomingSongsCombo = [combo copy];
346         [upcomingSongsButton setTitle:string];
347     }
348     [self cancelHotKey:sender];
349 }
350
351 - (IBAction)save:(id)sender
352 {
353     [self apply:nil];
354     [window close];
355     [mt closePreferences];
356 }
357
358 - (IBAction)setCurrentTrackInfo:(id)sender
359 {
360     [self setKeyCombo:trackInfoCombo];
361     [self setHotKey:@"TrackInfo"];
362 }
363
364 - (IBAction)setNextTrack:(id)sender
365 {
366     [self setKeyCombo:nextTrackCombo];
367     [self setHotKey:@"NextTrack"];
368 }
369
370 - (IBAction)setPlayPause:(id)sender
371 {
372     [self setKeyCombo:playPauseCombo];
373     [self setHotKey:@"PlayPause"];
374 }
375
376 - (IBAction)setPreviousTrack:(id)sender
377 {
378     [self setKeyCombo:prevTrackCombo];
379     [self setHotKey:@"PrevTrack"];
380 }
381
382 - (IBAction)setUpcomingSongs:(id)sender
383 {
384     [self setKeyCombo:upcomingSongsCombo];
385     [self setHotKey:@"UpcomingSongs"];
386 }
387
388 - (void)setHotKey:(NSString *)key
389 {
390     setHotKey = key;
391     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyEvent:) name:@"KeyBroadcasterEvent" object:nil];
392     [NSApp beginSheet:keyComboPanel modalForWindow:window modalDelegate:self didEndSelector:nil contextInfo:nil];
393 }
394
395 - (void)keyEvent:(NSNotification *)note
396 {
397     NSDictionary *info = [note userInfo];
398     short keyCode;
399     long modifiers;
400     KeyCombo *newCombo;
401     
402     keyCode = [[info objectForKey:@"KeyCode"] shortValue];
403     modifiers = [[info objectForKey:@"Modifiers"] longValue];
404     
405     newCombo = [[KeyCombo alloc] initWithKeyCode:keyCode andModifiers:modifiers];
406     [self setKeyCombo:newCombo];
407 }
408
409 - (void)setKeyCombo:(KeyCombo *)newCombo
410 {
411     NSString *string;
412     [combo release];
413     combo = [newCombo copy];
414     
415     string = [combo userDisplayRep];
416     if (string == nil) {
417         string = @"";
418     }
419     [keyComboField setStringValue:string];
420 }
421
422 //
423 //
424 // Text Field Delegate
425 //
426 //
427
428 - (void)controlTextDidChange:(NSNotification *)note
429 {
430     NSLog(@"%@", [note userInfo]);
431 }
432
433 //
434 //
435 // Table View Datasource Methods
436 //
437 //
438
439 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
440 {
441     if (aTableView == menuTableView) {
442         return [myItems count];
443     } else {
444         return [availableItems count];
445     }
446 }
447
448 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
449 {
450     if (aTableView == menuTableView) {
451         if ([[aTableColumn identifier] isEqualToString:@"name"]) {
452             return [myItems objectAtIndex:rowIndex];
453         } else {
454             if ([submenuItems containsObject:[myItems objectAtIndex:rowIndex]])
455             {
456                 return [NSImage imageNamed:@"submenu"];
457             } else {
458                 return nil;
459             }
460         }
461     } else {
462         if ([[aTableColumn identifier] isEqualToString:@"name"]) {
463             return [availableItems objectAtIndex:rowIndex];
464         } else {
465             if ([submenuItems containsObject:[availableItems objectAtIndex:rowIndex]]) {
466                 return [NSImage imageNamed:@"submenu"];
467             } else {
468                 return nil;
469             }
470         }
471     }
472 }
473
474 - (BOOL)tableView:(NSTableView *)tableView writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard
475 {
476     if (tableView == menuTableView) {
477         [pboard declareTypes:[NSArray arrayWithObjects:@"MenuTableViewPboardType", nil] owner:self];
478         [pboard setString:[[rows objectAtIndex:0] stringValue] forType:@"MenuTableViewPboardType"];
479         return YES;
480     }
481     
482     if (tableView == allTableView) {
483         [pboard declareTypes:[NSArray arrayWithObjects:@"AllTableViewPboardType", nil] owner:self];
484         [pboard setString:[[rows objectAtIndex:0] stringValue] forType:@"AllTableViewPboardType"];
485         return YES;
486     }
487     return NO;
488 }
489
490 - (BOOL)tableView:(NSTableView*)tableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation
491 {
492     NSPasteboard *pb;
493     int dragRow;
494     NSString *dragData, *temp;
495     
496     pb = [info draggingPasteboard];
497     
498     if ([[pb types] containsObject:@"MenuTableViewPboardType"]) {
499         dragData = [pb stringForType:@"MenuTableViewPboardType"];
500         dragRow = [dragData intValue];
501         temp = [myItems objectAtIndex:dragRow];
502         [myItems removeObjectAtIndex:dragRow];
503         
504         if (tableView == menuTableView) {
505             if (row > dragRow) {
506                 [myItems insertObject:temp atIndex:row - 1];
507             } else {
508                 [myItems insertObject:temp atIndex:row];
509             }
510         } else {
511             if (![temp isEqualToString:@"<separator>"]) {
512                 [availableItems addObject:temp];
513             }
514         }
515     } else if ([[pb types] containsObject:@"AllTableViewPboardType"]) {
516         dragData = [pb stringForType:@"AllTableViewPboardType"];
517         dragRow = [dragData intValue];
518         temp = [availableItems objectAtIndex:dragRow];
519         
520         if (![temp isEqualToString:@"<separator>"]) {
521             [availableItems removeObjectAtIndex:dragRow];
522         }
523         [myItems insertObject:temp atIndex:row];
524     }
525     
526     [menuTableView reloadData];
527     [allTableView reloadData];
528     return YES;
529 }
530
531 - (NSDragOperation)tableView:(NSTableView*)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)operation
532 {
533     if (tableView == allTableView) {
534         if ([[[info draggingPasteboard] types] containsObject:@"AllTableViewPboardType"]) {
535             return NSDragOperationNone;
536         }
537         
538         if ([[[info draggingPasteboard] types] containsObject:@"MenuTableViewPboardType"]) {
539             NSString *item = [myItems objectAtIndex:[[[info draggingPasteboard] stringForType:@"MenuTableViewPboardType"] intValue]];
540             if ([item isEqualToString:@"PreferencesÉ"] || [item isEqualToString:@"Quit"]) {
541                 return NSDragOperationNone;
542             }
543         }
544         
545         [tableView setDropRow:-1 dropOperation:NSTableViewDropOn];
546         return NSDragOperationGeneric;
547     }
548     
549     if (operation == NSTableViewDropOn || row == -1)
550     {
551         return NSDragOperationNone;
552     }
553     
554     return NSDragOperationGeneric;
555 }
556
557 @end