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