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