Readded the stupid ratings menu to the nib, since it went poof. Added
[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     songRatingMenuItem = nil;
205     playlistItem = nil;
206     [playlistMenu release];
207     playlistMenu = nil;
208     eqItem = nil;
209     [eqMenu release];
210     eqMenu = nil;
211     
212     for (i = 0; i < [myMenu count]; i++) {
213         NSString *item = [myMenu objectAtIndex:i];
214         if ([item isEqualToString:@"Play/Pause"]) {
215             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PlayPause"];
216             playPauseMenuItem = [menu addItemWithTitle:@"Play"
217                                     action:@selector(playPause:)
218                                     keyEquivalent:@""];
219             [playPauseMenuItem setTarget:self];
220             
221             if (tempCombo) {
222                 [self setKeyEquivalentForCode:[tempCombo keyCode]
223                     andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
224                 [tempCombo release];
225             }
226         } else if ([item isEqualToString:@"Next Track"]) {
227             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"NextTrack"];
228             NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
229                                         action:@selector(nextSong:)
230                                         keyEquivalent:@""];
231             
232             [nextTrack setTarget:self];
233             if (tempCombo) {
234                 [self setKeyEquivalentForCode:[tempCombo keyCode]
235                     andModifiers:[tempCombo modifiers] onItem:nextTrack];
236                 [tempCombo release];
237             }
238         } else if ([item isEqualToString:@"Previous Track"]) {
239             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PrevTrack"];
240             NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
241                                         action:@selector(prevSong:)
242                                         keyEquivalent:@""];
243             
244             [prevTrack setTarget:self];
245             if (tempCombo) {
246                 [self setKeyEquivalentForCode:[tempCombo keyCode]
247                     andModifiers:[tempCombo modifiers] onItem:prevTrack];
248                 [tempCombo release];
249             }
250         } else if ([item isEqualToString:@"Fast Forward"]) {
251             [[menu addItemWithTitle:@"Fast Forward"
252                     action:@selector(fastForward:)
253                     keyEquivalent:@""] setTarget:self];
254         } else if ([item isEqualToString:@"Rewind"]) {
255             [[menu addItemWithTitle:@"Rewind"
256                     action:@selector(rewind:)
257                     keyEquivalent:@""] setTarget:self];
258         } else if ([item isEqualToString:@"Upcoming Songs"]) {
259             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
260                     action:nil
261                     keyEquivalent:@""];
262         } else if ([item isEqualToString:@"Playlists"]) {
263             playlistItem = [menu addItemWithTitle:@"Playlists"
264                     action:nil
265                     keyEquivalent:@""];
266         } else if ([item isEqualToString:@"EQ Presets"]) {
267             eqItem = [menu addItemWithTitle:@"EQ Presets"
268                     action:nil
269                     keyEquivalent:@""];
270         } else if ([item isEqualToString:@"PreferencesÉ"]) {
271             [[menu addItemWithTitle:@"PreferencesÉ"
272                     action:@selector(showPreferences:)
273                     keyEquivalent:@""] setTarget:self];
274         } else if ([item isEqualToString:@"Quit"]) {
275             [[menu addItemWithTitle:@"Quit"
276                     action:@selector(quitMenuTunes:)
277                     keyEquivalent:@""] setTarget:self];
278         } else if ([item isEqualToString:@"Current Track Info"]) {
279             trackInfoIndex = [menu numberOfItems];
280             [menu addItemWithTitle:@"No Song"
281                     action:nil
282                     keyEquivalent:@""];
283         } else if ([item isEqualToString:@"Song Rating"]) {
284             songRatingMenuItem = [menu addItemWithTitle:@"Song Rating"
285                     action:nil
286                     keyEquivalent:@""];
287         } else if ([item isEqualToString:@"<separator>"]) {
288             [menu addItem:[NSMenuItem separatorItem]];
289         }
290     }
291     
292     [self timerUpdate]; //Updates dynamic info in the menu
293     
294     [self clearHotKeys];
295     [self setupHotKeys];
296 }
297
298 //Updates the menu with current player state, song, and upcoming songs
299 - (void)updateMenu
300 {
301     NSMenuItem *menuItem;
302     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
303     
304     if ( ( isAppRunning == ITMTRemotePlayerNotRunning ) ) {
305         return;
306     }
307     
308     if (upcomingSongsItem) {
309         [self rebuildUpcomingSongsMenu];
310     }
311     
312     if (playlistItem) {
313         [self rebuildPlaylistMenu];
314     }
315     
316     if (eqItem) {
317         [self rebuildEQPresetsMenu];
318     }
319     if (trackInfoIndex > -1) {
320         NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
321         curSongName = [currentRemote currentSongTitle];
322         
323         if ([defaults boolForKey:@"showAlbum"]) {
324             curAlbumName = [currentRemote currentSongAlbum];
325         }
326         
327         if ([defaults boolForKey:@"showArtist"]) {
328             curArtistName = [currentRemote currentSongArtist];
329         }
330         
331         if ([curSongName length] > 0) {
332             int index = [menu indexOfItemWithTitle:@"Now Playing"];
333             if (index > -1) {
334                 if ([defaults boolForKey:@"showName"]) {
335                     [menu removeItemAtIndex:index + 1];
336                 }
337                 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
338                     [menu removeItemAtIndex:index + 1];
339                 }
340                 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
341                     [menu removeItemAtIndex:index + 1];
342                 }
343                 if ([defaults boolForKey:@"showTime"]) {
344                     [menu removeItemAtIndex:index + 1];
345                 }
346             }
347             
348             if (!isPlayingRadio) {
349                 if ([defaults boolForKey:@"showTime"]) {
350                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", [currentRemote currentSongLength]]
351                             action:nil
352                             keyEquivalent:@""];
353                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
354                     [menuItem release];
355                 }
356                 
357                 if ([curArtistName length] > 0) {
358                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curArtistName]
359                             action:nil
360                             keyEquivalent:@""];
361                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
362                     [menuItem release];
363                 }
364                 
365                 if ([curAlbumName length] > 0) {
366                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName]
367                             action:nil
368                             keyEquivalent:@""];
369                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
370                     [menuItem release];
371                 }
372                 
373                 if (songRatingMenuItem) {
374                     int rating = (int)[currentRemote currentSongRating] * 10;
375                     int i;
376                     
377                     for (i = 0; i < 5; i++) {
378                         [[ratingMenu itemAtIndex:i] setState:NSOffState];
379                     }
380                     
381                     switch (rating) {
382                         case 0:
383                             [[ratingMenu itemAtIndex:5] setState:NSOnState];
384                         break;
385                         case 2:
386                             [[ratingMenu itemAtIndex:4] setState:NSOnState];
387                         break;
388                         case 4:
389                             [[ratingMenu itemAtIndex:3] setState:NSOnState];
390                         break;
391                         case 6:
392                             [[ratingMenu itemAtIndex:2] setState:NSOnState];
393                         break;
394                         case 8:
395                             [[ratingMenu itemAtIndex:1] setState:NSOnState];
396                         break;
397                         case 10:
398                             [[ratingMenu itemAtIndex:0] setState:NSOnState];
399                         break;
400                     }
401                 }
402             }
403             
404             if ([defaults boolForKey:@"showName"]) {
405                 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
406                             action:nil
407                             keyEquivalent:@""];
408                 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
409                 [menuItem release];
410             }
411             
412             if (index == -1) {
413                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
414                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
415                 [menu insertItem:menuItem atIndex:trackInfoIndex];
416                 [menuItem release];
417                 
418                 [songRatingMenuItem setSubmenu:ratingMenu];
419                 [songRatingMenuItem setEnabled:YES];
420             }
421         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
422             [menu removeItemAtIndex:trackInfoIndex];
423             
424             if ([defaults boolForKey:@"showName"] == YES) {
425                 [menu removeItemAtIndex:trackInfoIndex];
426             }
427             
428             if ([defaults boolForKey:@"showTime"] == YES) {
429                 [menu removeItemAtIndex:trackInfoIndex];
430             }
431             
432             if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
433                 [menu removeItemAtIndex:trackInfoIndex];
434             }
435             
436             if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
437                 [menu removeItemAtIndex:trackInfoIndex];
438             }
439             
440             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
441             [menu insertItem:menuItem atIndex:trackInfoIndex];
442             [menuItem release];
443         }
444         
445         if ([defaults boolForKey:@"showArtist"]) {
446             didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
447         }
448             
449         if ([defaults boolForKey:@"showAlbum"]) {
450             didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
451         }
452     }
453 }
454
455 //Rebuild the upcoming songs submenu. Can be improved a lot.
456 - (void)rebuildUpcomingSongsMenu
457 {
458     int curIndex = [currentRemote currentPlaylistIndex];
459     int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curIndex];
460     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
461     
462     if (!isPlayingRadio) {
463         if (numSongs > 0) {
464             int curTrack = [currentRemote currentSongIndex];
465             int i;
466             
467             [upcomingSongsMenu release];
468             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
469             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
470             [upcomingSongsItem setEnabled:YES];
471             
472             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
473                 if (i <= numSongs) {
474                     NSString *curSong = [currentRemote songTitleAtIndex:i];
475                     NSMenuItem *songItem;
476                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
477                     [songItem setTarget:self];
478                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
479                     [upcomingSongsMenu addItem:songItem];
480                     [songItem release];
481                 } else {
482                     break;
483                 }
484             }
485         }
486     } else {
487         [upcomingSongsItem setSubmenu:nil];
488         [upcomingSongsItem setEnabled:NO];
489     }
490 }
491
492 - (void)rebuildPlaylistMenu
493 {
494     NSArray *playlists = [currentRemote playlists];
495     int i, curPlaylist = [currentRemote currentPlaylistIndex];
496     
497     if (isPlayingRadio) {
498         curPlaylist = 0;
499     }
500     if (playlistMenu && ([playlists count] == [playlistMenu numberOfItems]))
501         return;
502     
503     [playlistMenu release];
504     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
505     
506     for (i = 0; i < [playlists count]; i++) {
507         NSString *playlistName = [playlists objectAtIndex:i];
508         NSMenuItem *tempItem;
509         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
510         [tempItem setTarget:self];
511         [tempItem setRepresentedObject:[NSNumber numberWithInt:i + 1]];
512         [playlistMenu addItem:tempItem];
513         [tempItem release];
514     }
515     [playlistItem setSubmenu:playlistMenu];
516     [playlistItem setEnabled:YES];
517     
518     if (curPlaylist) {
519         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
520     }
521 }
522
523 //Build a menu with the list of all available EQ presets
524 - (void)rebuildEQPresetsMenu
525 {
526     NSArray *eqPresets = [currentRemote eqPresets];
527     NSMenuItem *enabledItem;
528     int i;
529     
530     if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
531         return;
532     
533     [eqMenu release];
534     eqMenu = [[NSMenu alloc] initWithTitle:@""];
535     
536     enabledItem = [eqMenu addItemWithTitle:@"Disabled"
537                           action:@selector(toggleEqualizer)
538                           keyEquivalent:@""];
539     
540     if ([currentRemote equalizerEnabled] == NO) {
541         [enabledItem setState:NSOnState];
542     }
543     
544     [eqMenu addItem:[NSMenuItem separatorItem]];
545     
546     for (i = 0; i < [eqPresets count]; i++) {
547         NSString *setName = [eqPresets objectAtIndex:i];
548         NSMenuItem *tempItem;
549         if (setName) {
550         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
551         [tempItem setTarget:self];
552         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
553         [eqMenu addItem:tempItem];
554         [tempItem release];
555         }
556     }
557     [eqItem setSubmenu:eqMenu];
558     
559     [[eqMenu itemAtIndex:[currentRemote currentEQPresetIndex] + 1] setState:NSOnState];
560 }
561
562 - (void)clearHotKeys
563 {
564     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
565     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
566     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
567     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
568     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
569 }
570
571 - (void)setupHotKeys
572 {
573     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
574     
575     if ([defaults objectForKey:@"PlayPause"] != nil) {
576         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
577                 combo:[defaults keyComboForKey:@"PlayPause"]
578                 target:self action:@selector(playPause:)];
579     }
580     
581     if ([defaults objectForKey:@"NextTrack"] != nil) {
582         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
583                 combo:[defaults keyComboForKey:@"NextTrack"]
584                 target:self action:@selector(nextSong:)];
585     }
586     
587     if ([defaults objectForKey:@"PrevTrack"] != nil) {
588         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
589                 combo:[defaults keyComboForKey:@"PrevTrack"]
590                 target:self action:@selector(prevSong:)];
591     }
592     
593     if ([defaults objectForKey:@"TrackInfo"] != nil) {
594         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
595                 combo:[defaults keyComboForKey:@"TrackInfo"]
596                 target:self action:@selector(showCurrentTrackInfo)];
597     }
598     
599     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
600         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
601                combo:[defaults keyComboForKey:@"UpcomingSongs"]
602                target:self action:@selector(showUpcomingSongs)];
603     }
604 }
605
606 //Called when the timer fires.
607 - (void)timerUpdate
608 {
609     int playlist = [currentRemote currentPlaylistIndex];
610     ITMTRemotePlayerState playerState = [currentRemote playerState];
611     
612     if ((playlist > 0) || playerState != ITMTRemotePlayerStopped) {
613         int trackPlayingIndex = [currentRemote currentSongIndex];
614         
615         if (trackPlayingIndex != lastSongIndex) {
616             BOOL wasPlayingRadio = isPlayingRadio;
617             isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
618             
619             if (isPlayingRadio && !wasPlayingRadio) {
620                 int i;
621                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
622                 {
623                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
624                 }
625             } else {
626                 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
627             }
628             
629             if (wasPlayingRadio) {
630                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
631                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
632                 [temp release];
633             }
634             
635             [self updateMenu];
636             lastSongIndex = trackPlayingIndex;
637         } else {
638             if (playlist != lastPlaylistIndex) {
639                 BOOL wasPlayingRadio = isPlayingRadio;
640                 isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
641                 
642                 if (isPlayingRadio && !wasPlayingRadio) {
643                     int i;
644                     for (i = 0; i < [playlistMenu numberOfItems]; i++) {
645                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
646                     }
647                 }
648                 
649                 if (wasPlayingRadio) {
650                     NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
651                     [menu insertItem:temp atIndex:trackInfoIndex + 1];
652                     [temp release];
653                 }
654                 
655                 if (!isPlayingRadio) {
656                     int i;
657                     for (i = 0; i < [playlistMenu numberOfItems]; i++)
658                     {
659                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
660                     }
661                     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
662                 }
663                 
664                 [self updateMenu];
665                 lastSongIndex = trackPlayingIndex;
666                 lastPlaylistIndex = playlist;
667             }
668         }
669         //Update Play/Pause menu item
670         if (playPauseMenuItem){
671             if (playerState == ITMTRemotePlayerPlaying) {
672                 [playPauseMenuItem setTitle:@"Pause"];
673             } else {
674                 [playPauseMenuItem setTitle:@"Play"];
675             }
676         }
677     } else if ((lastPlaylistIndex > 0) && (playlist == 0)) {
678         NSMenuItem *menuItem;
679         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
680         //Remote the now playing item and add no song item
681         [menu removeItemAtIndex:trackInfoIndex];
682         
683         if ([defaults boolForKey:@"showName"] == YES) {
684             [menu removeItemAtIndex:trackInfoIndex];
685         }
686         
687         if ([defaults boolForKey:@"showTime"] == YES) {
688             [menu removeItemAtIndex:trackInfoIndex];
689         }
690         
691         if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
692             [menu removeItemAtIndex:trackInfoIndex];
693         }
694         
695         if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
696             [menu removeItemAtIndex:trackInfoIndex];
697         }
698         
699         [playPauseMenuItem setTitle:@"Play"];
700         
701         didHaveArtistName = NO;
702         didHaveAlbumName = NO;
703         lastPlaylistIndex = -1;
704         lastSongIndex = -1;
705         
706         [upcomingSongsItem setSubmenu:nil];
707         [upcomingSongsItem setEnabled:NO];
708         
709         [songRatingMenuItem setSubmenu:nil];
710         [songRatingMenuItem setEnabled:NO];
711         
712         menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
713         [menu insertItem:menuItem atIndex:trackInfoIndex];
714         [menuItem release];
715     }
716 }
717
718 - (void)remotePlayerLaunched:(NSNotification *)note
719 {
720     isAppRunning = ITMTRemotePlayerRunning;
721     
722     //Restart the timer
723     [NSThread detachNewThreadSelector:@selector(runTimerInNewThread) toTarget:self withObject:nil];
724     
725     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
726     if (playlistItem) {
727         [self rebuildPlaylistMenu];
728     }
729     if (eqItem) {
730         [self rebuildEQPresetsMenu];
731     }
732     [statusItem setMenu:menu]; //Set the menu back to the main one
733 }
734
735 - (void)runTimerInNewThread
736 {
737     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
738     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
739     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES] retain];
740     [runLoop run];
741     [pool release];
742 }
743
744 - (void)remotePlayerTerminated:(NSNotification *)note
745 {
746     isAppRunning = ITMTRemotePlayerNotRunning;
747     
748     [menu release];
749     menu = [[NSMenu alloc] initWithTitle:@""];
750     [menu addItemWithTitle:@"Audio Player" action:NULL keyEquivalent:@""];
751     [menu addItemWithTitle:@"Not Running" action:NULL keyEquivalent:@""];
752     [menu addItem:[NSMenuItem separatorItem]];
753     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
754     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
755     [statusItem setMenu:menu];
756     
757     [refreshTimer invalidate];
758     [refreshTimer release];
759     refreshTimer = nil;
760     [self clearHotKeys];
761 }
762
763 //
764 //
765 // Selectors - called from status item menu
766 //
767 //
768
769 // Plugin dependent selectors
770
771 - (void)playTrack:(id)sender
772 {
773     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
774     [self updateMenu];
775 }
776
777 - (void)selectPlaylist:(id)sender
778 {
779     int playlist = [[sender representedObject] intValue];
780     if (!isPlayingRadio) {
781         int curPlaylist = [currentRemote currentPlaylistIndex];
782         if (curPlaylist > 0) {
783             [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
784         }
785     }
786     [currentRemote switchToPlaylistAtIndex:playlist];
787     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
788     [self updateMenu];
789 }
790
791 - (void)selectEQPreset:(id)sender
792 {
793     int curSet = [currentRemote currentEQPresetIndex];
794     int item = [[sender representedObject] intValue];
795     [currentRemote switchToEQAtIndex:item];
796     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
797     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
798 }
799
800 - (void)playPause:(id)sender
801 {
802     ITMTRemotePlayerState state = [currentRemote playerState];
803     
804     if (state == ITMTRemotePlayerPlaying) {
805         [currentRemote pause];
806         [playPauseMenuItem setTitle:@"Play"];
807     } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
808         [currentRemote pause];
809         [currentRemote play];
810     } else {
811         [currentRemote play];
812         [playPauseMenuItem setTitle:@"Pause"];
813     }
814 }
815
816 - (void)nextSong:(id)sender
817 {
818     [currentRemote goToNextSong];
819 }
820
821 - (void)prevSong:(id)sender
822 {
823     [currentRemote goToPreviousSong];
824 }
825
826 - (void)fastForward:(id)sender
827 {
828     [currentRemote forward];
829     [playPauseMenuItem setTitle:@"Play"];
830 }
831
832 - (void)rewind:(id)sender
833 {
834     [currentRemote rewind];
835     [playPauseMenuItem setTitle:@"Play"];
836 }
837
838 - (void)toggleEqualizer
839 {
840     [currentRemote setEqualizerEnabled:![currentRemote equalizerEnabled]];
841 }
842
843 - (IBAction)setSongRating:(id)sender
844 {
845     NSLog(@"%f", [currentRemote currentSongRating]);
846     NSLog(@"%f", (float)[sender tag] / 100.0);
847     [currentRemote setCurrentSongRating:(float)[sender tag] / 100.0];
848 }
849
850 //
851 //
852 // Plugin independent selectors
853 //
854 //
855 - (void)quitMenuTunes:(id)sender
856 {
857     [NSApp terminate:self];
858 }
859
860 - (void)showPreferences:(id)sender
861 {
862     if (!prefsController) {
863         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
864         [self clearHotKeys];
865     }
866 }
867
868 - (void)closePreferences
869 {
870     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
871         [self setupHotKeys];
872     }
873     [prefsController release];
874     prefsController = nil;
875 }
876
877 //
878 //
879 // Show Current Track Info And Show Upcoming Songs Floaters
880 //
881 //
882
883 - (void)showCurrentTrackInfo
884 {
885     NSString *trackName = [currentRemote currentSongTitle];
886     if (!statusWindow && [trackName length]) {
887         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
888         NSString *stringToShow = @"";
889         
890         if ([defaults boolForKey:@"showName"]) {
891             if ([defaults boolForKey:@"showArtist"]) {
892                 NSString *trackArtist = [currentRemote currentSongArtist];
893                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
894             }
895             stringToShow = [stringToShow stringByAppendingString:trackName];
896             stringToShow = [stringToShow stringByAppendingString:@"\n"];
897         }
898         
899         if ([defaults boolForKey:@"showAlbum"]) {
900             NSString *trackAlbum = [currentRemote currentSongAlbum];
901             if ([trackAlbum length]) {
902                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
903                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
904             }
905         }
906         
907         if ([defaults boolForKey:@"showTime"]) {
908             NSString *trackTime = [currentRemote currentSongLength];
909             if ([trackTime length]) {
910                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
911             }
912         }
913         
914         {
915             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
916             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
917             if (seconds < 10) {
918                 stringToShow = [stringToShow stringByAppendingString:
919                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
920             } else {
921                 stringToShow = [stringToShow stringByAppendingString:
922                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
923             }
924         }
925         
926         [statusWindow setText:stringToShow];
927         [NSTimer scheduledTimerWithTimeInterval:3.0
928                     target:self
929                     selector:@selector(fadeAndCloseStatusWindow)
930                     userInfo:nil
931                     repeats:NO];
932     }
933 }
934
935 - (void)showUpcomingSongs
936 {
937     int curPlaylist = [currentRemote currentPlaylistIndex];
938     if (!statusWindow) {
939         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
940         
941         if (numSongs > 0) {
942             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
943             int curTrack = [currentRemote currentSongIndex];
944             int i;
945             NSString *songs = @"";
946             
947             statusWindow = [ITTransientStatusWindow sharedWindow];
948             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
949                 if (i <= numSongs) {
950                     NSString *curSong = [currentRemote songTitleAtIndex:i];
951                     songs = [songs stringByAppendingString:curSong];
952                     songs = [songs stringByAppendingString:@"\n"];
953                 }
954             }
955             [statusWindow setText:songs];
956             [NSTimer scheduledTimerWithTimeInterval:3.0
957                         target:self
958                         selector:@selector(fadeAndCloseStatusWindow)
959                         userInfo:nil
960                         repeats:NO];
961         }
962     }
963 }
964
965 - (void)fadeAndCloseStatusWindow
966 {
967     [statusWindow orderOut:self];
968 }
969
970 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
971         onItem:(NSMenuItem *)item
972 {
973     unichar charcode = 'a';
974     int i;
975     long cocoaModifiers = 0;
976     static long carbonToCocoa[6][2] = 
977     {
978         { cmdKey, NSCommandKeyMask },
979         { optionKey, NSAlternateKeyMask },
980         { controlKey, NSControlKeyMask },
981         { shiftKey, NSShiftKeyMask },
982     };
983     
984     for (i = 0; i < 6; i++) {
985         if (modifiers & carbonToCocoa[i][0]) {
986             cocoaModifiers += carbonToCocoa[i][1];
987         }
988     }
989     [item setKeyEquivalentModifierMask:cocoaModifiers];
990     
991     //Missing key combos for some keys. Must find them later.
992     switch (code)
993     {
994         case 36:
995             charcode = '\r';
996         break;
997         
998         case 48:
999             charcode = '\t';
1000         break;
1001         
1002         //Space -- ARGH!
1003         case 49:
1004         {
1005             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
1006             NSLog(@"%@", menuRef);
1007             SetMenuItemCommandKey(menuRef, 0, NO, 49);
1008             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
1009             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
1010             charcode = 'b';*/
1011         }
1012         break;
1013         
1014         case 51:
1015             charcode = NSDeleteFunctionKey;
1016         break;
1017         
1018         case 53:
1019             charcode = '\e';
1020         break;
1021         
1022         case 71:
1023             charcode = '\e';
1024         break;
1025         
1026         case 76:
1027             charcode = '\r';
1028         break;
1029         
1030         case 96:
1031             charcode = NSF5FunctionKey;
1032         break;
1033         
1034         case 97:
1035             charcode = NSF6FunctionKey;
1036         break;
1037         
1038         case 98:
1039             charcode = NSF7FunctionKey;
1040         break;
1041         
1042         case 99:
1043             charcode = NSF3FunctionKey;
1044         break;
1045         
1046         case 100:
1047             charcode = NSF8FunctionKey;
1048         break;
1049         
1050         case 101:
1051             charcode = NSF9FunctionKey;
1052         break;
1053         
1054         case 103:
1055             charcode = NSF11FunctionKey;
1056         break;
1057         
1058         case 105:
1059             charcode = NSF3FunctionKey;
1060         break;
1061         
1062         case 107:
1063             charcode = NSF14FunctionKey;
1064         break;
1065         
1066         case 109:
1067             charcode = NSF10FunctionKey;
1068         break;
1069         
1070         case 111:
1071             charcode = NSF12FunctionKey;
1072         break;
1073         
1074         case 113:
1075             charcode = NSF13FunctionKey;
1076         break;
1077         
1078         case 114:
1079             charcode = NSInsertFunctionKey;
1080         break;
1081         
1082         case 115:
1083             charcode = NSHomeFunctionKey;
1084         break;
1085         
1086         case 116:
1087             charcode = NSPageUpFunctionKey;
1088         break;
1089         
1090         case 117:
1091             charcode = NSDeleteFunctionKey;
1092         break;
1093         
1094         case 118:
1095             charcode = NSF4FunctionKey;
1096         break;
1097         
1098         case 119:
1099             charcode = NSEndFunctionKey;
1100         break;
1101         
1102         case 120:
1103             charcode = NSF2FunctionKey;
1104         break;
1105         
1106         case 121:
1107             charcode = NSPageDownFunctionKey;
1108         break;
1109         
1110         case 122:
1111             charcode = NSF1FunctionKey;
1112         break;
1113         
1114         case 123:
1115             charcode = NSLeftArrowFunctionKey;
1116         break;
1117         
1118         case 124:
1119             charcode = NSRightArrowFunctionKey;
1120         break;
1121         
1122         case 125:
1123             charcode = NSDownArrowFunctionKey;
1124         break;
1125         
1126         case 126:
1127             charcode = NSUpArrowFunctionKey;
1128         break;
1129     }
1130     
1131     if (charcode == 'a') {
1132         unsigned long state;
1133         long keyTrans;
1134         char charCode;
1135         Ptr kchr;
1136         state = 0;
1137         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1138         keyTrans = KeyTranslate(kchr, code, &state);
1139         charCode = keyTrans;
1140         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1141     } else if (charcode != 'b') {
1142         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1143     }
1144 }
1145
1146 /*************************************************************************/
1147 #pragma mark -
1148 #pragma mark NSApplication DELEGATE METHODS
1149 /*************************************************************************/
1150
1151 - (void)applicationWillTerminate:(NSNotification *)note
1152 {
1153     [self clearHotKeys];
1154     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1155 }
1156
1157
1158 /*************************************************************************/
1159 #pragma mark -
1160 #pragma mark DEALLOCATION METHODS
1161 /*************************************************************************/
1162
1163 - (void)dealloc
1164 {
1165     if (refreshTimer) {
1166         [refreshTimer invalidate];
1167         [refreshTimer release];
1168         refreshTimer = nil;
1169     }
1170     [currentRemote halt];
1171     [statusItem release];
1172     [menu release];
1173 //  [view release];
1174     [super dealloc];
1175 }
1176
1177 @end