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