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