Skip to content

Commit

Permalink
Modernized ObjC codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthias Schwab committed Jan 22, 2017
1 parent 28f9969 commit 670fa11
Show file tree
Hide file tree
Showing 52 changed files with 258 additions and 307 deletions.
30 changes: 15 additions & 15 deletions Classes/AccountPreferences.m
Expand Up @@ -9,7 +9,7 @@

@implementation AccountPreferences

- (id)init
- (instancetype)init
{
self = [super initWithNibName:@"AccountPreferences" bundle:nil];
self.putio = [PutIOAPI api];
Expand Down Expand Up @@ -47,9 +47,9 @@ -(void)connectAccountButtonClicked:(id)sender
{
if(!accountSetup)
accountSetup = [[AccountSetupController alloc] init];
[accountSetup setDelegate:self];
[NSApp beginSheet:[accountSetup window]
modalForWindow:[self.view window]
accountSetup.delegate = self;
[NSApp beginSheet:accountSetup.window
modalForWindow:(self.view).window
modalDelegate:nil
didEndSelector:nil
contextInfo:nil];
Expand All @@ -60,8 +60,8 @@ -(void)connectAccountButtonClicked:(id)sender

-(void)accountSetupController:(AccountSetupController *)c didFinishSetupWithOAuthAccessToken:(NSString *)token
{
[[accountSetup window] close];
[NSApp endSheet:[accountSetup window]];
[accountSetup.window close];
[NSApp endSheet:accountSetup.window];

// Abort all running syncs and downloads
[[SyncScheduler sharedSyncScheduler] cancelAllSyncsInProgress];
Expand All @@ -85,8 +85,8 @@ -(void)accountSetupController:(AccountSetupController *)c didFinishSetupWithOAut

-(void)accountSetupControllerDidCancelSetup:(AccountSetupController *)c
{
[[accountSetup window] close];
[NSApp endSheet:[accountSetup window]];
[accountSetup.window close];
[NSApp endSheet:accountSetup.window];
}

#pragma mark - Account Details
Expand All @@ -103,10 +103,10 @@ - (void)fetchAccountDetails
if(request.error == nil && !request.isCancelled){
PutIOAPIAccountInfo *accountInfo = request.accountInfo;
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
[d setObject:[accountInfo eMailAddress] forKey:@"account_email"];
[d setObject:[accountInfo username] forKey:@"account_username"];
[d setInteger:[accountInfo usedDiskSpace] forKey:@"account_space_used"];
[d setInteger:[accountInfo totalDiskSpace] forKey:@"account_space_total"];
[d setObject:accountInfo.eMailAddress forKey:@"account_email"];
[d setObject:accountInfo.username forKey:@"account_username"];
[d setInteger:accountInfo.usedDiskSpace forKey:@"account_space_used"];
[d setInteger:accountInfo.totalDiskSpace forKey:@"account_space_total"];
[self updateAccountDetailLabels];
}
[activityLabel setHidden:YES];
Expand All @@ -132,17 +132,17 @@ - (void)updateAccountDetailLabels
NSUInteger accountTotalSpace = [d integerForKey:@"account_space_total"];
if(accountUsername){
[accountUsernameLabel setHidden:NO];
[accountUsernameLabel setStringValue:accountUsername];
accountUsernameLabel.stringValue = accountUsername;
}
if(accountEMailAddress){
[accountEMailAddressLabel setHidden:NO];
[accountEMailAddressLabel setStringValue:accountEMailAddress];
accountEMailAddressLabel.stringValue = accountEMailAddress;
}
if(accountUsedSpace > 0 || accountTotalSpace > 0){
BytesFormatter *formatter = [[BytesFormatter alloc] init];
NSString *accountUsedSpaceString = [formatter stringFromBytes:accountUsedSpace];
NSString *accountTotalSpaceString = [formatter stringFromBytes:accountTotalSpace];
[spaceLabel setStringValue:[NSString stringWithFormat:NSLocalizedString(@"Used space: %@ of %@", nil), accountUsedSpaceString, accountTotalSpaceString]];
spaceLabel.stringValue = [NSString stringWithFormat:NSLocalizedString(@"Used space: %@ of %@", nil), accountUsedSpaceString, accountTotalSpaceString];
[spaceLabel setHidden:NO];
}
}else{
Expand Down
16 changes: 8 additions & 8 deletions Classes/AccountSetupController.m
Expand Up @@ -6,7 +6,7 @@

@implementation AccountSetupController

-(id)init
-(instancetype)init
{
self = [super initWithWindowNibName:NSStringFromClass([self class])];
if(self){
Expand All @@ -26,8 +26,8 @@ -(void)windowDidLoad
{
putio = [PutIOAPI api];
//[putio setDelegate:self];
[webView setFrameLoadDelegate:self];
[webView setPolicyDelegate:self];
webView.frameLoadDelegate = self;
webView.policyDelegate = self;
[webView setHidden:YES];
[spinner startAnimation:self];
}
Expand All @@ -40,13 +40,13 @@ -(void)windowWillClose:(NSNotification *)notification
-(void)beginAccountSetup
{
loggingOut = YES;
webView.mainFrameURL = [putio.oAuthLogoutURL absoluteString];
webView.mainFrameURL = (putio.oAuthLogoutURL).absoluteString;

}

-(void)beginAuthentication
{
webView.mainFrameURL = [putio.oAuthAuthenticationURL absoluteString];
webView.mainFrameURL = (putio.oAuthAuthenticationURL).absoluteString;
}

- (void)webView:(WebView *)webView
Expand All @@ -55,15 +55,15 @@ - (void)webView:(WebView *)webView
frame:(WebFrame *)frame
decisionListener:(id<WebPolicyDecisionListener>)listener
{
NSString *URL = [[request URL] absoluteString];
NSString *URL = request.URL.absoluteString;
NSString *callbackURL = putio.oAuthRedirectURI;
if([URL hasPrefix:callbackURL]){
callbackURL = [callbackURL stringByAppendingString:@"?code="];
NSString *code = [URL stringByReplacingOccurrencesOfString:callbackURL withString:@""];
__block PutIOAPIOAuthTokenRequest *request = [PutIOAPIOAuthTokenRequest requestOAuthTokenForCode:code api:putio secret:kAPISecret completion:^{
if(request.error == nil && !request.isCancelled){
NSDictionary *rawData = (NSDictionary*)[request responseObject];
NSString *accessToken = [rawData objectForKey:@"access_token"];
NSDictionary *rawData = (NSDictionary*)request.responseObject;
NSString *accessToken = rawData[@"access_token"];
[_delegate accountSetupController:self didFinishSetupWithOAuthAccessToken:accessToken];
}else if (request.error != nil){
[self.window presentError:request.error
Expand Down
13 changes: 6 additions & 7 deletions Classes/ApplicationDelegate.m
Expand Up @@ -159,7 +159,7 @@ - (void)deliverUserNotificationWithIdentifier:(NSString*)identifier message:(NSS

- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSString *url = [event paramDescriptorForKeyword:keyDirectObject].stringValue;
NSLog(@"Got URL event: %@", url);
}

Expand All @@ -170,7 +170,7 @@ -(void)addApplicationAsLoginItem
// Make sure we are not added twice
[self removeApplicationLoginItem];

NSString *appPath = [[NSBundle mainBundle] bundlePath];
NSString *appPath = [NSBundle mainBundle].bundlePath;

CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath];
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL,
Expand All @@ -187,19 +187,18 @@ -(void)addApplicationAsLoginItem

-(void)removeApplicationLoginItem
{
NSString *appPath = [[NSBundle mainBundle] bundlePath];
NSString *appPath = [NSBundle mainBundle].bundlePath;

CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath];
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if(loginItems){
UInt32 seedValue;
NSArray *loginItemsArray = (__bridge NSArray *)LSSharedFileListCopySnapshot(loginItems, &seedValue);
for(int i = 0; i < [loginItemsArray count]; i++){
LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)[loginItemsArray
objectAtIndex:i];
for(int i = 0; i < loginItemsArray.count; i++){
LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)loginItemsArray[i];
//Resolve the item with URL
if (LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &url, NULL) == noErr) {
NSString * urlPath = [(__bridge NSURL*)url path];
NSString * urlPath = ((__bridge NSURL*)url).path;
if ([urlPath compare:appPath] == NSOrderedSame){
LSSharedFileListItemRemove(loginItems,itemRef);
}
Expand Down
4 changes: 2 additions & 2 deletions Classes/BackgroundView.m
Expand Up @@ -18,7 +18,7 @@ @implementation BackgroundView

- (void)drawRect:(NSRect)dirtyRect
{
NSRect contentRect = NSInsetRect([self bounds], LINE_THICKNESS, LINE_THICKNESS);
NSRect contentRect = NSInsetRect(self.bounds, LINE_THICKNESS, LINE_THICKNESS);
NSBezierPath *path = [NSBezierPath bezierPath];

[path moveToPoint:NSMakePoint(_arrowX, NSMaxY(contentRect))];
Expand Down Expand Up @@ -54,7 +54,7 @@ - (void)drawRect:(NSRect)dirtyRect

[NSGraphicsContext saveGraphicsState];

NSBezierPath *clip = [NSBezierPath bezierPathWithRect:[self bounds]];
NSBezierPath *clip = [NSBezierPath bezierPathWithRect:self.bounds];
[clip appendBezierPath:path];
[clip addClip];

Expand Down
2 changes: 1 addition & 1 deletion Classes/BytesFormatter.m
Expand Up @@ -25,7 +25,7 @@ -(NSString *)stringFromBytes:(double)bytes
formatter.minimumFractionDigits = precisions[exponent];

// Beware of reusing this format string. -[NSString stringWithFormat] ignores \0, *printf does not.
return [NSString stringWithFormat:@"%@ %cB", [formatter stringFromNumber:[NSNumber numberWithDouble: bytes]], units[exponent]];
return [NSString stringWithFormat:@"%@ %cB", [formatter stringFromNumber:@(bytes)], units[exponent]];
}

@end
2 changes: 1 addition & 1 deletion Classes/Download.h
Expand Up @@ -43,7 +43,7 @@ typedef enum PutIODownloadStatusEnum : int16_t{
@property (nonatomic) NSUInteger bytesPerSecond;
@property (nonatomic, strong) NSError *downloadError;

- (id)initWithPutIOFile:(PutIOAPIFile*)file
- (instancetype)initWithPutIOFile:(PutIOAPIFile*)file
localPath:(NSString*)path
subdirectoryPath:(NSString*)subdirectoryPath
originatingSyncInstruction:(SyncInstruction*)syncInstruction;
Expand Down
68 changes: 11 additions & 57 deletions Classes/Download.m
Expand Up @@ -44,7 +44,7 @@ @implementation Download

#pragma mark - Init

- (id)initWithPutIOFile:(PutIOAPIFile*)file
- (instancetype)initWithPutIOFile:(PutIOAPIFile*)file
localPath:(NSString*)path
subdirectoryPath:(NSString*)subPath
originatingSyncInstruction:(SyncInstruction*)syncInstruction;
Expand Down Expand Up @@ -85,52 +85,6 @@ -(void)dealloc
[self stopWaitingForOtherDownloads];
}

//#pragma mark - Coding
//
//-(id)initWithCoder:(NSCoder *)decoder
//{
// self = [super init];
// if(self){
// self.putioFile = [decoder decodeObjectForKey:@"putioFile"];
// self.localFile = [decoder decodeObjectForKey:@"localFile"];
// localPath = [decoder decodeObjectForKey:@"localPath"];
// subdirectoryPath = [decoder decodeObjectForKey:@"subdirectoryPath"];
// self.progress = [decoder decodeFloatForKey:@"progress"];
// self.progressIsKnown = [decoder decodeBoolForKey:@"progressIsKnown"];
// self.estimatedRemainingTime = [decoder decodeIntegerForKey:@"estimatedRemainingTime"];
// self.estimatedRemainingTimeIsKnown = [decoder decodeBoolForKey:@"estimatedRemainingTimeIsKnown"];
// // NSInteger uniqueID = [decoder decodeIntegerForKey:@"originatingSyncInstruction.uniqueID"];
// // for(SyncInstruction *instruction in [SyncInstruction allSyncInstructions])
// // if(instruction.uniqueID == uniqueID)
// // self.originatingSyncInstruction = instruction;
// self.totalSize = [decoder decodeIntegerForKey:@"totalSize"];
// self.receivedSize = [decoder decodeIntegerForKey:@"receivedSize"];
// localFileTemporary = [decoder decodeObjectForKey:@"localFileTemporary"];
// self.shouldResumeOnAppLaunch = [decoder decodeBoolForKey:@"shouldResumeOnAppLaunch"];
// self.status = [decoder decodeIntForKey:@"status"];
//
// }
// return self;
//}
//
//-(void)encodeWithCoder:(NSCoder *)coder
//{
// [coder encodeObject:self.putioFile forKey:@"putioFile"];
// [coder encodeObject:self.localFile forKey:@"localFile"];
// [coder encodeObject:localPath forKey:@"localPath"];
// [coder encodeObject:subdirectoryPath forKey:@"subdirectoryPath"];
// [coder encodeFloat:self.progress forKey:@"progress"];
// [coder encodeBool:self.progressIsKnown forKey:@"progressIsKnown"];
// [coder encodeInteger:self.estimatedRemainingTime forKey:@"estimatedRemainingTime"];
// [coder encodeBool:self.estimatedRemainingTimeIsKnown forKey:@"estimatedRemainingTimeIsKnown"];
// // [coder encodeInteger:self.originatingSyncInstruction.uniqueID forKey:@"originatingSyncInstruction.uniqueID"];
// [coder encodeInteger:self.totalSize forKey:@"totalSize"];
// [coder encodeInteger:self.receivedSize forKey:@"receivedSize"];
// [coder encodeObject:localFileTemporary forKey:@"localFileTemporary"];
// [coder encodeInt:(int)self.status forKey:@"status"];
// [coder encodeBool:self.shouldResumeOnAppLaunch forKey:@"shouldResumeOnAppLaunch"];
//}

#pragma mark - Accessors

-(void)setPutioFile:(PutIOAPIFile *)putioFile
Expand Down Expand Up @@ -177,7 +131,7 @@ -(void)startDownload
selector:@selector(updateProgress)
userInfo:nil repeats:YES];

NSURL *requestURL = [[PutIOAPI api] downloadURLForFileWithID:[self.putioFile fileID]];
NSURL *requestURL = [[PutIOAPI api] downloadURLForFileWithID:(self.putioFile).fileID];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0f];
Expand Down Expand Up @@ -289,8 +243,8 @@ - (NSString*)resolveNamingConflictForFileAtPath:(NSString*)filePath
NSFileManager *fm = [NSFileManager defaultManager];
NSUInteger number = 0;
while([fm fileExistsAtPath:filePath])
filePath = [NSString stringWithFormat:@"%@/%@-%li.%@", [filePath stringByDeletingLastPathComponent],
[[filePath lastPathComponent] stringByDeletingPathExtension], ++number, [filePath pathExtension]];
filePath = [NSString stringWithFormat:@"%@/%@-%li.%@", filePath.stringByDeletingLastPathComponent,
filePath.lastPathComponent.stringByDeletingPathExtension, ++number, filePath.pathExtension];
return filePath;
}

Expand Down Expand Up @@ -342,10 +296,10 @@ - (void)unlinkFromOriginatingSyncInstruction
-(void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSDictionary *responseHeaders = [httpResponse allHeaderFields];
NSURL *requestURL = [[PutIOAPI api] downloadURLForFileWithID:[self.putioFile fileID]];
NSDictionary *responseHeaders = httpResponse.allHeaderFields;
NSURL *requestURL = [[PutIOAPI api] downloadURLForFileWithID:(self.putioFile).fileID];
NSLog(@"PutIO download %@ response headers: %@", requestURL, responseHeaders);
NSInteger httpStatus = [httpResponse statusCode];
NSInteger httpStatus = httpResponse.statusCode;
if((httpStatus >= 200 && httpStatus < 300)){
if(responseHeaders[@"Content-Length"] != nil){
if(self.receivedSize == 0)
Expand All @@ -371,12 +325,12 @@ -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
[fileHandle writeData:data];

// Don't update the progress too often
receivedBytesSinceLastProgressUpdate += [data length];
receivedBytesSinceLastProgressUpdate += data.length;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSInteger c = [error code];
NSInteger c = error.code;
if(c == NSURLErrorNetworkConnectionLost|| c == NSURLErrorNotConnectedToInternet){
[self pauseDownload];
return;
Expand Down Expand Up @@ -420,7 +374,7 @@ -(void)connectionDidFinishLoading:(NSURLConnection *)aConnection
NSLog(@"%@: Download finished", self);
if(self.originatingSyncInstruction != nil){
[self.originatingSyncInstruction addKnownItemWithID:self.putioFile.fileID];
if([self.originatingSyncInstruction.deleteRemoteFilesAfterSync boolValue]){
if((self.originatingSyncInstruction.deleteRemoteFilesAfterSync).boolValue){
PutIOAPIFileDeletionRequest *request = [PutIOAPIFileDeletionRequest requestDeletionOfFileWithID:self.putioFile.fileID
completion:nil];
[[PutIOAPI api] performRequest:request];
Expand Down Expand Up @@ -521,7 +475,7 @@ - (void)deliverUserNotification
}
if(identifier == nil)
return;
[(ApplicationDelegate*)[NSApp delegate] deliverUserNotificationWithIdentifier:identifier message:message];
[(ApplicationDelegate*)NSApp.delegate deliverUserNotificationWithIdentifier:identifier message:message];
}

-(NSString *)description
Expand Down
12 changes: 6 additions & 6 deletions Classes/DownloadCellView.m
Expand Up @@ -44,7 +44,7 @@ -(Download *)download

-(void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle
{
[super setBackgroundStyle:backgroundStyle];
super.backgroundStyle = backgroundStyle;
if(backgroundStyle == NSBackgroundStyleDark){
statusLabel.textColor = [NSColor alternateSelectedControlTextColor];
}else if (backgroundStyle == NSBackgroundStyleLight){
Expand All @@ -70,16 +70,16 @@ -(void)updateStatus
}

Download *download = _download;
[progressBar setHidden:!(download.status == PutIODownloadStatusDownloading)];
[statusLabelConstraint setConstant:((download.status == PutIODownloadStatusDownloading) ? 0 : -8)];
[textLabelConstraint setConstant:((download.status == PutIODownloadStatusDownloading) ? 3 : 12)];
progressBar.hidden = !(download.status == PutIODownloadStatusDownloading);
statusLabelConstraint.constant = ((download.status == PutIODownloadStatusDownloading) ? 0 : -8);
textLabelConstraint.constant = ((download.status == PutIODownloadStatusDownloading) ? 3 : 12);
if(download.status == PutIODownloadStatusDownloading || download.status == PutIODownloadStatusPending){
NSString *stopImage = (self.backgroundStyle == NSBackgroundStyleDark ? @"stopImageInverted.png" : @"stopImage.png");
[pauseResumeButton setImage:[NSImage imageNamed:stopImage]];
pauseResumeButton.image = [NSImage imageNamed:stopImage];
[pauseResumeButton setHidden:NO];
}else if(download.status == PutIODownloadStatusPaused || download.status == PutIODownloadStatusFailed){
NSString *resumeImage = (self.backgroundStyle == NSBackgroundStyleDark ? @"resumeImageInverted.png" : @"resumeImage.png");
[pauseResumeButton setImage:[NSImage imageNamed:resumeImage]];
pauseResumeButton.image = [NSImage imageNamed:resumeImage];
[pauseResumeButton setHidden:NO];
}else{
[pauseResumeButton setHidden:YES];
Expand Down

0 comments on commit 670fa11

Please sign in to comment.