M0nk3ys
[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:@"Audio Player" action:NULL keyEquivalent:@""];
753     [menu addItemWithTitle:@"Not Running" action:NULL keyEquivalent:@""];
754     [menu addItem:[NSMenuItem separatorItem]];
755     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
756     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
757     [statusItem setMenu:menu];
758     
759     [refreshTimer invalidate];
760     [refreshTimer release];
761     refreshTimer = nil;
762     [self clearHotKeys];
763 }
764
765 //
766 //
767 // Selectors - called from status item menu
768 //
769 //
770
771 // Plugin dependent selectors
772
773 - (void)playTrack:(id)sender
774 {
775     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
776 }
777
778 - (void)selectPlaylist:(id)sender
779 {
780     int playlist = [[sender representedObject] intValue];
781     if (!isPlayingRadio) {
782         int curPlaylist = [currentRemote currentPlaylistIndex];
783         if (curPlaylist > 0) {
784             [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
785         }
786     }
787     [currentRemote switchToPlaylistAtIndex:playlist];
788     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
789     [self updateMenu];
790 }
791
792 - (void)selectEQPreset:(id)sender
793 {
794     int curSet = [currentRemote currentEQPresetIndex];
795     int item = [[sender representedObject] intValue];
796     [currentRemote switchToEQAtIndex:item];
797     [[eqMenu itemAtIndex:curSet + 1] setState:NSOffState];
798     [[eqMenu itemAtIndex:item + 2] setState:NSOnState];
799 }
800
801 - (void)playPause:(id)sender
802 {
803     ITMTRemotePlayerPlayingState state = [currentRemote playerPlayingState];
804     
805     if (state == ITMTRemotePlayerPlaying) {
806         [currentRemote pause];
807         [playPauseMenuItem setTitle:@"Play"];
808     } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
809         [currentRemote pause];
810         [currentRemote play];
811     } else {
812         [currentRemote play];
813         [playPauseMenuItem setTitle:@"Pause"];
814     }
815 }
816
817 - (void)nextSong:(id)sender
818 {
819     [currentRemote goToNextSong];
820 }
821
822 - (void)prevSong:(id)sender
823 {
824     [currentRemote goToPreviousSong];
825 }
826
827 - (void)fastForward:(id)sender
828 {
829     [currentRemote forward];
830     [playPauseMenuItem setTitle:@"Play"];
831 }
832
833 - (void)rewind:(id)sender
834 {
835     [currentRemote rewind];
836     [playPauseMenuItem setTitle:@"Play"];
837 }
838
839 - (void)toggleEqualizer
840 {
841     [currentRemote setEqualizerEnabled:![currentRemote equalizerEnabled]];
842 }
843
844 - (void)setSongRating:(id)sender
845 {
846     NSLog(@"%f", [currentRemote currentSongRating]);
847     NSLog(@"%f", (float)[sender tag] / 100.0);
848     [currentRemote setCurrentSongRating:(float)[sender tag] / 100.0];
849 }
850
851 //
852 //
853 // Plugin independent selectors
854 //
855 //
856 - (void)quitMenuTunes:(id)sender
857 {
858     [NSApp terminate:self];
859 }
860
861 - (void)showPreferences:(id)sender
862 {
863     if (!prefsController) {
864         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
865         [self clearHotKeys];
866     }
867 }
868
869 - (void)closePreferences
870 {
871     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
872         [self setupHotKeys];
873     }
874     [prefsController release];
875     prefsController = nil;
876 }
877
878 //
879 //
880 // Show Current Track Info And Show Upcoming Songs Floaters
881 //
882 //
883
884 - (void)showCurrentTrackInfo
885 {
886     NSString *trackName = [currentRemote currentSongTitle];
887     if (!statusWindow && [trackName length]) {
888         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
889         NSString *stringToShow = @"";
890         
891         if ([defaults boolForKey:@"showName"]) {
892             if ([defaults boolForKey:@"showArtist"]) {
893                 NSString *trackArtist = [currentRemote currentSongArtist];
894                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
895             }
896             stringToShow = [stringToShow stringByAppendingString:trackName];
897             stringToShow = [stringToShow stringByAppendingString:@"\n"];
898         }
899         
900         if ([defaults boolForKey:@"showAlbum"]) {
901             NSString *trackAlbum = [currentRemote currentSongAlbum];
902             if ([trackAlbum length]) {
903                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
904                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
905             }
906         }
907         
908         if ([defaults boolForKey:@"showTime"]) {
909             NSString *trackTime = [currentRemote currentSongLength];
910             if ([trackTime length]) {
911                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
912             }
913         }
914         
915         {
916             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
917             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
918             if (seconds < 10) {
919                 stringToShow = [stringToShow stringByAppendingString:
920                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
921             } else {
922                 stringToShow = [stringToShow stringByAppendingString:
923                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
924             }
925         }
926         
927         [statusWindow setText:stringToShow];
928         [NSTimer scheduledTimerWithTimeInterval:3.0
929                     target:self
930                     selector:@selector(fadeAndCloseStatusWindow)
931                     userInfo:nil
932                     repeats:NO];
933     }
934 }
935
936 - (void)showUpcomingSongs
937 {
938     int curPlaylist = [currentRemote currentPlaylistIndex];
939     if (!statusWindow) {
940         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
941         
942         if (numSongs > 0) {
943             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
944             int curTrack = [currentRemote currentSongIndex];
945             int i;
946             NSString *songs = @"";
947             
948             statusWindow = [ITTransientStatusWindow sharedWindow];
949             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
950                 if (i <= numSongs) {
951                     NSString *curSong = [currentRemote songTitleAtIndex:i];
952                     songs = [songs stringByAppendingString:curSong];
953                     songs = [songs stringByAppendingString:@"\n"];
954                 }
955             }
956             [statusWindow setText:songs];
957             [NSTimer scheduledTimerWithTimeInterval:3.0
958                         target:self
959                         selector:@selector(fadeAndCloseStatusWindow)
960                         userInfo:nil
961                         repeats:NO];
962         }
963     }
964 }
965
966 - (void)fadeAndCloseStatusWindow
967 {
968     [statusWindow orderOut:self];
969 }
970
971 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
972         onItem:(NSMenuItem *)item
973 {
974     unichar charcode = 'a';
975     int i;
976     long cocoaModifiers = 0;
977     static long carbonToCocoa[6][2] = 
978     {
979         { cmdKey, NSCommandKeyMask },
980         { optionKey, NSAlternateKeyMask },
981         { controlKey, NSControlKeyMask },
982         { shiftKey, NSShiftKeyMask },
983     };
984     
985     for (i = 0; i < 6; i++) {
986         if (modifiers & carbonToCocoa[i][0]) {
987             cocoaModifiers += carbonToCocoa[i][1];
988         }
989     }
990     [item setKeyEquivalentModifierMask:cocoaModifiers];
991     
992     //Missing key combos for some keys. Must find them later.
993     switch (code)
994     {
995         case 36:
996             charcode = '\r';
997         break;
998         
999         case 48:
1000             charcode = '\t';
1001         break;
1002         
1003         //Space -- ARGH!
1004         case 49:
1005         {
1006             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
1007             NSLog(@"%@", menuRef);
1008             SetMenuItemCommandKey(menuRef, 0, NO, 49);
1009             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
1010             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
1011             charcode = 'b';*/
1012         }
1013         break;
1014         
1015         case 51:
1016             charcode = NSDeleteFunctionKey;
1017         break;
1018         
1019         case 53:
1020             charcode = '\e';
1021         break;
1022         
1023         case 71:
1024             charcode = '\e';
1025         break;
1026         
1027         case 76:
1028             charcode = '\r';
1029         break;
1030         
1031         case 96:
1032             charcode = NSF5FunctionKey;
1033         break;
1034         
1035         case 97:
1036             charcode = NSF6FunctionKey;
1037         break;
1038         
1039         case 98:
1040             charcode = NSF7FunctionKey;
1041         break;
1042         
1043         case 99:
1044             charcode = NSF3FunctionKey;
1045         break;
1046         
1047         case 100:
1048             charcode = NSF8FunctionKey;
1049         break;
1050         
1051         case 101:
1052             charcode = NSF9FunctionKey;
1053         break;
1054         
1055         case 103:
1056             charcode = NSF11FunctionKey;
1057         break;
1058         
1059         case 105:
1060             charcode = NSF3FunctionKey;
1061         break;
1062         
1063         case 107:
1064             charcode = NSF14FunctionKey;
1065         break;
1066         
1067         case 109:
1068             charcode = NSF10FunctionKey;
1069         break;
1070         
1071         case 111:
1072             charcode = NSF12FunctionKey;
1073         break;
1074         
1075         case 113:
1076             charcode = NSF13FunctionKey;
1077         break;
1078         
1079         case 114:
1080             charcode = NSInsertFunctionKey;
1081         break;
1082         
1083         case 115:
1084             charcode = NSHomeFunctionKey;
1085         break;
1086         
1087         case 116:
1088             charcode = NSPageUpFunctionKey;
1089         break;
1090         
1091         case 117:
1092             charcode = NSDeleteFunctionKey;
1093         break;
1094         
1095         case 118:
1096             charcode = NSF4FunctionKey;
1097         break;
1098         
1099         case 119:
1100             charcode = NSEndFunctionKey;
1101         break;
1102         
1103         case 120:
1104             charcode = NSF2FunctionKey;
1105         break;
1106         
1107         case 121:
1108             charcode = NSPageDownFunctionKey;
1109         break;
1110         
1111         case 122:
1112             charcode = NSF1FunctionKey;
1113         break;
1114         
1115         case 123:
1116             charcode = NSLeftArrowFunctionKey;
1117         break;
1118         
1119         case 124:
1120             charcode = NSRightArrowFunctionKey;
1121         break;
1122         
1123         case 125:
1124             charcode = NSDownArrowFunctionKey;
1125         break;
1126         
1127         case 126:
1128             charcode = NSUpArrowFunctionKey;
1129         break;
1130     }
1131     
1132     if (charcode == 'a') {
1133         unsigned long state;
1134         long keyTrans;
1135         char charCode;
1136         Ptr kchr;
1137         state = 0;
1138         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1139         keyTrans = KeyTranslate(kchr, code, &state);
1140         charCode = keyTrans;
1141         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1142     } else if (charcode != 'b') {
1143         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1144     }
1145 }
1146
1147 /*************************************************************************/
1148 #pragma mark -
1149 #pragma mark NSApplication DELEGATE METHODS
1150 /*************************************************************************/
1151
1152 - (void)applicationWillTerminate:(NSNotification *)note
1153 {
1154     [self clearHotKeys];
1155     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1156 }
1157
1158
1159 /*************************************************************************/
1160 #pragma mark -
1161 #pragma mark DEALLOCATION METHODS
1162 /*************************************************************************/
1163
1164 - (void)dealloc
1165 {
1166     if (refreshTimer) {
1167         [refreshTimer invalidate];
1168         [refreshTimer release];
1169         refreshTimer = nil;
1170     }
1171     [currentRemote halt];
1172     [statusItem release];
1173     [menu release];
1174 //  [view release];
1175     [super dealloc];
1176 }
1177
1178 @end