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