1 #import "MainController.h"
2 #import "MenuController.h"
3 #import "PreferencesController.h"
4 #import "NetworkController.h"
5 #import "NetworkObject.h"
6 #import <ITKit/ITHotKeyCenter.h>
7 #import <ITKit/ITHotKey.h>
8 #import <ITKit/ITKeyCombo.h>
9 #import "StatusWindow.h"
10 #import "StatusWindowController.h"
11 #import "StatusItemHack.h"
13 @interface NSImage (WeeAdditions)
14 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize;
17 @implementation NSImage (WeeAdditions)
19 - (NSImage *)imageScaledSmoothlyToSize:(NSSize)scaledSize
22 NSImageRep *rep = [self bestRepresentationForDevice:nil];
24 newImage = [[NSImage alloc] initWithSize:scaledSize];
27 [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
28 [[NSGraphicsContext currentContext] setShouldAntialias:YES];
29 [rep drawInRect:NSMakeRect(3, 3, scaledSize.width - 6, scaledSize.height - 6)];
31 [newImage unlockFocus];
32 return [newImage autorelease];
37 @interface MainController(Private)
38 - (ITMTRemote *)loadRemote;
40 - (void)setLatestSongIdentifier:(NSString *)newIdentifier;
41 - (void)applicationLaunched:(NSNotification *)note;
42 - (void)applicationTerminated:(NSNotification *)note;
45 static MainController *sharedController;
47 @implementation MainController
49 + (MainController *)sharedController
51 return sharedController;
54 /*************************************************************************/
56 #pragma mark INITIALIZATION/DEALLOCATION METHODS
57 /*************************************************************************/
61 if ( ( self = [super init] ) ) {
62 sharedController = self;
64 remoteArray = [[NSMutableArray alloc] initWithCapacity:1];
65 [[PreferencesController sharedPrefs] setController:self];
66 statusWindowController = [StatusWindowController sharedController];
67 menuController = [[MenuController alloc] init];
68 df = [[NSUserDefaults standardUserDefaults] retain];
75 - (void)applicationDidFinishLaunching:(NSNotification *)note
77 //Turn on debug mode if needed
78 if ([df boolForKey:@"ITDebugMode"]) {
82 if (([df integerForKey:@"appVersion"] < 1200) && ([df integerForKey:@"SongsInAdvance"] > 0)) {
83 [df removePersistentDomainForName:@"com.ithinksw.menutunes"];
85 [[PreferencesController sharedPrefs] registerDefaults];
86 [[StatusWindowController sharedController] showPreferencesUpdateWindow];
89 currentRemote = [self loadRemote];
90 [[self currentRemote] begin];
92 //Turn on network stuff if needed
93 networkController = [[NetworkController alloc] init];
94 if ([df boolForKey:@"enableSharing"]) {
95 [self setServerStatus:YES];
96 } else if ([df boolForKey:@"useSharedPlayer"]) {
97 if ([self connectToServer] == 0) {
98 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
102 //Setup for notification of the remote player launching or quitting
103 [[[NSWorkspace sharedWorkspace] notificationCenter]
105 selector:@selector(applicationTerminated:)
106 name:NSWorkspaceDidTerminateApplicationNotification
109 [[[NSWorkspace sharedWorkspace] notificationCenter]
111 selector:@selector(applicationLaunched:)
112 name:NSWorkspaceDidLaunchApplicationNotification
115 if ( ! [df objectForKey:@"menu"] ) { // If this is nil, defaults have never been registered.
116 [[PreferencesController sharedPrefs] registerDefaults];
119 if ([df boolForKey:@"ITMTNoStatusItem"]) {
122 [StatusItemHack install];
123 statusItem = [[ITStatusItem alloc]
124 initWithStatusBar:[NSStatusBar systemStatusBar]
125 withLength:NSSquareStatusItemLength];
128 bling = [[MTBlingController alloc] init];
130 registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
132 selector:@selector(blingTime)
134 repeats:YES] retain];
137 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
138 [self applicationLaunched:nil];
140 if ([df boolForKey:@"LaunchPlayerWithMT"])
143 [self applicationTerminated:nil];
146 [self networkError:localException];
149 [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
150 [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
152 [networkController startRemoteServerSearch];
156 - (ITMTRemote *)loadRemote
158 NSString *folderPath = [[NSBundle mainBundle] builtInPlugInsPath];
159 ITDebugLog(@"Gathering remotes.");
161 NSArray *bundlePathList = [NSBundle pathsForResourcesOfType:@"remote" inDirectory:folderPath];
162 NSEnumerator *enumerator = [bundlePathList objectEnumerator];
163 NSString *bundlePath;
165 while ( (bundlePath = [enumerator nextObject]) ) {
166 NSBundle* remoteBundle = [NSBundle bundleWithPath:bundlePath];
169 Class remoteClass = [remoteBundle principalClass];
171 if ([remoteClass conformsToProtocol:@protocol(ITMTRemote)] &&
172 [remoteClass isKindOfClass:[NSObject class]]) {
173 id remote = [remoteClass remote];
174 ITDebugLog(@"Adding remote at path %@", bundlePath);
175 [remoteArray addObject:remote];
180 // if ( [remoteArray count] > 0 ) { // UNCOMMENT WHEN WE HAVE > 1 PLUGIN
181 // if ( [remoteArray count] > 1 ) {
182 // [remoteArray sortUsingSelector:@selector(sortAlpha:)];
184 // [self loadModuleAccessUI]; //Comment out this line to disable remote visibility
187 // NSLog(@"%@", [remoteArray objectAtIndex:0]); //DEBUG
188 return [remoteArray objectAtIndex:0];
191 /*************************************************************************/
193 #pragma mark INSTANCE METHODS
194 /*************************************************************************/
196 /*- (void)startTimerInNewThread
198 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
199 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
200 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
202 selector:@selector(timerUpdate)
204 repeats:YES] retain];
206 ITDebugLog(@"Timer started.");
210 - (void)setBlingTime:(NSDate*)date
212 NSMutableDictionary *globalPrefs;
214 globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
216 [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
218 [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
220 [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
222 [globalPrefs release];
225 - (NSDate*)getBlingTime
228 return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
233 NSDate *now = [NSDate date];
234 if (![self blingBling]) {
235 if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
236 [self setBlingTime:now];
238 if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
240 [statusItem setEnabled:NO];
242 if ([refreshTimer isValid]) {
243 [refreshTimer invalidate];
245 [statusWindowController showRegistrationQueryWindow];
249 [statusItem setEnabled:YES];
251 if (![refreshTimer isValid]) {
252 [refreshTimer release];
253 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
255 selector:@selector(timerUpdate)
257 repeats:YES] retain];
261 [self setBlingTime:nil];
272 if ( ! ([bling checkDone] == 2475) ) {
279 - (BOOL)songIsPlaying
281 NSString *identifier = nil;
283 identifier = [[self currentRemote] playerStateUniqueIdentifier];
285 [self networkError:localException];
287 return ( ! ([identifier isEqualToString:@"0-0"]) );
290 - (BOOL)radioIsPlaying
292 ITMTRemotePlayerPlaylistClass class = nil;
294 class = [[self currentRemote] currentPlaylistClass];
296 [self networkError:localException];
298 return (class == ITMTRemotePlayerRadioPlaylist );
303 NSString *identifier = nil;
305 identifier = [[self currentRemote] playerStateUniqueIdentifier];
307 [self networkError:localException];
309 return ( ! [identifier isEqualToString:_latestSongIdentifier] );
312 - (NSString *)latestSongIdentifier
314 return _latestSongIdentifier;
317 - (void)setLatestSongIdentifier:(NSString *)newIdentifier
319 ITDebugLog(@"Setting latest song identifier to %@", newIdentifier);
320 [_latestSongIdentifier autorelease];
321 _latestSongIdentifier = [newIdentifier copy];
326 if ([networkController isConnectedToServer]) {
327 [statusItem setMenu:[menuController menu]];
330 if ( [self songChanged] && (timerUpdating != YES) && (playerRunningState == ITMTRemotePlayerRunning) ) {
331 ITDebugLog(@"The song changed.");
333 if ([df boolForKey:@"runScripts"] && [[self currentRemote] currentSongTitle]) {
334 NSArray *scripts = [[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"]];
335 NSEnumerator *scriptsEnum = [scripts objectEnumerator];
336 NSString *nextScript;
337 while ( (nextScript = [scriptsEnum nextObject]) ) {
339 NSAppleScript *currentScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/MenuTunes/Scripts"] stringByAppendingPathComponent:nextScript]] error:&error];
340 if (!currentScript || ![currentScript executeAndReturnError:nil]) {
341 ITDebugLog(@"Error running script %@.", nextScript);
343 [currentScript release];
350 latestPlaylistClass = [[self currentRemote] currentPlaylistClass];
351 [menuController rebuildSubmenus];
353 if ( [df boolForKey:@"showSongInfoOnChange"] ) {
354 [self performSelector:@selector(showCurrentTrackInfo) withObject:nil afterDelay:0.0];
357 [self setLatestSongIdentifier:[[self currentRemote] playerStateUniqueIdentifier]];
359 NSString *artist = [[self currentRemote] currentSongArtist];
360 NSString *title = [[self currentRemote] currentSongTitle];
363 toolTip = [NSString stringWithFormat:@"%@ - %@", artist, title];
367 toolTip = @"No Song Playing";
369 [statusItem setToolTip:toolTip];
371 [self networkError:localException];
380 ITDebugLog(@"Menu clicked.");
381 if ([networkController isConnectedToServer]) {
382 //Used the cached version
387 if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
388 [statusItem setMenu:[menuController menu]];
390 [statusItem setMenu:[menuController menuForNoPlayer]];
393 [self networkError:localException];
406 ITMTRemotePlayerPlayingState state = [[self currentRemote] playerPlayingState];
407 ITDebugLog(@"Play/Pause toggled");
408 if (state == ITMTRemotePlayerPlaying) {
409 [[self currentRemote] pause];
410 } else if ((state == ITMTRemotePlayerForwarding) || (state == ITMTRemotePlayerRewinding)) {
411 [[self currentRemote] pause];
412 [[self currentRemote] play];
414 [[self currentRemote] play];
417 [self networkError:localException];
425 ITDebugLog(@"Going to next song.");
427 [[self currentRemote] goToNextSong];
429 [self networkError:localException];
436 ITDebugLog(@"Going to previous song.");
438 [[self currentRemote] goToPreviousSong];
440 [self networkError:localException];
447 ITDebugLog(@"Fast forwarding.");
449 [[self currentRemote] forward];
451 [self networkError:localException];
458 ITDebugLog(@"Rewinding.");
460 [[self currentRemote] rewind];
462 [self networkError:localException];
467 - (void)selectPlaylistAtIndex:(int)index
469 ITDebugLog(@"Selecting playlist %i", index);
471 [[self currentRemote] switchToPlaylistAtIndex:(index % 1000) ofSourceAtIndex:(index / 1000)];
472 //[[self currentRemote] switchToPlaylistAtIndex:index];
474 [self networkError:localException];
479 - (void)selectSongAtIndex:(int)index
481 ITDebugLog(@"Selecting song %i", index);
483 [[self currentRemote] switchToSongAtIndex:index];
485 [self networkError:localException];
490 - (void)selectSongRating:(int)rating
492 ITDebugLog(@"Selecting song rating %i", rating);
494 [[self currentRemote] setCurrentSongRating:(float)rating / 100.0];
496 [self networkError:localException];
501 - (void)selectEQPresetAtIndex:(int)index
503 ITDebugLog(@"Selecting EQ preset %i", index);
505 [[self currentRemote] switchToEQAtIndex:index];
507 [self networkError:localException];
514 ITDebugLog(@"Beginning show player.");
515 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
516 ITDebugLog(@"Showing player interface.");
518 [[self currentRemote] showPrimaryInterface];
520 [self networkError:localException];
523 ITDebugLog(@"Launching player.");
526 if ( (path = [df stringForKey:@"CustomPlayerPath"]) ) {
528 path = [[self currentRemote] playerFullName];
530 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
531 ITDebugLog(@"Error Launching Player");
534 [self networkError:localException];
537 ITDebugLog(@"Finished show player.");
540 - (void)showPreferences
542 ITDebugLog(@"Show preferences.");
543 [[PreferencesController sharedPrefs] showPrefsWindow:self];
546 - (void)showPreferencesAndClose
548 ITDebugLog(@"Show preferences.");
549 [[PreferencesController sharedPrefs] showPrefsWindow:self];
550 [[StatusWindow sharedWindow] setLocked:NO];
551 [[StatusWindow sharedWindow] vanish:self];
552 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
555 - (void)showTestWindow
557 [self showCurrentTrackInfo];
560 - (void)quitMenuTunes
562 ITDebugLog(@"Quitting MenuTunes.");
563 [NSApp terminate:self];
569 - (void)closePreferences
571 ITDebugLog(@"Preferences closed.");
572 if ( ( playerRunningState == ITMTRemotePlayerRunning) ) {
577 - (ITMTRemote *)currentRemote
579 if ([networkController isConnectedToServer] && ![[networkController networkObject] isValid]) {
580 [self networkError:nil];
583 return currentRemote;
594 NSEnumerator *hotKeyEnumerator = [[[ITHotKeyCenter sharedCenter] allHotKeys] objectEnumerator];
595 ITHotKey *nextHotKey;
596 ITDebugLog(@"Clearing hot keys.");
597 while ( (nextHotKey = [hotKeyEnumerator nextObject]) ) {
598 [[ITHotKeyCenter sharedCenter] unregisterHotKey:nextHotKey];
600 ITDebugLog(@"Done clearing hot keys.");
606 ITDebugLog(@"Setting up hot keys.");
608 if (playerRunningState == ITMTRemotePlayerNotRunning) {
612 if ([df objectForKey:@"PlayPause"] != nil) {
613 ITDebugLog(@"Setting up play pause hot key.");
614 hotKey = [[ITHotKey alloc] init];
615 [hotKey setName:@"PlayPause"];
616 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PlayPause"]]];
617 [hotKey setTarget:self];
618 [hotKey setAction:@selector(playPause)];
619 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
622 if ([df objectForKey:@"NextTrack"] != nil) {
623 ITDebugLog(@"Setting up next track hot key.");
624 hotKey = [[ITHotKey alloc] init];
625 [hotKey setName:@"NextTrack"];
626 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"NextTrack"]]];
627 [hotKey setTarget:self];
628 [hotKey setAction:@selector(nextSong)];
629 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
632 if ([df objectForKey:@"PrevTrack"] != nil) {
633 ITDebugLog(@"Setting up previous track hot key.");
634 hotKey = [[ITHotKey alloc] init];
635 [hotKey setName:@"PrevTrack"];
636 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"PrevTrack"]]];
637 [hotKey setTarget:self];
638 [hotKey setAction:@selector(prevSong)];
639 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
642 if ([df objectForKey:@"ShowPlayer"] != nil) {
643 ITDebugLog(@"Setting up show player hot key.");
644 hotKey = [[ITHotKey alloc] init];
645 [hotKey setName:@"ShowPlayer"];
646 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
647 [hotKey setTarget:self];
648 [hotKey setAction:@selector(showPlayer)];
649 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
652 if ([df objectForKey:@"TrackInfo"] != nil) {
653 ITDebugLog(@"Setting up track info hot key.");
654 hotKey = [[ITHotKey alloc] init];
655 [hotKey setName:@"TrackInfo"];
656 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
657 [hotKey setTarget:self];
658 [hotKey setAction:@selector(showCurrentTrackInfo)];
659 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
662 if ([df objectForKey:@"UpcomingSongs"] != nil) {
663 ITDebugLog(@"Setting up upcoming songs hot key.");
664 hotKey = [[ITHotKey alloc] init];
665 [hotKey setName:@"UpcomingSongs"];
666 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"UpcomingSongs"]]];
667 [hotKey setTarget:self];
668 [hotKey setAction:@selector(showUpcomingSongs)];
669 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
672 if ([df objectForKey:@"ToggleLoop"] != nil) {
673 ITDebugLog(@"Setting up toggle loop hot key.");
674 hotKey = [[ITHotKey alloc] init];
675 [hotKey setName:@"ToggleLoop"];
676 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleLoop"]]];
677 [hotKey setTarget:self];
678 [hotKey setAction:@selector(toggleLoop)];
679 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
682 if ([df objectForKey:@"ToggleShuffle"] != nil) {
683 ITDebugLog(@"Setting up toggle shuffle hot key.");
684 hotKey = [[ITHotKey alloc] init];
685 [hotKey setName:@"ToggleShuffle"];
686 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ToggleShuffle"]]];
687 [hotKey setTarget:self];
688 [hotKey setAction:@selector(toggleShuffle)];
689 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
692 if ([df objectForKey:@"IncrementVolume"] != nil) {
693 ITDebugLog(@"Setting up increment volume hot key.");
694 hotKey = [[ITHotKey alloc] init];
695 [hotKey setName:@"IncrementVolume"];
696 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementVolume"]]];
697 [hotKey setTarget:self];
698 [hotKey setAction:@selector(incrementVolume)];
699 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
702 if ([df objectForKey:@"DecrementVolume"] != nil) {
703 ITDebugLog(@"Setting up decrement volume hot key.");
704 hotKey = [[ITHotKey alloc] init];
705 [hotKey setName:@"DecrementVolume"];
706 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementVolume"]]];
707 [hotKey setTarget:self];
708 [hotKey setAction:@selector(decrementVolume)];
709 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
712 if ([df objectForKey:@"IncrementRating"] != nil) {
713 ITDebugLog(@"Setting up increment rating hot key.");
714 hotKey = [[ITHotKey alloc] init];
715 [hotKey setName:@"IncrementRating"];
716 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"IncrementRating"]]];
717 [hotKey setTarget:self];
718 [hotKey setAction:@selector(incrementRating)];
719 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
722 if ([df objectForKey:@"DecrementRating"] != nil) {
723 ITDebugLog(@"Setting up decrement rating hot key.");
724 hotKey = [[ITHotKey alloc] init];
725 [hotKey setName:@"DecrementRating"];
726 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"DecrementRating"]]];
727 [hotKey setTarget:self];
728 [hotKey setAction:@selector(decrementRating)];
729 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
731 ITDebugLog(@"Finished setting up hot keys.");
734 - (void)showCurrentTrackInfo
736 ITMTRemotePlayerSource source = 0;
737 NSString *title = nil;
738 NSString *album = nil;
739 NSString *artist = nil;
740 NSString *time = nil;
741 NSString *track = nil;
746 source = [[self currentRemote] currentSource];
747 title = [[self currentRemote] currentSongTitle];
749 [self networkError:localException];
752 ITDebugLog(@"Showing track info status window.");
756 if ( [df boolForKey:@"showAlbum"] ) {
758 album = [[self currentRemote] currentSongAlbum];
760 [self networkError:localException];
764 if ( [df boolForKey:@"showArtist"] ) {
766 artist = [[self currentRemote] currentSongArtist];
768 [self networkError:localException];
772 if ( [df boolForKey:@"showTime"] ) {
774 time = [NSString stringWithFormat:@"%@: %@ / %@",
776 [[self currentRemote] currentSongElapsed],
777 [[self currentRemote] currentSongLength]];
779 [self networkError:localException];
783 if ( [df boolForKey:@"showTrackNumber"] ) {
788 trackNo = [[self currentRemote] currentSongTrack];
789 trackCount = [[self currentRemote] currentAlbumTrackCount];
791 [self networkError:localException];
794 if ( (trackNo > 0) || (trackCount > 0) ) {
795 track = [NSString stringWithFormat:@"%@: %i %@ %i",
796 @"Track", trackNo, @"of", trackCount];
800 if ( [df boolForKey:@"showTrackRating"] ) {
801 float currentRating = 0;
804 currentRating = [[self currentRemote] currentSongRating];
806 [self networkError:localException];
809 if (currentRating >= 0.0) {
810 rating = ( currentRating * 5 );
814 if ( [df boolForKey:@"showAlbumArtwork"] ) {
816 art = [[self currentRemote] currentSongAlbumArt];
818 [self networkError:localException];
823 title = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
825 [statusWindowController showSongInfoWindowWithSource:source
832 image:[[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:NSMakeSize(110,110)]];
835 - (void)showUpcomingSongs
839 numSongs = [[self currentRemote] numberOfSongsInPlaylistAtIndex:[[self currentRemote] currentPlaylistIndex]];
841 [self networkError:localException];
844 ITDebugLog(@"Showing upcoming songs status window.");
847 int numSongsInAdvance = [df integerForKey:@"SongsInAdvance"];
848 NSMutableArray *songList = [NSMutableArray arrayWithCapacity:numSongsInAdvance];
849 int curTrack = [[self currentRemote] currentSongIndex];
852 for (i = curTrack + 1; i <= curTrack + numSongsInAdvance; i++) {
854 [songList addObject:[[self currentRemote] songTitleAtIndex:i]];
858 if ([songList count] == 0) {
859 [songList addObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")];
862 [statusWindowController showUpcomingSongsWindowWithTitles:songList];
864 [statusWindowController showUpcomingSongsWindowWithTitles:[NSArray arrayWithObject:NSLocalizedString(@"noUpcomingSongs", @"No upcoming songs.")]];
867 [self networkError:localException];
871 - (void)incrementVolume
874 float volume = [[self currentRemote] volume];
875 float dispVol = volume;
876 ITDebugLog(@"Incrementing volume.");
885 ITDebugLog(@"Setting volume to %f", volume);
886 [[self currentRemote] setVolume:volume];
888 // Show volume status window
889 [statusWindowController showVolumeWindowWithLevel:dispVol];
891 [self networkError:localException];
895 - (void)decrementVolume
898 float volume = [[self currentRemote] volume];
899 float dispVol = volume;
900 ITDebugLog(@"Decrementing volume.");
909 ITDebugLog(@"Setting volume to %f", volume);
910 [[self currentRemote] setVolume:volume];
912 //Show volume status window
913 [statusWindowController showVolumeWindowWithLevel:dispVol];
915 [self networkError:localException];
919 - (void)incrementRating
922 float rating = [[self currentRemote] currentSongRating];
923 ITDebugLog(@"Incrementing rating.");
925 if ([[self currentRemote] currentPlaylistIndex] == 0) {
926 ITDebugLog(@"No song playing, rating change aborted.");
934 ITDebugLog(@"Setting rating to %f", rating);
935 [[self currentRemote] setCurrentSongRating:rating];
937 //Show rating status window
938 [statusWindowController showRatingWindowWithRating:rating];
940 [self networkError:localException];
944 - (void)decrementRating
947 float rating = [[self currentRemote] currentSongRating];
948 ITDebugLog(@"Decrementing rating.");
950 if ([[self currentRemote] currentPlaylistIndex] == 0) {
951 ITDebugLog(@"No song playing, rating change aborted.");
959 ITDebugLog(@"Setting rating to %f", rating);
960 [[self currentRemote] setCurrentSongRating:rating];
962 //Show rating status window
963 [statusWindowController showRatingWindowWithRating:rating];
965 [self networkError:localException];
972 ITMTRemotePlayerRepeatMode repeatMode = [[self currentRemote] repeatMode];
973 ITDebugLog(@"Toggling repeat mode.");
974 switch (repeatMode) {
975 case ITMTRemotePlayerRepeatOff:
976 repeatMode = ITMTRemotePlayerRepeatAll;
978 case ITMTRemotePlayerRepeatAll:
979 repeatMode = ITMTRemotePlayerRepeatOne;
981 case ITMTRemotePlayerRepeatOne:
982 repeatMode = ITMTRemotePlayerRepeatOff;
985 ITDebugLog(@"Setting repeat mode to %i", repeatMode);
986 [[self currentRemote] setRepeatMode:repeatMode];
988 //Show loop status window
989 [statusWindowController showRepeatWindowWithMode:repeatMode];
991 [self networkError:localException];
995 - (void)toggleShuffle
998 BOOL newShuffleEnabled = ( ! [[self currentRemote] shuffleEnabled] );
999 ITDebugLog(@"Toggling shuffle mode.");
1000 [[self currentRemote] setShuffleEnabled:newShuffleEnabled];
1001 //Show shuffle status window
1002 ITDebugLog(@"Setting shuffle mode to %i", newShuffleEnabled);
1003 [statusWindowController showShuffleWindow:newShuffleEnabled];
1005 [self networkError:localException];
1009 - (void)registerNowOK
1011 [[StatusWindow sharedWindow] setLocked:NO];
1012 [[StatusWindow sharedWindow] vanish:self];
1013 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1018 - (void)registerNowCancel
1020 [[StatusWindow sharedWindow] setLocked:NO];
1021 [[StatusWindow sharedWindow] vanish:self];
1022 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1024 [NSApp terminate:self];
1027 /*************************************************************************/
1029 #pragma mark NETWORK HANDLERS
1030 /*************************************************************************/
1032 - (void)setServerStatus:(BOOL)newStatus
1036 [networkController setServerStatus:YES];
1039 [networkController setServerStatus:NO];
1043 - (int)connectToServer
1046 ITDebugLog(@"Attempting to connect to shared remote.");
1047 result = [networkController connectToHost:[df stringForKey:@"sharedPlayerHost"]];
1050 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1051 currentRemote = [[[networkController networkObject] remote] retain];
1052 [refreshTimer invalidate];
1053 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1055 selector:@selector(timerUpdate)
1057 repeats:YES] retain];
1059 ITDebugLog(@"Connection successful.");
1061 } else if (result == 0) {
1062 ITDebugLog(@"Connection failed.");
1063 currentRemote = [remoteArray objectAtIndex:0];
1066 //Do something about the password being invalid
1067 ITDebugLog(@"Connection failed.");
1068 currentRemote = [remoteArray objectAtIndex:0];
1073 - (BOOL)disconnectFromServer
1075 ITDebugLog(@"Disconnecting from shared remote.");
1077 [currentRemote release];
1078 currentRemote = [remoteArray objectAtIndex:0];
1079 [networkController disconnect];
1084 - (void)checkForRemoteServer:(NSTimer *)timer
1086 ITDebugLog(@"Checking for remote server.");
1087 if ([networkController checkForServerAtHost:[df stringForKey:@"sharedPlayerHost"]]) {
1088 ITDebugLog(@"Remote server found.");
1090 if (![networkController isServerOn] && ![networkController isConnectedToServer]) {
1091 [[StatusWindowController sharedController] showReconnectQueryWindow];
1094 ITDebugLog(@"Remote server not found.");
1098 - (void)networkError:(NSException *)exception
1100 ITDebugLog(@"Remote exception thrown: %@: %@", [exception name], [exception reason]);
1101 if ( ((exception == nil) || [[exception name] isEqualToString:NSPortTimeoutException]) && [networkController isConnectedToServer]) {
1102 NSRunCriticalAlertPanel(@"Remote MenuTunes Disconnected", @"The MenuTunes server you were connected to stopped responding or quit. MenuTunes will revert back to the local player.", @"OK", nil, nil);
1103 if ([self disconnectFromServer]) {
1104 [[PreferencesController sharedPrefs] resetRemotePlayerTextFields];
1105 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1107 ITDebugLog(@"CRITICAL ERROR, DISCONNECTING!");
1114 if ([self connectToServer] == 0) {
1115 [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(checkForRemoteServer:) userInfo:nil repeats:YES];
1117 [[StatusWindow sharedWindow] setLocked:NO];
1118 [[StatusWindow sharedWindow] vanish:self];
1119 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1122 - (void)cancelReconnect
1124 [[StatusWindow sharedWindow] setLocked:NO];
1125 [[StatusWindow sharedWindow] vanish:self];
1126 [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
1129 /*************************************************************************/
1131 #pragma mark WORKSPACE NOTIFICATION HANDLERS
1132 /*************************************************************************/
1134 - (void)applicationLaunched:(NSNotification *)note
1137 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1138 ITDebugLog(@"Remote application launched.");
1139 playerRunningState = ITMTRemotePlayerRunning;
1140 [[self currentRemote] begin];
1141 [self setLatestSongIdentifier:@""];
1143 refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
1145 selector:@selector(timerUpdate)
1147 repeats:YES] retain];
1148 //[NSThread detachNewThreadSelector:@selector(startTimerInNewThread) toTarget:self withObject:nil];
1149 [self setupHotKeys];
1152 [self networkError:localException];
1156 - (void)applicationTerminated:(NSNotification *)note
1159 if (!note || [[[note userInfo] objectForKey:@"NSApplicationName"] isEqualToString:[[self currentRemote] playerFullName]]) {
1160 ITDebugLog(@"Remote application terminated.");
1161 playerRunningState = ITMTRemotePlayerNotRunning;
1162 [[self currentRemote] halt];
1163 [refreshTimer invalidate];
1164 [refreshTimer release];
1166 [self clearHotKeys];
1168 if ([df objectForKey:@"ShowPlayer"] != nil) {
1170 ITDebugLog(@"Setting up show player hot key.");
1171 hotKey = [[ITHotKey alloc] init];
1172 [hotKey setName:@"ShowPlayer"];
1173 [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"ShowPlayer"]]];
1174 [hotKey setTarget:self];
1175 [hotKey setAction:@selector(showPlayer)];
1176 [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
1180 [self networkError:localException];
1185 /*************************************************************************/
1187 #pragma mark NSApplication DELEGATE METHODS
1188 /*************************************************************************/
1190 - (void)applicationWillTerminate:(NSNotification *)note
1192 [networkController stopRemoteServerSearch];
1193 [self clearHotKeys];
1194 [[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
1198 /*************************************************************************/
1200 #pragma mark DEALLOCATION METHOD
1201 /*************************************************************************/
1205 [self applicationTerminated:nil];
1207 [statusItem release];
1208 [statusWindowController release];
1209 [menuController release];
1210 [networkController release];