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