Easy parts of the plugin are done. Small improvements in MenuTunes main
[MenuTunes.git] / MenuTunes.m
1 /*
2 Things to do:
3 ¥ Make preferences window pretty
4 ¥ Optimize
5 ¥ Apple Events! Apple Events! Apple Events!
6 ¥ Manual and webpage
7 ¥ Finish up registration frontend
8 */
9
10 #import "MenuTunes.h"
11 #import "PreferencesController.h"
12 #import "HotKeyCenter.h"
13 #import "StatusWindowController.h"
14
15 @interface MenuTunes(Private)
16 - (ITMTRemote *)loadRemote;
17 - (void)updateMenu;
18 - (void)rebuildUpcomingSongsMenu;
19 - (void)rebuildPlaylistMenu;
20 - (void)rebuildEQPresetsMenu;
21 - (void)setupHotKeys;
22 - (NSString *)runScriptAndReturnResult:(NSString *)script;
23 - (void)timerUpdate;
24 - (void)sendAEWithEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID;
25 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
26         onItem:(NSMenuItem *)item;
27
28 @end
29
30 @implementation MenuTunes
31
32 /*************************************************************************/
33 #pragma mark -
34 #pragma mark INITIALIZATION METHODS
35 /*************************************************************************/
36
37 - (id)init
38 {
39     if ( ( self = [super init] ) ) {
40         remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
41     }
42     return self;
43 }
44
45 - (void)applicationDidFinishLaunching:(NSNotification *)note
46 {
47     currentRemote = [self loadRemote];
48     asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
49
50     [self registerDefaultsIfNeeded];
51     
52     menu = [[NSMenu alloc] initWithTitle:@""];
53     iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
54     
55     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
56     {
57         [self rebuildMenu];
58         refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
59                             target:self
60                             selector:@selector(timerUpdate)
61                             userInfo:nil
62                             repeats:YES];
63         
64         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
65     }
66     else
67     {
68         menu = [[NSMenu alloc] initWithTitle:@""];
69         [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
70         [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
71         [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
72         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
73         refreshTimer = nil;
74     }
75
76     statusItem = [[ITStatusItem alloc] initWithStatusBar:[NSStatusBar systemStatusBar]
77                                               withLength:NSSquareStatusItemLength];
78     
79     [statusItem setImage:[NSImage imageNamed:@"menu"]];
80     [statusItem setAlternateImage:[NSImage imageNamed:@"selected_image"]];
81     [statusItem setMenu:menu];
82     // Below line of code is for creating builds for Beta Testers
83     // [statusItem setToolTip:@[NSString stringWithFormat:@"This Nontransferable Beta (Built on %s) of iThink Software's MenuTunes is Registered to: Beta Tester (betatester@somedomain.com).",__DATE__]];
84 }
85
86 - (ITMTRemote *)loadRemote
87 {
88     NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
89
90     if (folderPath) {
91         NSArray      *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
92         NSEnumerator *enumerator     = [bundlePathList objectEnumerator];
93         NSString     *bundlePath;
94
95         while ( (bundlePath = [enumerator nextObject]) ) {
96             NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
97
98             if (remoteBundle) {
99                 Class remoteClass = [remoteBundle principalClass];
100
101                 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
102                     [remoteClass isKindOfClass:[NSObject class]]) {
103
104                     id remote = [remoteClass remote];
105                     [remoteArray addObject:remote];
106                 }
107             }
108         }
109
110 //      if ( [remoteArray count] > 0 ) {
111 //          if ( [remoteArray count] > 1 ) {
112 //              [remoteArray sortUsingSelector:@selector(sortAlpha:)];
113 //          }
114 //          [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
115 //      }
116     }
117     NSLog(@"%@", [remoteArray objectAtIndex:0]);
118     return [remoteArray objectAtIndex:0];
119 }
120
121
122 /*************************************************************************/
123 #pragma mark -
124 #pragma mark INSTANCE METHODS
125 /*************************************************************************/
126
127 - (void)registerDefaultsIfNeeded
128 {
129     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
130     if (![defaults objectForKey:@"menu"]) {
131         bool found = NO;
132         NSMutableDictionary *loginwindow;
133         NSMutableArray *loginarray;
134         int i;
135         
136         [defaults setObject:
137             [NSArray arrayWithObjects:
138                 @"Play/Pause",
139                 @"Next Track",
140                 @"Previous Track",
141                 @"Fast Forward",
142                 @"Rewind",
143                 @"<separator>",
144                 @"Upcoming Songs",
145                 @"Playlists",
146                 @"<separator>",
147                 @"PreferencesÉ",
148                 @"Quit",
149                 @"<separator>",
150                 @"Current Track Info",
151                 nil] forKey:@"menu"];
152         
153         [defaults synchronize];
154         loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
155         loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
156         
157         for (i = 0; i < [loginarray count]; i++) {
158             NSDictionary *tempDict = [loginarray objectAtIndex:i];
159             if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
160                 found = YES;
161             }
162         }
163         
164         if (!found) {
165             if (NSRunInformationalAlertPanel(@"Auto-launch MenuTunes", @"Would you like MenuTunes to automatically launch at login?", @"Yes", @"No", nil) == NSOKButton) {
166                 AEDesc scriptDesc, resultDesc;
167                 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]];
168                 
169                 AECreateDesc(typeChar, [script cString], [script cStringLength], 
170             &scriptDesc);
171                 
172                 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
173                 
174                 AEDisposeDesc(&scriptDesc);
175                 AEDisposeDesc(&resultDesc);
176             }
177         }
178     }
179     
180     if (![defaults integerForKey:@"SongsInAdvance"])
181     {
182         [defaults setInteger:5 forKey:@"SongsInAdvance"];
183     }
184     
185     if (![defaults objectForKey:@"showName"]) {
186         [defaults setBool:YES forKey:@"showName"];
187     }
188     
189     if (![defaults objectForKey:@"showArtist"]) {
190         [defaults setBool:YES forKey:@"showArtist"];
191     }
192     
193     if (![defaults objectForKey:@"showAlbum"]) {
194         [defaults setBool:NO forKey:@"showAlbum"];
195     }
196     
197     if (![defaults objectForKey:@"showTime"]) {
198         [defaults setBool:NO forKey:@"showTime"];
199     }
200 }
201
202 //Recreate the status item menu
203 - (void)rebuildMenu
204 {
205     NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
206     int i;
207     
208     trackInfoIndex = -1;
209     didHaveAlbumName = ([[self runScriptAndReturnResult:@"return album of current track"] length] > 0);
210     didHaveArtistName = ([[self runScriptAndReturnResult:@"return artist of current track"] length] > 0);
211     
212     
213     while ([menu numberOfItems] > 0) {
214         [menu removeItemAtIndex:0];
215     }
216     
217     playPauseMenuItem = nil;
218     upcomingSongsItem = nil;
219     playlistItem = nil;
220     [playlistMenu release];
221     playlistMenu = nil;
222     eqItem = nil;
223     [eqMenu release];
224     eqMenu = nil;
225     
226     for (i = 0; i < [myMenu count]; i++) {
227         NSString *item = [myMenu objectAtIndex:i];
228         if ([item isEqualToString:@"Play/Pause"]) {
229             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PlayPause"];
230             playPauseMenuItem = [menu addItemWithTitle:@"Play"
231                                     action:@selector(playPause:)
232                                     keyEquivalent:@""];
233             [playPauseMenuItem setTarget:self];
234             
235             if (tempCombo)
236             {
237                 [self setKeyEquivalentForCode:[tempCombo keyCode]
238                     andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
239                 [tempCombo release];
240             }
241         } else if ([item isEqualToString:@"Next Track"]) {
242             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"NextTrack"];
243             NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
244                                         action:@selector(nextSong:)
245                                         keyEquivalent:@""];
246             
247             [nextTrack setTarget:self];
248             if (tempCombo)
249             {
250                 [self setKeyEquivalentForCode:[tempCombo keyCode]
251                     andModifiers:[tempCombo modifiers] onItem:nextTrack];
252                 [tempCombo release];
253             }
254         } else if ([item isEqualToString:@"Previous Track"]) {
255             KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PrevTrack"];
256             NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
257                                         action:@selector(prevSong:)
258                                         keyEquivalent:@""];
259             
260             [prevTrack setTarget:self];
261             if (tempCombo)
262             {
263                 [self setKeyEquivalentForCode:[tempCombo keyCode]
264                     andModifiers:[tempCombo modifiers] onItem:prevTrack];
265                 [tempCombo release];
266             }
267         } else if ([item isEqualToString:@"Fast Forward"]) {
268             [[menu addItemWithTitle:@"Fast Forward"
269                              action:@selector(fastForward:)
270                       keyEquivalent:@""] setTarget:self];
271         } else if ([item isEqualToString:@"Rewind"]) {
272             [[menu addItemWithTitle:@"Rewind"
273                              action:@selector(rewind:)
274                       keyEquivalent:@""] setTarget:self];
275         } else if ([item isEqualToString:@"Upcoming Songs"]) {
276             upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
277                                                 action:nil
278                                          keyEquivalent:@""];
279         } else if ([item isEqualToString:@"Playlists"]) {
280             playlistItem = [menu addItemWithTitle:@"Playlists"
281                                            action:nil
282                                     keyEquivalent:@""];
283         } else if ([item isEqualToString:@"EQ Presets"]) {
284             eqItem = [menu addItemWithTitle:@"EQ Presets"
285                                      action:nil
286                               keyEquivalent:@""];
287         } else if ([item isEqualToString:@"PreferencesÉ"]) {
288             [[menu addItemWithTitle:@"PreferencesÉ"
289                              action:@selector(showPreferences:)
290                       keyEquivalent:@""] setTarget:self];
291         } else if ([item isEqualToString:@"Quit"]) {
292             [[menu addItemWithTitle:@"Quit"
293                              action:@selector(quitMenuTunes:)
294                       keyEquivalent:@""] setTarget:self];
295         } else if ([item isEqualToString:@"Current Track Info"]) {
296             trackInfoIndex = [menu numberOfItems];
297             [menu addItemWithTitle:@"No Song"
298                             action:nil
299                      keyEquivalent:@""];
300         } else if ([item isEqualToString:@"<separator>"]) {
301             [menu addItem:[NSMenuItem separatorItem]];
302         }
303     }
304     
305     curTrackIndex = -1; //Force update of everything
306     [self timerUpdate]; //Updates dynamic info in the menu
307     
308     [self clearHotKeys];
309     [self setupHotKeys];
310 }
311
312 //Updates the menu with current player state, song, and upcoming songs
313 - (void)updateMenu
314 {
315     NSMenuItem *menuItem;
316     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
317     
318     if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
319         return;
320     }
321     
322     if (upcomingSongsItem) {
323         [self rebuildUpcomingSongsMenu];
324     }
325     
326     if (playlistItem) {
327         [self rebuildPlaylistMenu];
328     }
329     
330     if (eqItem) {
331         [self rebuildEQPresetsMenu];
332     }
333     
334     if (trackInfoIndex > -1)
335     {
336         NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
337         curSongName = [self runScriptAndReturnResult:@"return name of current track"];
338         
339         if ([defaults boolForKey:@"showAlbum"]) {
340             curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
341         }
342         
343         if ([defaults boolForKey:@"showArtist"]) {
344             curArtistName = [self runScriptAndReturnResult:@"return artist of current track"];
345         }
346         
347         if ([curSongName length] > 0) {
348             int index = [menu indexOfItemWithTitle:@"Now Playing"];
349             if (index > -1) {
350                 if ([defaults boolForKey:@"showName"]) {
351                     [menu removeItemAtIndex:index + 1];
352                 }
353                 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
354                     [menu removeItemAtIndex:index + 1];
355                 }
356                 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
357                     [menu removeItemAtIndex:index + 1];
358                 }
359                 if ([defaults boolForKey:@"showTime"]) {
360                     [menu removeItemAtIndex:index + 1];
361                 }
362             }
363             
364             if (!isPlayingRadio) {
365                 if ([defaults boolForKey:@"showTime"]) {
366                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", [self runScriptAndReturnResult:@"return time of current track"]]
367                                                         action:nil
368                                                         keyEquivalent:@""];
369                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
370                     [menuItem release];
371                 }
372                 
373                 if ([curArtistName length] > 0) {
374                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curArtistName]
375                                                         action:nil
376                                                         keyEquivalent:@""];
377                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
378                     [menuItem release];
379                 }
380                 
381                 if ([curAlbumName length] > 0) {
382                     menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curAlbumName]
383                                                         action:nil
384                                                         keyEquivalent:@""];
385                     [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
386                     [menuItem release];
387                 }
388             }
389             
390             if ([defaults boolForKey:@"showName"]) {
391                 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"  %@", curSongName]
392                                                     action:nil
393                                                     keyEquivalent:@""];
394                 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
395                 [menuItem release];
396             }
397             
398             if (index == -1) {
399                 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
400                 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
401                 [menu insertItem:menuItem atIndex:trackInfoIndex];
402                 [menuItem release];
403             }
404         } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
405             [menu removeItemAtIndex:trackInfoIndex];
406             
407             if ([defaults boolForKey:@"showName"] == YES) {
408                 [menu removeItemAtIndex:trackInfoIndex];
409             }
410             
411             if ([defaults boolForKey:@"showTime"] == YES) {
412                 [menu removeItemAtIndex:trackInfoIndex];
413             }
414             
415             if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
416                 [menu removeItemAtIndex:trackInfoIndex];
417             }
418             
419             if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
420                 [menu removeItemAtIndex:trackInfoIndex];
421             }
422             
423             menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
424             [menu insertItem:menuItem atIndex:trackInfoIndex];
425             [menuItem release];
426         }
427         
428         if ([defaults boolForKey:@"showArtist"]) {
429             didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
430         }
431             
432         if ([defaults boolForKey:@"showAlbum"]) {
433             didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
434         }
435     }
436 }
437
438 //Rebuild the upcoming songs submenu. Can be improved a lot.
439 - (void)rebuildUpcomingSongsMenu
440 {
441     int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
442     int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
443     if (!isPlayingRadio) {
444         if (numSongs > 0) {
445             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
446             int i;
447             
448             [upcomingSongsMenu release];
449             upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
450             [upcomingSongsItem setSubmenu:upcomingSongsMenu];
451             [upcomingSongsItem setEnabled:YES];
452             
453             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
454                 if (i <= numSongs) {
455                     NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
456                     NSMenuItem *songItem;
457                     songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
458                     [songItem setTarget:self];
459                     [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
460                     [upcomingSongsMenu addItem:songItem];
461                     [songItem release];
462                 } else {
463                     break;
464                 }
465             }
466         }
467     } else {
468         [upcomingSongsItem setSubmenu:nil];
469         [upcomingSongsItem setEnabled:NO];
470     }
471 }
472
473 - (void)rebuildPlaylistMenu
474 {
475     int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
476     int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
477     
478     if (isPlayingRadio)
479     {
480         curPlaylist = 0;
481     }
482     
483     if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
484         return;
485     
486     [playlistMenu release];
487     playlistMenu = [[NSMenu alloc] initWithTitle:@""];
488     
489     for (i = 1; i <= numPlaylists; i++) {
490         NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
491         NSMenuItem *tempItem;
492         tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
493         [tempItem setTarget:self];
494         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
495         [playlistMenu addItem:tempItem];
496         [tempItem release];
497     }
498     [playlistItem setSubmenu:playlistMenu];
499     
500     if (curPlaylist) {
501         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
502     }
503 }
504
505 //Build a menu with the list of all available EQ presets
506 - (void)rebuildEQPresetsMenu
507 {
508     int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
509     int i;
510     
511     if (eqMenu && (numSets == [eqMenu numberOfItems]))
512         return;
513     
514     [eqMenu release];
515     eqMenu = [[NSMenu alloc] initWithTitle:@""];
516     
517     for (i = 1; i <= numSets; i++) {
518         NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
519         NSMenuItem *tempItem;
520         tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
521         [tempItem setTarget:self];
522         [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
523         [eqMenu addItem:tempItem];
524         [tempItem release];
525     }
526     [eqItem setSubmenu:eqMenu];
527     
528     [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
529 }
530
531 - (void)clearHotKeys
532 {
533     [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
534     [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
535     [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
536     [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
537     [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
538 }
539
540 - (void)setupHotKeys
541 {
542     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
543     
544     if ([defaults objectForKey:@"PlayPause"] != nil) {
545         [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
546                 combo:[defaults keyComboForKey:@"PlayPause"]
547                 target:self action:@selector(playPause:)];
548     }
549     
550     if ([defaults objectForKey:@"NextTrack"] != nil) {
551         [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
552                 combo:[defaults keyComboForKey:@"NextTrack"]
553                 target:self action:@selector(nextSong:)];
554     }
555     
556     if ([defaults objectForKey:@"PrevTrack"] != nil) {
557         [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
558                 combo:[defaults keyComboForKey:@"PrevTrack"]
559                 target:self action:@selector(prevSong:)];
560     }
561     
562     if ([defaults objectForKey:@"TrackInfo"] != nil) {
563         [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
564                 combo:[defaults keyComboForKey:@"TrackInfo"]
565                 target:self action:@selector(showCurrentTrackInfo)];
566     }
567     
568     if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
569         [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
570                combo:[defaults keyComboForKey:@"UpcomingSongs"]
571                target:self action:@selector(showUpcomingSongs)];
572     }
573 }
574
575 //Runs an AppleScript and returns the result as an NSString after stripping quotes, if needed. It takes in script and automatically adds the tell iTunes and end tell statements.
576 - (NSString *)runScriptAndReturnResult:(NSString *)script
577 {
578     AEDesc scriptDesc, resultDesc;
579     Size length;
580     NSString *result;
581     Ptr buffer;
582     
583     script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
584     
585     AECreateDesc(typeChar, [script cString], [script cStringLength], 
586 &scriptDesc);
587     
588     OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
589     
590     length = AEGetDescDataSize(&resultDesc);
591     buffer = malloc(length);
592     
593     AEGetDescData(&resultDesc, buffer, length);
594     AEDisposeDesc(&scriptDesc);
595     AEDisposeDesc(&resultDesc);
596     result = [NSString stringWithCString:buffer length:length];
597     if ( (! [result isEqualToString:@""])      &&
598          ([result characterAtIndex:0] == '\"') &&
599          ([result characterAtIndex:[result length] - 1] == '\"') ) {
600         result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
601     }
602     free(buffer);
603     buffer = nil;
604     return result;
605 }
606
607 //Called when the timer fires.
608 - (void)timerUpdate
609 {
610     int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
611     
612     if (trackPlayingIndex != curTrackIndex) {
613         bool wasPlayingRadio = isPlayingRadio;
614         isPlayingRadio = [[self runScriptAndReturnResult:@"return class of current playlist"] isEqualToString:@"radio tuner playlist"];
615         if (isPlayingRadio && !wasPlayingRadio) {
616             int i;
617             for (i = 0; i < [playlistMenu numberOfItems]; i++)
618             {
619                 [[playlistMenu itemAtIndex:i] setState:NSOffState];
620             }
621         }
622         if (wasPlayingRadio) {
623             NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
624             [menu insertItem:temp atIndex:trackInfoIndex + 1];
625             [temp release];
626         }
627         [self updateMenu];
628         curTrackIndex = trackPlayingIndex;
629     }
630     else
631     {
632         int playlist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
633         if (playlist != curPlaylistIndex) {
634             bool wasPlayingRadio = isPlayingRadio;
635             isPlayingRadio = [[self runScriptAndReturnResult:@"return class of current playlist"] isEqualToString:@"radio tuner playlist"];
636             if (isPlayingRadio && !wasPlayingRadio) {
637                 int i;
638                 for (i = 0; i < [playlistMenu numberOfItems]; i++)
639                 {
640                     [[playlistMenu itemAtIndex:i] setState:NSOffState];
641                 }
642             }
643             if (wasPlayingRadio) {
644                 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
645                 [menu insertItem:temp atIndex:trackInfoIndex + 1];
646                 [temp release];
647             }
648             [self updateMenu];
649             curTrackIndex = trackPlayingIndex;
650             curPlaylistIndex = playlist;
651         }
652     }
653     //Update Play/Pause menu item
654     if (playPauseMenuItem){
655         if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"]) {
656             [playPauseMenuItem setTitle:@"Pause"];
657         } else {
658             [playPauseMenuItem setTitle:@"Play"];
659         }
660     }
661 }
662
663 - (void)iTunesLaunched:(NSNotification *)note
664 {
665     NSDictionary *info = [note userInfo];
666     
667     iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
668     iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
669     
670     //Restart the timer
671     refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; 
672     
673     [self rebuildMenu]; //Rebuild the menu since no songs will be playing
674     [statusItem setMenu:menu]; //Set the menu back to the main one
675     [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
676     
677     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
678 }
679
680 - (void)iTunesTerminated:(NSNotification *)note
681 {
682     [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
683     
684     [menu release];
685     menu = [[NSMenu alloc] initWithTitle:@""];
686     [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
687     [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
688     [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
689     [statusItem setMenu:menu];
690     
691     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
692     [refreshTimer invalidate];
693     refreshTimer = nil;
694     [self clearHotKeys];
695 }
696
697 //Return the PSN of iTunes, if it's running
698 - (ProcessSerialNumber)iTunesPSN
699 {
700     NSArray *apps = [[NSWorkspace sharedWorkspace] launchedApplications];
701     ProcessSerialNumber number;
702     int i;
703     
704     number.highLongOfPSN = kNoProcess;
705     
706     for (i = 0; i < [apps count]; i++)
707     {
708         NSDictionary *curApp = [apps objectAtIndex:i];
709         
710         if ([[curApp objectForKey:@"NSApplicationName"] isEqualToString:@"iTunes"])
711         {
712             number.highLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
713             number.lowLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
714         }
715     }
716     return number;
717 }
718
719 //Send an AppleEvent with a given event ID
720 - (void)sendAEWithEventClass:(AEEventClass)eventClass 
721 andEventID:(AEEventID)eventID
722 {
723     OSType iTunesType = 'hook';
724     AppleEvent event, reply;
725     
726     AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
727     
728     AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
729     AEDisposeDesc(&event);
730     AEDisposeDesc(&reply);
731 }
732
733 //
734 //
735 // Selectors - called from status item menu
736 //
737 //
738
739 // Plugin dependent selectors
740
741 - (void)playTrack:(id)sender
742 {
743     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
744     [self updateMenu];
745 }
746
747 - (void)selectPlaylist:(id)sender
748 {
749     int playlist = [[sender representedObject] intValue];
750     if (!isPlayingRadio) {
751         int curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
752         [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
753     }
754     [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
755     [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
756 }
757
758 - (void)selectEQPreset:(id)sender
759 {
760     int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
761     int item = [[sender representedObject] intValue];
762     [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
763     [self runScriptAndReturnResult:@"set EQ enabled to 1"];
764     [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
765     [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
766 }
767
768 - (void)playPause:(id)sender
769 {
770     NSString *rawr;
771     NSString *state = [self runScriptAndReturnResult:@"return player state"];
772     if ([state isEqualToString:@"playing"]) {
773         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
774         [playPauseMenuItem setTitle:@"Play"];
775     } else if ([state isEqualToString:@"fast forwarding"] || [state 
776 isEqualToString:@"rewinding"]) {
777         [self sendAEWithEventClass:'hook' andEventID:'Paus'];
778         [self sendAEWithEventClass:'hook' andEventID:'Play'];
779     } else {
780         [self sendAEWithEventClass:'hook' andEventID:'Play'];
781         [playPauseMenuItem setTitle:@"Pause"];
782     }
783 }
784
785 - (void)nextSong:(id)sender
786 {
787     [currentRemote goToNextSong];
788 }
789
790 - (void)prevSong:(id)sender
791 {
792     [currentRemote goToPreviousSong];
793 }
794
795 - (void)fastForward:(id)sender
796 {
797     [self sendAEWithEventClass:'hook' andEventID:'Fast'];
798 }
799
800 - (void)rewind:(id)sender
801 {
802     [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
803 }
804
805 // Plugin independent selectors
806
807 - (void)quitMenuTunes:(id)sender
808 {
809     [NSApp terminate:self];
810 }
811
812 - (void)openiTunes:(id)sender
813 {
814     [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
815 }
816
817 - (void)showPreferences:(id)sender
818 {
819     if (!prefsController) {
820         prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
821         [self clearHotKeys];
822     }
823 }
824
825
826 - (void)closePreferences
827 {
828     if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
829         [self setupHotKeys];
830     }
831     [prefsController release];
832     prefsController = nil;
833 }
834
835 //
836 //
837 // Show Current Track Info And Show Upcoming Songs Floaters
838 //
839 //
840
841 - (void)showCurrentTrackInfo
842 {
843     NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
844     if (!statusController && [trackName length]) {
845         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
846         NSString *stringToShow = @"";
847         
848         if ([defaults boolForKey:@"showName"]) {
849             if ([defaults boolForKey:@"showArtist"]) {
850                 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
851                 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
852             }
853             stringToShow = [stringToShow stringByAppendingString:trackName];
854             stringToShow = [stringToShow stringByAppendingString:@"\n"];
855         }
856         
857         if ([defaults boolForKey:@"showAlbum"]) {
858             NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
859             if ([trackAlbum length]) {
860                 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
861                 stringToShow = [stringToShow stringByAppendingString:@"\n"];
862             }
863         }
864         
865         if ([defaults boolForKey:@"showTime"]) {
866             NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
867             if ([trackTime length]) {
868                 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
869             }
870         }
871         
872         {
873             int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
874             int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
875             if (seconds < 10) {
876                 stringToShow = [stringToShow stringByAppendingString:
877                             [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
878             } else {
879                 stringToShow = [stringToShow stringByAppendingString:
880                             [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
881             }
882         }
883         
884         statusController = [[StatusWindowController alloc] init];
885         [statusController setTrackInfo:stringToShow];
886         [NSTimer scheduledTimerWithTimeInterval:3.0
887                                     target:self
888                                     selector:@selector(fadeAndCloseStatusWindow)
889                                     userInfo:nil
890                                     repeats:NO];
891     }
892 }
893
894 - (void)showUpcomingSongs
895 {
896     if (!statusController) {
897         int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
898         
899         if (numSongs > 0) {
900             int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
901             int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
902             int i;
903             NSString *songs = @"";
904             
905             statusController = [[StatusWindowController alloc] init];
906             for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
907                 if (i <= numSongs) {
908                     NSString *curSong = [self runScriptAndReturnResult:
909                         [NSString stringWithFormat:@"return name of track %i of current playlist", i]];
910                     songs = [songs stringByAppendingString:curSong];
911                     songs = [songs stringByAppendingString:@"\n"];
912                 }
913             }
914             [statusController setUpcomingSongs:songs];
915             [NSTimer scheduledTimerWithTimeInterval:3.0
916                         target:self
917                         selector:@selector(fadeAndCloseStatusWindow)
918                         userInfo:nil
919                         repeats:NO];
920         }
921     }
922 }
923
924 - (void)fadeAndCloseStatusWindow
925 {
926     [statusController fadeWindowOut];
927     [statusController release];
928     statusController = nil;
929 }
930
931 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
932         onItem:(NSMenuItem *)item
933 {
934     unichar charcode = 'a';
935     int i;
936     long cocoaModifiers = 0;
937     static long carbonToCocoa[6][2] = 
938     {
939         { cmdKey, NSCommandKeyMask },
940         { optionKey, NSAlternateKeyMask },
941         { controlKey, NSControlKeyMask },
942         { shiftKey, NSShiftKeyMask },
943     };
944     
945     for (i = 0; i < 6; i++)
946     {
947         if (modifiers & carbonToCocoa[i][0])
948         {
949             cocoaModifiers += carbonToCocoa[i][1];
950         }
951     }
952     [item setKeyEquivalentModifierMask:cocoaModifiers];
953     
954     //Missing key combos for some keys. Must find them later.
955     switch (code)
956     {
957         case 36:
958         break;
959         
960         case 48:
961         break;
962         
963         case 49:
964         break;
965         
966         case 51:
967             charcode = NSDeleteFunctionKey;
968         break;        
969         case 53:
970         break;
971                 
972         case 71:
973         break;
974         
975         case 76:
976         break;
977         
978         case 96:
979             charcode = NSF5FunctionKey;
980         break;
981         
982         case 97:
983             charcode = NSF6FunctionKey;
984         break;
985         
986         case 98:
987             charcode = NSF7FunctionKey;
988         break;
989         
990         case 99:
991             charcode = NSF3FunctionKey;
992         break;
993         
994         case 100:
995             charcode = NSF8FunctionKey;
996         break;
997         
998         case 101:
999             charcode = NSF9FunctionKey;
1000         break;
1001         
1002         case 103:
1003             charcode = NSF11FunctionKey;
1004         break;
1005         
1006         case 105:
1007             charcode = NSF3FunctionKey;
1008         break;
1009         
1010         case 107:
1011             charcode = NSF14FunctionKey;
1012         break;
1013         
1014         case 109:
1015             charcode = NSF10FunctionKey;
1016         break;
1017         
1018         case 111:
1019             charcode = NSF12FunctionKey;
1020         break;
1021         
1022         case 113:
1023             charcode = NSF13FunctionKey;
1024         break;
1025         
1026         case 114:
1027             charcode = NSInsertFunctionKey;
1028         break;
1029         
1030         case 115:
1031         break;
1032         
1033         case 116:
1034             charcode = NSPageUpFunctionKey;
1035         break;
1036         
1037         case 117:
1038             charcode = NSDeleteFunctionKey;
1039         break;
1040         
1041         case 118:
1042             charcode = NSF4FunctionKey;
1043         break;
1044         
1045         case 119:
1046             charcode = NSEndFunctionKey;
1047         break;
1048         
1049         case 120:
1050             charcode = NSF2FunctionKey;
1051         break;
1052         
1053         case 121:
1054             charcode = NSPageDownFunctionKey;
1055         break;
1056         
1057         case 122:
1058             charcode = NSF1FunctionKey;
1059         break;
1060         
1061         case 123:
1062             charcode = NSLeftArrowFunctionKey;
1063         break;
1064         
1065         case 124:
1066             charcode = NSRightArrowFunctionKey;
1067         break;
1068         
1069         case 125:
1070             charcode = NSDownArrowFunctionKey;
1071         break;
1072         
1073         case 126:
1074             charcode = NSUpArrowFunctionKey;
1075         break;
1076     }
1077     
1078     if (charcode == 'a') {
1079         unsigned long state;
1080         long keyTrans;
1081         char charCode;
1082         Ptr kchr;
1083         state = 0;
1084         kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1085         keyTrans = KeyTranslate(kchr, code, &state);
1086         charCode = keyTrans;
1087         [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1088     } else {
1089         [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1090     }
1091 }
1092
1093 /*************************************************************************/
1094 #pragma mark -
1095 #pragma mark NSApplication DELEGATE METHODS
1096 /*************************************************************************/
1097
1098 - (void)applicationWillTerminate:(NSNotification *)note
1099 {
1100     [self clearHotKeys];
1101     [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1102 }
1103
1104
1105 /*************************************************************************/
1106 #pragma mark -
1107 #pragma mark DEALLOCATION METHODS
1108 /*************************************************************************/
1109
1110 - (void)dealloc
1111 {
1112     if (refreshTimer) {
1113         [refreshTimer invalidate];
1114         refreshTimer = nil;
1115     }
1116     CloseComponent(asComponent);
1117     [statusItem release];
1118     [menu release];
1119 //  [view release];
1120     [super dealloc];
1121 }
1122
1123 @end