From 58fa11ce04ac8e4e991aa9ceac601bab6a230d54 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 4 Jun 2022 13:14:01 -0700 Subject: [PATCH] Add standard user driver APIs for gentle scheduled update reminders (#2122) * Log warning if gentle reminders aren't implemented for background app * Don't let background running app steal focus from other apps except at launch * Don't set update alert window level to floating for background apps * Show update alert in back for currently active background apps * Disable warnings for direct ivar access * Center update status window to last update alert window shown * Activate app from user initiated checks if it's not active * Set systemHasBeenIdle to YES only if the app isn't preventing display sleep * Don't make status window key if update alert wasn't key window --- Configurations/ConfigCommon.xcconfig | 2 +- .../InstallerProgress/ShowInstallerProgress.m | 2 +- Sparkle/SPUStandardUserDriver.m | 383 ++++++++++++++---- Sparkle/SPUStandardUserDriverDelegate.h | 108 ++++- Sparkle/SPUUpdater.m | 11 + Sparkle/SUStatusController.h | 2 +- Sparkle/SUStatusController.m | 18 +- Sparkle/SUUpdateAlert.h | 2 +- Sparkle/SUUpdateAlert.m | 29 +- 9 files changed, 456 insertions(+), 101 deletions(-) diff --git a/Configurations/ConfigCommon.xcconfig b/Configurations/ConfigCommon.xcconfig index f64e7ca1..8895756a 100644 --- a/Configurations/ConfigCommon.xcconfig +++ b/Configurations/ConfigCommon.xcconfig @@ -118,4 +118,4 @@ GCC_WARN_UNUSED_VARIABLE = YES WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties // Turn on all warnings, then disable a few which are almost impossible to avoid -WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso $(WARNING_CFLAGS_EXTRA) +WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access $(WARNING_CFLAGS_EXTRA) diff --git a/Sparkle/InstallerProgress/ShowInstallerProgress.m b/Sparkle/InstallerProgress/ShowInstallerProgress.m index 9cbce5a9..cf9a3fc6 100644 --- a/Sparkle/InstallerProgress/ShowInstallerProgress.m +++ b/Sparkle/InstallerProgress/ShowInstallerProgress.m @@ -24,7 +24,7 @@ - (void)installerProgressShouldDisplayWithHost:(SUHost *)host { - self.statusController = [[SUStatusController alloc] initWithHost:host minimizable:NO]; + self.statusController = [[SUStatusController alloc] initWithHost:host centerPointValue:nil minimizable:NO]; [self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:nil isDefault:NO]; [self.statusController beginActionWithTitle:SULocalizedString(@"Installing update…", @"") maxProgressValue:0 statusText:@""]; diff --git a/Sparkle/SPUStandardUserDriver.m b/Sparkle/SPUStandardUserDriver.m index 0a9debfd..f1e67a54 100644 --- a/Sparkle/SPUStandardUserDriver.m +++ b/Sparkle/SPUStandardUserDriver.m @@ -22,13 +22,14 @@ #import "SPUUserUpdateState.h" #import "SUErrors.h" #import "SPUInstallationType.h" +#import "SULog.h" #include +#include +#import #import -// The amount of time we wait until the app becomes inactive and active again to show an update prompt at an opportune time. -static const NSTimeInterval SUScheduledUpdateActiveAppLeewayInterval = DEBUG ? 60.0 * 2 : 30 * 60.0; // The amount of time the app is allowed to be idle for us to consider showing an update prompt right away when the app is active static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 30.0 : 5 * 60.0; @@ -53,13 +54,19 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 @property (nonatomic) uint64_t expectedContentLength; @property (nonatomic) uint64_t bytesDownloaded; -@property (nonatomic, readonly) uint64_t initializationTime; - -@property (nonatomic) BOOL regularApplicationUpdate; - @end @implementation SPUStandardUserDriver +{ + mach_timebase_info_data_t _timebaseInfo; + double _initializationTime; + id _applicationBecameActiveAfterUpdateAlertBecameKeyObserver; + NSValue *_updateAlertWindowFrameValue; + BOOL _updateAlertWindowWasInactive; + BOOL _loggedGentleUpdateReminderWarning; + BOOL _regularApplicationUpdate; + BOOL _updateReceivedUserAttention; +} @synthesize host = _host; @synthesize oldHostName = _oldHostName; @@ -73,8 +80,6 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 @synthesize permissionPrompt = _permissionPrompt; @synthesize expectedContentLength = _expectedContentLength; @synthesize bytesDownloaded = _bytesDownloaded; -@synthesize initializationTime = _initializationTime; -@synthesize regularApplicationUpdate = _regularApplicationUpdate; #pragma mark Birth @@ -87,13 +92,33 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 _oldHostBundleURL = hostBundle.bundleURL; _delegate = delegate; - if (@available(macOS 10.12, *)) { - _initializationTime = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + kern_return_t timebaseInfoResult = mach_timebase_info(&_timebaseInfo); + if (timebaseInfoResult != KERN_SUCCESS) { + SULog(SULogLevelError, @"Error: failed to fill mach_timebase_info() with error %d", timebaseInfoResult); + + _timebaseInfo.numer = 0; + _timebaseInfo.denom = 0; + } else { + [self _resetInitializationTime]; } } return self; } +- (double)currentTime +{ + if (_timebaseInfo.denom > 0) { + return (1.0 * mach_absolute_time() * _timebaseInfo.numer / _timebaseInfo.denom); + } else { + return 0.0; + } +} + +- (void)_resetInitializationTime +{ + _initializationTime = [self currentTime]; +} + #pragma mark Update Permission - (void)showUpdatePermissionRequest:(SPUUpdatePermissionRequest *)request reply:(void (^)(SUUpdatePermissionResponse *))reply @@ -106,6 +131,8 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 __weak __typeof__(self) weakSelf = self; self.permissionPrompt = [[SUUpdatePermissionPrompt alloc] initPromptWithHost:self.host request:request reply:^(SUUpdatePermissionResponse *response) { + [weakSelf _resetInitializationTime]; + reply(response); weakSelf.permissionPrompt = nil; }]; @@ -115,52 +142,171 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 #pragma mark Update Alert Focus -- (void)setUpActiveUpdateAlertRequestingFocus:(BOOL)requestingFocus +// This private method is used by SPUUpdater when scheduling for update checks +- (void)_logGentleScheduledUpdateReminderWarningIfNeeded +{ + id delegate = self.delegate; + if (!_loggedGentleUpdateReminderWarning && (![delegate respondsToSelector:@selector(supportsGentleScheduledUpdateReminders)] || !delegate.supportsGentleScheduledUpdateReminders)) { + BOOL isBackgroundApp = [SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]; + if (isBackgroundApp) { + SULog(SULogLevelError, @"Warning: Background app automatically schedules for update checks but does not implement gentle reminders. As a result, users may not take notice to update alerts that show up in the background. Please visit https://sparkle-project.org/documentation/gentle-reminders for more information. This warning will only be logged once."); + + _loggedGentleUpdateReminderWarning = YES; + } + } +} + +// updateItem should be non-nil when showing an update for first time for scheduled updates +// If appcastItem is != nil, then state must be != nil +- (void)setUpActiveUpdateAlertForScheduledUpdate:(SUAppcastItem * _Nullable)updateItem state:(SPUUserUpdateState * _Nullable)state { // Make sure the window is loaded in any case [self.activeUpdateAlert window]; - [self _removeScheduledUpdateAlertAfterDelay]; + [self _removeApplicationBecomeActiveObserver]; - // If the app is a menubar app or the like, we need to focus it first and alter the - // update prompt to behave like a normal window. Otherwise if the window were hidden - // there may be no way for the application to be activated to make it visible again. - BOOL isBackgroundApp = [SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]; - if (isBackgroundApp) { - [NSApp activateIgnoringOtherApps:YES]; - - [self.activeUpdateAlert showWindow:nil]; - [self.activeUpdateAlert setInstallButtonFocus:requestingFocus]; - } else { - // Only show the update alert if the app is active and if it's an an opportune time; otherwise, we'll wait until the app becomes active and the time is right - BOOL observeApplicationActiveState; - if ([NSApp isActive]) { - // If the system has been inactive for several minutes, allow the update alert to show up immediately. We assume it's likely the user isn't at their computer in this case. - CFTimeInterval timeSinceLastEvent; - if (!requestingFocus) { - timeSinceLastEvent = CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateHIDSystemState, kCGAnyInputEventType); - } else { - timeSinceLastEvent = 0; - } - - if (requestingFocus || timeSinceLastEvent >= SUScheduledUpdateIdleEventLeewayInterval) { - [self.activeUpdateAlert showWindow:nil]; - [self.activeUpdateAlert setInstallButtonFocus:YES]; - - observeApplicationActiveState = NO; - } else { - // If the application does not become inactive and active again within a threshold, - // we will give up and show the update - [self performSelector:@selector(showScheduledUpdateAlertAfterDelay) withObject:nil afterDelay:SUScheduledUpdateActiveAppLeewayInterval]; - observeApplicationActiveState = YES; - } - } else { - // We will show the update alert when the user comes back to the app - observeApplicationActiveState = YES; + if (updateItem == nil) { + // This is a user initiated check or a check to bring the already shown update back in focus + if (![NSApp isActive]) { + // If the user initiated an update check, we should make the app active, + // regardless if it's a background running app or not + [NSApp activateIgnoringOtherApps:YES]; } - if (observeApplicationActiveState) { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; + [self.activeUpdateAlert showWindow:nil]; + [self.activeUpdateAlert setInstallButtonFocus:YES]; + } else { + // Handle scheduled update check + uint64_t timeElapsedSinceInitialization = (uint64_t)([self currentTime] - _initializationTime); + + // Give scheduled update alerts priority if 3 or less seconds have passed since initialization + BOOL appNearUpdaterInitialization = (timeElapsedSinceInitialization <= 3000000000ULL); + + // We will always show an update alert at the right time + [self.activeUpdateAlert setInstallButtonFocus:YES]; + + // If the delegate doesn't override our behavior: + // For regular applications, only show the update alert if the app is active and if it's an an opportune time, otherwise, we'll wait until the app becomes active again. + // For background applications, if the app is active, we will show the update window ordered back. + // If the app is inactive, we'll show the update alert in the background behind other running apps + // But we are near app launch, we will activate the app and show the alert as key + BOOL backgroundApp = [SUApplicationInfo isBackgroundApplication:NSApp]; + BOOL driverShowingUpdateNow; + BOOL immediateFocus; + BOOL showingUpdateInBack; + BOOL activatingApp; + if ([NSApp isActive]) { + BOOL systemHasBeenIdle; + { + // If the system has been inactive for several minutes, allow the update alert to show up immediately. We assume it's likely the user isn't at their computer in this case. + // Note this is not done for background running applications. + CFTimeInterval timeSinceLastEvent; + if (!appNearUpdaterInitialization && !backgroundApp) { + timeSinceLastEvent = CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateHIDSystemState, kCGAnyInputEventType); + + if (timeSinceLastEvent >= SUScheduledUpdateIdleEventLeewayInterval) { + // Make sure there's no active power management assertions preventing + // the display from sleeping by the current application. + // If there is, then the app may still actively be in use + CFDictionaryRef cfAssertions = NULL; + if (IOPMCopyAssertionsByProcess(&cfAssertions) == kIOReturnSuccess) { + NSDictionary *> *> *assertions = CFBridgingRelease(cfAssertions); + + pid_t currentProcessIdentifier = NSRunningApplication.currentApplication.processIdentifier; + + NSNumber *processIdentifierKey = @(currentProcessIdentifier); + NSArray *> *currentProcessAssertions = assertions[processIdentifierKey]; + + BOOL foundNoDisplaySleepAssertion = NO; + for (NSDictionary *assertion in currentProcessAssertions) { + NSString *assertionType = assertion[(NSString *)kIOPMAssertionTypeKey]; + NSNumber *assertionLevel = assertion[(NSString *)kIOPMAssertionLevelKey]; + if ([assertionType isEqualToString:(NSString *)kIOPMAssertionTypeNoDisplaySleep] && [assertionLevel isEqual:@(kIOPMAssertionLevelOn)]) { + + foundNoDisplaySleepAssertion = YES; + break; + } + } + + systemHasBeenIdle = !foundNoDisplaySleepAssertion; + } else { + systemHasBeenIdle = NO; + } + } else { + systemHasBeenIdle = NO; + } + } else { + systemHasBeenIdle = NO; + } + } + + if (appNearUpdaterInitialization || systemHasBeenIdle) { + driverShowingUpdateNow = YES; + immediateFocus = YES; + showingUpdateInBack = NO; + activatingApp = backgroundApp; + } else { + driverShowingUpdateNow = backgroundApp; + immediateFocus = NO; + // If there is a key window active in the app, show the update alert behind other windows + showingUpdateInBack = backgroundApp && ([NSApp keyWindow] != nil); + activatingApp = NO; + } + } else { + // For regular applications, we will show the update alert when the user comes back to the app + // For background applications, we will show the update alert right away but in the background, + // unless focus is requested + if (!backgroundApp) { + driverShowingUpdateNow = NO; + immediateFocus = NO; + showingUpdateInBack = NO; + activatingApp = NO; + } else { + driverShowingUpdateNow = YES; + immediateFocus = appNearUpdaterInitialization; + showingUpdateInBack = NO; + activatingApp = appNearUpdaterInitialization; + } + } + + BOOL handleShowingUpdates; + if ([self.delegate respondsToSelector:@selector(standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:)]) { + handleShowingUpdates = [self.delegate standardUserDriverShouldHandleShowingScheduledUpdate:(SUAppcastItem * _Nonnull)updateItem andInImmediateFocus:immediateFocus]; + } else { + handleShowingUpdates = YES; + } + + if (!handleShowingUpdates) { + // Delay a runloop cycle to make sure the update can properly be checked + SPUStandardUserDriver *__weak weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + id delegate = weakSelf.delegate; + if ([delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [delegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; + } else { + SULog(SULogLevelError, @"Error: Delegate <%@> is handling showing scheduled update but does not implement %@", delegate, NSStringFromSelector(@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:))); + } + }); + } else { + // The update will be shown, but not necessarily immediately if !driverShowingUpdateNow + // It is useful to post this early in case the delegate wants to post a notification + if ([self.delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [self.delegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; + } + + if (!driverShowingUpdateNow) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; + } else { + if (activatingApp) { + [NSApp activateIgnoringOtherApps:YES]; + } + + if (showingUpdateInBack) { + [self.activeUpdateAlert.window orderBack:nil]; + } else { + [self.activeUpdateAlert showWindow:nil]; + } + } } } } @@ -170,21 +316,8 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp]; } -- (void)_removeScheduledUpdateAlertAfterDelay -{ - [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(showScheduledUpdateAlertAfterDelay) object:nil]; -} - -- (void)showScheduledUpdateAlertAfterDelay -{ - [self.activeUpdateAlert showWindow:nil]; - [self.activeUpdateAlert setInstallButtonFocus:NO]; -} - - (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification { - [self _removeScheduledUpdateAlertAfterDelay]; - [self.activeUpdateAlert showWindow:nil]; [self.activeUpdateAlert setInstallButtonFocus:YES]; @@ -204,29 +337,84 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 versionDisplayer = [self.delegate standardUserDriverRequestsVersionDisplayer]; } + BOOL needsToObserveUserAttention = [self.delegate respondsToSelector:@selector(standardUserDriverDidReceiveUserAttentionForUpdate:)]; + __weak SPUStandardUserDriver *weakSelf = self; - self.activeUpdateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem state:state host:self.host versionDisplayer:versionDisplayer completionBlock:^(SPUUserUpdateChoice choice) { + __weak id weakDelegate = self.delegate; + self.activeUpdateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem state:state host:self.host versionDisplayer:versionDisplayer completionBlock:^(SPUUserUpdateChoice choice, NSRect windowFrame, BOOL wasKeyWindow) { reply(choice); - weakSelf.activeUpdateAlert = nil; + + SPUStandardUserDriver *strongSelf = weakSelf; + + if (strongSelf != nil) { + if (needsToObserveUserAttention && !strongSelf->_updateReceivedUserAttention) { + strongSelf->_updateReceivedUserAttention = YES; + + id strongDelegate = weakDelegate; + // needsToObserveUserAttention already checks delegate responds to this selector + [strongDelegate standardUserDriverDidReceiveUserAttentionForUpdate:appcastItem]; + } + + // Record the window frame of the update alert right before we deallocate it + // So we can center future status window to where the update alert last was. + // Also record if the window was inactive at the time a response was made + // (the window may not be key if the window e.g. holds command while clicking on a response button) + strongSelf->_updateAlertWindowFrameValue = [NSValue valueWithRect:windowFrame]; + strongSelf->_updateAlertWindowWasInactive = !wasKeyWindow; + + strongSelf.activeUpdateAlert = nil; + } + } didBecomeKeyBlock:^{ + if (!needsToObserveUserAttention) { + return; + } + + if ([NSApp isActive]) { + SPUStandardUserDriver *strongSelf = weakSelf; + if (strongSelf != nil && !strongSelf->_updateReceivedUserAttention) { + strongSelf->_updateReceivedUserAttention = YES; + + id strongDelegate = weakDelegate; + // needsToObserveUserAttention already checks delegate responds to this selector + [strongDelegate standardUserDriverDidReceiveUserAttentionForUpdate:appcastItem]; + } + } else { + // We need to listen for when the app becomes active again, and then test if the window alert + // is still key. if it is, let the delegate know. Remove the observation after that. + + SPUStandardUserDriver *strongSelfOuter = weakSelf; + if (strongSelfOuter != nil && strongSelfOuter->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver == nil) { + strongSelfOuter->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidBecomeActiveNotification object:NSApp queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull __unused note) { + SPUStandardUserDriver *strongSelf = weakSelf; + if (strongSelf != nil) { + if (!strongSelf->_updateReceivedUserAttention && [strongSelf.activeUpdateAlert.window isKeyWindow]) { + strongSelf->_updateReceivedUserAttention = YES; + + id strongDelegate = weakDelegate; + // needsToObserveUserAttention already checks delegate responds to this selector + [strongDelegate standardUserDriverDidReceiveUserAttentionForUpdate:appcastItem]; + } + + if (strongSelf->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver != nil) { + [[NSNotificationCenter defaultCenter] removeObserver:strongSelf->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver]; + + strongSelf->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver = nil; + } + } + }]; + } + } }]; - self.regularApplicationUpdate = [appcastItem.installationType isEqualToString:SPUInstallationTypeApplication]; + _regularApplicationUpdate = [appcastItem.installationType isEqualToString:SPUInstallationTypeApplication]; - BOOL allowInstallButtonFocus; - if (state.userInitiated) { - allowInstallButtonFocus = YES; - } else { - if (@available(macOS 10.12, *)) { - uint64_t currentTime = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); - uint64_t timeElapsedSinceInitialization = currentTime - self.initializationTime; - - // Allow the install button to focus if 3 or less seconds have passed since initialization - allowInstallButtonFocus = (timeElapsedSinceInitialization <= 3000000000ULL); - } else { - allowInstallButtonFocus = NO; - } + // For user initiated checks, let the delegate know we'll be showing an update + // For scheduled checks, -setUpActiveUpdateAlertForUpdate:state: below will handle this + if (state.userInitiated && [self.delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [self.delegate standardUserDriverWillHandleShowingUpdate:YES forUpdate:appcastItem state:state]; } - [self setUpActiveUpdateAlertRequestingFocus:allowInstallButtonFocus]; + + [self setUpActiveUpdateAlertForScheduledUpdate:(state.userInitiated ? nil : appcastItem) state:state]; } - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData @@ -249,7 +437,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 - (void)showUpdateInFocus { if (self.activeUpdateAlert != nil) { - [self setUpActiveUpdateAlertRequestingFocus:YES]; + [self setUpActiveUpdateAlertForScheduledUpdate:nil state:nil]; } else if (self.permissionPrompt != nil) { [self.permissionPrompt showWindow:nil]; } else if (self.statusController != nil) { @@ -291,7 +479,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 self.cancellation = cancellation; - self.checkingController = [[SUStatusController alloc] initWithHost:self.host minimizable:NO]; + self.checkingController = [[SUStatusController alloc] initWithHost:self.host centerPointValue:nil minimizable:NO]; [[self.checkingController window] center]; // Force the checking controller to load its window. [self.checkingController beginActionWithTitle:SULocalizedString(@"Checking for updates…", nil) maxProgressValue:0.0 statusText:nil]; [self.checkingController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelCheckForUpdates:) isDefault:NO]; @@ -441,7 +629,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // We will make the status window minimizable for regular app updates which are often // quick and atomic to install on quit. But we won't do this for package based updates. BOOL minimizable; - if (!self.regularApplicationUpdate) { + if (!_regularApplicationUpdate) { minimizable = NO; } else if ([self.delegate respondsToSelector:@selector(standardUserDriverAllowsMinimizableStatusWindow)]) { minimizable = [self.delegate standardUserDriverAllowsMinimizableStatusWindow]; @@ -449,8 +637,23 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 minimizable = YES; } - self.statusController = [[SUStatusController alloc] initWithHost:self.host minimizable:minimizable]; - [self.statusController showWindow:self]; + NSValue *centerPointValue; + if (_updateAlertWindowFrameValue != nil) { + NSRect updateAlertFrame = _updateAlertWindowFrameValue.rectValue; + NSPoint centerPoint = NSMakePoint(updateAlertFrame.origin.x + updateAlertFrame.size.width / 2.0, updateAlertFrame.origin.y + updateAlertFrame.size.height / 2.0); + + centerPointValue = [NSValue valueWithPoint:centerPoint]; + } else { + centerPointValue = nil; + } + + self.statusController = [[SUStatusController alloc] initWithHost:self.host centerPointValue:centerPointValue minimizable:minimizable]; + + if (_updateAlertWindowWasInactive) { + [self.statusController.window orderFront:nil]; + } else { + [self.statusController showWindow:self]; + } } } @@ -588,6 +791,17 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); + id delegate = self.delegate; + if ([delegate respondsToSelector:@selector(standardUserDriverWillFinishUpdateSession)]) { + [delegate standardUserDriverWillFinishUpdateSession]; + } + + if (_applicationBecameActiveAfterUpdateAlertBecameKeyObserver != nil) { + [[NSNotificationCenter defaultCenter] removeObserver:_applicationBecameActiveAfterUpdateAlertBecameKeyObserver]; + _applicationBecameActiveAfterUpdateAlertBecameKeyObserver = nil; + } + + _updateReceivedUserAttention = NO; self.installUpdateHandler = nil; self.cancellation = nil; @@ -609,7 +823,6 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } [self _removeApplicationBecomeActiveObserver]; - [self _removeScheduledUpdateAlertAfterDelay]; } @end diff --git a/Sparkle/SPUStandardUserDriverDelegate.h b/Sparkle/SPUStandardUserDriverDelegate.h index 6cef7856..3cf9e068 100644 --- a/Sparkle/SPUStandardUserDriverDelegate.h +++ b/Sparkle/SPUStandardUserDriverDelegate.h @@ -16,7 +16,11 @@ #endif #import +NS_ASSUME_NONNULL_BEGIN + @protocol SUVersionDisplay; +@class SUAppcastItem; +@class SPUUserUpdateState; /** A protocol for Sparkle's standard user driver's delegate @@ -59,7 +63,7 @@ SU_EXPORT @protocol SPUStandardUserDriverDelegate @param item The appcast item corresponding to the latest version available. */ -- (void)standardUserDriverShowVersionHistoryForAppcastItem:(SUAppcastItem *_Nonnull)item; +- (void)standardUserDriverShowVersionHistoryForAppcastItem:(SUAppcastItem *)item; /** Specifies whether or not the download, extraction, and installing status windows allows to be minimized. @@ -71,4 +75,106 @@ SU_EXPORT @protocol SPUStandardUserDriverDelegate */ - (BOOL)standardUserDriverAllowsMinimizableStatusWindow; +/** + Declares whether or not gentle scheduled update reminders are supported. + + The delegate may implement scheduled update reminders that are presented in a gentle manner by implementing one or both of: + `-standardUserDriverWillShowUpdate:state:` and `-standardUserDriverShouldHandleShowingUpdateAlertForScheduledUpdate:andInImmediateFocus:` + + Visit https://sparkle-project.org/documentation/gentle-reminders for more information and examples. + + @return @c YES if gentle scheduled update reminders are implemented by standard user driver delegate, otherwise @c NO (default). + */ +@property (nonatomic, readonly) BOOL supportsGentleScheduledUpdateReminders; + +/** + Specifies if the standard user driver should handle showing a new scheduled update, or if its delegate should handle showing the update instead. + + If you implement this method and return @c NO the delegate is then responsible for showing the update, + which must be implemented and done in `-standardUserDriverWillHandleShowingUpdate:forUpdate:state:` + The motivation for the delegate being responsible for showing updates is to override Sparkle's default behavior + and add gentle reminders for new updates. + + Returning @c YES is the default behavior and allows the standard user driver to handle showing the update. + + If the standard user driver handles showing the update, `immediateFocus` reflects whether or not it will show the update in immediate and utmost focus. + The standard user driver may choose to show the update in immediate and utmost focus when the app was launched recently + or the system has been idle for some time. If `immediateFocus` is @c NO the standard user driver may want to + defer showing the update until the user comes back to the app. + For background running applications, when `immediateFocus` is @c NO the standard user driver will always want to show + the update alert immediately, but behind other running applications or behind the app's own windows if it's currently active. + + There should be no side effects made when implementing this method so you should just return @c YES or @c NO + You will also want to implement `-standardUserDriverWillHandleShowingUpdate:forUpdate:state:` for adding additional update reminders. + + This method is not called for user-initiated update checks. The standard user driver always handles those. + + Visit https://sparkle-project.org/documentation/gentle-reminders for more information and examples. + + @param update The update the standard user driver should show. + @param immediateFocus If @c immediateFocus is @c YES, then the standard user driver proposes to show the update in immediate and utmost focus. See discussion for more details. + + @return @c YES if the standard user should handle showing the scheduled update (default behavior), otherwise @c NO if the delegate handles showing it. + */ +- (BOOL)standardUserDriverShouldHandleShowingScheduledUpdate:(SUAppcastItem *)update andInImmediateFocus:(BOOL)immediateFocus; + +/** + Called before an update will be shown to the user. + + If the standard user driver handles showing the update, `handleShowingUpdate` will be @c YES + In this case, if the update is not user initiated (`state.userInitiated` is @c NO) then the standard user driver may defer showing the update, + and it may be shown when the user comes back to the app. + For a background (dockless) running app, the update alert will always show up immediately but behind other running applications or behind + its own windows if the app is currently active. + + If the delegate declared it handles showing the update by returning @c NO in `-standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:` + then the delegate should handle showing update reminders in this method, or at some later point. + In this case, `handleShowingUpdate` will be @c NO. + To bring the update alert in focus, you may call `-[SPUStandardUpdateController checkForUpdates:]` or `-[SPUUpdater checkForUpdates]` + You may want to show additional UI indicators in your application that will show this update in focus + and want to dismiss additional UI indicators in `-standardUserDriverWillFinishUpdateSession` or `-standardUserDriverDidReceiveUserAttentionForUpdate:` + + If `state.userInitiated` is @c YES then the standard user driver always handles showing the new update and `handleShowingUpdate` will be @c YES. + In this case, it may still be useful for the delegate to intercept this method right before a new update will be shown. + + This method is not called when bringing an update that has already been presented back in focus. + + Visit https://sparkle-project.org/documentation/gentle-reminders for more information and examples. + + @param handleShowingUpdate @c YES if the standard user driver handles showing the update, otherwise @c NO if the delegate handles showing the update. + @param update The update that will be shown. + @param state The user state of the update which includes if the update check was initiated by the user. + */ +- (void)standardUserDriverWillHandleShowingUpdate:(BOOL)handleShowingUpdate forUpdate:(SUAppcastItem *)update state:(SPUUserUpdateState *)state; + +/** + Called when a new update first receives attention from the user. + + This occurs either when the user first brings the update alert in utmost focus or when the user makes a choice to install an update or dismiss/skip it. + + This may be useful to intercept for dismissing custom attention-based UI indicators (e.g, user notifications) introduced when implementing + `-standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:` + + For custom UI indicators that need to still be on screen after the user has started to install an update, please see `standardUserDriverWillFinishUpdateSession`. + + @param update The new update that the user gave attention to. + */ +- (void)standardUserDriverDidReceiveUserAttentionForUpdate:(SUAppcastItem *)update; + +/** + Called before the standard user driver session will finish its current update session. + + This may occur after the user has dismissed / skipped a new update or after an update error has occurred. + For updaters updating external/other bundles, this may also be called after an update has been successfully installed. + + This may be useful to intercept for dismissing custom UI indicators introduced when implementing + `-standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:` + + For UI indicators that need to be dismissed when the user has given attention to a new update alert, + please see `standardUserDriverDidReceiveUserAttentionForUpdate:` + */ +- (void)standardUserDriverWillFinishUpdateSession; + @end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUUpdater.m b/Sparkle/SPUUpdater.m index a315827e..58015ca2 100644 --- a/Sparkle/SPUUpdater.m +++ b/Sparkle/SPUUpdater.m @@ -36,6 +36,12 @@ #include "AppKitPrevention.h" +@interface NSObject (SPUStandardUserDriverPrivate) + +- (void)_logGentleScheduledUpdateReminderWarningIfNeeded; + +@end + NSString *const SUUpdaterDidFinishLoadingAppCastNotification = @"SUUpdaterDidFinishLoadingAppCastNotification"; NSString *const SUUpdaterDidFindValidUpdateNotification = @"SUUpdaterDidFindValidUpdateNotification"; NSString *const SUUpdaterDidNotFindUpdateNotification = @"SUUpdaterDidNotFindUpdateNotification"; @@ -510,6 +516,11 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification if ([self.delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) { [self.delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck]; } + + if ([self.userDriver respondsToSelector:@selector(_logGentleScheduledUpdateReminderWarningIfNeeded)]) { + [(NSObject *)self.userDriver _logGentleScheduledUpdateReminderWarningIfNeeded]; + } + [self.updaterTimer startAndFireAfterDelay:delayUntilCheck]; } else { // We're overdue! Run one now. diff --git a/Sparkle/SUStatusController.h b/Sparkle/SUStatusController.h index f7fc1c83..ab51b449 100644 --- a/Sparkle/SUStatusController.h +++ b/Sparkle/SUStatusController.h @@ -24,7 +24,7 @@ @property (nonatomic) double maxProgressValue; @property (getter=isButtonEnabled) BOOL buttonEnabled; -- (instancetype)initWithHost:(SUHost *)host minimizable:(BOOL)minimizable; +- (instancetype)initWithHost:(SUHost *)host centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable; // Pass 0 for the max progress value to get an indeterminate progress bar. // Pass nil for the status text to not show it. diff --git a/Sparkle/SUStatusController.m b/Sparkle/SUStatusController.m index b3c6c256..9b205a69 100644 --- a/Sparkle/SUStatusController.m +++ b/Sparkle/SUStatusController.m @@ -25,6 +25,10 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL @end @implementation SUStatusController +{ + NSValue *_centerPointValue; +} + @synthesize progressValue; @synthesize maxProgressValue; @synthesize statusText; @@ -37,12 +41,13 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL @synthesize touchBarButton; @synthesize minimizable = _minimizable; -- (instancetype)initWithHost:(SUHost *)aHost minimizable:(BOOL)minimizable +- (instancetype)initWithHost:(SUHost *)aHost centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable { self = [super initWithWindowNibName:@"SUStatus" owner:self]; if (self) { self.host = aHost; + _centerPointValue = centerPointValue; _minimizable = minimizable; [self setShouldCascadeWindows:NO]; } @@ -53,8 +58,15 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL - (void)windowDidLoad { - [[self window] center]; - [[self window] setFrameAutosaveName:@"SUStatusFrame"]; + NSRect windowFrame = self.window.frame; + + if (_centerPointValue != nil) { + NSPoint centerPoint = _centerPointValue.pointValue; + [self.window setFrameOrigin:NSMakePoint(centerPoint.x - windowFrame.size.width / 2.0, centerPoint.y - windowFrame.size.height / 2.0)]; + } else { + [self.window center]; + } + if (self.minimizable) { self.window.styleMask |= NSWindowStyleMaskMiniaturizable; } diff --git a/Sparkle/SUUpdateAlert.h b/Sparkle/SUUpdateAlert.h index b89e23f9..bb124a13 100644 --- a/Sparkle/SUUpdateAlert.h +++ b/Sparkle/SUUpdateAlert.h @@ -22,7 +22,7 @@ @property (nonatomic, weak, readonly) id versionDisplayer; -- (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id )aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice))block; +- (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id )aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice, NSRect, BOOL))completionBlock didBecomeKeyBlock:(void (^)(void))didBecomeKeyBlock; - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData; - (void)showReleaseNotesFailedToDownload; diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 6c785d36..95ad95bb 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -37,7 +37,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @property (strong) SUAppcastItem *updateItem; @property (strong) SUHost *host; @property (nonatomic) BOOL allowsAutomaticUpdates; -@property (nonatomic, copy, nullable) void(^completionBlock)(SPUUserUpdateChoice); +@property (nonatomic, copy, nullable) void(^completionBlock)(SPUUserUpdateChoice, NSRect, BOOL); @property (nonatomic) SPUUserUpdateState *state; @property (strong) NSProgressIndicator *releaseNotesSpinner; @@ -58,6 +58,9 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @end @implementation SUUpdateAlert +{ + void (^_didBecomeKeyBlock)(void); +} @synthesize completionBlock = _completionBlock; @synthesize state = _state; @@ -82,7 +85,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @synthesize webView = _webView; -- (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id )aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice))block +- (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id )aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice, NSRect, BOOL))completionBlock didBecomeKeyBlock:(void (^)(void))didBecomeKeyBlock { self = [super initWithWindowNibName:@"SUUpdateAlert"]; if (self != nil) { @@ -91,11 +94,14 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE versionDisplayer = aVersionDisplayer; _state = state; - _completionBlock = [block copy]; + _completionBlock = [completionBlock copy]; + _didBecomeKeyBlock = [didBecomeKeyBlock copy]; SPUUpdaterSettings *updaterSettings = [[SPUUpdaterSettings alloc] initWithHostBundle:host.bundle]; _allowsAutomaticUpdates = updaterSettings.allowsAutomaticUpdates && updaterSettings.automaticallyChecksForUpdates && !item.informationOnlyUpdate; [self setShouldCascadeWindows:NO]; + } else { + assert(false); } return self; } @@ -115,10 +121,14 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE { [self.webView stopLoading]; [self.webView.view removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. + + BOOL wasKeyWindow = self.window.keyWindow; + NSRect windowFrame = self.window.frame; + [self close]; if (self.completionBlock != nil) { - self.completionBlock(choice); + self.completionBlock(choice, windowFrame, wasKeyWindow); self.completionBlock = nil; } } @@ -312,10 +322,6 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE [self.window setFrameAutosaveName: showReleaseNotes ? @"SUUpdateAlert" : @"SUUpdateAlertSmall" ]; - if ([SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]) { - [self.window setLevel:NSFloatingWindowLevel]; // This means the window will float over all other apps, if our app is switched out ?! - } - if (self.updateItem.informationOnlyUpdate) { [self.installButton setTitle:SULocalizedString(@"Learn More…", @"Alternate title for 'Install Update' button when there's no download in RSS feed.")]; [self.installButton setAction:@selector(openInfoURL:)]; @@ -371,6 +377,13 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE [self.window center]; } +- (void)windowDidBecomeKey:(NSNotification *)__unused note +{ + if (_didBecomeKeyBlock != NULL) { + _didBecomeKeyBlock(); + } +} + - (BOOL)windowShouldClose:(NSNotification *) __unused note { [self endWithSelection:SPUUserUpdateChoiceDismiss];