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
17 ¥ Apple Events! Apple Events! Apple Events!
18 ¥ Upcoming songs menu items are disabled after launching iTunes and playing
22 #import "MenuTunesView.h"
23 #import "PreferencesController.h"
24 #import "HotKeyCenter.h"
25 #import "StatusWindowController.h"
27 @implementation MenuTunes
29 - (void)applicationDidFinishLaunching:(NSNotification *)note
31 asComponent = OpenDefaultComponent(kOSAComponentType, kAppleScriptSubtype);
32 if (![[NSUserDefaults standardUserDefaults] objectForKey:@"menu"])
34 [[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"];
37 menu = [[NSMenu alloc] initWithTitle:@""];
38 iTunesPSN = [self iTunesPSN]; //Get PSN of iTunes if it's running
40 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
43 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5
44 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
48 menu = [[NSMenu alloc] initWithTitle:@""];
49 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
50 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
51 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
52 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
56 statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
57 [statusItem setImage:[NSImage imageNamed:@"menu.tiff"]];
58 [statusItem setHighlightMode:YES];
59 [statusItem setMenu:menu];
61 view = [[MenuTunesView alloc] initWithFrame:[[statusItem view] frame]];
62 //[statusItem setView:view];
65 - (void)applicationWillTerminate:(NSNotification *)note
68 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
75 [refreshTimer invalidate];
77 CloseComponent(asComponent);
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]];
162 curTrackIndex = -1; //Force update of everything
163 [self timerUpdate]; //Updates dynamic info in the menu
169 //Updates the menu with current player state, song, and upcoming songs
172 NSString *curSongName, *curAlbumName;
173 NSMenuItem *menuItem;
175 if ((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0))
180 //Get the current track name and album.
181 curSongName = [self runScriptAndReturnResult:@"return name of current track"];
182 curAlbumName = [self runScriptAndReturnResult:@"return album of current track"];
184 if (upcomingSongsItem)
186 [self rebuildUpcomingSongsMenu];
190 [self rebuildPlaylistMenu];
194 [self rebuildEQPresetsMenu];
197 if ([curSongName length] > 0)
199 int index = [menu indexOfItemWithTitle:@"Now Playing"];
203 [menu removeItemAtIndex:index + 1];
204 if (didHaveAlbumName)
206 [menu removeItemAtIndex:index + 1];
210 if ([curAlbumName length] > 0)
212 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curAlbumName] action:NULL keyEquivalent:@""];
213 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
217 menuItem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@" %@", curSongName] action:NULL keyEquivalent:@""];
218 [menu insertItem:menuItem atIndex:trackInfoIndex + 1];
223 menuItem = [[NSMenuItem alloc] initWithTitle:@"Now Playing" action:NULL keyEquivalent:@""];
224 [menu removeItemAtIndex:[menu indexOfItemWithTitle:@"No Song"]];
225 [menu insertItem:menuItem atIndex:trackInfoIndex];
229 else if ([menu indexOfItemWithTitle:@"No Song"] == -1)
231 [menu removeItemAtIndex:trackInfoIndex];
232 [menu removeItemAtIndex:trackInfoIndex];
233 if (didHaveAlbumName)
235 [menu removeItemAtIndex:trackInfoIndex];
237 menuItem = [[NSMenuItem alloc] initWithTitle:@"No Song" action:NULL keyEquivalent:@""];
238 [menu insertItem:menuItem atIndex:trackInfoIndex];
242 didHaveAlbumName = (([curAlbumName length] > 0) ? YES : NO);
245 //Rebuild the upcoming songs submenu. Can be improved a lot.
246 - (void)rebuildUpcomingSongsMenu
248 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
249 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
253 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
256 [upcomingSongsMenu release];
257 upcomingSongsMenu = [[NSMenu alloc] initWithTitle:@""];
259 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
263 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
264 NSMenuItem *songItem;
265 songItem = [[NSMenuItem alloc] initWithTitle:curSong action:@selector(playTrack:) keyEquivalent:@""];
266 [songItem setTarget:self];
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(asComponent, &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)];
420 //Called when the timer fires.
425 if (GetProcessPID(&iTunesPSN, &pid) == noErr)
427 int trackPlayingIndex = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
429 if (trackPlayingIndex != curTrackIndex)
432 curTrackIndex = trackPlayingIndex;
435 //Update Play/Pause menu item
436 if (playPauseMenuItem)
438 if ([[self runScriptAndReturnResult:@"return player state"] isEqualToString:@"playing"])
440 [playPauseMenuItem setTitle:@"Pause"];
444 [playPauseMenuItem setTitle:@"Play"];
451 menu = [[NSMenu alloc] initWithTitle:@""];
452 [[menu addItemWithTitle:@"Open iTunes" action:@selector(openiTunes:) keyEquivalent:@""] setTarget:self];
453 [[menu addItemWithTitle:@"Preferences" action:@selector(showPreferences:) keyEquivalent:@""] setTarget:self];
454 [[menu addItemWithTitle:@"Quit" action:@selector(quitMenuTunes:) keyEquivalent:@""] setTarget:self];
455 [statusItem setMenu:menu];
457 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(iTunesLaunched:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
458 [refreshTimer invalidate];
464 - (void)iTunesLaunched:(NSNotification *)note
466 NSDictionary *info = [note userInfo];
468 iTunesPSN.highLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberHigh"] longValue];
469 iTunesPSN.lowLongOfPSN = [[info objectForKey:@"NSApplicationProcessSerialNumberLow"] longValue];
472 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
474 [self rebuildMenu]; //Rebuild the menu since no songs will be playing
475 [statusItem setMenu:menu]; //Set the menu back to the main one
476 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
479 //Return the PSN of iTunes, if it's running
480 - (ProcessSerialNumber)iTunesPSN
482 ProcessSerialNumber procNum;
483 procNum.highLongOfPSN = kNoProcess;
484 procNum.lowLongOfPSN = 0;
486 while ( (GetNextProcess(&procNum) == noErr) )
488 CFStringRef procName;
489 if ( (CopyProcessName(&procNum, &procName) == noErr) )
491 if ([(NSString *)procName isEqualToString:@"iTunes"])
495 [(NSString *)procName release];
501 //Send an AppleEvent with a given event ID
502 - (void)sendAEWithEventClass:(AEEventClass)eventClass
503 andEventID:(AEEventID)eventID
505 OSType iTunesType = 'hook';
506 AppleEvent event, reply;
508 AEBuildAppleEvent(eventClass, eventID, typeApplSignature, &iTunesType, sizeof(iTunesType), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, "");
510 AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, nil, nil);
511 AEDisposeDesc(&event);
512 AEDisposeDesc(&reply);
516 // Selectors - called from status item menu
519 - (void)playTrack:(id)sender
521 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play track %i of current playlist", [[sender representedObject] intValue]]];
525 - (void)selectPlaylist:(id)sender
527 int playlist = [[sender representedObject] intValue];
528 [self runScriptAndReturnResult:[NSString stringWithFormat:@"play playlist %i", playlist]];
529 [[playlistMenu itemAtIndex:playlist - 1] setState:NSOnState];
533 - (void)selectEQPreset:(id)sender
535 int curSet = [[self runScriptAndReturnResult:@"return index of current EQ preset"] intValue];
536 int item = [[sender representedObject] intValue];
537 [self runScriptAndReturnResult:[NSString stringWithFormat:@"set current EQ preset to EQ preset %i", item]];
538 [self runScriptAndReturnResult:@"set EQ enabled to 1"];
539 [[eqMenu itemAtIndex:curSet - 1] setState:NSOffState];
540 [[eqMenu itemAtIndex:item - 1] setState:NSOnState];
543 - (void)playPause:(id)sender
545 NSString *state = [self runScriptAndReturnResult:@"return player state"];
546 if ([state isEqualToString:@"playing"])
548 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
549 [playPauseMenuItem setTitle:@"Play"];
551 else if ([state isEqualToString:@"fast forwarding"] || [state
552 isEqualToString:@"rewinding"])
554 [self sendAEWithEventClass:'hook' andEventID:'Paus'];
555 [self sendAEWithEventClass:'hook' andEventID:'Play'];
559 [self sendAEWithEventClass:'hook' andEventID:'Play'];
560 [playPauseMenuItem setTitle:@"Pause"];
564 - (void)nextSong:(id)sender
566 [self sendAEWithEventClass:'hook' andEventID:'Next'];
569 - (void)prevSong:(id)sender
571 [self sendAEWithEventClass:'hook' andEventID:'Prev'];
574 - (void)fastForward:(id)sender
576 [self sendAEWithEventClass:'hook' andEventID:'Fast'];
579 - (void)rewind:(id)sender
581 [self sendAEWithEventClass:'hook' andEventID:'Rwnd'];
584 - (void)quitMenuTunes:(id)sender
586 [NSApp terminate:self];
589 - (void)openiTunes:(id)sender
591 [[NSWorkspace sharedWorkspace] launchApplication:@"iTunes"];
594 - (void)showPreferences:(id)sender
596 if (!prefsController)
598 prefsController = [[PreferencesController alloc] initWithMenuTunes:self];
604 - (void)closePreferences
606 if (!((iTunesPSN.highLongOfPSN == kNoProcess) && (iTunesPSN.lowLongOfPSN == 0)))
610 [prefsController release];
611 prefsController = nil;
616 // Show Current Track Info And Show Upcoming Songs Floaters
620 - (void)showCurrentTrackInfo
622 NSString *trackName = [self runScriptAndReturnResult:@"return name of current track"];
623 if (!statusController && [trackName length])
625 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
626 NSString *stringToShow = @"";
629 if ([defaults boolForKey:@"showName"])
631 if ([defaults boolForKey:@"showArtist"])
633 NSString *trackArtist = [self runScriptAndReturnResult:@"return artist of current track"];
634 trackName = [NSString stringWithFormat:@"%@ - %@", trackArtist, trackName];
636 stringToShow = [stringToShow stringByAppendingString:trackName];
637 stringToShow = [stringToShow stringByAppendingString:@"\n"];
638 if ([trackName length] > 38)
645 if ([defaults boolForKey:@"showAlbum"])
647 NSString *trackAlbum = [self runScriptAndReturnResult:@"return album of current track"];
648 if ([trackAlbum length])
650 stringToShow = [stringToShow stringByAppendingString:trackAlbum];
651 stringToShow = [stringToShow stringByAppendingString:@"\n"];
656 if ([defaults boolForKey:@"showTime"])
658 NSString *trackTime = [self runScriptAndReturnResult:@"return time of current track"];
659 if ([trackTime length])
661 stringToShow = [NSString stringWithFormat:@"%@Total Time: %@\n", stringToShow, trackTime];
667 int trackTimeLeft = [[self runScriptAndReturnResult:@"return (duration of current track) - player position"] intValue];
668 int minutes = trackTimeLeft / 60, seconds = trackTimeLeft % 60;
671 stringToShow = [stringToShow stringByAppendingString:
672 [NSString stringWithFormat:@"Time Remaining: %i:0%i", minutes, seconds]];
676 stringToShow = [stringToShow stringByAppendingString:
677 [NSString stringWithFormat:@"Time Remaining: %i:%i", minutes, seconds]];
681 statusController = [[StatusWindowController alloc] init];
682 [statusController setTrackInfo:stringToShow lines:lines];
683 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
687 - (void)showUpcomingSongs
689 if (!statusController)
691 int numSongs = [[self runScriptAndReturnResult:@"return number of tracks in current playlist"] intValue];
695 int numSongsInAdvance = [[NSUserDefaults standardUserDefaults] integerForKey:@"SongsInAdvance"];
696 int curTrack = [[self runScriptAndReturnResult:@"return index of current track"] intValue];
698 NSString *songs = @"";
700 statusController = [[StatusWindowController alloc] init];
701 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++)
705 NSString *curSong = [self runScriptAndReturnResult:[NSString stringWithFormat:@"return name of track %i of current playlist", i]];
706 songs = [songs stringByAppendingString:curSong];
707 songs = [songs stringByAppendingString:@"\n"];
710 [statusController setUpcomingSongs:songs numSongs:numSongsInAdvance];
711 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(fadeAndCloseStatusWindow) userInfo:nil repeats:NO];
716 - (void)fadeAndCloseStatusWindow
718 [statusController fadeWindowOut];
719 [statusController release];
720 statusController = nil;