Added stuff for current song rating. Right now in the submenu there are
[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     int i;
526     
527     if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
528         return;
529     
530     [eqMenu release];
531     eqMenu = [[NSMenu alloc] initWithTitle:@""];
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     PlayerState playerState = [currentRemote playerState];
598     
599     if ((playlist > 0) || playerState != stopped) {
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 == playing) {
659                 [playPauseMenuItem setTitle:@"Pause"];
660             } else {
661                 [playPauseMenuItem setTitle:@"Play"];
662             }
663         }
664     }
665 }
666
667 - (void)remotePlayerLaunched:(NSNotification *)note
668 {
669     isAppRunning = YES;
670     
671     //Restart the timer
672     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
673     
674     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
675     [self rebuildPlaylistMenu];
676     [statusItem setMenu:menu]; //Set the menu back to the main one
677 }
678
679 - (void)remotePlayerTerminated:(NSNotification *)note
680 {
681     isAppRunning = NO;
682     
683     [menu release];
684     menu = [[NSMenu alloc] initWithTitle:@""];
685     [menu addItemWithTitle:@"Audio Player" action:NULL keyEquivalent:@""];
686     [menu addItemWithTitle:@"Not Running" action:NULL keyEquivalent:@""];
687     [menu addItem:[NSMenuItem separatorItem]];
688     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
689     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
690     [statusItem setMenu:menu];
691     
692     [refreshTimer invalidate];
693     refreshTimer = nil;
694     [self clearHotKeys];
695 }
696
697 //
698 //
699 // Selectors - called from status item menu
700 //
701 //
702
703 // Plugin dependent selectors
704
705 - (void)playTrack:(id)sender
706 {
707     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
708     [self updateMenu];
709 }
710
711 - (void)selectPlaylist:(id)sender
712 {
713     int playlist = [[sender representedObject] intValue];
714     if (!isPlayingRadio) {
715         int curPlaylist = [currentRemote currentPlaylistIndex];
716         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
717     }
718     [currentRemote switchToPlaylistAtIndex:playlist];
719     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
720     [self updateMenu];
721 }
722
723 - (void)selectEQPreset:(id)sender
724 {
725     int curSet = [currentRemote currentEQPresetIndex];
726     int item = [[sender representedObject] intValue];
727     [currentRemote switchToEQAtIndex:item];
728     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
729     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
730 }
731
732 - (void)playPause:(id)sender
733 {
734     PlayerState state = [currentRemote playerState];
735     
736     if (state == playing) {
737         [currentRemote pause];
738         [playPauseMenuItem setTitle:@"Play"];
739     } else if ((state == forwarding) || (state == rewinding)) {
740         [currentRemote pause];
741         [currentRemote play];
742     } else {
743         [currentRemote play];
744         [playPauseMenuItem setTitle:@"Pause"];
745     }
746 }
747
748 - (void)nextSong:(id)sender
749 {
750     [currentRemote goToNextSong];
751 }
752
753 - (void)prevSong:(id)sender
754 {
755     [currentRemote goToPreviousSong];
756 }
757
758 - (void)fastForward:(id)sender
759 {
760     [currentRemote fastForward];
761     [playPauseMenuItem setTitle:@"Play"];
762 }
763
764 - (void)rewind:(id)sender
765 {
766     [currentRemote rewind];
767     [playPauseMenuItem setTitle:@"Play"];
768 }
769
770 - (void)setSongRating:(id)sender
771 {
772     //[currentRemote setCurrentSongRating:[sender tag]];
773 }
774
775 //
776 //
777 // Plugin independent selectors
778 //
779 //
780 - (void)quitMenuTunes:(id)sender
781 {
782     [NSApp terminate:self];
783 }
784
785 - (void)showPreferences:(id)sender
786 {
787     if (!prefsController) {
788         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
789         [self clearHotKeys];
790     }
791 }
792
793 - (void)closePreferences
794 {
795     if (isAppRunning) {
796         [self setupHotKeys];
797     }
798     [prefsController release];
799     prefsController = nil;
800 }
801
802 //
803 //
804 // Show Current Track Info And Show Upcoming Songs Floaters
805 //
806 //
807
808 - (void)showCurrentTrackInfo
809 {
810     NSString *trackName = [currentRemote currentSongTitle];
811     if (!statusWindow && [trackName length]) {
812         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
813         NSString *stringToShow = @"";
814         
815         if ([defaults boolForKey:@"showName"]) {
816             if ([defaults boolForKey:@"showArtist"]) {
817                 NSString *trackArtist = [currentRemote currentSongArtist];
818                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
819             }
820             stringToShow = [stringToShow stringByAppendingString:trackName];
821             stringToShow = [stringToShow stringByAppendingString:@"\n"];
822         }
823         
824         if ([defaults boolForKey:@"showAlbum"]) {
825             NSString *trackAlbum = [currentRemote currentSongAlbum];
826             if ([trackAlbum length]) {
827                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
828                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
829             }
830         }
831         
832         if ([defaults boolForKey:@"showTime"]) {
833             NSString *trackTime = [currentRemote currentSongLength];
834             if ([trackTime length]) {
835                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
836             }
837         }
838         
839         {
840             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
841             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
842             if (seconds < 10) {
843                 stringToShow = [stringToShow stringByAppendingString:
844                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
845             } else {
846                 stringToShow = [stringToShow stringByAppendingString:
847                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
848             }
849         }
850         
851         [statusWindow setText:stringToShow];
852         [NSTimer scheduledTimerWithTimeInterval:3.0
853                     target:self
854                     selector:@selector(fadeAndCloseStatusWindow)
855                     userInfo:nil
856                     repeats:NO];
857     }
858 }
859
860 - (void)showUpcomingSongs
861 {
862     int curPlaylist = [currentRemote currentPlaylistIndex];
863     if (!statusWindow) {
864         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
865         
866         if (numSongs > 0) {
867             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
868             int curTrack = [currentRemote currentSongIndex];
869             int i;
870             NSString *songs = @"";
871             
872             statusWindow = [ITTransientStatusWindow sharedWindow];
873             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
874                 if (i <= numSongs) {
875                     NSString *curSong = [currentRemote songTitleAtIndex:i];
876                     songs = [songs stringByAppendingString:curSong];
877                     songs = [songs stringByAppendingString:@"\n"];
878                 }
879             }
880             [statusWindow setText:songs];
881             [NSTimer scheduledTimerWithTimeInterval:3.0
882                         target:self
883                         selector:@selector(fadeAndCloseStatusWindow)
884                         userInfo:nil
885                         repeats:NO];
886         }
887     }
888 }
889
890 - (void)fadeAndCloseStatusWindow
891 {
892     [statusWindow orderOut:self];
893 }
894
895 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
896         onItem:(NSMenuItem *)item
897 {
898     unichar charcode = 'a';
899     int i;
900     long cocoaModifiers = 0;
901     static long carbonToCocoa[6][2] = 
902     {
903         { cmdKey, NSCommandKeyMask },
904         { optionKey, NSAlternateKeyMask },
905         { controlKey, NSControlKeyMask },
906         { shiftKey, NSShiftKeyMask },
907     };
908     
909     for (i = 0; i < 6; i++) {
910         if (modifiers & carbonToCocoa[i][0]) {
911             cocoaModifiers += carbonToCocoa[i][1];
912         }
913     }
914     [item setKeyEquivalentModifierMask:cocoaModifiers];
915     
916     //Missing key combos for some keys. Must find them later.
917     switch (code)
918     {
919         case 36:
920             charcode = '\r';
921         break;
922         
923         case 48:
924             charcode = '\t';
925         break;
926         
927         //Space -- ARGH!
928         case 49:
929         {
930             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
931             NSLog(@"%@", menuRef);
932             SetMenuItemCommandKey(menuRef, 0, NO, 49);
933             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
934             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
935             charcode = 'b';*/
936         }
937         break;
938         
939         case 51:
940             charcode = NSDeleteFunctionKey;
941         break;
942         
943         case 53:
944             charcode = '\e';
945         break;
946         
947         case 71:
948             charcode = '\e';
949         break;
950         
951         case 76:
952             charcode = '\r';
953         break;
954         
955         case 96:
956             charcode = NSF5FunctionKey;
957         break;
958         
959         case 97:
960             charcode = NSF6FunctionKey;
961         break;
962         
963         case 98:
964             charcode = NSF7FunctionKey;
965         break;
966         
967         case 99:
968             charcode = NSF3FunctionKey;
969         break;
970         
971         case 100:
972             charcode = NSF8FunctionKey;
973         break;
974         
975         case 101:
976             charcode = NSF9FunctionKey;
977         break;
978         
979         case 103:
980             charcode = NSF11FunctionKey;
981         break;
982         
983         case 105:
984             charcode = NSF3FunctionKey;
985         break;
986         
987         case 107:
988             charcode = NSF14FunctionKey;
989         break;
990         
991         case 109:
992             charcode = NSF10FunctionKey;
993         break;
994         
995         case 111:
996             charcode = NSF12FunctionKey;
997         break;
998         
999         case 113:
1000             charcode = NSF13FunctionKey;
1001         break;
1002         
1003         case 114:
1004             charcode = NSInsertFunctionKey;
1005         break;
1006         
1007         case 115:
1008             charcode = NSHomeFunctionKey;
1009         break;
1010         
1011         case 116:
1012             charcode = NSPageUpFunctionKey;
1013         break;
1014         
1015         case 117:
1016             charcode = NSDeleteFunctionKey;
1017         break;
1018         
1019         case 118:
1020             charcode = NSF4FunctionKey;
1021         break;
1022         
1023         case 119:
1024             charcode = NSEndFunctionKey;
1025         break;
1026         
1027         case 120:
1028             charcode = NSF2FunctionKey;
1029         break;
1030         
1031         case 121:
1032             charcode = NSPageDownFunctionKey;
1033         break;
1034         
1035         case 122:
1036             charcode = NSF1FunctionKey;
1037         break;
1038         
1039         case 123:
1040             charcode = NSLeftArrowFunctionKey;
1041         break;
1042         
1043         case 124:
1044             charcode = NSRightArrowFunctionKey;
1045         break;
1046         
1047         case 125:
1048             charcode = NSDownArrowFunctionKey;
1049         break;
1050         
1051         case 126:
1052             charcode = NSUpArrowFunctionKey;
1053         break;
1054     }
1055     
1056     if (charcode == 'a') {
1057         unsigned long state;
1058         long keyTrans;
1059         char charCode;
1060         Ptr kchr;
1061         state = 0;
1062         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1063         keyTrans = KeyTranslate(kchr, code, &state);
1064         charCode = keyTrans;
1065         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1066     } else if (charcode != 'b') {
1067         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1068     }
1069 }
1070
1071 /*************************************************************************/
1072 #pragma mark -
1073 #pragma mark NSApplication DELEGATE METHODS
1074 /*************************************************************************/
1075
1076 - (void)applicationWillTerminate:(NSNotification *)note
1077 {
1078     [self clearHotKeys];
1079     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1080 }
1081
1082
1083 /*************************************************************************/
1084 #pragma mark -
1085 #pragma mark DEALLOCATION METHODS
1086 /*************************************************************************/
1087
1088 - (void)dealloc
1089 {
1090     if (refreshTimer) {
1091         [refreshTimer invalidate];
1092         refreshTimer = nil;
1093     }
1094     [currentRemote halt];
1095     [statusItem release];
1096     [menu release];
1097 //  [view release];
1098     [super dealloc];
1099 }
1100
1101 @end