4 // iThink Software, Copyright 2002
10 ¥ Radio mode makes things act oddly
11 ¥ Make preferences window pretty
13 - hot keys can't be set when NSBGOnly is on. The window is not key,
14 so the KeyBroadcaster does not pick up key combos
15 - going to need a different way of defining key combos
16 ¥ Optimize, this thing is big and slow :(
17 ¥ Apple Events! Apple Events! Apple Events!
19 ¥ I think I found a slight memory leak:
20 425 MenuTunes 7.8% 8:29.87 1 56 4827 215M+ 3.14M 135M- 599M+
24 #import "MenuTunesView.h"
25 #import "PreferencesController.h"
26 #import "HotKeyCenter.h"
27 #import "StatusWindowController.h"
29 @implementation MenuTunes
31 - (void)applicationDidFinishLaunching:(NSNotification *)note
33 if (![[NSUserDefaults standardUserDefaults] objectForKey:@"menu"])
35 [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"Play/Pause", @"Next Track", @"Previous Track", @"Fast Forward", @"Rewind", @"<separator>", @"Upcoming Songs", @"Playlists", @"<separator>", @"PreferencesÉ", @"Quit", @"<separator>", @"Current Track Info", nil] forKey:@"menu"];
38 menu = [[NSMenu alloc] initWithTitle:@""];
39 iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
41 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
44 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
45 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
49 menu = [[NSMenu alloc] initWithTitle:@""];
50 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
51 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
52 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
53 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
57 statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
58 [statusItem setImage:[NSImage imageNamed:@"menu.tiff"]];
59 [statusItem setHighlightMode:YES];
60 [statusItem setMenu:menu];
62 view = [[MenuTunesView alloc] initWithFrame:[[statusItem view] frame]];
63 //[statusItem setView:view];
66 - (void)applicationWillTerminate:(NSNotification *)note
69 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
76 [refreshTimer invalidate];
84 //Recreate the status item menu
87 NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
91 didHaveAlbumName = (([[self runScriptAndReturnResult:@"return album of current track"] length] > 0) ? YES : NO);
93 while ([menu numberOfItems] > 0)
95 [menu removeItemAtIndex:0];
98 playPauseMenuItem = nil;
99 upcomingSongsItem = nil;
101 [playlistMenu release];
107 for (i = 0; i < [myMenu count]; i++)
109 NSString *item = [myMenu objectAtIndex:i];
110 if ([item isEqualToString:@"Play/Pause"])
112 playPauseMenuItem = [menu addItemWithTitle:@"Play" action:@selector(playPause:) keyEquivalent:@""];
113 [playPauseMenuItem setTarget:self];
115 else if ([item isEqualToString:@"Next Track"])
117 [[menu addItemWithTitle:@"Next Track" action:@selector(nextSong:) keyEquivalent:@""] setTarget:self];
119 else if ([item isEqualToString:@"Previous Track"])
121 [[menu addItemWithTitle:@"Previous Track" action:@selector(prevSong:) keyEquivalent:@""] setTarget:self];
123 else if ([item isEqualToString:@"Fast Forward"])
125 [[menu addItemWithTitle:@"Fast Forward" action:@selector(fastForward:) keyEquivalent:@""] setTarget:self];
127 else if ([item isEqualToString:@"Rewind"])
129 [[menu addItemWithTitle:@"Rewind" action:@selector(rewind:) keyEquivalent:@""] setTarget:self];
131 else if ([item isEqualToString:@"Upcoming Songs"])
133 upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs" action:NULL keyEquivalent:@""];
135 else if ([item isEqualToString:@"Playlists"])
137 playlistItem = [menu addItemWithTitle:@"Playlists" action:NULL keyEquivalent:@""];
139 else if ([item isEqualToString:@"EQ Presets"])
141 eqItem = [menu addItemWithTitle:@"EQ Presets" action:NULL keyEquivalent:@""];
143 else if ([item isEqualToString:@"PreferencesÉ"])
145 [[menu addItemWithTitle:@"PreferencesÉ" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
147 else if ([item isEqualToString:@"Quit"])
149 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
151 else if ([item isEqualToString:@"Current Track Info"])
153 trackInfoIndex = [menu numberOfItems];
154 [menu addItemWithTitle:@"No Song" action:NULL keyEquivalent:@""];
156 else if ([item isEqualToString:@"<separator>"])
158 [menu addItem:[NSMenuItem separatorItem]];
161 curTrackIndex = -1; //Force update of everything
162 [self timerUpdate]; //Updates dynamic info in the menu
168 //Updates the menu with current player state, song, and upcoming songs
171 NSString *curSongName, *curAlbumName;
172 NSMenuItem *menuItem;
174 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))
179 //Get the current track name and album.
180 curSongName = [self runScriptAndReturnResult:@"return name of current track"];
181 curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
183 if (upcomingSongsItem)
185 [self rebuildUpcomingSongsMenu];
189 [self rebuildPlaylistMenu];
193 [self rebuildEQPresetsMenu];
196 if ([curSongName length] > 0)
198 int index = [menu indexOfItemWithTitle:@"Now Playing"];
202 [menu removeItemAtIndex:index + 1];
203 if (didHaveAlbumName)
205 [menu removeItemAtIndex:index + 1];
209 if ([curAlbumName length] > 0)
211 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName] action:NULL keyEquivalent:@""];
212 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
216 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName] action:NULL keyEquivalent:@""];
217 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
222 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:NULL keyEquivalent:@""];
223 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
224 [menu insertItem:menuItem atIndex:trackInfoIndex];
228 else if ([menu indexOfItemWithTitle:@"No Song"] == -1)
230 [menu removeItemAtIndex:trackInfoIndex];
231 [menu removeItemAtIndex:trackInfoIndex];
232 if (didHaveAlbumName)
234 [menu removeItemAtIndex:trackInfoIndex];
236 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:NULL keyEquivalent:@""];
237 [menu insertItem:menuItem atIndex:trackInfoIndex];
241 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
244 //Rebuild the upcoming songs submenu. Can be improved a lot.
245 - (void)rebuildUpcomingSongsMenu
247 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
248 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
252 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
255 [upcomingSongsMenu release];
256 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
258 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
262 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
263 NSMenuItem *songItem;
264 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
265 [songItem setTarget:self];
266 [songItem setEnabled:YES];
267 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
268 [upcomingSongsMenu addItem:songItem];
273 [upcomingSongsMenu addItemWithTitle:@"End of playlist." action:NULL keyEquivalent:@""];
277 [upcomingSongsItem setSubmenu:upcomingSongsMenu];
278 [upcomingSongsItem setEnabled:YES];
282 - (void)rebuildPlaylistMenu
284 int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
285 int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
287 if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
290 [playlistMenu release];
291 playlistMenu = [[NSMenu alloc] initWithTitle:@""];
293 for (i = 1; i <= numPlaylists; i++)
295 NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
296 NSMenuItem *tempItem;
297 tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
298 [tempItem setTarget:self];
299 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
300 [playlistMenu addItem:tempItem];
303 [playlistItem setSubmenu:playlistMenu];
307 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
311 //Build a menu with the list of all available EQ presets
312 - (void)rebuildEQPresetsMenu
314 int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
317 if (eqMenu && (numSets == [eqMenu numberOfItems]))
321 eqMenu = [[NSMenu alloc] initWithTitle:@""];
323 for (i = 1; i <= numSets; i++)
325 NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
326 NSMenuItem *tempItem;
327 tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
328 [tempItem setTarget:self];
329 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
330 [eqMenu addItem:tempItem];
333 [eqItem setSubmenu:eqMenu];
335 [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
340 [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
341 [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
342 [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
343 [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
344 [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
349 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
351 if ([defaults objectForKey:@"PlayPause"] != nil)
353 [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
354 combo:[defaults keyComboForKey:@"PlayPause"]
355 target:self action:@selector(playPause:)];
358 if ([defaults objectForKey:@"NextTrack"] != nil)
360 [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
361 combo:[defaults keyComboForKey:@"NextTrack"]
362 target:self action:@selector(nextSong:)];
365 if ([defaults objectForKey:@"PrevTrack"] != nil)
367 [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
368 combo:[defaults keyComboForKey:@"PrevTrack"]
369 target:self action:@selector(prevSong:)];
372 if ([defaults objectForKey:@"TrackInfo"] != nil)
374 [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
375 combo:[defaults keyComboForKey:@"TrackInfo"]
376 target:self action:@selector(showCurrentTrackInfo)];
379 if ([defaults objectForKey:@"UpcomingSongs"] != nil)
381 [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
382 combo:[defaults keyComboForKey:@"UpcomingSongs"]
383 target:self action:@selector(showUpcomingSongs)];
387 //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.
388 - (NSString *)runScriptAndReturnResult:(NSString *)script
390 AEDesc scriptDesc, resultDesc;
395 script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
397 AECreateDesc(typeChar, [script cString], [script cStringLength],
400 OSADoScript(OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype), &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
402 length = AEGetDescDataSize(&resultDesc);
403 buffer = malloc(length);
405 AEGetDescData(&resultDesc, buffer, length);
406 AEDisposeDesc(&scriptDesc);
407 AEDisposeDesc(&resultDesc);
408 result = [NSString stringWithCString:buffer length:length];
409 if (![result isEqualToString:@""] &&
410 ([result characterAtIndex:0] == '\"') &&
411 ([result characterAtIndex:[result length] - 1] == '\"'))
413 result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
421 //Called when the timer fires.
425 if (GetProcessPID(&iTunesPSN, &pid) == noErr)
427 int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
428 if (trackPlayingIndex != curTrackIndex)
431 curTrackIndex = trackPlayingIndex;
434 //Update Play/Pause menu item
435 if (playPauseMenuItem)
437 if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"])
439 [playPauseMenuItem setTitle:@"Pause"];
443 [playPauseMenuItem setTitle:@"Play"];
450 menu = [[NSMenu alloc] initWithTitle:@""];
451 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
452 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
453 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
454 [statusItem setMenu:menu];
456 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
457 [refreshTimer invalidate];
463 - (void)iTunesLaunched:(NSNotification *)note
465 NSDictionary *info = [note userInfo];
467 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
468 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
471 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
473 [self rebuildMenu]; //Rebuild the menu since no songs will be playing
474 [statusItem setMenu:menu]; //Set the menu back to the main one
475 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
478 //Return the PSN of iTunes, if it's running
479 - (ProcessSerialNumber)iTunesPSN
481 ProcessSerialNumber procNum;
482 procNum.highLongOfPSN = kNoProcess;
483 procNum.lowLongOfPSN = 0;
485 while ( (GetNextProcess(&procNum) == noErr) )
487 CFStringRef procName;
488 if ( (CopyProcessName(&procNum, &procName) == noErr) )
490 if ([(NSString *)procName isEqualToString:@"iTunes"])
494 [(NSString *)procName release];
500 //Send an AppleEvent with a given event ID
501 - (void)sendAEWithEventClass:(AEEventClass)eventClass
502 andEventID:(AEEventID)eventID
504 OSType iTunesType = 'hook';
505 AppleEvent event, reply;
507 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, "");
509 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
510 AEDisposeDesc(&event);
511 AEDisposeDesc(&reply);
515 // Selectors - called from status item menu
518 - (void)playTrack:(id)sender
520 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
524 - (void)selectPlaylist:(id)sender
526 int playlist = [[sender representedObject] intValue];
527 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
528 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
532 - (void)selectEQPreset:(id)sender
534 int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
535 int item = [[sender representedObject] intValue];
536 [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
537 [self runScriptAndReturnResult:@"set EQ enabled to 1"];
538 [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
539 [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
542 - (void)playPause:(id)sender
544 NSString *state = [self runScriptAndReturnResult:@"return player state"];
545 if ([state isEqualToString:@"playing"])
547 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
548 [playPauseMenuItem setTitle:@"Play"];
550 else if ([state isEqualToString:@"fast forwarding"] || [state
551 isEqualToString:@"rewinding"])
553 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
554 [self sendAEWithEventClass:'hook' andEventID:'Play'];
558 [self sendAEWithEventClass:'hook' andEventID:'Play'];
559 [playPauseMenuItem setTitle:@"Pause"];
563 - (void)nextSong:(id)sender
565 [self sendAEWithEventClass:'hook' andEventID:'Next'];
568 - (void)prevSong:(id)sender
570 [self sendAEWithEventClass:'hook' andEventID:'Prev'];
573 - (void)fastForward:(id)sender
575 [self sendAEWithEventClass:'hook' andEventID:'Fast'];
578 - (void)rewind:(id)sender
580 [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
583 - (void)quitMenuTunes:(id)sender
585 [NSApp terminate:self];
588 - (void)openiTunes:(id)sender
590 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
593 - (void)showPreferences:(id)sender
595 if (!prefsController)
597 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
603 - (void)closePreferences
605 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
609 [prefsController release];
610 prefsController = nil;
615 // Show Current Track Info And Show Upcoming Songs Floaters
619 - (void)showCurrentTrackInfo
621 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
622 if (!statusController && [trackName length])
624 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
625 NSString *stringToShow = @"";
628 if ([defaults boolForKey:@"showName"])
630 if ([defaults boolForKey:@"showArtist"])
632 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
633 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
635 stringToShow = [stringToShow stringByAppendingString:trackName];
636 stringToShow = [stringToShow stringByAppendingString:@"\n"];
637 if ([trackName length] > 38)
644 if ([defaults boolForKey:@"showAlbum"])
646 NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
647 if ([trackAlbum length])
649 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
650 stringToShow = [stringToShow stringByAppendingString:@"\n"];
655 if ([defaults boolForKey:@"showTime"])
657 NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
658 if ([trackTime length])
660 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
666 int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
667 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
670 stringToShow = [stringToShow stringByAppendingString:
671 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
675 stringToShow = [stringToShow stringByAppendingString:
676 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
680 statusController = [[StatusWindowController alloc] init];
681 [statusController setTrackInfo:stringToShow lines:lines];
682 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
686 - (void)showUpcomingSongs
688 if (!statusController)
690 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
694 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
695 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
697 NSString *songs = @"";
699 statusController = [[StatusWindowController alloc] init];
700 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
704 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
705 songs = [songs stringByAppendingString:curSong];
706 songs = [songs stringByAppendingString:@"\n"];
709 [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
710 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
715 - (void)fadeAndCloseStatusWindow
717 [statusController fadeWindowOut];
718 [statusController release];
719 statusController = nil;