Bugfixing
[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     
448     if (!isPlayingRadio) {
449         if (numSongs > 0) {
450             int curTrack = [currentRemote currentSongIndex];
451             int i;
452             
453             [upcomingSongsMenu release];
454             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
455             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
456             [upcomingSongsItem setEnabled:YES];
457             
458             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
459                 if (i <= numSongs) {
460                     NSString *curSong = [currentRemote songTitleAtIndex:i];
461                     NSMenuItem *songItem;
462                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
463                     [songItem setTarget:self];
464                     [songItem setRepresentedObject:[NSNumber numberWithInt:i + 1]];
465                     [upcomingSongsMenu addItem:songItem];
466                     [songItem release];
467                 } else {
468                     break;
469                 }
470             }
471         }
472     } else {
473         [upcomingSongsItem setSubmenu:nil];
474         [upcomingSongsItem setEnabled:NO];
475     }
476 }
477
478 - (void)rebuildPlaylistMenu
479 {
480     NSArray *playlists = [currentRemote playlists];
481     int i, curPlaylist = [currentRemote currentPlaylistIndex];
482     
483     if (isPlayingRadio)
484     {
485         curPlaylist = 0;
486     }
487     if (playlistMenu && ([playlists count] == [playlistMenu numberOfItems]))
488         return;
489     
490     [playlistMenu release];
491     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
492     
493     for (i = 0; i < [playlists count]; i++) {
494         NSString *playlistName = [playlists objectAtIndex:i];
495         NSMenuItem *tempItem;
496         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
497         [tempItem setTarget:self];
498         [tempItem setRepresentedObject:[NSNumber numberWithInt:i + 1]];
499         [playlistMenu addItem:tempItem];
500         [tempItem release];
501     }
502     [playlistItem setSubmenu:playlistMenu];
503     
504     if (curPlaylist) {
505         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
506     }
507 }
508
509 //Build a menu with the list of all available EQ presets
510 - (void)rebuildEQPresetsMenu
511 {
512     NSArray *eqPresets = [currentRemote eqPresets];
513     int i;
514     
515     if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
516         return;
517     
518     [eqMenu release];
519     eqMenu = [[NSMenu alloc] initWithTitle:@""];
520     
521     for (i = 0; i < [eqPresets count]; i++) {
522         NSString *setName = [eqPresets objectAtIndex:i];
523         NSMenuItem *tempItem;
524         if (setName) {
525         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
526         [tempItem setTarget:self];
527         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
528         [eqMenu addItem:tempItem];
529         [tempItem release];
530         }
531     }
532     [eqItem setSubmenu:eqMenu];
533     
534     [[eqMenu itemAtIndex:[currentRemote currentEQPresetIndex] - 1] setState:NSOnState];
535 }
536
537 - (void)clearHotKeys
538 {
539     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
540     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
541     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
542     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
543     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
544 }
545
546 - (void)setupHotKeys
547 {
548     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
549     
550     if ([defaults objectForKey:@"PlayPause"] != nil) {
551         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
552                 combo:[defaults keyComboForKey:@"PlayPause"]
553                 target:self action:@selector(playPause:)];
554     }
555     
556     if ([defaults objectForKey:@"NextTrack"] != nil) {
557         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
558                 combo:[defaults keyComboForKey:@"NextTrack"]
559                 target:self action:@selector(nextSong:)];
560     }
561     
562     if ([defaults objectForKey:@"PrevTrack"] != nil) {
563         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
564                 combo:[defaults keyComboForKey:@"PrevTrack"]
565                 target:self action:@selector(prevSong:)];
566     }
567     
568     if ([defaults objectForKey:@"TrackInfo"] != nil) {
569         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
570                 combo:[defaults keyComboForKey:@"TrackInfo"]
571                 target:self action:@selector(showCurrentTrackInfo)];
572     }
573     
574     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
575         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
576                combo:[defaults keyComboForKey:@"UpcomingSongs"]
577                target:self action:@selector(showUpcomingSongs)];
578     }
579 }
580
581 //Called when the timer fires.
582 - (void)timerUpdate
583 {
584     NSLog(@"%i", [currentRemote playerState]);
585     if ([currentRemote playerState] != stopped) {
586         int trackPlayingIndex = [currentRemote currentSongIndex];
587         int playlist = [currentRemote currentPlaylistIndex];
588         
589         if (trackPlayingIndex != lastSongIndex) {
590             BOOL wasPlayingRadio = isPlayingRadio;
591             isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
592             if (isPlayingRadio && !wasPlayingRadio) {
593                 int i;
594                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
595                 {
596                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
597                 }
598             }
599             if (wasPlayingRadio) {
600                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
601                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
602                 [temp release];
603             }
604             
605             [self updateMenu];
606             lastSongIndex = trackPlayingIndex;
607         }
608         else
609         {
610             if (playlist != [currentRemote currentPlaylistIndex]) {
611                 BOOL wasPlayingRadio = isPlayingRadio;
612                 isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
613                 if (isPlayingRadio && !wasPlayingRadio) {
614                     int i;
615                     for (i = 0; i < [playlistMenu numberOfItems]; i++)
616                     {
617                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
618                     }
619                 }
620                 if (wasPlayingRadio) {
621                     NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
622                     [menu insertItem:temp atIndex:trackInfoIndex + 1];
623                     [temp release];
624                 }
625                 [self updateMenu];
626                 lastSongIndex = trackPlayingIndex;
627             }
628         }
629         //Update Play/Pause menu item
630         if (playPauseMenuItem){
631             if ([currentRemote playerState] == playing) {
632                 [playPauseMenuItem setTitle:@"Pause"];
633             } else {
634                 [playPauseMenuItem setTitle:@"Play"];
635             }
636         }
637     }
638 }
639
640 - (void)iTunesLaunched:(NSNotification *)note
641 {
642     isAppRunning = YES;
643     
644     //Restart the timer
645     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
646     
647     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
648     [statusItem setMenu:menu]; //Set the menu back to the main one
649 }
650
651 - (void)iTunesTerminated:(NSNotification *)note
652 {
653     isAppRunning = NO;
654     
655     [menu release];
656     menu = [[NSMenu alloc] initWithTitle:@""];
657     [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
658     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
659     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
660     [statusItem setMenu:menu];
661     
662     [refreshTimer invalidate];
663     refreshTimer = nil;
664     [self clearHotKeys];
665 }
666
667 //
668 //
669 // Selectors - called from status item menu
670 //
671 //
672
673 // Plugin dependent selectors
674
675 - (void)playTrack:(id)sender
676 {
677     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
678     [self updateMenu];
679 }
680
681 - (void)selectPlaylist:(id)sender
682 {
683     int playlist = [[sender representedObject] intValue];
684     if (!isPlayingRadio) {
685         int curPlaylist = [currentRemote currentPlaylistIndex];
686         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
687     }
688     [currentRemote switchToPlaylistAtIndex:playlist];
689     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
690     [self updateMenu];
691 }
692
693 - (void)selectEQPreset:(id)sender
694 {
695     int curSet = [currentRemote currentEQPresetIndex];
696     int item = [[sender representedObject] intValue];
697     [currentRemote switchToEQAtIndex:item];
698     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
699     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
700 }
701
702 - (void)playPause:(id)sender
703 {
704     PlayerState state = [currentRemote playerState];
705     if (state == playing) {
706         [currentRemote pause];
707         [playPauseMenuItem setTitle:@"Play"];
708     } else if ((state == forwarding) || (state == rewinding)) {
709         [currentRemote pause];
710         [currentRemote play];
711     } else {
712         [currentRemote play];
713         [playPauseMenuItem setTitle:@"Pause"];
714     }
715 }
716
717 - (void)nextSong:(id)sender
718 {
719     [currentRemote goToNextSong];
720 }
721
722 - (void)prevSong:(id)sender
723 {
724     [currentRemote goToPreviousSong];
725 }
726
727 - (void)fastForward:(id)sender
728 {
729     [currentRemote fastForward];
730     [playPauseMenuItem setTitle:@"Play"];
731 }
732
733 - (void)rewind:(id)sender
734 {
735     [currentRemote rewind];
736     [playPauseMenuItem setTitle:@"Play"];
737 }
738
739 //
740 //
741 // Plugin independent selectors
742 //
743 //
744 - (void)quitMenuTunes:(id)sender
745 {
746     [NSApp terminate:self];
747 }
748
749 //How is this going to work, now that we're pluginized?
750 - (void)openiTunes:(id)sender
751 {
752     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
753 }
754
755 - (void)showPreferences:(id)sender
756 {
757     if (!prefsController) {
758         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
759         [self clearHotKeys];
760     }
761 }
762
763
764 - (void)closePreferences
765 {
766     if (isAppRunning) {
767         [self setupHotKeys];
768     }
769     [prefsController release];
770     prefsController = nil;
771 }
772
773 //
774 //
775 // Show Current Track Info And Show Upcoming Songs Floaters
776 //
777 //
778
779 - (void)showCurrentTrackInfo
780 {
781     NSString *trackName = [currentRemote currentSongTitle];
782     if (!statusWindow && [trackName length]) {
783         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
784         NSString *stringToShow = @"";
785         
786         if ([defaults boolForKey:@"showName"]) {
787             if ([defaults boolForKey:@"showArtist"]) {
788                 NSString *trackArtist = [currentRemote currentSongArtist];
789                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
790             }
791             stringToShow = [stringToShow stringByAppendingString:trackName];
792             stringToShow = [stringToShow stringByAppendingString:@"\n"];
793         }
794         
795         if ([defaults boolForKey:@"showAlbum"]) {
796             NSString *trackAlbum = [currentRemote currentSongAlbum];
797             if ([trackAlbum length]) {
798                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
799                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
800             }
801         }
802         
803         if ([defaults boolForKey:@"showTime"]) {
804             NSString *trackTime = [currentRemote currentSongLength];
805             if ([trackTime length]) {
806                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
807             }
808         }
809         
810         {
811             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
812             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
813             if (seconds < 10) {
814                 stringToShow = [stringToShow stringByAppendingString:
815                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
816             } else {
817                 stringToShow = [stringToShow stringByAppendingString:
818                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
819             }
820         }
821         
822         [statusWindow setTrackInfo:stringToShow];
823         [NSTimer scheduledTimerWithTimeInterval:3.0
824                                     target:self
825                                     selector:@selector(fadeAndCloseStatusWindow)
826                                     userInfo:nil
827                                     repeats:NO];
828     }
829 }
830
831 - (void)showUpcomingSongs
832 {
833     int curPlaylist = [currentRemote currentPlaylistIndex];
834     if (!statusWindow) {
835         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
836         
837         if (numSongs > 0) {
838             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
839             int curTrack = [currentRemote currentSongIndex];
840             int i;
841             NSString *songs = @"";
842             
843             statusWindow = [ITTransientStatusWindow sharedWindow];
844             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
845                 if (i <= numSongs) {
846                     NSString *curSong = [currentRemote songTitleAtIndex:i];
847                     songs = [songs stringByAppendingString:curSong];
848                     songs = [songs stringByAppendingString:@"\n"];
849                 }
850             }
851             [statusWindow setUpcomingSongs:songs];
852             [NSTimer scheduledTimerWithTimeInterval:3.0
853                         target:self
854                         selector:@selector(fadeAndCloseStatusWindow)
855                         userInfo:nil
856                         repeats:NO];
857         }
858     }
859 }
860
861 - (void)fadeAndCloseStatusWindow
862 {
863     [statusWindow orderOut:self];
864 }
865
866 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
867         onItem:(NSMenuItem *)item
868 {
869     unichar charcode = 'a';
870     int i;
871     long cocoaModifiers = 0;
872     static long carbonToCocoa[6][2] = 
873     {
874         { cmdKey, NSCommandKeyMask },
875         { optionKey, NSAlternateKeyMask },
876         { controlKey, NSControlKeyMask },
877         { shiftKey, NSShiftKeyMask },
878     };
879     
880     for (i = 0; i < 6; i++)
881     {
882         if (modifiers & carbonToCocoa[i][0])
883         {
884             cocoaModifiers += carbonToCocoa[i][1];
885         }
886     }
887     [item setKeyEquivalentModifierMask:cocoaModifiers];
888     
889     //Missing key combos for some keys. Must find them later.
890     switch (code)
891     {
892         case 36:
893             charcode = '\r';
894         break;
895         
896         case 48:
897             charcode = '\t';
898         break;
899         
900         //Space -- ARGH!
901         case 49:
902         {
903             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
904             NSLog(@"%@", menuRef);
905             SetMenuItemCommandKey(menuRef, 0, NO, 49);
906             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
907             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
908             charcode = 'b';*/
909         }
910         break;
911         
912         case 51:
913             charcode = NSDeleteFunctionKey;
914         break;
915         
916         case 53:
917             charcode = '\e';
918         break;
919         
920         case 71:
921             charcode = '\e';
922         break;
923         
924         case 76:
925             charcode = '\r';
926         break;
927         
928         case 96:
929             charcode = NSF5FunctionKey;
930         break;
931         
932         case 97:
933             charcode = NSF6FunctionKey;
934         break;
935         
936         case 98:
937             charcode = NSF7FunctionKey;
938         break;
939         
940         case 99:
941             charcode = NSF3FunctionKey;
942         break;
943         
944         case 100:
945             charcode = NSF8FunctionKey;
946         break;
947         
948         case 101:
949             charcode = NSF9FunctionKey;
950         break;
951         
952         case 103:
953             charcode = NSF11FunctionKey;
954         break;
955         
956         case 105:
957             charcode = NSF3FunctionKey;
958         break;
959         
960         case 107:
961             charcode = NSF14FunctionKey;
962         break;
963         
964         case 109:
965             charcode = NSF10FunctionKey;
966         break;
967         
968         case 111:
969             charcode = NSF12FunctionKey;
970         break;
971         
972         case 113:
973             charcode = NSF13FunctionKey;
974         break;
975         
976         case 114:
977             charcode = NSInsertFunctionKey;
978         break;
979         
980         case 115:
981             charcode = NSHomeFunctionKey;
982         break;
983         
984         case 116:
985             charcode = NSPageUpFunctionKey;
986         break;
987         
988         case 117:
989             charcode = NSDeleteFunctionKey;
990         break;
991         
992         case 118:
993             charcode = NSF4FunctionKey;
994         break;
995         
996         case 119:
997             charcode = NSEndFunctionKey;
998         break;
999         
1000         case 120:
1001             charcode = NSF2FunctionKey;
1002         break;
1003         
1004         case 121:
1005             charcode = NSPageDownFunctionKey;
1006         break;
1007         
1008         case 122:
1009             charcode = NSF1FunctionKey;
1010         break;
1011         
1012         case 123:
1013             charcode = NSLeftArrowFunctionKey;
1014         break;
1015         
1016         case 124:
1017             charcode = NSRightArrowFunctionKey;
1018         break;
1019         
1020         case 125:
1021             charcode = NSDownArrowFunctionKey;
1022         break;
1023         
1024         case 126:
1025             charcode = NSUpArrowFunctionKey;
1026         break;
1027     }
1028     
1029     if (charcode == 'a') {
1030         unsigned long state;
1031         long keyTrans;
1032         char charCode;
1033         Ptr kchr;
1034         state = 0;
1035         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1036         keyTrans = KeyTranslate(kchr, code, &state);
1037         charCode = keyTrans;
1038         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1039     } else if (charcode != 'b') {
1040         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1041     }
1042 }
1043
1044 /*************************************************************************/
1045 #pragma mark -
1046 #pragma mark NSApplication DELEGATE METHODS
1047 /*************************************************************************/
1048
1049 - (void)applicationWillTerminate:(NSNotification *)note
1050 {
1051     [self clearHotKeys];
1052     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1053 }
1054
1055
1056 /*************************************************************************/
1057 #pragma mark -
1058 #pragma mark DEALLOCATION METHODS
1059 /*************************************************************************/
1060
1061 - (void)dealloc
1062 {
1063     if (refreshTimer) {
1064         [refreshTimer invalidate];
1065         refreshTimer = nil;
1066     }
1067     [currentRemote halt];
1068     [statusItem release];
1069     [menu release];
1070 //  [view release];
1071     [super dealloc];
1072 }
1073
1074 @end