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