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