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