Updated to version 1.6.5
[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(terminate:) keyEquivalent:@""] setTarget:NSApp];
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             ITKeyCombo *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             ITKeyCombo *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             ITKeyCombo *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(terminate:)
304                     keyEquivalent:@""] setTarget:NSApp];
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 playerStateUniqueIdentifier] 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 ) {
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 playerStateUniqueIdentifier];
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 showCurrentTrackInfoStatusWindow];
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
616 - (void)showPlayer:(id)sender
617 {
618     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
619         [currentRemote showPrimaryInterface];
620     } else {
621         if (![[NSWorkspace sharedWorkspace] launchApplication:[currentRemote playerFullName]]) {
622             NSLog(@"Error Launching Player");
623         }
624     }
625 }
626
627 - (void)showPreferences:(id)sender
628 {
629     [[PreferencesController sharedPrefs] setController:self];
630     [[PreferencesController sharedPrefs] showPrefsWindow:self];
631 }
632
633 - (void)closePreferences
634 {
635     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
636         [self setupHotKeys];
637     }
638 }
639
640 - (ITMTRemote *)currentRemote
641 {
642     return currentRemote;
643 }
644
645 //
646 //
647 // Hot key setup
648 //
649 //
650
651 - (void)clearHotKeys
652 {
653     [[ITHotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
654     [[ITHotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
655     [[ITHotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
656     [[ITHotKeyCenter sharedCenter] removeHotKey:@"ToggleVisualizer"];
657     [[ITHotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
658     [[ITHotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
659     [[ITHotKeyCenter sharedCenter] removeHotKey:@"ToggleLoop"];
660     [[ITHotKeyCenter sharedCenter] removeHotKey:@"ToggleShuffle"];
661     [[ITHotKeyCenter sharedCenter] removeHotKey:@"IncrementVolume"];
662     [[ITHotKeyCenter sharedCenter] removeHotKey:@"DecrementVolume"];
663     [[ITHotKeyCenter sharedCenter] removeHotKey:@"IncrementRating"];
664     [[ITHotKeyCenter sharedCenter] removeHotKey:@"DecrementRating"];
665 }
666
667 - (void)setupHotKeys
668 {
669     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
670     
671     if ([defaults objectForKey:@"PlayPause"] != nil) {
672         [[ITHotKeyCenter sharedCenter] addHotKey:@"PlayPause"
673                 combo:[defaults keyComboForKey:@"PlayPause"]
674                 target:self action:@selector(playPause:)];
675     }
676     
677     if ([defaults objectForKey:@"NextTrack"] != nil) {
678         [[ITHotKeyCenter sharedCenter] addHotKey:@"NextTrack"
679                 combo:[defaults keyComboForKey:@"NextTrack"]
680                 target:self action:@selector(nextSong:)];
681     }
682     
683     if ([defaults objectForKey:@"PrevTrack"] != nil) {
684         [[ITHotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
685                 combo:[defaults keyComboForKey:@"PrevTrack"]
686                 target:self action:@selector(prevSong:)];
687     }
688     
689     if ([defaults objectForKey:@"ToggleVisualizer"] != nil) {
690         [[ITHotKeyCenter sharedCenter] addHotKey:@"ToggleVisualizer"
691                 combo:[defaults keyComboForKey:@"ToggleVisualizer"]
692                 target:self action:@selector(toggleVisualizer)];
693     }
694     
695     if ([defaults objectForKey:@"TrackInfo"] != nil) {
696         [[ITHotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
697                 combo:[defaults keyComboForKey:@"TrackInfo"]
698                 target:self action:@selector(showCurrentTrackInfoStatusWindow)];
699     }
700     
701     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
702         [[ITHotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
703                combo:[defaults keyComboForKey:@"UpcomingSongs"]
704                target:self action:@selector(showUpcomingSongsStatusWindow)];
705     }
706     
707     if ([defaults objectForKey:@"ToggleLoop"] != nil) {
708         [[ITHotKeyCenter sharedCenter] addHotKey:@"ToggleLoop"
709                combo:[defaults keyComboForKey:@"ToggleLoop"]
710                target:self action:@selector(showToggleLoopStatusWindow)];
711     }
712     
713     if ([defaults objectForKey:@"ToggleShuffle"] != nil) {
714         [[ITHotKeyCenter sharedCenter] addHotKey:@"ToggleShuffle"
715                combo:[defaults keyComboForKey:@"ToggleShuffle"]
716                target:self action:@selector(showToggleShuffleStatusWindow)];
717     }
718     
719     if ([defaults objectForKey:@"IncrementVolume"] != nil) {
720         [[ITHotKeyCenter sharedCenter] addHotKey:@"IncrementVolume"
721                combo:[defaults keyComboForKey:@"IncrementVolume"]
722                target:self action:@selector(showVolumeIncrementStatusWindow)];
723     }
724     
725     if ([defaults objectForKey:@"DecrementVolume"] != nil) {
726         [[ITHotKeyCenter sharedCenter] addHotKey:@"DecrementVolume"
727                combo:[defaults keyComboForKey:@"DecrementVolume"]
728                target:self action:@selector(showVolumeDecrementStatusWindow)];
729     }
730     
731     if ([defaults objectForKey:@"IncrementRating"] != nil) {
732         [[ITHotKeyCenter sharedCenter] addHotKey:@"IncrementRating"
733                combo:[defaults keyComboForKey:@"IncrementRating"]
734                target:self action:@selector(showRatingIncrementStatusWindow)];
735     }
736     
737     if ([defaults objectForKey:@"DecrementRating"] != nil) {
738         [[ITHotKeyCenter sharedCenter] addHotKey:@"DecrementRating"
739                combo:[defaults keyComboForKey:@"DecrementRating"]
740                target:self action:@selector(showRatingDecrementStatusWindow)];
741     }
742 }
743
744 //
745 //
746 // Status Window Methods
747 //
748 //
749
750 - (void)showCurrentTrackInfoStatusWindow
751 {
752     NSString *trackName = [currentRemote currentSongTitle];
753     if (!statusWindow && [trackName length]) {
754         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
755         NSString *stringToShow = @"";
756         
757         if ([defaults boolForKey:@"showName"]) {
758             if ([defaults boolForKey:@"showArtist"]) {
759                 NSString *trackArtist = [currentRemote currentSongArtist];
760                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
761             }
762             stringToShow = [stringToShow stringByAppendingString:trackName];
763             stringToShow = [stringToShow stringByAppendingString:@"\n"];
764         }
765         
766         if ([defaults boolForKey:@"showAlbum"]) {
767             NSString *trackAlbum = [currentRemote currentSongAlbum];
768             if ( trackAlbum ) {
769                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
770                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
771             }
772         }
773         
774         if ([defaults boolForKey:@"showTime"]) {
775             NSString *trackTime = [currentRemote currentSongLength];
776             if ([trackTime length]) {
777                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
778             }
779         }
780         
781         {
782             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
783             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
784             if (seconds < 10) {
785                 stringToShow = [stringToShow stringByAppendingString:
786                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
787             } else {
788                 stringToShow = [stringToShow stringByAppendingString:
789                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
790             }
791         }
792         
793         //
794         //SHOW THE STATUS WINDOW HERE WITH STRING stringToShow
795         //
796         
797         /*[statusWindow setText:stringToShow];
798         [NSTimer scheduledTimerWithTimeInterval:3.0
799                     target:self
800                     selector:@selector(fadeAndCloseStatusWindow)
801                     userInfo:nil
802                     repeats:NO];*/
803     }
804 }
805
806 - (void)showUpcomingSongsStatusWindow
807 {
808     int curPlaylist = [currentRemote currentPlaylistIndex];
809     if (!statusWindow) {
810         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
811         
812         if (numSongs > 0) {
813             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
814             int curTrack = [currentRemote currentSongIndex];
815             int i;
816             NSString *songs = @"";
817             
818             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
819                 if (i <= numSongs) {
820                     NSString *curSong = [currentRemote songTitleAtIndex:i];
821                     songs = [songs stringByAppendingString:curSong];
822                     songs = [songs stringByAppendingString:@"\n"];
823                 }
824             }
825             
826             //
827             //SHOW STATUS WINDOW HERE WITH STRING songs
828             //
829             
830             /*[statusWindow setText:songs];
831             [NSTimer scheduledTimerWithTimeInterval:3.0
832                         target:self
833                         selector:@selector(fadeAndCloseStatusWindow)
834                         userInfo:nil
835                         repeats:NO];*/
836         }
837     }
838 }
839
840 - (void)showVolumeIncrementStatusWindow
841 {
842 }
843
844 - (void)showVolumeDecrementStatusWindow
845 {
846 }
847
848 - (void)showRatingIncrementStatusWindow
849 {
850 }
851
852 - (void)showRatingDecrementStatusWindow
853 {
854 }
855
856 - (void)showToggleLoopStatusWindow
857 {
858 }
859
860 - (void)showToggleShuffleStatusWindow
861 {
862 }
863
864 - (void)toggleVisualizer
865 {
866     NSLog(@"Visualizer On/Off");
867 }
868
869 - (void)fadeAndCloseStatusWindow
870 {
871     [statusWindow orderOut:self];
872 }
873
874 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
875         onItem:(NSMenuItem *)item
876 {
877     unichar charcode = 'a';
878     int i;
879     long cocoaModifiers = 0;
880     static long carbonToCocoa[6][2] = 
881     {
882         { cmdKey, NSCommandKeyMask },
883         { optionKey, NSAlternateKeyMask },
884         { controlKey, NSControlKeyMask },
885         { shiftKey, NSShiftKeyMask },
886     };
887     
888     for (i = 0; i < 6; i++) {
889         if (modifiers & carbonToCocoa[i][0]) {
890             cocoaModifiers += carbonToCocoa[i][1];
891         }
892     }
893     [item setKeyEquivalentModifierMask:cocoaModifiers];
894     
895     //Missing key combos for some keys. Must find them later.
896     switch (code)
897     {
898         case 36:
899             charcode = '\r';
900         break;
901         
902         case 48:
903             charcode = '\t';
904         break;
905         
906         //Space -- ARGH!
907         case 49:
908         {
909             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
910             SetMenuItemCommandKey(menuRef, 1, NO, 49);
911             SetMenuItemModifiers(menuRef, 1, kMenuNoCommandModifier);
912             SetMenuItemKeyGlyph(menuRef, 1, kMenuBlankGlyph);*/
913             charcode = 'b';
914             
915         }
916         break;
917         
918         case 51:
919             charcode = NSDeleteFunctionKey;
920         break;
921         
922         case 53:
923             charcode = '\e';
924         break;
925         
926         case 71:
927             charcode = '\e';
928         break;
929         
930         case 76:
931             charcode = '\r';
932         break;
933         
934         case 96:
935             charcode = NSF5FunctionKey;
936         break;
937         
938         case 97:
939             charcode = NSF6FunctionKey;
940         break;
941         
942         case 98:
943             charcode = NSF7FunctionKey;
944         break;
945         
946         case 99:
947             charcode = NSF3FunctionKey;
948         break;
949         
950         case 100:
951             charcode = NSF8FunctionKey;
952         break;
953         
954         case 101:
955             charcode = NSF9FunctionKey;
956         break;
957         
958         case 103:
959             charcode = NSF11FunctionKey;
960         break;
961         
962         case 105:
963             charcode = NSF3FunctionKey;
964         break;
965         
966         case 107:
967             charcode = NSF14FunctionKey;
968         break;
969         
970         case 109:
971             charcode = NSF10FunctionKey;
972         break;
973         
974         case 111:
975             charcode = NSF12FunctionKey;
976         break;
977         
978         case 113:
979             charcode = NSF13FunctionKey;
980         break;
981         
982         case 114:
983             charcode = NSInsertFunctionKey;
984         break;
985         
986         case 115:
987             charcode = NSHomeFunctionKey;
988         break;
989         
990         case 116:
991             charcode = NSPageUpFunctionKey;
992         break;
993         
994         case 117:
995             charcode = NSDeleteFunctionKey;
996         break;
997         
998         case 118:
999             charcode = NSF4FunctionKey;
1000         break;
1001         
1002         case 119:
1003             charcode = NSEndFunctionKey;
1004         break;
1005         
1006         case 120:
1007             charcode = NSF2FunctionKey;
1008         break;
1009         
1010         case 121:
1011             charcode = NSPageDownFunctionKey;
1012         break;
1013         
1014         case 122:
1015             charcode = NSF1FunctionKey;
1016         break;
1017         
1018         case 123:
1019             charcode = NSLeftArrowFunctionKey;
1020         break;
1021         
1022         case 124:
1023             charcode = NSRightArrowFunctionKey;
1024         break;
1025         
1026         case 125:
1027             charcode = NSDownArrowFunctionKey;
1028         break;
1029         
1030         case 126:
1031             charcode = NSUpArrowFunctionKey;
1032         break;
1033     }
1034     
1035     if (charcode == 'a') {
1036         unsigned long state;
1037         long keyTrans;
1038         char charCode;
1039         Ptr kchr;
1040         state = 0;
1041         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1042         keyTrans = KeyTranslate(kchr, code, &state);
1043         charCode = keyTrans;
1044         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1045     } else if (charcode != 'b') {
1046         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1047     }
1048 }
1049
1050 @end