From def8cfa1ff0f52abd07d8ffe22df96e1e38e785f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Mon, 7 Jul 2014 01:26:01 +0100 Subject: [PATCH] Whitespace-only clang-format changes --- Sparkle/Autoupdate/Autoupdate.m | 164 +++--- Sparkle/SUAppcast.h | 2 +- Sparkle/SUAppcast.m | 148 +++--- Sparkle/SUAppcastItem.h | 2 +- Sparkle/SUAppcastItem.m | 158 +++--- Sparkle/SUAutomaticUpdateAlert.h | 6 +- Sparkle/SUAutomaticUpdateAlert.m | 36 +- Sparkle/SUAutomaticUpdateDriver.m | 70 +-- Sparkle/SUBasicUpdateDriver.h | 2 +- Sparkle/SUBasicUpdateDriver.m | 266 +++++----- Sparkle/SUCodeSigningVerifier.m | 8 +- Sparkle/SUConstants.h | 6 +- Sparkle/SUDiskImageUnarchiver.m | 136 ++--- Sparkle/SUHost.m | 166 +++--- Sparkle/SUInstaller.m | 154 +++--- Sparkle/SULog.h | 4 +- Sparkle/SULog.m | 46 +- Sparkle/SUPipedUnarchiver.m | 112 ++-- Sparkle/SUPlainInstaller.m | 16 +- Sparkle/SUPlainInstallerInternals.h | 2 +- Sparkle/SUPlainInstallerInternals.m | 706 +++++++++++++------------- Sparkle/SUProbingUpdateDriver.m | 12 +- Sparkle/SUScheduledUpdateDriver.m | 18 +- Sparkle/SUStandardVersionComparator.m | 20 +- Sparkle/SUStatusController.h | 4 +- Sparkle/SUStatusController.m | 70 +-- Sparkle/SUSystemProfiler.m | 218 ++++---- Sparkle/SUUIBasedUpdateDriver.h | 4 +- Sparkle/SUUIBasedUpdateDriver.m | 194 +++---- Sparkle/SUUnarchiver.m | 14 +- Sparkle/SUUpdateAlert.h | 10 +- Sparkle/SUUpdateAlert.m | 166 +++--- Sparkle/SUUpdateDriver.h | 6 +- Sparkle/SUUpdateDriver.m | 20 +- Sparkle/SUUpdatePermissionPrompt.h | 4 +- Sparkle/SUUpdatePermissionPrompt.m | 126 ++--- Sparkle/SUUpdater.h | 22 +- Sparkle/SUUpdater.m | 430 ++++++++-------- Sparkle/SUUserInitiatedUpdateDriver.m | 62 +-- Sparkle/SUVersionComparisonProtocol.h | 2 +- Sparkle/SUVersionDisplayProtocol.h | 2 +- Sparkle/SUWindowController.m | 18 +- TestApplication/main.m | 2 +- 43 files changed, 1817 insertions(+), 1817 deletions(-) diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 60a85266..fa65de13 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -33,13 +33,13 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25; @property (assign) BOOL shouldRelaunch; @property (assign) BOOL shouldShowUI; -- (void) parentHasQuit; +- (void)parentHasQuit; -- (void) relaunch; -- (void) install; +- (void)relaunch; +- (void)install; -- (void) showAppIconInDock:(NSTimer *)aTimer; -- (void) watchdog:(NSTimer *)aTimer; +- (void)showAppIconInDock:(NSTimer *)aTimer; +- (void)watchdog:(NSTimer *)aTimer; @end @@ -58,100 +58,100 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25; @synthesize shouldRelaunch; @synthesize shouldShowUI; -- (instancetype) initWithHostPath:(const char *)inhostpath executablePath:(const char *)execpath parentProcessId:(pid_t)ppid folderPath:(const char*)infolderpath shouldRelaunch:(BOOL)relaunch shouldShowUI:(BOOL)showUI selfPath:(NSString*)inSelfPath +- (instancetype)initWithHostPath:(const char *)inhostpath executablePath:(const char *)execpath parentProcessId:(pid_t)ppid folderPath:(const char *)infolderpath shouldRelaunch:(BOOL)relaunch shouldShowUI:(BOOL)showUI selfPath:(NSString *)inSelfPath { - if (!(self = [super init])) { - return nil; - } + if (!(self = [super init])) { + return nil; + } - hostpath = inhostpath; - executablepath = execpath; - parentprocessid = ppid; - folderpath = infolderpath; - selfPath = inSelfPath; - shouldRelaunch = relaunch; - shouldShowUI = showUI; + hostpath = inhostpath; + executablepath = execpath; + parentprocessid = ppid; + folderpath = infolderpath; + selfPath = inSelfPath; + shouldRelaunch = relaunch; + shouldShowUI = showUI; - BOOL alreadyTerminated = (getppid() == 1); // ppid is launchd (1) => parent terminated already + BOOL alreadyTerminated = (getppid() == 1); // ppid is launchd (1) => parent terminated already - if( alreadyTerminated ) - [self parentHasQuit]; - else - watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:nil repeats:YES]; + if (alreadyTerminated) + [self parentHasQuit]; + else + watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:nil repeats:YES]; - return self; + return self; } --(void) dealloc +- (void)dealloc { - [longInstallationTimer invalidate]; + [longInstallationTimer invalidate]; } --(void) parentHasQuit +- (void)parentHasQuit { - [self.watchdogTimer invalidate]; - self.longInstallationTimer = [NSTimer scheduledTimerWithTimeInterval:SUInstallationTimeLimit + [self.watchdogTimer invalidate]; + self.longInstallationTimer = [NSTimer scheduledTimerWithTimeInterval:SUInstallationTimeLimit target: self selector: @selector(showAppIconInDock:) userInfo:nil repeats:NO]; - if( self.folderpath ) - [self install]; - else - [self relaunch]; + if (self.folderpath) + [self install]; + else + [self relaunch]; } -- (void)watchdog:(NSTimer *) __unused aTimer +- (void)watchdog:(NSTimer *)__unused aTimer { - if (![NSRunningApplication runningApplicationWithProcessIdentifier:self.parentprocessid]) { - [self parentHasQuit]; -} + if (![NSRunningApplication runningApplicationWithProcessIdentifier:self.parentprocessid]) { + [self parentHasQuit]; + } } -- (void)showAppIconInDock:(NSTimer *) __unused aTimer +- (void)showAppIconInDock:(NSTimer *)__unused aTimer { - ProcessSerialNumber psn = { 0, kCurrentProcess }; - TransformProcessType( &psn, kProcessTransformToForegroundApplication ); + ProcessSerialNumber psn = { 0, kCurrentProcess }; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); } -- (void) relaunch __attribute__((noreturn)) +- (void)relaunch __attribute__((noreturn)) { if (self.shouldRelaunch) { - NSString *appPath = nil; - if( !self.folderpath || strcmp(self.executablepath, self.hostpath) != 0 ) + NSString *appPath = nil; + if (!self.folderpath || strcmp(self.executablepath, self.hostpath) != 0) appPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:self.executablepath length:strlen(self.executablepath)]; else appPath = self.installationPath; - [[NSWorkspace sharedWorkspace] openFile: appPath]; + [[NSWorkspace sharedWorkspace] openFile:appPath]; } if (self.folderpath) { NSError *theError = nil; - if( ![SUPlainInstaller _removeFileAtPath: [SUInstaller updateFolder] error: &theError] ) - SULog( @"Couldn't remove update folder: %@.", theError ); + if (![SUPlainInstaller _removeFileAtPath:[SUInstaller updateFolder] error:&theError]) + SULog(@"Couldn't remove update folder: %@.", theError); } - [[NSFileManager defaultManager] removeItemAtPath: self.selfPath error: NULL]; + [[NSFileManager defaultManager] removeItemAtPath:self.selfPath error:NULL]; - exit(EXIT_SUCCESS); + exit(EXIT_SUCCESS); } -- (void) install +- (void)install { - NSBundle *theBundle = [NSBundle bundleWithPath: [[NSFileManager defaultManager] stringWithFileSystemRepresentation: self.hostpath length:strlen(self.hostpath)]]; - self.host = [[SUHost alloc] initWithBundle: theBundle]; + NSBundle *theBundle = [NSBundle bundleWithPath:[[NSFileManager defaultManager] stringWithFileSystemRepresentation:self.hostpath length:strlen(self.hostpath)]]; + self.host = [[SUHost alloc] initWithBundle:theBundle]; self.installationPath = [[self.host installationPath] copy]; if (self.shouldShowUI) { - SUStatusController* statusCtl = [[SUStatusController alloc] initWithHost: self.host]; // We quit anyway after we've installed, so leak this for now. - [statusCtl setButtonTitle: SULocalizedString(@"Cancel Update",@"") target: nil action: Nil isDefault: NO]; - [statusCtl beginActionWithTitle: SULocalizedString(@"Installing update...",@"") + SUStatusController *statusCtl = [[SUStatusController alloc] initWithHost:self.host]; // We quit anyway after we've installed, so leak this for now. + [statusCtl setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO]; + [statusCtl beginActionWithTitle:SULocalizedString(@"Installing update...", @"") maxProgressValue: 0 statusText: @""]; - [statusCtl showWindow: self]; + [statusCtl showWindow:self]; } [SUInstaller installFromUpdateFolder:[[NSFileManager defaultManager] stringWithFileSystemRepresentation:self.folderpath length:strlen(self.folderpath)] @@ -161,31 +161,31 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25; versionComparator:[SUStandardVersionComparator defaultComparator]]; } -- (void)installerFinishedForHost:(SUHost *) __unused aHost +- (void)installerFinishedForHost:(SUHost *)__unused aHost { - [self relaunch]; + [self relaunch]; } -- (void)installerForHost:(SUHost *) __unused host failedWithError:(NSError *)error __attribute__((noreturn)) +- (void)installerForHost:(SUHost *)__unused host failedWithError:(NSError *)error __attribute__((noreturn)) { if (self.shouldShowUI) - NSRunAlertPanel( @"", @"%@", @"OK", @"", @"", [error localizedDescription] ); - exit(EXIT_FAILURE); + NSRunAlertPanel(@"", @"%@", @"OK", @"", @"", [error localizedDescription]); + exit(EXIT_FAILURE); } @end -int main (int argc, const char * argv[]) +int main(int argc, const char *argv[]) { - if (argc < 5 || argc > 7) { - return EXIT_FAILURE; - } + if (argc < 5 || argc > 7) { + return EXIT_FAILURE; + } @autoreleasepool { - //ProcessSerialNumber psn = { 0, kCurrentProcess }; - //TransformProcessType( &psn, kProcessTransformToForegroundApplication ); +//ProcessSerialNumber psn = { 0, kCurrentProcess }; +//TransformProcessType( &psn, kProcessTransformToForegroundApplication ); -#if 0 // Cmdline tool +#if 0 // Cmdline tool NSString* selfPath = nil; if (argv[0][0] == '/') { selfPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]; @@ -196,28 +196,28 @@ int main (int argc, const char * argv[]) selfPath = [selfPath stringByAppendingPathComponent: [[NSFileManager defaultManager] stringWithFileSystemRepresentation: argv[0] length: strlen(argv[0])]]; } #else - NSString* selfPath = [[NSBundle mainBundle] bundlePath]; + NSString *selfPath = [[NSBundle mainBundle] bundlePath]; #endif - BOOL shouldShowUI = (argc > 6) ? !!atoi(argv[6]) : YES; + BOOL shouldShowUI = (argc > 6) ? !!atoi(argv[6]) : YES; if (shouldShowUI) { - [[NSApplication sharedApplication] activateIgnoringOtherApps: YES]; - } + [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; + } - [NSApplication sharedApplication]; - TerminationListener *termListen = [[TerminationListener alloc] initWithHostPath: (argc > 1) ? argv[1] : NULL - executablePath: (argc > 2) ? argv[2] : NULL - parentProcessId: (argc > 3) ? atoi(argv[3]) : 0 - folderPath: (argc > 4) ? argv[4] : NULL - shouldRelaunch: (argc > 5) ? !!atoi(argv[5]) : YES - shouldShowUI: shouldShowUI - selfPath: selfPath]; - - [termListen class]; - [[NSApplication sharedApplication] run]; + [NSApplication sharedApplication]; + TerminationListener *termListen = [[TerminationListener alloc] initWithHostPath:(argc > 1) ? argv[1] : NULL + executablePath:(argc > 2) ? argv[2] : NULL + parentProcessId:(argc > 3) ? atoi(argv[3]) : 0 + folderPath:(argc > 4) ? argv[4] : NULL + shouldRelaunch:(argc > 5) ? !!atoi(argv[5]) : YES + shouldShowUI:shouldShowUI + selfPath:selfPath]; - } + [termListen class]; + [[NSApplication sharedApplication] run]; - return EXIT_SUCCESS; + } + + return EXIT_SUCCESS; } diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index 9df6b9c4..702f549e 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -12,7 +12,7 @@ @protocol SUAppcastDelegate; @class SUAppcastItem; -@interface SUAppcast : NSObject +@interface SUAppcast : NSObject @property (weak) id delegate; @property (copy) NSString *userAgentString; diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 32631e27..f68a9bb1 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -22,13 +22,13 @@ @implementation NSXMLElement (SUAppcastExtensions) - (NSDictionary *)attributesAsDictionary { - NSEnumerator *attributeEnum = [[self attributes] objectEnumerator]; - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + NSEnumerator *attributeEnum = [[self attributes] objectEnumerator]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - for (NSXMLNode *attribute in attributeEnum) { - dictionary[[attribute name]] = [attribute stringValue]; - } - return dictionary; + for (NSXMLNode *attribute in attributeEnum) { + dictionary[[attribute name]] = [attribute stringValue]; + } + return dictionary; } @end @@ -51,50 +51,50 @@ - (void)fetchAppcastFromURL:(NSURL *)url { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0]; - if (self.userAgentString) { + if (self.userAgentString) { [request setValue:self.userAgentString forHTTPHeaderField:@"User-Agent"]; - } + } self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; } -- (void)download:(NSURLDownload *) __unused aDownload decideDestinationWithSuggestedFilename:(NSString *)filename +- (void)download:(NSURLDownload *)__unused aDownload decideDestinationWithSuggestedFilename:(NSString *)filename { - NSString* destinationFilename = NSTemporaryDirectory(); + NSString *destinationFilename = NSTemporaryDirectory(); if (destinationFilename) { - destinationFilename = [destinationFilename stringByAppendingPathComponent:filename]; - [self.download setDestination:destinationFilename allowOverwrite:NO]; - } + destinationFilename = [destinationFilename stringByAppendingPathComponent:filename]; + [self.download setDestination:destinationFilename allowOverwrite:NO]; + } } -- (void)download:(NSURLDownload *) __unused aDownload didCreateDestination:(NSString *)path +- (void)download:(NSURLDownload *)__unused aDownload didCreateDestination:(NSString *)path { self.downloadFilename = path; } -- (void)downloadDidFinish:(NSURLDownload *) __unused aDownload +- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload { - NSError *error = nil; + NSError *error = nil; - NSXMLDocument *document = nil; - BOOL failed = NO; - NSArray *xmlItems = nil; - NSMutableArray *appcastItems = [NSMutableArray array]; + NSXMLDocument *document = nil; + BOOL failed = NO; + NSArray *xmlItems = nil; + NSMutableArray *appcastItems = [NSMutableArray array]; if (self.downloadFilename) { NSUInteger options = 0; - options = NSXMLNodeLoadExternalEntitiesSameOriginOnly; - document = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.downloadFilename] options:options error:&error]; + options = NSXMLNodeLoadExternalEntitiesSameOriginOnly; + document = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.downloadFilename] options:options error:&error]; - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; - self.downloadFilename = nil; + [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; + self.downloadFilename = nil; } else { - failed = YES; - } + failed = YES; + } if (nil == document) { @@ -112,14 +112,14 @@ if (failed == NO) { - NSEnumerator *nodeEnum = [xmlItems objectEnumerator]; - NSXMLNode *node; - NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary]; - NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + NSEnumerator *nodeEnum = [xmlItems objectEnumerator]; + NSXMLNode *node; + NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary]; + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; while (failed == NO && (node = [nodeEnum nextObject])) { - // First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later. + // First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later. if ([[node children] count]) { node = [node childAtIndex:0]; @@ -145,84 +145,84 @@ node = [self bestNodeInNodes:nodesDict[name]]; if ([name isEqualToString:@"enclosure"]) { - // enclosure is flattened as a separate dictionary for some reason - NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary]; - dict[@"enclosure"] = encDict; + // enclosure is flattened as a separate dictionary for some reason + NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary]; + dict[@"enclosure"] = encDict; } else if ([name isEqualToString:@"pubDate"]) { - // pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString - NSDate *date = [NSDate dateWithNaturalLanguageString:[node stringValue]]; - if (date) - dict[name] = date; + // pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString + NSDate *date = [NSDate dateWithNaturalLanguageString:[node stringValue]]; + if (date) + dict[name] = date; } else if ([name isEqualToString:@"sparkle:deltas"]) { - NSMutableArray *deltas = [NSMutableArray array]; - NSEnumerator *childEnum = [[node children] objectEnumerator]; - for (NSXMLNode *child in childEnum) { - if ([[child name] isEqualToString:@"enclosure"]) - [deltas addObject:[(NSXMLElement *)child attributesAsDictionary]]; - } - dict[@"deltas"] = deltas; + NSMutableArray *deltas = [NSMutableArray array]; + NSEnumerator *childEnum = [[node children] objectEnumerator]; + for (NSXMLNode *child in childEnum) { + if ([[child name] isEqualToString:@"enclosure"]) + [deltas addObject:[(NSXMLElement *)child attributesAsDictionary]]; + } + dict[@"deltas"] = deltas; } else if (name != nil) { - // add all other values as strings - NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - if (theValue != nil) { - dict[name] = theValue; - } - } + // add all other values as strings + NSString *theValue = [[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + if (theValue != nil) { + dict[name] = theValue; + } + } } - NSString *errString; - SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString]; + NSString *errString; + SUAppcastItem *anItem = [[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString]; if (anItem) { [appcastItems addObject:anItem]; } else { - SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); + SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); } [nodesDict removeAllObjects]; [dict removeAllObjects]; - } - } + } + } if ([appcastItems count]) { - NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; - [appcastItems sortUsingDescriptors:@[sort]]; - self.items = appcastItems; - } + NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; + [appcastItems sortUsingDescriptors:@[sort]]; + self.items = appcastItems; + } if (failed) { - [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while parsing the update feed.", nil)}]]; + [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while parsing the update feed.", nil) }]]; } else if ([self.delegate respondsToSelector:@selector(appcastDidFinishLoading:)]) { [self.delegate appcastDidFinishLoading:self]; - } + } } -- (void)download:(NSURLDownload *) __unused aDownload didFailWithError:(NSError *)error +- (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error { if (self.downloadFilename) { - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; - } - self.downloadFilename = nil; + [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; + } + self.downloadFilename = nil; - [self reportError:error]; + [self reportError:error]; } -- (NSURLRequest *)download:(NSURLDownload *) __unused aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *) __unused redirectResponse +- (NSURLRequest *)download:(NSURLDownload *)__unused aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)__unused redirectResponse { - return request; + return request; } - (void)reportError:(NSError *)error @@ -230,12 +230,12 @@ if ([self.delegate respondsToSelector:@selector(appcast:failedToLoadWithError:)]) { [self.delegate appcast:self failedToLoadWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil), NSLocalizedFailureReasonErrorKey: [error localizedDescription]}]]; - } + } } - (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes { - // We use this method to pick out the localized version of a node when one's available. + // We use this method to pick out the localized version of a node when one's available. if ([nodes count] == 1) return nodes[0]; else if ([nodes count] == 0) @@ -244,15 +244,15 @@ NSMutableArray *languages = [NSMutableArray array]; NSString *lang; NSUInteger i; - for (NSXMLElement *node in nodes) { + for (NSXMLElement *node in nodes) { lang = [[node attributeForName:@"xml:lang"] stringValue]; [languages addObject:(lang ? lang : @"")]; } lang = [NSBundle preferredLocalizationsFromArray:languages][0]; i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")]; - if (i == NSNotFound) { + if (i == NSNotFound) { i = 0; - } + } return nodes[i]; } diff --git a/Sparkle/SUAppcastItem.h b/Sparkle/SUAppcastItem.h index c859a10e..3334a1af 100644 --- a/Sparkle/SUAppcastItem.h +++ b/Sparkle/SUAppcastItem.h @@ -25,7 +25,7 @@ // Initializes with data from a dictionary provided by the RSS class. - (instancetype)initWithDictionary:(NSDictionary *)dict; -- (instancetype)initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error; +- (instancetype)initWithDictionary:(NSDictionary *)dict failureReason:(NSString **)error; @property (getter=isDeltaUpdate, readonly) BOOL deltaUpdate; @property (getter=isCriticalUpdate, readonly) BOOL criticalUpdate; diff --git a/Sparkle/SUAppcastItem.m b/Sparkle/SUAppcastItem.m index 16c26fd9..ea72dd2d 100644 --- a/Sparkle/SUAppcastItem.m +++ b/Sparkle/SUAppcastItem.m @@ -47,7 +47,7 @@ - (BOOL)isDeltaUpdate { - return self.propertiesDictionary[@"enclosure"][@"sparkle:deltaFrom"] != nil; + return self.propertiesDictionary[@"enclosure"][@"sparkle:deltaFrom"] != nil; } - (BOOL)isCriticalUpdate @@ -55,123 +55,123 @@ return [self.propertiesDictionary[@"sparkle:tags"] containsObject:@"sparkle:criticalUpdate"]; } -- (instancetype) initWithDictionary:(NSDictionary *)dict +- (instancetype)initWithDictionary:(NSDictionary *)dict { - return [self initWithDictionary:dict failureReason:nil]; + return [self initWithDictionary:dict failureReason:nil]; } -- (instancetype) initWithDictionary:(NSDictionary *)dict failureReason:(NSString*__autoreleasing *)error +- (instancetype)initWithDictionary:(NSDictionary *)dict failureReason:(NSString *__autoreleasing *)error { - self = [super init]; + self = [super init]; if (self) { - id enclosure = dict[@"enclosure"]; + id enclosure = dict[@"enclosure"]; - // Try to find a version string. - // Finding the new version number from the RSS feed is a little bit hacky. There are two ways: - // 1. A "sparkle:version" attribute on the enclosure tag, an extension from the RSS spec. - // 2. If there isn't a version attribute, Sparkle will parse the path in the enclosure, expecting - // that it will look like this: http://something.com/YourApp_0.5.zip. It'll read whatever's between the last - // underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension. - // The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle. - // Feel free to change the separator string to a hyphen or something more suited to your needs if you like. - NSString *newVersion = enclosure[@"sparkle:version"]; - if( newVersion == nil ) - newVersion = dict[@"sparkle:version"]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade). - if (newVersion == nil) // no sparkle:version attribute anywhere? - { - // Separate the url by underscores and take the last component, as that'll be closest to the end, - // then we remove the extension. Hopefully, this will be the version. - NSArray *fileComponents = [enclosure[@"url"] componentsSeparatedByString:@"_"]; - if ([fileComponents count] > 1) - newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; - } + // Try to find a version string. + // Finding the new version number from the RSS feed is a little bit hacky. There are two ways: + // 1. A "sparkle:version" attribute on the enclosure tag, an extension from the RSS spec. + // 2. If there isn't a version attribute, Sparkle will parse the path in the enclosure, expecting + // that it will look like this: http://something.com/YourApp_0.5.zip. It'll read whatever's between the last + // underscore and the last period as the version number. So name your packages like this: APPNAME_VERSION.extension. + // The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle. + // Feel free to change the separator string to a hyphen or something more suited to your needs if you like. + NSString *newVersion = enclosure[@"sparkle:version"]; + if (newVersion == nil) + newVersion = dict[@"sparkle:version"]; // Get version from the item, in case it's a download-less item (i.e. paid upgrade). + if (newVersion == nil) // no sparkle:version attribute anywhere? + { + // Separate the url by underscores and take the last component, as that'll be closest to the end, + // then we remove the extension. Hopefully, this will be the version. + NSArray *fileComponents = [enclosure[@"url"] componentsSeparatedByString:@"_"]; + if ([fileComponents count] > 1) + newVersion = [[fileComponents lastObject] stringByDeletingPathExtension]; + } if(!newVersion ) { - if (error) - *error = @"Feed item lacks sparkle:version attribute, and version couldn't be deduced from file name (would have used last component of a file name like AppName_1.3.4.zip)"; - return nil; - } + if (error) + *error = @"Feed item lacks sparkle:version attribute, and version couldn't be deduced from file name (would have used last component of a file name like AppName_1.3.4.zip)"; + return nil; + } - propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict]; - self.title = dict[@"title"]; - self.date = dict[@"pubDate"]; - self.itemDescription = dict[@"description"]; + propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict]; + self.title = dict[@"title"]; + self.date = dict[@"pubDate"]; + self.itemDescription = dict[@"description"]; - NSString* theInfoURL = dict[@"link"]; + NSString *theInfoURL = dict[@"link"]; if( theInfoURL ) { - if( ![theInfoURL isKindOfClass: [NSString class]] ) - SULog(@"SUAppcastItem -initWithDictionary: Info URL is not of valid type."); - else - self.infoURL = [NSURL URLWithString:theInfoURL]; - } + if (![theInfoURL isKindOfClass:[NSString class]]) + SULog(@"SUAppcastItem -initWithDictionary: Info URL is not of valid type."); + else + self.infoURL = [NSURL URLWithString:theInfoURL]; + } - // Need an info URL or an enclosure URL. Former to show "More Info" - // page, latter to download & install: + // Need an info URL or an enclosure URL. Former to show "More Info" + // page, latter to download & install: if( !enclosure && !theInfoURL ) { - if (error) - *error = @"No enclosure in feed item"; - return nil; - } + if (error) + *error = @"No enclosure in feed item"; + return nil; + } - NSString* enclosureURLString = enclosure[@"url"]; + NSString *enclosureURLString = enclosure[@"url"]; if( !enclosureURLString && !theInfoURL ) { - if (error) { - *error = @"Feed item's enclosure lacks URL"; - } - return nil; - } + if (error) { + *error = @"Feed item's enclosure lacks URL"; + } + return nil; + } - if( enclosureURLString ) { - NSString *fileURLString = [[enclosureURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - self.fileURL = [NSURL URLWithString:fileURLString]; - } - if (enclosure) { - self.DSASignature = enclosure[@"sparkle:dsaSignature"]; - } + if (enclosureURLString) { + NSString *fileURLString = [[enclosureURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + self.fileURL = [NSURL URLWithString:fileURLString]; + } + if (enclosure) { + self.DSASignature = enclosure[@"sparkle:dsaSignature"]; + } - self.versionString = newVersion; - self.minimumSystemVersion = dict[@"sparkle:minimumSystemVersion"]; + self.versionString = newVersion; + self.minimumSystemVersion = dict[@"sparkle:minimumSystemVersion"]; self.maximumSystemVersion = dict[@"sparkle:maximumSystemVersion"]; - NSString *shortVersionString = enclosure[@"sparkle:shortVersionString"]; - if (nil == shortVersionString) { + NSString *shortVersionString = enclosure[@"sparkle:shortVersionString"]; + if (nil == shortVersionString) { shortVersionString = dict[@"sparkle:shortVersionString"]; // fall back on the - } + } - if (shortVersionString) - self.displayVersionString = shortVersionString; - else - self.displayVersionString = [self versionString]; + if (shortVersionString) + self.displayVersionString = shortVersionString; + else + self.displayVersionString = [self versionString]; - // Find the appropriate release notes URL. - if (dict[@"sparkle:releaseNotesLink"]) - self.releaseNotesURL = [NSURL URLWithString:dict[@"sparkle:releaseNotesLink"]]; - else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that. - self.releaseNotesURL = [NSURL URLWithString:self.itemDescription]; - else - self.releaseNotesURL = nil; + // Find the appropriate release notes URL. + if (dict[@"sparkle:releaseNotesLink"]) + self.releaseNotesURL = [NSURL URLWithString:dict[@"sparkle:releaseNotesLink"]]; + else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that. + self.releaseNotesURL = [NSURL URLWithString:self.itemDescription]; + else + self.releaseNotesURL = nil; if (dict[@"deltas"]) { NSMutableDictionary *deltas = [NSMutableDictionary dictionary]; NSArray *deltaDictionaries = dict[@"deltas"]; - for (NSDictionary *deltaDictionary in deltaDictionaries) { - NSMutableDictionary *fakeAppCastDict = [dict mutableCopy]; + for (NSDictionary *deltaDictionary in deltaDictionaries) { + NSMutableDictionary *fakeAppCastDict = [dict mutableCopy]; [fakeAppCastDict removeObjectForKey:@"deltas"]; fakeAppCastDict[@"enclosure"] = deltaDictionary; SUAppcastItem *deltaItem = [[[self class] alloc] initWithDictionary:fakeAppCastDict]; deltas[deltaDictionary[@"sparkle:deltaFrom"]] = deltaItem; - } + } self.deltaUpdates = deltas; } - } - return self; + } + return self; } @end diff --git a/Sparkle/SUAutomaticUpdateAlert.h b/Sparkle/SUAutomaticUpdateAlert.h index 5d1a91f5..7ac9b46d 100644 --- a/Sparkle/SUAutomaticUpdateAlert.h +++ b/Sparkle/SUAutomaticUpdateAlert.h @@ -15,9 +15,9 @@ typedef enum { - SUInstallNowChoice, - SUInstallLaterChoice, - SUDoNotInstallChoice + SUInstallNowChoice, + SUInstallLaterChoice, + SUDoNotInstallChoice } SUAutomaticInstallationChoice; @class SUAppcastItem, SUHost; diff --git a/Sparkle/SUAutomaticUpdateAlert.m b/Sparkle/SUAutomaticUpdateAlert.m index 6bb83c15..85cb0cbc 100644 --- a/Sparkle/SUAutomaticUpdateAlert.m +++ b/Sparkle/SUAutomaticUpdateAlert.m @@ -23,41 +23,41 @@ - (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost delegate:(id)del { - self = [super initWithHost:aHost windowNibName:@"SUAutomaticUpdateAlert"]; + self = [super initWithHost:aHost windowNibName:@"SUAutomaticUpdateAlert"]; if (self) { - self.updateItem = item; - self.delegate = del; - self.host = aHost; - [self setShouldCascadeWindows:NO]; - [[self window] center]; - } - return self; + self.updateItem = item; + self.delegate = del; + self.host = aHost; + [self setShouldCascadeWindows:NO]; + [[self window] center]; + } + return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; } -- (IBAction)installNow:(id) __unused sender +- (IBAction)installNow:(id)__unused sender { - [self close]; - [self.delegate automaticUpdateAlert:self finishedWithChoice:SUInstallNowChoice]; + [self close]; + [self.delegate automaticUpdateAlert:self finishedWithChoice:SUInstallNowChoice]; } -- (IBAction)installLater:(id) __unused sender +- (IBAction)installLater:(id)__unused sender { - [self close]; - [self.delegate automaticUpdateAlert:self finishedWithChoice:SUInstallLaterChoice]; + [self close]; + [self.delegate automaticUpdateAlert:self finishedWithChoice:SUInstallLaterChoice]; } -- (IBAction)doNotInstall:(id) __unused sender +- (IBAction)doNotInstall:(id)__unused sender { - [self close]; - [self.delegate automaticUpdateAlert:self finishedWithChoice:SUDoNotInstallChoice]; + [self close]; + [self.delegate automaticUpdateAlert:self finishedWithChoice:SUDoNotInstallChoice]; } - (NSImage *)applicationIcon { - return [self.host icon]; + return [self.host icon]; } - (NSString *)titleText diff --git a/Sparkle/SUAutomaticUpdateDriver.m b/Sparkle/SUAutomaticUpdateDriver.m index 61664812..ff6668a0 100644 --- a/Sparkle/SUAutomaticUpdateDriver.m +++ b/Sparkle/SUAutomaticUpdateDriver.m @@ -44,22 +44,22 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 self.interruptible = NO; self.alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host delegate:self]; - // 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. + // 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. if ([self.host isBackgroundApplication]) { - [[self.alert window] setHidesOnDeactivate:NO]; - [NSApp activateIgnoringOtherApps:YES]; - } + [[self.alert window] setHidesOnDeactivate:NO]; + [NSApp activateIgnoringOtherApps:YES]; + } - if ([NSApp isActive]) - [[self.alert window] makeKeyAndOrderFront:self]; - else - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; + if ([NSApp isActive]) + [[self.alert window] makeKeyAndOrderFront:self]; + else + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; } -- (void)unarchiverDidFinish:(SUUnarchiver *) __unused ua +- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; @@ -132,58 +132,58 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 [super abortUpdate]; } -- (void)applicationDidBecomeActive:(NSNotification *) __unused aNotification +- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification { - [[self.alert window] makeKeyAndOrderFront:self]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp]; + [[self.alert window] makeKeyAndOrderFront:self]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp]; } -- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *) __unused aua finishedWithChoice:(SUAutomaticInstallationChoice)choice +- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *)__unused aua finishedWithChoice:(SUAutomaticInstallationChoice)choice { switch (choice) { - case SUInstallNowChoice: + case SUInstallNowChoice: [self stopUpdatingOnTermination]; - [self installWithToolAndRelaunch:YES]; - break; + [self installWithToolAndRelaunch:YES]; + break; - case SUInstallLaterChoice: - self.postponingInstallation = YES; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; - // We're already waiting on quit, just indicate that we're idle. + case SUInstallLaterChoice: + self.postponingInstallation = YES; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; + // We're already waiting on quit, just indicate that we're idle. self.interruptible = YES; - break; + break; - case SUDoNotInstallChoice: + case SUDoNotInstallChoice: [self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey]; - [self abortUpdate]; - break; - } + [self abortUpdate]; + break; + } } - (BOOL)shouldInstallSynchronously { return self.postponingInstallation; } - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI { - if (relaunch) { + if (relaunch) { [self stopUpdatingOnTermination]; - } + } self.showErrors = YES; [super installWithToolAndRelaunch:relaunch displayingUserInterface:showUI]; } -- (void)applicationWillTerminate:(NSNotification *) __unused note +- (void)applicationWillTerminate:(NSNotification *)__unused note { - [self installWithToolAndRelaunch:NO]; + [self installWithToolAndRelaunch:NO]; } - (void)abortUpdateWithError:(NSError *)error { - if (self.showErrors) - [super abortUpdateWithError:error]; - else - [self abortUpdate]; + if (self.showErrors) + [super abortUpdateWithError:error]; + else + [self abortUpdate]; } @end diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index e63b8edb..341be385 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -15,7 +15,7 @@ #import "SUAppcast.h" @class SUAppcastItem, SUHost; -@interface SUBasicUpdateDriver : SUUpdateDriver +@interface SUBasicUpdateDriver : SUUpdateDriver @property (weak, readonly) SUAppcastItem *updateItem; @property (strong, readonly) NSURLDownload *download; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 7c4b2217..5a323868 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -22,12 +22,12 @@ #import "SUUpdater_Private.h" #ifdef FINISH_INSTALL_TOOL_NAME - // FINISH_INSTALL_TOOL_NAME expands to unquoted Autoupdate - #define QUOTE_NS_STRING2(str) @"" #str - #define QUOTE_NS_STRING1(str) QUOTE_NS_STRING2(str) - #define FINISH_INSTALL_TOOL_NAME_STRING QUOTE_NS_STRING1(FINISH_INSTALL_TOOL_NAME) +// FINISH_INSTALL_TOOL_NAME expands to unquoted Autoupdate +#define QUOTE_NS_STRING2(str) @"" #str +#define QUOTE_NS_STRING1(str) QUOTE_NS_STRING2(str) +#define FINISH_INSTALL_TOOL_NAME_STRING QUOTE_NS_STRING1(FINISH_INSTALL_TOOL_NAME) #else - #error FINISH_INSTALL_TOOL_NAME not defined +#error FINISH_INSTALL_TOOL_NAME not defined #endif @interface SUBasicUpdateDriver () @@ -54,35 +54,35 @@ - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost { - [super checkForUpdatesAtURL:URL host:aHost]; + [super checkForUpdatesAtURL:URL host:aHost]; if ([aHost isRunningOnReadOnlyVolume]) { - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]]}]]; - return; - } + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]] }]]; + return; + } - SUAppcast *appcast = [[SUAppcast alloc] init]; + SUAppcast *appcast = [[SUAppcast alloc] init]; - [appcast setDelegate:self]; + [appcast setDelegate:self]; [appcast setUserAgentString:[self.updater userAgentString]]; - [appcast fetchAppcastFromURL:URL]; + [appcast fetchAppcastFromURL:URL]; } -- (id )versionComparator +- (id)versionComparator { - id comparator = nil; + id comparator = nil; - // Give the delegate a chance to provide a custom version comparator + // Give the delegate a chance to provide a custom version comparator if ([[self.updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)]) { comparator = [[self.updater delegate] versionComparatorForUpdater:self.updater]; - } + } - // If we don't get a comparator from the delegate, use the default comparator - if (!comparator) { - comparator = [SUStandardVersionComparator defaultComparator]; - } + // If we don't get a comparator from the delegate, use the default comparator + if (!comparator) { + comparator = [SUStandardVersionComparator defaultComparator]; + } - return comparator; + return comparator; } - (BOOL)isItemNewer:(SUAppcastItem *)ui @@ -113,112 +113,112 @@ { NSString *skippedVersion = [self.host objectForUserDefaultsKey:SUSkippedVersionKey]; if (skippedVersion == nil) { return NO; } - return [[self versionComparator] compareVersion:[ui versionString] toVersion:skippedVersion] != NSOrderedDescending; + return [[self versionComparator] compareVersion:[ui versionString] toVersion:skippedVersion] != NSOrderedDescending; } - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui { - return [self hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui]; + return [self hostSupportsItem:ui] && [self isItemNewer:ui] && ![self itemContainsSkippedVersion:ui]; } - (void)appcastDidFinishLoading:(SUAppcast *)ac { if ([[self.updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) { [[self.updater delegate] updater:self.updater didFinishLoadingAppcast:ac]; - } + } - NSDictionary *userInfo = (ac != nil) ? @{SUUpdaterAppcastNotificationKey : ac} : nil; + NSDictionary *userInfo = (ac != nil) ? @{ SUUpdaterAppcastNotificationKey: ac } : nil; [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:self.updater userInfo:userInfo]; SUAppcastItem *item = nil; - // Now we have to find the best valid update in the appcast. + // Now we have to find the best valid update in the appcast. if ([[self.updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it? - { + { item = [[self.updater delegate] bestValidUpdateInAppcast:ac forUpdater:self.updater]; } else // If not, we'll take care of it ourselves. - { - // Find the first update we can actually use. - NSEnumerator *updateEnumerator = [[ac items] objectEnumerator]; - do { - item = [updateEnumerator nextObject]; - } while (item && ![self hostSupportsItem:item]); + { + // Find the first update we can actually use. + NSEnumerator *updateEnumerator = [[ac items] objectEnumerator]; + do { + item = [updateEnumerator nextObject]; + } while (item && ![self hostSupportsItem:item]); - if (binaryDeltaSupported()) { + if (binaryDeltaSupported()) { SUAppcastItem *deltaUpdateItem = [item deltaUpdates][[self.host version]]; - if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) { - self.nonDeltaUpdateItem = item; - item = deltaUpdateItem; - } - } - } + if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) { + self.nonDeltaUpdateItem = item; + item = deltaUpdateItem; + } + } + } self.updateItem = item; if (self.updateItem == nil) { [self didNotFindUpdate]; return; } - if ([self itemContainsValidUpdate:self.updateItem]) - [self didFindValidUpdate]; - else - [self didNotFindUpdate]; + if ([self itemContainsValidUpdate:self.updateItem]) + [self didFindValidUpdate]; + else + [self didNotFindUpdate]; } - (void)appcast:(SUAppcast *)__unused ac failedToLoadWithError:(NSError *)error { - [self abortUpdateWithError:error]; + [self abortUpdateWithError:error]; } - (void)didFindValidUpdate { if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) [[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem]; - NSDictionary *userInfo = (self.updateItem != nil) ? @{SUUpdaterAppcastItemNotificationKey : self.updateItem} : nil; + NSDictionary *userInfo = (self.updateItem != nil) ? @{ SUUpdaterAppcastItemNotificationKey: self.updateItem } : nil; [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification object:self.updater userInfo:userInfo]; - [self downloadUpdate]; + [self downloadUpdate]; } - (void)didNotFindUpdate { if ([[self.updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { [[self.updater delegate] updaterDidNotFindUpdate:self.updater]; - } + } [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater]; - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", "'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI)"), [self.host name]] - }]]; + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", "'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI)"), [self.host name]] + }]]; } - (void)downloadUpdate { - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self.updateItem fileURL]]; [request setValue:[self.updater userAgentString] forHTTPHeaderField:@"User-Agent"]; - self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; + self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; } -- (void)download:(NSURLDownload *) __unused d decideDestinationWithSuggestedFilename:(NSString *)name +- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name { NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; self.tempDir = [[self.host appSupportPath] stringByAppendingPathComponent:downloadFileName]; - int cnt=1; + int cnt = 1; while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999) { self.tempDir = [[self.host appSupportPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]]; - } + } // Create the temporary directory if necessary. - BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.tempDir withIntermediateDirectories:YES attributes:nil error:NULL]; + BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.tempDir withIntermediateDirectories:YES attributes:nil error:NULL]; if (!success) { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.",self.tempDir]}]]; - } + // Okay, something's really broken with this user's file structure. + [self.download cancel]; + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", self.tempDir] }]]; + } - self.downloadPath = [self.tempDir stringByAppendingPathComponent:name]; - [self.download setDestination:self.downloadPath allowOverwrite:YES]; + self.downloadPath = [self.tempDir stringByAppendingPathComponent:name]; + [self.download setDestination:self.downloadPath allowOverwrite:YES]; } - (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey @@ -237,21 +237,21 @@ return [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; } -- (void)downloadDidFinish:(NSURLDownload *) __unused d +- (void)downloadDidFinish:(NSURLDownload *)__unused d { - [self extractUpdate]; + [self extractUpdate]; } -- (void)download:(NSURLDownload *) __unused download didFailWithError:(NSError *)error +- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error { [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), NSLocalizedFailureReasonErrorKey: [error localizedDescription]}]]; } -- (BOOL)download:(NSURLDownload *) __unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType +- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType { - // We don't want the download system to extract our gzips. - // Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug. - return ([encodingType rangeOfString:@"gzip"].location == NSNotFound); + // We don't want the download system to extract our gzips. + // Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug. + return ([encodingType rangeOfString:@"gzip"].location == NSNotFound); } - (void)extractUpdate @@ -259,44 +259,44 @@ SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHost:self.host]; if (!unarchiver) { - SULog(@"Sparkle Error: No valid unarchiver for %@!", self.downloadPath); - [self unarchiverDidFail:nil]; - return; - } - [unarchiver setDelegate:self]; - [unarchiver start]; + SULog(@"Sparkle Error: No valid unarchiver for %@!", self.downloadPath); + [self unarchiverDidFail:nil]; + return; + } + [unarchiver setDelegate:self]; + [unarchiver start]; } - (void)failedToApplyDeltaUpdate { - // When a delta update fails to apply we fall back on updating via a full install. - self.updateItem = self.nonDeltaUpdateItem; - self.nonDeltaUpdateItem = nil; + // When a delta update fails to apply we fall back on updating via a full install. + self.updateItem = self.nonDeltaUpdateItem; + self.nonDeltaUpdateItem = nil; - [self downloadUpdate]; + [self downloadUpdate]; } - (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua { - [self installWithToolAndRelaunch:YES]; + [self installWithToolAndRelaunch:YES]; } - (void)unarchiverDidFail:(SUUnarchiver *)__unused ua { - if ([self.updateItem isDeltaUpdate]) { - [self failedToApplyDeltaUpdate]; - return; - } + if ([self.updateItem isDeltaUpdate]) { + [self failedToApplyDeltaUpdate]; + return; + } - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil)}]]; + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]]; } - (BOOL)shouldInstallSynchronously { return NO; } - (void)installWithToolAndRelaunch:(BOOL)relaunch { - // Perhaps a poor assumption but: if we're not relaunching, we assume we shouldn't be showing any UI either. Because non-relaunching installations are kicked off without any user interaction, we shouldn't be interrupting them. - [self installWithToolAndRelaunch:relaunch displayingUserInterface:relaunch]; + // Perhaps a poor assumption but: if we're not relaunching, we assume we shouldn't be showing any UI either. Because non-relaunching installations are kicked off without any user interaction, we shouldn't be interrupting them. + [self installWithToolAndRelaunch:relaunch displayingUserInterface:relaunch]; } - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI @@ -309,7 +309,7 @@ }; [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:userInfo]]; return; - } + } if (![self.updater mayUpdateAndRestart]) { @@ -329,31 +329,31 @@ postponedOnce = YES; if ([updaterDelegate updater:self.updater shouldPostponeRelaunchForUpdate:self.updateItem untilInvoking:invocation]) { return; + } } - } - if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdate:)]) { + if ([updaterDelegate respondsToSelector:@selector(updater:willInstallUpdate:)]) { [updaterDelegate updater:self.updater willInstallUpdate:self.updateItem]; - } + } NSString *const finishInstallToolName = FINISH_INSTALL_TOOL_NAME_STRING; - // Copy the relauncher into a temporary directory so we can get to it after the new version's installed. - // Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems. - NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:finishInstallToolName ofType:@"app"]; + // Copy the relauncher into a temporary directory so we can get to it after the new version's installed. + // Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems. + NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:finishInstallToolName ofType:@"app"]; if (relaunchPathToCopy != nil) { NSString *targetPath = [[self.host appSupportPath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]]; - // Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems. - NSError *error = nil; - [[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: @{} error: &error]; + // Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems. + NSError *error = nil; + [[NSFileManager defaultManager] createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&error]; - if( [SUPlainInstaller copyPathWithAuthentication: relaunchPathToCopy overPath: targetPath temporaryName: nil error: &error] ) - self.relaunchPath = targetPath; - else + if ([SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error]) + self.relaunchPath = targetPath; + else [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")]}]]; - } + } [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self]; if ([updaterDelegate respondsToSelector:@selector(updaterWillRelaunchApplication:)]) @@ -368,59 +368,59 @@ } NSString *pathToRelaunch = [self.host bundlePath]; - if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { + if ([updaterDelegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater]; - } - NSString *relaunchToolPath = [[self.relaunchPath stringByAppendingPathComponent: @"/Contents/MacOS"] stringByAppendingPathComponent: finishInstallToolName]; - [NSTask launchedTaskWithLaunchPath: relaunchToolPath arguments:@[[self.host bundlePath], - pathToRelaunch, - [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], - self.tempDir, - relaunch ? @"1" : @"0", - showUI ? @"1" : @"0"]]; + } + NSString *relaunchToolPath = [[self.relaunchPath stringByAppendingPathComponent:@"/Contents/MacOS"] stringByAppendingPathComponent:finishInstallToolName]; + [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath], + pathToRelaunch, + [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], + self.tempDir, + relaunch ? @"1" : @"0", + showUI ? @"1" : @"0"]]; [NSApp terminate:self]; } - (void)cleanUpDownload { - if (self.tempDir != nil) // tempDir contains downloadPath, so we implicitly delete both here. - { - BOOL success = NO; - NSError * error = nil; - success = [[NSFileManager defaultManager] removeItemAtPath:self.tempDir error: &error]; // Clean up the copied relauncher - if( !success ) - [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[self.tempDir stringByDeletingLastPathComponent] destination:@"" files:@[[self.tempDir lastPathComponent]] tag:NULL]; - } + if (self.tempDir != nil) // tempDir contains downloadPath, so we implicitly delete both here. + { + BOOL success = NO; + NSError *error = nil; + success = [[NSFileManager defaultManager] removeItemAtPath:self.tempDir error:&error]; // Clean up the copied relauncher + if (!success) + [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[self.tempDir stringByDeletingLastPathComponent] destination:@"" files:@[[self.tempDir lastPathComponent]] tag:NULL]; + } } - (void)installerForHost:(SUHost *)aHost failedWithError:(NSError *)error { if (aHost != self.host) { return; } - NSError * dontThrow = nil; - [[NSFileManager defaultManager] removeItemAtPath:self.relaunchPath error: &dontThrow]; // Clean up the copied relauncher + NSError *dontThrow = nil; + [[NSFileManager defaultManager] removeItemAtPath:self.relaunchPath error:&dontThrow]; // Clean up the copied relauncher [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while installing the update. Please try again later.", nil), NSLocalizedFailureReasonErrorKey: [error localizedDescription]}]]; } - (void)abortUpdate { [self cleanUpDownload]; - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super abortUpdate]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [super abortUpdate]; } - (void)abortUpdateWithError:(NSError *)error { - if ([error code] != SUNoUpdateError) { // Let's not bother logging this. - SULog(@"Sparkle Error: %@", [error localizedDescription]); - } - if ([error localizedFailureReason]) { - SULog(@"Sparkle Error (continued): %@", [error localizedFailureReason]); - } - if (self.download) { - [self.download cancel]; - } - [self abortUpdate]; + if ([error code] != SUNoUpdateError) { // Let's not bother logging this. + SULog(@"Sparkle Error: %@", [error localizedDescription]); + } + if ([error localizedFailureReason]) { + SULog(@"Sparkle Error (continued): %@", [error localizedFailureReason]); + } + if (self.download) { + [self.download cancel]; + } + [self abortUpdate]; } @end diff --git a/Sparkle/SUCodeSigningVerifier.m b/Sparkle/SUCodeSigningVerifier.m index eaefc3d4..b7517fdd 100644 --- a/Sparkle/SUCodeSigningVerifier.m +++ b/Sparkle/SUCodeSigningVerifier.m @@ -81,12 +81,12 @@ finally: CFDictionaryRef signingInfo = nil; const SecCSFlags flags = kSecCSSigningInformation | kSecCSRequirementInformation | kSecCSDynamicInformation | kSecCSContentInformation; if (SecCodeCopySigningInformation(code, flags, &signingInfo) == noErr) { - NSDictionary* signingDict = CFBridgingRelease(signingInfo); - NSMutableDictionary* relevantInfo = [NSMutableDictionary dictionary]; - for (NSString* key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) { + NSDictionary *signingDict = CFBridgingRelease(signingInfo); + NSMutableDictionary *relevantInfo = [NSMutableDictionary dictionary]; + for (NSString *key in @[@"format", @"identifier", @"requirements", @"teamid", @"signing-time"]) { relevantInfo[key] = signingDict[key]; } - NSDictionary* infoPlist = signingDict[@"info-plist"]; + NSDictionary *infoPlist = signingDict[@"info-plist"]; relevantInfo[@"version"] = infoPlist[@"CFBundleShortVersionString"]; relevantInfo[@"build"] = infoPlist[@"CFBundleVersion"]; SULog(@"%@: %@", label, relevantInfo); diff --git a/Sparkle/SUConstants.h b/Sparkle/SUConstants.h index 5b208707..44427965 100644 --- a/Sparkle/SUConstants.h +++ b/Sparkle/SUConstants.h @@ -16,15 +16,15 @@ // Sparkle usually doesn't allow downgrades as they're usually accidental, but // if your app has a downgrade function or URL handler, turn this on: -#define PERMIT_AUTOMATED_DOWNGRADES 0 +#define PERMIT_AUTOMATED_DOWNGRADES 0 // If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it // in place, giving you an app named 1.1b4 that is actually 1.2. Turn the // following on to always reset the name back to "MyApp": -#define NORMALIZE_INSTALLED_APP_NAME 0 +#define NORMALIZE_INSTALLED_APP_NAME 0 -#define TRY_TO_APPEND_VERSION_NUMBER 1 +#define TRY_TO_APPEND_VERSION_NUMBER 1 // ----------------------------------------------------------------------------- // Notifications: diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 1bddd723..f5d39fd9 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -16,28 +16,28 @@ + (BOOL)canUnarchivePath:(NSString *)path { - return [[path pathExtension] isEqualToString:@"dmg"]; + return [[path pathExtension] isEqualToString:@"dmg"]; } // Called on a non-main thread. - (void)extractDMG { @autoreleasepool { - [self extractDMGWithPassword:nil]; - } + [self extractDMGWithPassword:nil]; + } } // Called on a non-main thread. -- (void)extractDMGWithPassword:(NSString *) __unused password +- (void)extractDMGWithPassword:(NSString *)__unused password { @autoreleasepool { - BOOL mountedSuccessfully = NO; + BOOL mountedSuccessfully = NO; SULog(@"Extracting %@ as a DMG", self.archivePath); - // get a unique mount point path - NSString *mountPoint = nil; - FSRef tmpRef; + // get a unique mount point path + NSString *mountPoint = nil; + FSRef tmpRef; NSFileManager *manager; NSError *error; NSArray *contents; @@ -47,122 +47,122 @@ dispatch_block_t delegateFailure = ^{ [self notifyDelegateOfFailure]; }; - dispatch_block_t delegateSuccess = ^{ + dispatch_block_t delegateSuccess = ^{ [self notifyDelegateOfSuccess]; }; do { - // Using NSUUID would make creating UUIDs be done in Cocoa, - // and thus managed under ARC. Sadly, the class is in 10.8 and later. - CFUUIDRef uuid = CFUUIDCreate(NULL); + // Using NSUUID would make creating UUIDs be done in Cocoa, + // and thus managed under ARC. Sadly, the class is in 10.8 and later. + CFUUIDRef uuid = CFUUIDCreate(NULL); if (uuid) { - NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); + NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); if (uuidString) { - mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString]; - } - CFRelease(uuid); - } + mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString]; + } + CFRelease(uuid); + } } while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); - NSData *promptData = nil; - promptData = [NSData dataWithBytes:"yes\n" length:4]; + NSData *promptData = nil; + promptData = [NSData dataWithBytes:"yes\n" length:4]; - NSArray* arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"]; + NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"]; - NSData *output = nil; - NSInteger taskResult = -1; + NSData *output = nil; + NSInteger taskResult = -1; @try { - NTSynchronousTask* task = [[NTSynchronousTask alloc] init]; + NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; - [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; + [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; - taskResult = [task result]; + taskResult = [task result]; output = [[task output] copy]; - } - @catch (NSException *) - { - goto reportError; - } + } + @catch (NSException *) + { + goto reportError; + } if (taskResult != 0) { - NSString* resultStr = output ? [[NSString alloc] initWithData: output encoding: NSUTF8StringEncoding] : nil; - SULog( @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr ); - goto reportError; - } - mountedSuccessfully = YES; + NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil; + SULog(@"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr); + goto reportError; + } + mountedSuccessfully = YES; - // Now that we've mounted it, we need to copy out its contents. + // Now that we've mounted it, we need to copy out its contents. manager = [[NSFileManager alloc] init]; contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; if (error) { - SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); - goto reportError; - } + SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); + goto reportError; + } for (NSString *item in contents) { - NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; + NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; - // We skip any files in the DMG which are not readable. - if (![manager isReadableFileAtPath:fromPath]) { - continue; - } + // We skip any files in the DMG which are not readable. + if (![manager isReadableFileAtPath:fromPath]) { + continue; + } - SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); + SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) { - SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); - goto reportError; - } - } + SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); + goto reportError; + } + } - dispatch_async(dispatch_get_main_queue(), delegateSuccess); - goto finally; + dispatch_async(dispatch_get_main_queue(), delegateSuccess); + goto finally; - reportError: - dispatch_async(dispatch_get_main_queue(), delegateFailure); + reportError: + dispatch_async(dispatch_get_main_queue(), delegateFailure); - finally: - if (mountedSuccessfully) - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; - else + finally: + if (mountedSuccessfully) + [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; + else SULog(@"Can't mount DMG %@", self.archivePath); - } + } } - (void)start { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self extractDMG]; - }); + }); } + (void)load { - [self registerImplementation:self]; + [self registerImplementation:self]; } -- (BOOL)isEncrypted:(NSData*)resultData +- (BOOL)isEncrypted:(NSData *)resultData { - BOOL result = NO; + BOOL result = NO; if(resultData) { - NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; + NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0))) { - result = YES; - } - } - return result; + result = YES; + } + } + return result; } @end diff --git a/Sparkle/SUHost.m b/Sparkle/SUHost.m index df730427..be5fce14 100644 --- a/Sparkle/SUHost.m +++ b/Sparkle/SUHost.m @@ -43,17 +43,17 @@ typedef struct { { if (aBundle == nil) aBundle = [NSBundle mainBundle]; self.bundle = aBundle; - if (![self.bundle bundleIdentifier]) { - SULog(@"Sparkle Error: the bundle being updated at %@ has no CFBundleIdentifier! This will cause preference read/write to not work properly.", self.bundle); - } + if (![self.bundle bundleIdentifier]) { + SULog(@"Sparkle Error: the bundle being updated at %@ has no CFBundleIdentifier! This will cause preference read/write to not work properly.", self.bundle); + } - self.defaultsDomain = [self.bundle objectForInfoDictionaryKey:SUDefaultsDomainKey]; - if (!self.defaultsDomain) { - self.defaultsDomain = [self.bundle bundleIdentifier]; - } + self.defaultsDomain = [self.bundle objectForInfoDictionaryKey:SUDefaultsDomainKey]; + if (!self.defaultsDomain) { + self.defaultsDomain = [self.bundle bundleIdentifier]; + } - // If we're using the main bundle's defaults we'll use the standard user defaults mechanism, otherwise we have to get CF-y. - usesStandardUserDefaults = [self.defaultsDomain isEqualToString:[[NSBundle mainBundle] bundleIdentifier]]; + // If we're using the main bundle's defaults we'll use the standard user defaults mechanism, otherwise we have to get CF-y. + usesStandardUserDefaults = [self.defaultsDomain isEqualToString:[[NSBundle mainBundle] bundleIdentifier]]; } return self; } @@ -77,7 +77,7 @@ typedef struct { } else { appSupportPath = appSupportPaths[0]; - } + } appSupportPath = [appSupportPath stringByAppendingPathComponent:[self name]]; appSupportPath = [appSupportPath stringByAppendingPathComponent:@".Sparkle"]; return appSupportPath; @@ -87,93 +87,93 @@ typedef struct { { #if NORMALIZE_INSTALLED_APP_NAME // We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name. - NSString *normalizedAppPath = [[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [self.bundle objectForInfoDictionaryKey:@"CFBundleName"], [[self.bundle bundlePath] pathExtension]]]; - if (![[NSFileManager defaultManager] fileExistsAtPath:[[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [self.bundle objectForInfoDictionaryKey:@"CFBundleName"], [[self.bundle bundlePath] pathExtension]]]]) { + NSString *normalizedAppPath = [[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self.bundle objectForInfoDictionaryKey:@"CFBundleName"], [[self.bundle bundlePath] pathExtension]]]; + if (![[NSFileManager defaultManager] fileExistsAtPath:[[[self.bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [self.bundle objectForInfoDictionaryKey:@"CFBundleName"], [[self.bundle bundlePath] pathExtension]]]]) { return normalizedAppPath; - } + } #endif - return [self.bundle bundlePath]; + return [self.bundle bundlePath]; } - (NSString *)name { - NSString *name = [self.bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + NSString *name = [self.bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; if (name) return name; - name = [self objectForInfoDictionaryKey:@"CFBundleName"]; + name = [self objectForInfoDictionaryKey:@"CFBundleName"]; if (name) return name; - return [[[NSFileManager defaultManager] displayNameAtPath:[self.bundle bundlePath]] stringByDeletingPathExtension]; + return [[[NSFileManager defaultManager] displayNameAtPath:[self.bundle bundlePath]] stringByDeletingPathExtension]; } - (NSString *)version { - NSString *version = [self.bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; - if (!version || [version isEqualToString:@""]) - [NSException raise:@"SUNoVersionException" format:@"This host (%@) has no CFBundleVersion! This attribute is required.", [self bundlePath]]; - return version; + NSString *version = [self.bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; + if (!version || [version isEqualToString:@""]) + [NSException raise:@"SUNoVersionException" format:@"This host (%@) has no CFBundleVersion! This attribute is required.", [self bundlePath]]; + return version; } - (NSString *)displayVersion { - NSString *shortVersionString = [self.bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - if (shortVersionString) - return shortVersionString; - else - return [self version]; // Fall back on the normal version string. + NSString *shortVersionString = [self.bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + if (shortVersionString) + return shortVersionString; + else + return [self version]; // Fall back on the normal version string. } - (NSImage *)icon { - // Cache the application icon. - NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"]; - // According to the OS X docs, "CFBundleIconFile - This key identifies the file containing - // the icon for the bundle. The filename you specify does not need to include the .icns - // extension, although it may." - // - // However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try: - if (!iconPath) { - iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType: nil]; - } - NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath]; - // Use a default icon if none is defined. - if (!icon) { - BOOL isMainBundle = (self.bundle == [NSBundle mainBundle]); + // Cache the application icon. + NSString *iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"]; + // According to the OS X docs, "CFBundleIconFile - This key identifies the file containing + // the icon for the bundle. The filename you specify does not need to include the .icns + // extension, although it may." + // + // However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try: + if (!iconPath) { + iconPath = [self.bundle pathForResource:[self.bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil]; + } + NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath]; + // Use a default icon if none is defined. + if (!icon) { + BOOL isMainBundle = (self.bundle == [NSBundle mainBundle]); - NSString *fileType = isMainBundle ? (NSString*)kUTTypeApplication : (NSString*)kUTTypeBundle; - icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType]; - } - return icon; + NSString *fileType = isMainBundle ? (NSString *)kUTTypeApplication : (NSString *)kUTTypeBundle; + icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType]; + } + return icon; } - (BOOL)isRunningOnReadOnlyVolume { - struct statfs statfs_info; - statfs([[self.bundle bundlePath] fileSystemRepresentation], &statfs_info); - return (statfs_info.f_flags & MNT_RDONLY); + struct statfs statfs_info; + statfs([[self.bundle bundlePath] fileSystemRepresentation], &statfs_info); + return (statfs_info.f_flags & MNT_RDONLY); } - (BOOL)isBackgroundApplication { - return ([[NSApplication sharedApplication] activationPolicy] == NSApplicationActivationPolicyAccessory); + return ([[NSApplication sharedApplication] activationPolicy] == NSApplicationActivationPolicyAccessory); } - (NSString *)publicDSAKey { - // Maybe the key is just a string in the Info.plist. - NSString *key = [self.bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey]; + // Maybe the key is just a string in the Info.plist. + NSString *key = [self.bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey]; if (key) { return key; } - // More likely, we've got a reference to a Resources file by filename: - NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey]; + // More likely, we've got a reference to a Resources file by filename: + NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey]; if (!keyFilename) { return nil; } - NSError *ignoreErr = nil; - return [NSString stringWithContentsOfFile:[self.bundle pathForResource:keyFilename ofType:nil] encoding:NSASCIIStringEncoding error: &ignoreErr]; + NSError *ignoreErr = nil; + return [NSString stringWithContentsOfFile:[self.bundle pathForResource:keyFilename ofType:nil] encoding:NSASCIIStringEncoding error:&ignoreErr]; } - (NSArray *)systemProfile { - return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self]; + return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self]; } - (id)objectForInfoDictionaryKey:(NSString *)key @@ -183,7 +183,7 @@ typedef struct { - (BOOL)boolForInfoDictionaryKey:(NSString *)key { - return [[self objectForInfoDictionaryKey:key] boolValue]; + return [[self objectForInfoDictionaryKey:key] boolValue]; } - (id)objectForUserDefaultsKey:(NSString *)defaultName @@ -192,60 +192,60 @@ typedef struct { return nil; } - // Under Tiger, CFPreferencesCopyAppValue doesn't get values from NSRegistrationDomain, so anything - // passed into -[NSUserDefaults registerDefaults:] is ignored. The following line falls - // back to using NSUserDefaults, but only if the host bundle is the main bundle. - if (self.usesStandardUserDefaults) { - return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName]; - } + // Under Tiger, CFPreferencesCopyAppValue doesn't get values from NSRegistrationDomain, so anything + // passed into -[NSUserDefaults registerDefaults:] is ignored. The following line falls + // back to using NSUserDefaults, but only if the host bundle is the main bundle. + if (self.usesStandardUserDefaults) { + return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName]; + } - CFPropertyListRef obj = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); - return CFBridgingRelease(obj); + CFPropertyListRef obj = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); + return CFBridgingRelease(obj); } - (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName { if (self.usesStandardUserDefaults) { - [[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName]; + [[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName]; } else { - CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFPropertyListRef)(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - } + CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFPropertyListRef)(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + } } - (BOOL)boolForUserDefaultsKey:(NSString *)defaultName { - if (self.usesStandardUserDefaults) { - return [[NSUserDefaults standardUserDefaults] boolForKey:defaultName]; - } + if (self.usesStandardUserDefaults) { + return [[NSUserDefaults standardUserDefaults] boolForKey:defaultName]; + } - BOOL value; - CFPropertyListRef plr = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); - if (plr == NULL) { - value = NO; + BOOL value; + CFPropertyListRef plr = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); + if (plr == NULL) { + value = NO; } else { - value = (BOOL)CFBooleanGetValue((CFBooleanRef)plr); - CFRelease(plr); - } - return value; + value = (BOOL)CFBooleanGetValue((CFBooleanRef)plr); + CFRelease(plr); + } + return value; } - (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName { if (self.usesStandardUserDefaults) { - [[NSUserDefaults standardUserDefaults] setBool:value forKey:defaultName]; + [[NSUserDefaults standardUserDefaults] setBool:value forKey:defaultName]; } else { - CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFBooleanRef)@(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - } + CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFBooleanRef) @(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + } } - (id)objectForKey:(NSString *)key { diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index fe1b1ffa..0f14562c 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -16,94 +16,94 @@ @implementation SUInstaller -static NSString* sUpdateFolder = nil; +static NSString *sUpdateFolder = nil; -+(NSString*) updateFolder ++ (NSString *)updateFolder { - return sUpdateFolder; + return sUpdateFolder; } + (BOOL)isAliasFolderAtPath:(NSString *)path { - FSRef fileRef; - OSStatus err = noErr; - Boolean aliasFileFlag = false, folderFlag = false; - NSURL *fileURL = [NSURL fileURLWithPath:path]; + FSRef fileRef; + OSStatus err = noErr; + Boolean aliasFileFlag = false, folderFlag = false; + NSURL *fileURL = [NSURL fileURLWithPath:path]; - if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef)) - err = coreFoundationUnknownErr; + if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef)) + err = coreFoundationUnknownErr; - if (noErr == err) - err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag); + if (noErr == err) + err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag); - if (noErr == err) - return !!(aliasFileFlag && folderFlag); - else - return NO; + if (noErr == err) + return !!(aliasFileFlag && folderFlag); + else + return NO; } + (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr { // Search subdirectories for the application - NSString *currentFile, - *newAppDownloadPath = nil, - *bundleFileName = [[host bundlePath] lastPathComponent], - *alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]]; - BOOL isPackage = NO; - NSString *fallbackPackagePath = nil; - NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath: inUpdateFolder]; + NSString *currentFile, + *newAppDownloadPath = nil, + *bundleFileName = [[host bundlePath] lastPathComponent], + *alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]]; + BOOL isPackage = NO; + NSString *fallbackPackagePath = nil; + NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder]; - sUpdateFolder = inUpdateFolder; + sUpdateFolder = inUpdateFolder; while ((currentFile = [dirEnum nextObject])) { - NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile]; - if ([[currentFile lastPathComponent] isEqualToString:bundleFileName] || - [[currentFile lastPathComponent] isEqualToString:alternateBundleFileName]) // We found one! - { - isPackage = NO; - newAppDownloadPath = currentPath; - break; + NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile]; + if ([[currentFile lastPathComponent] isEqualToString:bundleFileName] || + [[currentFile lastPathComponent] isEqualToString:alternateBundleFileName]) // We found one! + { + isPackage = NO; + newAppDownloadPath = currentPath; + break; } else if ([[currentFile pathExtension] isEqualToString:@"pkg"] || [[currentFile pathExtension] isEqualToString:@"mpkg"]) { if ([[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]]) { - isPackage = YES; - newAppDownloadPath = currentPath; - break; + isPackage = YES; + newAppDownloadPath = currentPath; + break; } else { - // Remember any other non-matching packages we have seen should we need to use one of them as a fallback. - fallbackPackagePath = currentPath; - } + // Remember any other non-matching packages we have seen should we need to use one of them as a fallback. + fallbackPackagePath = currentPath; + } } else { - // Try matching on bundle identifiers in case the user has changed the name of the host app - NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath]; + // Try matching on bundle identifiers in case the user has changed the name of the host app + NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath]; if(incomingBundle && [[incomingBundle bundleIdentifier] isEqualToString:[[host bundle] bundleIdentifier]]) { - isPackage = NO; - newAppDownloadPath = currentPath; - break; - } - } + isPackage = NO; + newAppDownloadPath = currentPath; + break; + } + } - // Some DMGs have symlinks into /Applications! That's no good! - if ([self isAliasFolderAtPath:currentPath]) - [dirEnum skipDescendents]; - } + // Some DMGs have symlinks into /Applications! That's no good! + if ([self isAliasFolderAtPath:currentPath]) + [dirEnum skipDescendents]; + } - // We don't have a valid path. Try to use the fallback package. + // We don't have a valid path. Try to use the fallback package. if (newAppDownloadPath == nil && fallbackPackagePath != nil) { - isPackage = YES; - newAppDownloadPath = fallbackPackagePath; - } + isPackage = YES; + newAppDownloadPath = fallbackPackagePath; + } if (isPackagePtr) *isPackagePtr = isPackage; return newAppDownloadPath; @@ -133,49 +133,49 @@ static NSString* sUpdateFolder = nil; + (void)mdimportInstallationPath:(NSString *)installationPath { - // *** GETS CALLED ON NON-MAIN THREAD! + // *** GETS CALLED ON NON-MAIN THREAD! - SULog( @"mdimporting" ); + SULog(@"mdimporting"); - NSTask *mdimport = [[NSTask alloc] init]; - [mdimport setLaunchPath:@"/usr/bin/mdimport"]; - [mdimport setArguments:@[installationPath]]; + NSTask *mdimport = [[NSTask alloc] init]; + [mdimport setLaunchPath:@"/usr/bin/mdimport"]; + [mdimport setArguments:@[installationPath]]; @try { - [mdimport launch]; - [mdimport waitUntilExit]; - } - @catch (NSException * launchException) - { - // No big deal. - SULog(@"Sparkle Error: %@", [launchException description]); - } + [mdimport launch]; + [mdimport waitUntilExit]; + } + @catch (NSException *launchException) + { + // No big deal. + SULog(@"Sparkle Error: %@", [launchException description]); + } } -#define SUNotifyDictHostKey @"SUNotifyDictHost" -#define SUNotifyDictErrorKey @"SUNotifyDictError" -#define SUNotifyDictDelegateKey @"SUNotifyDictDelegate" +#define SUNotifyDictHostKey @"SUNotifyDictHost" +#define SUNotifyDictErrorKey @"SUNotifyDictError" +#define SUNotifyDictDelegateKey @"SUNotifyDictDelegate" + (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:(id)delegate { if (result) { - [self mdimportInstallationPath:installationPath]; - if ([delegate respondsToSelector:@selector(installerFinishedForHost:)]) { - dispatch_async(dispatch_get_main_queue(), ^{ + [self mdimportInstallationPath:installationPath]; + if ([delegate respondsToSelector:@selector(installerFinishedForHost:)]) { + dispatch_async(dispatch_get_main_queue(), ^{ [delegate installerFinishedForHost:host]; - }); - } + }); + } } else { - if ([delegate respondsToSelector:@selector(installerForHost:failedWithError:)]) { - dispatch_async(dispatch_get_main_queue(), ^{ + if ([delegate respondsToSelector:@selector(installerForHost:failedWithError:)]) { + dispatch_async(dispatch_get_main_queue(), ^{ [delegate installerForHost:host failedWithError:error]; - }); - } - } + }); + } + } } @end diff --git a/Sparkle/SULog.h b/Sparkle/SULog.h index 00ff2414..e3559b5e 100644 --- a/Sparkle/SULog.h +++ b/Sparkle/SULog.h @@ -25,7 +25,7 @@ // Prototypes: // ----------------------------------------------------------------------------- -void SUClearLog( void ); -void SULog( NSString* format, ... ) NS_FORMAT_FUNCTION(1,2); +void SUClearLog(void); +void SULog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2); diff --git a/Sparkle/SULog.m b/Sparkle/SULog.m index c77cfd38..587776e4 100644 --- a/Sparkle/SULog.m +++ b/Sparkle/SULog.m @@ -18,7 +18,7 @@ // Constants: // ----------------------------------------------------------------------------- -#define LOG_FILE_PATH @"~/Library/Logs/SparkleUpdateLog.log" +#define LOG_FILE_PATH @"~/Library/Logs/SparkleUpdateLog.log" // ----------------------------------------------------------------------------- @@ -36,13 +36,13 @@ // result - same here. // ----------------------------------------------------------------------------- -void SUClearLog( void ) +void SUClearLog(void) { - FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"w"); - if( logfile ) - fclose(logfile); - else - NSLog(@"----- Sparkle Log -----"); + FILE *logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation], "w"); + if (logfile) + fclose(logfile); + else + NSLog(@"----- Sparkle Log -----"); } @@ -56,25 +56,25 @@ void SUClearLog( void ) // ... - More parameters depending on format string's contents. // ----------------------------------------------------------------------------- -void SULog( NSString* format, ... ) +void SULog(NSString *format, ...) { - va_list ap; - va_start(ap, format); - NSString* theStr = [[NSString alloc] initWithFormat: format arguments: ap]; - FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"a"); - if( !logfile ) - NSLog( @"%@",theStr ); + va_list ap; + va_start(ap, format); + NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap]; + FILE *logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation], "a"); + if (!logfile) + NSLog(@"%@", theStr); else { - theStr = [NSString stringWithFormat: @"%@: %@", [NSDate date], theStr]; - NSData* theData = [theStr dataUsingEncoding: NSUTF8StringEncoding]; - char newlineChar = '\n'; - fwrite( [theData bytes], 1, [theData length], logfile ); - fwrite( &newlineChar, 1, 1, logfile ); // Append a newline. - fclose( logfile ); - logfile = NULL; - } - va_end(ap); + theStr = [NSString stringWithFormat:@"%@: %@", [NSDate date], theStr]; + NSData *theData = [theStr dataUsingEncoding:NSUTF8StringEncoding]; + char newlineChar = '\n'; + fwrite([theData bytes], 1, [theData length], logfile); + fwrite(&newlineChar, 1, 1, logfile); // Append a newline. + fclose(logfile); + logfile = NULL; + } + va_end(ap); } diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 6a897385..1f2f68ea 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -15,23 +15,23 @@ + (SEL)selectorConformingToTypeOfPath:(NSString *)path { - static NSDictionary *typeSelectorDictionary; - if (!typeSelectorDictionary) - typeSelectorDictionary = @{@".zip": @"extractZIP", + static NSDictionary *typeSelectorDictionary; + if (!typeSelectorDictionary) + typeSelectorDictionary = @{ @".zip": @"extractZIP", @".tar": @"extractTAR", - @".tar.gz": @"extractTGZ", + @".tar.gz": @"extractTGZ", @".tgz": @"extractTGZ", - @".tar.bz2": @"extractTBZ", - @".tbz": @"extractTBZ"}; + @".tar.bz2": @"extractTBZ", + @".tbz": @"extractTBZ" }; - NSString *lastPathComponent = [path lastPathComponent]; + NSString *lastPathComponent = [path lastPathComponent]; for (NSString *currentType in typeSelectorDictionary) { if ([currentType length] > [lastPathComponent length]) continue; - if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) - return NSSelectorFromString(typeSelectorDictionary[currentType]); - } - return NULL; + if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) + return NSSelectorFromString(typeSelectorDictionary[currentType]); + } + return NULL; } - (void)start @@ -41,16 +41,16 @@ + (BOOL)canUnarchivePath:(NSString *)path { - return ([self selectorConformingToTypeOfPath:path] != nil); + return ([self selectorConformingToTypeOfPath:path] != nil); } // This method abstracts the types that use a command line tool piping data from stdin. - (void)extractArchivePipingDataToCommand:(NSString *)command { - // *** GETS CALLED ON NON-MAIN THREAD!!! + // *** GETS CALLED ON NON-MAIN THREAD!!! @autoreleasepool { - FILE *fp = NULL, *cmdFP = NULL; - char *oldDestinationString = NULL; + FILE *fp = NULL, *cmdFP = NULL; + char *oldDestinationString = NULL; // We have to declare these before a goto to prevent an error under ARC. // No, we cannot have them in the dispatch_async calls, as the goto "jump enters // lifetime of block which strongly captures a variable" @@ -61,91 +61,91 @@ [self notifyDelegateOfFailure]; }; - SULog(@"Extracting %@ using '%@'", self.archivePath,command); + SULog(@"Extracting %@ using '%@'", self.archivePath, command); - // Get the file size. + // Get the file size. NSNumber *fs = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil][NSFileSize]; if (fs == nil) goto reportError; - // Thank you, Allan Odgaard! - // (who wrote the following extraction alg.) + // Thank you, Allan Odgaard! + // (who wrote the following extraction alg.) fp = fopen([self.archivePath fileSystemRepresentation], "r"); if (!fp) goto reportError; - oldDestinationString = getenv("DESTINATION"); + oldDestinationString = getenv("DESTINATION"); setenv("DESTINATION", [[self.archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], 1); - cmdFP = popen([command fileSystemRepresentation], "w"); - size_t written; + cmdFP = popen([command fileSystemRepresentation], "w"); + size_t written; if (!cmdFP) goto reportError; - char buf[32*1024]; - size_t len; + char buf[32 * 1024]; + size_t len; while((len = fread(buf, 1, 32*1024, fp))) { - written = fwrite(buf, 1, len, cmdFP); + written = fwrite(buf, 1, len, cmdFP); if( written < len ) { - pclose(cmdFP); - goto reportError; - } + pclose(cmdFP); + goto reportError; + } - dispatch_async(dispatch_get_main_queue(), ^{ + dispatch_async(dispatch_get_main_queue(), ^{ [self notifyDelegateOfExtractedLength:len]; - }); - } - pclose(cmdFP); + }); + } + pclose(cmdFP); - if (ferror(fp)) { - goto reportError; - } + if (ferror(fp)) { + goto reportError; + } - dispatch_async(dispatch_get_main_queue(), delegateSuccess); - goto finally; + dispatch_async(dispatch_get_main_queue(), delegateSuccess); + goto finally; - reportError: - dispatch_async(dispatch_get_main_queue(), delegateFailure); + reportError: + dispatch_async(dispatch_get_main_queue(), delegateFailure); - finally: - if (fp) - fclose(fp); - if (oldDestinationString) - setenv("DESTINATION", oldDestinationString, 1); - else - unsetenv("DESTINATION"); - } + finally: + if (fp) + fclose(fp); + if (oldDestinationString) + setenv("DESTINATION", oldDestinationString, 1); + else + unsetenv("DESTINATION"); + } } - (void)extractTAR { - // *** GETS CALLED ON NON-MAIN THREAD!!! + // *** GETS CALLED ON NON-MAIN THREAD!!! - [self extractArchivePipingDataToCommand:@"tar -xC \"$DESTINATION\""]; + [self extractArchivePipingDataToCommand:@"tar -xC \"$DESTINATION\""]; } - (void)extractTGZ { - // *** GETS CALLED ON NON-MAIN THREAD!!! + // *** GETS CALLED ON NON-MAIN THREAD!!! - [self extractArchivePipingDataToCommand:@"tar -zxC \"$DESTINATION\""]; + [self extractArchivePipingDataToCommand:@"tar -zxC \"$DESTINATION\""]; } - (void)extractTBZ { - // *** GETS CALLED ON NON-MAIN THREAD!!! + // *** GETS CALLED ON NON-MAIN THREAD!!! - [self extractArchivePipingDataToCommand:@"tar -jxC \"$DESTINATION\""]; + [self extractArchivePipingDataToCommand:@"tar -jxC \"$DESTINATION\""]; } - (void)extractZIP { - // *** GETS CALLED ON NON-MAIN THREAD!!! + // *** GETS CALLED ON NON-MAIN THREAD!!! - [self extractArchivePipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""]; + [self extractArchivePipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""]; } + (void)load { - [self registerImplementation:self]; + [self registerImplementation:self]; } @end diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index e38cb81f..8eb98a3b 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -15,16 +15,16 @@ + (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:(id)delegate versionComparator:(id)comparator { - // Prevent malicious downgrades: - #if !PERMIT_AUTOMATED_DOWNGRADES +// Prevent malicious downgrades: +#if !PERMIT_AUTOMATED_DOWNGRADES if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]] == NSOrderedDescending) { - NSString * errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Possible attack in progress! Attempting to \"upgrade\" from %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]]; - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; - [self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate]; - return; - } - #endif + NSString *errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Possible attack in progress! Attempting to \"upgrade\" from %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]]; + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + [self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate]; + return; + } +#endif dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; diff --git a/Sparkle/SUPlainInstallerInternals.h b/Sparkle/SUPlainInstallerInternals.h index 24cd49a2..1bb645d4 100644 --- a/Sparkle/SUPlainInstallerInternals.h +++ b/Sparkle/SUPlainInstallerInternals.h @@ -15,7 +15,7 @@ + (NSString *)temporaryNameForPath:(NSString *)path; + (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error; + (void)_movePathToTrash:(NSString *)path; -+ (BOOL)_removeFileAtPath:(NSString *)path error: (NSError**)error; ++ (BOOL)_removeFileAtPath:(NSString *)path error:(NSError **)error; + (BOOL)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError **)error; @end diff --git a/Sparkle/SUPlainInstallerInternals.m b/Sparkle/SUPlainInstallerInternals.m index 46c9030d..09504b17 100644 --- a/Sparkle/SUPlainInstallerInternals.m +++ b/Sparkle/SUPlainInstallerInternals.m @@ -25,11 +25,11 @@ static inline void PerformOnMainThreadSync(dispatch_block_t theBlock) { - if ([NSThread isMainThread]) { - theBlock(); - } else { - dispatch_sync(dispatch_get_main_queue(), theBlock); - } + if ([NSThread isMainThread]) { + theBlock(); + } else { + dispatch_sync(dispatch_get_main_queue(), theBlock); + } } @interface SUPlainInstaller (MMExtendedAttributes) @@ -51,31 +51,31 @@ static inline void PerformOnMainThreadSync(dispatch_block_t theBlock) // that the quarantine is implemented in part by setting an extended attribute, // "com.apple.quarantine", on affected files. Removing this attribute is // sufficient to remove files from the quarantine. -+ (void)releaseFromQuarantine:(NSString*)root; ++ (void)releaseFromQuarantine:(NSString *)root; @end // Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan! #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // this is terrible; will fix later probably -static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments) +static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, const char *const *arguments) { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - BOOL returnValue = YES; + sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); + BOOL returnValue = YES; if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, (char* const*)arguments, NULL) == errAuthorizationSuccess) { - int status; - pid_t pid = wait(&status); - if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) - returnValue = NO; + int status; + pid_t pid = wait(&status); + if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) + returnValue = NO; } else - returnValue = NO; + returnValue = NO; - signal(SIGCHLD, oldSigChildHandler); - return returnValue; + signal(SIGCHLD, oldSigChildHandler); + return returnValue; } #pragma clang diagnostic pop @@ -83,405 +83,405 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza + (NSString *)temporaryNameForPath:(NSString *)path { - // Let's try to read the version number so the filename will be more meaningful. - NSString *postFix; - NSString *version; + // Let's try to read the version number so the filename will be more meaningful. + NSString *postFix; + NSString *version; if ((version = [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""]) { - NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; - [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; - postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; + NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; + [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; + postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; } else - postFix = @"old"; - NSString *prefix = [[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix]; - NSString *tempDir = [prefix stringByAppendingPathExtension:[path pathExtension]]; - // Now let's make sure we get a unique path. - unsigned int cnt=2; - while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999) - tempDir = [NSString stringWithFormat:@"%@ %u.%@", prefix, cnt++, [path pathExtension]]; - return [tempDir lastPathComponent]; + postFix = @"old"; + NSString *prefix = [[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix]; + NSString *tempDir = [prefix stringByAppendingPathExtension:[path pathExtension]]; + // Now let's make sure we get a unique path. + unsigned int cnt = 2; + while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999) + tempDir = [NSString stringWithFormat:@"%@ %u.%@", prefix, cnt++, [path pathExtension]]; + return [tempDir lastPathComponent]; } -+ (NSString *)_temporaryCopyNameForPath:(NSString *)path didFindTrash: (BOOL*)outDidFindTrash ++ (NSString *)_temporaryCopyNameForPath:(NSString *)path didFindTrash:(BOOL *)outDidFindTrash { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - NSString *tempDir = nil; + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + NSString *tempDir = nil; - UInt8 trashPath[MAXPATHLEN +1] = { 0 }; - FSRef trashRef, pathRef; - FSVolumeRefNum vSrcRefNum = kFSInvalidVolumeRefNum; - FSCatalogInfo catInfo; - memset( &catInfo, 0, sizeof(catInfo) ); - OSStatus err = FSPathMakeRef( (UInt8*) [path fileSystemRepresentation], &pathRef, NULL ); + UInt8 trashPath[MAXPATHLEN + 1] = { 0 }; + FSRef trashRef, pathRef; + FSVolumeRefNum vSrcRefNum = kFSInvalidVolumeRefNum; + FSCatalogInfo catInfo; + memset(&catInfo, 0, sizeof(catInfo)); + OSStatus err = FSPathMakeRef((UInt8 *)[path fileSystemRepresentation], &pathRef, NULL); if( err == noErr ) { - err = FSGetCatalogInfo( &pathRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL ); - vSrcRefNum = catInfo.volume; - } - if( err == noErr ) - err = FSFindFolder( vSrcRefNum, kTrashFolderType, kCreateFolder, &trashRef ); - if( err == noErr ) - err = FSGetCatalogInfo( &trashRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL ); - if( err == noErr && vSrcRefNum != catInfo.volume ) - err = nsvErr; // Couldn't find a trash folder on same volume as given path. Docs say this may happen in the future. - if( err == noErr ) - err = FSRefMakePath( &trashRef, trashPath, MAXPATHLEN ); - if( err == noErr ) - tempDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: (char*) trashPath length: strlen((char*) trashPath)]; - if( outDidFindTrash ) - *outDidFindTrash = (tempDir != nil); - if( !tempDir ) - tempDir = [path stringByDeletingLastPathComponent]; + err = FSGetCatalogInfo(&pathRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL); + vSrcRefNum = catInfo.volume; + } + if (err == noErr) + err = FSFindFolder(vSrcRefNum, kTrashFolderType, kCreateFolder, &trashRef); + if (err == noErr) + err = FSGetCatalogInfo(&trashRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL); + if (err == noErr && vSrcRefNum != catInfo.volume) + err = nsvErr; // Couldn't find a trash folder on same volume as given path. Docs say this may happen in the future. + if (err == noErr) + err = FSRefMakePath(&trashRef, trashPath, MAXPATHLEN); + if (err == noErr) + tempDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:(char *)trashPath length:strlen((char *)trashPath)]; + if (outDidFindTrash) + *outDidFindTrash = (tempDir != nil); + if (!tempDir) + tempDir = [path stringByDeletingLastPathComponent]; - // Let's try to read the version number so the filename will be more meaningful. - #if TRY_TO_APPEND_VERSION_NUMBER - NSString *postFix = nil; - NSString *version = nil; +// Let's try to read the version number so the filename will be more meaningful. +#if TRY_TO_APPEND_VERSION_NUMBER + NSString *postFix = nil; + NSString *version = nil; if ((version = [[NSBundle bundleWithPath: path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""]) { - NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; - [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; - postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; + NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; + [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; + postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; } else { - postFix = @"old"; - } - NSString *prefix = [NSString stringWithFormat: @"%@ (%@)", [[path lastPathComponent] stringByDeletingPathExtension], postFix]; - #else - NSString *prefix = [[path lastPathComponent] stringByDeletingPathExtension]; - #endif - NSString *tempName = [prefix stringByAppendingPathExtension: [path pathExtension]]; - tempDir = [tempDir stringByAppendingPathComponent: tempName]; + postFix = @"old"; + } + NSString *prefix = [NSString stringWithFormat:@"%@ (%@)", [[path lastPathComponent] stringByDeletingPathExtension], postFix]; +#else + NSString *prefix = [[path lastPathComponent] stringByDeletingPathExtension]; +#endif + NSString *tempName = [prefix stringByAppendingPathExtension:[path pathExtension]]; + tempDir = [tempDir stringByAppendingPathComponent:tempName]; - // Now let's make sure we get a unique path. - int cnt=2; - while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 9999) { - tempDir = [[tempDir stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]]]; - } + // Now let's make sure we get a unique path. + int cnt = 2; + while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 9999) { + tempDir = [[tempDir stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]]]; + } - return tempDir; + return tempDir; } + (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst temporaryPath:(NSString *)tmp error:(NSError *__autoreleasing *)error { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - const char* srcPath = [src fileSystemRepresentation]; - const char* tmpPath = [tmp fileSystemRepresentation]; - const char* dstPath = [dst fileSystemRepresentation]; + const char *srcPath = [src fileSystemRepresentation]; + const char *tmpPath = [tmp fileSystemRepresentation]; + const char *dstPath = [dst fileSystemRepresentation]; - struct stat dstSB; - if( stat(dstPath, &dstSB) != 0 ) // Doesn't exist yet, try containing folder. - { - const char* dstDirPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation]; + struct stat dstSB; + if (stat(dstPath, &dstSB) != 0) // Doesn't exist yet, try containing folder. + { + const char *dstDirPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation]; if( stat(dstDirPath, &dstSB) != 0 ) { - NSString *errorMessage = [NSString stringWithFormat:@"Stat on %@ during authenticated file copy failed.", dst]; - if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; - return NO; - } - } + NSString *errorMessage = [NSString stringWithFormat:@"Stat on %@ during authenticated file copy failed.", dst]; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + return NO; + } + } - AuthorizationRef auth = NULL; - OSStatus authStat = errAuthorizationDenied; - while (authStat == errAuthorizationDenied) { - authStat = AuthorizationCreate(NULL, - kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults, - &auth); - } + AuthorizationRef auth = NULL; + OSStatus authStat = errAuthorizationDenied; + while (authStat == errAuthorizationDenied) { + authStat = AuthorizationCreate(NULL, + kAuthorizationEmptyEnvironment, + kAuthorizationFlagDefaults, + &auth); + } - BOOL res = NO; - if (authStat == errAuthorizationSuccess) { - res = YES; + BOOL res = NO; + if (authStat == errAuthorizationSuccess) { + res = YES; - char uidgid[42]; - snprintf(uidgid, sizeof(uidgid), "%u:%u", - dstSB.st_uid, dstSB.st_gid); + char uidgid[42]; + snprintf(uidgid, sizeof(uidgid), "%u:%u", + dstSB.st_uid, dstSB.st_gid); - // If the currently-running application is trusted, the new - // version should be trusted as well. Remove it from the - // quarantine to avoid a delay at launch, and to avoid - // presenting the user with a confusing trust dialog. - // - // This needs to be done after the application is moved to its - // new home with "mv" in case it's moved across filesystems: if - // that happens, "mv" actually performs a copy and may result - // in the application being quarantined. It also needs to be - // done before "chown" changes ownership, because the ownership - // change will almost certainly make it impossible to change - // attributes to release the files from the quarantine. + // If the currently-running application is trusted, the new + // version should be trusted as well. Remove it from the + // quarantine to avoid a delay at launch, and to avoid + // presenting the user with a confusing trust dialog. + // + // This needs to be done after the application is moved to its + // new home with "mv" in case it's moved across filesystems: if + // that happens, "mv" actually performs a copy and may result + // in the application being quarantined. It also needs to be + // done before "chown" changes ownership, because the ownership + // change will almost certainly make it impossible to change + // attributes to release the files from the quarantine. if (res) { - SULog(@"releaseFromQuarantine"); - PerformOnMainThreadSync(^{ + SULog(@"releaseFromQuarantine"); + PerformOnMainThreadSync(^{ [self releaseFromQuarantine:src]; - }); - } + }); + } - if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination. - { - const char* coParams[] = { "-R", uidgid, srcPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams ); - if( !res ) - SULog( @"chown -R %s %s failed.", uidgid, srcPath ); - } + if (res) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination. + { + const char *coParams[] = { "-R", uidgid, srcPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams); + if (!res) + SULog(@"chown -R %s %s failed.", uidgid, srcPath); + } - BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst]; - if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first. - { - const char* rmParams[] = { "-rf", tmpPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams ); - if( !res ) - SULog( @"rm failed" ); - } + BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath:dst]; + if (res && haveDst) // If there's something at our tmp path (previous failed update or whatever) delete that first. + { + const char *rmParams[] = { "-rf", tmpPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams); + if (!res) + SULog(@"rm failed"); + } - if( res && haveDst ) // Move old exe to tmp path. - { - const char* mvParams[] = { "-f", dstPath, tmpPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams ); - if( !res ) - SULog( @"mv 1 failed" ); - } + if (res && haveDst) // Move old exe to tmp path. + { + const char *mvParams[] = { "-f", dstPath, tmpPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams); + if (!res) + SULog(@"mv 1 failed"); + } - if( res ) // Move new exe to old exe's path. - { - const char* mvParams2[] = { "-f", srcPath, dstPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2 ); - if( !res ) - SULog( @"mv 2 failed" ); - } + if (res) // Move new exe to old exe's path. + { + const char *mvParams2[] = { "-f", srcPath, dstPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2); + if (!res) + SULog(@"mv 2 failed"); + } -// if( res && haveDst /*&& !foundTrash*/ ) // If we managed to put the old exe in the trash, leave it there for the user to delete or recover. -// { // ... Otherwise we better delete it, wouldn't want dozens of old versions lying around next to the new one. -// const char* rmParams2[] = { "-rf", tmpPath, NULL }; -// res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 ); -// } + // if( res && haveDst /*&& !foundTrash*/ ) // If we managed to put the old exe in the trash, leave it there for the user to delete or recover. + // { // ... Otherwise we better delete it, wouldn't want dozens of old versions lying around next to the new one. + // const char* rmParams2[] = { "-rf", tmpPath, NULL }; + // res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 ); + // } - AuthorizationFree(auth, 0); + AuthorizationFree(auth, 0); - // If the currently-running application is trusted, the new - // version should be trusted as well. Remove it from the - // quarantine to avoid a delay at launch, and to avoid - // presenting the user with a confusing trust dialog. - // - // This needs to be done after the application is moved to its - // new home with "mv" in case it's moved across filesystems: if - // that happens, "mv" actually performs a copy and may result - // in the application being quarantined. + // If the currently-running application is trusted, the new + // version should be trusted as well. Remove it from the + // quarantine to avoid a delay at launch, and to avoid + // presenting the user with a confusing trust dialog. + // + // This needs to be done after the application is moved to its + // new home with "mv" in case it's moved across filesystems: if + // that happens, "mv" actually performs a copy and may result + // in the application being quarantined. if (res) { - SULog(@"releaseFromQuarantine after installing"); - PerformOnMainThreadSync(^{ + SULog(@"releaseFromQuarantine after installing"); + PerformOnMainThreadSync(^{ [self releaseFromQuarantine:dst]; - }); - } + }); + } if (!res) { - // Something went wrong somewhere along the way, but we're not sure exactly where. - NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file copy from %@ to %@ failed.", src, dst]; - if (error != nil) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; - } + // Something went wrong somewhere along the way, but we're not sure exactly where. + NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file copy from %@ to %@ failed.", src, dst]; + if (error != nil) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + } } else { - if (error != nil) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate."}]; - } - return res; + if (error != nil) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate." }]; + } + return res; } + (BOOL)_movePathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError *__autoreleasing *)error { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - const char* srcPath = [src fileSystemRepresentation]; - const char* dstPath = [dst fileSystemRepresentation]; - const char* dstContainerPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation]; + const char *srcPath = [src fileSystemRepresentation]; + const char *dstPath = [dst fileSystemRepresentation]; + const char *dstContainerPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation]; - struct stat dstSB; - stat(dstContainerPath, &dstSB); + struct stat dstSB; + stat(dstContainerPath, &dstSB); - AuthorizationRef auth = NULL; - OSStatus authStat = errAuthorizationDenied; + AuthorizationRef auth = NULL; + OSStatus authStat = errAuthorizationDenied; while( authStat == errAuthorizationDenied ) { - authStat = AuthorizationCreate(NULL, - kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults, - &auth); - } + authStat = AuthorizationCreate(NULL, + kAuthorizationEmptyEnvironment, + kAuthorizationFlagDefaults, + &auth); + } - BOOL res = NO; + BOOL res = NO; if (authStat == errAuthorizationSuccess) { - res = YES; + res = YES; - char uidgid[42]; - snprintf(uidgid, sizeof(uidgid), "%d:%d", - dstSB.st_uid, dstSB.st_gid); + char uidgid[42]; + snprintf(uidgid, sizeof(uidgid), "%d:%d", + dstSB.st_uid, dstSB.st_gid); - if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination. - { - const char* coParams[] = { "-R", uidgid, srcPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams ); - if( !res ) - SULog(@"Can't set permissions"); - } + if (res) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination. + { + const char *coParams[] = { "-R", uidgid, srcPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams); + if (!res) + SULog(@"Can't set permissions"); + } - BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst]; - if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first. - { - const char* rmParams[] = { "-rf", dstPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams ); - if( !res ) - SULog(@"Can't remove destination file"); - } + BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath:dst]; + if (res && haveDst) // If there's something at our tmp path (previous failed update or whatever) delete that first. + { + const char *rmParams[] = { "-rf", dstPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams); + if (!res) + SULog(@"Can't remove destination file"); + } - if( res ) // Move!. - { - const char* mvParams[] = { "-f", srcPath, dstPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams ); - if( !res ) - SULog(@"Can't move source file"); - } + if (res) // Move!. + { + const char *mvParams[] = { "-f", srcPath, dstPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams); + if (!res) + SULog(@"Can't move source file"); + } - AuthorizationFree(auth, 0); + AuthorizationFree(auth, 0); if (!res) { - // Something went wrong somewhere along the way, but we're not sure exactly where. - NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file move from %@ to %@ failed.", src, dst]; - if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; - } + // Something went wrong somewhere along the way, but we're not sure exactly where. + NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file move from %@ to %@ failed.", src, dst]; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + } } else { - if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate."}]; - } - return res; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate." }]; + } + return res; } + (BOOL)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError *__autoreleasing *)error { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - const char* srcPath = [src fileSystemRepresentation]; + const char *srcPath = [src fileSystemRepresentation]; - AuthorizationRef auth = NULL; - OSStatus authStat = errAuthorizationDenied; + AuthorizationRef auth = NULL; + OSStatus authStat = errAuthorizationDenied; while( authStat == errAuthorizationDenied ) { - authStat = AuthorizationCreate(NULL, - kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults, - &auth); - } + authStat = AuthorizationCreate(NULL, + kAuthorizationEmptyEnvironment, + kAuthorizationFlagDefaults, + &auth); + } - BOOL res = NO; + BOOL res = NO; if (authStat == errAuthorizationSuccess) { - res = YES; + res = YES; - if( res ) // If there's something at our tmp path (previous failed update or whatever) delete that first. - { - const char* rmParams[] = { "-rf", srcPath, NULL }; - res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams ); - if( !res ) - SULog(@"Can't remove destination file"); - } + if (res) // If there's something at our tmp path (previous failed update or whatever) delete that first. + { + const char *rmParams[] = { "-rf", srcPath, NULL }; + res = AuthorizationExecuteWithPrivilegesAndWait(auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams); + if (!res) + SULog(@"Can't remove destination file"); + } - AuthorizationFree(auth, 0); + AuthorizationFree(auth, 0); if (!res) { - // Something went wrong somewhere along the way, but we're not sure exactly where. - NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file remove from %@ failed.", src]; - if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; - } + // Something went wrong somewhere along the way, but we're not sure exactly where. + NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file remove from %@ failed.", src]; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + } } else { - if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate."}]; - } - return res; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't get permission to authenticate." }]; + } + return res; } -+ (BOOL)_removeFileAtPath:(NSString *)path error: (NSError*__autoreleasing *)error ++ (BOOL)_removeFileAtPath:(NSString *)path error:(NSError *__autoreleasing *)error { - BOOL success = YES; + BOOL success = YES; if( ![[NSFileManager defaultManager] removeItemAtPath: path error: NULL] ) { - success = [self _removeFileAtPathWithForcedAuthentication: path error: error]; - } + success = [self _removeFileAtPathWithForcedAuthentication:path error:error]; + } - return success; + return success; } + (void)_movePathToTrash:(NSString *)path { - //SULog(@"Moving %@ to the trash.", path); - NSInteger tag = 0; + //SULog(@"Moving %@ to the trash.", path); + NSInteger tag = 0; if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[path stringByDeletingLastPathComponent] destination:@"" files:@[[path lastPathComponent]] tag:&tag]) { - BOOL didFindTrash = NO; - NSString* trashPath = [self _temporaryCopyNameForPath: path didFindTrash: &didFindTrash]; + BOOL didFindTrash = NO; + NSString *trashPath = [self _temporaryCopyNameForPath:path didFindTrash:&didFindTrash]; if( didFindTrash ) { - NSError *err = nil; - if( ![self _movePathWithForcedAuthentication: path toPath: trashPath error: &err] ) - SULog(@"Sparkle error: couldn't move %@ to the trash (%@). %@", path, trashPath, err); + NSError *err = nil; + if (![self _movePathWithForcedAuthentication:path toPath:trashPath error:&err]) + SULog(@"Sparkle error: couldn't move %@ to the trash (%@). %@", path, trashPath, err); } else - SULog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", path); + SULog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", path); } else - ;//SULog(@"Moved %@ to the trash.", path); + ; //SULog(@"Moved %@ to the trash.", path); } -+ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *) __unused tmp error:(NSError *__autoreleasing *)error ++ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)__unused tmp error:(NSError *__autoreleasing *)error { - FSRef srcRef, dstRef, dstDirRef, tmpDirRef; - OSStatus err; - BOOL hadFileAtDest = NO, didFindTrash = NO; - NSString *tmpPath = [self _temporaryCopyNameForPath: dst didFindTrash: &didFindTrash]; + FSRef srcRef, dstRef, dstDirRef, tmpDirRef; + OSStatus err; + BOOL hadFileAtDest = NO, didFindTrash = NO; + NSString *tmpPath = [self _temporaryCopyNameForPath:dst didFindTrash:&didFindTrash]; - // Make FSRef for destination: - err = FSPathMakeRefWithOptions((UInt8 *)[dst fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &dstRef, NULL); - hadFileAtDest = (err == noErr); // There is a file at the destination, move it aside. If we normalized the name, we might not get here, so don't error. + // Make FSRef for destination: + err = FSPathMakeRefWithOptions((UInt8 *)[dst fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &dstRef, NULL); + hadFileAtDest = (err == noErr); // There is a file at the destination, move it aside. If we normalized the name, we might not get here, so don't error. if( hadFileAtDest ) { if (0 != access([dst fileSystemRepresentation], W_OK) || 0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK)) { - return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error]; - } + return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error]; + } } else { - if (0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK) + if (0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK) || 0 != access([[[dst stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK)) { - return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error]; - } - } + return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error]; + } + } if( hadFileAtDest ) { - err = FSPathMakeRef((UInt8 *)[[tmpPath stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL); - if (err != noErr) - FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL); - } + err = FSPathMakeRef((UInt8 *)[[tmpPath stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL); + if (err != noErr) + FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL); + } - err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &dstDirRef, NULL); + err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &dstDirRef, NULL); if (err == noErr && hadFileAtDest) { @@ -490,43 +490,43 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza if (!success && hadFileAtDest) { if (error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath]}]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] }]; return NO; } - } + } - err = FSPathMakeRef((UInt8 *)[src fileSystemRepresentation], &srcRef, NULL); + err = FSPathMakeRef((UInt8 *)[src fileSystemRepresentation], &srcRef, NULL); if (err == noErr) { - NSFileManager *manager = [[NSFileManager alloc] init]; - BOOL success = [manager copyItemAtPath:src toPath:dst error:error]; + NSFileManager *manager = [[NSFileManager alloc] init]; + BOOL success = [manager copyItemAtPath:src toPath:dst error:error]; if (!success) { - // We better move the old version back to its old location - if (hadFileAtDest) { - success = [manager moveItemAtPath:tmpPath toPath:dst error:error]; - } - if (!success && error != NULL) - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath]}]; - return NO; + // We better move the old version back to its old location + if (hadFileAtDest) { + success = [manager moveItemAtPath:tmpPath toPath:dst error:error]; + } + if (!success && error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] }]; + return NO; - } - } + } + } - // If the currently-running application is trusted, the new - // version should be trusted as well. Remove it from the - // quarantine to avoid a delay at launch, and to avoid - // presenting the user with a confusing trust dialog. - // - // This needs to be done after the application is moved to its - // new home in case it's moved across filesystems: if that - // happens, the move is actually a copy, and it may result - // in the application being quarantined. - PerformOnMainThreadSync(^{ + // If the currently-running application is trusted, the new + // version should be trusted as well. Remove it from the + // quarantine to avoid a delay at launch, and to avoid + // presenting the user with a confusing trust dialog. + // + // This needs to be done after the application is moved to its + // new home in case it's moved across filesystems: if that + // happens, the move is actually a copy, and it may result + // in the application being quarantined. + PerformOnMainThreadSync(^{ [self releaseFromQuarantine:dst]; - }); + }); - return YES; + return YES; } @end @@ -537,55 +537,55 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza @implementation SUPlainInstaller (MMExtendedAttributes) -+ (int)removeXAttr:(const char*)name - fromFile:(NSString*)file ++ (int)removeXAttr:(const char *)name + fromFile:(NSString *)file options:(int)options { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - const char* path = NULL; - @try { - path = [file fileSystemRepresentation]; - } + const char *path = NULL; + @try { + path = [file fileSystemRepresentation]; + } @catch (id) { - // -[NSString fileSystemRepresentation] throws an exception if it's - // unable to convert the string to something suitable. Map that to - // EDOM, "argument out of domain", which sort of conveys that there - // was a conversion failure. - errno = EDOM; - return -1; - } + // -[NSString fileSystemRepresentation] throws an exception if it's + // unable to convert the string to something suitable. Map that to + // EDOM, "argument out of domain", which sort of conveys that there + // was a conversion failure. + errno = EDOM; + return -1; + } - return removexattr(path, name, options); + return removexattr(path, name, options); } -+ (void)releaseFromQuarantine:(NSString*)root ++ (void)releaseFromQuarantine:(NSString *)root { - // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! + // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD! - const char* quarantineAttribute = "com.apple.quarantine"; - const int removeXAttrOptions = XATTR_NOFOLLOW; + const char *quarantineAttribute = "com.apple.quarantine"; + const int removeXAttrOptions = XATTR_NOFOLLOW; - [self removeXAttr:quarantineAttribute - fromFile:root - options:removeXAttrOptions]; + [self removeXAttr:quarantineAttribute + fromFile:root + options:removeXAttrOptions]; - // Only recurse if it's actually a directory. Don't recurse into a - // root-level symbolic link. - NSDictionary* rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:root error:nil]; - NSString* rootType = rootAttributes[NSFileType]; + // Only recurse if it's actually a directory. Don't recurse into a + // root-level symbolic link. + NSDictionary *rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:root error:nil]; + NSString *rootType = rootAttributes[NSFileType]; - if (rootType == NSFileTypeDirectory) { - // The NSDirectoryEnumerator will avoid recursing into any contained - // symbolic links, so no further type checks are needed. - NSDirectoryEnumerator* directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:root]; - NSString* file = nil; - while ((file = [directoryEnumerator nextObject])) { - [self removeXAttr:quarantineAttribute - fromFile:[root stringByAppendingPathComponent:file] - options:removeXAttrOptions]; - } - } + if (rootType == NSFileTypeDirectory) { + // The NSDirectoryEnumerator will avoid recursing into any contained + // symbolic links, so no further type checks are needed. + NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:root]; + NSString *file = nil; + while ((file = [directoryEnumerator nextObject])) { + [self removeXAttr:quarantineAttribute + fromFile:[root stringByAppendingPathComponent:file] + options:removeXAttrOptions]; + } + } } @end diff --git a/Sparkle/SUProbingUpdateDriver.m b/Sparkle/SUProbingUpdateDriver.m index fa13ee92..1fde6c6d 100644 --- a/Sparkle/SUProbingUpdateDriver.m +++ b/Sparkle/SUProbingUpdateDriver.m @@ -17,23 +17,23 @@ { id updaterDelegate = [self.updater delegate]; - if ([updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) + if ([updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) [updaterDelegate updater:self.updater didFindValidUpdate:self.updateItem]; - NSDictionary *userInfo = (self.updateItem != nil) ? @{SUUpdaterAppcastItemNotificationKey : self.updateItem} : nil; + NSDictionary *userInfo = (self.updateItem != nil) ? @{ SUUpdaterAppcastItemNotificationKey: self.updateItem } : nil; [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification object:self.updater userInfo:userInfo]; - [self abortUpdate]; + [self abortUpdate]; } - (void)didNotFindUpdate { id updaterDelegate = [self.updater delegate]; - if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { + if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { [updaterDelegate updaterDidNotFindUpdate:self.updater]; - } + } [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater]; - [self abortUpdate]; + [self abortUpdate]; } @end diff --git a/Sparkle/SUScheduledUpdateDriver.m b/Sparkle/SUScheduledUpdateDriver.m index bae98c29..b51fd91d 100644 --- a/Sparkle/SUScheduledUpdateDriver.m +++ b/Sparkle/SUScheduledUpdateDriver.m @@ -25,28 +25,28 @@ - (void)didFindValidUpdate { - self.showErrors = YES; // We only start showing errors after we present the UI for the first time. - [super didFindValidUpdate]; + self.showErrors = YES; // We only start showing errors after we present the UI for the first time. + [super didFindValidUpdate]; } - (void)didNotFindUpdate { id updaterDelegate = [self.updater delegate]; - if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { + if ([updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { [updaterDelegate updaterDidNotFindUpdate:self.updater]; - } + } [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater]; - [self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update. + [self abortUpdate]; // Don't tell the user that no update was found; this was a scheduled update. } - (void)abortUpdateWithError:(NSError *)error { - if (self.showErrors) - [super abortUpdateWithError:error]; - else - [self abortUpdate]; + if (self.showErrors) + [super abortUpdateWithError:error]; + else + [self abortUpdate]; } @end diff --git a/Sparkle/SUStandardVersionComparator.m b/Sparkle/SUStandardVersionComparator.m index 1a82ee3d..bb9eab5a 100644 --- a/Sparkle/SUStandardVersionComparator.m +++ b/Sparkle/SUStandardVersionComparator.m @@ -17,11 +17,11 @@ + (SUStandardVersionComparator *)defaultComparator { - static SUStandardVersionComparator *defaultComparator = nil; - if (defaultComparator == nil) { - defaultComparator = [[SUStandardVersionComparator alloc] init]; - } - return defaultComparator; + static SUStandardVersionComparator *defaultComparator = nil; + if (defaultComparator == nil) { + defaultComparator = [[SUStandardVersionComparator alloc] init]; + } + return defaultComparator; } typedef enum { @@ -50,7 +50,7 @@ typedef enum { NSString *character; NSMutableString *s; NSUInteger i, n; - SUCharacterType oldType, newType; + SUCharacterType oldType, newType; NSMutableArray *parts = [NSMutableArray array]; if ([version length] == 0) { // Nothing to do here @@ -64,7 +64,7 @@ typedef enum { newType = [self typeOfCharacter:character]; if (oldType != newType || oldType == kSeparatorType) { // We've reached a new segment - NSString *aPart = [[NSString alloc] initWithString:s]; + NSString *aPart = [[NSString alloc] initWithString:s]; [parts addObject:aPart]; [s setString:character]; } else { @@ -81,12 +81,12 @@ typedef enum { - (NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB { - NSArray *partsA = [self splitVersionString:versionA]; + NSArray *partsA = [self splitVersionString:versionA]; NSArray *partsB = [self splitVersionString:versionB]; NSString *partA, *partB; NSUInteger i, n; - long long valueA, valueB; + long long valueA, valueB; SUCharacterType typeA, typeB; n = MIN([partsA count], [partsB count]); @@ -139,7 +139,7 @@ typedef enum { // n holds the index of the part we want. NSString *missingPart; SUCharacterType missingType; - NSComparisonResult shorterResult, largerResult; + NSComparisonResult shorterResult, largerResult; if ([partsA count] > [partsB count]) { missingPart = partsA[n]; diff --git a/Sparkle/SUStatusController.h b/Sparkle/SUStatusController.h index af17c3c6..8a279258 100644 --- a/Sparkle/SUStatusController.h +++ b/Sparkle/SUStatusController.h @@ -14,12 +14,12 @@ @class SUHost; @interface SUStatusController : SUWindowController @property (weak) IBOutlet NSButton *actionButton; -@property (weak) IBOutlet NSProgressIndicator* progressBar; +@property (weak) IBOutlet NSProgressIndicator *progressBar; @property (copy) NSString *statusText; @property double progressValue; @property (nonatomic) double maxProgressValue; -@property (getter = isButtonEnabled) BOOL buttonEnabled; +@property (getter=isButtonEnabled) BOOL buttonEnabled; - (instancetype)initWithHost:(SUHost *)host; diff --git a/Sparkle/SUStatusController.m b/Sparkle/SUStatusController.m index 1ac1c694..b1ca3b03 100644 --- a/Sparkle/SUStatusController.m +++ b/Sparkle/SUStatusController.m @@ -31,13 +31,13 @@ - (instancetype)initWithHost:(SUHost *)aHost { - self = [super initWithHost:aHost windowNibName:@"SUStatus"]; + self = [super initWithHost:aHost windowNibName:@"SUStatus"]; if (self) { - self.host = aHost; - [self setShouldCascadeWindows:NO]; - } - return self; + self.host = aHost; + [self setShouldCascadeWindows:NO]; + } + return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; } @@ -48,73 +48,73 @@ [[self window] setLevel:NSFloatingWindowLevel]; } - [[self window] center]; - [[self window] setFrameAutosaveName:@"SUStatusFrame"]; - [self.progressBar setUsesThreadedAnimation:YES]; + [[self window] center]; + [[self window] setFrameAutosaveName:@"SUStatusFrame"]; + [self.progressBar setUsesThreadedAnimation:YES]; } - (NSString *)windowTitle { - return [NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [self.host name]]; } - (NSImage *)applicationIcon { - return [self.host icon]; + return [self.host icon]; } - (void)beginActionWithTitle:(NSString *)aTitle maxProgressValue:(double)aMaxProgressValue statusText:(NSString *)aStatusText { - self.title = aTitle; + self.title = aTitle; - self.maxProgressValue = aMaxProgressValue; - self.statusText = aStatusText; + self.maxProgressValue = aMaxProgressValue; + self.statusText = aStatusText; } - (void)setButtonTitle:(NSString *)aButtonTitle target:(id)target action:(SEL)action isDefault:(BOOL)isDefault { - self.buttonTitle = aButtonTitle; + self.buttonTitle = aButtonTitle; - [self window]; - [self.actionButton sizeToFit]; - // Except we're going to add 15 px for padding. - [self.actionButton setFrameSize:NSMakeSize([self.actionButton frame].size.width + 15, [self.actionButton frame].size.height)]; - // Now we have to move it over so that it's always 15px from the side of the window. - [self.actionButton setFrameOrigin:NSMakePoint([[self window] frame].size.width - 15 - [self.actionButton frame].size.width, [self.actionButton frame].origin.y)]; - // Redisplay superview to clean up artifacts - [[self.actionButton superview] display]; + [self window]; + [self.actionButton sizeToFit]; + // Except we're going to add 15 px for padding. + [self.actionButton setFrameSize:NSMakeSize([self.actionButton frame].size.width + 15, [self.actionButton frame].size.height)]; + // Now we have to move it over so that it's always 15px from the side of the window. + [self.actionButton setFrameOrigin:NSMakePoint([[self window] frame].size.width - 15 - [self.actionButton frame].size.width, [self.actionButton frame].origin.y)]; + // Redisplay superview to clean up artifacts + [[self.actionButton superview] display]; - [self.actionButton setTarget:target]; - [self.actionButton setAction:action]; - [self.actionButton setKeyEquivalent:isDefault ? @"\r" : @""]; + [self.actionButton setTarget:target]; + [self.actionButton setAction:action]; + [self.actionButton setKeyEquivalent:isDefault ? @"\r" : @""]; - // 06/05/2008 Alex: Avoid a crash when cancelling during the extraction - [self setButtonEnabled: (target != nil)]; + // 06/05/2008 Alex: Avoid a crash when cancelling during the extraction + [self setButtonEnabled:(target != nil)]; } - (BOOL)progressBarShouldAnimate { - return YES; + return YES; } - (void)setButtonEnabled:(BOOL)enabled { - [self.actionButton setEnabled:enabled]; + [self.actionButton setEnabled:enabled]; } - (BOOL)isButtonEnabled { - return [self.actionButton isEnabled]; + return [self.actionButton isEnabled]; } - (void)setMaxProgressValue:(double)value { if (value < 0.0) value = 0.0; - maxProgressValue = value; - [self setProgressValue:0.0]; - [self.progressBar setIndeterminate:(value == 0.0)]; - [self.progressBar startAnimation:self]; - [self.progressBar setUsesThreadedAnimation: YES]; + maxProgressValue = value; + [self setProgressValue:0.0]; + [self.progressBar setIndeterminate:(value == 0.0)]; + [self.progressBar startAnimation:self]; + [self.progressBar setUsesThreadedAnimation:YES]; } @end diff --git a/Sparkle/SUSystemProfiler.m b/Sparkle/SUSystemProfiler.m index 091e5c8b..767438d0 100644 --- a/Sparkle/SUSystemProfiler.m +++ b/Sparkle/SUSystemProfiler.m @@ -15,142 +15,142 @@ @implementation SUSystemProfiler + (SUSystemProfiler *)sharedSystemProfiler { - static SUSystemProfiler *sharedSystemProfiler = nil; - if (!sharedSystemProfiler) { - sharedSystemProfiler = [[self alloc] init]; - } - return sharedSystemProfiler; + static SUSystemProfiler *sharedSystemProfiler = nil; + if (!sharedSystemProfiler) { + sharedSystemProfiler = [[self alloc] init]; + } + return sharedSystemProfiler; } - (NSDictionary *)modelTranslationTable { - NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"SUModelTranslation" ofType:@"plist"]; - return [[NSDictionary alloc] initWithContentsOfFile:path]; + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"SUModelTranslation" ofType:@"plist"]; + return [[NSDictionary alloc] initWithContentsOfFile:path]; } - (NSMutableArray *)systemProfileArrayForHost:(SUHost *)host { - NSDictionary *modelTranslation = [self modelTranslationTable]; + NSDictionary *modelTranslation = [self modelTranslationTable]; - // Gather profile information and append it to the URL. - NSMutableArray *profileArray = [NSMutableArray array]; - NSArray *profileDictKeys = @[@"key", @"displayKey", @"value", @"displayValue"]; - int error = 0; - int value = 0; - size_t length = sizeof(value); + // Gather profile information and append it to the URL. + NSMutableArray *profileArray = [NSMutableArray array]; + NSArray *profileDictKeys = @[@"key", @"displayKey", @"value", @"displayValue"]; + int error = 0; + int value = 0; + size_t length = sizeof(value); - // OS version - NSString *currentSystemVersion = [SUHost systemVersionString]; - if (currentSystemVersion != nil) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"osVersion",@"OS Version",currentSystemVersion,currentSystemVersion] forKeys:profileDictKeys]]; - } + // OS version + NSString *currentSystemVersion = [SUHost systemVersionString]; + if (currentSystemVersion != nil) { + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"osVersion", @"OS Version", currentSystemVersion, currentSystemVersion] forKeys:profileDictKeys]]; + } - // CPU type (decoder info for values found here is in mach/machine.h) - error = sysctlbyname("hw.cputype", &value, &length, NULL, 0); - int cpuType = -1; - if (error == 0) { - cpuType = value; - NSString *visibleCPUType; - switch(value) { + // CPU type (decoder info for values found here is in mach/machine.h) + error = sysctlbyname("hw.cputype", &value, &length, NULL, 0); + int cpuType = -1; + if (error == 0) { + cpuType = value; + NSString *visibleCPUType; + switch (value) { case CPU_TYPE_X86: visibleCPUType = @"Intel"; break; case CPU_TYPE_POWERPC: visibleCPUType = @"PowerPC"; break; default: visibleCPUType = @"Unknown"; break; - } - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cputype",@"CPU Type", @(value), visibleCPUType] forKeys:profileDictKeys]]; - } - error = sysctlbyname("hw.cpu64bit_capable", &value, &length, NULL, 0); - if (error != 0) { - error = sysctlbyname("hw.optional.x86_64", &value, &length, NULL, 0); //x86 specific - } - if (error != 0) { - error = sysctlbyname("hw.optional.64bitops", &value, &length, NULL, 0); //PPC specific - } + } + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cputype", @"CPU Type", @(value), visibleCPUType] forKeys:profileDictKeys]]; + } + error = sysctlbyname("hw.cpu64bit_capable", &value, &length, NULL, 0); + if (error != 0) { + error = sysctlbyname("hw.optional.x86_64", &value, &length, NULL, 0); //x86 specific + } + if (error != 0) { + error = sysctlbyname("hw.optional.64bitops", &value, &length, NULL, 0); //PPC specific + } - BOOL is64bit = NO; + BOOL is64bit = NO; - if (error == 0) { - is64bit = value == 1; - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpu64bit", @"CPU is 64-Bit?", @(is64bit), is64bit ? @"Yes" : @"No"] forKeys:profileDictKeys]]; - } - error = sysctlbyname("hw.cpusubtype", &value, &length, NULL, 0); - if (error == 0) { - NSString *visibleCPUSubType; - if (cpuType == 7) { - // Intel - // TODO: other Intel processors, like Core i7, i5, i3, Xeon? - visibleCPUSubType = is64bit ? @"Intel Core 2" : @"Intel Core"; // If anyone knows how to tell a Core Duo from a Core Solo, please email tph@atomicbird.com - } else if (cpuType == 18) { - // PowerPC - switch(value) { + if (error == 0) { + is64bit = value == 1; + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpu64bit", @"CPU is 64-Bit?", @(is64bit), is64bit ? @"Yes" : @"No"] forKeys:profileDictKeys]]; + } + error = sysctlbyname("hw.cpusubtype", &value, &length, NULL, 0); + if (error == 0) { + NSString *visibleCPUSubType; + if (cpuType == 7) { + // Intel + // TODO: other Intel processors, like Core i7, i5, i3, Xeon? + visibleCPUSubType = is64bit ? @"Intel Core 2" : @"Intel Core"; // If anyone knows how to tell a Core Duo from a Core Solo, please email tph@atomicbird.com + } else if (cpuType == 18) { + // PowerPC + switch (value) { case 9: visibleCPUSubType=@"G3"; break; case 10: case 11: visibleCPUSubType=@"G4"; break; case 100: visibleCPUSubType=@"G5"; break; default: visibleCPUSubType=@"Other"; break; - } - } else { - visibleCPUSubType = @"Other"; - } - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpusubtype",@"CPU Subtype", @(value), visibleCPUSubType] forKeys:profileDictKeys]]; - } - error = sysctlbyname("hw.model", NULL, &length, NULL, 0); - if (error == 0) { - char *cpuModel = (char *)malloc(sizeof(char) * length); - if (cpuModel != NULL) { - error = sysctlbyname("hw.model", cpuModel, &length, NULL, 0); - if (error == 0) { - NSString *rawModelName = @(cpuModel); - NSString *visibleModelName = modelTranslation[rawModelName]; - if (visibleModelName == nil) { - visibleModelName = rawModelName; - } - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"model",@"Mac Model", rawModelName, visibleModelName] forKeys:profileDictKeys]]; - } - free(cpuModel); - } - } + } + } else { + visibleCPUSubType = @"Other"; + } + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpusubtype", @"CPU Subtype", @(value), visibleCPUSubType] forKeys:profileDictKeys]]; + } + error = sysctlbyname("hw.model", NULL, &length, NULL, 0); + if (error == 0) { + char *cpuModel = (char *)malloc(sizeof(char) * length); + if (cpuModel != NULL) { + error = sysctlbyname("hw.model", cpuModel, &length, NULL, 0); + if (error == 0) { + NSString *rawModelName = @(cpuModel); + NSString *visibleModelName = modelTranslation[rawModelName]; + if (visibleModelName == nil) { + visibleModelName = rawModelName; + } + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"model", @"Mac Model", rawModelName, visibleModelName] forKeys:profileDictKeys]]; + } + free(cpuModel); + } + } - // Number of CPUs - error = sysctlbyname("hw.ncpu", &value, &length, NULL, 0); - if (error == 0) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"ncpu",@"Number of CPUs", @(value), @(value)] forKeys:profileDictKeys]]; - } + // Number of CPUs + error = sysctlbyname("hw.ncpu", &value, &length, NULL, 0); + if (error == 0) { + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"ncpu", @"Number of CPUs", @(value), @(value)] forKeys:profileDictKeys]]; + } - // User preferred language - NSUserDefaults *defs = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defs objectForKey:@"AppleLanguages"]; - if ([languages count] > 0) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"lang",@"Preferred Language", languages[0], languages[0]] forKeys:profileDictKeys]]; - } + // User preferred language + NSUserDefaults *defs = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defs objectForKey:@"AppleLanguages"]; + if ([languages count] > 0) { + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"lang", @"Preferred Language", languages[0], languages[0]] forKeys:profileDictKeys]]; + } - // Application sending the request - NSString *appName = [host name]; - if (appName) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"appName",@"Application Name", appName, appName] forKeys:profileDictKeys]]; - } - NSString *appVersion = [host version]; - if (appVersion) { - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"appVersion",@"Application Version", appVersion, appVersion] forKeys:profileDictKeys]]; - } + // Application sending the request + NSString *appName = [host name]; + if (appName) { + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"appName", @"Application Name", appName, appName] forKeys:profileDictKeys]]; + } + NSString *appVersion = [host version]; + if (appVersion) { + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"appVersion", @"Application Version", appVersion, appVersion] forKeys:profileDictKeys]]; + } - // Number of displays? + // Number of displays? - // CPU speed - unsigned long hz; - size_t hz_size = sizeof(unsigned long); - if (sysctlbyname("hw.cpufrequency", &hz, &hz_size, NULL, 0) == 0) { - unsigned long mhz = hz / 1000000; - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpuFreqMHz",@"CPU Speed (GHz)", @(mhz), @(mhz / 1000.)] forKeys:profileDictKeys]]; - } + // CPU speed + unsigned long hz; + size_t hz_size = sizeof(unsigned long); + if (sysctlbyname("hw.cpufrequency", &hz, &hz_size, NULL, 0) == 0) { + unsigned long mhz = hz / 1000000; + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"cpuFreqMHz", @"CPU Speed (GHz)", @(mhz), @(mhz / 1000.)] forKeys:profileDictKeys]]; + } - // amount of RAM - unsigned long bytes; - size_t bytes_size = sizeof(unsigned long); - if (sysctlbyname("hw.memsize", &bytes, &bytes_size, NULL, 0) == 0) { - double megabytes = bytes / (1024.*1024.); - [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"ramMB",@"Memory (MB)", @(megabytes), @(megabytes)] forKeys:profileDictKeys]]; - } + // amount of RAM + unsigned long bytes; + size_t bytes_size = sizeof(unsigned long); + if (sysctlbyname("hw.memsize", &bytes, &bytes_size, NULL, 0) == 0) { + double megabytes = bytes / (1024. * 1024.); + [profileArray addObject:[NSDictionary dictionaryWithObjects:@[@"ramMB", @"Memory (MB)", @(megabytes), @(megabytes)] forKeys:profileDictKeys]]; + } - return profileArray; + return profileArray; } @end diff --git a/Sparkle/SUUIBasedUpdateDriver.h b/Sparkle/SUUIBasedUpdateDriver.h index 5fb8885f..fb145072 100644 --- a/Sparkle/SUUIBasedUpdateDriver.h +++ b/Sparkle/SUUIBasedUpdateDriver.h @@ -18,8 +18,8 @@ @interface SUUIBasedUpdateDriver : SUBasicUpdateDriver - (void)showModalAlert:(NSAlert *)alert; -- (IBAction)cancelDownload: (id)sender; -- (void)installAndRestart: (id)sender; +- (IBAction)cancelDownload:(id)sender; +- (void)installAndRestart:(id)sender; @end diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index 4b08b5e5..f9aa8925 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -29,32 +29,32 @@ - (void)didFindValidUpdate { self.updateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:self.updateItem host:self.host]; - [self.updateAlert setDelegate:self]; + [self.updateAlert setDelegate:self]; - id versDisp = nil; + id versDisp = nil; if ([[self.updater delegate] respondsToSelector:@selector(versionDisplayerForUpdater:)]) { versDisp = [[self.updater delegate] versionDisplayerForUpdater:self.updater]; - } - [self.updateAlert setVersionDisplayer: versDisp]; + } + [self.updateAlert setVersionDisplayer:versDisp]; if ([[self.updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)]) { [[self.updater delegate] updater:self.updater didFindValidUpdate:self.updateItem]; - } + } - // 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. + // 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. if ([self.host isBackgroundApplication]) { - [[self.updateAlert window] setHidesOnDeactivate:NO]; - [NSApp activateIgnoringOtherApps:YES]; - } + [[self.updateAlert window] setHidesOnDeactivate:NO]; + [NSApp activateIgnoringOtherApps:YES]; + } - // Only show the update alert if the app is active; otherwise, we'll wait until it is. - if ([NSApp isActive]) - [[self.updateAlert window] makeKeyAndOrderFront:self]; - else - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; + // Only show the update alert if the app is active; otherwise, we'll wait until it is. + if ([NSApp isActive]) + [[self.updateAlert window] makeKeyAndOrderFront:self]; + else + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; } - (void)didNotFindUpdate @@ -72,163 +72,163 @@ [self abortUpdate]; } -- (void)applicationDidBecomeActive:(NSNotification *) __unused aNotification +- (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification { - [[self.updateAlert window] makeKeyAndOrderFront:self]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp]; + [[self.updateAlert window] makeKeyAndOrderFront:self]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp]; } -- (void)updateAlert:(SUUpdateAlert *) __unused alert finishedWithChoice:(SUUpdateAlertChoice)choice +- (void)updateAlert:(SUUpdateAlert *)__unused alert finishedWithChoice:(SUUpdateAlertChoice)choice { - self.updateAlert = nil; + self.updateAlert = nil; [self.host setObject:nil forUserDefaultsKey:SUSkippedVersionKey]; switch (choice) { - case SUInstallUpdateChoice: + case SUInstallUpdateChoice: self.statusController = [[SUStatusController alloc] initWithHost:self.host]; - [self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; - [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO]; - [self.statusController showWindow:self]; - [self downloadUpdate]; - break; + [self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; + [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO]; + [self.statusController showWindow:self]; + [self downloadUpdate]; + break; - case SUOpenInfoURLChoice: - [[NSWorkspace sharedWorkspace] openURL: [self.updateItem infoURL]]; - [self abortUpdate]; - break; + case SUOpenInfoURLChoice: + [[NSWorkspace sharedWorkspace] openURL:[self.updateItem infoURL]]; + [self abortUpdate]; + break; - case SUSkipThisVersionChoice: + case SUSkipThisVersionChoice: [self.host setObject:[self.updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey]; - [self abortUpdate]; - break; + [self abortUpdate]; + break; - case SURemindMeLaterChoice: - [self abortUpdate]; - break; - } + case SURemindMeLaterChoice: + [self abortUpdate]; + break; + } } -- (void)download:(NSURLDownload *) __unused download didReceiveResponse:(NSURLResponse *)response +- (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response { - [self.statusController setMaxProgressValue:[response expectedContentLength]]; + [self.statusController setMaxProgressValue:[response expectedContentLength]]; } - (NSString *)humanReadableSizeFromDouble:(double)value { - if (value < 1000) { - return [NSString stringWithFormat:@"%.0lf %@", value, SULocalizedString(@"B", @"the unit for bytes")]; - } + if (value < 1000) { + return [NSString stringWithFormat:@"%.0lf %@", value, SULocalizedString(@"B", @"the unit for bytes")]; + } - if (value < 1000 * 1000) { - return [NSString stringWithFormat:@"%.0lf %@", value / 1000.0, SULocalizedString(@"KB", @"the unit for kilobytes")]; - } + if (value < 1000 * 1000) { + return [NSString stringWithFormat:@"%.0lf %@", value / 1000.0, SULocalizedString(@"KB", @"the unit for kilobytes")]; + } - if (value < 1000 * 1000 * 1000) { - return [NSString stringWithFormat:@"%.1lf %@", value / 1000.0 / 1000.0, SULocalizedString(@"MB", @"the unit for megabytes")]; - } + if (value < 1000 * 1000 * 1000) { + return [NSString stringWithFormat:@"%.1lf %@", value / 1000.0 / 1000.0, SULocalizedString(@"MB", @"the unit for megabytes")]; + } - return [NSString stringWithFormat:@"%.2lf %@", value / 1000.0 / 1000.0 / 1000.0, SULocalizedString(@"GB", @"the unit for gigabytes")]; + return [NSString stringWithFormat:@"%.2lf %@", value / 1000.0 / 1000.0 / 1000.0, SULocalizedString(@"GB", @"the unit for gigabytes")]; } -- (void)download:(NSURLDownload *) __unused download didReceiveDataOfLength:(NSUInteger)length +- (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length { - [self.statusController setProgressValue:[self.statusController progressValue] + (double)length]; - if ([self.statusController maxProgressValue] > 0.0) - [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ of %@", nil), [self humanReadableSizeFromDouble:[self.statusController progressValue]], [self humanReadableSizeFromDouble:[self.statusController maxProgressValue]]]]; - else - [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ downloaded", nil), [self humanReadableSizeFromDouble:[self.statusController progressValue]]]]; + [self.statusController setProgressValue:[self.statusController progressValue] + (double)length]; + if ([self.statusController maxProgressValue] > 0.0) + [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ of %@", nil), [self humanReadableSizeFromDouble:[self.statusController progressValue]], [self humanReadableSizeFromDouble:[self.statusController maxProgressValue]]]]; + else + [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ downloaded", nil), [self humanReadableSizeFromDouble:[self.statusController progressValue]]]]; } -- (IBAction)cancelDownload:(id) __unused sender +- (IBAction)cancelDownload:(id)__unused sender { if (self.download) [self.download cancel]; - [self abortUpdate]; + [self abortUpdate]; } - (void)extractUpdate { - // Now we have to extract the downloaded archive. - [self.statusController beginActionWithTitle:SULocalizedString(@"Extracting update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; - [self.statusController setButtonEnabled:NO]; - [super extractUpdate]; + // Now we have to extract the downloaded archive. + [self.statusController beginActionWithTitle:SULocalizedString(@"Extracting update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; + [self.statusController setButtonEnabled:NO]; + [super extractUpdate]; } -- (void)unarchiver:(SUUnarchiver *) __unused ua extractedLength:(unsigned long)length +- (void)unarchiver:(SUUnarchiver *)__unused ua extractedLength:(unsigned long)length { - // We do this here instead of in extractUpdate so that we only have a determinate progress bar for archives with progress. + // We do this here instead of in extractUpdate so that we only have a determinate progress bar for archives with progress. if ([self.statusController maxProgressValue] == 0.0) { - NSDictionary * attributes; + NSDictionary *attributes; attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.downloadPath error:nil]; - [self.statusController setMaxProgressValue:[attributes[NSFileSize] doubleValue]]; - } - [self.statusController setProgressValue:[self.statusController progressValue] + (double)length]; + [self.statusController setMaxProgressValue:[attributes[NSFileSize] doubleValue]]; + } + [self.statusController setProgressValue:[self.statusController progressValue] + (double)length]; } -- (void)unarchiverDidFinish:(SUUnarchiver *) __unused ua +- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua { - [self.statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1.0 statusText:nil]; - [self.statusController setProgressValue:1.0]; // Fill the bar. - [self.statusController setButtonEnabled:YES]; - [self.statusController setButtonTitle:SULocalizedString(@"Install and Relaunch", nil) target:self action:@selector(installAndRestart:) isDefault:YES]; - [[self.statusController window] makeKeyAndOrderFront: self]; - [NSApp requestUserAttention:NSInformationalRequest]; + [self.statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1.0 statusText:nil]; + [self.statusController setProgressValue:1.0]; // Fill the bar. + [self.statusController setButtonEnabled:YES]; + [self.statusController setButtonTitle:SULocalizedString(@"Install and Relaunch", nil) target:self action:@selector(installAndRestart:) isDefault:YES]; + [[self.statusController window] makeKeyAndOrderFront:self]; + [NSApp requestUserAttention:NSInformationalRequest]; } -- (void)installAndRestart:(id) __unused sender +- (void)installAndRestart:(id)__unused sender { [self installWithToolAndRelaunch:YES]; } - (void)installWithToolAndRelaunch:(BOOL)relaunch { - [self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; - [self.statusController setButtonEnabled:NO]; - [super installWithToolAndRelaunch:relaunch]; + [self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; + [self.statusController setButtonEnabled:NO]; + [super installWithToolAndRelaunch:relaunch]; - // if a user chooses to NOT relaunch the app (as is the case with WebKit - // when it asks you if you are sure you want to close the app with multiple - // tabs open), the status window still stays on the screen and obscures - // other windows; with this fix, it doesn't + // if a user chooses to NOT relaunch the app (as is the case with WebKit + // when it asks you if you are sure you want to close the app with multiple + // tabs open), the status window still stays on the screen and obscures + // other windows; with this fix, it doesn't if (self.statusController) { - [self.statusController close]; - self.statusController = nil; - } + [self.statusController close]; + self.statusController = nil; + } } - (void)abortUpdateWithError:(NSError *)error { - NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"Update Error!", nil) defaultButton:SULocalizedString(@"Cancel Update", nil) alternateButton:nil otherButton:nil informativeTextWithFormat: @"%@", [error localizedDescription]]; - [self showModalAlert:alert]; - [super abortUpdateWithError:error]; + NSAlert *alert = [NSAlert alertWithMessageText:SULocalizedString(@"Update Error!", nil) defaultButton:SULocalizedString(@"Cancel Update", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", [error localizedDescription]]; + [self showModalAlert:alert]; + [super abortUpdateWithError:error]; } - (void)abortUpdate { if (self.statusController) { - [self.statusController close]; - self.statusController = nil; - } - [super abortUpdate]; + [self.statusController close]; + self.statusController = nil; + } + [super abortUpdate]; } - (void)showModalAlert:(NSAlert *)alert { if ([[self.updater delegate] respondsToSelector:@selector(updaterWillShowModalAlert:)]) { [[self.updater delegate] updaterWillShowModalAlert:self.updater]; - } + } - // When showing a modal alert we need to ensure that background applications - // are focused to inform the user since there is no dock icon to notify them. + // When showing a modal alert we need to ensure that background applications + // are focused to inform the user since there is no dock icon to notify them. if ([self.host isBackgroundApplication]) { [NSApp activateIgnoringOtherApps:YES]; } [alert setIcon:[self.host icon]]; - [alert runModal]; + [alert runModal]; if ([[self.updater delegate] respondsToSelector:@selector(updaterDidShowModalAlert:)]) [[self.updater delegate] updaterDidShowModalAlert:self.updater]; diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index 2faa334f..99f77759 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -25,18 +25,18 @@ { for (id current in [self unarchiverImplementations]) { - if ([current canUnarchivePath:path]) { - return [[current alloc] initWithPath:path host:host]; - } - } - return nil; + if ([current canUnarchivePath:path]) { + return [[current alloc] initWithPath:path host:host]; + } + } + return nil; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } - (void)start { - // No-op + // No-op } - (instancetype)initWithPath:(NSString *)path host:(SUHost *)host @@ -49,7 +49,7 @@ return self; } -+ (BOOL)canUnarchivePath:(NSString *) __unused path ++ (BOOL)canUnarchivePath:(NSString *)__unused path { return NO; } diff --git a/Sparkle/SUUpdateAlert.h b/Sparkle/SUUpdateAlert.h index 55a36d04..d1d07d5e 100644 --- a/Sparkle/SUUpdateAlert.h +++ b/Sparkle/SUUpdateAlert.h @@ -16,10 +16,10 @@ typedef enum { - SUInstallUpdateChoice, - SURemindMeLaterChoice, - SUSkipThisVersionChoice, - SUOpenInfoURLChoice + SUInstallUpdateChoice, + SURemindMeLaterChoice, + SUSkipThisVersionChoice, + SUOpenInfoURLChoice } SUUpdateAlertChoice; @class WebView, SUAppcastItem, SUHost; @@ -39,7 +39,7 @@ typedef enum @protocol SUUpdateAlertDelegate - (void)updateAlert:(SUUpdateAlert *)updateAlert finishedWithChoice:(SUUpdateAlertChoice)updateChoice; @optional -- (void)updateAlert:(SUUpdateAlert *)updateAlert shouldAllowAutoUpdate: (BOOL*)shouldAllowAutoUpdate; +- (void)updateAlert:(SUUpdateAlert *)updateAlert shouldAllowAutoUpdate:(BOOL *)shouldAllowAutoUpdate; @end #endif diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index b79e5d7e..1f8b12ca 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -59,19 +59,19 @@ - (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost { - self = [super initWithHost:host windowNibName:@"SUUpdateAlert"]; + self = [super initWithHost:host windowNibName:@"SUUpdateAlert"]; if (self) { - host = aHost; - updateItem = item; - [self setShouldCascadeWindows:NO]; + host = aHost; + updateItem = item; + [self setShouldCascadeWindows:NO]; - // Alex: This dummy line makes sure that the binary is linked against WebKit. - // The SUUpdateAlert.xib file contains a WebView and if we don't link against WebKit, - // we will get a runtime crash when decoding the NIB. It is better to get a link error. - [WebView MIMETypesShownAsHTML]; - } - return self; + // Alex: This dummy line makes sure that the binary is linked against WebKit. + // The SUUpdateAlert.xib file contains a WebView and if we don't link against WebKit, + // we will get a runtime crash when decoding the NIB. It is better to get a link error. + [WebView MIMETypesShownAsHTML]; + } + return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } @@ -79,101 +79,101 @@ - (void)endWithSelection:(SUUpdateAlertChoice)choice { - [self.releaseNotesView stopLoading:self]; - [self.releaseNotesView setFrameLoadDelegate:nil]; - [self.releaseNotesView setPolicyDelegate:nil]; - [self.releaseNotesView removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. - [self close]; - if ([self.delegate respondsToSelector:@selector(updateAlert:finishedWithChoice:)]) - [self.delegate updateAlert:self finishedWithChoice:choice]; + [self.releaseNotesView stopLoading:self]; + [self.releaseNotesView setFrameLoadDelegate:nil]; + [self.releaseNotesView setPolicyDelegate:nil]; + [self.releaseNotesView removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. + [self close]; + if ([self.delegate respondsToSelector:@selector(updateAlert:finishedWithChoice:)]) + [self.delegate updateAlert:self finishedWithChoice:choice]; } -- (IBAction)installUpdate:(id) __unused sender +- (IBAction)installUpdate:(id)__unused sender { - [self endWithSelection:SUInstallUpdateChoice]; + [self endWithSelection:SUInstallUpdateChoice]; } -- (IBAction)openInfoURL:(id) __unused sender +- (IBAction)openInfoURL:(id)__unused sender { - [self endWithSelection:SUOpenInfoURLChoice]; + [self endWithSelection:SUOpenInfoURLChoice]; } -- (IBAction)skipThisVersion:(id) __unused sender +- (IBAction)skipThisVersion:(id)__unused sender { - [self endWithSelection:SUSkipThisVersionChoice]; + [self endWithSelection:SUSkipThisVersionChoice]; } -- (IBAction)remindMeLater:(id) __unused sender +- (IBAction)remindMeLater:(id)__unused sender { - [self endWithSelection:SURemindMeLaterChoice]; + [self endWithSelection:SURemindMeLaterChoice]; } - (void)displayReleaseNotes { - // Set the default font - [self.releaseNotesView setPreferencesIdentifier:[SPARKLE_BUNDLE bundleIdentifier]]; + // Set the default font + [self.releaseNotesView setPreferencesIdentifier:[SPARKLE_BUNDLE bundleIdentifier]]; WebPreferences *prefs = [self.releaseNotesView preferences]; NSString *familyName = [[NSFont systemFontOfSize:8] familyName]; if ([familyName hasPrefix:@"."]) { // 10.9 returns ".Lucida Grande UI", which isn't a valid name for the WebView familyName = @"Lucida Grande"; } - [prefs setStandardFontFamily:familyName]; - [prefs setDefaultFontSize:(int)[NSFont systemFontSizeForControlSize:NSSmallControlSize]]; + [prefs setStandardFontFamily:familyName]; + [prefs setDefaultFontSize:(int)[NSFont systemFontSizeForControlSize:NSSmallControlSize]]; [prefs setPlugInsEnabled:NO]; - [self.releaseNotesView setFrameLoadDelegate:self]; - [self.releaseNotesView setPolicyDelegate:self]; + [self.releaseNotesView setFrameLoadDelegate:self]; + [self.releaseNotesView setPolicyDelegate:self]; - // Stick a nice big spinner in the middle of the web view until the page is loaded. - NSRect frame = [[self.releaseNotesView superview] frame]; - self.releaseNotesSpinner = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(NSMidX(frame)-16, NSMidY(frame)-16, 32, 32)]; - [self.releaseNotesSpinner setStyle:NSProgressIndicatorSpinningStyle]; - [self.releaseNotesSpinner startAnimation:self]; - self.webViewFinishedLoading = NO; - [[self.releaseNotesView superview] addSubview:self.releaseNotesSpinner]; + // Stick a nice big spinner in the middle of the web view until the page is loaded. + NSRect frame = [[self.releaseNotesView superview] frame]; + self.releaseNotesSpinner = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(NSMidX(frame) - 16, NSMidY(frame) - 16, 32, 32)]; + [self.releaseNotesSpinner setStyle:NSProgressIndicatorSpinningStyle]; + [self.releaseNotesSpinner startAnimation:self]; + self.webViewFinishedLoading = NO; + [[self.releaseNotesView superview] addSubview:self.releaseNotesSpinner]; - // If there's a release notes URL, load it; otherwise, just stick the contents of the description into the web view. + // If there's a release notes URL, load it; otherwise, just stick the contents of the description into the web view. if ([self.updateItem releaseNotesURL]) { if ([[self.updateItem releaseNotesURL] isFileURL]) { - [[self.releaseNotesView mainFrame] loadHTMLString:@"Release notes with file:// URLs are not supported for security reasons—Javascript would be able to read files on your file system." baseURL:nil]; + [[self.releaseNotesView mainFrame] loadHTMLString:@"Release notes with file:// URLs are not supported for security reasons—Javascript would be able to read files on your file system." baseURL:nil]; } else { - [[self.releaseNotesView mainFrame] loadRequest:[NSURLRequest requestWithURL:[self.updateItem releaseNotesURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]]; - } + [[self.releaseNotesView mainFrame] loadRequest:[NSURLRequest requestWithURL:[self.updateItem releaseNotesURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]]; + } } else { - [[self.releaseNotesView mainFrame] loadHTMLString:[self.updateItem itemDescription] baseURL:nil]; - } + [[self.releaseNotesView mainFrame] loadHTMLString:[self.updateItem itemDescription] baseURL:nil]; + } } - (BOOL)showsReleaseNotes { - NSNumber *shouldShowReleaseNotes = [self.host objectForInfoDictionaryKey:SUShowReleaseNotesKey]; + NSNumber *shouldShowReleaseNotes = [self.host objectForInfoDictionaryKey:SUShowReleaseNotesKey]; if (shouldShowReleaseNotes == nil) { - // Don't show release notes if RSS item contains no description and no release notes URL: - return( ([self.updateItem itemDescription] != nil - && [[[self.updateItem itemDescription] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) - || [self.updateItem releaseNotesURL] != nil ); + // Don't show release notes if RSS item contains no description and no release notes URL: + return (([self.updateItem itemDescription] != nil + && [[[self.updateItem itemDescription] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) + || [self.updateItem releaseNotesURL] != nil); } else - return [shouldShowReleaseNotes boolValue]; + return [shouldShowReleaseNotes boolValue]; } - (BOOL)allowsAutomaticUpdates { - BOOL allowAutoUpdates = YES; // Defaults to YES. - if( [self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey] ) - allowAutoUpdates = [self.host boolForInfoDictionaryKey: SUAllowsAutomaticUpdatesKey]; + BOOL allowAutoUpdates = YES; // Defaults to YES. + if ([self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]) + allowAutoUpdates = [self.host boolForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]; - // Give delegate a chance to modify this choice: - if (self.delegate && [self.delegate respondsToSelector: @selector(updateAlert:shouldAllowAutoUpdate:)] ) - [self.delegate updateAlert: self shouldAllowAutoUpdate: &allowAutoUpdates]; + // Give delegate a chance to modify this choice: + if (self.delegate && [self.delegate respondsToSelector:@selector(updateAlert:shouldAllowAutoUpdate:)]) + [self.delegate updateAlert:self shouldAllowAutoUpdate:&allowAutoUpdates]; - return allowAutoUpdates; + return allowAutoUpdates; } - (void)awakeFromNib @@ -295,27 +295,27 @@ - (NSImage *)applicationIcon { - return [self.host icon]; + return [self.host icon]; } - (NSString *)titleText { - return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is available!", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is available!", nil), [self.host name]]; } - (NSString *)descriptionText { - NSString *updateItemVersion = [self.updateItem displayVersionString]; + NSString *updateItemVersion = [self.updateItem displayVersionString]; NSString *hostVersion = [self.host displayVersion]; - // Display more info if the version strings are the same; useful for betas. + // Display more info if the version strings are the same; useful for betas. if (!self.versionDisplayer && [updateItemVersion isEqualToString:hostVersion] ) { updateItemVersion = [updateItemVersion stringByAppendingFormat:@" (%@)", [self.updateItem versionString]]; hostVersion = [hostVersion stringByAppendingFormat:@" (%@)", [self.host version]]; } else { - [self.versionDisplayer formatVersion: &updateItemVersion andVersion: &hostVersion]; - } + [self.versionDisplayer formatVersion:&updateItemVersion andVersion:&hostVersion]; + } return [NSString stringWithFormat:SULocalizedString(@"%@ %@ is now available--you have %@. Would you like to download it now?", nil), [self.host name], updateItemVersion, hostVersion]; } @@ -323,12 +323,12 @@ { if ([frame parentFrame] == nil) { self.webViewFinishedLoading = YES; - [self.releaseNotesSpinner setHidden:YES]; - [sender display]; // necessary to prevent weird scroll bar artifacting + [self.releaseNotesSpinner setHidden:YES]; + [sender display]; // necessary to prevent weird scroll bar artifacting } } -- (void)webView:(WebView *) __unused sender decidePolicyForNavigationAction:(NSDictionary *) __unused actionInformation request:(NSURLRequest *)request frame:(WebFrame *) __unused frame decisionListener:(id )listener +- (void)webView:(WebView *)__unused sender decidePolicyForNavigationAction:(NSDictionary *)__unused actionInformation request:(NSURLRequest *)request frame:(WebFrame *)__unused frame decisionListener:(id)listener { if (self.webViewFinishedLoading) { [[NSWorkspace sharedWorkspace] openURL:[request URL]]; @@ -341,33 +341,33 @@ } // Clean up the contextual menu. -- (NSArray *)webView:(WebView *) __unused sender contextMenuItemsForElement:(NSDictionary *) __unused element defaultMenuItems:(NSArray *)defaultMenuItems +- (NSArray *)webView:(WebView *)__unused sender contextMenuItemsForElement:(NSDictionary *)__unused element defaultMenuItems:(NSArray *)defaultMenuItems { - NSMutableArray *webViewMenuItems = [defaultMenuItems mutableCopy]; + NSMutableArray *webViewMenuItems = [defaultMenuItems mutableCopy]; if (webViewMenuItems) { for (NSMenuItem *menuItem in defaultMenuItems) { - NSInteger tag = [menuItem tag]; + NSInteger tag = [menuItem tag]; switch (tag) { - case WebMenuItemTagOpenLinkInNewWindow: - case WebMenuItemTagDownloadLinkToDisk: - case WebMenuItemTagOpenImageInNewWindow: - case WebMenuItemTagDownloadImageToDisk: - case WebMenuItemTagOpenFrameInNewWindow: - case WebMenuItemTagGoBack: - case WebMenuItemTagGoForward: - case WebMenuItemTagStop: - case WebMenuItemTagReload: - [webViewMenuItems removeObjectIdenticalTo: menuItem]; - } - } - } + case WebMenuItemTagOpenLinkInNewWindow: + case WebMenuItemTagDownloadLinkToDisk: + case WebMenuItemTagOpenImageInNewWindow: + case WebMenuItemTagDownloadImageToDisk: + case WebMenuItemTagOpenFrameInNewWindow: + case WebMenuItemTagGoBack: + case WebMenuItemTagGoForward: + case WebMenuItemTagStop: + case WebMenuItemTagReload: + [webViewMenuItems removeObjectIdenticalTo:menuItem]; + } + } + } - return webViewMenuItems; + return webViewMenuItems; } @end diff --git a/Sparkle/SUUpdateDriver.h b/Sparkle/SUUpdateDriver.h index d1600b8b..5575994d 100644 --- a/Sparkle/SUUpdateDriver.h +++ b/Sparkle/SUUpdateDriver.h @@ -11,15 +11,15 @@ #import -extern NSString * const SUUpdateDriverFinishedNotification; +extern NSString *const SUUpdateDriverFinishedNotification; @class SUHost, SUUpdater; -@interface SUUpdateDriver : NSObject +@interface SUUpdateDriver : NSObject @property (readonly, weak) SUUpdater *updater; @property (strong) SUHost *host; -- (instancetype) initWithUpdater:(SUUpdater *)updater; +- (instancetype)initWithUpdater:(SUUpdater *)updater; - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host; - (void)abortUpdate; @property (getter=isInterruptible, readonly) BOOL interruptible; diff --git a/Sparkle/SUUpdateDriver.m b/Sparkle/SUUpdateDriver.m index c1153485..cee31648 100644 --- a/Sparkle/SUUpdateDriver.m +++ b/Sparkle/SUUpdateDriver.m @@ -9,7 +9,7 @@ #import "SUUpdateDriver.h" #import "SUHost.h" -NSString * const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished"; +NSString *const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished"; @interface SUUpdateDriver () @@ -27,26 +27,26 @@ NSString * const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished"; @synthesize finished; @synthesize appcastURL; -- (instancetype) initWithUpdater:(SUUpdater *)anUpdater +- (instancetype)initWithUpdater:(SUUpdater *)anUpdater { - if ((self = [super init])) { - self.updater = anUpdater; - } - return self; + if ((self = [super init])) { + self.updater = anUpdater; + } + return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; } - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)h { - self.appcastURL = URL; - self.host = h; + self.appcastURL = URL; + self.host = h; } - (void)abortUpdate { - [self setValue:@YES forKey:@"finished"]; - [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdateDriverFinishedNotification object:self]; + [self setValue:@YES forKey:@"finished"]; + [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdateDriverFinishedNotification object:self]; } @end diff --git a/Sparkle/SUUpdatePermissionPrompt.h b/Sparkle/SUUpdatePermissionPrompt.h index 450594d7..cadff1bc 100644 --- a/Sparkle/SUUpdatePermissionPrompt.h +++ b/Sparkle/SUUpdatePermissionPrompt.h @@ -12,8 +12,8 @@ #import "SUWindowController.h" typedef enum { - SUAutomaticallyCheck, - SUDoNotAutomaticallyCheck + SUAutomaticallyCheck, + SUDoNotAutomaticallyCheck } SUPermissionPromptResult; @protocol SUUpdatePermissionPromptDelegate; diff --git a/Sparkle/SUUpdatePermissionPrompt.m b/Sparkle/SUUpdatePermissionPrompt.m index f00b7f6e..6d31cdf6 100644 --- a/Sparkle/SUUpdatePermissionPrompt.m +++ b/Sparkle/SUUpdatePermissionPrompt.m @@ -18,7 +18,7 @@ @property (strong) SUHost *host; @property (strong) NSArray *systemProfileInformationArray; -@property (weak) id delegate; +@property (weak) id delegate; @property (weak) IBOutlet NSTextField *descriptionTextField; @property (weak) IBOutlet NSView *moreInfoView; @property (weak) IBOutlet NSButton *moreInfoButton; @@ -40,33 +40,33 @@ - (BOOL)shouldAskAboutProfile { - return [[self.host objectForInfoDictionaryKey:SUEnableSystemProfilingKey] boolValue]; + return [[self.host objectForInfoDictionaryKey:SUEnableSystemProfilingKey] boolValue]; } - (instancetype)initWithHost:(SUHost *)aHost systemProfile:(NSArray *)profile delegate:(id)d { - self = [super initWithHost:aHost windowNibName:@"SUUpdatePermissionPrompt"]; + self = [super initWithHost:aHost windowNibName:@"SUUpdatePermissionPrompt"]; if (self) { - host = aHost; - delegate = d; - self.isShowingMoreInfo = NO; - self.shouldSendProfile = [self shouldAskAboutProfile]; - systemProfileInformationArray = profile; - [self setShouldCascadeWindows:NO]; - } - return self; + host = aHost; + delegate = d; + self.isShowingMoreInfo = NO; + self.shouldSendProfile = [self shouldAskAboutProfile]; + systemProfileInformationArray = profile; + [self setShouldCascadeWindows:NO]; + } + return self; } -+ (void)promptWithHost:(SUHost *)aHost systemProfile:(NSArray *)profile delegate:(id )d ++ (void)promptWithHost:(SUHost *)aHost systemProfile:(NSArray *)profile delegate:(id)d { - // If this is a background application we need to focus it in order to bring the prompt - // to the user's attention. Otherwise the prompt would be hidden behind other applications and - // the user would not know why the application was paused. + // If this is a background application we need to focus it in order to bring the prompt + // to the user's attention. Otherwise the prompt would be hidden behind other applications and + // the user would not know why the application was paused. if ([aHost isBackgroundApplication]) { [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; } - - SUUpdatePermissionPrompt *prompt = [[[self class] alloc] initWithHost:aHost systemProfile:profile delegate:d]; - [NSApp runModalForWindow:[prompt window]]; + + SUUpdatePermissionPrompt *prompt = [[[self class] alloc] initWithHost:aHost systemProfile:profile delegate:d]; + [NSApp runModalForWindow:[prompt window]]; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } @@ -75,10 +75,10 @@ { if (![self shouldAskAboutProfile]) { - NSRect frame = [[self window] frame]; - frame.size.height -= [self.moreInfoButton frame].size.height; - [[self window] setFrame:frame display:YES]; - } else { + NSRect frame = [[self window] frame]; + frame.size.height -= [self.moreInfoButton frame].size.height; + [[self window] setFrame:frame display:YES]; + } else { // Set the table view's delegate so we can disable row selection. [self.profileTableView setDelegate:(id)self]; } @@ -89,66 +89,66 @@ - (NSImage *)icon { - return [self.host icon]; + return [self.host icon]; } - (NSString *)promptDescription { - return [NSString stringWithFormat:SULocalizedString(@"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu.", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedString(@"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu.", nil), [self.host name]]; } -- (IBAction)toggleMoreInfo:(id) __unused sender +- (IBAction)toggleMoreInfo:(id)__unused sender { - self.isShowingMoreInfo = !self.isShowingMoreInfo; + self.isShowingMoreInfo = !self.isShowingMoreInfo; - NSView *contentView = [[self window] contentView]; - NSRect contentViewFrame = [contentView frame]; - NSRect windowFrame = [[self window] frame]; + NSView *contentView = [[self window] contentView]; + NSRect contentViewFrame = [contentView frame]; + NSRect windowFrame = [[self window] frame]; - NSRect profileMoreInfoViewFrame = [self.moreInfoView frame]; - NSRect profileMoreInfoButtonFrame = [self.moreInfoButton frame]; - NSRect descriptionFrame = [self.descriptionTextField frame]; + NSRect profileMoreInfoViewFrame = [self.moreInfoView frame]; + NSRect profileMoreInfoButtonFrame = [self.moreInfoButton frame]; + NSRect descriptionFrame = [self.descriptionTextField frame]; if (self.isShowingMoreInfo) { - // Add the subview - contentViewFrame.size.height += profileMoreInfoViewFrame.size.height; - profileMoreInfoViewFrame.origin.y = profileMoreInfoButtonFrame.origin.y - profileMoreInfoViewFrame.size.height; - profileMoreInfoViewFrame.origin.x = descriptionFrame.origin.x; - profileMoreInfoViewFrame.size.width = descriptionFrame.size.width; + // Add the subview + contentViewFrame.size.height += profileMoreInfoViewFrame.size.height; + profileMoreInfoViewFrame.origin.y = profileMoreInfoButtonFrame.origin.y - profileMoreInfoViewFrame.size.height; + profileMoreInfoViewFrame.origin.x = descriptionFrame.origin.x; + profileMoreInfoViewFrame.size.width = descriptionFrame.size.width; - windowFrame.size.height += profileMoreInfoViewFrame.size.height; - windowFrame.origin.y -= profileMoreInfoViewFrame.size.height; + windowFrame.size.height += profileMoreInfoViewFrame.size.height; + windowFrame.origin.y -= profileMoreInfoViewFrame.size.height; - [self.moreInfoView setFrame:profileMoreInfoViewFrame]; - [self.moreInfoView setHidden:YES]; - [contentView addSubview:self.moreInfoView - positioned:NSWindowBelow - relativeTo:self.moreInfoButton]; - } else { - // Remove the subview - [self.moreInfoView setHidden:NO]; - [self.moreInfoView removeFromSuperview]; - contentViewFrame.size.height -= profileMoreInfoViewFrame.size.height; + [self.moreInfoView setFrame:profileMoreInfoViewFrame]; + [self.moreInfoView setHidden:YES]; + [contentView addSubview:self.moreInfoView + positioned:NSWindowBelow + relativeTo:self.moreInfoButton]; + } else { + // Remove the subview + [self.moreInfoView setHidden:NO]; + [self.moreInfoView removeFromSuperview]; + contentViewFrame.size.height -= profileMoreInfoViewFrame.size.height; - windowFrame.size.height -= profileMoreInfoViewFrame.size.height; - windowFrame.origin.y += profileMoreInfoViewFrame.size.height; - } - [[self window] setFrame:windowFrame display:YES animate:YES]; - [contentView setFrame:contentViewFrame]; - [contentView setNeedsDisplay:YES]; - [self.moreInfoView setHidden:!self.isShowingMoreInfo]; + windowFrame.size.height -= profileMoreInfoViewFrame.size.height; + windowFrame.origin.y += profileMoreInfoViewFrame.size.height; + } + [[self window] setFrame:windowFrame display:YES animate:YES]; + [contentView setFrame:contentViewFrame]; + [contentView setNeedsDisplay:YES]; + [self.moreInfoView setHidden:!self.isShowingMoreInfo]; } - (IBAction)finishPrompt:(id)sender { - if (![self.delegate respondsToSelector:@selector(updatePermissionPromptFinishedWithResult:)]) { - [NSException raise:@"SUInvalidDelegate" format:@"SUUpdatePermissionPrompt's delegate (%@) doesn't respond to updatePermissionPromptFinishedWithResult:!", self.delegate]; - } - [self.host setBool:self.shouldSendProfile forUserDefaultsKey:SUSendProfileInfoKey]; - [self.delegate updatePermissionPromptFinishedWithResult:([sender tag] == 1 ? SUAutomaticallyCheck : SUDoNotAutomaticallyCheck)]; - [[self window] close]; - [NSApp stopModal]; + if (![self.delegate respondsToSelector:@selector(updatePermissionPromptFinishedWithResult:)]) { + [NSException raise:@"SUInvalidDelegate" format:@"SUUpdatePermissionPrompt's delegate (%@) doesn't respond to updatePermissionPromptFinishedWithResult:!", self.delegate]; + } + [self.host setBool:self.shouldSendProfile forUserDefaultsKey:SUSendProfileInfoKey]; + [self.delegate updatePermissionPromptFinishedWithResult:([sender tag] == 1 ? SUAutomaticallyCheck : SUDoNotAutomaticallyCheck)]; + [[self window] close]; + [NSApp stopModal]; } @end diff --git a/Sparkle/SUUpdater.h b/Sparkle/SUUpdater.h index 2a1108f4..4c838571 100644 --- a/Sparkle/SUUpdater.h +++ b/Sparkle/SUUpdater.h @@ -32,9 +32,9 @@ @property (readonly, strong) NSBundle *hostBundle; -@property BOOL automaticallyChecksForUpdates; +@property BOOL automaticallyChecksForUpdates; -@property NSTimeInterval updateCheckInterval; +@property NSTimeInterval updateCheckInterval; /*! * The URL of the appcast used to download update information. @@ -45,9 +45,9 @@ @property (nonatomic, copy) NSString *userAgentString; -@property BOOL sendsSystemProfile; +@property BOOL sendsSystemProfile; -@property BOOL automaticallyDownloadsUpdates; +@property BOOL automaticallyDownloadsUpdates; /*! Explicitly checks for updates and displays a progress dialog while doing so. @@ -157,7 +157,7 @@ extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. */ -- (NSString*)feedURLStringForUpdater:(SUUpdater*)updater; +- (NSString *)feedURLStringForUpdater:(SUUpdater *)updater; /*! Returns whether Sparkle should prompt the user about automatic update checks. @@ -255,7 +255,7 @@ extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. */ -- (id )versionComparatorForUpdater:(SUUpdater *)updater; +- (id)versionComparatorForUpdater:(SUUpdater *)updater; /*! Returns an object that formats version numbers for display to the user. @@ -267,7 +267,7 @@ extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. */ -- (id )versionDisplayerForUpdater:(SUUpdater *)updater; +- (id)versionDisplayerForUpdater:(SUUpdater *)updater; /*! Returns the path which is used to relaunch the client after the update is installed. @@ -284,7 +284,7 @@ extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. */ --(void) updaterWillShowModalAlert:(SUUpdater *)updater; +- (void)updaterWillShowModalAlert:(SUUpdater *)updater; /*! Called after an updater shows a modal alert window, @@ -292,7 +292,7 @@ extern NSString *const SUUpdaterAppcastNotificationKey; \param updater The SUUpdater instance. */ --(void) updaterDidShowModalAlert:(SUUpdater *)updater; +- (void)updaterDidShowModalAlert:(SUUpdater *)updater; /*! Called when an update is scheduled to be silently installed on quit. @@ -322,13 +322,13 @@ extern NSString *const SUUpdaterAppcastNotificationKey; #if defined(DEBUG) && DEBUG && 0 #define SU_MIN_CHECK_INTERVAL 60 #else -#define SU_MIN_CHECK_INTERVAL 60*60 +#define SU_MIN_CHECK_INTERVAL 60 * 60 #endif #if defined(DEBUG) && DEBUG && 0 #define SU_DEFAULT_CHECK_INTERVAL 60 #else -#define SU_DEFAULT_CHECK_INTERVAL 60*60*24 +#define SU_DEFAULT_CHECK_INTERVAL 60 * 60 * 24 #endif #endif diff --git a/Sparkle/SUUpdater.m b/Sparkle/SUUpdater.m index 88952356..1461a3a4 100644 --- a/Sparkle/SUUpdater.m +++ b/Sparkle/SUUpdater.m @@ -38,8 +38,8 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (void)updateDriverDidFinish:(NSNotification *)note; @property (readonly, copy) NSURL *parameterizedFeedURL; --(void) notifyWillShowModalAlert; --(void) notifyDidShowModalAlert; +- (void)notifyWillShowModalAlert; +- (void)notifyDidShowModalAlert; @property (strong) SUUpdateDriver *driver; @property (strong) SUHost *host; @@ -58,49 +58,49 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification #pragma mark Initialization static NSMutableDictionary *sharedUpdaters = nil; -static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaultsObservationContext"; +static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaultsObservationContext"; + (SUUpdater *)sharedUpdater { - return [self updaterForBundle:[NSBundle mainBundle]]; + return [self updaterForBundle:[NSBundle mainBundle]]; } // SUUpdater has a singleton for each bundle. We use the fact that NSBundle instances are also singletons, so we can use them as keys. If you don't trust that you can also use the identifier as key + (SUUpdater *)updaterForBundle:(NSBundle *)bundle { if (bundle == nil) bundle = [NSBundle mainBundle]; - id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; - if (updater == nil) { - updater = [[[self class] alloc] initForBundle:bundle]; - } - return updater; + id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; + if (updater == nil) { + updater = [[[self class] alloc] initForBundle:bundle]; + } + return updater; } // This is the designated initializer for SUUpdater, important for subclasses - (instancetype)initForBundle:(NSBundle *)bundle { - self = [super init]; + self = [super init]; if (bundle == nil) bundle = [NSBundle mainBundle]; - // Register as observer straight away to avoid exceptions on -dealloc when -unregisterAsObserver is called: - if (self) { - [self registerAsObserver]; - } + // Register as observer straight away to avoid exceptions on -dealloc when -unregisterAsObserver is called: + if (self) { + [self registerAsObserver]; + } - id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; + id updater = sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]]; if (updater) { - self = updater; + self = updater; } else if (self) { - if (sharedUpdaters == nil) { + if (sharedUpdaters == nil) { sharedUpdaters = [[NSMutableDictionary alloc] init]; - } + } sharedUpdaters[[NSValue valueWithNonretainedObject:bundle]] = self; host = [[SUHost alloc] initWithBundle:bundle]; - // Saving-the-developer-from-a-stupid-mistake-check: + // Saving-the-developer-from-a-stupid-mistake-check: BOOL hasPublicDSAKey = [host publicDSAKey] != nil; BOOL isMainBundle = [bundle isEqualTo:[NSBundle mainBundle]]; BOOL hostIsCodeSigned = [SUCodeSigningVerifier hostApplicationIsCodeSigned]; @@ -116,8 +116,8 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault // This runs the permission prompt if needed, but never before the app has finished launching because the runloop won't run before that [self performSelector:@selector(startUpdateCycle) withObject:nil afterDelay:0]; - } - return self; + } + return self; } @@ -130,17 +130,17 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self.host bundlePath], [self.host installationPath]]; } --(void) notifyWillShowModalAlert +- (void)notifyWillShowModalAlert { - if ([self.delegate respondsToSelector: @selector(updaterWillShowModalAlert:)] ) - [self.delegate updaterWillShowModalAlert: self]; + if ([self.delegate respondsToSelector:@selector(updaterWillShowModalAlert:)]) + [self.delegate updaterWillShowModalAlert:self]; } --(void) notifyDidShowModalAlert +- (void)notifyDidShowModalAlert { - if ([self.delegate respondsToSelector: @selector(updaterDidShowModalAlert:)] ) - [self.delegate updaterDidShowModalAlert: self]; + if ([self.delegate respondsToSelector:@selector(updaterDidShowModalAlert:)]) + [self.delegate updaterDidShowModalAlert:self]; } @@ -148,7 +148,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault { BOOL shouldPrompt = NO; - // If the user has been asked about automatic checks, don't bother prompting + // If the user has been asked about automatic checks, don't bother prompting if ([self.host objectForUserDefaultsKey:SUEnableAutomaticChecksKey]) { shouldPrompt = NO; @@ -161,9 +161,9 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault // Has he been asked already? And don't ask if the host has a default value set in its Info.plist. else if ([self.host objectForKey:SUEnableAutomaticChecksKey] == nil) { - if ([self.host objectForUserDefaultsKey:SUEnableAutomaticChecksKeyOld]) { + if ([self.host objectForUserDefaultsKey:SUEnableAutomaticChecksKeyOld]) { [self setAutomaticallyChecksForUpdates:[self.host boolForUserDefaultsKey:SUEnableAutomaticChecksKeyOld]]; - } + } // Now, we don't want to ask the user for permission to do a weird thing on the first launch. // We wait until the second launch, unless explicitly overridden via SUPromptUserOnFirstLaunchKey. else if (![self.host objectForKey:SUPromptUserOnFirstLaunchKey]) @@ -179,11 +179,11 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault if (shouldPrompt) { - NSArray *profileInfo = [self.host systemProfile]; - // Always say we're sending the system profile here so that the delegate displays the parameters it would send. - if ([self.delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { - profileInfo = [profileInfo arrayByAddingObjectsFromArray:[self.delegate feedParametersForUpdater:self sendingSystemProfile:YES]]; - } + NSArray *profileInfo = [self.host systemProfile]; + // Always say we're sending the system profile here so that the delegate displays the parameters it would send. + if ([self.delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { + profileInfo = [profileInfo arrayByAddingObjectsFromArray:[self.delegate feedParametersForUpdater:self sendingSystemProfile:YES]]; + } [SUUpdatePermissionPrompt promptWithHost:self.host systemProfile:profileInfo delegate:self]; // We start the update checks and register as observer for changes after the prompt finishes } @@ -196,139 +196,139 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault - (void)updatePermissionPromptFinishedWithResult:(SUPermissionPromptResult)result { - [self setAutomaticallyChecksForUpdates:(result == SUAutomaticallyCheck)]; + [self setAutomaticallyChecksForUpdates:(result == SUAutomaticallyCheck)]; // Schedule checks, but make sure we ignore the delayed call from KVO - [self resetUpdateCycle]; + [self resetUpdateCycle]; } - (void)updateDriverDidFinish:(NSNotification *)note { if ([note object] == self.driver && [self.driver finished]) { - self.driver = nil; - [self scheduleNextUpdateCheck]; + self.driver = nil; + [self scheduleNextUpdateCheck]; } } - (NSDate *)lastUpdateCheckDate { - return [self.host objectForUserDefaultsKey:SULastCheckTimeKey]; + return [self.host objectForUserDefaultsKey:SULastCheckTimeKey]; } - (void)scheduleNextUpdateCheck { if (self.checkTimer) { - [self.checkTimer invalidate]; - self.checkTimer = nil; // Timer is non-repeating, may have invalidated itself, so we had to retain it. - } + [self.checkTimer invalidate]; + self.checkTimer = nil; // Timer is non-repeating, may have invalidated itself, so we had to retain it. + } if (![self automaticallyChecksForUpdates]) return; - // How long has it been since last we checked for an update? - NSDate *lastCheckDate = [self lastUpdateCheckDate]; + // How long has it been since last we checked for an update? + NSDate *lastCheckDate = [self lastUpdateCheckDate]; if (!lastCheckDate) { lastCheckDate = [NSDate distantPast]; } - NSTimeInterval intervalSinceCheck = [[NSDate date] timeIntervalSinceDate:lastCheckDate]; + NSTimeInterval intervalSinceCheck = [[NSDate date] timeIntervalSinceDate:lastCheckDate]; - // Now we want to figure out how long until we check again. - NSTimeInterval delayUntilCheck, updateCheckInterval = [self updateCheckInterval]; - if (updateCheckInterval < SU_MIN_CHECK_INTERVAL) - updateCheckInterval = SU_MIN_CHECK_INTERVAL; - if (intervalSinceCheck < updateCheckInterval) - delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough. - else - delayUntilCheck = 0; // We're overdue! Run one now. - self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:delayUntilCheck target:self selector:@selector(checkForUpdatesInBackground) userInfo:nil repeats:NO]; // Timer is non-repeating, may have invalidated itself, so we had to retain it. + // Now we want to figure out how long until we check again. + NSTimeInterval delayUntilCheck, updateCheckInterval = [self updateCheckInterval]; + if (updateCheckInterval < SU_MIN_CHECK_INTERVAL) + updateCheckInterval = SU_MIN_CHECK_INTERVAL; + if (intervalSinceCheck < updateCheckInterval) + delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough. + else + delayUntilCheck = 0; // We're overdue! Run one now. + self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:delayUntilCheck target:self selector:@selector(checkForUpdatesInBackground) userInfo:nil repeats:NO]; // Timer is non-repeating, may have invalidated itself, so we had to retain it. } --(void) putFeedURLIntoDictionary: (NSMutableDictionary*)theDict // You release this. +- (void)putFeedURLIntoDictionary:(NSMutableDictionary *)theDict // You release this. { - theDict[@"feedURL"] = [self feedURL]; + theDict[@"feedURL"] = [self feedURL]; } --(void) checkForUpdatesInBgReachabilityCheckWithDriver: (SUUpdateDriver*)inDriver /* RUNS ON ITS OWN THREAD */ +- (void)checkForUpdatesInBgReachabilityCheckWithDriver:(SUUpdateDriver *)inDriver /* RUNS ON ITS OWN THREAD */ { - @try { - // This method *must* be called on its own thread. SCNetworkReachabilityCheckByName - // can block, and it can be waiting a long time on slow networks, and we - // wouldn't want to beachball the main thread for a background operation. - // We could use asynchronous reachability callbacks, but those aren't - // reliable enough and can 'get lost' sometimes, which we don't want. + @try { + // This method *must* be called on its own thread. SCNetworkReachabilityCheckByName + // can block, and it can be waiting a long time on slow networks, and we + // wouldn't want to beachball the main thread for a background operation. + // We could use asynchronous reachability callbacks, but those aren't + // reliable enough and can 'get lost' sometimes, which we don't want. @autoreleasepool { - SCNetworkConnectionFlags flags = 0; - BOOL isNetworkReachable = YES; + SCNetworkConnectionFlags flags = 0; + BOOL isNetworkReachable = YES; - // Don't perform automatic checks on unconnected laptops or dial-up connections that aren't online: - NSMutableDictionary* theDict = [NSMutableDictionary dictionary]; - dispatch_sync(dispatch_get_main_queue(), ^{ + // Don't perform automatic checks on unconnected laptops or dial-up connections that aren't online: + NSMutableDictionary *theDict = [NSMutableDictionary dictionary]; + dispatch_sync(dispatch_get_main_queue(), ^{ [self putFeedURLIntoDictionary:theDict]; // Get feed URL on main thread, it's not safe to call elsewhere. - }); + }); - const char *hostname = [[(NSURL *)theDict[@"feedURL"] host] cStringUsingEncoding: NSUTF8StringEncoding]; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostname); - Boolean reachabilityResult = NO; - // If the feed's using a file:// URL, we won't be able to use reachability. - if (reachability != NULL) { - SCNetworkReachabilityGetFlags(reachability, &flags); - CFRelease(reachability); - } + const char *hostname = [[(NSURL *)theDict[@"feedURL"] host] cStringUsingEncoding:NSUTF8StringEncoding]; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostname); + Boolean reachabilityResult = NO; + // If the feed's using a file:// URL, we won't be able to use reachability. + if (reachability != NULL) { + SCNetworkReachabilityGetFlags(reachability, &flags); + CFRelease(reachability); + } if( reachabilityResult ) { - BOOL reachable = (flags & kSCNetworkFlagsReachable) == kSCNetworkFlagsReachable; - BOOL automatic = (flags & kSCNetworkFlagsConnectionAutomatic) == kSCNetworkFlagsConnectionAutomatic; - BOOL local = (flags & kSCNetworkFlagsIsLocalAddress) == kSCNetworkFlagsIsLocalAddress; + BOOL reachable = (flags & kSCNetworkFlagsReachable) == kSCNetworkFlagsReachable; + BOOL automatic = (flags & kSCNetworkFlagsConnectionAutomatic) == kSCNetworkFlagsConnectionAutomatic; + BOOL local = (flags & kSCNetworkFlagsIsLocalAddress) == kSCNetworkFlagsIsLocalAddress; - //NSLog(@"reachable = %s, automatic = %s, local = %s", (reachable?"YES":"NO"), (automatic?"YES":"NO"), (local?"YES":"NO")); + //NSLog(@"reachable = %s, automatic = %s, local = %s", (reachable?"YES":"NO"), (automatic?"YES":"NO"), (local?"YES":"NO")); - if( !(reachable || automatic || local) ) - isNetworkReachable = NO; - } + if (!(reachable || automatic || local)) + isNetworkReachable = NO; + } - // If the network's not reachable, we pass a nil driver into checkForUpdatesWithDriver, which will then reschedule the next update so we try again later. - dispatch_async(dispatch_get_main_queue(), ^{ + // If the network's not reachable, we pass a nil driver into checkForUpdatesWithDriver, which will then reschedule the next update so we try again later. + dispatch_async(dispatch_get_main_queue(), ^{ [self checkForUpdatesWithDriver: isNetworkReachable ? inDriver : nil]; - }); + }); - } + } } @catch (NSException *localException) { - SULog(@"UNCAUGHT EXCEPTION IN UPDATE CHECK TIMER: %@",[localException reason]); - // Don't propagate the exception beyond here. In Carbon apps that would trash the stack. - } + SULog(@"UNCAUGHT EXCEPTION IN UPDATE CHECK TIMER: %@", [localException reason]); + // Don't propagate the exception beyond here. In Carbon apps that would trash the stack. + } } - (void)checkForUpdatesInBackground { - // Background update checks should only happen if we have a network connection. - // Wouldn't want to annoy users on dial-up by establishing a connection every - // hour or so: - SUUpdateDriver * theUpdateDriver = [[([self automaticallyDownloadsUpdates] ? [SUAutomaticUpdateDriver class] : [SUScheduledUpdateDriver class]) alloc] initWithUpdater:self]; + // Background update checks should only happen if we have a network connection. + // Wouldn't want to annoy users on dial-up by establishing a connection every + // hour or so: + SUUpdateDriver *theUpdateDriver = [[([self automaticallyDownloadsUpdates] ? [SUAutomaticUpdateDriver class] : [SUScheduledUpdateDriver class])alloc] initWithUpdater:self]; - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self checkForUpdatesInBgReachabilityCheckWithDriver:theUpdateDriver]; - }); + }); } - (BOOL)mayUpdateAndRestart { - return( !self.delegate || ![self.delegate respondsToSelector: @selector(updaterShouldRelaunchApplication:)] || [self.delegate updaterShouldRelaunchApplication: self] ); + return (!self.delegate || ![self.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)] || [self.delegate updaterShouldRelaunchApplication:self]); } -- (IBAction)checkForUpdates:(id) __unused sender +- (IBAction)checkForUpdates:(id)__unused sender { - if (self.driver && [self.driver isInterruptible]) { - [self.driver abortUpdate]; - } + if (self.driver && [self.driver isInterruptible]) { + [self.driver abortUpdate]; + } - [self checkForUpdatesWithDriver:[[SUUserInitiatedUpdateDriver alloc] initWithUpdater:self]]; + [self checkForUpdatesWithDriver:[[SUUserInitiatedUpdateDriver alloc] initWithUpdater:self]]; } - (void)checkForUpdateInformation { - [self checkForUpdatesWithDriver:[[SUProbingUpdateDriver alloc] initWithUpdater:self]]; + [self checkForUpdatesWithDriver:[[SUProbingUpdateDriver alloc] initWithUpdater:self]]; } - (void)checkForUpdatesWithDriver:(SUUpdateDriver *)d @@ -336,18 +336,18 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault if ([self updateInProgress]) { return; } if (self.checkTimer) { [self.checkTimer invalidate]; self.checkTimer = nil; } // Timer is non-repeating, may have invalidated itself, so we had to retain it. - SUClearLog(); - SULog( @"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath: [[NSBundle mainBundle] bundlePath]] ); + SUClearLog(); + SULog(@"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath:[[NSBundle mainBundle] bundlePath]]); - [self willChangeValueForKey:@"lastUpdateCheckDate"]; - [self.host setObject:[NSDate date] forUserDefaultsKey:SULastCheckTimeKey]; - [self didChangeValueForKey:@"lastUpdateCheckDate"]; + [self willChangeValueForKey:@"lastUpdateCheckDate"]; + [self.host setObject:[NSDate date] forUserDefaultsKey:SULastCheckTimeKey]; + [self didChangeValueForKey:@"lastUpdateCheckDate"]; if( [self.delegate respondsToSelector: @selector(updaterMayCheckForUpdates:)] && ![self.delegate updaterMayCheckForUpdates: self] ) { - [self scheduleNextUpdateCheck]; - return; - } + [self scheduleNextUpdateCheck]; + return; + } self.driver = d; @@ -358,16 +358,16 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault return; } - NSURL* theFeedURL = [self parameterizedFeedURL]; - if( theFeedURL ) // Use a NIL URL to cancel quietly. - [self.driver checkForUpdatesAtURL: theFeedURL host:self.host]; - else - [self.driver abortUpdate]; + NSURL *theFeedURL = [self parameterizedFeedURL]; + if (theFeedURL) // Use a NIL URL to cancel quietly. + [self.driver checkForUpdatesAtURL:theFeedURL host:self.host]; + else + [self.driver abortUpdate]; } - (void)registerAsObserver { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDriverDidFinish:) name:SUUpdateDriverFinishedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDriverDidFinish:) name:SUUpdateDriverFinishedNotification object:nil]; [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:[@"values." stringByAppendingString:SUScheduledCheckIntervalKey] options:(NSKeyValueObservingOptions)0 context:(__bridge void *)(SUUpdaterDefaultsObservationContext)]; [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:[@"values." stringByAppendingString:SUEnableAutomaticChecksKey] options:(NSKeyValueObservingOptions)0 context:(__bridge void *)(SUUpdaterDefaultsObservationContext)]; } @@ -376,14 +376,14 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault { @try { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeyPath:[@"values." stringByAppendingString:SUScheduledCheckIntervalKey]]; - [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeyPath:[@"values." stringByAppendingString:SUEnableAutomaticChecksKey]]; - } - @catch (NSException *) - { - NSLog(@"Sparkle Error: [SUUpdater unregisterAsObserver] called, but the updater wasn't registered as an observer."); - } + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeyPath:[@"values." stringByAppendingString:SUScheduledCheckIntervalKey]]; + [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKeyPath:[@"values." stringByAppendingString:SUEnableAutomaticChecksKey]]; + } + @catch (NSException *) + { + NSLog(@"Sparkle Error: [SUUpdater unregisterAsObserver] called, but the updater wasn't registered as an observer."); + } } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context @@ -397,7 +397,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault } else { - [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } @@ -409,40 +409,40 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault - (void)setAutomaticallyChecksForUpdates:(BOOL)automaticallyCheckForUpdates { - [self.host setBool:automaticallyCheckForUpdates forUserDefaultsKey:SUEnableAutomaticChecksKey]; - // Hack to support backwards compatibility with older Sparkle versions, which supported - // disabling updates by setting the check interval to 0. - if (automaticallyCheckForUpdates && (NSInteger)[self updateCheckInterval] == 0) { + [self.host setBool:automaticallyCheckForUpdates forUserDefaultsKey:SUEnableAutomaticChecksKey]; + // Hack to support backwards compatibility with older Sparkle versions, which supported + // disabling updates by setting the check interval to 0. + if (automaticallyCheckForUpdates && (NSInteger)[self updateCheckInterval] == 0) { [self setUpdateCheckInterval:SU_DEFAULT_CHECK_INTERVAL]; - } + } [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(resetUpdateCycle) object:nil]; - // Provide a small delay in case multiple preferences are being updated simultaneously. + // Provide a small delay in case multiple preferences are being updated simultaneously. [self performSelector:@selector(resetUpdateCycle) withObject:nil afterDelay:1]; } - (BOOL)automaticallyChecksForUpdates { - // Don't automatically update when the check interval is 0, to be compatible with 1.1 settings. - if ((NSInteger)[self updateCheckInterval] == 0) { + // Don't automatically update when the check interval is 0, to be compatible with 1.1 settings. + if ((NSInteger)[self updateCheckInterval] == 0) { return NO; - } - return [self.host boolForKey:SUEnableAutomaticChecksKey]; + } + return [self.host boolForKey:SUEnableAutomaticChecksKey]; } - (void)setAutomaticallyDownloadsUpdates:(BOOL)automaticallyUpdates { - [self.host setBool:automaticallyUpdates forUserDefaultsKey:SUAutomaticallyUpdateKey]; + [self.host setBool:automaticallyUpdates forUserDefaultsKey:SUAutomaticallyUpdateKey]; } - (BOOL)automaticallyDownloadsUpdates { - // If the SUAllowsAutomaticUpdatesKey exists and is set to NO, return NO. - if ([self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey] && [self.host boolForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey] == NO) { - return NO; - } + // If the SUAllowsAutomaticUpdatesKey exists and is set to NO, return NO. + if ([self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey] && [self.host boolForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey] == NO) { + return NO; + } - // Otherwise, automatically downloading updates is allowed. Does the user want it? - return [self.host boolForUserDefaultsKey:SUAutomaticallyUpdateKey]; + // Otherwise, automatically downloading updates is allowed. Does the user want it? + return [self.host boolForUserDefaultsKey:SUAutomaticallyUpdateKey]; } - (void)setFeedURL:(NSURL *)feedURL @@ -450,7 +450,7 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault if (![NSThread isMainThread]) [NSException raise:@"SUThreadException" format:@"This method must be called on the main thread"]; - [self.host setObject:[feedURL absoluteString] forUserDefaultsKey:SUFeedURLKey]; + [self.host setObject:[feedURL absoluteString] forUserDefaultsKey:SUFeedURLKey]; } - (NSURL *)feedURL @@ -458,123 +458,123 @@ static NSString * const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefault if (![NSThread isMainThread]) [NSException raise:@"SUThreadException" format:@"This method must be called on the main thread"]; - // A value in the user defaults overrides one in the Info.plist (so preferences panels can be created wherein users choose between beta / release feeds). - NSString *appcastString = [self.host objectForKey:SUFeedURLKey]; - if( [self.delegate respondsToSelector: @selector(feedURLStringForUpdater:)] ) - appcastString = [self.delegate feedURLStringForUpdater: self]; - if (!appcastString) // Can't find an appcast string! - [NSException raise:@"SUNoFeedURL" format:@"You must specify the URL of the appcast as the %@ key in either the Info.plist or the user defaults!", SUFeedURLKey]; - NSCharacterSet* quoteSet = [NSCharacterSet characterSetWithCharactersInString: @"\"\'"]; // Some feed publishers add quotes; strip 'em. - NSString* castUrlStr = [appcastString stringByTrimmingCharactersInSet:quoteSet]; - if( !castUrlStr || [castUrlStr length] == 0 ) - return nil; - else - return [NSURL URLWithString: castUrlStr]; + // A value in the user defaults overrides one in the Info.plist (so preferences panels can be created wherein users choose between beta / release feeds). + NSString *appcastString = [self.host objectForKey:SUFeedURLKey]; + if ([self.delegate respondsToSelector:@selector(feedURLStringForUpdater:)]) + appcastString = [self.delegate feedURLStringForUpdater:self]; + if (!appcastString) // Can't find an appcast string! + [NSException raise:@"SUNoFeedURL" format:@"You must specify the URL of the appcast as the %@ key in either the Info.plist or the user defaults!", SUFeedURLKey]; + NSCharacterSet *quoteSet = [NSCharacterSet characterSetWithCharactersInString:@"\"\'"]; // Some feed publishers add quotes; strip 'em. + NSString *castUrlStr = [appcastString stringByTrimmingCharactersInSet:quoteSet]; + if (!castUrlStr || [castUrlStr length] == 0) + return nil; + else + return [NSURL URLWithString:castUrlStr]; } - (NSString *)userAgentString { - if (customUserAgentString) { - return customUserAgentString; - } + if (customUserAgentString) { + return customUserAgentString; + } - NSString *version = [SPARKLE_BUNDLE objectForInfoDictionaryKey:@"CFBundleVersion"]; - NSString *userAgent = [NSString stringWithFormat:@"%@/%@ Sparkle/%@", [self.host name], [self.host displayVersion], version ? version : @"?"]; - NSData *cleanedAgent = [userAgent dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; - return [[NSString alloc] initWithData:cleanedAgent encoding:NSASCIIStringEncoding]; + NSString *version = [SPARKLE_BUNDLE objectForInfoDictionaryKey:@"CFBundleVersion"]; + NSString *userAgent = [NSString stringWithFormat:@"%@/%@ Sparkle/%@", [self.host name], [self.host displayVersion], version ? version : @"?"]; + NSData *cleanedAgent = [userAgent dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; + return [[NSString alloc] initWithData:cleanedAgent encoding:NSASCIIStringEncoding]; } - (void)setSendsSystemProfile:(BOOL)sendsSystemProfile { - [self.host setBool:sendsSystemProfile forUserDefaultsKey:SUSendProfileInfoKey]; + [self.host setBool:sendsSystemProfile forUserDefaultsKey:SUSendProfileInfoKey]; } - (BOOL)sendsSystemProfile { - return [self.host boolForKey:SUSendProfileInfoKey]; + return [self.host boolForKey:SUSendProfileInfoKey]; } - (NSURL *)parameterizedFeedURL { - NSURL *baseFeedURL = [self feedURL]; + NSURL *baseFeedURL = [self feedURL]; - // Determine all the parameters we're attaching to the base feed URL. - BOOL sendingSystemProfile = [self sendsSystemProfile]; + // Determine all the parameters we're attaching to the base feed URL. + BOOL sendingSystemProfile = [self sendsSystemProfile]; - // Let's only send the system profiling information once per week at most, so we normalize daily-checkers vs. biweekly-checkers and the such. - NSDate *lastSubmitDate = [self.host objectForUserDefaultsKey:SULastProfileSubmitDateKey]; - if (!lastSubmitDate) { - lastSubmitDate = [NSDate distantPast]; - } - const NSTimeInterval oneWeek = 60 * 60 * 24 * 7; - sendingSystemProfile &= (-[lastSubmitDate timeIntervalSinceNow] >= oneWeek); + // Let's only send the system profiling information once per week at most, so we normalize daily-checkers vs. biweekly-checkers and the such. + NSDate *lastSubmitDate = [self.host objectForUserDefaultsKey:SULastProfileSubmitDateKey]; + if (!lastSubmitDate) { + lastSubmitDate = [NSDate distantPast]; + } + const NSTimeInterval oneWeek = 60 * 60 * 24 * 7; + sendingSystemProfile &= (-[lastSubmitDate timeIntervalSinceNow] >= oneWeek); - NSArray *parameters = @[]; - if ([self.delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { - parameters = [parameters arrayByAddingObjectsFromArray:[self.delegate feedParametersForUpdater:self sendingSystemProfile:sendingSystemProfile]]; - } + NSArray *parameters = @[]; + if ([self.delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { + parameters = [parameters arrayByAddingObjectsFromArray:[self.delegate feedParametersForUpdater:self sendingSystemProfile:sendingSystemProfile]]; + } if (sendingSystemProfile) { - parameters = [parameters arrayByAddingObjectsFromArray:[self.host systemProfile]]; - [self.host setObject:[NSDate date] forUserDefaultsKey:SULastProfileSubmitDateKey]; - } + parameters = [parameters arrayByAddingObjectsFromArray:[self.host systemProfile]]; + [self.host setObject:[NSDate date] forUserDefaultsKey:SULastProfileSubmitDateKey]; + } if ([parameters count] == 0) { return baseFeedURL; } - // Build up the parameterized URL. - NSMutableArray *parameterStrings = [NSMutableArray array]; - for (NSDictionary *currentProfileInfo in parameters) { - [parameterStrings addObject:[NSString stringWithFormat:@"%@=%@", [[currentProfileInfo[@"key"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[currentProfileInfo[@"value"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; - } + // Build up the parameterized URL. + NSMutableArray *parameterStrings = [NSMutableArray array]; + for (NSDictionary *currentProfileInfo in parameters) { + [parameterStrings addObject:[NSString stringWithFormat:@"%@=%@", [[currentProfileInfo[@"key"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[currentProfileInfo[@"value"] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; + } - NSString *separatorCharacter = @"?"; - if ([baseFeedURL query]) { - separatorCharacter = @"&"; // In case the URL is already http://foo.org/baz.xml?bat=4 - } - NSString *appcastStringWithProfile = [NSString stringWithFormat:@"%@%@%@", [baseFeedURL absoluteString], separatorCharacter, [parameterStrings componentsJoinedByString:@"&"]]; + NSString *separatorCharacter = @"?"; + if ([baseFeedURL query]) { + separatorCharacter = @"&"; // In case the URL is already http://foo.org/baz.xml?bat=4 + } + NSString *appcastStringWithProfile = [NSString stringWithFormat:@"%@%@%@", [baseFeedURL absoluteString], separatorCharacter, [parameterStrings componentsJoinedByString:@"&"]]; - // Clean it up so it's a valid URL - return [NSURL URLWithString:appcastStringWithProfile]; + // Clean it up so it's a valid URL + return [NSURL URLWithString:appcastStringWithProfile]; } - (void)setUpdateCheckInterval:(NSTimeInterval)updateCheckInterval { - [self.host setObject:@(updateCheckInterval) forUserDefaultsKey:SUScheduledCheckIntervalKey]; - if ((NSInteger)updateCheckInterval == 0) { // For compatibility with 1.1's settings. - [self setAutomaticallyChecksForUpdates:NO]; - } - [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(resetUpdateCycle) object:nil]; + [self.host setObject:@(updateCheckInterval) forUserDefaultsKey:SUScheduledCheckIntervalKey]; + if ((NSInteger)updateCheckInterval == 0) { // For compatibility with 1.1's settings. + [self setAutomaticallyChecksForUpdates:NO]; + } + [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(resetUpdateCycle) object:nil]; - // Provide a small delay in case multiple preferences are being updated simultaneously. - [self performSelector:@selector(resetUpdateCycle) withObject:nil afterDelay:1]; + // Provide a small delay in case multiple preferences are being updated simultaneously. + [self performSelector:@selector(resetUpdateCycle) withObject:nil afterDelay:1]; } - (NSTimeInterval)updateCheckInterval { - // Find the stored check interval. User defaults override Info.plist. - NSNumber *intervalValue = [self.host objectForKey:SUScheduledCheckIntervalKey]; - if (intervalValue) - return [intervalValue doubleValue]; - else - return SU_DEFAULT_CHECK_INTERVAL; + // Find the stored check interval. User defaults override Info.plist. + NSNumber *intervalValue = [self.host objectForKey:SUScheduledCheckIntervalKey]; + if (intervalValue) + return [intervalValue doubleValue]; + else + return SU_DEFAULT_CHECK_INTERVAL; } - (void)dealloc { - [self unregisterAsObserver]; + [self unregisterAsObserver]; if (checkTimer) { [checkTimer invalidate]; } // Timer is non-repeating, may have invalidated itself, so we had to retain it. } - (BOOL)validateMenuItem:(NSMenuItem *)item { - if ([item action] == @selector(checkForUpdates:)) { - return ![self updateInProgress]; - } - return YES; + if ([item action] == @selector(checkForUpdates:)) { + return ![self updateInProgress]; + } + return YES; } - (BOOL)updateInProgress { - return self.driver && ([self.driver finished] == NO); + return self.driver && ([self.driver finished] == NO); } - (NSBundle *)hostBundle { return [self.host bundle]; } diff --git a/Sparkle/SUUserInitiatedUpdateDriver.m b/Sparkle/SUUserInitiatedUpdateDriver.m index c839fcdf..5dd66f29 100644 --- a/Sparkle/SUUserInitiatedUpdateDriver.m +++ b/Sparkle/SUUserInitiatedUpdateDriver.m @@ -27,71 +27,71 @@ { if (self.checkingController) { - [[self.checkingController window] close]; - self.checkingController = nil; - } + [[self.checkingController window] close]; + self.checkingController = nil; + } } -- (void)cancelCheckForUpdates:(id) __unused sender +- (void)cancelCheckForUpdates:(id)__unused sender { - [self closeCheckingWindow]; - self.canceled = YES; + [self closeCheckingWindow]; + self.canceled = YES; } - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost { - self.checkingController = [[SUStatusController alloc] initWithHost:aHost]; - [[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]; - [self.checkingController showWindow:self]; - [super checkForUpdatesAtURL:URL host:aHost]; + self.checkingController = [[SUStatusController alloc] initWithHost:aHost]; + [[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]; + [self.checkingController showWindow:self]; + [super checkForUpdatesAtURL:URL host:aHost]; - // For background applications, obtain focus. - // Useful if the update check is requested from another app like System Preferences. + // For background applications, obtain focus. + // Useful if the update check is requested from another app like System Preferences. if ([aHost isBackgroundApplication]) { - [NSApp activateIgnoringOtherApps:YES]; - } + [NSApp activateIgnoringOtherApps:YES]; + } } - (void)appcastDidFinishLoading:(SUAppcast *)ac { if (self.isCanceled) { - [self abortUpdate]; - return; - } - [self closeCheckingWindow]; - [super appcastDidFinishLoading:ac]; + [self abortUpdate]; + return; + } + [self closeCheckingWindow]; + [super appcastDidFinishLoading:ac]; } - (void)abortUpdateWithError:(NSError *)error { - [self closeCheckingWindow]; - [super abortUpdateWithError:error]; + [self closeCheckingWindow]; + [super abortUpdateWithError:error]; } - (void)abortUpdate { - [self closeCheckingWindow]; - [super abortUpdate]; + [self closeCheckingWindow]; + [super abortUpdate]; } - (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error { if (self.isCanceled) { - [self abortUpdate]; - return; - } - [super appcast:ac failedToLoadWithError:error]; + [self abortUpdate]; + return; + } + [super appcast:ac failedToLoadWithError:error]; } - (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui { - // We don't check to see if this update's been skipped, because the user explicitly *asked* if he had the latest version. - return [self hostSupportsItem:ui] && [self isItemNewer:ui]; + // We don't check to see if this update's been skipped, because the user explicitly *asked* if he had the latest version. + return [self hostSupportsItem:ui] && [self isItemNewer:ui]; } @end diff --git a/Sparkle/SUVersionComparisonProtocol.h b/Sparkle/SUVersionComparisonProtocol.h index 0649b03c..d3fb3d2b 100644 --- a/Sparkle/SUVersionComparisonProtocol.h +++ b/Sparkle/SUVersionComparisonProtocol.h @@ -22,7 +22,7 @@ Should return NSOrderedAscending if b > a, NSOrderedDescending if b < a, and NSOrderedSame if they are equivalent. */ -- (NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB; // *** MAY BE CALLED ON NON-MAIN THREAD! +- (NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB; // *** MAY BE CALLED ON NON-MAIN THREAD! @end diff --git a/Sparkle/SUVersionDisplayProtocol.h b/Sparkle/SUVersionDisplayProtocol.h index 7ef17121..697f1a87 100644 --- a/Sparkle/SUVersionDisplayProtocol.h +++ b/Sparkle/SUVersionDisplayProtocol.h @@ -20,6 +20,6 @@ Both versions are provided so that important distinguishing information can be displayed while also leaving out unnecessary/confusing parts. */ --(void) formatVersion: (NSString**)inOutVersionA andVersion: (NSString**)inOutVersionB; +- (void)formatVersion:(NSString **)inOutVersionA andVersion:(NSString **)inOutVersionB; @end diff --git a/Sparkle/SUWindowController.m b/Sparkle/SUWindowController.m index c08d0692..874f7653 100644 --- a/Sparkle/SUWindowController.m +++ b/Sparkle/SUWindowController.m @@ -13,15 +13,15 @@ - (instancetype)initWithHost:(SUHost *)host windowNibName:(NSString *)nibName { - NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:nibName ofType:@"nib"]; - if (path == nil) // Slight hack to resolve issues with running Sparkle in debug configurations. - { - NSString *frameworkPath = [[[host bundle] sharedFrameworksPath] stringByAppendingPathComponent:@"Sparkle.framework"]; - NSBundle *framework = [NSBundle bundleWithPath:frameworkPath]; - path = [framework pathForResource:nibName ofType:@"nib"]; - } - self = [super initWithWindowNibPath:path owner:self]; - return self; + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:nibName ofType:@"nib"]; + if (path == nil) // Slight hack to resolve issues with running Sparkle in debug configurations. + { + NSString *frameworkPath = [[[host bundle] sharedFrameworksPath] stringByAppendingPathComponent:@"Sparkle.framework"]; + NSBundle *framework = [NSBundle bundleWithPath:frameworkPath]; + path = [framework pathForResource:nibName ofType:@"nib"]; + } + self = [super initWithWindowNibPath:path owner:self]; + return self; } @end diff --git a/TestApplication/main.m b/TestApplication/main.m index c4bc08f7..f858e875 100644 --- a/TestApplication/main.m +++ b/TestApplication/main.m @@ -10,5 +10,5 @@ int main(int argc, char *argv[]) { - return NSApplicationMain(argc, (const char **) argv); + return NSApplicationMain(argc, (const char **)argv); }