w00t. If player application is not running, instead of simply saying so,
[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 playerRunningState] == 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             NSMenuItem *item;
284             int i;
285             NSString *curTitle = @".....";
286             
287             songRatingMenuItem = [menu addItemWithTitle:@"Song Rating"
288                     action:nil
289                     keyEquivalent:@""];
290             
291             ratingMenu = [[NSMenu alloc] initWithTitle:@""];
292             
293             item = [ratingMenu addItemWithTitle:@"....."
294                             action:@selector(setSongRating:)
295                             keyEquivalent:@""];
296             [item setTarget:self];
297             [item setTag:0];
298             
299             for (i = 1; i < 6; i++) {
300                 curTitle = [curTitle substringToIndex:4];
301                 curTitle = [@"x" stringByAppendingString:curTitle];
302                 item = [ratingMenu addItemWithTitle:curTitle
303                             action:@selector(setSongRating:)
304                             keyEquivalent:@""];
305                 [item setTarget:self];
306                 [item setTag:(i * 20)];
307             }
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                 if (songRatingMenuItem) {
395                     int rating = (int)[currentRemote currentSongRating] * 10;
396                     int i;
397                     for (i = 0; i < 5; i++) {
398                         [[ratingMenu itemAtIndex:i] setState:NSOffState];
399                         [[ratingMenu itemAtIndex:i] setTarget:self];
400                     }
401                     [[ratingMenu itemAtIndex:rating / 2] setState:NSOnState];
402                 }
403             }
404             
405             if ([defaults boolForKey:@"showName"]) {
406                 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
407                             action:nil
408                             keyEquivalent:@""];
409                 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
410                 [menuItem release];
411             }
412             
413             if (index == -1) {
414                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
415                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
416                 [menu insertItem:menuItem atIndex:trackInfoIndex];
417                 [menuItem release];
418                 
419                 [songRatingMenuItem setSubmenu:ratingMenu];
420                 [songRatingMenuItem setEnabled:YES];
421             }
422         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
423             [menu removeItemAtIndex:trackInfoIndex];
424             
425             if ([defaults boolForKey:@"showName"] == YES) {
426                 [menu removeItemAtIndex:trackInfoIndex];
427             }
428             
429             if ([defaults boolForKey:@"showTime"] == YES) {
430                 [menu removeItemAtIndex:trackInfoIndex];
431             }
432             
433             if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
434                 [menu removeItemAtIndex:trackInfoIndex];
435             }
436             
437             if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
438                 [menu removeItemAtIndex:trackInfoIndex];
439             }
440             
441             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
442             [menu insertItem:menuItem atIndex:trackInfoIndex];
443             [menuItem release];
444         }
445         
446         if ([defaults boolForKey:@"showArtist"]) {
447             didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
448         }
449             
450         if ([defaults boolForKey:@"showAlbum"]) {
451             didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
452         }
453     }
454     [menu update];
455 }
456
457 //Rebuild the upcoming songs submenu. Can be improved a lot.
458 - (void)rebuildUpcomingSongsMenu
459 {
460     int curIndex = [currentRemote currentPlaylistIndex];
461     int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curIndex];
462     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
463     
464     if (!isPlayingRadio) {
465         if (numSongs > 0) {
466             int curTrack = [currentRemote currentSongIndex];
467             int i;
468             
469             [upcomingSongsMenu release];
470             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
471             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
472             [upcomingSongsItem setEnabled:YES];
473             
474             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
475                 if (i <= numSongs) {
476                     NSString *curSong = [currentRemote songTitleAtIndex:i];
477                     NSMenuItem *songItem;
478                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
479                     [songItem setTarget:self];
480                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
481                     [upcomingSongsMenu addItem:songItem];
482                     [songItem release];
483                 } else {
484                     break;
485                 }
486             }
487         }
488     } else {
489         [upcomingSongsItem setSubmenu:nil];
490         [upcomingSongsItem setEnabled:NO];
491     }
492 }
493
494 - (void)rebuildPlaylistMenu
495 {
496     NSArray *playlists = [currentRemote playlists];
497     int i, curPlaylist = [currentRemote currentPlaylistIndex];
498     
499     if (isPlayingRadio) {
500         curPlaylist = 0;
501     }
502     if (playlistMenu && ([playlists count] == [playlistMenu numberOfItems]))
503         return;
504     
505     [playlistMenu release];
506     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
507     
508     for (i = 0; i < [playlists count]; i++) {
509         NSString *playlistName = [playlists objectAtIndex:i];
510         NSMenuItem *tempItem;
511         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
512         [tempItem setTarget:self];
513         [tempItem setRepresentedObject:[NSNumber numberWithInt:i + 1]];
514         [playlistMenu addItem:tempItem];
515         [tempItem release];
516     }
517     [playlistItem setSubmenu:playlistMenu];
518     [playlistItem setEnabled:YES];
519     
520     if (curPlaylist) {
521         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
522     }
523 }
524
525 //Build a menu with the list of all available EQ presets
526 - (void)rebuildEQPresetsMenu
527 {
528     NSArray *eqPresets = [currentRemote eqPresets];
529     NSMenuItem *enabledItem;
530     int i;
531     
532     if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
533         return;
534     
535     [eqMenu release];
536     eqMenu = [[NSMenu alloc] initWithTitle:@""];
537     
538     enabledItem = [eqMenu addItemWithTitle:@"Disabled"
539                           action:@selector(toggleEqualizer)
540                           keyEquivalent:@""];
541     
542     if ([currentRemote equalizerEnabled] == NO) {
543         [enabledItem setState:NSOnState];
544     }
545     
546     [eqMenu addItem:[NSMenuItem separatorItem]];
547     
548     for (i = 0; i < [eqPresets count]; i++) {
549         NSString *setName = [eqPresets objectAtIndex:i];
550         NSMenuItem *tempItem;
551         if (setName) {
552         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
553         [tempItem setTarget:self];
554         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
555         [eqMenu addItem:tempItem];
556         [tempItem release];
557         }
558     }
559     [eqItem setSubmenu:eqMenu];
560     
561     [[eqMenu itemAtIndex:[currentRemote currentEQPresetIndex] + 1] setState:NSOnState];
562 }
563
564 - (void)clearHotKeys
565 {
566     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
567     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
568     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
569     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
570     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
571 }
572
573 - (void)setupHotKeys
574 {
575     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
576     
577     if ([defaults objectForKey:@"PlayPause"] != nil) {
578         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
579                 combo:[defaults keyComboForKey:@"PlayPause"]
580                 target:self action:@selector(playPause:)];
581     }
582     
583     if ([defaults objectForKey:@"NextTrack"] != nil) {
584         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
585                 combo:[defaults keyComboForKey:@"NextTrack"]
586                 target:self action:@selector(nextSong:)];
587     }
588     
589     if ([defaults objectForKey:@"PrevTrack"] != nil) {
590         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
591                 combo:[defaults keyComboForKey:@"PrevTrack"]
592                 target:self action:@selector(prevSong:)];
593     }
594     
595     if ([defaults objectForKey:@"TrackInfo"] != nil) {
596         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
597                 combo:[defaults keyComboForKey:@"TrackInfo"]
598                 target:self action:@selector(showCurrentTrackInfo)];
599     }
600     
601     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
602         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
603                combo:[defaults keyComboForKey:@"UpcomingSongs"]
604                target:self action:@selector(showUpcomingSongs)];
605     }
606 }
607
608 //Called when the timer fires.
609 - (void)timerUpdate
610 {
611     int playlist = [currentRemote currentPlaylistIndex];
612     ITMTRemotePlayerPlayingState playerPlayingState = [currentRemote playerPlayingState];
613     
614     if ((playlist > 0) || playerPlayingState != ITMTRemotePlayerStopped) {
615         int trackPlayingIndex = [currentRemote currentSongIndex];
616         
617         if (trackPlayingIndex != lastSongIndex) {
618             BOOL wasPlayingRadio = isPlayingRadio;
619             isPlayingRadio = ([currentRemote classOfPlaylistAtIndex:playlist] == ITMTRemotePlayerRadioPlaylist);
620             
621             if (isPlayingRadio && !wasPlayingRadio) {
622                 int i;
623                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
624                 {
625                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
626                 }
627             } else {
628                 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
629             }
630             
631             if (wasPlayingRadio) {
632                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
633                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
634                 [temp release];
635             }
636             
637             [self updateMenu];
638             lastSongIndex = trackPlayingIndex;
639         } else {
640             if (playlist != lastPlaylistIndex) {
641                 BOOL wasPlayingRadio = isPlayingRadio;
642                 isPlayingRadio = ([currentRemote classOfPlaylistAtIndex:playlist] == ITMTRemotePlayerRadioPlaylist);
643                 
644                 if (isPlayingRadio && !wasPlayingRadio) {
645                     int i;
646                     for (i = 0; i < [playlistMenu numberOfItems]; i++) {
647                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
648                     }
649                 }
650                 
651                 if (wasPlayingRadio) {
652                     NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
653                     [menu insertItem:temp atIndex:trackInfoIndex + 1];
654                     [temp release];
655                 }
656                 
657                 if (!isPlayingRadio) {
658                     int i;
659                     for (i = 0; i < [playlistMenu numberOfItems]; i++)
660                     {
661                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
662                     }
663                     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
664                 }
665                 
666                 [self updateMenu];
667                 lastSongIndex = trackPlayingIndex;
668                 lastPlaylistIndex = playlist;
669             }
670         }
671         //Update Play/Pause menu item
672         if (playPauseMenuItem){
673             if (playerPlayingState == ITMTRemotePlayerPlaying) {
674                 [playPauseMenuItem setTitle:@"Pause"];
675             } else {
676                 [playPauseMenuItem setTitle:@"Play"];
677             }
678         }
679     } else if ((lastPlaylistIndex > 0) && (playlist == 0)) {
680         NSMenuItem *menuItem;
681         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
682         //Remote the now playing item and add no song item
683         [menu removeItemAtIndex:trackInfoIndex];
684         
685         if ([defaults boolForKey:@"showName"] == YES) {
686             [menu removeItemAtIndex:trackInfoIndex];
687         }
688         
689         if ([defaults boolForKey:@"showTime"] == YES) {
690             [menu removeItemAtIndex:trackInfoIndex];
691         }
692         
693         if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
694             [menu removeItemAtIndex:trackInfoIndex];
695         }
696         
697         if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
698             [menu removeItemAtIndex:trackInfoIndex];
699         }
700         
701         [playPauseMenuItem setTitle:@"Play"];
702         
703         didHaveArtistName = NO;
704         didHaveAlbumName = NO;
705         lastPlaylistIndex = -1;
706         lastSongIndex = -1;
707         
708         [upcomingSongsItem setSubmenu:nil];
709         [upcomingSongsItem setEnabled:NO];
710         
711         [songRatingMenuItem setSubmenu:nil];
712         [songRatingMenuItem setEnabled:NO];
713         
714         menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
715         [menu insertItem:menuItem atIndex:trackInfoIndex];
716         [menuItem release];
717     }
718 }
719
720 - (void)remotePlayerLaunched:(NSNotification *)note
721 {
722     isAppRunning = ITMTRemotePlayerRunning;
723     
724     //Restart the timer
725     [NSThread detachNewThreadSelector:@selector(runTimerInNewThread) toTarget:self withObject:nil];
726     
727     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
728     if (playlistItem) {
729         [self rebuildPlaylistMenu];
730     }
731     if (eqItem) {
732         [self rebuildEQPresetsMenu];
733     }
734     [statusItem setMenu:menu]; //Set the menu back to the main one
735 }
736
737 - (void)runTimerInNewThread
738 {
739     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
740     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
741     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES] retain];
742     [runLoop run];
743     [pool release];
744 }
745
746 - (void)remotePlayerTerminated:(NSNotification *)note
747 {
748     isAppRunning = ITMTRemotePlayerNotRunning;
749     
750     [menu release];
751     menu = [[NSMenu alloc] initWithTitle:@""];
752     [[menu addItemWithTitle:[NSString stringWithFormat:@"Open %@", [currentRemote playerSimpleName]] action:@selector(showPlayer:) keyEquivalent:@""] setTarget:self];
753     [menu addItem:[NSMenuItem separatorItem]];
754     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
755     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
756     [statusItem setMenu:menu];
757     
758     [refreshTimer invalidate];
759     [refreshTimer release];
760     refreshTimer = nil;
761     [self clearHotKeys];
762 }
763
764 //
765 //
766 // Selectors - called from status item menu
767 //
768 //
769
770 // Plugin dependent selectors
771
772 - (void)playTrack:(id)sender
773 {
774     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
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 + 2] setState:NSOnState];
798 }
799
800 - (void)playPause:(id)sender
801 {
802     ITMTRemotePlayerPlayingState state = [currentRemote playerPlayingState];
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 - (void)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 - (void)showPlayer:(id)sender
878 {
879     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
880         [currentRemote showPrimaryInterface];
881     } else {
882         if (![[NSWorkspace sharedWorkspace] launchApplication:[currentRemote playerFullName]]) {
883             NSLog(@"Error Launching Player");
884         }
885     }
886 }
887         
888
889 //
890 //
891 // Show Current Track Info And Show Upcoming Songs Floaters
892 //
893 //
894
895 - (void)showCurrentTrackInfo
896 {
897     NSString *trackName = [currentRemote currentSongTitle];
898     if (!statusWindow && [trackName length]) {
899         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
900         NSString *stringToShow = @"";
901         
902         if ([defaults boolForKey:@"showName"]) {
903             if ([defaults boolForKey:@"showArtist"]) {
904                 NSString *trackArtist = [currentRemote currentSongArtist];
905                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
906             }
907             stringToShow = [stringToShow stringByAppendingString:trackName];
908             stringToShow = [stringToShow stringByAppendingString:@"\n"];
909         }
910         
911         if ([defaults boolForKey:@"showAlbum"]) {
912             NSString *trackAlbum = [currentRemote currentSongAlbum];
913             if ([trackAlbum length]) {
914                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
915                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
916             }
917         }
918         
919         if ([defaults boolForKey:@"showTime"]) {
920             NSString *trackTime = [currentRemote currentSongLength];
921             if ([trackTime length]) {
922                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
923             }
924         }
925         
926         {
927             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
928             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
929             if (seconds < 10) {
930                 stringToShow = [stringToShow stringByAppendingString:
931                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
932             } else {
933                 stringToShow = [stringToShow stringByAppendingString:
934                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
935             }
936         }
937         
938         [statusWindow setText:stringToShow];
939         [NSTimer scheduledTimerWithTimeInterval:3.0
940                     target:self
941                     selector:@selector(fadeAndCloseStatusWindow)
942                     userInfo:nil
943                     repeats:NO];
944     }
945 }
946
947 - (void)showUpcomingSongs
948 {
949     int curPlaylist = [currentRemote currentPlaylistIndex];
950     if (!statusWindow) {
951         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
952         
953         if (numSongs > 0) {
954             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
955             int curTrack = [currentRemote currentSongIndex];
956             int i;
957             NSString *songs = @"";
958             
959             statusWindow = [ITTransientStatusWindow sharedWindow];
960             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
961                 if (i <= numSongs) {
962                     NSString *curSong = [currentRemote songTitleAtIndex:i];
963                     songs = [songs stringByAppendingString:curSong];
964                     songs = [songs stringByAppendingString:@"\n"];
965                 }
966             }
967             [statusWindow setText:songs];
968             [NSTimer scheduledTimerWithTimeInterval:3.0
969                         target:self
970                         selector:@selector(fadeAndCloseStatusWindow)
971                         userInfo:nil
972                         repeats:NO];
973         }
974     }
975 }
976
977 - (void)fadeAndCloseStatusWindow
978 {
979     [statusWindow orderOut:self];
980 }
981
982 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
983         onItem:(NSMenuItem *)item
984 {
985     unichar charcode = 'a';
986     int i;
987     long cocoaModifiers = 0;
988     static long carbonToCocoa[6][2] = 
989     {
990         { cmdKey, NSCommandKeyMask },
991         { optionKey, NSAlternateKeyMask },
992         { controlKey, NSControlKeyMask },
993         { shiftKey, NSShiftKeyMask },
994     };
995     
996     for (i = 0; i < 6; i++) {
997         if (modifiers & carbonToCocoa[i][0]) {
998             cocoaModifiers += carbonToCocoa[i][1];
999         }
1000     }
1001     [item setKeyEquivalentModifierMask:cocoaModifiers];
1002     
1003     //Missing key combos for some keys. Must find them later.
1004     switch (code)
1005     {
1006         case 36:
1007             charcode = '\r';
1008         break;
1009         
1010         case 48:
1011             charcode = '\t';
1012         break;
1013         
1014         //Space -- ARGH!
1015         case 49:
1016         {
1017             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
1018             NSLog(@"%@", menuRef);
1019             SetMenuItemCommandKey(menuRef, 0, NO, 49);
1020             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
1021             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
1022             charcode = 'b';*/
1023         }
1024         break;
1025         
1026         case 51:
1027             charcode = NSDeleteFunctionKey;
1028         break;
1029         
1030         case 53:
1031             charcode = '\e';
1032         break;
1033         
1034         case 71:
1035             charcode = '\e';
1036         break;
1037         
1038         case 76:
1039             charcode = '\r';
1040         break;
1041         
1042         case 96:
1043             charcode = NSF5FunctionKey;
1044         break;
1045         
1046         case 97:
1047             charcode = NSF6FunctionKey;
1048         break;
1049         
1050         case 98:
1051             charcode = NSF7FunctionKey;
1052         break;
1053         
1054         case 99:
1055             charcode = NSF3FunctionKey;
1056         break;
1057         
1058         case 100:
1059             charcode = NSF8FunctionKey;
1060         break;
1061         
1062         case 101:
1063             charcode = NSF9FunctionKey;
1064         break;
1065         
1066         case 103:
1067             charcode = NSF11FunctionKey;
1068         break;
1069         
1070         case 105:
1071             charcode = NSF3FunctionKey;
1072         break;
1073         
1074         case 107:
1075             charcode = NSF14FunctionKey;
1076         break;
1077         
1078         case 109:
1079             charcode = NSF10FunctionKey;
1080         break;
1081         
1082         case 111:
1083             charcode = NSF12FunctionKey;
1084         break;
1085         
1086         case 113:
1087             charcode = NSF13FunctionKey;
1088         break;
1089         
1090         case 114:
1091             charcode = NSInsertFunctionKey;
1092         break;
1093         
1094         case 115:
1095             charcode = NSHomeFunctionKey;
1096         break;
1097         
1098         case 116:
1099             charcode = NSPageUpFunctionKey;
1100         break;
1101         
1102         case 117:
1103             charcode = NSDeleteFunctionKey;
1104         break;
1105         
1106         case 118:
1107             charcode = NSF4FunctionKey;
1108         break;
1109         
1110         case 119:
1111             charcode = NSEndFunctionKey;
1112         break;
1113         
1114         case 120:
1115             charcode = NSF2FunctionKey;
1116         break;
1117         
1118         case 121:
1119             charcode = NSPageDownFunctionKey;
1120         break;
1121         
1122         case 122:
1123             charcode = NSF1FunctionKey;
1124         break;
1125         
1126         case 123:
1127             charcode = NSLeftArrowFunctionKey;
1128         break;
1129         
1130         case 124:
1131             charcode = NSRightArrowFunctionKey;
1132         break;
1133         
1134         case 125:
1135             charcode = NSDownArrowFunctionKey;
1136         break;
1137         
1138         case 126:
1139             charcode = NSUpArrowFunctionKey;
1140         break;
1141     }
1142     
1143     if (charcode == 'a') {
1144         unsigned long state;
1145         long keyTrans;
1146         char charCode;
1147         Ptr kchr;
1148         state = 0;
1149         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1150         keyTrans = KeyTranslate(kchr, code, &state);
1151         charCode = keyTrans;
1152         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1153     } else if (charcode != 'b') {
1154         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1155     }
1156 }
1157
1158 /*************************************************************************/
1159 #pragma mark -
1160 #pragma mark NSApplication DELEGATE METHODS
1161 /*************************************************************************/
1162
1163 - (void)applicationWillTerminate:(NSNotification *)note
1164 {
1165     [self clearHotKeys];
1166     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1167 }
1168
1169
1170 /*************************************************************************/
1171 #pragma mark -
1172 #pragma mark DEALLOCATION METHODS
1173 /*************************************************************************/
1174
1175 - (void)dealloc
1176 {
1177     if (refreshTimer) {
1178         [refreshTimer invalidate];
1179         [refreshTimer release];
1180         refreshTimer = nil;
1181     }
1182     [currentRemote halt];
1183     [statusItem release];
1184     [menu release];
1185 //  [view release];
1186     [super dealloc];
1187 }
1188
1189 @end