A couple semantic tw34ks.
[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 *curSongName, *curAlbumName;
193     NSMenuItem *menuItem;
194     
195     if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
196         return;
197     }
198     
199     //Get the current track name and album.
200     curSongName = [self runScriptAndReturnResult:@"return name of current track"];
201     curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
202     
203     if (upcomingSongsItem) {
204         [self rebuildUpcomingSongsMenu];
205     }
206     if (playlistItem) {
207         [self rebuildPlaylistMenu];
208     }
209     if (eqItem) {
210         [self rebuildEQPresetsMenu];
211     }
212     
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     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
520     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
521     [self updateMenu];
522 }
523
524 - (void)selectEQPreset:(id)sender
525 {
526     int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
527     int item = [[sender representedObject] intValue];
528     [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
529     [self runScriptAndReturnResult:@"set EQ enabled to 1"];
530     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
531     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
532 }
533
534 - (void)playPause:(id)sender
535 {
536     NSString *state = [self runScriptAndReturnResult:@"return player state"];
537     if ([state isEqualToString:@"playing"]) {
538         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
539         [playPauseMenuItem setTitle:@"Play"];
540     } else if ([state isEqualToString:@"fast forwarding"] || [state 
541 isEqualToString:@"rewinding"]) {
542         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
543         [self sendAEWithEventClass:'hook' andEventID:'Play'];
544     } else {
545         [self sendAEWithEventClass:'hook' andEventID:'Play'];
546         [playPauseMenuItem setTitle:@"Pause"];
547     }
548 }
549
550 - (void)nextSong:(id)sender
551 {
552     [self sendAEWithEventClass:'hook' andEventID:'Next'];
553 }
554
555 - (void)prevSong:(id)sender
556 {
557     [self sendAEWithEventClass:'hook' andEventID:'Prev'];
558 }
559
560 - (void)fastForward:(id)sender
561 {
562     [self sendAEWithEventClass:'hook' andEventID:'Fast'];
563 }
564
565 - (void)rewind:(id)sender
566 {
567     [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
568 }
569
570 - (void)quitMenuTunes:(id)sender
571 {
572     [NSApp terminate:self];
573 }
574
575 - (void)openiTunes:(id)sender
576 {
577     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
578 }
579
580 - (void)showPreferences:(id)sender
581 {
582     if (!prefsController) {
583         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
584         [self clearHotKeys];
585     }
586 }
587
588
589 - (void)closePreferences
590 {
591     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
592         [self setupHotKeys];
593     }
594     [prefsController release];
595     prefsController = nil;
596 }
597
598 //
599 //
600 // Show Current Track Info And Show Upcoming Songs Floaters
601 //
602 //
603
604 - (void)showCurrentTrackInfo
605 {
606     NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
607     if (!statusController && [trackName length]) {
608         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
609         NSString *stringToShow = @"";
610         int lines = 1;
611         
612         if ([defaults boolForKey:@"showName"]) {
613             if ([defaults boolForKey:@"showArtist"]) {
614                 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
615                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
616             }
617             stringToShow = [stringToShow stringByAppendingString:trackName];
618             stringToShow = [stringToShow stringByAppendingString:@"\n"];
619             if ([trackName length] > 38) {
620                 lines++;
621             }
622             lines++;
623         }
624         
625         if ([defaults boolForKey:@"showAlbum"]) {
626             NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
627             if ([trackAlbum length]) {
628                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
629                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
630                 lines++;
631             }
632         }
633         
634         if ([defaults boolForKey:@"showTime"]) {
635             NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
636             if ([trackTime length]) {
637                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
638                 lines++;
639             }
640         }
641         
642         {
643             int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
644             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
645             if (seconds < 10) {
646                 stringToShow = [stringToShow stringByAppendingString:
647                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
648             } else {
649                 stringToShow = [stringToShow stringByAppendingString:
650                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
651             }
652         }
653         
654         statusController = [[StatusWindowController alloc] init];
655         [statusController setTrackInfo:stringToShow lines:lines];
656         [NSTimer scheduledTimerWithTimeInterval:3.0
657                                          target:self
658                                        selector:@selector(fadeAndCloseStatusWindow)
659                                        userInfo:nil
660                                         repeats:NO];
661     }
662 }
663
664 - (void)showUpcomingSongs
665 {
666     if (!statusController) {
667         int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
668         
669         if (numSongs > 0) {
670             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
671             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
672             int i;
673             NSString *songs = @"";
674             
675             statusController = [[StatusWindowController alloc] init];
676             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
677                 if (i <= numSongs) {
678                     NSString *curSong = [self runScriptAndReturnResult:
679                         [NSString stringWithFormat:@"return name of track %i of current playlist", i]];
680                     songs = [songs stringByAppendingString:curSong];
681                     songs = [songs stringByAppendingString:@"\n"];
682                 }
683             }
684             [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
685             [NSTimer scheduledTimerWithTimeInterval:3.0
686                                              target:self
687                                            selector:@selector(fadeAndCloseStatusWindow)
688                                            userInfo:nil
689                                             repeats:NO];
690         }
691     }
692 }
693
694 - (void)fadeAndCloseStatusWindow
695 {
696     [statusController fadeWindowOut];
697     [statusController release];
698     statusController = nil;
699 }
700
701 /*************************************************************************/
702 #pragma mark -
703 #pragma mark NSApplication DELEGATE METHODS
704 /*************************************************************************/
705
706 - (void)applicationWillTerminate:(NSNotification *)note
707 {
708     [self clearHotKeys];
709     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
710 }
711
712
713 /*************************************************************************/
714 #pragma mark -
715 #pragma mark DEALLOCATION METHODS
716 /*************************************************************************/
717
718 - (void)dealloc
719 {
720     if (refreshTimer) {
721         [refreshTimer invalidate];
722         refreshTimer = nil;
723     }
724     CloseComponent(asComponent);
725     [statusItem release];
726     [menu release];
727 //  [view release];
728     [super dealloc];
729 }
730
731
732 @end