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