Mmm, Renaming for the BIG REWRITE OF MARCH 2003!!!! BBQ!!!!1
[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)updateMenu;
9 - (void)rebuildUpcomingSongsMenu;
10 - (void)rebuildPlaylistMenu;
11 - (void)rebuildEQPresetsMenu;
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 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)applicationDidFinishLaunching:(NSNotification *)note
36 {
37     currentRemote = [self loadRemote];
38     [currentRemote begin];
39     
40     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(remotePlayerTerminated:) name:@"ITMTRemoteAppDidTerminateNotification" object:nil];
41     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(remotePlayerLaunched:) name:@"ITMTRemoteAppDidLaunchNotification" object:nil];
42     
43     [self registerDefaultsIfNeeded];
44     
45     menu = [[NSMenu alloc] initWithTitle:@""];
46     
47     if ( ( [currentRemote playerRunningState] == ITMTRemotePlayerRunning ) ) {
48         [self remotePlayerLaunched:nil];
49     } else {
50         [self remotePlayerTerminated:nil];
51     }
52     
53     statusItem = [[ITStatusItem alloc] initWithStatusBar:[NSStatusBar systemStatusBar] withLength:NSSquareStatusItemLength];
54     
55     [statusItem setImage:[NSImage imageNamed:@"menu"]];
56     [statusItem setAlternateImage:[NSImage imageNamed:@"selected_image"]];
57     [statusItem setMenu:menu];
58     // Below line of code is for creating builds for Beta Testers
59     // [statusItem setToolTip:@[NSString stringWithFormat:@"This Nontransferable Beta (Built on %s) of iThink Software's MenuTunes is Registered to: Beta Tester (betatester@somedomain.com).",__DATE__]];
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 /*************************************************************************/
99 #pragma mark -
100 #pragma mark INSTANCE METHODS
101 /*************************************************************************/
102
103 - (void)registerDefaultsIfNeeded
104 {
105     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
106     if (![defaults objectForKey:@"menu"]) {
107         BOOL found = NO;
108         NSMutableDictionary *loginwindow;
109         NSMutableArray *loginarray;
110         int i;
111         
112         [defaults setObject:
113             [NSArray arrayWithObjects:
114                 @"Play/Pause",
115                 @"Next Track",
116                 @"Previous Track",
117                 @"Fast Forward",
118                 @"Rewind",
119                 @"<separator>",
120                 @"Upcoming Songs",
121                 @"Playlists",
122                 @"Song Rating",
123                 @"<separator>",
124                 @"PreferencesÉ",
125                 @"Quit",
126                 @"<separator>",
127                 @"Current Track Info",
128                 nil] forKey:@"menu"];
129         
130         [defaults synchronize];
131         loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
132         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
133         
134         for (i = 0; i < [loginarray count]; i++) {
135             NSDictionary *tempDict = [loginarray objectAtIndex:i];
136             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
137                 found = YES;
138             }
139         }
140         
141         //
142         //This is teh sux
143         //We must fix it so it is no longer suxy
144         if (!found) {
145             if (NSRunInformationalAlertPanel(@"Auto-launch MenuTunes", @"Would you like MenuTunes to automatically launch at login?", @"Yes", @"No", nil) == NSOKButton) {
146                 AEDesc scriptDesc, resultDesc;
147                 NSString *script = [NSString stringWithFormat:@"tell application \"System Events\"\nmake new login item at end of login items with properties {path:\"%@\", kind:\"APPLICATION\"}\nend tell", [[NSBundle mainBundle] bundlePath]];
148                 ComponentInstance asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
149                 
150                 AECreateDesc(typeChar, [script cString], [script cStringLength], 
151             &scriptDesc);
152                 
153                 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
154                 
155                 AEDisposeDesc(&scriptDesc);
156                 AEDisposeDesc(&resultDesc);
157                 
158                 CloseComponent(asComponent);
159             }
160         }
161     }
162     
163     if (![defaults integerForKey:@"SongsInAdvance"])
164     {
165         [defaults setInteger:5 forKey:@"SongsInAdvance"];
166     }
167     
168     if (![defaults objectForKey:@"showName"]) {
169         [defaults setBool:YES forKey:@"showName"];
170     }
171     
172     if (![defaults objectForKey:@"showArtist"]) {
173         [defaults setBool:YES forKey:@"showArtist"];
174     }
175     
176     if (![defaults objectForKey:@"showAlbum"]) {
177         [defaults setBool:NO forKey:@"showAlbum"];
178     }
179     
180     if (![defaults objectForKey:@"showTime"]) {
181         [defaults setBool:NO forKey:@"showTime"];
182     }
183 }
184
185 //Recreate the status item menu
186 - (void)rebuildMenu
187 {
188     NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
189     int i;
190     
191     trackInfoIndex = -1;
192     lastSongIndex = -1;
193     lastPlaylistIndex = -1;
194     didHaveAlbumName = ([[currentRemote currentSongAlbum] length] > 0);
195     didHaveArtistName = ([[currentRemote currentSongArtist] length] > 0);
196     
197     while ([menu numberOfItems] > 0) {
198         [menu removeItemAtIndex:0];
199     }
200     
201     playPauseMenuItem = nil;
202     upcomingSongsItem = nil;
203     songRatingMenuItem = nil;
204     playlistItem = nil;
205     [playlistMenu release];
206     playlistMenu = nil;
207     eqItem = nil;
208     [eqMenu release];
209     eqMenu = nil;
210     
211     for (i = 0; i < [myMenu count]; i++) {
212         NSString *item = [myMenu objectAtIndex:i];
213         if ([item isEqualToString:@"Play/Pause"]) {
214             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PlayPause"];
215             playPauseMenuItem = [menu addItemWithTitle:@"Play"
216                                     action:@selector(playPause:)
217                                     keyEquivalent:@""];
218             [playPauseMenuItem setTarget:self];
219             
220             if (tempCombo) {
221                 [self setKeyEquivalentForCode:[tempCombo keyCode]
222                     andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
223                 [tempCombo release];
224             }
225         } else if ([item isEqualToString:@"Next Track"]) {
226             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"NextTrack"];
227             NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
228                                         action:@selector(nextSong:)
229                                         keyEquivalent:@""];
230             
231             [nextTrack setTarget:self];
232             if (tempCombo) {
233                 [self setKeyEquivalentForCode:[tempCombo keyCode]
234                     andModifiers:[tempCombo modifiers] onItem:nextTrack];
235                 [tempCombo release];
236             }
237         } else if ([item isEqualToString:@"Previous Track"]) {
238             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PrevTrack"];
239             NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
240                                         action:@selector(prevSong:)
241                                         keyEquivalent:@""];
242             
243             [prevTrack setTarget:self];
244             if (tempCombo) {
245                 [self setKeyEquivalentForCode:[tempCombo keyCode]
246                     andModifiers:[tempCombo modifiers] onItem:prevTrack];
247                 [tempCombo release];
248             }
249         } else if ([item isEqualToString:@"Fast Forward"]) {
250             [[menu addItemWithTitle:@"Fast Forward"
251                     action:@selector(fastForward:)
252                     keyEquivalent:@""] setTarget:self];
253         } else if ([item isEqualToString:@"Rewind"]) {
254             [[menu addItemWithTitle:@"Rewind"
255                     action:@selector(rewind:)
256                     keyEquivalent:@""] setTarget:self];
257         } else if ([item isEqualToString:@"Upcoming Songs"]) {
258             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
259                     action:nil
260                     keyEquivalent:@""];
261         } else if ([item isEqualToString:@"Playlists"]) {
262             playlistItem = [menu addItemWithTitle:@"Playlists"
263                     action:nil
264                     keyEquivalent:@""];
265         } else if ([item isEqualToString:@"EQ Presets"]) {
266             eqItem = [menu addItemWithTitle:@"EQ Presets"
267                     action:nil
268                     keyEquivalent:@""];
269         } else if ([item isEqualToString:@"PreferencesÉ"]) {
270             [[menu addItemWithTitle:@"PreferencesÉ"
271                     action:@selector(showPreferences:)
272                     keyEquivalent:@""] setTarget:self];
273         } else if ([item isEqualToString:@"Quit"]) {
274             [[menu addItemWithTitle:@"Quit"
275                     action:@selector(quitMenuTunes:)
276                     keyEquivalent:@""] setTarget:self];
277         } else if ([item isEqualToString:@"Current Track Info"]) {
278             trackInfoIndex = [menu numberOfItems];
279             [menu addItemWithTitle:@"No Song"
280                     action:nil
281                     keyEquivalent:@""];
282         } else if ([item isEqualToString:@"Song Rating"]) {
283             unichar fullstar = 0x2605;
284             unichar emptystar = 0x2606;
285             NSString *fullStarChar = [NSString stringWithCharacters:&fullstar length:1];
286             NSString *emptyStarChar = [NSString stringWithCharacters:&emptystar length:1];
287             NSMenuItem *item;
288             int i;
289             NSString *curTitle = [NSString stringWithFormat:@"%@%@%@%@%@", emptyStarChar, emptyStarChar, emptyStarChar, emptyStarChar, emptyStarChar];
290             
291             songRatingMenuItem = [menu addItemWithTitle:@"Song Rating"
292                     action:nil
293                     keyEquivalent:@""];
294             
295             ratingMenu = [[NSMenu alloc] initWithTitle:@""];
296             
297             item = [ratingMenu addItemWithTitle:[NSString stringWithFormat:@"%@%@%@%@%@", emptyStarChar, emptyStarChar, emptyStarChar, emptyStarChar, emptyStarChar]
298                             action:@selector(setSongRating:)
299                             keyEquivalent:@""];
300             [item setTarget:self];
301             [item setTag:0];
302             
303             for (i = 1; i < 6; i++) {
304                 curTitle = [curTitle substringToIndex:4];
305                 curTitle = [fullStarChar stringByAppendingString:curTitle];
306                 item = [ratingMenu addItemWithTitle:curTitle
307                             action:@selector(setSongRating:)
308                             keyEquivalent:@""];
309                 [item setTarget:self];
310                 [item setTag:(i * 20)];
311             }
312         } else if ([item isEqualToString:@"<separator>"]) {
313             [menu addItem:[NSMenuItem separatorItem]];
314         }
315     }
316     
317     [self timerUpdate]; //Updates dynamic info in the menu
318     
319     [self clearHotKeys];
320     [self setupHotKeys];
321 }
322
323 //Updates the menu with current player state, song, and upcoming songs
324 - (void)updateMenu
325 {
326     NSMenuItem *menuItem;
327     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
328     
329     if ( ( isAppRunning == ITMTRemotePlayerNotRunning ) ) {
330         return;
331     }
332     
333     if (upcomingSongsItem) {
334         [self rebuildUpcomingSongsMenu];
335     }
336     
337     if (playlistItem) {
338         [self rebuildPlaylistMenu];
339     }
340     
341     if (eqItem) {
342         [self rebuildEQPresetsMenu];
343     }
344     if (trackInfoIndex > -1) {
345         NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
346         curSongName = [currentRemote currentSongTitle];
347         
348         if ([defaults boolForKey:@"showAlbum"]) {
349             curAlbumName = [currentRemote currentSongAlbum];
350         }
351         
352         if ([defaults boolForKey:@"showArtist"]) {
353             curArtistName = [currentRemote currentSongArtist];
354         }
355         
356         if ([curSongName length] > 0) {
357             int index = [menu indexOfItemWithTitle:@"Now Playing"];
358             if (index > -1) {
359                 if ([defaults boolForKey:@"showName"]) {
360                     [menu removeItemAtIndex:index + 1];
361                 }
362                 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
363                     [menu removeItemAtIndex:index + 1];
364                 }
365                 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
366                     [menu removeItemAtIndex:index + 1];
367                 }
368                 if ([defaults boolForKey:@"showTime"]) {
369                     [menu removeItemAtIndex:index + 1];
370                 }
371             }
372             
373             if (!isPlayingRadio) {
374                 if ([defaults boolForKey:@"showTime"]) {
375                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", [currentRemote currentSongLength]]
376                             action:nil
377                             keyEquivalent:@""];
378                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
379                     [menuItem release];
380                 }
381                 
382                 if ([curArtistName length] > 0) {
383                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curArtistName]
384                             action:nil
385                             keyEquivalent:@""];
386                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
387                     [menuItem release];
388                 }
389                 
390                 if ([curAlbumName length] > 0) {
391                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName]
392                             action:nil
393                             keyEquivalent:@""];
394                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
395                     [menuItem release];
396                 }
397                 
398                 if (songRatingMenuItem) {
399                     int rating = (int)[currentRemote currentSongRating] * 10;
400                     int i;
401                     for (i = 0; i < 5; i++) {
402                         [[ratingMenu itemAtIndex:i] setState:NSOffState];
403                         [[ratingMenu itemAtIndex:i] setTarget:self];
404                     }
405                     [[ratingMenu itemAtIndex:rating / 2] setState:NSOnState];
406                 }
407             }
408             
409             if ([defaults boolForKey:@"showName"]) {
410                 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
411                             action:nil
412                             keyEquivalent:@""];
413                 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
414                 [menuItem release];
415             }
416             
417             if (index == -1) {
418                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
419                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
420                 [menu insertItem:menuItem atIndex:trackInfoIndex];
421                 [menuItem release];
422                 
423                 [songRatingMenuItem setSubmenu:ratingMenu];
424                 [songRatingMenuItem setEnabled:YES];
425             }
426         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
427             [menu removeItemAtIndex:trackInfoIndex];
428             
429             if ([defaults boolForKey:@"showName"] == YES) {
430                 [menu removeItemAtIndex:trackInfoIndex];
431             }
432             
433             if ([defaults boolForKey:@"showTime"] == YES) {
434                 [menu removeItemAtIndex:trackInfoIndex];
435             }
436             
437             if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
438                 [menu removeItemAtIndex:trackInfoIndex];
439             }
440             
441             if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
442                 [menu removeItemAtIndex:trackInfoIndex];
443             }
444             
445             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
446             [menu insertItem:menuItem atIndex:trackInfoIndex];
447             [menuItem release];
448         }
449         
450         if ([defaults boolForKey:@"showArtist"]) {
451             didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
452         }
453             
454         if ([defaults boolForKey:@"showAlbum"]) {
455             didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
456         }
457     }
458     [menu update];
459 }
460
461 //Rebuild the upcoming songs submenu. Can be improved a lot.
462 - (void)rebuildUpcomingSongsMenu
463 {
464     int curIndex = [currentRemote currentPlaylistIndex];
465     int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curIndex];
466     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
467     
468     if (!isPlayingRadio) {
469         if (numSongs > 0) {
470             int curTrack = [currentRemote currentSongIndex];
471             int i;
472             
473             [upcomingSongsMenu release];
474             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
475             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
476             [upcomingSongsItem setEnabled:YES];
477             
478             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
479                 if (i <= numSongs) {
480                     NSString *curSong = [currentRemote songTitleAtIndex:i];
481                     NSMenuItem *songItem;
482                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
483                     [songItem setTarget:self];
484                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
485                     [upcomingSongsMenu addItem:songItem];
486                     [songItem release];
487                 } else {
488                     break;
489                 }
490             }
491         }
492     } else {
493         [upcomingSongsItem setSubmenu:nil];
494         [upcomingSongsItem setEnabled:NO];
495     }
496 }
497
498 - (void)rebuildPlaylistMenu
499 {
500     NSArray *playlists = [currentRemote playlists];
501     int i, curPlaylist = [currentRemote currentPlaylistIndex];
502     
503     if (isPlayingRadio) {
504         curPlaylist = 0;
505     }
506     if (playlistMenu && ([playlists count] == [playlistMenu numberOfItems]))
507         return;
508     
509     [playlistMenu release];
510     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
511     
512     for (i = 0; i < [playlists count]; i++) {
513         NSString *playlistName = [playlists objectAtIndex:i];
514         NSMenuItem *tempItem;
515         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
516         [tempItem setTarget:self];
517         [tempItem setRepresentedObject:[NSNumber numberWithInt:i + 1]];
518         [playlistMenu addItem:tempItem];
519         [tempItem release];
520     }
521     [playlistItem setSubmenu:playlistMenu];
522     [playlistItem setEnabled:YES];
523     
524     if (curPlaylist) {
525         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
526     }
527 }
528
529 //Build a menu with the list of all available EQ presets
530 - (void)rebuildEQPresetsMenu
531 {
532     NSArray *eqPresets = [currentRemote eqPresets];
533     NSMenuItem *enabledItem;
534     int i;
535     
536     if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
537         return;
538     
539     [eqMenu release];
540     eqMenu = [[NSMenu alloc] initWithTitle:@""];
541     
542     enabledItem = [eqMenu addItemWithTitle:@"Disabled"
543                           action:@selector(toggleEqualizer)
544                           keyEquivalent:@""];
545     
546     if ([currentRemote equalizerEnabled] == NO) {
547         [enabledItem setState:NSOnState];
548     }
549     
550     [eqMenu addItem:[NSMenuItem separatorItem]];
551     
552     for (i = 0; i < [eqPresets count]; i++) {
553         NSString *setName = [eqPresets objectAtIndex:i];
554         NSMenuItem *tempItem;
555         if (setName) {
556         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
557         [tempItem setTarget:self];
558         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
559         [eqMenu addItem:tempItem];
560         [tempItem release];
561         }
562     }
563     [eqItem setSubmenu:eqMenu];
564     
565     [[eqMenu itemAtIndex:[currentRemote currentEQPresetIndex] + 1] setState:NSOnState];
566 }
567
568 - (void)clearHotKeys
569 {
570     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
571     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
572     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
573     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
574     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
575 }
576
577 - (void)setupHotKeys
578 {
579     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
580     
581     if ([defaults objectForKey:@"PlayPause"] != nil) {
582         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
583                 combo:[defaults keyComboForKey:@"PlayPause"]
584                 target:self action:@selector(playPause:)];
585     }
586     
587     if ([defaults objectForKey:@"NextTrack"] != nil) {
588         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
589                 combo:[defaults keyComboForKey:@"NextTrack"]
590                 target:self action:@selector(nextSong:)];
591     }
592     
593     if ([defaults objectForKey:@"PrevTrack"] != nil) {
594         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
595                 combo:[defaults keyComboForKey:@"PrevTrack"]
596                 target:self action:@selector(prevSong:)];
597     }
598     
599     if ([defaults objectForKey:@"TrackInfo"] != nil) {
600         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
601                 combo:[defaults keyComboForKey:@"TrackInfo"]
602                 target:self action:@selector(showCurrentTrackInfo)];
603     }
604     
605     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
606         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
607                combo:[defaults keyComboForKey:@"UpcomingSongs"]
608                target:self action:@selector(showUpcomingSongs)];
609     }
610 }
611
612 //Called when the timer fires.
613 - (void)timerUpdate
614 {
615     int playlist = [currentRemote currentPlaylistIndex];
616     ITMTRemotePlayerPlayingState playerPlayingState = [currentRemote playerPlayingState];
617     
618     if ((playlist > 0) || playerPlayingState != ITMTRemotePlayerStopped) {
619         int trackPlayingIndex = [currentRemote currentSongIndex];
620         
621         if (trackPlayingIndex != lastSongIndex) {
622             BOOL wasPlayingRadio = isPlayingRadio;
623             isPlayingRadio = ([currentRemote classOfPlaylistAtIndex:playlist] == ITMTRemotePlayerRadioPlaylist);
624             
625             if (isPlayingRadio && !wasPlayingRadio) {
626                 int i;
627                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
628                 {
629                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
630                 }
631             } else {
632                 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
633             }
634             
635             if (wasPlayingRadio) {
636                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
637                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
638                 [temp release];
639             }
640             
641             [self updateMenu];
642             lastSongIndex = trackPlayingIndex;
643         } else {
644             if (playlist != lastPlaylistIndex) {
645                 BOOL wasPlayingRadio = isPlayingRadio;
646                 isPlayingRadio = ([currentRemote classOfPlaylistAtIndex:playlist] == ITMTRemotePlayerRadioPlaylist);
647                 
648                 if (isPlayingRadio && !wasPlayingRadio) {
649                     int i;
650                     for (i = 0; i < [playlistMenu numberOfItems]; i++) {
651                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
652                     }
653                 }
654                 
655                 if (wasPlayingRadio) {
656                     NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
657                     [menu insertItem:temp atIndex:trackInfoIndex + 1];
658                     [temp release];
659                 }
660                 
661                 if (!isPlayingRadio) {
662                     int i;
663                     for (i = 0; i < [playlistMenu numberOfItems]; i++)
664                     {
665                         [[playlistMenu itemAtIndex:i] setState:NSOffState];
666                     }
667                     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
668                 }
669                 
670                 [self updateMenu];
671                 lastSongIndex = trackPlayingIndex;
672                 lastPlaylistIndex = playlist;
673             }
674         }
675         //Update Play/Pause menu item
676         if (playPauseMenuItem){
677             if (playerPlayingState == ITMTRemotePlayerPlaying) {
678                 [playPauseMenuItem setTitle:@"Pause"];
679             } else {
680                 [playPauseMenuItem setTitle:@"Play"];
681             }
682         }
683     } else if ((lastPlaylistIndex > 0) && (playlist == 0)) {
684         NSMenuItem *menuItem;
685         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
686         //Remote the now playing item and add no song item
687         [menu removeItemAtIndex:trackInfoIndex];
688         
689         if ([defaults boolForKey:@"showName"] == YES) {
690             [menu removeItemAtIndex:trackInfoIndex];
691         }
692         
693         if ([defaults boolForKey:@"showTime"] == YES) {
694             [menu removeItemAtIndex:trackInfoIndex];
695         }
696         
697         if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
698             [menu removeItemAtIndex:trackInfoIndex];
699         }
700         
701         if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
702             [menu removeItemAtIndex:trackInfoIndex];
703         }
704         
705         [playPauseMenuItem setTitle:@"Play"];
706         
707         didHaveArtistName = NO;
708         didHaveAlbumName = NO;
709         lastPlaylistIndex = -1;
710         lastSongIndex = -1;
711         
712         [upcomingSongsItem setSubmenu:nil];
713         [upcomingSongsItem setEnabled:NO];
714         
715         [songRatingMenuItem setSubmenu:nil];
716         [songRatingMenuItem setEnabled:NO];
717         
718         menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
719         [menu insertItem:menuItem atIndex:trackInfoIndex];
720         [menuItem release];
721     }
722 }
723
724 - (void)remotePlayerLaunched:(NSNotification *)note
725 {
726     isAppRunning = ITMTRemotePlayerRunning;
727     
728     //Restart the timer
729     [NSThread detachNewThreadSelector:@selector(runTimerInNewThread) toTarget:self withObject:nil];
730     
731     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
732     if (playlistItem) {
733         [self rebuildPlaylistMenu];
734     }
735     if (eqItem) {
736         [self rebuildEQPresetsMenu];
737     }
738     [statusItem setMenu:menu]; //Set the menu back to the main one
739 }
740
741 - (void)runTimerInNewThread
742 {
743     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
744     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
745     refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES] retain];
746     [runLoop run];
747     [pool release];
748 }
749
750 - (void)remotePlayerTerminated:(NSNotification *)note
751 {
752     isAppRunning = ITMTRemotePlayerNotRunning;
753     
754     [menu release];
755     menu = [[NSMenu alloc] initWithTitle:@""];
756     [[menu addItemWithTitle:[NSString stringWithFormat:@"Open %@", [currentRemote playerSimpleName]] action:@selector(showPlayer:) keyEquivalent:@""] setTarget:self];
757     [menu addItem:[NSMenuItem separatorItem]];
758     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
759     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
760     [statusItem setMenu:menu];
761     
762     [refreshTimer invalidate];
763     [refreshTimer release];
764     refreshTimer = nil;
765     [self clearHotKeys];
766 }
767
768 //
769 //
770 // Selectors - called from status item menu
771 //
772 //
773
774 // Plugin dependent selectors
775
776 - (void)playTrack:(id)sender
777 {
778     [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
779 }
780
781 - (void)selectPlaylist:(id)sender
782 {
783     int playlist = [[sender representedObject] intValue];
784     if (!isPlayingRadio) {
785         int curPlaylist = [currentRemote currentPlaylistIndex];
786         if (curPlaylist > 0) {
787             [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
788         }
789     }
790     [currentRemote switchToPlaylistAtIndex:playlist];
791     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
792     [self updateMenu];
793 }
794
795 - (void)selectEQPreset:(id)sender
796 {
797     int curSet = [currentRemote currentEQPresetIndex];
798     int item = [[sender representedObject] intValue];
799     [currentRemote switchToEQAtIndex:item];
800     [[eqMenu itemAtIndex:curSet + 1] setState:NSOffState];
801     [[eqMenu itemAtIndex:item + 2] setState:NSOnState];
802 }
803
804 - (void)playPause:(id)sender
805 {
806     ITMTRemotePlayerPlayingState state = [currentRemote playerPlayingState];
807     
808     if (state == ITMTRemotePlayerPlaying) {
809         [currentRemote pause];
810         [playPauseMenuItem setTitle:@"Play"];
811     } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
812         [currentRemote pause];
813         [currentRemote play];
814     } else {
815         [currentRemote play];
816         [playPauseMenuItem setTitle:@"Pause"];
817     }
818 }
819
820 - (void)nextSong:(id)sender
821 {
822     [currentRemote goToNextSong];
823 }
824
825 - (void)prevSong:(id)sender
826 {
827     [currentRemote goToPreviousSong];
828 }
829
830 - (void)fastForward:(id)sender
831 {
832     [currentRemote forward];
833     [playPauseMenuItem setTitle:@"Play"];
834 }
835
836 - (void)rewind:(id)sender
837 {
838     [currentRemote rewind];
839     [playPauseMenuItem setTitle:@"Play"];
840 }
841
842 - (void)toggleEqualizer
843 {
844     [currentRemote setEqualizerEnabled:![currentRemote equalizerEnabled]];
845 }
846
847 - (void)setSongRating:(id)sender
848 {
849     NSLog(@"%f", [currentRemote currentSongRating]);
850     NSLog(@"%f", (float)[sender tag] / 100.0);
851     [currentRemote setCurrentSongRating:(float)[sender tag] / 100.0];
852 }
853
854 //
855 //
856 // Plugin independent selectors
857 //
858 //
859 - (void)quitMenuTunes:(id)sender
860 {
861     [NSApp terminate:self];
862 }
863
864 - (void)showPreferences:(id)sender
865 {
866     if (!prefsController) {
867         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
868         [self clearHotKeys];
869     }
870 }
871
872 - (void)closePreferences
873 {
874     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
875         [self setupHotKeys];
876     }
877     [prefsController release];
878     prefsController = nil;
879 }
880
881 - (void)showPlayer:(id)sender
882 {
883     if ( ( isAppRunning == ITMTRemotePlayerRunning) ) {
884         [currentRemote showPrimaryInterface];
885     } else {
886         if (![[NSWorkspace sharedWorkspace] launchApplication:[currentRemote playerFullName]]) {
887             NSLog(@"Error Launching Player");
888         }
889     }
890 }
891         
892
893 //
894 //
895 // Show Current Track Info And Show Upcoming Songs Floaters
896 //
897 //
898
899 - (void)showCurrentTrackInfo
900 {
901     NSString *trackName = [currentRemote currentSongTitle];
902     if (!statusWindow && [trackName length]) {
903         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
904         NSString *stringToShow = @"";
905         
906         if ([defaults boolForKey:@"showName"]) {
907             if ([defaults boolForKey:@"showArtist"]) {
908                 NSString *trackArtist = [currentRemote currentSongArtist];
909                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
910             }
911             stringToShow = [stringToShow stringByAppendingString:trackName];
912             stringToShow = [stringToShow stringByAppendingString:@"\n"];
913         }
914         
915         if ([defaults boolForKey:@"showAlbum"]) {
916             NSString *trackAlbum = [currentRemote currentSongAlbum];
917             if ([trackAlbum length]) {
918                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
919                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
920             }
921         }
922         
923         if ([defaults boolForKey:@"showTime"]) {
924             NSString *trackTime = [currentRemote currentSongLength];
925             if ([trackTime length]) {
926                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
927             }
928         }
929         
930         {
931             int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
932             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
933             if (seconds < 10) {
934                 stringToShow = [stringToShow stringByAppendingString:
935                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
936             } else {
937                 stringToShow = [stringToShow stringByAppendingString:
938                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
939             }
940         }
941         
942         [statusWindow setText:stringToShow];
943         [NSTimer scheduledTimerWithTimeInterval:3.0
944                     target:self
945                     selector:@selector(fadeAndCloseStatusWindow)
946                     userInfo:nil
947                     repeats:NO];
948     }
949 }
950
951 - (void)showUpcomingSongs
952 {
953     int curPlaylist = [currentRemote currentPlaylistIndex];
954     if (!statusWindow) {
955         int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
956         
957         if (numSongs > 0) {
958             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
959             int curTrack = [currentRemote currentSongIndex];
960             int i;
961             NSString *songs = @"";
962             
963             statusWindow = [ITTransientStatusWindow sharedWindow];
964             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
965                 if (i <= numSongs) {
966                     NSString *curSong = [currentRemote songTitleAtIndex:i];
967                     songs = [songs stringByAppendingString:curSong];
968                     songs = [songs stringByAppendingString:@"\n"];
969                 }
970             }
971             [statusWindow setText:songs];
972             [NSTimer scheduledTimerWithTimeInterval:3.0
973                         target:self
974                         selector:@selector(fadeAndCloseStatusWindow)
975                         userInfo:nil
976                         repeats:NO];
977         }
978     }
979 }
980
981 - (void)fadeAndCloseStatusWindow
982 {
983     [statusWindow orderOut:self];
984 }
985
986 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
987         onItem:(NSMenuItem *)item
988 {
989     unichar charcode = 'a';
990     int i;
991     long cocoaModifiers = 0;
992     static long carbonToCocoa[6][2] = 
993     {
994         { cmdKey, NSCommandKeyMask },
995         { optionKey, NSAlternateKeyMask },
996         { controlKey, NSControlKeyMask },
997         { shiftKey, NSShiftKeyMask },
998     };
999     
1000     for (i = 0; i < 6; i++) {
1001         if (modifiers & carbonToCocoa[i][0]) {
1002             cocoaModifiers += carbonToCocoa[i][1];
1003         }
1004     }
1005     [item setKeyEquivalentModifierMask:cocoaModifiers];
1006     
1007     //Missing key combos for some keys. Must find them later.
1008     switch (code)
1009     {
1010         case 36:
1011             charcode = '\r';
1012         break;
1013         
1014         case 48:
1015             charcode = '\t';
1016         break;
1017         
1018         //Space -- ARGH!
1019         case 49:
1020         {
1021             /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
1022             NSLog(@"%@", menuRef);
1023             SetMenuItemCommandKey(menuRef, 0, NO, 49);
1024             SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
1025             SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
1026             charcode = 'b';*/
1027         }
1028         break;
1029         
1030         case 51:
1031             charcode = NSDeleteFunctionKey;
1032         break;
1033         
1034         case 53:
1035             charcode = '\e';
1036         break;
1037         
1038         case 71:
1039             charcode = '\e';
1040         break;
1041         
1042         case 76:
1043             charcode = '\r';
1044         break;
1045         
1046         case 96:
1047             charcode = NSF5FunctionKey;
1048         break;
1049         
1050         case 97:
1051             charcode = NSF6FunctionKey;
1052         break;
1053         
1054         case 98:
1055             charcode = NSF7FunctionKey;
1056         break;
1057         
1058         case 99:
1059             charcode = NSF3FunctionKey;
1060         break;
1061         
1062         case 100:
1063             charcode = NSF8FunctionKey;
1064         break;
1065         
1066         case 101:
1067             charcode = NSF9FunctionKey;
1068         break;
1069         
1070         case 103:
1071             charcode = NSF11FunctionKey;
1072         break;
1073         
1074         case 105:
1075             charcode = NSF3FunctionKey;
1076         break;
1077         
1078         case 107:
1079             charcode = NSF14FunctionKey;
1080         break;
1081         
1082         case 109:
1083             charcode = NSF10FunctionKey;
1084         break;
1085         
1086         case 111:
1087             charcode = NSF12FunctionKey;
1088         break;
1089         
1090         case 113:
1091             charcode = NSF13FunctionKey;
1092         break;
1093         
1094         case 114:
1095             charcode = NSInsertFunctionKey;
1096         break;
1097         
1098         case 115:
1099             charcode = NSHomeFunctionKey;
1100         break;
1101         
1102         case 116:
1103             charcode = NSPageUpFunctionKey;
1104         break;
1105         
1106         case 117:
1107             charcode = NSDeleteFunctionKey;
1108         break;
1109         
1110         case 118:
1111             charcode = NSF4FunctionKey;
1112         break;
1113         
1114         case 119:
1115             charcode = NSEndFunctionKey;
1116         break;
1117         
1118         case 120:
1119             charcode = NSF2FunctionKey;
1120         break;
1121         
1122         case 121:
1123             charcode = NSPageDownFunctionKey;
1124         break;
1125         
1126         case 122:
1127             charcode = NSF1FunctionKey;
1128         break;
1129         
1130         case 123:
1131             charcode = NSLeftArrowFunctionKey;
1132         break;
1133         
1134         case 124:
1135             charcode = NSRightArrowFunctionKey;
1136         break;
1137         
1138         case 125:
1139             charcode = NSDownArrowFunctionKey;
1140         break;
1141         
1142         case 126:
1143             charcode = NSUpArrowFunctionKey;
1144         break;
1145     }
1146     
1147     if (charcode == 'a') {
1148         unsigned long state;
1149         long keyTrans;
1150         char charCode;
1151         Ptr kchr;
1152         state = 0;
1153         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1154         keyTrans = KeyTranslate(kchr, code, &state);
1155         charCode = keyTrans;
1156         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1157     } else if (charcode != 'b') {
1158         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1159     }
1160 }
1161
1162 /*************************************************************************/
1163 #pragma mark -
1164 #pragma mark NSApplication DELEGATE METHODS
1165 /*************************************************************************/
1166
1167 - (void)applicationWillTerminate:(NSNotification *)note
1168 {
1169     [self clearHotKeys];
1170     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1171 }
1172
1173
1174 /*************************************************************************/
1175 #pragma mark -
1176 #pragma mark DEALLOCATION METHODS
1177 /*************************************************************************/
1178
1179 - (void)dealloc
1180 {
1181     if (refreshTimer) {
1182         [refreshTimer invalidate];
1183         [refreshTimer release];
1184         refreshTimer = nil;
1185     }
1186     [currentRemote halt];
1187     [statusItem release];
1188     [menu release];
1189 //  [view release];
1190     [super dealloc];
1191 }
1192
1193 @end