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