3 ¥ Make preferences window pretty
5 ¥ Apple Events! Apple Events! Apple Events!
7 ¥ Finish up registration frontend
11 #import "PreferencesController.h"
12 #import "HotKeyCenter.h"
13 #import "StatusWindowController.h"
15 @interface MenuTunes(Private)
16 - (ITMTRemote *)loadRemote;
18 - (void)rebuildUpcomingSongsMenu;
19 - (void)rebuildPlaylistMenu;
20 - (void)rebuildEQPresetsMenu;
22 - (NSString *)runScriptAndReturnResult:(NSString *)script;
24 - (void)sendAEWithEventClass:(AEEventClass)eventClass andEventID:(AEEventID)eventID;
25 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
26 onItem:(NSMenuItem *)item;
30 @implementation MenuTunes
32 /*************************************************************************/
34 #pragma mark INITIALIZATION METHODS
35 /*************************************************************************/
39 if ( ( self = [super init] ) ) {
40 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
45 - (void)applicationDidFinishLaunching:(NSNotification *)note
47 currentRemote = [self loadRemote];
48 asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
50 [self registerDefaultsIfNeeded];
52 menu = [[NSMenu alloc] initWithTitle:@""];
53 iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
55 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
58 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
60 selector:@selector(timerUpdate)
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];
74 statusItem = [[ITStatusItem alloc] initWithStatusBar:[NSStatusBar systemStatusBar]
75 withLength:NSSquareStatusItemLength];
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__]];
84 - (ITMTRemote *)loadRemote
86 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
89 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
90 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
93 while ( (bundlePath = [enumerator nextObject]) ) {
94 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
97 Class remoteClass = [remoteBundle principalClass];
99 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
100 [remoteClass isKindOfClass:[NSObject class]]) {
102 id remote = [remoteClass remote];
103 [remoteArray addObject:remote];
108 // if ( [remoteArray count] > 0 ) {
109 // if ( [remoteArray count] > 1 ) {
110 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
112 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
115 NSLog(@"%@", [remoteArray objectAtIndex:0]);
116 return [remoteArray objectAtIndex:0];
120 /*************************************************************************/
122 #pragma mark INSTANCE METHODS
123 /*************************************************************************/
125 - (void)registerDefaultsIfNeeded
127 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
128 if (![defaults objectForKey:@"menu"]) {
130 NSMutableDictionary *loginwindow;
131 NSMutableArray *loginarray;
135 [NSArray arrayWithObjects:
148 @"Current Track Info",
149 nil] forKey:@"menu"];
151 [defaults synchronize];
152 loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
153 loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
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]]) {
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]];
167 AECreateDesc(typeChar, [script cString], [script cStringLength],
170 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
172 AEDisposeDesc(&scriptDesc);
173 AEDisposeDesc(&resultDesc);
178 if (![defaults integerForKey:@"SongsInAdvance"])
180 [defaults setInteger:5 forKey:@"SongsInAdvance"];
183 if (![defaults objectForKey:@"showName"]) {
184 [defaults setBool:YES forKey:@"showName"];
187 if (![defaults objectForKey:@"showArtist"]) {
188 [defaults setBool:YES forKey:@"showArtist"];
191 if (![defaults objectForKey:@"showAlbum"]) {
192 [defaults setBool:NO forKey:@"showAlbum"];
195 if (![defaults objectForKey:@"showTime"]) {
196 [defaults setBool:NO forKey:@"showTime"];
200 //Recreate the status item menu
203 NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
207 didHaveAlbumName = ([[self runScriptAndReturnResult:@"return album of current track"] length] > 0);
208 didHaveArtistName = ([[self runScriptAndReturnResult:@"return artist of current track"] length] > 0);
211 while ([menu numberOfItems] > 0) {
212 [menu removeItemAtIndex:0];
215 playPauseMenuItem = nil;
216 upcomingSongsItem = nil;
218 [playlistMenu release];
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:)
231 [playPauseMenuItem setTarget:self];
235 [self setKeyEquivalentForCode:[tempCombo keyCode]
236 andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
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:)
245 [nextTrack setTarget:self];
248 [self setKeyEquivalentForCode:[tempCombo keyCode]
249 andModifiers:[tempCombo modifiers] onItem:nextTrack];
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:)
258 [prevTrack setTarget:self];
261 [self setKeyEquivalentForCode:[tempCombo keyCode]
262 andModifiers:[tempCombo modifiers] onItem:prevTrack];
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"
277 } else if ([item isEqualToString:@"Playlists"]) {
278 playlistItem = [menu addItemWithTitle:@"Playlists"
281 } else if ([item isEqualToString:@"EQ Presets"]) {
282 eqItem = [menu addItemWithTitle:@"EQ Presets"
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"
298 } else if ([item isEqualToString:@"<separator>"]) {
299 [menu addItem:[NSMenuItem separatorItem]];
303 curTrackIndex = -1; //Force update of everything
304 [self timerUpdate]; //Updates dynamic info in the menu
310 //Updates the menu with current player state, song, and upcoming songs
313 NSMenuItem *menuItem;
314 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
316 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
320 if (upcomingSongsItem) {
321 [self rebuildUpcomingSongsMenu];
325 [self rebuildPlaylistMenu];
329 [self rebuildEQPresetsMenu];
332 if (trackInfoIndex > -1)
334 NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
335 curSongName = [self runScriptAndReturnResult:@"return name of current track"];
337 if ([defaults boolForKey:@"showAlbum"]) {
338 curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
341 if ([defaults boolForKey:@"showArtist"]) {
342 curArtistName = [self runScriptAndReturnResult:@"return artist of current track"];
345 if ([curSongName length] > 0) {
346 int index = [menu indexOfItemWithTitle:@"Now Playing"];
348 if ([defaults boolForKey:@"showName"]) {
349 [menu removeItemAtIndex:index + 1];
351 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
352 [menu removeItemAtIndex:index + 1];
354 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
355 [menu removeItemAtIndex:index + 1];
357 if ([defaults boolForKey:@"showTime"]) {
358 [menu removeItemAtIndex:index + 1];
362 if (!isPlayingRadio) {
363 if ([defaults boolForKey:@"showTime"]) {
364 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", [self runScriptAndReturnResult:@"return time of current track"]]
367 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
371 if ([curArtistName length] > 0) {
372 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curArtistName]
375 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
379 if ([curAlbumName length] > 0) {
380 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName]
383 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
388 if ([defaults boolForKey:@"showName"]) {
389 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName]
392 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
397 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
398 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
399 [menu insertItem:menuItem atIndex:trackInfoIndex];
402 } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
403 [menu removeItemAtIndex:trackInfoIndex];
405 if ([defaults boolForKey:@"showName"] == YES) {
406 [menu removeItemAtIndex:trackInfoIndex];
409 if ([defaults boolForKey:@"showTime"] == YES) {
410 [menu removeItemAtIndex:trackInfoIndex];
413 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
414 [menu removeItemAtIndex:trackInfoIndex];
417 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
418 [menu removeItemAtIndex:trackInfoIndex];
421 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
422 [menu insertItem:menuItem atIndex:trackInfoIndex];
426 if ([defaults boolForKey:@"showArtist"]) {
427 didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
430 if ([defaults boolForKey:@"showAlbum"]) {
431 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
436 //Rebuild the upcoming songs submenu. Can be improved a lot.
437 - (void)rebuildUpcomingSongsMenu
439 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
440 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
441 if (!isPlayingRadio) {
443 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
446 [upcomingSongsMenu release];
447 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
448 [upcomingSongsItem setSubmenu:upcomingSongsMenu];
449 [upcomingSongsItem setEnabled:YES];
451 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
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];
466 [upcomingSongsItem setSubmenu:nil];
467 [upcomingSongsItem setEnabled:NO];
471 - (void)rebuildPlaylistMenu
473 int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
474 int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
481 if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
484 [playlistMenu release];
485 playlistMenu = [[NSMenu alloc] initWithTitle:@""];
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];
496 [playlistItem setSubmenu:playlistMenu];
499 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
503 //Build a menu with the list of all available EQ presets
504 - (void)rebuildEQPresetsMenu
506 int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
509 if (eqMenu && (numSets == [eqMenu numberOfItems]))
513 eqMenu = [[NSMenu alloc] initWithTitle:@""];
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];
524 [eqItem setSubmenu:eqMenu];
526 [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
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"];
540 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
542 if ([defaults objectForKey:@"PlayPause"] != nil) {
543 [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
544 combo:[defaults keyComboForKey:@"PlayPause"]
545 target:self action:@selector(playPause:)];
548 if ([defaults objectForKey:@"NextTrack"] != nil) {
549 [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
550 combo:[defaults keyComboForKey:@"NextTrack"]
551 target:self action:@selector(nextSong:)];
554 if ([defaults objectForKey:@"PrevTrack"] != nil) {
555 [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
556 combo:[defaults keyComboForKey:@"PrevTrack"]
557 target:self action:@selector(prevSong:)];
560 if ([defaults objectForKey:@"TrackInfo"] != nil) {
561 [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
562 combo:[defaults keyComboForKey:@"TrackInfo"]
563 target:self action:@selector(showCurrentTrackInfo)];
566 if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
567 [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
568 combo:[defaults keyComboForKey:@"UpcomingSongs"]
569 target:self action:@selector(showUpcomingSongs)];
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
576 AEDesc scriptDesc, resultDesc;
581 script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
583 AECreateDesc(typeChar, [script cString], [script cStringLength],
586 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
588 length = AEGetDescDataSize(&resultDesc);
589 buffer = malloc(length);
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)];
605 //Called when the timer fires.
609 if (GetProcessPID(&iTunesPSN, &pid) == noErr) {
610 int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
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) {
617 for (i = 0; i < [playlistMenu numberOfItems]; i++)
619 [[playlistMenu itemAtIndex:i] setState:NSOffState];
622 if (wasPlayingRadio) {
623 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
624 [menu insertItem:temp atIndex:trackInfoIndex + 1];
628 curTrackIndex = trackPlayingIndex;
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) {
638 for (i = 0; i < [playlistMenu numberOfItems]; i++)
640 [[playlistMenu itemAtIndex:i] setState:NSOffState];
643 if (wasPlayingRadio) {
644 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
645 [menu insertItem:temp atIndex:trackInfoIndex + 1];
649 curTrackIndex = trackPlayingIndex;
650 curPlaylistIndex = playlist;
653 //Update Play/Pause menu item
654 if (playPauseMenuItem){
655 if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"]) {
656 [playPauseMenuItem setTitle:@"Pause"];
658 [playPauseMenuItem setTitle:@"Play"];
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];
669 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
670 [refreshTimer invalidate];
676 - (void)iTunesLaunched:(NSNotification *)note
678 NSDictionary *info = [note userInfo];
680 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
681 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
684 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
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];
691 //Return the PSN of iTunes, if it's running
692 - (ProcessSerialNumber)iTunesPSN
694 ProcessSerialNumber procNum;
695 procNum.highLongOfPSN = kNoProcess;
696 procNum.lowLongOfPSN = 0;
698 while ( (GetNextProcess(&procNum) == noErr) ) {
699 CFStringRef procName;
700 if ( (CopyProcessName(&procNum, &procName) == noErr) ) {
701 if ([(NSString *)procName isEqualToString:@"iTunes"]) {
710 //Send an AppleEvent with a given event ID
711 - (void)sendAEWithEventClass:(AEEventClass)eventClass
712 andEventID:(AEEventID)eventID
714 OSType iTunesType = 'hook';
715 AppleEvent event, reply;
717 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
719 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
720 AEDisposeDesc(&event);
721 AEDisposeDesc(&reply);
725 // Selectors - called from status item menu
728 - (void)playTrack:(id)sender
730 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
734 - (void)selectPlaylist:(id)sender
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];
741 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
742 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
745 - (void)selectEQPreset:(id)sender
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];
755 - (void)playPause:(id)sender
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'];
766 [self sendAEWithEventClass:'hook' andEventID:'Play'];
767 [playPauseMenuItem setTitle:@"Pause"];
771 - (void)nextSong:(id)sender
773 [self sendAEWithEventClass:'hook' andEventID:'Next'];
776 - (void)prevSong:(id)sender
778 [self sendAEWithEventClass:'hook' andEventID:'Prev'];
781 - (void)fastForward:(id)sender
783 [self sendAEWithEventClass:'hook' andEventID:'Fast'];
786 - (void)rewind:(id)sender
788 [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
791 - (void)quitMenuTunes:(id)sender
793 [NSApp terminate:self];
796 - (void)openiTunes:(id)sender
798 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
801 - (void)showPreferences:(id)sender
803 if (!prefsController) {
804 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
810 - (void)closePreferences
812 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
815 [prefsController release];
816 prefsController = nil;
821 // Show Current Track Info And Show Upcoming Songs Floaters
825 - (void)showCurrentTrackInfo
827 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
828 if (!statusController && [trackName length]) {
829 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
830 NSString *stringToShow = @"";
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];
837 stringToShow = [stringToShow stringByAppendingString:trackName];
838 stringToShow = [stringToShow stringByAppendingString:@"\n"];
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"];
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];
857 int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
858 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
860 stringToShow = [stringToShow stringByAppendingString:
861 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
863 stringToShow = [stringToShow stringByAppendingString:
864 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
868 statusController = [[StatusWindowController alloc] init];
869 [statusController setTrackInfo:stringToShow];
870 [NSTimer scheduledTimerWithTimeInterval:3.0
872 selector:@selector(fadeAndCloseStatusWindow)
878 - (void)showUpcomingSongs
880 if (!statusController) {
881 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
884 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
885 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
887 NSString *songs = @"";
889 statusController = [[StatusWindowController alloc] init];
890 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
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"];
898 [statusController setUpcomingSongs:songs];
899 [NSTimer scheduledTimerWithTimeInterval:3.0
901 selector:@selector(fadeAndCloseStatusWindow)
908 - (void)fadeAndCloseStatusWindow
910 [statusController fadeWindowOut];
911 [statusController release];
912 statusController = nil;
915 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
916 onItem:(NSMenuItem *)item
918 unichar charcode = 'a';
920 long cocoaModifiers = 0;
921 static long carbonToCocoa[6][2] =
923 { cmdKey, NSCommandKeyMask },
924 { optionKey, NSAlternateKeyMask },
925 { controlKey, NSControlKeyMask },
926 { shiftKey, NSShiftKeyMask },
929 for (i = 0; i < 6; i++)
931 if (modifiers & carbonToCocoa[i][0])
933 cocoaModifiers += carbonToCocoa[i][1];
936 [item setKeyEquivalentModifierMask:cocoaModifiers];
938 //Missing key combos for some keys. Must find them later.
951 charcode = NSDeleteFunctionKey;
963 charcode = NSF5FunctionKey;
967 charcode = NSF6FunctionKey;
971 charcode = NSF7FunctionKey;
975 charcode = NSF3FunctionKey;
979 charcode = NSF8FunctionKey;
983 charcode = NSF9FunctionKey;
987 charcode = NSF11FunctionKey;
991 charcode = NSF3FunctionKey;
995 charcode = NSF14FunctionKey;
999 charcode = NSF10FunctionKey;
1003 charcode = NSF12FunctionKey;
1007 charcode = NSF13FunctionKey;
1011 charcode = NSInsertFunctionKey;
1018 charcode = NSPageUpFunctionKey;
1022 charcode = NSDeleteFunctionKey;
1026 charcode = NSF4FunctionKey;
1030 charcode = NSEndFunctionKey;
1034 charcode = NSF2FunctionKey;
1038 charcode = NSPageDownFunctionKey;
1042 charcode = NSF1FunctionKey;
1046 charcode = NSLeftArrowFunctionKey;
1050 charcode = NSRightArrowFunctionKey;
1054 charcode = NSDownArrowFunctionKey;
1058 charcode = NSUpArrowFunctionKey;
1062 if (charcode == 'a') {
1063 unsigned long state;
1068 kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1069 keyTrans = KeyTranslate(kchr, code, &state);
1070 charCode = keyTrans;
1071 [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1073 [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1077 /*************************************************************************/
1079 #pragma mark NSApplication DELEGATE METHODS
1080 /*************************************************************************/
1082 - (void)applicationWillTerminate:(NSNotification *)note
1084 [self clearHotKeys];
1085 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1089 /*************************************************************************/
1091 #pragma mark DEALLOCATION METHODS
1092 /*************************************************************************/
1097 [refreshTimer invalidate];
1100 CloseComponent(asComponent);
1101 [statusItem release];