Added a commented-out line, template for when making builds for beta testers.
[MenuTunes.git] / MenuTunes.m
1 /*
2 Things to do:
3 ¥ Make preferences window pretty
4 ¥ Hot Keys
5     - hot keys can't be set when NSBGOnly is on. The window is not key,
6       so the KeyBroadcaster does not pick up key combos
7     - going to need a different way of defining key combos
8 ¥ Optimize
9 ¥ Apple Events! Apple Events! Apple Events!
10 */
11
12 #import "MenuTunes.h"
13 // #import "MenuTunesView.h"
14 #import "PreferencesController.h"
15 #import "HotKeyCenter.h"
16 #import "StatusWindowController.h"
17
18 @interface MenuTunes(Private)
19 - (void)registerDefaultsIfNeeded;
20 - (void)updateMenu;
21 - (void)rebuildUpcomingSongsMenu;
22 - (void)rebuildPlaylistMenu;
23 - (void)rebuildEQPresetsMenu;
24 - (void)setupHotKeys;
25 - (NSString *)runScriptAndReturnResult:(NSString *)script;
26 - (void)timerUpdate;
27 - (void)sendAEWithEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID;
28
29 @end
30
31 @implementation MenuTunes
32
33 /*************************************************************************/
34 #pragma mark -
35 #pragma mark INITIALIZATION METHODS
36 /*************************************************************************/
37
38 - (void)applicationDidFinishLaunching:(NSNotification *)note
39 {
40     asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
41
42     [self registerDefaultsIfNeeded];
43     
44     menu = [[NSMenu alloc] initWithTitle:@""];
45     iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
46     
47     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
48     {
49         [self rebuildMenu];
50         refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
51                                                         target:self
52                                                       selector:@selector(timerUpdate)
53                                                       userInfo:nil
54                                                        repeats:YES];
55     }
56     else
57     {
58         menu = [[NSMenu alloc] initWithTitle:@""];
59         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
60         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
61         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
62         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
63         refreshTimer = nil;
64     }
65     
66     statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
67     [[[statusItem _button] cell] setType:NSNullCellType];
68     [statusItem setImage:[NSImage imageNamed:@"menu"]];
69     [[statusItem _button] setAlternateImage:[NSImage imageNamed:@"selected_image"]];
70     [statusItem setHighlightMode:YES];
71     [statusItem setMenu:menu];
72     // Below line of code is for creating builds for Beta Testers
73     // [statusItem setToolTip:@"This Nontransferable Beta (Built on __DATE__) of iThink Software's MenuTunes is Registered to: Beta Tester (betatester@somedomain.com)."];
74     [statusItem retain];
75 //  view = [[MenuTunesView alloc] initWithFrame:[[statusItem view] frame]];
76 //  [statusItem setView:view];
77 }
78
79
80 /*************************************************************************/
81 #pragma mark -
82 #pragma mark INSTANCE METHODS
83 /*************************************************************************/
84
85 - (void)registerDefaultsIfNeeded
86 {
87     if (![[NSUserDefaults standardUserDefaults] objectForKey:@"menu"]) {
88         [[NSUserDefaults standardUserDefaults] setObject:
89             [NSArray arrayWithObjects:
90                 @"Play/Pause",
91                 @"Next Track",
92                 @"Previous Track",
93                 @"Fast Forward",
94                 @"Rewind",
95                 @"<separator>",
96                 @"Upcoming Songs",
97                 @"Playlists",
98                 @"<separator>",
99                 @"PreferencesÉ",
100                 @"Quit",
101                 @"<separator>",
102                 @"Current Track Info",
103                 nil] forKey:@"menu"];
104     }
105 }
106
107 //Recreate the status item menu
108 - (void)rebuildMenu
109 {
110     NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
111     int i;
112     
113     trackInfoIndex = -1;
114     didHaveAlbumName = ([[self runScriptAndReturnResult:@"return album of current track"] length] > 0);
115
116     while ([menu numberOfItems] > 0) {
117         [menu removeItemAtIndex:0];
118     }
119     
120     playPauseMenuItem = nil;
121     upcomingSongsItem = nil;
122     playlistItem = nil;
123     [playlistMenu release];
124     playlistMenu = nil;
125     eqItem = nil;
126     [eqMenu release];
127     eqMenu = nil;
128     
129     for (i = 0; i < [myMenu count]; i++) {
130         NSString *item = [myMenu objectAtIndex:i];
131         if ([item isEqualToString:@"Play/Pause"]) {
132             playPauseMenuItem = [menu addItemWithTitle:@"Play"
133                                                 action:@selector(playPause:)
134                                          keyEquivalent:@""];
135             [playPauseMenuItem setTarget:self];
136         } else if ([item isEqualToString:@"Next Track"]) {
137             [[menu addItemWithTitle:@"Next Track"
138                              action:@selector(nextSong:)
139                       keyEquivalent:@""] setTarget:self];
140         } else if ([item isEqualToString:@"Previous Track"]) {
141             [[menu addItemWithTitle:@"Previous Track"
142                              action:@selector(prevSong:)
143                       keyEquivalent:@""] setTarget:self];
144         } else if ([item isEqualToString:@"Fast Forward"]) {
145             [[menu addItemWithTitle:@"Fast Forward"
146                              action:@selector(fastForward:)
147                       keyEquivalent:@""] setTarget:self];
148         } else if ([item isEqualToString:@"Rewind"]) {
149             [[menu addItemWithTitle:@"Rewind"
150                              action:@selector(rewind:)
151                       keyEquivalent:@""] setTarget:self];
152         } else if ([item isEqualToString:@"Upcoming Songs"]) {
153             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
154                                                 action:nil
155                                          keyEquivalent:@""];
156         } else if ([item isEqualToString:@"Playlists"]) {
157             playlistItem = [menu addItemWithTitle:@"Playlists"
158                                            action:nil
159                                     keyEquivalent:@""];
160         } else if ([item isEqualToString:@"EQ Presets"]) {
161             eqItem = [menu addItemWithTitle:@"EQ Presets"
162                                      action:nil
163                               keyEquivalent:@""];
164         } else if ([item isEqualToString:@"PreferencesÉ"]) {
165             [[menu addItemWithTitle:@"PreferencesÉ"
166                              action:@selector(showPreferences:)
167                       keyEquivalent:@""] setTarget:self];
168         } else if ([item isEqualToString:@"Quit"]) {
169             [[menu addItemWithTitle:@"Quit"
170                              action:@selector(quitMenuTunes:)
171                       keyEquivalent:@""] setTarget:self];
172         } else if ([item isEqualToString:@"Current Track Info"]) {
173             trackInfoIndex = [menu numberOfItems];
174             [menu addItemWithTitle:@"No Song"
175                             action:nil
176                      keyEquivalent:@""];
177         } else if ([item isEqualToString:@"<separator>"]) {
178             [menu addItem:[NSMenuItem separatorItem]];
179         }
180     }
181     
182     curTrackIndex = -1; //Force update of everything
183     [self timerUpdate]; //Updates dynamic info in the menu
184     
185     [self clearHotKeys];
186     [self setupHotKeys];
187 }
188
189 //Updates the menu with current player state, song, and upcoming songs
190 - (void)updateMenu
191 {
192     NSString *curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
193     NSMenuItem *menuItem;
194     if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
195         return;
196     }
197     
198     if (upcomingSongsItem) {
199         [self rebuildUpcomingSongsMenu];
200     }
201     if (playlistItem) {
202         [self rebuildPlaylistMenu];
203     }
204     if (eqItem) {
205         [self rebuildEQPresetsMenu];
206     }
207     
208     if (trackInfoIndex > -1)
209     {
210         NSString *curSongName;
211         curSongName = [self runScriptAndReturnResult:@"return name of current track"];
212         if ([curSongName length] > 0) {
213             int index = [menu indexOfItemWithTitle:@"Now Playing"];
214             
215             if (index > -1) {
216                 [menu removeItemAtIndex:index + 1];
217                 if (didHaveAlbumName) {
218                     [menu removeItemAtIndex:index + 1];
219                 }
220             }
221             if (!isPlayingRadio) {
222                 if ([curAlbumName length] > 0) {
223                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName]
224                                                         action:nil
225                                                         keyEquivalent:@""];
226                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
227                     [menuItem release];
228                 }
229             }
230             menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
231                                                 action:nil
232                                                 keyEquivalent:@""];
233             [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
234             [menuItem release];
235             
236             if (index == -1) {
237                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
238                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
239                 [menu insertItem:menuItem atIndex:trackInfoIndex];
240                 [menuItem release];
241             }
242             
243         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
244             [menu removeItemAtIndex:trackInfoIndex];
245             [menu removeItemAtIndex:trackInfoIndex];
246             
247             if (didHaveAlbumName) {
248                 [menu removeItemAtIndex:trackInfoIndex];
249             }
250             
251             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
252             [menu insertItem:menuItem atIndex:trackInfoIndex];
253             [menuItem release];
254         }
255     }
256     didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
257 }
258
259 //Rebuild the upcoming songs submenu. Can be improved a lot.
260 - (void)rebuildUpcomingSongsMenu
261 {
262     int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
263     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
264     if (!isPlayingRadio) {
265         if (numSongs > 0) {
266             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
267             int i;
268             
269             [upcomingSongsMenu release];
270             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
271             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
272             [upcomingSongsItem setEnabled:YES];
273             
274             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
275                 if (i <= numSongs) {
276                     NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
277                     NSMenuItem *songItem;
278                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
279                     [songItem setTarget:self];
280                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
281                     [upcomingSongsMenu addItem:songItem];
282                     [songItem release];
283                 } else {
284                     break;
285                 }
286             }
287         }
288     } else {
289         [upcomingSongsItem setSubmenu:nil];
290         [upcomingSongsItem setEnabled:NO];
291     }
292 }
293
294 - (void)rebuildPlaylistMenu
295 {
296     int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
297     int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
298     
299     if (isPlayingRadio)
300     {
301         curPlaylist = 0;
302     }
303     
304     if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
305         return;
306     
307     [playlistMenu release];
308     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
309     
310     for (i = 1; i <= numPlaylists; i++) {
311         NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
312         NSMenuItem *tempItem;
313         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
314         [tempItem setTarget:self];
315         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
316         [playlistMenu addItem:tempItem];
317         [tempItem release];
318     }
319     [playlistItem setSubmenu:playlistMenu];
320     
321     if (curPlaylist) {
322         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
323     }
324 }
325
326 //Build a menu with the list of all available EQ presets
327 - (void)rebuildEQPresetsMenu
328 {
329     int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
330     int i;
331     
332     if (eqMenu && (numSets == [eqMenu numberOfItems]))
333         return;
334     
335     [eqMenu release];
336     eqMenu = [[NSMenu alloc] initWithTitle:@""];
337     
338     for (i = 1; i <= numSets; i++) {
339         NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
340         NSMenuItem *tempItem;
341         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
342         [tempItem setTarget:self];
343         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
344         [eqMenu addItem:tempItem];
345         [tempItem release];
346     }
347     [eqItem setSubmenu:eqMenu];
348     
349     [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
350 }
351
352 - (void)clearHotKeys
353 {
354     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
355     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
356     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
357     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
358     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
359 }
360
361 - (void)setupHotKeys
362 {
363     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
364     
365     if ([defaults objectForKey:@"PlayPause"] != nil) {
366         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
367                 combo:[defaults keyComboForKey:@"PlayPause"]
368                 target:self action:@selector(playPause:)];
369     }
370     
371     if ([defaults objectForKey:@"NextTrack"] != nil) {
372         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
373                 combo:[defaults keyComboForKey:@"NextTrack"]
374                 target:self action:@selector(nextSong:)];
375     }
376     
377     if ([defaults objectForKey:@"PrevTrack"] != nil) {
378         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
379                 combo:[defaults keyComboForKey:@"PrevTrack"]
380                 target:self action:@selector(prevSong:)];
381     }
382     
383     if ([defaults objectForKey:@"TrackInfo"] != nil) {
384         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
385                 combo:[defaults keyComboForKey:@"TrackInfo"]
386                 target:self action:@selector(showCurrentTrackInfo)];
387     }
388     
389     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
390         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
391                combo:[defaults keyComboForKey:@"UpcomingSongs"]
392                target:self action:@selector(showUpcomingSongs)];
393     }
394 }
395
396 //Runs an AppleScript and returns the result as an NSString after stripping quotes, if needed. It takes in script and automatically adds the tell iTunes and end tell statements.
397 - (NSString *)runScriptAndReturnResult:(NSString *)script
398 {
399     AEDesc scriptDesc, resultDesc;
400     Size length;
401     NSString *result;
402     Ptr buffer;
403     
404     script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
405     
406     AECreateDesc(typeChar, [script cString], [script cStringLength], 
407 &scriptDesc);
408     
409     OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
410     
411     length = AEGetDescDataSize(&resultDesc);
412     buffer = malloc(length);
413     
414     AEGetDescData(&resultDesc, buffer, length);
415     AEDisposeDesc(&scriptDesc);
416     AEDisposeDesc(&resultDesc);
417     result = [NSString stringWithCString:buffer length:length];
418     if ( (! [result isEqualToString:@""])      &&
419          ([result characterAtIndex:0] == '\"') &&
420          ([result characterAtIndex:[result length] - 1] == '\"') ) {
421         result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
422     }
423     free(buffer);
424     buffer = nil;
425     return result;
426 }
427
428 //Called when the timer fires.
429 - (void)timerUpdate
430 {
431     int pid;
432     if (GetProcessPID(&iTunesPSN, &pid) == noErr) {
433         int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
434         
435         if (trackPlayingIndex != curTrackIndex) {
436             bool wasPlayingRadio = isPlayingRadio;
437             isPlayingRadio = [[self runScriptAndReturnResult:@"return class of current playlist"] isEqualToString:@"radio tuner playlist"];
438             if (isPlayingRadio && !wasPlayingRadio) {
439                 int i;
440                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
441                 {
442                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
443                 }
444             }
445             if (wasPlayingRadio) {
446                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
447                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
448                 [temp release];
449             }
450             [self updateMenu];
451             curTrackIndex = trackPlayingIndex;
452         }
453         else
454         {
455             int playlist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
456             if (playlist != curPlaylistIndex) {
457                 bool wasPlayingRadio = isPlayingRadio;
458                 isPlayingRadio = [[self runScriptAndReturnResult:@"return class of current playlist"] isEqualToString:@"radio tuner playlist"];
459                 if (isPlayingRadio && !wasPlayingRadio) {
460                     int i;
461                     for (i = 0; i < [playlistMenu numberOfItems]; i++)
462                     {
463                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
464                     }
465                 }
466                 if (wasPlayingRadio) {
467                     NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
468                     [menu insertItem:temp atIndex:trackInfoIndex + 1];
469                     [temp release];
470                 }
471                 [self updateMenu];
472                 curTrackIndex = trackPlayingIndex;
473                 curPlaylistIndex = playlist;
474             }
475         }
476         //Update Play/Pause menu item
477         if (playPauseMenuItem){
478             if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"]) {
479                 [playPauseMenuItem setTitle:@"Pause"];
480             } else {
481                 [playPauseMenuItem setTitle:@"Play"];
482             }
483         }
484     } else {
485         [menu release];
486         menu = [[NSMenu alloc] initWithTitle:@""];
487         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
488         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
489         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
490         [statusItem setMenu:menu];
491         
492         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
493         [refreshTimer invalidate];
494         refreshTimer = nil;
495         [self clearHotKeys];
496     }
497 }
498
499 - (void)iTunesLaunched:(NSNotification *)note
500 {
501     NSDictionary *info = [note userInfo];
502     
503     iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
504     iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
505     
506     //Restart the timer
507     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
508     
509     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
510     [statusItem setMenu:menu]; //Set the menu back to the main one
511     [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
512 }
513
514 //Return the PSN of iTunes, if it's running
515 - (ProcessSerialNumber)iTunesPSN
516 {
517     ProcessSerialNumber procNum;
518     procNum.highLongOfPSN = kNoProcess;
519     procNum.lowLongOfPSN = 0;
520     
521     while ( (GetNextProcess(&procNum) == noErr) ) {
522         CFStringRef procName;
523         if ( (CopyProcessName(&procNum, &procName) == noErr) ) {
524             if ([(NSString *)procName isEqualToString:@"iTunes"]) {
525                 return procNum;
526             }
527             [(NSString *)procName release];
528         }
529     }
530     return procNum;
531 }
532
533 //Send an AppleEvent with a given event ID
534 - (void)sendAEWithEventClass:(AEEventClass)eventClass 
535 andEventID:(AEEventID)eventID
536 {
537     OSType iTunesType = 'hook';
538     AppleEvent event, reply;
539     
540     AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
541     
542     AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
543     AEDisposeDesc(&event);
544     AEDisposeDesc(&reply);
545 }
546
547 //
548 // Selectors - called from status item menu
549 //
550
551 - (void)playTrack:(id)sender
552 {
553     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
554     [self updateMenu];
555 }
556
557 - (void)selectPlaylist:(id)sender
558 {
559     int playlist = [[sender representedObject] intValue];
560     if (!isPlayingRadio) {
561         int curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
562         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
563     }
564     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
565     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
566 }
567
568 - (void)selectEQPreset:(id)sender
569 {
570     int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
571     int item = [[sender representedObject] intValue];
572     [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
573     [self runScriptAndReturnResult:@"set EQ enabled to 1"];
574     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
575     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
576 }
577
578 - (void)playPause:(id)sender
579 {
580     NSString *state = [self runScriptAndReturnResult:@"return player state"];
581     if ([state isEqualToString:@"playing"]) {
582         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
583         [playPauseMenuItem setTitle:@"Play"];
584     } else if ([state isEqualToString:@"fast forwarding"] || [state 
585 isEqualToString:@"rewinding"]) {
586         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
587         [self sendAEWithEventClass:'hook' andEventID:'Play'];
588     } else {
589         [self sendAEWithEventClass:'hook' andEventID:'Play'];
590         [playPauseMenuItem setTitle:@"Pause"];
591     }
592 }
593
594 - (void)nextSong:(id)sender
595 {
596     [self sendAEWithEventClass:'hook' andEventID:'Next'];
597 }
598
599 - (void)prevSong:(id)sender
600 {
601     [self sendAEWithEventClass:'hook' andEventID:'Prev'];
602 }
603
604 - (void)fastForward:(id)sender
605 {
606     [self sendAEWithEventClass:'hook' andEventID:'Fast'];
607 }
608
609 - (void)rewind:(id)sender
610 {
611     [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
612 }
613
614 - (void)quitMenuTunes:(id)sender
615 {
616     [NSApp terminate:self];
617 }
618
619 - (void)openiTunes:(id)sender
620 {
621     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
622 }
623
624 - (void)showPreferences:(id)sender
625 {
626     if (!prefsController) {
627         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
628         [self clearHotKeys];
629     }
630 }
631
632
633 - (void)closePreferences
634 {
635     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
636         [self setupHotKeys];
637     }
638     [prefsController release];
639     prefsController = nil;
640 }
641
642 //
643 //
644 // Show Current Track Info And Show Upcoming Songs Floaters
645 //
646 //
647
648 - (void)showCurrentTrackInfo
649 {
650     NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
651     if (!statusController && [trackName length]) {
652         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
653         NSString *stringToShow = @"";
654         int lines = 1;
655         
656         if ([defaults boolForKey:@"showName"]) {
657             if ([defaults boolForKey:@"showArtist"]) {
658                 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
659                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
660             }
661             stringToShow = [stringToShow stringByAppendingString:trackName];
662             stringToShow = [stringToShow stringByAppendingString:@"\n"];
663             if ([trackName length] > 38) {
664                 lines++;
665             }
666             lines++;
667         }
668         
669         if ([defaults boolForKey:@"showAlbum"]) {
670             NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
671             if ([trackAlbum length]) {
672                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
673                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
674                 lines++;
675             }
676         }
677         
678         if ([defaults boolForKey:@"showTime"]) {
679             NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
680             if ([trackTime length]) {
681                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
682                 lines++;
683             }
684         }
685         
686         {
687             int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
688             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
689             if (seconds < 10) {
690                 stringToShow = [stringToShow stringByAppendingString:
691                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
692             } else {
693                 stringToShow = [stringToShow stringByAppendingString:
694                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
695             }
696         }
697         
698         statusController = [[StatusWindowController alloc] init];
699         [statusController setTrackInfo:stringToShow lines:lines];
700         [NSTimer scheduledTimerWithTimeInterval:3.0
701                                          target:self
702                                        selector:@selector(fadeAndCloseStatusWindow)
703                                        userInfo:nil
704                                         repeats:NO];
705     }
706 }
707
708 - (void)showUpcomingSongs
709 {
710     if (!statusController) {
711         int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
712         
713         if (numSongs > 0) {
714             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
715             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
716             int i;
717             NSString *songs = @"";
718             
719             statusController = [[StatusWindowController alloc] init];
720             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
721                 if (i <= numSongs) {
722                     NSString *curSong = [self runScriptAndReturnResult:
723                         [NSString stringWithFormat:@"return name of track %i of current playlist", i]];
724                     songs = [songs stringByAppendingString:curSong];
725                     songs = [songs stringByAppendingString:@"\n"];
726                 }
727             }
728             [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
729             [NSTimer scheduledTimerWithTimeInterval:3.0
730                                              target:self
731                                            selector:@selector(fadeAndCloseStatusWindow)
732                                            userInfo:nil
733                                             repeats:NO];
734         }
735     }
736 }
737
738 - (void)fadeAndCloseStatusWindow
739 {
740     [statusController fadeWindowOut];
741     [statusController release];
742     statusController = nil;
743 }
744
745 /*************************************************************************/
746 #pragma mark -
747 #pragma mark NSApplication DELEGATE METHODS
748 /*************************************************************************/
749
750 - (void)applicationWillTerminate:(NSNotification *)note
751 {
752     [self clearHotKeys];
753     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
754 }
755
756
757 /*************************************************************************/
758 #pragma mark -
759 #pragma mark DEALLOCATION METHODS
760 /*************************************************************************/
761
762 - (void)dealloc
763 {
764     if (refreshTimer) {
765         [refreshTimer invalidate];
766         refreshTimer = nil;
767     }
768     CloseComponent(asComponent);
769     [statusItem release];
770     [menu release];
771 //  [view release];
772     [super dealloc];
773 }
774
775
776 @end