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)
64 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
68 menu = [[NSMenu alloc] initWithTitle:@""];
69 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
70 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
71 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
72 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
76 statusItem = [[ITStatusItem alloc] initWithStatusBar:[NSStatusBar systemStatusBar]
77 withLength:NSSquareStatusItemLength];
79 [statusItem setImage:[NSImage imageNamed:@"menu"]];
80 [statusItem setAlternateImage:[NSImage imageNamed:@"selected_image"]];
81 [statusItem setMenu:menu];
82 // Below line of code is for creating builds for Beta Testers
83 // [statusItem setToolTip:@[NSString stringWithFormat:@"This Nontransferable Beta (Built on %s) of iThink Software's MenuTunes is Registered to: Beta Tester (betatester@somedomain.com).",__DATE__]];
86 - (ITMTRemote *)loadRemote
88 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
91 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
92 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
95 while ( (bundlePath = [enumerator nextObject]) ) {
96 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
99 Class remoteClass = [remoteBundle principalClass];
101 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
102 [remoteClass isKindOfClass:[NSObject class]]) {
104 id remote = [remoteClass remote];
105 [remoteArray addObject:remote];
110 // if ( [remoteArray count] > 0 ) {
111 // if ( [remoteArray count] > 1 ) {
112 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
114 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
117 NSLog(@"%@", [remoteArray objectAtIndex:0]);
118 return [remoteArray objectAtIndex:0];
122 /*************************************************************************/
124 #pragma mark INSTANCE METHODS
125 /*************************************************************************/
127 - (void)registerDefaultsIfNeeded
129 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
130 if (![defaults objectForKey:@"menu"]) {
132 NSMutableDictionary *loginwindow;
133 NSMutableArray *loginarray;
137 [NSArray arrayWithObjects:
150 @"Current Track Info",
151 nil] forKey:@"menu"];
153 [defaults synchronize];
154 loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
155 loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
157 for (i = 0; i < [loginarray count]; i++) {
158 NSDictionary *tempDict = [loginarray objectAtIndex:i];
159 if ([[[tempDict objectForKey:@"Path"] lastPathComponent] isEqualToString:[[[NSBundle mainBundle] bundlePath] lastPathComponent]]) {
165 if (NSRunInformationalAlertPanel(@"Auto-launch MenuTunes", @"Would you like MenuTunes to automatically launch at login?", @"Yes", @"No", nil) == NSOKButton) {
166 AEDesc scriptDesc, resultDesc;
167 NSString *script = [NSString stringWithFormat:@"tell application \"System Events\"\nmake new login item at end of login items with properties {path:\"%@\", kind:\"APPLICATION\"}\nend tell", [[NSBundle mainBundle] bundlePath]];
169 AECreateDesc(typeChar, [script cString], [script cStringLength],
172 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
174 AEDisposeDesc(&scriptDesc);
175 AEDisposeDesc(&resultDesc);
180 if (![defaults integerForKey:@"SongsInAdvance"])
182 [defaults setInteger:5 forKey:@"SongsInAdvance"];
185 if (![defaults objectForKey:@"showName"]) {
186 [defaults setBool:YES forKey:@"showName"];
189 if (![defaults objectForKey:@"showArtist"]) {
190 [defaults setBool:YES forKey:@"showArtist"];
193 if (![defaults objectForKey:@"showAlbum"]) {
194 [defaults setBool:NO forKey:@"showAlbum"];
197 if (![defaults objectForKey:@"showTime"]) {
198 [defaults setBool:NO forKey:@"showTime"];
202 //Recreate the status item menu
205 NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
209 didHaveAlbumName = ([[self runScriptAndReturnResult:@"return album of current track"] length] > 0);
210 didHaveArtistName = ([[self runScriptAndReturnResult:@"return artist of current track"] length] > 0);
213 while ([menu numberOfItems] > 0) {
214 [menu removeItemAtIndex:0];
217 playPauseMenuItem = nil;
218 upcomingSongsItem = nil;
220 [playlistMenu release];
226 for (i = 0; i < [myMenu count]; i++) {
227 NSString *item = [myMenu objectAtIndex:i];
228 if ([item isEqualToString:@"Play/Pause"]) {
229 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PlayPause"];
230 playPauseMenuItem = [menu addItemWithTitle:@"Play"
231 action:@selector(playPause:)
233 [playPauseMenuItem setTarget:self];
237 [self setKeyEquivalentForCode:[tempCombo keyCode]
238 andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
241 } else if ([item isEqualToString:@"Next Track"]) {
242 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"NextTrack"];
243 NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
244 action:@selector(nextSong:)
247 [nextTrack setTarget:self];
250 [self setKeyEquivalentForCode:[tempCombo keyCode]
251 andModifiers:[tempCombo modifiers] onItem:nextTrack];
254 } else if ([item isEqualToString:@"Previous Track"]) {
255 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PrevTrack"];
256 NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
257 action:@selector(prevSong:)
260 [prevTrack setTarget:self];
263 [self setKeyEquivalentForCode:[tempCombo keyCode]
264 andModifiers:[tempCombo modifiers] onItem:prevTrack];
267 } else if ([item isEqualToString:@"Fast Forward"]) {
268 [[menu addItemWithTitle:@"Fast Forward"
269 action:@selector(fastForward:)
270 keyEquivalent:@""] setTarget:self];
271 } else if ([item isEqualToString:@"Rewind"]) {
272 [[menu addItemWithTitle:@"Rewind"
273 action:@selector(rewind:)
274 keyEquivalent:@""] setTarget:self];
275 } else if ([item isEqualToString:@"Upcoming Songs"]) {
276 upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
279 } else if ([item isEqualToString:@"Playlists"]) {
280 playlistItem = [menu addItemWithTitle:@"Playlists"
283 } else if ([item isEqualToString:@"EQ Presets"]) {
284 eqItem = [menu addItemWithTitle:@"EQ Presets"
287 } else if ([item isEqualToString:@"PreferencesÉ"]) {
288 [[menu addItemWithTitle:@"PreferencesÉ"
289 action:@selector(showPreferences:)
290 keyEquivalent:@""] setTarget:self];
291 } else if ([item isEqualToString:@"Quit"]) {
292 [[menu addItemWithTitle:@"Quit"
293 action:@selector(quitMenuTunes:)
294 keyEquivalent:@""] setTarget:self];
295 } else if ([item isEqualToString:@"Current Track Info"]) {
296 trackInfoIndex = [menu numberOfItems];
297 [menu addItemWithTitle:@"No Song"
300 } else if ([item isEqualToString:@"<separator>"]) {
301 [menu addItem:[NSMenuItem separatorItem]];
305 curTrackIndex = -1; //Force update of everything
306 [self timerUpdate]; //Updates dynamic info in the menu
312 //Updates the menu with current player state, song, and upcoming songs
315 NSMenuItem *menuItem;
316 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
318 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
322 if (upcomingSongsItem) {
323 [self rebuildUpcomingSongsMenu];
327 [self rebuildPlaylistMenu];
331 [self rebuildEQPresetsMenu];
334 if (trackInfoIndex > -1)
336 NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
337 curSongName = [self runScriptAndReturnResult:@"return name of current track"];
339 if ([defaults boolForKey:@"showAlbum"]) {
340 curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
343 if ([defaults boolForKey:@"showArtist"]) {
344 curArtistName = [self runScriptAndReturnResult:@"return artist of current track"];
347 if ([curSongName length] > 0) {
348 int index = [menu indexOfItemWithTitle:@"Now Playing"];
350 if ([defaults boolForKey:@"showName"]) {
351 [menu removeItemAtIndex:index + 1];
353 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
354 [menu removeItemAtIndex:index + 1];
356 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
357 [menu removeItemAtIndex:index + 1];
359 if ([defaults boolForKey:@"showTime"]) {
360 [menu removeItemAtIndex:index + 1];
364 if (!isPlayingRadio) {
365 if ([defaults boolForKey:@"showTime"]) {
366 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", [self runScriptAndReturnResult:@"return time of current track"]]
369 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
373 if ([curArtistName length] > 0) {
374 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curArtistName]
377 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
381 if ([curAlbumName length] > 0) {
382 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName]
385 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
390 if ([defaults boolForKey:@"showName"]) {
391 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName]
394 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
399 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
400 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
401 [menu insertItem:menuItem atIndex:trackInfoIndex];
404 } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
405 [menu removeItemAtIndex:trackInfoIndex];
407 if ([defaults boolForKey:@"showName"] == YES) {
408 [menu removeItemAtIndex:trackInfoIndex];
411 if ([defaults boolForKey:@"showTime"] == YES) {
412 [menu removeItemAtIndex:trackInfoIndex];
415 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
416 [menu removeItemAtIndex:trackInfoIndex];
419 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
420 [menu removeItemAtIndex:trackInfoIndex];
423 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
424 [menu insertItem:menuItem atIndex:trackInfoIndex];
428 if ([defaults boolForKey:@"showArtist"]) {
429 didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
432 if ([defaults boolForKey:@"showAlbum"]) {
433 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
438 //Rebuild the upcoming songs submenu. Can be improved a lot.
439 - (void)rebuildUpcomingSongsMenu
441 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
442 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
443 if (!isPlayingRadio) {
445 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
448 [upcomingSongsMenu release];
449 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
450 [upcomingSongsItem setSubmenu:upcomingSongsMenu];
451 [upcomingSongsItem setEnabled:YES];
453 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
455 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
456 NSMenuItem *songItem;
457 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
458 [songItem setTarget:self];
459 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
460 [upcomingSongsMenu addItem:songItem];
468 [upcomingSongsItem setSubmenu:nil];
469 [upcomingSongsItem setEnabled:NO];
473 - (void)rebuildPlaylistMenu
475 int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
476 int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
483 if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
486 [playlistMenu release];
487 playlistMenu = [[NSMenu alloc] initWithTitle:@""];
489 for (i = 1; i <= numPlaylists; i++) {
490 NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
491 NSMenuItem *tempItem;
492 tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
493 [tempItem setTarget:self];
494 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
495 [playlistMenu addItem:tempItem];
498 [playlistItem setSubmenu:playlistMenu];
501 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
505 //Build a menu with the list of all available EQ presets
506 - (void)rebuildEQPresetsMenu
508 int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
511 if (eqMenu && (numSets == [eqMenu numberOfItems]))
515 eqMenu = [[NSMenu alloc] initWithTitle:@""];
517 for (i = 1; i <= numSets; i++) {
518 NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
519 NSMenuItem *tempItem;
520 tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
521 [tempItem setTarget:self];
522 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
523 [eqMenu addItem:tempItem];
526 [eqItem setSubmenu:eqMenu];
528 [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
533 [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
534 [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
535 [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
536 [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
537 [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
542 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
544 if ([defaults objectForKey:@"PlayPause"] != nil) {
545 [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
546 combo:[defaults keyComboForKey:@"PlayPause"]
547 target:self action:@selector(playPause:)];
550 if ([defaults objectForKey:@"NextTrack"] != nil) {
551 [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
552 combo:[defaults keyComboForKey:@"NextTrack"]
553 target:self action:@selector(nextSong:)];
556 if ([defaults objectForKey:@"PrevTrack"] != nil) {
557 [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
558 combo:[defaults keyComboForKey:@"PrevTrack"]
559 target:self action:@selector(prevSong:)];
562 if ([defaults objectForKey:@"TrackInfo"] != nil) {
563 [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
564 combo:[defaults keyComboForKey:@"TrackInfo"]
565 target:self action:@selector(showCurrentTrackInfo)];
568 if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
569 [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
570 combo:[defaults keyComboForKey:@"UpcomingSongs"]
571 target:self action:@selector(showUpcomingSongs)];
575 //Runs an AppleScript and returns the result as an NSString after stripping quotes, if needed. It takes in script and automatically adds the tell iTunes and end tell statements.
576 - (NSString *)runScriptAndReturnResult:(NSString *)script
578 AEDesc scriptDesc, resultDesc;
583 script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
585 AECreateDesc(typeChar, [script cString], [script cStringLength],
588 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
590 length = AEGetDescDataSize(&resultDesc);
591 buffer = malloc(length);
593 AEGetDescData(&resultDesc, buffer, length);
594 AEDisposeDesc(&scriptDesc);
595 AEDisposeDesc(&resultDesc);
596 result = [NSString stringWithCString:buffer length:length];
597 if ( (! [result isEqualToString:@""]) &&
598 ([result characterAtIndex:0] == '\"') &&
599 ([result characterAtIndex:[result length] - 1] == '\"') ) {
600 result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
607 //Called when the timer fires.
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 - (void)iTunesLaunched:(NSNotification *)note
665 NSDictionary *info = [note userInfo];
667 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
668 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
671 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
673 [self rebuildMenu]; //Rebuild the menu since no songs will be playing
674 [statusItem setMenu:menu]; //Set the menu back to the main one
675 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
677 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
680 - (void)iTunesTerminated:(NSNotification *)note
682 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
685 menu = [[NSMenu alloc] initWithTitle:@""];
686 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
687 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
688 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
689 [statusItem setMenu:menu];
691 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
692 [refreshTimer invalidate];
697 //Return the PSN of iTunes, if it's running
698 - (ProcessSerialNumber)iTunesPSN
700 NSArray *apps = [[NSWorkspace sharedWorkspace] launchedApplications];
701 ProcessSerialNumber number;
704 number.highLongOfPSN = kNoProcess;
706 for (i = 0; i < [apps count]; i++)
708 NSDictionary *curApp = [apps objectAtIndex:i];
710 if ([[curApp objectForKey:@"NSApplicationName"] isEqualToString:@"iTunes"])
712 number.highLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
713 number.lowLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
719 //Send an AppleEvent with a given event ID
720 - (void)sendAEWithEventClass:(AEEventClass)eventClass
721 andEventID:(AEEventID)eventID
723 OSType iTunesType = 'hook';
724 AppleEvent event, reply;
726 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
728 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
729 AEDisposeDesc(&event);
730 AEDisposeDesc(&reply);
735 // Selectors - called from status item menu
739 // Plugin dependent selectors
741 - (void)playTrack:(id)sender
743 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
747 - (void)selectPlaylist:(id)sender
749 int playlist = [[sender representedObject] intValue];
750 if (!isPlayingRadio) {
751 int curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
752 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
754 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
755 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
758 - (void)selectEQPreset:(id)sender
760 int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
761 int item = [[sender representedObject] intValue];
762 [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
763 [self runScriptAndReturnResult:@"set EQ enabled to 1"];
764 [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
765 [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
768 - (void)playPause:(id)sender
771 NSString *state = [self runScriptAndReturnResult:@"return player state"];
772 if ([state isEqualToString:@"playing"]) {
773 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
774 [playPauseMenuItem setTitle:@"Play"];
775 } else if ([state isEqualToString:@"fast forwarding"] || [state
776 isEqualToString:@"rewinding"]) {
777 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
778 [self sendAEWithEventClass:'hook' andEventID:'Play'];
780 [self sendAEWithEventClass:'hook' andEventID:'Play'];
781 [playPauseMenuItem setTitle:@"Pause"];
785 - (void)nextSong:(id)sender
787 [currentRemote goToNextSong];
790 - (void)prevSong:(id)sender
792 [currentRemote goToPreviousSong];
795 - (void)fastForward:(id)sender
797 [self sendAEWithEventClass:'hook' andEventID:'Fast'];
800 - (void)rewind:(id)sender
802 [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
805 // Plugin independent selectors
807 - (void)quitMenuTunes:(id)sender
809 [NSApp terminate:self];
812 - (void)openiTunes:(id)sender
814 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
817 - (void)showPreferences:(id)sender
819 if (!prefsController) {
820 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
826 - (void)closePreferences
828 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
831 [prefsController release];
832 prefsController = nil;
837 // Show Current Track Info And Show Upcoming Songs Floaters
841 - (void)showCurrentTrackInfo
843 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
844 if (!statusController && [trackName length]) {
845 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
846 NSString *stringToShow = @"";
848 if ([defaults boolForKey:@"showName"]) {
849 if ([defaults boolForKey:@"showArtist"]) {
850 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
851 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
853 stringToShow = [stringToShow stringByAppendingString:trackName];
854 stringToShow = [stringToShow stringByAppendingString:@"\n"];
857 if ([defaults boolForKey:@"showAlbum"]) {
858 NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
859 if ([trackAlbum length]) {
860 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
861 stringToShow = [stringToShow stringByAppendingString:@"\n"];
865 if ([defaults boolForKey:@"showTime"]) {
866 NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
867 if ([trackTime length]) {
868 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
873 int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
874 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
876 stringToShow = [stringToShow stringByAppendingString:
877 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
879 stringToShow = [stringToShow stringByAppendingString:
880 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
884 statusController = [[StatusWindowController alloc] init];
885 [statusController setTrackInfo:stringToShow];
886 [NSTimer scheduledTimerWithTimeInterval:3.0
888 selector:@selector(fadeAndCloseStatusWindow)
894 - (void)showUpcomingSongs
896 if (!statusController) {
897 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
900 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
901 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
903 NSString *songs = @"";
905 statusController = [[StatusWindowController alloc] init];
906 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
908 NSString *curSong = [self runScriptAndReturnResult:
909 [NSString stringWithFormat:@"return name of track %i of current playlist", i]];
910 songs = [songs stringByAppendingString:curSong];
911 songs = [songs stringByAppendingString:@"\n"];
914 [statusController setUpcomingSongs:songs];
915 [NSTimer scheduledTimerWithTimeInterval:3.0
917 selector:@selector(fadeAndCloseStatusWindow)
924 - (void)fadeAndCloseStatusWindow
926 [statusController fadeWindowOut];
927 [statusController release];
928 statusController = nil;
931 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
932 onItem:(NSMenuItem *)item
934 unichar charcode = 'a';
936 long cocoaModifiers = 0;
937 static long carbonToCocoa[6][2] =
939 { cmdKey, NSCommandKeyMask },
940 { optionKey, NSAlternateKeyMask },
941 { controlKey, NSControlKeyMask },
942 { shiftKey, NSShiftKeyMask },
945 for (i = 0; i < 6; i++)
947 if (modifiers & carbonToCocoa[i][0])
949 cocoaModifiers += carbonToCocoa[i][1];
952 [item setKeyEquivalentModifierMask:cocoaModifiers];
954 //Missing key combos for some keys. Must find them later.
967 charcode = NSDeleteFunctionKey;
979 charcode = NSF5FunctionKey;
983 charcode = NSF6FunctionKey;
987 charcode = NSF7FunctionKey;
991 charcode = NSF3FunctionKey;
995 charcode = NSF8FunctionKey;
999 charcode = NSF9FunctionKey;
1003 charcode = NSF11FunctionKey;
1007 charcode = NSF3FunctionKey;
1011 charcode = NSF14FunctionKey;
1015 charcode = NSF10FunctionKey;
1019 charcode = NSF12FunctionKey;
1023 charcode = NSF13FunctionKey;
1027 charcode = NSInsertFunctionKey;
1034 charcode = NSPageUpFunctionKey;
1038 charcode = NSDeleteFunctionKey;
1042 charcode = NSF4FunctionKey;
1046 charcode = NSEndFunctionKey;
1050 charcode = NSF2FunctionKey;
1054 charcode = NSPageDownFunctionKey;
1058 charcode = NSF1FunctionKey;
1062 charcode = NSLeftArrowFunctionKey;
1066 charcode = NSRightArrowFunctionKey;
1070 charcode = NSDownArrowFunctionKey;
1074 charcode = NSUpArrowFunctionKey;
1078 if (charcode == 'a') {
1079 unsigned long state;
1084 kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1085 keyTrans = KeyTranslate(kchr, code, &state);
1086 charCode = keyTrans;
1087 [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1089 [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1093 /*************************************************************************/
1095 #pragma mark NSApplication DELEGATE METHODS
1096 /*************************************************************************/
1098 - (void)applicationWillTerminate:(NSNotification *)note
1100 [self clearHotKeys];
1101 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1105 /*************************************************************************/
1107 #pragma mark DEALLOCATION METHODS
1108 /*************************************************************************/
1113 [refreshTimer invalidate];
1116 CloseComponent(asComponent);
1117 [statusItem release];