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