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 [currentRemote begin];
50 asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
52 [self registerDefaultsIfNeeded];
54 menu = [[NSMenu alloc] initWithTitle:@""];
55 iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
57 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
60 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
62 selector:@selector(timerUpdate)
66 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
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];
78 statusItem = [[ITStatusItem alloc] initWithStatusBar:[NSStatusBar systemStatusBar]
79 withLength:NSSquareStatusItemLength];
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__]];
88 - (ITMTRemote *)loadRemote
90 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
93 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
94 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
97 while ( (bundlePath = [enumerator nextObject]) ) {
98 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
101 Class remoteClass = [remoteBundle principalClass];
103 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
104 [remoteClass isKindOfClass:[NSObject class]]) {
106 id remote = [remoteClass remote];
107 [remoteArray addObject:remote];
112 // if ( [remoteArray count] > 0 ) {
113 // if ( [remoteArray count] > 1 ) {
114 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
116 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
119 NSLog(@"%@", [remoteArray objectAtIndex:0]);
120 return [remoteArray objectAtIndex:0];
124 /*************************************************************************/
126 #pragma mark INSTANCE METHODS
127 /*************************************************************************/
129 - (void)registerDefaultsIfNeeded
131 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
132 if (![defaults objectForKey:@"menu"]) {
134 NSMutableDictionary *loginwindow;
135 NSMutableArray *loginarray;
139 [NSArray arrayWithObjects:
152 @"Current Track Info",
153 nil] forKey:@"menu"];
155 [defaults synchronize];
156 loginwindow = [[defaults persistentDomainForName:@"loginwindow"] mutableCopy];
157 loginarray = [loginwindow objectForKey:@"AutoLaunchedApplicationDictionary"];
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]]) {
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]];
171 AECreateDesc(typeChar, [script cString], [script cStringLength],
174 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
176 AEDisposeDesc(&scriptDesc);
177 AEDisposeDesc(&resultDesc);
182 if (![defaults integerForKey:@"SongsInAdvance"])
184 [defaults setInteger:5 forKey:@"SongsInAdvance"];
187 if (![defaults objectForKey:@"showName"]) {
188 [defaults setBool:YES forKey:@"showName"];
191 if (![defaults objectForKey:@"showArtist"]) {
192 [defaults setBool:YES forKey:@"showArtist"];
195 if (![defaults objectForKey:@"showAlbum"]) {
196 [defaults setBool:NO forKey:@"showAlbum"];
199 if (![defaults objectForKey:@"showTime"]) {
200 [defaults setBool:NO forKey:@"showTime"];
204 //Recreate the status item menu
207 NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
212 didHaveAlbumName = ([[self runScriptAndReturnResult:@"return album of current track"] length] > 0);
213 didHaveArtistName = ([[self runScriptAndReturnResult:@"return artist of current track"] length] > 0);
216 while ([menu numberOfItems] > 0) {
217 [menu removeItemAtIndex:0];
220 playPauseMenuItem = nil;
221 upcomingSongsItem = nil;
223 [playlistMenu release];
229 for (i = 0; i < [myMenu count]; i++) {
230 NSString *item = [myMenu objectAtIndex:i];
231 if ([item isEqualToString:@"Play/Pause"]) {
232 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PlayPause"];
233 playPauseMenuItem = [menu addItemWithTitle:@"Play"
234 action:@selector(playPause:)
236 [playPauseMenuItem setTarget:self];
240 [self setKeyEquivalentForCode:[tempCombo keyCode]
241 andModifiers:[tempCombo modifiers] onItem:playPauseMenuItem];
244 } else if ([item isEqualToString:@"Next Track"]) {
245 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"NextTrack"];
246 NSMenuItem *nextTrack = [menu addItemWithTitle:@"Next Track"
247 action:@selector(nextSong:)
250 [nextTrack setTarget:self];
253 [self setKeyEquivalentForCode:[tempCombo keyCode]
254 andModifiers:[tempCombo modifiers] onItem:nextTrack];
257 } else if ([item isEqualToString:@"Previous Track"]) {
258 KeyCombo *tempCombo = [[NSUserDefaults standardUserDefaults] keyComboForKey:@"PrevTrack"];
259 NSMenuItem *prevTrack = [menu addItemWithTitle:@"Previous Track"
260 action:@selector(prevSong:)
263 [prevTrack setTarget:self];
266 [self setKeyEquivalentForCode:[tempCombo keyCode]
267 andModifiers:[tempCombo modifiers] onItem:prevTrack];
270 } else if ([item isEqualToString:@"Fast Forward"]) {
271 [[menu addItemWithTitle:@"Fast Forward"
272 action:@selector(fastForward:)
273 keyEquivalent:@""] setTarget:self];
274 } else if ([item isEqualToString:@"Rewind"]) {
275 [[menu addItemWithTitle:@"Rewind"
276 action:@selector(rewind:)
277 keyEquivalent:@""] setTarget:self];
278 } else if ([item isEqualToString:@"Upcoming Songs"]) {
279 upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs"
282 } else if ([item isEqualToString:@"Playlists"]) {
283 playlistItem = [menu addItemWithTitle:@"Playlists"
286 } else if ([item isEqualToString:@"EQ Presets"]) {
287 eqItem = [menu addItemWithTitle:@"EQ Presets"
290 } else if ([item isEqualToString:@"PreferencesÉ"]) {
291 [[menu addItemWithTitle:@"PreferencesÉ"
292 action:@selector(showPreferences:)
293 keyEquivalent:@""] setTarget:self];
294 } else if ([item isEqualToString:@"Quit"]) {
295 [[menu addItemWithTitle:@"Quit"
296 action:@selector(quitMenuTunes:)
297 keyEquivalent:@""] setTarget:self];
298 } else if ([item isEqualToString:@"Current Track Info"]) {
299 trackInfoIndex = [menu numberOfItems];
300 [menu addItemWithTitle:@"No Song"
303 } else if ([item isEqualToString:@"<separator>"]) {
304 [menu addItem:[NSMenuItem separatorItem]];
308 [self timerUpdate]; //Updates dynamic info in the menu
314 //Updates the menu with current player state, song, and upcoming songs
317 NSMenuItem *menuItem;
318 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
320 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)) {
324 if (upcomingSongsItem) {
325 [self rebuildUpcomingSongsMenu];
329 [self rebuildPlaylistMenu];
333 [self rebuildEQPresetsMenu];
336 if (trackInfoIndex > -1)
338 NSString *curSongName, *curAlbumName = @"", *curArtistName = @"";
339 curSongName = [currentRemote currentSongTitle];
341 if ([defaults boolForKey:@"showAlbum"]) {
342 curAlbumName = [currentRemote currentSongAlbum];
345 if ([defaults boolForKey:@"showArtist"]) {
346 curArtistName = [currentRemote currentSongArtist];
349 if ([curSongName length] > 0) {
350 int index = [menu indexOfItemWithTitle:@"Now Playing"];
352 if ([defaults boolForKey:@"showName"]) {
353 [menu removeItemAtIndex:index + 1];
355 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
356 [menu removeItemAtIndex:index + 1];
358 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
359 [menu removeItemAtIndex:index + 1];
361 if ([defaults boolForKey:@"showTime"]) {
362 [menu removeItemAtIndex:index + 1];
366 if (!isPlayingRadio) {
367 if ([defaults boolForKey:@"showTime"]) {
368 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", [self runScriptAndReturnResult:@"return time of current track"]]
371 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
375 if ([curArtistName length] > 0) {
376 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curArtistName]
379 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
383 if ([curAlbumName length] > 0) {
384 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName]
387 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
392 if ([defaults boolForKey:@"showName"]) {
393 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName]
396 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
401 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:nil keyEquivalent:@""];
402 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
403 [menu insertItem:menuItem atIndex:trackInfoIndex];
406 } else if ([menu indexOfItemWithTitle:@"No Song"] == -1) {
407 [menu removeItemAtIndex:trackInfoIndex];
409 if ([defaults boolForKey:@"showName"] == YES) {
410 [menu removeItemAtIndex:trackInfoIndex];
413 if ([defaults boolForKey:@"showTime"] == YES) {
414 [menu removeItemAtIndex:trackInfoIndex];
417 if (didHaveArtistName && [defaults boolForKey:@"showArtist"]) {
418 [menu removeItemAtIndex:trackInfoIndex];
421 if (didHaveAlbumName && [defaults boolForKey:@"showAlbum"]) {
422 [menu removeItemAtIndex:trackInfoIndex];
425 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:nil keyEquivalent:@""];
426 [menu insertItem:menuItem atIndex:trackInfoIndex];
430 if ([defaults boolForKey:@"showArtist"]) {
431 didHaveArtistName = (([curArtistName length] > 0) ? YES : NO);
434 if ([defaults boolForKey:@"showAlbum"]) {
435 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
440 //Rebuild the upcoming songs submenu. Can be improved a lot.
441 - (void)rebuildUpcomingSongsMenu
443 int curIndex = [currentRemote currentPlaylistIndex];
444 int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curIndex];
445 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
446 if (!isPlayingRadio) {
448 int curTrack = [currentRemote currentSongIndex];
451 [upcomingSongsMenu release];
452 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
453 [upcomingSongsItem setSubmenu:upcomingSongsMenu];
454 [upcomingSongsItem setEnabled:YES];
456 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
458 NSString *curSong = [currentRemote songTitleAtIndex:i];
459 NSMenuItem *songItem;
460 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
461 [songItem setTarget:self];
462 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
463 [upcomingSongsMenu addItem:songItem];
471 [upcomingSongsItem setSubmenu:nil];
472 [upcomingSongsItem setEnabled:NO];
476 - (void)rebuildPlaylistMenu
478 NSArray *playlists = [currentRemote playlists];
479 int i, curPlaylist = [currentRemote currentPlaylistIndex];
486 if (playlistMenu && ([playlists count] == [playlistMenu numberOfItems]))
489 [playlistMenu release];
490 playlistMenu = [[NSMenu alloc] initWithTitle:@""];
492 for (i = 1; i < [playlists count]; i++) {
493 NSString *playlistName = [playlists objectAtIndex:i];
494 NSMenuItem *tempItem;
495 tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
496 [tempItem setTarget:self];
497 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
498 [playlistMenu addItem:tempItem];
501 [playlistItem setSubmenu:playlistMenu];
504 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
508 //Build a menu with the list of all available EQ presets
509 - (void)rebuildEQPresetsMenu
511 NSArray *eqPresets = [currentRemote eqPresets];
514 if (eqMenu && ([[currentRemote eqPresets] count] == [eqMenu numberOfItems]))
518 eqMenu = [[NSMenu alloc] initWithTitle:@""];
520 for (i = 0; i < [eqPresets count]; i++) {
521 NSString *setName = [eqPresets objectAtIndex:i];
522 NSMenuItem *tempItem;
523 tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
524 [tempItem setTarget:self];
525 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
526 [eqMenu addItem:tempItem];
529 [eqItem setSubmenu:eqMenu];
531 [[eqMenu itemAtIndex:[currentRemote currentEQPresetIndex] - 1] setState:NSOnState];
536 [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
537 [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
538 [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
539 [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
540 [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
545 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
547 if ([defaults objectForKey:@"PlayPause"] != nil) {
548 [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
549 combo:[defaults keyComboForKey:@"PlayPause"]
550 target:self action:@selector(playPause:)];
553 if ([defaults objectForKey:@"NextTrack"] != nil) {
554 [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
555 combo:[defaults keyComboForKey:@"NextTrack"]
556 target:self action:@selector(nextSong:)];
559 if ([defaults objectForKey:@"PrevTrack"] != nil) {
560 [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
561 combo:[defaults keyComboForKey:@"PrevTrack"]
562 target:self action:@selector(prevSong:)];
565 if ([defaults objectForKey:@"TrackInfo"] != nil) {
566 [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
567 combo:[defaults keyComboForKey:@"TrackInfo"]
568 target:self action:@selector(showCurrentTrackInfo)];
571 if ([defaults objectForKey:@"UpcomingSongs"] != nil) {
572 [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
573 combo:[defaults keyComboForKey:@"UpcomingSongs"]
574 target:self action:@selector(showUpcomingSongs)];
578 //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.
579 - (NSString *)runScriptAndReturnResult:(NSString *)script
581 AEDesc scriptDesc, resultDesc;
586 script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
588 AECreateDesc(typeChar, [script cString], [script cStringLength],
591 OSADoScript(asComponent, &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
593 length = AEGetDescDataSize(&resultDesc);
594 buffer = malloc(length);
596 AEGetDescData(&resultDesc, buffer, length);
597 AEDisposeDesc(&scriptDesc);
598 AEDisposeDesc(&resultDesc);
599 result = [NSString stringWithCString:buffer length:length];
600 if ( (! [result isEqualToString:@""]) &&
601 ([result characterAtIndex:0] == '\"') &&
602 ([result characterAtIndex:[result length] - 1] == '\"') ) {
603 result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
610 //Called when the timer fires.
613 int trackPlayingIndex = [currentRemote currentSongIndex];
614 int playlist = [currentRemote currentPlaylistIndex];
616 if (trackPlayingIndex != lastSongIndex) {
617 bool wasPlayingRadio = isPlayingRadio;
618 isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
619 if (isPlayingRadio && !wasPlayingRadio) {
621 for (i = 0; i < [playlistMenu numberOfItems]; i++)
623 [[playlistMenu itemAtIndex:i] setState:NSOffState];
626 if (wasPlayingRadio) {
627 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
628 [menu insertItem:temp atIndex:trackInfoIndex + 1];
632 lastSongIndex = trackPlayingIndex;
636 if (playlist != [currentRemote currentPlaylistIndex]) {
637 bool wasPlayingRadio = isPlayingRadio;
638 isPlayingRadio = [[currentRemote classOfPlaylistAtIndex:playlist] isEqualToString:@"radio tuner playlist"];
639 if (isPlayingRadio && !wasPlayingRadio) {
641 for (i = 0; i < [playlistMenu numberOfItems]; i++)
643 [[playlistMenu itemAtIndex:i] setState:NSOffState];
646 if (wasPlayingRadio) {
647 NSMenuItem *temp = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""];
648 [menu insertItem:temp atIndex:trackInfoIndex + 1];
652 lastSongIndex = trackPlayingIndex;
655 //Update Play/Pause menu item
656 if (playPauseMenuItem){
657 if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"]) {
658 [playPauseMenuItem setTitle:@"Pause"];
660 [playPauseMenuItem setTitle:@"Play"];
665 - (void)iTunesLaunched:(NSNotification *)note
667 NSDictionary *info = [note userInfo];
669 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
670 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
673 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
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];
679 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
682 - (void)iTunesTerminated:(NSNotification *)note
684 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
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];
693 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
694 [refreshTimer invalidate];
699 //Return the PSN of iTunes, if it's running
700 - (ProcessSerialNumber)iTunesPSN
702 NSArray *apps = [[NSWorkspace sharedWorkspace] launchedApplications];
703 ProcessSerialNumber number;
706 number.highLongOfPSN = kNoProcess;
708 for (i = 0; i < [apps count]; i++)
710 NSDictionary *curApp = [apps objectAtIndex:i];
712 if ([[curApp objectForKey:@"NSApplicationName"] isEqualToString:@"iTunes"])
714 number.highLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
715 number.lowLongOfPSN = [[curApp objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
721 //Send an AppleEvent with a given event ID
722 - (void)sendAEWithEventClass:(AEEventClass)eventClass
723 andEventID:(AEEventID)eventID
725 OSType iTunesType = 'hook';
726 AppleEvent event, reply;
728 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, nil, "");
730 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
731 AEDisposeDesc(&event);
732 AEDisposeDesc(&reply);
737 // Selectors - called from status item menu
741 // Plugin dependent selectors
743 - (void)playTrack:(id)sender
745 [currentRemote switchToSongAtIndex:[[sender representedObject] intValue]];
749 - (void)selectPlaylist:(id)sender
751 int playlist = [[sender representedObject] intValue];
752 if (!isPlayingRadio) {
753 int curPlaylist = [currentRemote currentPlaylistIndex];
754 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOffState];
756 [currentRemote switchToPlaylistAtIndex:playlist];
757 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
761 - (void)selectEQPreset:(id)sender
763 int curSet = [currentRemote currentEQPresetIndex];
764 int item = [[sender representedObject] intValue];
765 [currentRemote switchToEQAtIndex:item];
766 [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
767 [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
770 - (void)playPause:(id)sender
772 NSString *state = [self runScriptAndReturnResult:@"return player state"];
773 NSLog(@"%i", [currentRemote playerState]);
774 if ([state isEqualToString:@"playing"]) {
775 [currentRemote play];
776 [playPauseMenuItem setTitle:@"Play"];
777 } else if ([state isEqualToString:@"fast forwarding"] || [state
778 isEqualToString:@"rewinding"]) {
779 [currentRemote play];
780 [currentRemote pause];
782 [currentRemote play];
783 [playPauseMenuItem setTitle:@"Pause"];
787 - (void)nextSong:(id)sender
789 [currentRemote goToNextSong];
792 - (void)prevSong:(id)sender
794 [currentRemote goToPreviousSong];
797 - (void)fastForward:(id)sender
799 [currentRemote fastForward];
802 - (void)rewind:(id)sender
804 [currentRemote rewind];
809 // Plugin independent selectors
812 - (void)quitMenuTunes:(id)sender
814 [NSApp terminate:self];
817 //How is this going to work, now that we're pluginized?
818 - (void)openiTunes:(id)sender
820 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
823 - (void)showPreferences:(id)sender
825 if (!prefsController) {
826 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
832 - (void)closePreferences
834 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))) {
837 [prefsController release];
838 prefsController = nil;
843 // Show Current Track Info And Show Upcoming Songs Floaters
847 - (void)showCurrentTrackInfo
849 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
850 if (!statusController && [trackName length]) {
851 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
852 NSString *stringToShow = @"";
854 if ([defaults boolForKey:@"showName"]) {
855 if ([defaults boolForKey:@"showArtist"]) {
856 NSString *trackArtist = [currentRemote currentSongArtist];
857 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
859 stringToShow = [stringToShow stringByAppendingString:trackName];
860 stringToShow = [stringToShow stringByAppendingString:@"\n"];
863 if ([defaults boolForKey:@"showAlbum"]) {
864 NSString *trackAlbum = [currentRemote currentSongAlbum];
865 if ([trackAlbum length]) {
866 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
867 stringToShow = [stringToShow stringByAppendingString:@"\n"];
871 if ([defaults boolForKey:@"showTime"]) {
872 NSString *trackTime = [currentRemote currentSongLength];
873 NSLog(@"%@", trackTime);
874 if ([trackTime length]) {
875 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
880 int trackTimeLeft = [[currentRemote currentSongRemaining] intValue];
881 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
883 stringToShow = [stringToShow stringByAppendingString:
884 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
886 stringToShow = [stringToShow stringByAppendingString:
887 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
891 statusController = [[StatusWindowController alloc] init];
892 [statusController setTrackInfo:stringToShow];
893 [NSTimer scheduledTimerWithTimeInterval:3.0
895 selector:@selector(fadeAndCloseStatusWindow)
901 - (void)showUpcomingSongs
903 int curPlaylist = [currentRemote currentPlaylistIndex];
904 if (!statusController) {
905 int numSongs = [currentRemote numberOfSongsInPlaylistAtIndex:curPlaylist];
908 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
909 int curTrack = [currentRemote currentSongIndex];
911 NSString *songs = @"";
913 statusController = [[StatusWindowController alloc] init];
914 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
916 NSString *curSong = [currentRemote songTitleAtIndex:i];
917 songs = [songs stringByAppendingString:curSong];
918 songs = [songs stringByAppendingString:@"\n"];
921 [statusController setUpcomingSongs:songs];
922 [NSTimer scheduledTimerWithTimeInterval:3.0
924 selector:@selector(fadeAndCloseStatusWindow)
931 - (void)fadeAndCloseStatusWindow
933 [statusController fadeWindowOut];
934 [statusController release];
935 statusController = nil;
938 - (void)setKeyEquivalentForCode:(short)code andModifiers:(long)modifiers
939 onItem:(NSMenuItem *)item
941 unichar charcode = 'a';
943 long cocoaModifiers = 0;
944 static long carbonToCocoa[6][2] =
946 { cmdKey, NSCommandKeyMask },
947 { optionKey, NSAlternateKeyMask },
948 { controlKey, NSControlKeyMask },
949 { shiftKey, NSShiftKeyMask },
952 for (i = 0; i < 6; i++)
954 if (modifiers & carbonToCocoa[i][0])
956 cocoaModifiers += carbonToCocoa[i][1];
959 [item setKeyEquivalentModifierMask:cocoaModifiers];
961 //Missing key combos for some keys. Must find them later.
975 /*MenuRef menuRef = _NSGetCarbonMenu([item menu]);
976 NSLog(@"%@", menuRef);
977 SetMenuItemCommandKey(menuRef, 0, NO, 49);
978 SetMenuItemModifiers(menuRef, 0, kMenuNoCommandModifier);
979 SetMenuItemKeyGlyph(menuRef, 0, kMenuBlankGlyph);
985 charcode = NSDeleteFunctionKey;
1001 charcode = NSF5FunctionKey;
1005 charcode = NSF6FunctionKey;
1009 charcode = NSF7FunctionKey;
1013 charcode = NSF3FunctionKey;
1017 charcode = NSF8FunctionKey;
1021 charcode = NSF9FunctionKey;
1025 charcode = NSF11FunctionKey;
1029 charcode = NSF3FunctionKey;
1033 charcode = NSF14FunctionKey;
1037 charcode = NSF10FunctionKey;
1041 charcode = NSF12FunctionKey;
1045 charcode = NSF13FunctionKey;
1049 charcode = NSInsertFunctionKey;
1053 charcode = NSHomeFunctionKey;
1057 charcode = NSPageUpFunctionKey;
1061 charcode = NSDeleteFunctionKey;
1065 charcode = NSF4FunctionKey;
1069 charcode = NSEndFunctionKey;
1073 charcode = NSF2FunctionKey;
1077 charcode = NSPageDownFunctionKey;
1081 charcode = NSF1FunctionKey;
1085 charcode = NSLeftArrowFunctionKey;
1089 charcode = NSRightArrowFunctionKey;
1093 charcode = NSDownArrowFunctionKey;
1097 charcode = NSUpArrowFunctionKey;
1101 if (charcode == 'a') {
1102 unsigned long state;
1107 kchr = (Ptr) GetScriptVariable(smCurrentScript, smKCHRCache);
1108 keyTrans = KeyTranslate(kchr, code, &state);
1109 charCode = keyTrans;
1110 [item setKeyEquivalent:[NSString stringWithCString:&charCode length:1]];
1111 } else if (charcode != 'b') {
1112 [item setKeyEquivalent:[NSString stringWithCharacters:&charcode length:1]];
1116 /*************************************************************************/
1118 #pragma mark NSApplication DELEGATE METHODS
1119 /*************************************************************************/
1121 - (void)applicationWillTerminate:(NSNotification *)note
1123 [self clearHotKeys];
1124 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1128 /*************************************************************************/
1130 #pragma mark DEALLOCATION METHODS
1131 /*************************************************************************/
1136 [refreshTimer invalidate];
1139 CloseComponent(asComponent);
1140 [currentRemote halt];
1141 [statusItem release];