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