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