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