b3f858ac5e4748f0eb92a0f4c67f01e8cf5dd634
[MenuTunes.git] / MenuTunes.m
1 /*
2 Things to do:
3 ¥ Radio mode makes things act oddly
4 ¥ Make preferences window pretty
5 ¥ Hot Keys
6     - hot keys can't be set when NSBGOnly is on. The window is not key,
7       so the KeyBroadcaster does not pick up key combos
8     - going to need a different way of defining key combos
9 ¥ Optimize
10 ¥ Apple Events! Apple Events! Apple Events!
11 ¥ Upcoming songs menu items are disabled after launching iTunes and playing
12 */
13
14 #import "MenuTunes.h"
15 // #import "MenuTunesView.h"
16 #import "PreferencesController.h"
17 #import "HotKeyCenter.h"
18 #import "StatusWindowController.h"
19
20 @interface MenuTunes(Private)
21 - (void)registerDefaultsIfNeeded;
22 - (void)updateMenu;
23 - (void)rebuildUpcomingSongsMenu;
24 - (void)rebuildPlaylistMenu;
25 - (void)rebuildEQPresetsMenu;
26 - (void)setupHotKeys;
27 - (NSString *)runScriptAndReturnResult:(NSString *)script;
28 - (void)timerUpdate;
29 - (void)sendAEWithEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID;
30
31 @end
32
33 @implementation MenuTunes
34
35 /*************************************************************************/
36 #pragma mark -
37 #pragma mark INITIALIZATION METHODS
38 /*************************************************************************/
39
40 - (void)applicationDidFinishLaunching:(NSNotification *)note
41 {
42     asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
43
44     [self registerDefaultsIfNeeded];
45     
46     menu = [[NSMenu alloc] initWithTitle:@""];
47     iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
48     
49     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
50     {
51         [self rebuildMenu];
52         refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
53                                                         target:self
54                                                       selector:@selector(timerUpdate)
55                                                       userInfo:nil
56                                                        repeats:YES];
57     }
58     else
59     {
60         menu = [[NSMenu alloc] initWithTitle:@""];
61         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
62         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
63         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
64         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
65         refreshTimer = nil;
66     }
67     
68     statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
69     [[[statusItem _button] cell] setType:NSNullCellType];
70     [statusItem setImage:[NSImage imageNamed:@"menu"]];
71     [[statusItem _button] setAlternateImage:[NSImage imageNamed:@"selected_image"]];
72     [statusItem setHighlightMode:YES];
73     [statusItem setMenu:menu];
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                 
218                 if (!isPlayingRadio) {
219                     if (didHaveAlbumName) {
220                         [menu removeItemAtIndex:index + 1];
221                     }
222                 }
223             }
224             if (!isPlayingRadio) {
225                 if ([curAlbumName length] > 0) {
226                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName]
227                                                         action:nil
228                                                         keyEquivalent:@""];
229                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
230                     [menuItem release];
231                 }
232             }
233             menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
234                                                 action:nil
235                                                 keyEquivalent:@""];
236             [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
237             [menuItem release];
238             
239             if (index == -1) {
240                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
241                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
242                 [menu insertItem:menuItem atIndex:trackInfoIndex];
243                 [menuItem release];
244             }
245             
246         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
247             [menu removeItemAtIndex:trackInfoIndex];
248             [menu removeItemAtIndex:trackInfoIndex];
249             
250             if (didHaveAlbumName) {
251                 [menu removeItemAtIndex:trackInfoIndex];
252             }
253             
254             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
255             [menu insertItem:menuItem atIndex:trackInfoIndex];
256             [menuItem release];
257         }
258     }
259     didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
260 }
261
262 //Rebuild the upcoming songs submenu. Can be improved a lot.
263 - (void)rebuildUpcomingSongsMenu
264 {
265     int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
266     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
267     if (!isPlayingRadio) {
268         if (numSongs > 0) {
269             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
270             int i;
271             
272             [upcomingSongsMenu release];
273             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
274             
275             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
276                 if (i <= numSongs) {
277                     NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
278                     NSMenuItem *songItem;
279                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
280                     [songItem setTarget:self];
281                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
282                     [upcomingSongsMenu addItem:songItem];
283                     [songItem release];
284                 } else {
285                     [upcomingSongsMenu addItemWithTitle:@"End of playlist." action:nil keyEquivalent:@""];
286                     break;
287                 }
288             }
289             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
290             [upcomingSongsItem setEnabled:YES];
291         }
292     } else {
293         [upcomingSongsItem setSubmenu:nil];
294         [upcomingSongsItem setEnabled:NO];
295     }
296 }
297
298 - (void)rebuildPlaylistMenu
299 {
300     int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
301     int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
302     
303     if (isPlayingRadio)
304     {
305         curPlaylist = 0;
306     }
307     
308     if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
309         return;
310     
311     [playlistMenu release];
312     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
313     
314     for (i = 1; i <= numPlaylists; i++) {
315         NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
316         NSMenuItem *tempItem;
317         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
318         [tempItem setTarget:self];
319         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
320         [playlistMenu addItem:tempItem];
321         [tempItem release];
322     }
323     [playlistItem setSubmenu:playlistMenu];
324     
325     if (curPlaylist) {
326         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
327     }
328 }
329
330 //Build a menu with the list of all available EQ presets
331 - (void)rebuildEQPresetsMenu
332 {
333     int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
334     int i;
335     
336     if (eqMenu && (numSets == [eqMenu numberOfItems]))
337         return;
338     
339     [eqMenu release];
340     eqMenu = [[NSMenu alloc] initWithTitle:@""];
341     
342     for (i = 1; i <= numSets; i++) {
343         NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
344         NSMenuItem *tempItem;
345         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
346         [tempItem setTarget:self];
347         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
348         [eqMenu addItem:tempItem];
349         [tempItem release];
350     }
351     [eqItem setSubmenu:eqMenu];
352     
353     [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
354 }
355
356 - (void)clearHotKeys
357 {
358     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
359     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
360     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
361     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
362     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
363 }
364
365 - (void)setupHotKeys
366 {
367     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
368     
369     if ([defaults objectForKey:@"PlayPause"] != nil) {
370         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
371                 combo:[defaults keyComboForKey:@"PlayPause"]
372                 target:self action:@selector(playPause:)];
373     }
374     
375     if ([defaults objectForKey:@"NextTrack"] != nil) {
376         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
377                 combo:[defaults keyComboForKey:@"NextTrack"]
378                 target:self action:@selector(nextSong:)];
379     }
380     
381     if ([defaults objectForKey:@"PrevTrack"] != nil) {
382         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
383                 combo:[defaults keyComboForKey:@"PrevTrack"]
384                 target:self action:@selector(prevSong:)];
385     }
386     
387     if ([defaults objectForKey:@"TrackInfo"] != nil) {
388         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
389                 combo:[defaults keyComboForKey:@"TrackInfo"]
390                 target:self action:@selector(showCurrentTrackInfo)];
391     }
392     
393     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
394         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
395                combo:[defaults keyComboForKey:@"UpcomingSongs"]
396                target:self action:@selector(showUpcomingSongs)];
397     }
398 }
399
400 //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.
401 - (NSString *)runScriptAndReturnResult:(NSString *)script
402 {
403     AEDesc scriptDesc, resultDesc;
404     Size length;
405     NSString *result;
406     Ptr buffer;
407     
408     script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
409     
410     AECreateDesc(typeChar, [script cString], [script cStringLength], 
411 &scriptDesc);
412     
413     OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
414     
415     length = AEGetDescDataSize(&resultDesc);
416     buffer = malloc(length);
417     
418     AEGetDescData(&resultDesc, buffer, length);
419     AEDisposeDesc(&scriptDesc);
420     AEDisposeDesc(&resultDesc);
421     result = [NSString stringWithCString:buffer length:length];
422     if ( (! [result isEqualToString:@""])      &&
423          ([result characterAtIndex:0] == '\"') &&
424          ([result characterAtIndex:[result length] - 1] == '\"') ) {
425         result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
426     }
427     free(buffer);
428     buffer = nil;
429     return result;
430 }
431
432 //Called when the timer fires.
433 - (void)timerUpdate
434 {
435     int pid;
436     
437     if (GetProcessPID(&iTunesPSN, &pid) == noErr) {
438         int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
439         
440         if (trackPlayingIndex != curTrackIndex) {
441             isPlayingRadio = [[self runScriptAndReturnResult:@"return class of current playlist"] isEqualToString:@"radio tuner playlist"];
442             [self updateMenu];
443             curTrackIndex = trackPlayingIndex;
444         }
445         
446         //Update Play/Pause menu item
447         if (playPauseMenuItem){
448             if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"]) {
449                 [playPauseMenuItem setTitle:@"Pause"];
450             } else {
451                 [playPauseMenuItem setTitle:@"Play"];
452             }
453         }
454     } else {
455         [menu release];
456         menu = [[NSMenu alloc] initWithTitle:@""];
457         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
458         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
459         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
460         [statusItem setMenu:menu];
461         
462         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
463         [refreshTimer invalidate];
464         refreshTimer = nil;
465         [self clearHotKeys];
466     }
467 }
468
469 - (void)iTunesLaunched:(NSNotification *)note
470 {
471     NSDictionary *info = [note userInfo];
472     
473     iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
474     iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
475     
476     //Restart the timer
477     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
478     
479     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
480     [statusItem setMenu:menu]; //Set the menu back to the main one
481     [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
482 }
483
484 //Return the PSN of iTunes, if it's running
485 - (ProcessSerialNumber)iTunesPSN
486 {
487     ProcessSerialNumber procNum;
488     procNum.highLongOfPSN = kNoProcess;
489     procNum.lowLongOfPSN = 0;
490     
491     while ( (GetNextProcess(&procNum) == noErr) ) {
492         CFStringRef procName;
493         if ( (CopyProcessName(&procNum, &procName) == noErr) ) {
494             if ([(NSString *)procName isEqualToString:@"iTunes"]) {
495                 return procNum;
496             }
497             [(NSString *)procName release];
498         }
499     }
500     return procNum;
501 }
502
503 //Send an AppleEvent with a given event ID
504 - (void)sendAEWithEventClass:(AEEventClass)eventClass 
505 andEventID:(AEEventID)eventID
506 {
507     OSType iTunesType = 'hook';
508     AppleEvent event, reply;
509     
510     AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
511     
512     AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
513     AEDisposeDesc(&event);
514     AEDisposeDesc(&reply);
515 }
516
517 //
518 // Selectors - called from status item menu
519 //
520
521 - (void)playTrack:(id)sender
522 {
523     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
524     [self updateMenu];
525 }
526
527 - (void)selectPlaylist:(id)sender
528 {
529     int playlist = [[sender representedObject] intValue];
530     int curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
531     [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
532     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
533     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
534     [self updateMenu];
535 }
536
537 - (void)selectEQPreset:(id)sender
538 {
539     int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
540     int item = [[sender representedObject] intValue];
541     [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
542     [self runScriptAndReturnResult:@"set EQ enabled to 1"];
543     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
544     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
545 }
546
547 - (void)playPause:(id)sender
548 {
549     NSString *state = [self runScriptAndReturnResult:@"return player state"];
550     if ([state isEqualToString:@"playing"]) {
551         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
552         [playPauseMenuItem setTitle:@"Play"];
553     } else if ([state isEqualToString:@"fast forwarding"] || [state 
554 isEqualToString:@"rewinding"]) {
555         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
556         [self sendAEWithEventClass:'hook' andEventID:'Play'];
557     } else {
558         [self sendAEWithEventClass:'hook' andEventID:'Play'];
559         [playPauseMenuItem setTitle:@"Pause"];
560     }
561 }
562
563 - (void)nextSong:(id)sender
564 {
565     [self sendAEWithEventClass:'hook' andEventID:'Next'];
566 }
567
568 - (void)prevSong:(id)sender
569 {
570     [self sendAEWithEventClass:'hook' andEventID:'Prev'];
571 }
572
573 - (void)fastForward:(id)sender
574 {
575     [self sendAEWithEventClass:'hook' andEventID:'Fast'];
576 }
577
578 - (void)rewind:(id)sender
579 {
580     [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
581 }
582
583 - (void)quitMenuTunes:(id)sender
584 {
585     [NSApp terminate:self];
586 }
587
588 - (void)openiTunes:(id)sender
589 {
590     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
591 }
592
593 - (void)showPreferences:(id)sender
594 {
595     if (!prefsController) {
596         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
597         [self clearHotKeys];
598     }
599 }
600
601
602 - (void)closePreferences
603 {
604     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
605         [self setupHotKeys];
606     }
607     [prefsController release];
608     prefsController = nil;
609 }
610
611 //
612 //
613 // Show Current Track Info And Show Upcoming Songs Floaters
614 //
615 //
616
617 - (void)showCurrentTrackInfo
618 {
619     NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
620     if (!statusController && [trackName length]) {
621         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
622         NSString *stringToShow = @"";
623         int lines = 1;
624         
625         if ([defaults boolForKey:@"showName"]) {
626             if ([defaults boolForKey:@"showArtist"]) {
627                 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
628                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
629             }
630             stringToShow = [stringToShow stringByAppendingString:trackName];
631             stringToShow = [stringToShow stringByAppendingString:@"\n"];
632             if ([trackName length] > 38) {
633                 lines++;
634             }
635             lines++;
636         }
637         
638         if ([defaults boolForKey:@"showAlbum"]) {
639             NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
640             if ([trackAlbum length]) {
641                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
642                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
643                 lines++;
644             }
645         }
646         
647         if ([defaults boolForKey:@"showTime"]) {
648             NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
649             if ([trackTime length]) {
650                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
651                 lines++;
652             }
653         }
654         
655         {
656             int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
657             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
658             if (seconds < 10) {
659                 stringToShow = [stringToShow stringByAppendingString:
660                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
661             } else {
662                 stringToShow = [stringToShow stringByAppendingString:
663                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
664             }
665         }
666         
667         statusController = [[StatusWindowController alloc] init];
668         [statusController setTrackInfo:stringToShow lines:lines];
669         [NSTimer scheduledTimerWithTimeInterval:3.0
670                                          target:self
671                                        selector:@selector(fadeAndCloseStatusWindow)
672                                        userInfo:nil
673                                         repeats:NO];
674     }
675 }
676
677 - (void)showUpcomingSongs
678 {
679     if (!statusController) {
680         int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
681         
682         if (numSongs > 0) {
683             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
684             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
685             int i;
686             NSString *songs = @"";
687             
688             statusController = [[StatusWindowController alloc] init];
689             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
690                 if (i <= numSongs) {
691                     NSString *curSong = [self runScriptAndReturnResult:
692                         [NSString stringWithFormat:@"return name of track %i of current playlist", i]];
693                     songs = [songs stringByAppendingString:curSong];
694                     songs = [songs stringByAppendingString:@"\n"];
695                 }
696             }
697             [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
698             [NSTimer scheduledTimerWithTimeInterval:3.0
699                                              target:self
700                                            selector:@selector(fadeAndCloseStatusWindow)
701                                            userInfo:nil
702                                             repeats:NO];
703         }
704     }
705 }
706
707 - (void)fadeAndCloseStatusWindow
708 {
709     [statusController fadeWindowOut];
710     [statusController release];
711     statusController = nil;
712 }
713
714 /*************************************************************************/
715 #pragma mark -
716 #pragma mark NSApplication DELEGATE METHODS
717 /*************************************************************************/
718
719 - (void)applicationWillTerminate:(NSNotification *)note
720 {
721     [self clearHotKeys];
722     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
723 }
724
725
726 /*************************************************************************/
727 #pragma mark -
728 #pragma mark DEALLOCATION METHODS
729 /*************************************************************************/
730
731 - (void)dealloc
732 {
733     if (refreshTimer) {
734         [refreshTimer invalidate];
735         refreshTimer = nil;
736     }
737     CloseComponent(asComponent);
738     [statusItem release];
739     [menu release];
740 //  [view release];
741     [super dealloc];
742 }
743
744
745 @end