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