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!
21 #import "MenuTunesView.h"
22 #import "PreferencesController.h"
23 #import "HotKeyCenter.h"
24 #import "StatusWindowController.h"
26 @implementation MenuTunes
28 - (void)applicationDidFinishLaunching:(NSNotification *)note
30 if (![[NSUserDefaults standardUserDefaults] objectForKey:@"menu"])
32 [[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"];
35 menu = [[NSMenu alloc] initWithTitle:@""];
36 iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
38 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
41 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
42 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
46 menu = [[NSMenu alloc] initWithTitle:@""];
47 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
48 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
49 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
50 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
54 statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
55 [statusItem setImage:[NSImage imageNamed:@"menu.tiff"]];
56 [statusItem setHighlightMode:YES];
57 [statusItem setMenu:menu];
59 view = [[MenuTunesView alloc] initWithFrame:[[statusItem view] frame]];
60 //[statusItem setView:view];
63 - (void)applicationWillTerminate:(NSNotification *)note
66 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
73 [refreshTimer invalidate];
81 //Recreate the status item menu
84 NSArray *myMenu = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menu"];
88 didHaveAlbumName = (([[self runScriptAndReturnResult:@"return album of current track"] length] > 0) ? YES : NO);
90 while ([menu numberOfItems] > 0)
92 [menu removeItemAtIndex:0];
95 playPauseMenuItem = nil;
96 upcomingSongsItem = nil;
98 [playlistMenu release];
104 for (i = 0; i < [myMenu count]; i++)
106 NSString *item = [myMenu objectAtIndex:i];
107 if ([item isEqualToString:@"Play/Pause"])
109 playPauseMenuItem = [menu addItemWithTitle:@"Play" action:@selector(playPause:) keyEquivalent:@""];
110 [playPauseMenuItem setTarget:self];
112 else if ([item isEqualToString:@"Next Track"])
114 [[menu addItemWithTitle:@"Next Track" action:@selector(nextSong:) keyEquivalent:@""] setTarget:self];
116 else if ([item isEqualToString:@"Previous Track"])
118 [[menu addItemWithTitle:@"Previous Track" action:@selector(prevSong:) keyEquivalent:@""] setTarget:self];
120 else if ([item isEqualToString:@"Fast Forward"])
122 [[menu addItemWithTitle:@"Fast Forward" action:@selector(fastForward:) keyEquivalent:@""] setTarget:self];
124 else if ([item isEqualToString:@"Rewind"])
126 [[menu addItemWithTitle:@"Rewind" action:@selector(rewind:) keyEquivalent:@""] setTarget:self];
128 else if ([item isEqualToString:@"Upcoming Songs"])
130 upcomingSongsItem = [menu addItemWithTitle:@"Upcoming Songs" action:NULL keyEquivalent:@""];
132 else if ([item isEqualToString:@"Playlists"])
134 playlistItem = [menu addItemWithTitle:@"Playlists" action:NULL keyEquivalent:@""];
136 else if ([item isEqualToString:@"EQ Presets"])
138 eqItem = [menu addItemWithTitle:@"EQ Presets" action:NULL keyEquivalent:@""];
140 else if ([item isEqualToString:@"PreferencesÉ"])
142 [[menu addItemWithTitle:@"PreferencesÉ" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
144 else if ([item isEqualToString:@"Quit"])
146 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
148 else if ([item isEqualToString:@"Current Track Info"])
150 trackInfoIndex = [menu numberOfItems];
151 [menu addItemWithTitle:@"No Song" action:NULL keyEquivalent:@""];
153 else if ([item isEqualToString:@"<separator>"])
155 [menu addItem:[NSMenuItem separatorItem]];
158 curTrackIndex = -1; //Force update of everything
159 [self timerUpdate]; //Updates dynamic info in the menu
165 //Updates the menu with current player state, song, and upcoming songs
168 NSString *curSongName, *curAlbumName;
169 NSMenuItem *menuItem;
171 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))
176 //Get the current track name and album.
177 curSongName = [self runScriptAndReturnResult:@"return name of current track"];
178 curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
180 if (upcomingSongsItem)
182 [self rebuildUpcomingSongsMenu];
186 [self rebuildPlaylistMenu];
190 [self rebuildEQPresetsMenu];
193 if ([curSongName length] > 0)
195 int index = [menu indexOfItemWithTitle:@"Now Playing"];
199 [menu removeItemAtIndex:index + 1];
200 if (didHaveAlbumName)
202 [menu removeItemAtIndex:index + 1];
206 if ([curAlbumName length] > 0)
208 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName] action:NULL keyEquivalent:@""];
209 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
213 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName] action:NULL keyEquivalent:@""];
214 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
219 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:NULL keyEquivalent:@""];
220 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
221 [menu insertItem:menuItem atIndex:trackInfoIndex];
225 else if ([menu indexOfItemWithTitle:@"No Song"] == -1)
227 [menu removeItemAtIndex:trackInfoIndex];
228 [menu removeItemAtIndex:trackInfoIndex];
229 if (didHaveAlbumName)
231 [menu removeItemAtIndex:trackInfoIndex];
233 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:NULL keyEquivalent:@""];
234 [menu insertItem:menuItem atIndex:trackInfoIndex];
238 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
241 //Rebuild the upcoming songs submenu. Can be improved a lot.
242 - (void)rebuildUpcomingSongsMenu
244 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
245 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
249 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
252 [upcomingSongsMenu release];
253 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
255 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
259 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
260 NSMenuItem *songItem;
261 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
262 [songItem setTarget:self];
263 [songItem setEnabled:YES];
264 [songItem setRepresentedObject:[NSNumber numberWithInt:i]];
265 [upcomingSongsMenu addItem:songItem];
270 [upcomingSongsMenu addItemWithTitle:@"End of playlist." action:NULL keyEquivalent:@""];
274 [upcomingSongsItem setSubmenu:upcomingSongsMenu];
275 [upcomingSongsItem setEnabled:YES];
279 - (void)rebuildPlaylistMenu
281 int numPlaylists = [[self runScriptAndReturnResult:@"return number of playlists"] intValue];
282 int i, curPlaylist = [[self runScriptAndReturnResult:@"return index of current playlist"] intValue];
284 if (playlistMenu && (numPlaylists == [playlistMenu numberOfItems]))
287 [playlistMenu release];
288 playlistMenu = [[NSMenu alloc] initWithTitle:@""];
290 for (i = 1; i <= numPlaylists; i++)
292 NSString *playlistName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of playlist %i", i]];
293 NSMenuItem *tempItem;
294 tempItem = [[NSMenuItem alloc] initWithTitle:playlistName action:@selector(selectPlaylist:) keyEquivalent:@""];
295 [tempItem setTarget:self];
296 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
297 [playlistMenu addItem:tempItem];
300 [playlistItem setSubmenu:playlistMenu];
304 [[playlistMenu itemAtIndex:curPlaylist - 1] setState:NSOnState];
308 //Build a menu with the list of all available EQ presets
309 - (void)rebuildEQPresetsMenu
311 int numSets = [[self runScriptAndReturnResult:@"return number of EQ presets"] intValue];
314 if (eqMenu && (numSets == [eqMenu numberOfItems]))
318 eqMenu = [[NSMenu alloc] initWithTitle:@""];
320 for (i = 1; i <= numSets; i++)
322 NSString *setName = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of EQ preset %i", i]];
323 NSMenuItem *tempItem;
324 tempItem = [[NSMenuItem alloc] initWithTitle:setName action:@selector(selectEQPreset:) keyEquivalent:@""];
325 [tempItem setTarget:self];
326 [tempItem setRepresentedObject:[NSNumber numberWithInt:i]];
327 [eqMenu addItem:tempItem];
330 [eqItem setSubmenu:eqMenu];
332 [[eqMenu itemAtIndex:[[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue] - 1] setState:NSOnState];
337 [[HotKeyCenter sharedCenter] removeHotKey:@"PlayPause"];
338 [[HotKeyCenter sharedCenter] removeHotKey:@"NextTrack"];
339 [[HotKeyCenter sharedCenter] removeHotKey:@"PrevTrack"];
340 [[HotKeyCenter sharedCenter] removeHotKey:@"TrackInfo"];
341 [[HotKeyCenter sharedCenter] removeHotKey:@"UpcomingSongs"];
346 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
348 if ([defaults objectForKey:@"PlayPause"] != nil)
350 [[HotKeyCenter sharedCenter] addHotKey:@"PlayPause"
351 combo:[defaults keyComboForKey:@"PlayPause"]
352 target:self action:@selector(playPause:)];
355 if ([defaults objectForKey:@"NextTrack"] != nil)
357 [[HotKeyCenter sharedCenter] addHotKey:@"NextTrack"
358 combo:[defaults keyComboForKey:@"NextTrack"]
359 target:self action:@selector(nextSong:)];
362 if ([defaults objectForKey:@"PrevTrack"] != nil)
364 [[HotKeyCenter sharedCenter] addHotKey:@"PrevTrack"
365 combo:[defaults keyComboForKey:@"PrevTrack"]
366 target:self action:@selector(prevSong:)];
369 if ([defaults objectForKey:@"TrackInfo"] != nil)
371 [[HotKeyCenter sharedCenter] addHotKey:@"TrackInfo"
372 combo:[defaults keyComboForKey:@"TrackInfo"]
373 target:self action:@selector(showCurrentTrackInfo)];
376 if ([defaults objectForKey:@"UpcomingSongs"] != nil)
378 [[HotKeyCenter sharedCenter] addHotKey:@"UpcomingSongs"
379 combo:[defaults keyComboForKey:@"UpcomingSongs"]
380 target:self action:@selector(showUpcomingSongs)];
384 //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.
385 - (NSString *)runScriptAndReturnResult:(NSString *)script
387 AEDesc scriptDesc, resultDesc;
392 script = [NSString stringWithFormat:@"tell application \"iTunes\"\n%@\nend tell", script];
394 AECreateDesc(typeChar, [script cString], [script cStringLength],
397 OSADoScript(OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype), &scriptDesc, kOSANullScript, typeChar, kOSAModeCanInteract, &resultDesc);
399 length = AEGetDescDataSize(&resultDesc);
400 buffer = malloc(length);
402 AEGetDescData(&resultDesc, buffer, length);
403 result = [NSString stringWithCString:buffer length:length];
404 if (![result isEqualToString:@""] &&
405 ([result characterAtIndex:0] == '\"') &&
406 ([result characterAtIndex:[result length] - 1] == '\"'))
408 result = [result substringWithRange:NSMakeRange(1, [result length] - 2)];
415 //Called when the timer fires.
419 if (GetProcessPID(&iTunesPSN, &pid) == noErr)
421 int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
422 if (trackPlayingIndex != curTrackIndex)
425 curTrackIndex = trackPlayingIndex;
428 //Update Play/Pause menu item
429 if (playPauseMenuItem)
431 if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"])
433 [playPauseMenuItem setTitle:@"Pause"];
437 [playPauseMenuItem setTitle:@"Play"];
444 menu = [[NSMenu alloc] initWithTitle:@""];
445 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
446 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
447 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
448 [statusItem setMenu:menu];
450 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
451 [refreshTimer invalidate];
457 - (void)iTunesLaunched:(NSNotification *)note
459 NSDictionary *info = [note userInfo];
461 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
462 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
465 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
467 [self rebuildMenu]; //Rebuild the menu since no songs will be playing
468 [statusItem setMenu:menu]; //Set the menu back to the main one
469 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
472 //Return the PSN of iTunes, if it's running
473 - (ProcessSerialNumber)iTunesPSN
475 ProcessSerialNumber procNum;
476 procNum.highLongOfPSN = kNoProcess;
477 procNum.lowLongOfPSN = 0;
479 while ( (GetNextProcess(&procNum) == noErr) )
481 CFStringRef procName;
482 if ( (CopyProcessName(&procNum, &procName) == noErr) )
484 if ([(NSString *)procName isEqualToString:@"iTunes"])
488 [(NSString *)procName release];
494 //Send an AppleEvent with a given event ID
495 - (void)sendAEWithEventClass:(AEEventClass)eventClass
496 andEventID:(AEEventID)eventID
498 OSType iTunesType = 'hook';
499 AppleEvent event, reply;
501 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, "");
503 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
504 AEDisposeDesc(&event);
505 AEDisposeDesc(&reply);
509 // Selectors - called from status item menu
512 - (void)playTrack:(id)sender
514 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
518 - (void)selectPlaylist:(id)sender
520 int playlist = [[sender representedObject] intValue];
521 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
522 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
526 - (void)selectEQPreset:(id)sender
528 int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
529 int item = [[sender representedObject] intValue];
530 [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
531 [self runScriptAndReturnResult:@"set EQ enabled to 1"];
532 [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
533 [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
536 - (void)playPause:(id)sender
538 NSString *state = [self runScriptAndReturnResult:@"return player state"];
539 if ([state isEqualToString:@"playing"])
541 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
542 [playPauseMenuItem setTitle:@"Play"];
544 else if ([state isEqualToString:@"fast forwarding"] || [state
545 isEqualToString:@"rewinding"])
547 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
548 [self sendAEWithEventClass:'hook' andEventID:'Play'];
552 [self sendAEWithEventClass:'hook' andEventID:'Play'];
553 [playPauseMenuItem setTitle:@"Pause"];
557 - (void)nextSong:(id)sender
559 [self sendAEWithEventClass:'hook' andEventID:'Next'];
562 - (void)prevSong:(id)sender
564 [self sendAEWithEventClass:'hook' andEventID:'Prev'];
567 - (void)fastForward:(id)sender
569 [self sendAEWithEventClass:'hook' andEventID:'Fast'];
572 - (void)rewind:(id)sender
574 [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
577 - (void)quitMenuTunes:(id)sender
579 [NSApp terminate:self];
582 - (void)openiTunes:(id)sender
584 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
587 - (void)showPreferences:(id)sender
589 if (!prefsController)
591 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
597 - (void)closePreferences
599 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
603 [prefsController release];
604 prefsController = nil;
609 // Show Current Track Info And Show Upcoming Songs Floaters
613 - (void)showCurrentTrackInfo
615 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
616 if (!statusController && [trackName length])
618 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
619 NSString *stringToShow = @"";
622 if ([defaults boolForKey:@"showName"])
624 if ([defaults boolForKey:@"showArtist"])
626 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
627 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
629 stringToShow = [stringToShow stringByAppendingString:trackName];
630 stringToShow = [stringToShow stringByAppendingString:@"\n"];
631 if ([trackName length] > 38)
638 if ([defaults boolForKey:@"showAlbum"])
640 NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
641 if ([trackAlbum length])
643 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
644 stringToShow = [stringToShow stringByAppendingString:@"\n"];
649 if ([defaults boolForKey:@"showTime"])
651 NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
652 if ([trackTime length])
654 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
660 int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
661 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
664 stringToShow = [stringToShow stringByAppendingString:
665 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
669 stringToShow = [stringToShow stringByAppendingString:
670 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
674 statusController = [[StatusWindowController alloc] init];
675 [statusController setTrackInfo:stringToShow lines:lines];
676 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
680 - (void)showUpcomingSongs
682 if (!statusController)
684 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
688 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
689 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
691 NSString *songs = @"";
693 statusController = [[StatusWindowController alloc] init];
694 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
698 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
699 songs = [songs stringByAppendingString:curSong];
700 songs = [songs stringByAppendingString:@"\n"];
703 [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
704 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
709 - (void)fadeAndCloseStatusWindow
711 [statusController fadeWindowOut];
712 [statusController release];
713 statusController = nil;