Separating Autoupdate into separate files

This commit is contained in:
Zorg committed 2016-03-08 00:00:00 -05:00
1 parent 57f0bc4245
commit 7ea2d0f9cf
6 files changed
+330 -245

No files matched your search

+12
View File
@@ -210,6 +210,8 @@
7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */; };
7275F9C21B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; };
7275F9C31B5F1F2900B1D19E /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; };
729746201C8E8D9A00FC134E /* TerminationListener.m in Sources */ = {isa = PBXBuildFile; fileRef = 7297461F1C8E8D9A00FC134E /* TerminationListener.m */; };
729746231C8E8F1100FC134E /* AppInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 729746221C8E8F1100FC134E /* AppInstaller.m */; };
72A450531C69A68900D67EEA /* SUUpdatePermissionPromptResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 72A450511C69A68900D67EEA /* SUUpdatePermissionPromptResult.h */; settings = {ATTRIBUTES = (Public, ); }; };
72A450541C69A68900D67EEA /* SUUpdatePermissionPromptResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 72A450521C69A68900D67EEA /* SUUpdatePermissionPromptResult.m */; };
72A4A2401BB6567D00E7820D /* SUFileManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */; };
@@ -710,6 +712,10 @@
726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUOperatingSystem.m; sourceTree = "<group>"; };
7275F9BF1B5F1F2900B1D19E /* SUFileManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileManager.h; sourceTree = "<group>"; };
7275F9C01B5F1F2900B1D19E /* SUFileManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileManager.m; sourceTree = "<group>"; };
7297461E1C8E8D9A00FC134E /* TerminationListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TerminationListener.h; sourceTree = "<group>"; };
7297461F1C8E8D9A00FC134E /* TerminationListener.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TerminationListener.m; sourceTree = "<group>"; };
729746211C8E8F1100FC134E /* AppInstaller.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppInstaller.h; sourceTree = "<group>"; };
729746221C8E8F1100FC134E /* AppInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppInstaller.m; sourceTree = "<group>"; };
729F10FD1C65A9B500DFCCC5 /* ConfigUITest.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITest.xcconfig; sourceTree = "<group>"; };
729F10FE1C65A9B500DFCCC5 /* ConfigUITestCoverage.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITestCoverage.xcconfig; sourceTree = "<group>"; };
729F10FF1C65A9B500DFCCC5 /* ConfigUITestDebug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUITestDebug.xcconfig; sourceTree = "<group>"; };
@@ -996,6 +1002,10 @@
children = (
55C14BB9136EEF1500649790 /* Autoupdate-Info.plist */,
55C14BD3136EEFCE00649790 /* Autoupdate.m */,
729746211C8E8F1100FC134E /* AppInstaller.h */,
729746221C8E8F1100FC134E /* AppInstaller.m */,
7297461E1C8E8D9A00FC134E /* TerminationListener.h */,
7297461F1C8E8D9A00FC134E /* TerminationListener.m */,
);
path = Autoupdate;
sourceTree = "<group>";
@@ -1770,6 +1780,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
729746201C8E8D9A00FC134E /* TerminationListener.m in Sources */,
725602D71C83576100DAA70E /* SUApplicationInfo.m in Sources */,
55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */,
F8761EB61ADC5E7A000C9034 /* SUCodeSigningVerifier.m in Sources */,
@@ -1778,6 +1789,7 @@
767B61AE1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */,
55C14F0C136EF6EA00649790 /* SUHost.m in Sources */,
55C14F0D136EF6F200649790 /* SUInstaller.m in Sources */,
729746231C8E8F1100FC134E /* AppInstaller.m in Sources */,
55C14F08136EF6DB00649790 /* SULog.m in Sources */,
726F2CE71BC9C3E2001971A4 /* SUOperatingSystem.m in Sources */,
55C14F24136EF86F00649790 /* SUPackageInstaller.m in Sources */,
+17
View File
@@ -0,0 +1,17 @@
//
// AppInstaller.h
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppInstaller : NSObject
- (instancetype)initWithHostPath:(NSString *)hostPath relaunchPath:(NSString *)relaunchPath hostProcessIdentifier:(NSNumber *)hostProcessIdentifier updateFolderPath:(NSString *)updateFolderPath shouldRelaunch:(BOOL)shouldRelaunch shouldShowUI:(BOOL)shouldShowUI;
- (void)installAfterHostTermination;
@end
+190
View File
@@ -0,0 +1,190 @@
//
// AppInstaller.m
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "AppInstaller.h"
#import "SUStatusController.h"
#import "TerminationListener.h"
#import "SUInstaller.h"
#import "SULog.h"
#import "SUHost.h"
#import "SULocalizations.h"
#import "SUStandardVersionComparator.h"
/*!
* If the Installation takes longer than this time the Application Icon is shown in the Dock so that the user has some feedback.
*/
static const NSTimeInterval SUInstallationTimeLimit = 5;
/*!
* Terminate the application after a delay from launching the new update to avoid OS activation issues
* This delay should be be high enough to increase the likelihood that our updated app will be launched up front,
* but should be low enough so that the user doesn't ponder why the updater hasn't finished terminating yet
*/
static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@interface AppInstaller ()
@property (nonatomic, strong) TerminationListener *terminationListener;
@property (nonatomic, strong) SUStatusController *statusController;
@property (nonatomic, copy) NSString *updateFolderPath;
@property (nonatomic, copy) NSString *hostPath;
@property (nonatomic, copy) NSString *relaunchPath;
@property (nonatomic, assign) BOOL shouldRelaunch;
@property (nonatomic, assign) BOOL shouldShowUI;
@property (nonatomic, assign) BOOL isTerminating;
@end
@implementation AppInstaller
@synthesize terminationListener = _terminationListener;
@synthesize statusController = _statusController;
@synthesize updateFolderPath = _updateFolderPath;
@synthesize hostPath = _hostPath;
@synthesize relaunchPath = _relaunchPath;
@synthesize shouldRelaunch = _shouldRelaunch;
@synthesize shouldShowUI = _shouldShowUI;
@synthesize isTerminating = _isTerminating;
/*
* hostPath - path to host (original) application
* relaunchPath - path to what the host wants to relaunch (default is same as hostPath)
* hostProcessIdentifier - process identifier of the host before launching us
* updateFolderPath - path to update folder (i.e, temporary directory containing the new update)
* shouldRelaunch - indicates if the new installed app should re-launched
* shouldShowUI - indicates if we should show the status window when installing the update
*/
- (instancetype)initWithHostPath:(NSString *)hostPath relaunchPath:(NSString *)relaunchPath hostProcessIdentifier:(NSNumber *)hostProcessIdentifier updateFolderPath:(NSString *)updateFolderPath shouldRelaunch:(BOOL)shouldRelaunch shouldShowUI:(BOOL)shouldShowUI
{
if (!(self = [super init])) {
return nil;
}
self.hostPath = hostPath;
self.relaunchPath = relaunchPath;
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:hostProcessIdentifier];
self.updateFolderPath = updateFolderPath;
self.shouldRelaunch = shouldRelaunch;
self.shouldShowUI = shouldShowUI;
return self;
}
- (void)installAfterHostTermination
{
[self.terminationListener startListeningWithCompletion:^(BOOL success){
self.terminationListener = nil;
if (!success) {
// We should just give up now - should we show an alert though??
SULog(@"Timed out waiting for target to terminate. Target path is %@", self.hostPath);
[self cleanupAndExit];
} else {
if (self.shouldShowUI) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!self.isTerminating) {
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
});
}
[self install];
}
}];
}
- (void)install
{
NSBundle *theBundle = [NSBundle bundleWithPath:self.hostPath];
SUHost *host = [[SUHost alloc] initWithBundle:theBundle];
NSString *installationPath = [[host installationPath] copy];
if (self.shouldShowUI) {
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
maxProgressValue: 0 statusText: @""];
[self.statusController showWindow:self];
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
}
[SUInstaller
installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) {
if (error) {
SULog(@"Installation Error: %@", error);
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
exit(EXIT_FAILURE);
} else {
NSString *pathToRelaunch = nil;
// If the installation path differs from the host path, we give higher precedence for it than
// if the desired relaunch path differs from the host path
if (![installationPath.pathComponents isEqualToArray:self.hostPath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.hostPath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
}
}];
}
- (void)cleanupAndExit __attribute__((noreturn))
{
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
SULog(@"Couldn't remove update folder: %@.", theError);
}
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
{
self.isTerminating = YES;
if (self.shouldRelaunch) {
// The auto updater can terminate before the newly updated app is finished launching
// If that happens, the OS may not make the updated app active and frontmost
// (Or it does become frontmost, but the OS backgrounds it afterwards.. It's some kind of timing/activation issue that doesn't occur all the time)
// The only remedy I've been able to find is waiting an arbitrary delay before exiting our application
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
SULog(@"Failed to launch %@", relaunchPath);
}
[self.statusController close];
// Don't even think about hiding the app icon from the dock if we've already shown it
// Transforming the app back to a background one has a backfiring effect, decreasing the likelihood
// that the updated app will be brought up front
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self cleanupAndExit];
});
} else {
[self cleanupAndExit];
}
}
@end
+14 -245
View File
@@ -1,262 +1,29 @@
#import <AppKit/AppKit.h>
#import "SUInstaller.h"
#import "SUHost.h"
#import "SUStandardVersionComparator.h"
#import "SUStatusController.h"
#import <Cocoa/Cocoa.h>
#import "SULog.h"
#import "SULocalizations.h"
#import "SUFileManager.h"
#import "AppInstaller.h"
#include <unistd.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
/*!
* Time this app uses to recheck if the host app has already died.
*/
static const NSTimeInterval SUParentQuitCheckInterval = .25;
/*!
* Timeout to wait until the host app has died.
*/
static const NSTimeInterval SUParentQuitTimeoutInterval = 30.0;
@interface TerminationListener : NSObject
@property (nonatomic, readonly) AppInstaller *appInstaller;
@end
@interface TerminationListener ()
@implementation AppDelegate
@property (nonatomic, strong) NSNumber *processIdentifier;
@property (nonatomic, strong) NSTimer *watchdogTimer;
@property (nonatomic, strong) NSTimer *timeoutTimer;
@synthesize appInstaller = _appInstaller;
@end
@implementation TerminationListener
@synthesize processIdentifier = _processIdentifier;
@synthesize watchdogTimer = _watchdogTimer;
@synthesize timeoutTimer = _timeoutTimer;
- (instancetype)initWithProcessIdentifier:(NSNumber *)processIdentifier
- (instancetype)initWithAppInstaller:(AppInstaller *)appInstaller
{
if (!(self = [super init])) {
return nil;
self = [super init];
if (self != nil) {
_appInstaller = appInstaller;
}
self.processIdentifier = processIdentifier;
return self;
}
- (void)cleanupWithSuccess:(BOOL)success completion:(void (^)(BOOL))completionBlock
{
[self.watchdogTimer invalidate];
[self.timeoutTimer invalidate];
completionBlock(success);
}
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock
{
BOOL alreadyTerminated = (self.processIdentifier == nil || (kill(self.processIdentifier.intValue, 0) != 0));
if (alreadyTerminated) {
[self cleanupWithSuccess:YES completion:completionBlock];
} else {
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:completionBlock repeats:YES];
self.timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitTimeoutInterval target:self selector:@selector(timeout:) userInfo:completionBlock repeats:NO];
}
}
- (void)watchdog:(NSTimer *)timer
{
if ([NSRunningApplication runningApplicationWithProcessIdentifier:self.processIdentifier.intValue] == nil) {
[self cleanupWithSuccess:YES completion:timer.userInfo];
}
}
- (void)timeout:(NSTimer *)timer
{
if (self.watchdogTimer.valid) {
[self cleanupWithSuccess:NO completion:timer.userInfo];
}
}
@end
/*!
* If the Installation takes longer than this time the Application Icon is shown in the Dock so that the user has some feedback.
*/
static const NSTimeInterval SUInstallationTimeLimit = 5;
/*!
* Terminate the application after a delay from launching the new update to avoid OS activation issues
* This delay should be be high enough to increase the likelihood that our updated app will be launched up front,
* but should be low enough so that the user doesn't ponder why the updater hasn't finished terminating yet
*/
static const NSTimeInterval SUTerminationTimeDelay = 0.5;
@interface AppInstaller : NSObject <NSApplicationDelegate>
@end
@interface AppInstaller ()
@property (nonatomic, strong) TerminationListener *terminationListener;
@property (nonatomic, strong) SUStatusController *statusController;
@property (nonatomic, copy) NSString *updateFolderPath;
@property (nonatomic, copy) NSString *hostPath;
@property (nonatomic, copy) NSString *relaunchPath;
@property (nonatomic, assign) BOOL shouldRelaunch;
@property (nonatomic, assign) BOOL shouldShowUI;
@property (nonatomic, assign) BOOL isTerminating;
@end
@implementation AppInstaller
@synthesize terminationListener = _terminationListener;
@synthesize statusController = _statusController;
@synthesize updateFolderPath = _updateFolderPath;
@synthesize hostPath = _hostPath;
@synthesize relaunchPath = _relaunchPath;
@synthesize shouldRelaunch = _shouldRelaunch;
@synthesize shouldShowUI = _shouldShowUI;
@synthesize isTerminating = _isTerminating;
/*
* hostPath - path to host (original) application
* relaunchPath - path to what the host wants to relaunch (default is same as hostPath)
* hostProcessIdentifier - process identifier of the host before launching us
* updateFolderPath - path to update folder (i.e, temporary directory containing the new update)
* shouldRelaunch - indicates if the new installed app should re-launched
* shouldShowUI - indicates if we should show the status window when installing the update
*/
- (instancetype)initWithHostPath:(NSString *)hostPath relaunchPath:(NSString *)relaunchPath hostProcessIdentifier:(NSNumber *)hostProcessIdentifier updateFolderPath:(NSString *)updateFolderPath shouldRelaunch:(BOOL)shouldRelaunch shouldShowUI:(BOOL)shouldShowUI
{
if (!(self = [super init])) {
return nil;
}
self.hostPath = hostPath;
self.relaunchPath = relaunchPath;
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:hostProcessIdentifier];
self.updateFolderPath = updateFolderPath;
self.shouldRelaunch = shouldRelaunch;
self.shouldShowUI = shouldShowUI;
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification __unused *)notification
{
[self.terminationListener startListeningWithCompletion:^(BOOL success){
self.terminationListener = nil;
if (!success) {
// We should just give up now - should we show an alert though??
SULog(@"Timed out waiting for target to terminate. Target path is %@", self.hostPath);
[self cleanupAndExit];
} else {
if (self.shouldShowUI) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!self.isTerminating) {
// Show app icon in the dock
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
});
}
[self install];
}
}];
}
- (void)install
{
NSBundle *theBundle = [NSBundle bundleWithPath:self.hostPath];
SUHost *host = [[SUHost alloc] initWithBundle:theBundle];
NSString *installationPath = [[host installationPath] copy];
if (self.shouldShowUI) {
self.statusController = [[SUStatusController alloc] initWithHost:host];
[self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO];
[self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"")
maxProgressValue: 0 statusText: @""];
[self.statusController showWindow:self];
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
}
[SUInstaller installFromUpdateFolder:self.updateFolderPath
overHost:host
installationPath:installationPath
versionComparator:[SUStandardVersionComparator defaultComparator]
completionHandler:^(NSError *error) {
if (error) {
SULog(@"Installation Error: %@", error);
if (self.shouldShowUI) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"";
alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]];
[alert runModal];
}
exit(EXIT_FAILURE);
} else {
NSString *pathToRelaunch = nil;
// If the installation path differs from the host path, we give higher precedence for it than
// if the desired relaunch path differs from the host path
if (![installationPath.pathComponents isEqualToArray:self.hostPath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.hostPath.pathComponents]) {
pathToRelaunch = installationPath;
} else {
pathToRelaunch = self.relaunchPath;
}
[self cleanupAndTerminateWithPathToRelaunch:pathToRelaunch];
}
}];
}
- (void)cleanupAndExit __attribute__((noreturn))
{
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) {
SULog(@"Couldn't remove update folder: %@.", theError);
}
[[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
exit(EXIT_SUCCESS);
}
- (void)cleanupAndTerminateWithPathToRelaunch:(NSString *)relaunchPath
{
self.isTerminating = YES;
if (self.shouldRelaunch) {
// The auto updater can terminate before the newly updated app is finished launching
// If that happens, the OS may not make the updated app active and frontmost
// (Or it does become frontmost, but the OS backgrounds it afterwards.. It's some kind of timing/activation issue that doesn't occur all the time)
// The only remedy I've been able to find is waiting an arbitrary delay before exiting our application
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
SULog(@"Failed to launch %@", relaunchPath);
}
[self.statusController close];
// Don't even think about hiding the app icon from the dock if we've already shown it
// Transforming the app back to a background one has a backfiring effect, decreasing the likelihood
// that the updated app will be brought up front
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self cleanupAndExit];
});
} else {
[self cleanupAndExit];
}
[self.appInstaller installAfterHostTermination];
}
@end
@@ -323,7 +90,9 @@ int main(int __unused argc, const char __unused *argv[])
updateFolderPath:updateDirectoryPath
shouldRelaunch:shouldRelaunchApp
shouldShowUI:shouldShowUI];
[application setDelegate:appInstaller];
AppDelegate *delegate = [[AppDelegate alloc] initWithAppInstaller:appInstaller];
[application setDelegate:delegate];
[application run];
}
+17
View File
@@ -0,0 +1,17 @@
//
// TerminationListener.h
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface TerminationListener : NSObject
- (instancetype)initWithProcessIdentifier:(NSNumber *)processIdentifier;
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock;
@end
+80
View File
@@ -0,0 +1,80 @@
//
// TerminationListener.m
// Sparkle
//
// Created by Mayur Pawashe on 3/7/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "TerminationListener.h"
/*!
* Time this app uses to recheck if the host app has already died.
*/
static const NSTimeInterval SUParentQuitCheckInterval = .25;
/*!
* Timeout to wait until the host app has died.
*/
static const NSTimeInterval SUParentQuitTimeoutInterval = 30.0;
@interface TerminationListener ()
@property (nonatomic, strong) NSNumber *processIdentifier;
@property (nonatomic, strong) NSTimer *watchdogTimer;
@property (nonatomic, strong) NSTimer *timeoutTimer;
@end
@implementation TerminationListener
@synthesize processIdentifier = _processIdentifier;
@synthesize watchdogTimer = _watchdogTimer;
@synthesize timeoutTimer = _timeoutTimer;
- (instancetype)initWithProcessIdentifier:(NSNumber *)processIdentifier
{
if (!(self = [super init])) {
return nil;
}
self.processIdentifier = processIdentifier;
return self;
}
- (void)cleanupWithSuccess:(BOOL)success completion:(void (^)(BOOL))completionBlock
{
[self.watchdogTimer invalidate];
[self.timeoutTimer invalidate];
completionBlock(success);
}
- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock
{
BOOL alreadyTerminated = (self.processIdentifier == nil || (kill(self.processIdentifier.intValue, 0) != 0));
if (alreadyTerminated) {
[self cleanupWithSuccess:YES completion:completionBlock];
} else {
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:completionBlock repeats:YES];
self.timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitTimeoutInterval target:self selector:@selector(timeout:) userInfo:completionBlock repeats:NO];
}
}
- (void)watchdog:(NSTimer *)timer
{
if ([NSRunningApplication runningApplicationWithProcessIdentifier:self.processIdentifier.intValue] == nil) {
[self cleanupWithSuccess:YES completion:timer.userInfo];
}
}
- (void)timeout:(NSTimer *)timer
{
if (self.watchdogTimer.valid) {
[self cleanupWithSuccess:NO completion:timer.userInfo];
}
}
@end