Should Build and Run with the new Controller
[MenuTunes.git] / MainController.m
1 #import "NewMainController.h"
2 #import "PreferencesController.h"
3 #import "HotKeyCenter.h"
4 #import "StatusWindowController.h"
5
6 @interface MainController(Private)
7 - (ITMTRemote *)loadRemote;
8 - (void)setupHotKeys;
9 - (void)timerUpdate;
10 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
11         onItem:(NSMenuItem *)item;
12 @end
13
14 @implementation MainController
15
16 /*************************************************************************/
17 #pragma mark -
18 #pragma mark INITIALIZATION/DEALLOCATION METHODS
19 /*************************************************************************/
20
21 - (id)init
22 {
23     if ( ( self = [super init] ) ) {
24         remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
25         statusWindowController = [[StatusWindowController alloc] init];
26         df = [[NSUserDefaults standardUserDefaults] retain];
27         [self setLatestSongIdentifier:@"0-0"];
28     }
29     return self;
30 }
31
32 - (void)applicationDidFinishLaunching:(NSNotification *)note
33 {
34     currentRemote = [self loadRemote];
35     [currentRemote begin];
36     
37     //Setup for notification of the remote player launching or quitting
38     [[[NSWorkspace sharedWorkspace] notificationCenter]
39             addObserver:self
40             selector:@selector(applicationTerminated:)
41             name:NSWorkspaceDidTerminateApplicationNotification
42             object:nil];
43     
44     [[[NSWorkspace sharedWorkspace] notificationCenter]
45             addObserver:self
46             selector:@selector(applicationLaunched:)
47             name:NSWorkspaceDidLaunchApplicationNotification
48             object:nil];
49
50     if ( ! [df objectForKey:@"menu"] ) {  // If this is nil, defaults have never been registered.
51         [[PreferencesController sharedPrefs] registerDefaults];
52     }
53     
54     statusItem = [[ITStatusItem alloc]
55             initWithStatusBar:[NSStatusBar systemStatusBar]
56             withLength:NSSquareStatusItemLength];
57     
58     [statusItem setImage:[NSImage imageNamed:@"menu"]];
59     [statusItem setAlternateImage:[NSImage imageNamed:@"selected_image"]];
60 }
61
62 - (ITMTRemote *)loadRemote
63 {
64     NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
65     
66     if (folderPath) {
67         NSArray      *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
68         NSEnumerator *enumerator     = [bundlePathList objectEnumerator];
69         NSString     *bundlePath;
70
71         while ( (bundlePath = [enumerator nextObject]) ) {
72             NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
73
74             if (remoteBundle) {
75                 Class remoteClass = [remoteBundle principalClass];
76
77                 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
78                     [remoteClass isKindOfClass:[NSObject class]]) {
79
80                     id remote = [remoteClass remote];
81                     [remoteArray addObject:remote];
82                 }
83             }
84         }
85
86 //      if ( [remoteArray count] > 0 ) {  // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
87 //          if ( [remoteArray count] > 1 ) {
88 //              [remoteArray sortUsingSelector:@selector(sortAlpha:)];
89 //          }
90 //          [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
91 //      }
92     }
93 //  NSLog(@"%@", [remoteArray objectAtIndex:0]);  //DEBUG
94     return [remoteArray objectAtIndex:0];
95 }
96
97 /*************************************************************************/
98 #pragma mark -
99 #pragma mark INSTANCE METHODS
100 /*************************************************************************/
101
102 - (void)startTimerInNewThread
103 {
104     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
105     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
106     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
107                              target:self
108                              selector:@selector(timerUpdate)
109                              userInfo:nil
110                              repeats:YES] retain];
111     [runLoop run];
112     [pool release];
113 }
114
115
116 /*************************************************************************/
117 #pragma mark -
118 #pragma mark MENU BUILDING METHODS
119 /*************************************************************************/
120
121 - (NSMenu *)menu
122 {
123     NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
124     
125     [theMenu addItem:[self playlistMenuItem]];
126     [theMenu addItem:[self upcomingSongsMenuItem]];
127     [theMenu addItem:[self ratingMenuItem]];
128
129     return theMenu;
130 }
131
132 - (NSMenu *)menuForNoPlayer
133 {
134     return nil;
135 }
136
137 - (NSMenuItem *)playlistMenuItem
138 {
139     NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"Playlists"
140                                                    action:nil
141                                             keyEquivalent:@""] autorelease];
142     NSMenu  *submenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
143
144     int           currentPlaylist = [currentRemote currentPlaylistIndex];
145     NSArray      *playlists       = [currentRemote playlists];
146     NSEnumerator *playlistEnum    = [playlists objectEnumerator];
147     int           playlistTag     = 1;
148     id            aPlaylist;
149
150     [item setSubmenu:submenu];
151     [submenu setAutoenablesItems:NO];
152     
153     while ( (aPlaylist = [playlistEnum nextObject]) ) {
154         NSMenuItem *playlistItem = [[[NSMenuItem alloc] initWithTitle:aPlaylist
155                                                                action:@selector(selectPlaylist:)
156                                                         keyEquivalent:@""] autorelease];
157         [playlistItem setTag:playlistTag];
158         [playlistItem setTarget:self];
159         playlistTag++;
160         [submenu addItem:playlistItem];
161     }
162
163     if ( (! [self radioIsPlaying]) && currentPlaylist) {
164         [[submenu itemAtIndex:(currentPlaylist - 1)] setState:NSOnState];
165     }
166
167     return item;
168 }
169
170 - (NSMenuItem *)upcomingSongsMenuItem
171 {
172     NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"Upcoming Songs"
173                                                    action:nil
174                                             keyEquivalent:@""] autorelease];
175     NSMenu  *submenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
176     
177     int curIndex = [currentRemote currentPlaylistIndex];
178     int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curIndex];
179     int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
180
181     [item setSubmenu:submenu];
182
183     if ( [self radioIsPlaying] ) {
184         [submenu addItemWithTitle:@"No Upcoming Songs..." action:nil keyEquivalent:@""];
185         [submenu addItemWithTitle:@"Playing Radio Stream" action:nil keyEquivalent:@""];
186     } else {
187         if ( ! (numSongs > 0) ) {
188             [submenu addItemWithTitle:@"No Songs in Playlist" action:nil keyEquivalent:@""];
189         } else {
190             int curTrack = [currentRemote currentSongIndex];
191             int i;
192
193             for (i = curTrack + 1; ( (i <= curTrack + numSongsInAdvance) && (i <= numSongs) ); i++) {
194
195                 NSString *curSong = [currentRemote songTitleAtIndex:i];
196                 NSMenuItem *songItem = [[[NSMenuItem alloc] initWithTitle:curSong
197                                                                    action:@selector(selectSong:)
198                                                             keyEquivalent:@""] autorelease];
199                 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
200                 [submenu addItem:songItem];
201             }
202         }
203     }
204     
205     return item;
206 }
207
208 - (NSMenuItem *)ratingMenuItem
209 {
210     NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"Rating"
211                                                    action:nil
212                                             keyEquivalent:@""] autorelease];
213     NSMenu  *submenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
214
215     [item setSubmenu:submenu];
216
217     [submenu addItemWithTitle:[NSString stringWithUTF8String:"☆☆☆☆☆"] action:nil keyEquivalent:@""];
218     [submenu addItemWithTitle:[NSString stringWithUTF8String:"★☆☆☆☆"] action:nil keyEquivalent:@""];
219     [submenu addItemWithTitle:[NSString stringWithUTF8String:"★★☆☆☆"] action:nil keyEquivalent:@""];
220     [submenu addItemWithTitle:[NSString stringWithUTF8String:"★★★☆☆"] action:nil keyEquivalent:@""];
221     [submenu addItemWithTitle:[NSString stringWithUTF8String:"★★★★☆"] action:nil keyEquivalent:@""];
222     [submenu addItemWithTitle:[NSString stringWithUTF8String:"★★★★★"] action:nil keyEquivalent:@""];
223
224     if ( ! ( [self radioIsPlaying] || [self songIsPlaying] ) ) {
225
226         NSEnumerator *itemEnum;
227         id            anItem;
228         int           itemTag      = 0;
229         SEL           itemSelector = @selector(selectSongRating:);
230
231         itemEnum = [[submenu itemArray] objectEnumerator];
232         while ( (anItem = [itemEnum nextObject]) ) {
233             [anItem setAction:itemSelector];
234             [anItem setTag:itemTag];
235             itemTag += 20;
236         }
237     }
238
239     return item;
240 }
241
242 - (NSMenuItem *)eqMenuItem
243 {
244     NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"Equalizer"
245                                                    action:nil
246                                             keyEquivalent:@""] autorelease];
247     NSMenu  *submenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
248
249     NSArray      *eqPresets = [currentRemote eqPresets];
250     NSEnumerator *eqEnum    = [eqPresets objectEnumerator];
251     int           eqTag     = 0;
252     id            anEq;
253     
254     [item setSubmenu:submenu];
255
256     while ( ( anEq = [eqEnum nextObject]) ) {
257         NSMenuItem *eqItem = [[[NSMenuItem alloc] initWithTitle:anEq
258                                                          action:@selector(selectEQPreset:)
259                                                   keyEquivalent:@""] autorelease];
260         [eqItem setTag:eqTag];
261         eqTag++;
262         [submenu addItem:eqItem];
263     }
264
265     [[submenu itemAtIndex:([currentRemote currentEQPresetIndex] - 1)] setState:NSOnState];
266 }
267
268 - (BOOL)songIsPlaying
269 {
270     return ( ! ([[currentRemote currentSongUniqueIdentifier] isEqualToString:@"0-0"]) );
271 }
272
273 - (BOOL)radioIsPlaying
274 {
275     return ( [currentRemote currentPlaylistClass] == ITMTRemotePlayerRadioPlaylist );
276 }
277
278 - (BOOL)songChanged
279 {
280     return ( ! [[currentRemote currentSongUniqueIdentifier] isEqualToString:_latestSongIdentifier] );
281 }
282
283 - (NSString *)latestSongIdentifier
284 {
285     return _latestSongIdentifier;
286 }
287
288 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
289 {
290     [_latestSongIdentifier autorelease];
291     _latestSongIdentifier = [newIdentifier copy];
292 }
293
294 /*
295 //Recreate the status item menu
296 - (void)rebuildMenu
297 {
298     NSArray *myMenu = [df arrayForKey:@"menu"];
299     int playlist = [currentRemote currentPlaylistIndex];
300     int i;
301     
302     if ([currentRemote playerRunningState] == ITMTRemotePlayerNotRunning) {
303         return;
304     }
305     
306     trackInfoIndex = -1;
307     lastPlaylistIndex = -1;
308     
309     [menu release];
310     menu = [[NSMenu alloc] initWithTitle:@""];
311     
312     playPauseItem = nil;
313     
314     upcomingSongsItem = nil;
315     [upcomingSongsMenu release];
316     upcomingSongsMenu = nil;
317     
318     if (ratingItem) {
319         [ratingItem setSubmenu:nil];
320     }
321     
322     playlistItem = nil;
323     [playlistMenu release];
324     playlistMenu = nil;
325     
326     eqItem = nil;
327     [eqMenu release];
328     eqMenu = nil;
329     
330     //Build the custom menu
331     for (i = 0; i < [myMenu count]; i++) {
332         NSString *item = [myMenu objectAtIndex:i];
333         if ([item isEqualToString:@"Play/Pause"]) {
334             KeyCombo *tempCombo = [df keyComboForKey:@"PlayPause"];
335             playPauseItem = [menu addItemWithTitle:@"Play"
336                                     action:@selector(playPause:)
337                                     keyEquivalent:@""];
338             
339             if (tempCombo) {
340                 [self setKeyEquivalentForCode:[tempCombo keyCode]
341                     andModifiers:[tempCombo modifiers] onItem:playPauseItem];
342                 [tempCombo release];
343             }
344         } else if ([item isEqualToString:@"Next Track"]) {
345             KeyCombo *tempCombo = [df keyComboForKey:@"NextTrack"];
346             NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
347                                         action:@selector(nextSong:)
348                                         keyEquivalent:@""];
349             
350             if (tempCombo) {
351                 [self setKeyEquivalentForCode:[tempCombo keyCode]
352                     andModifiers:[tempCombo modifiers] onItem:nextTrack];
353                 [tempCombo release];
354             }
355         } else if ([item isEqualToString:@"Previous Track"]) {
356             KeyCombo *tempCombo = [df keyComboForKey:@"PrevTrack"];
357             NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
358                                         action:@selector(prevSong:)
359                                         keyEquivalent:@""];
360             
361             if (tempCombo) {
362                 [self setKeyEquivalentForCode:[tempCombo keyCode]
363                     andModifiers:[tempCombo modifiers] onItem:prevTrack];
364                 [tempCombo release];
365             }
366         } else if ([item isEqualToString:@"Fast Forward"]) {
367             [menu addItemWithTitle:@"Fast Forward"
368                     action:@selector(fastForward:)
369                     keyEquivalent:@""];
370         } else if ([item isEqualToString:@"Rewind"]) {
371             [menu addItemWithTitle:@"Rewind"
372                     action:@selector(rewind:)
373                     keyEquivalent:@""];
374         } else if ([item isEqualToString:@"Show Player"]) {
375             [menu addItemWithTitle:[NSString stringWithFormat:@"Show %@", [currentRemote playerSimpleName]]
376                     action:@selector(showPlayer:)
377                     keyEquivalent:@""];
378         } else if ([item isEqualToString:@"Upcoming Songs"]) {
379             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
380                     action:nil
381                     keyEquivalent:@""];
382             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
383             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
384             [upcomingSongsItem setEnabled:NO];
385         } else if ([item isEqualToString:@"Playlists"]) {
386             playlistItem = [menu addItemWithTitle:@"Playlists"
387                     action:nil
388                     keyEquivalent:@""];
389         } else if ([item isEqualToString:@"EQ Presets"]) {
390             eqItem = [menu addItemWithTitle:@"EQ Presets"
391                     action:nil
392                     keyEquivalent:@""];
393         } else if ([item isEqualToString:@"Preferences…"]) {
394             [menu addItemWithTitle:@"Preferences…"
395                     action:@selector(showPreferences:)
396                     keyEquivalent:@""];
397         } else if ([item isEqualToString:@"Quit"]) {
398             [menu addItemWithTitle:@"Quit"
399                     action:@selector(quitMenuTunes:)
400                     keyEquivalent:@""];
401         } else if ([item isEqualToString:@"Current Track Info"]) {
402             trackInfoIndex = [menu numberOfItems];
403             [menu addItemWithTitle:@"No Song"
404                     action:nil
405                     keyEquivalent:@""];
406         } else if ([item isEqualToString:@"Song Rating"]) {
407             ratingItem = [menu addItemWithTitle:@"Song Rating"
408                     action:nil
409                     keyEquivalent:@""];
410             [ratingItem setSubmenu:ratingMenu];
411         } else if ([item isEqualToString:@"<separator>"]) {
412             [menu addItem:[NSMenuItem separatorItem]];
413         }
414     }
415     
416     if (playlistItem) {
417         [self rebuildPlaylistMenu];
418     }
419     
420     if (eqItem) {
421         [self rebuildEQPresetsMenu];
422     }
423     
424     isPlayingRadio = ([currentRemote classOfPlaylistAtIndex:playlist] == ITMTRemotePlayerRadioPlaylist);
425     
426     if (upcomingSongsItem) {
427         [self rebuildUpcomingSongsMenu];
428     }
429     
430     if (ratingItem) {
431         if (isPlayingRadio || !playlist) {
432             [ratingItem setEnabled:NO];
433         } else {
434             int currentSongRating = ([currentRemote currentSongRating] * 5);
435             [[ratingMenu itemAtIndex:lastSongRating] setState:NSOffState];
436             lastSongRating = currentSongRating;
437             [[ratingMenu itemAtIndex:lastSongRating] setState:NSOnState];
438             [ratingItem setEnabled:YES];
439         }
440     }
441     
442     //Set the new unique song identifier
443     lastSongIdentifier = [[currentRemote currentSongUniqueIdentifier] retain];
444     
445     //If we're in a playlist or radio mode
446     if ( ![lastSongIdentifier isEqualToString:@"0-0"] && (trackInfoIndex > -1) ) {
447         NSString *title;
448         
449         if ( (i = [menu indexOfItemWithTitle:@"No Song"]) ) {
450             if ( (i > -1) ) {
451                 [menu removeItemAtIndex:i];
452                 [menu insertItemWithTitle:@"Now Playing" action:NULL keyEquivalent:@"" atIndex:i];
453             }
454         }
455         
456         title = [currentRemote currentSongTitle];
457         
458         if (!isPlayingRadio) {
459             if ([df boolForKey:@"showTime"]) {
460                 NSString *length = [currentRemote currentSongLength];
461                 char character = [length characterAtIndex:0];
462                 if ( (character > '0') && (character < '9') ) {
463                     [menu insertItemWithTitle:[NSString stringWithFormat:@"  %@", [currentRemote currentSongLength]] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
464                 }
465             }
466             
467             if ([df boolForKey:@"showRating"]) {
468                 if (title) { //Check to see if there's a song playing
469                 [menu insertItemWithTitle:[NSString stringWithFormat:@"  %@", [[ratingMenu itemAtIndex:[currentRemote currentSongRating] * 5] title]] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
470                 }
471             }
472             
473             if ([df boolForKey:@"showArtist"]) {
474                 NSString *artist = [currentRemote currentSongArtist];
475                 if ([artist length] > 0) {
476                     [menu insertItemWithTitle:[NSString stringWithFormat:@"  %@", artist] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
477                 }
478             }
479             
480             if ([df boolForKey:@"showNumber"]) {
481                 int track = [currentRemote currentSongTrack];
482                 int total = [currentRemote currentAlbumTrackCount];
483                 if (total > 0) {
484                     [menu insertItemWithTitle:[NSString stringWithFormat:@"  Track %i of %i", track, total] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
485                 }
486             }
487             
488             if ([df boolForKey:@"showAlbum"]) {
489                 NSString *album = [currentRemote currentSongAlbum];
490                 if ([album length] > 0) {
491                     [menu insertItemWithTitle:[NSString stringWithFormat:@"  %@", album] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
492                 }
493             }
494         }
495         
496         if ([title length] > 0) {
497             [menu insertItemWithTitle:[NSString stringWithFormat:@"  %@", title] action:nil keyEquivalent:@"" atIndex:trackInfoIndex + 1];
498         }
499     }
500     
501     [statusItem setMenu:menu];
502     
503     [self clearHotKeys];
504     [self setupHotKeys];
505 }
506
507
508 //Build a menu with the list of all available EQ presets
509 - (void)rebuildEQPresetsMenu
510 {
511     NSArray *eqPresets = [currentRemote eqPresets];
512     int i;
513     
514     [eqMenu autorelease];
515     eqMenu = [[NSMenu alloc] initWithTitle:@""];
516     
517     for (i = 0; i < [eqPresets count]; i++) {
518         NSString *name;
519         NSMenuItem *tempItem;
520         if ( ( name = [eqPresets objectAtIndex:i] ) ) {
521             tempItem = [[NSMenuItem alloc] initWithTitle:name action:@selector(selectEQPreset:) keyEquivalent:@""];
522             [tempItem setTag:i];
523             [eqMenu addItem:tempItem];
524             [tempItem autorelease];
525         }
526     }
527     
528     [eqItem setSubmenu:eqMenu];
529     [eqItem setEnabled:YES];
530     [[eqMenu itemAtIndex:([currentRemote currentEQPresetIndex] - 1)] setState:NSOnState];
531 }
532
533 */
534
535 - (void)timerUpdate
536 {
537     if ( ( [self songChanged] ) ||
538          ( ([self radioIsPlaying]) && (latestPlaylistClass != ITMTRemotePlayerRadioPlaylist) ) ||
539          ( (! [self radioIsPlaying]) && (latestPlaylistClass == ITMTRemotePlayerRadioPlaylist) ) ) {
540         [statusItem setMenu:[self menu]];
541         [self setLatestSongIdentifier:[currentRemote currentSongUniqueIdentifier]];
542         latestPlaylistClass = [currentRemote currentPlaylistClass];
543         
544         if ( [df boolForKey:@"showSongInfoOnChange"] ) {
545             [self showCurrentTrackInfo];
546         }
547     }
548 /*    
549     //Update Play/Pause menu item
550     if (playPauseItem){
551         if ([currentRemote playerPlayingState] == ITMTRemotePlayerPlaying) {
552             [playPauseItem setTitle:@"Pause"];
553         } else {
554             [playPauseItem setTitle:@"Play"];
555         }
556     }
557 */
558 }
559
560 /*
561 //
562 //
563 // Menu Selectors
564 //
565 //
566
567 - (void)selectSong:(id)sender
568 {
569     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
570 }
571 */
572 - (void)selectPlaylist:(id)sender
573 {
574     int playlist = [sender tag];
575     [currentRemote switchToPlaylistAtIndex:playlist];
576 }
577 /*
578 - (void)selectEQPreset:(id)sender
579 {
580     int curSet = [currentRemote currentEQPresetIndex];
581     int item = [sender tag];
582     
583     [currentRemote switchToEQAtIndex:item];
584     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
585     [[eqMenu itemAtIndex:item] setState:NSOnState];
586 }
587 */
588 /*
589 - (void)selectSongRating:(id)sender
590 {
591     int newRating = [sender tag];
592 //  [[ratingMenu itemAtIndex:lastSongRating] setState:NSOffState];
593     [sender setState:NSOnState];
594     [currentRemote setCurrentSongRating:(float)newRating / 100.0];
595     lastSongRating = newRating / 20;
596 }
597 */
598 /*
599 - (void)playPause:(id)sender
600 {
601     ITMTRemotePlayerPlayingState state = [currentRemote playerPlayingState];
602     
603     if (state == ITMTRemotePlayerPlaying) {
604         [currentRemote pause];
605         [playPauseItem setTitle:@"Play"];
606     } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
607         [currentRemote pause];
608         [currentRemote play];
609     } else {
610         [currentRemote play];
611         [playPauseItem setTitle:@"Pause"];
612     }
613 }
614
615 - (void)nextSong:(id)sender
616 {
617     [currentRemote goToNextSong];
618 }
619
620 - (void)prevSong:(id)sender
621 {
622     [currentRemote goToPreviousSong];
623 }
624
625 - (void)fastForward:(id)sender
626 {
627     [currentRemote forward];
628     [playPauseItem setTitle:@"Play"];
629 }
630
631 - (void)rewind:(id)sender
632 {
633     [currentRemote rewind];
634     [playPauseItem setTitle:@"Play"];
635 }
636 */
637
638 //
639 //
640 - (void)quitMenuTunes:(id)sender
641 {
642     [NSApp terminate:self];
643 }
644
645 - (void)showPlayer:(id)sender
646 {
647     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
648         [currentRemote showPrimaryInterface];
649     } else {
650         if (![[NSWorkspace sharedWorkspace] launchApplication:[currentRemote playerFullName]]) {
651             NSLog(@"Error Launching Player");
652         }
653     }
654 }
655
656 - (void)showPreferences:(id)sender
657 {
658     [[PreferencesController sharedPrefs] setController:self];
659     [[PreferencesController sharedPrefs] showPrefsWindow:self];
660 }
661
662 - (void)closePreferences
663 {
664     if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
665         [self setupHotKeys];
666     }
667 }
668
669 - (ITMTRemote *)currentRemote
670 {
671     return currentRemote;
672 }
673
674 //
675 //
676 // Hot key setup
677 //
678 //
679
680 - (void)clearHotKeys
681 {
682     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
683     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
684     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
685     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
686     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
687     [[HotKeyCenter sharedCenter] removeHotKey:@"ToggleLoop"];
688     [[HotKeyCenter sharedCenter] removeHotKey:@"ToggleShuffle"];
689     [[HotKeyCenter sharedCenter] removeHotKey:@"IncrementVolume"];
690     [[HotKeyCenter sharedCenter] removeHotKey:@"DecrementVolume"];
691     [[HotKeyCenter sharedCenter] removeHotKey:@"IncrementRating"];
692     [[HotKeyCenter sharedCenter] removeHotKey:@"DecrementRating"];
693 }
694
695 - (void)setupHotKeys
696 {
697     if ([df objectForKey:@"PlayPause"] != nil) {
698         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
699                 combo:[df keyComboForKey:@"PlayPause"]
700                 target:self action:@selector(playPause:)];
701     }
702     
703     if ([df objectForKey:@"NextTrack"] != nil) {
704         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
705                 combo:[df keyComboForKey:@"NextTrack"]
706                 target:self action:@selector(nextSong:)];
707     }
708     
709     if ([df objectForKey:@"PrevTrack"] != nil) {
710         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
711                 combo:[df keyComboForKey:@"PrevTrack"]
712                 target:self action:@selector(prevSong:)];
713     }
714     
715     if ([df objectForKey:@"TrackInfo"] != nil) {
716         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
717                 combo:[df keyComboForKey:@"TrackInfo"]
718                 target:self action:@selector(showCurrentTrackInfo)];
719     }
720     
721     if ([df objectForKey:@"UpcomingSongs"] != nil) {
722         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
723                combo:[df keyComboForKey:@"UpcomingSongs"]
724                target:self action:@selector(showUpcomingSongs)];
725     }
726     
727     if ([df objectForKey:@"ToggleLoop"] != nil) {
728         [[HotKeyCenter sharedCenter] addHotKey:@"ToggleLoop"
729                combo:[df keyComboForKey:@"ToggleLoop"]
730                target:self action:NULL/*Set this to something*/];
731     }
732     
733     if ([df objectForKey:@"ToggleShuffle"] != nil) {
734         [[HotKeyCenter sharedCenter] addHotKey:@"ToggleShuffle"
735                combo:[df keyComboForKey:@"ToggleShuffle"]
736                target:self action:NULL/*Set this to something*/];
737     }
738     
739     if ([df objectForKey:@"IncrementVolume"] != nil) {
740         [[HotKeyCenter sharedCenter] addHotKey:@"IncrementVolume"
741                combo:[df keyComboForKey:@"IncrementVolume"]
742                target:self action:NULL/*Set this to something*/];
743     }
744     
745     if ([df objectForKey:@"DecrementVolume"] != nil) {
746         [[HotKeyCenter sharedCenter] addHotKey:@"DecrementVolume"
747                combo:[df keyComboForKey:@"DecrementVolume"]
748                target:self action:NULL/*Set this to something*/];
749     }
750     
751     if ([df objectForKey:@"IncrementRating"] != nil) {
752         [[HotKeyCenter sharedCenter] addHotKey:@"IncrementRating"
753                combo:[df keyComboForKey:@"IncrementRating"]
754                target:self action:NULL/*Set this to something*/];
755     }
756     
757     if ([df objectForKey:@"DecrementRating"] != nil) {
758         [[HotKeyCenter sharedCenter] addHotKey:@"DecrementRating"
759                combo:[df keyComboForKey:@"DecrementRating"]
760                target:self action:NULL/*Set this to something*/];
761     }
762 }
763
764 - (void)showCurrentTrackInfo
765 {
766     NSString *title = [currentRemote currentSongTitle];
767
768     if ( title ) {
769         NSString *album       = nil;
770         NSString *artist      = nil;
771         NSString *time        = nil;
772         int       trackNumber = 0;
773         int       trackTotal  = 0;
774         int       rating      = 0;
775
776         if ( [df boolForKey:@"showAlbum"] ) {
777             album = [currentRemote currentSongAlbum];
778         }
779
780         if ( [df boolForKey:@"showArtist"] ) {
781             artist = [currentRemote currentSongArtist];
782         }
783
784         if ( [df boolForKey:@"showTime"] ) {
785             time = [currentRemote currentSongLength];
786         }
787
788         if ( [df boolForKey:@"showNumber"] ) {
789             trackNumber = [currentRemote currentSongTrack];
790             trackTotal  = [currentRemote currentAlbumTrackCount];
791         }
792
793         if ( [df boolForKey:@"showRating"] ) {
794             rating = ( [currentRemote currentSongRating] * 5 );
795         }
796
797         [statusWindowController showSongWindowWithTitle:title
798                                                   album:album
799                                                  artist:artist
800                                                    time:time
801                                             trackNumber:trackNumber
802                                              trackTotal:trackTotal
803                                                  rating:rating];
804     } else {
805         title = @"No song is playing.";
806         [statusWindowController showSongWindowWithTitle:title
807                                                   album:nil
808                                                  artist:nil
809                                                    time:nil
810                                             trackNumber:0
811                                              trackTotal:0
812                                                  rating:0];
813     }
814 }
815
816 - (void)showUpcomingSongs
817 {
818     int curPlaylist = [currentRemote currentPlaylistIndex];
819     int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
820
821     if (numSongs > 0) {
822         NSMutableArray *songList = [NSMutableArray arrayWithCapacity:5];
823         int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
824         int curTrack = [currentRemote currentSongIndex];
825         int i;
826
827         for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
828             if (i <= numSongs) {
829                 [songList addObject:[currentRemote songTitleAtIndex:i]];
830             }
831         }
832         
833         [statusWindowController showUpcomingSongsWithTitles:songList];
834         
835     } else {
836         [statusWindowController showUpcomingSongsWithTitles:[NSArray arrayWithObject:@"No upcoming songs."]];
837     }
838 }
839
840 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
841         onItem:(NSMenuItem *)item
842 {
843     unichar charcode = 'a';
844     int i;
845     long cocoaModifiers = 0;
846     static long carbonToCocoa[6][2] = 
847     {
848         { cmdKey, NSCommandKeyMask },
849         { optionKey, NSAlternateKeyMask },
850         { controlKey, NSControlKeyMask },
851         { shiftKey, NSShiftKeyMask },
852     };
853     
854     for (i = 0; i < 6; i++) {
855         if (modifiers & carbonToCocoa[i][0]) {
856             cocoaModifiers += carbonToCocoa[i][1];
857         }
858     }
859     [item setKeyEquivalentModifierMask:cocoaModifiers];
860     
861     //Missing key combos for some keys. Must find them later.
862     switch (code)
863     {
864         case 36:
865             charcode = '\r';
866         break;
867         
868         case 48:
869             charcode = '\t';
870         break;
871         
872         //Space -- ARGH!
873         case 49:
874         {
875             // Haven't tested this, though it should work.
876             unichar buffer;
877             [[NSString stringWithString:@"Space"] getCharacters:&buffer];
878             charcode = buffer;
879             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
880             NSLog(@"%@", menuRef);
881             SetMenuItemCommandKey(menuRef, 0, NO, 49);
882             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
883             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
884             charcode = 'b';*/
885             
886         }
887         break;
888         
889         case 51:
890             charcode = NSDeleteFunctionKey;
891         break;
892         
893         case 53:
894             charcode = '\e';
895         break;
896         
897         case 71:
898             charcode = '\e';
899         break;
900         
901         case 76:
902             charcode = '\r';
903         break;
904         
905         case 96:
906             charcode = NSF5FunctionKey;
907         break;
908         
909         case 97:
910             charcode = NSF6FunctionKey;
911         break;
912         
913         case 98:
914             charcode = NSF7FunctionKey;
915         break;
916         
917         case 99:
918             charcode = NSF3FunctionKey;
919         break;
920         
921         case 100:
922             charcode = NSF8FunctionKey;
923         break;
924         
925         case 101:
926             charcode = NSF9FunctionKey;
927         break;
928         
929         case 103:
930             charcode = NSF11FunctionKey;
931         break;
932         
933         case 105:
934             charcode = NSF3FunctionKey;
935         break;
936         
937         case 107:
938             charcode = NSF14FunctionKey;
939         break;
940         
941         case 109:
942             charcode = NSF10FunctionKey;
943         break;
944         
945         case 111:
946             charcode = NSF12FunctionKey;
947         break;
948         
949         case 113:
950             charcode = NSF13FunctionKey;
951         break;
952         
953         case 114:
954             charcode = NSInsertFunctionKey;
955         break;
956         
957         case 115:
958             charcode = NSHomeFunctionKey;
959         break;
960         
961         case 116:
962             charcode = NSPageUpFunctionKey;
963         break;
964         
965         case 117:
966             charcode = NSDeleteFunctionKey;
967         break;
968         
969         case 118:
970             charcode = NSF4FunctionKey;
971         break;
972         
973         case 119:
974             charcode = NSEndFunctionKey;
975         break;
976         
977         case 120:
978             charcode = NSF2FunctionKey;
979         break;
980         
981         case 121:
982             charcode = NSPageDownFunctionKey;
983         break;
984         
985         case 122:
986             charcode = NSF1FunctionKey;
987         break;
988         
989         case 123:
990             charcode = NSLeftArrowFunctionKey;
991         break;
992         
993         case 124:
994             charcode = NSRightArrowFunctionKey;
995         break;
996         
997         case 125:
998             charcode = NSDownArrowFunctionKey;
999         break;
1000         
1001         case 126:
1002             charcode = NSUpArrowFunctionKey;
1003         break;
1004     }
1005     
1006     if (charcode == 'a') {
1007         unsigned long state;
1008         long keyTrans;
1009         char charCode;
1010         Ptr kchr;
1011         state = 0;
1012         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1013         keyTrans = KeyTranslate(kchr, code, &state);
1014         charCode = keyTrans;
1015         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1016     } else if (charcode != 'b') {
1017         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1018     }
1019 }
1020
1021 /*************************************************************************/
1022 #pragma mark -
1023 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1024 /*************************************************************************/
1025
1026 - (void)applicationLaunched:(NSNotification *)note
1027 {
1028     if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[currentRemote playerFullName]]) {
1029         [NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1030         [self setupHotKeys];
1031         playerRunningState = ITMTRemotePlayerRunning;
1032     }
1033 }
1034
1035  - (void)applicationTerminated:(NSNotification *)note
1036  {
1037      if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[currentRemote playerFullName]]) {
1038 /*
1039          NSMenu *notRunningMenu = [[NSMenu alloc] initWithTitle:@""];
1040          [notRunningMenu addItemWithTitle:[NSString stringWithFormat:@"Open %@", [currentRemote playerSimpleName]] action:@selector(showPlayer:) keyEquivalent:@""];
1041          [notRunningMenu addItem:[NSMenuItem separatorItem]];
1042          [notRunningMenu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""];
1043          [notRunningMenu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""];
1044 */
1045          [refreshTimer invalidate];
1046          [refreshTimer release];
1047          refreshTimer = nil;
1048          [self clearHotKeys];
1049          playerRunningState = ITMTRemotePlayerNotRunning;
1050
1051          [statusItem setMenu:[self menuForNoPlayer]];
1052      }
1053  }
1054
1055
1056 /*************************************************************************/
1057 #pragma mark -
1058 #pragma mark NSApplication DELEGATE METHODS
1059 /*************************************************************************/
1060
1061 - (void)applicationWillTerminate:(NSNotification *)note
1062 {
1063     [self clearHotKeys];
1064     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1065 }
1066
1067
1068 /*************************************************************************/
1069 #pragma mark -
1070 #pragma mark DEALLOCATION METHOD
1071 /*************************************************************************/
1072
1073 - (void)dealloc
1074 {
1075     if (refreshTimer) {
1076         [refreshTimer invalidate];
1077         [refreshTimer release];
1078         refreshTimer = nil;
1079     }
1080     
1081     [currentRemote halt];
1082     [statusItem release];
1083     [statusWindowController release];
1084     [super dealloc];
1085 }
1086
1087
1088 @end