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