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