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