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