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