Bumped to version 1.7.2. First freeware release.
[MenuTunes.git] / MainController.m
index 548ca25..7fe136e 100755 (executable)
@@ -97,7 +97,6 @@ static MainController *sharedController;
         menuController = [[MenuController alloc] init];
         df = [[NSUserDefaults standardUserDefaults] retain];
         timerUpdating = NO;
-        blinged = NO;
     }
     return self;
 }
@@ -140,6 +139,8 @@ static MainController *sharedController;
     currentRemote = [self loadRemote];
     [[self currentRemote] begin];
     
+       [[self currentRemote] currentSongElapsed];
+       
     //Turn on network stuff if needed
     networkController = [[NetworkController alloc] init];
     if ([df boolForKey:@"enableSharing"]) {
@@ -174,14 +175,6 @@ static MainController *sharedController;
                 withLength:NSSquareStatusItemLength];
     }
     
-    /*bling = [[MTBlingController alloc] init];
-    [self blingTime];
-    registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
-                             target:self
-                             selector:@selector(blingTime)
-                             userInfo:nil
-                             repeats:YES] retain];*/
-    
     NS_DURING
         if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
             [self applicationLaunched:nil];
@@ -198,17 +191,15 @@ static MainController *sharedController;
     [statusItem setImage:[NSImage imageNamed:@"MenuNormal"]];
     [statusItem setAlternateImage:[NSImage imageNamed:@"MenuInverted"]];
 
+       if ([df boolForKey:@"audioscrobblerEnabled"]) {
+               if ([PreferencesController getKeychainItemPasswordForUser:[df stringForKey:@"audioscrobblerUser"]] != nil) {
+                       [[AudioscrobblerController sharedController] attemptHandshake:NO];
+               }
+       }
+
     [networkController startRemoteServerSearch];
     [NSApp deactivate];
        [self performSelector:@selector(rawr) withObject:nil afterDelay:1.0];
-       
-       bling = [[MTBlingController alloc] init];
-    [self blingTime];
-    registerTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0
-                             target:self
-                             selector:@selector(blingTime)
-                             userInfo:nil
-                             repeats:YES] retain];
 }
 
 - (void)rawr
@@ -270,92 +261,6 @@ static MainController *sharedController;
     [pool release];
 }*/
 
-- (void)setBlingTime:(NSDate*)date
-{
-    NSMutableDictionary *globalPrefs;
-    [df synchronize];
-    globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
-    if (date) {
-        [globalPrefs setObject:date forKey:@"ITMTTrialStart"];
-        [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
-    } else {
-        [globalPrefs removeObjectForKey:@"ITMTTrialStart"];
-        [globalPrefs removeObjectForKey:@"ITMTTrialVers"];
-    }
-    [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
-    [df synchronize];
-    [globalPrefs release];
-}
-
-- (NSDate*)getBlingTime
-{
-    [df synchronize];
-    return [[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialStart"];
-}
-
-- (void)blingTime
-{
-    NSDate *now = [NSDate date];
-    if (![self blingBling]) {
-        if ( (! [self getBlingTime] ) || ([now timeIntervalSinceDate:[self getBlingTime]] < 0) ) {
-            [self setBlingTime:now];
-        } else if ([[[df persistentDomainForName:@".GlobalPreferences"] objectForKey:@"ITMTTrialVers"] intValue] < MT_CURRENT_VERSION) {
-            if ([now timeIntervalSinceDate:[self getBlingTime]] >= 345600) {
-                [self setBlingTime:[now addTimeInterval:-259200]];
-            } else {
-                NSMutableDictionary *globalPrefs;
-                [df synchronize];
-                globalPrefs = [[df persistentDomainForName:@".GlobalPreferences"] mutableCopy];
-                [globalPrefs setObject:[NSNumber numberWithInt:MT_CURRENT_VERSION] forKey:@"ITMTTrialVers"];
-                [df setPersistentDomain:globalPrefs forName:@".GlobalPreferences"];
-                [df synchronize];
-                [globalPrefs release];
-            }
-        }
-        
-        if ( ([now timeIntervalSinceDate:[self getBlingTime]] >= 604800) && (blinged != YES) ) {
-            blinged = YES;
-            [statusItem setEnabled:NO];
-                       [[ITHotKeyCenter sharedCenter] setEnabled:NO];
-            if ([refreshTimer isValid]) {
-                [refreshTimer invalidate];
-                               [refreshTimer release];
-                               refreshTimer = nil;
-            }
-            [statusWindowController showRegistrationQueryWindow];
-        }
-    } else {
-        if (blinged) {
-            [statusItem setEnabled:YES];
-            [[ITHotKeyCenter sharedCenter] setEnabled:YES];
-            if (_needsPolling && ![refreshTimer isValid]) {
-                [refreshTimer release];
-                refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
-                             target:self
-                             selector:@selector(timerUpdate)
-                             userInfo:nil
-                             repeats:YES] retain];
-            }
-            blinged = NO;
-        }
-        [self setBlingTime:nil];
-    }
-}
-
-- (void)blingNow
-{
-    [bling showPanel];
-}
-
-- (BOOL)blingBling
-{
-    if ( ! ([bling checkDone] == 2475) ) {
-        return NO;
-    } else {
-        return YES;
-    }
-}
-
 - (BOOL)songIsPlaying
 {
     NSString *identifier = nil;
@@ -404,7 +309,12 @@ static MainController *sharedController;
 
 - (void)timerUpdate
 {
-       NSString *identifier = [[self currentRemote] playerStateUniqueIdentifier];
+       NSString *identifier = nil;
+       NS_DURING
+               identifier = [[self currentRemote] playerStateUniqueIdentifier];
+       NS_HANDLER
+               [self networkError:localException];
+       NS_ENDHANDLER
        if (refreshTimer && identifier == nil) {
                if ([statusItem isEnabled]) {
                        [statusItem setToolTip:@"iTunes not responding."];
@@ -466,11 +376,12 @@ static MainController *sharedController;
                        
                        if ([df boolForKey:@"audioscrobblerEnabled"]) {
                                int length = [[self currentRemote] currentSongDuration];
-                               if (_audioscrobblerTimer) {
+                               if (length > 30) {
+                                       _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
                                        [_audioscrobblerTimer invalidate];
-                               }
-                               if (length > 0) {
-                                       _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
+                                       [_audioscrobblerTimer release];
+                                       _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:nil target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
+                                       [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
                                }
                        } else {
                                _audioscrobblerTimer = nil;
@@ -592,11 +503,12 @@ static MainController *sharedController;
                
                if ([df boolForKey:@"audioscrobblerEnabled"]) {
                        int length = [[self currentRemote] currentSongDuration];
-                       if (_audioscrobblerTimer) {
+                       if (length > 30) {
+                               _audioscrobblerInterval = ((length / 2 < 240) ? length / 2 : 240);
                                [_audioscrobblerTimer invalidate];
-                       }
-                       if (length > 0) {
-                               _audioscrobblerTimer = [NSTimer scheduledTimerWithTimeInterval:((length < 240) ? length / 2 : 120) target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
+                               [_audioscrobblerTimer release];
+                               _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
+                               [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
                        }
                } else {
                        _audioscrobblerTimer = nil;
@@ -614,20 +526,30 @@ static MainController *sharedController;
 
 - (void)submitAudioscrobblerTrack:(NSTimer *)timer
 {
+       ITDebugLog(@"Audioscrobbler: Attempting to submit current track");
+       [timer invalidate];
        if ([df boolForKey:@"audioscrobblerEnabled"]) {
                NS_DURING
-                       NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
-                       if (title && artist) {
-                               [[AudioscrobblerController sharedController] submitTrack:title
-                                                                                                                               artist:artist
-                                                                                                                               album:[[self currentRemote] currentSongAlbum]
-                                                                                                                               length:[[self currentRemote] currentSongDuration]];
+                       int elapsed = [[self currentRemote] currentSongPlayed], length = [[self currentRemote] currentSongDuration], requiredInterval = ((length / 2 < 240) ? length / 2 : 240);
+                       if ((abs(elapsed - requiredInterval) < 5) && ([[self currentRemote] playerPlayingState] == ITMTRemotePlayerPlaying)) {
+                               NSString *title = [[self currentRemote] currentSongTitle], *artist = [[self currentRemote] currentSongArtist];
+                               if (title && artist) {
+                                       ITDebugLog(@"Audioscrobbler: Submitting current track");
+                                       [[AudioscrobblerController sharedController] submitTrack:title
+                                                                                                                                       artist:artist
+                                                                                                                                       album:[[self currentRemote] currentSongAlbum]
+                                                                                                                                       length:[[self currentRemote] currentSongDuration]];
+                               }
+                       } else if (requiredInterval - elapsed > 0) {
+                               _audioscrobblerInterval = requiredInterval - elapsed;
+                               [_audioscrobblerTimer release];
+                               ITDebugLog(@"Audioscrobbler: Creating a new timer that will run in %i seconds", _audioscrobblerInterval);
+                               _audioscrobblerTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:_audioscrobblerInterval] interval:1.0 target:self selector:@selector(submitAudioscrobblerTrack:) userInfo:nil repeats:NO];
+                               [[NSRunLoop currentRunLoop] addTimer:_audioscrobblerTimer forMode:NSDefaultRunLoopMode];
                        }
                NS_HANDLER
                        [self networkError:localException];
                NS_ENDHANDLER
-               [timer invalidate];
-               _audioscrobblerTimer = nil;
        }
 }
 
@@ -950,10 +872,20 @@ static MainController *sharedController;
         [hotKey setName:@"TrackInfo"];
         [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"TrackInfo"]]];
         [hotKey setTarget:self];
-        [hotKey setAction:@selector(showCurrentTrackInfo)];
+        [hotKey setAction:@selector(showCurrentTrackInfoHotKey)];
         [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
     }
     
+       if ([df objectForKey:@"AlbumArt"] != nil) {
+        ITDebugLog(@"Setting up album art hot key.");
+        hotKey = [[ITHotKey alloc] init];
+        [hotKey setName:@"AlbumArt"];
+        [hotKey setKeyCombo:[ITKeyCombo keyComboWithPlistRepresentation:[df objectForKey:@"AlbumArt"]]];
+        [hotKey setTarget:self];
+        [hotKey setAction:@selector(showCurrentAlbumArtHotKey)];
+        [[ITHotKeyCenter sharedCenter] registerHotKey:[hotKey autorelease]];
+    }
+       
     if ([df objectForKey:@"UpcomingSongs"] != nil) {
         ITDebugLog(@"Setting up upcoming songs hot key.");
         hotKey = [[ITHotKey alloc] init];
@@ -1060,6 +992,69 @@ static MainController *sharedController;
     ITDebugLog(@"Finished setting up hot keys.");
 }
 
+- (void)showCurrentTrackInfoHotKey
+{
+       //If we're already visible and the setting says so, vanish instead of displaying again.
+       if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
+               ITDebugLog(@"Track window is already visible, hiding track window.");
+               [self invalidateStatusWindowUpdateTimer];
+               [[StatusWindow sharedWindow] vanish:nil];
+               return;
+       }
+       [self showCurrentTrackInfo];
+}
+
+- (void)showCurrentAlbumArtHotKey
+{
+       //If we're already visible and the setting says so, vanish instead of displaying again.
+       if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowAlbumArtType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
+               ITDebugLog(@"Art window is already visible, hiding track window.");
+               [[StatusWindow sharedWindow] vanish:nil];
+               return;
+       }
+       [self showCurrentAlbumArt];
+}
+
+- (void)showCurrentAlbumArt
+{
+       NSImage *art = nil;
+       NS_DURING
+               art = [[self currentRemote] currentSongAlbumArt];
+       NS_HANDLER
+               [self networkError:localException];
+       NS_ENDHANDLER
+       
+       if (art) {
+               NSSize oldSize = [art size], newSize;
+               if (oldSize.width > 300 && oldSize.height > 300) {
+                       if (oldSize.width > oldSize.height) {
+                               newSize = NSMakeSize(300, oldSize.height * (300.0f / oldSize.width));
+                       } else {
+                               newSize = NSMakeSize(oldSize.width * (300.0f / oldSize.height), 300);
+                       }
+               } else {
+                       newSize = oldSize;
+               }
+               
+               art = [[[[NSImage alloc] initWithData:[art TIFFRepresentation]] autorelease] imageScaledSmoothlyToSize:newSize];
+               
+               [statusWindowController showAlbumArtWindowWithImage:art];
+       } else {
+               NSString *string = nil;
+               NS_DURING
+                       if ([[self currentRemote] currentSongTitle]) {
+                               string = NSLocalizedString(@"noAlbumArt", @"No art for current song.");
+                       } else {
+                               string = NSLocalizedString(@"noSongPlaying", @"No song is playing.");
+                       }
+               NS_HANDLER
+                       [self networkError:localException];
+               NS_ENDHANDLER
+               //Show the no song playing window if there is no album art or no track is playing
+               [statusWindowController showAlbumArtWindowWithErrorText:string];
+       }
+}
+
 - (void)showCurrentTrackInfo
 {
     ITMTRemotePlayerSource  source      = 0;
@@ -1073,14 +1068,6 @@ static MainController *sharedController;
     int                     rating      = -1;
     int                     playCount   = -1;
        
-       //If we're already visible and the setting says so, vanish instead of displaying again.
-       if ([df boolForKey:@"ToggleTrackInfoWithHotKey"] && [statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [[StatusWindow sharedWindow] visibilityState] == ITWindowVisibleState) {
-               ITDebugLog(@"Track window is already visible, hiding track window.");
-               [self invalidateStatusWindowUpdateTimer];
-               [[StatusWindow sharedWindow] vanish:nil];
-               return;
-       }
-       
     ITDebugLog(@"Showing track info status window.");
     
     NS_DURING
@@ -1200,9 +1187,9 @@ static MainController *sharedController;
 
 - (void)updateTime:(NSTimer *)timer
 {
-       StatusWindow *sw = [StatusWindow sharedWindow];
+       StatusWindow *sw = (StatusWindow *)[StatusWindow sharedWindow];
        _timeUpdateCount++;
-       if (_timeUpdateCount < (int)[sw exitDelay] + (int)[[sw exitEffect] effectTime] + (int)[[sw entryEffect] effectTime]) {
+       if ([statusWindowController currentStatusWindowType] == StatusWindowTrackInfoType && [sw visibilityState] != ITWindowHiddenState) {
                NSString *time = nil, *length;
                NS_DURING
                        length = [[self currentRemote] currentSongLength];
@@ -1449,24 +1436,6 @@ static MainController *sharedController;
        }
 }
 
-- (void)registerNowOK
-{
-    [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
-    [[StatusWindow sharedWindow] vanish:self];
-    [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
-
-    [self blingNow];
-}
-
-- (void)registerNowCancel
-{
-    [(StatusWindow *)[StatusWindow sharedWindow] setLocked:NO];
-    [[StatusWindow sharedWindow] vanish:self];
-    [[StatusWindow sharedWindow] setIgnoresMouseEvents:YES];
-
-    [NSApp terminate:self];
-}
-
 /*************************************************************************/
 #pragma mark -
 #pragma mark NETWORK HANDLERS
@@ -1500,12 +1469,14 @@ static MainController *sharedController;
                        if (refreshTimer) {
                                [refreshTimer invalidate];
                        }
-                       refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
-                                                                        target:self
-                                                                        selector:@selector(timerUpdate)
-                                                                        userInfo:nil
-                                                                        repeats:YES] retain];
                }
+               
+               refreshTimer = [[NSTimer scheduledTimerWithTimeInterval:([networkController isConnectedToServer] ? 10.0 : 0.5)
+                                                                target:self
+                                                                selector:@selector(timerUpdate)
+                                                                userInfo:nil
+                                                                repeats:YES] retain];
+               
         [self timerUpdate];
         ITDebugLog(@"Connection successful.");
         return 1;
@@ -1530,10 +1501,12 @@ static MainController *sharedController;
     [networkController disconnect];
     
     if ([[self currentRemote] playerRunningState] == ITMTRemotePlayerRunning) {
+               refreshTimer = nil;
         [self applicationLaunched:nil];
     } else {
         [self applicationTerminated:nil];
     }
+       
     if (refreshTimer) {
                [self timerUpdate];
        };
@@ -1710,7 +1683,7 @@ static MainController *sharedController;
 - (void)applicationDidBecomeActive:(NSNotification *)note
 {
        //This appears to not work in 10.4
-       if (_open && !blinged && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
+       if (_open && ![[ITAboutWindowController sharedController] isVisible] && ![NSApp mainWindow] && ([[StatusWindow sharedWindow] exitMode] == ITTransientStatusWindowExitAfterDelay)) {
                [[MainController sharedController] showPreferences];
        }
 }
@@ -1723,7 +1696,6 @@ static MainController *sharedController;
 - (void)dealloc
 {
     [self applicationTerminated:nil];
-    [bling release];
     [statusItem release];
     [statusWindowController release];
     [menuController release];