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