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