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