Reduce code size and make codebase more consistent (#2305)

This commit is contained in:
Zorg authored and GitHub committed 2022-12-27 12:03:03 -08:00
1 parent 91b8f4eaa0
commit be7f6952c2
203 files changed
+4058 -3474

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
#import <Foundation/Foundation.h>
@interface SUAdHocCodeSigning : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface SUAdHocCodeSigning : NSObject
+ (BOOL)codeSignApplicationAtPath:(NSString *)applicationPath;
@@ -9,7 +9,7 @@
#import <Cocoa/Cocoa.h>
#import <Sparkle/Sparkle.h>
@interface SUInstallUpdateViewController : NSViewController
SPU_OBJC_DIRECT_MEMBERS @interface SUInstallUpdateViewController : NSViewController
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SPUUserUpdateChoice))reply;
+32 -39
View File
@@ -8,30 +8,23 @@
#import "SUInstallUpdateViewController.h"
@interface SUInstallUpdateViewController ()
@property (nonatomic) IBOutlet NSButton *skipUpdatesButton;
@property (nonatomic) IBOutlet NSTextView *textView;
@property (nonatomic, readonly) SUAppcastItem *appcastItem;
@property (nonatomic, nullable) NSAttributedString *preloadedReleaseNotes;
@property (nonatomic, copy) void (^reply)(SPUUserUpdateChoice);
@end
@implementation SUInstallUpdateViewController
@synthesize skipUpdatesButton = _skipUpdatesButton;
@synthesize textView = _textView;
@synthesize preloadedReleaseNotes = _preloadedReleaseNotes;
@synthesize appcastItem = _appcastItem;
@synthesize reply = _reply;
{
void (^_reply)(SPUUserUpdateChoice);
SUAppcastItem *_appcastItem;
NSAttributedString *_preloadedReleaseNotes;
IBOutlet NSTextView *_textView;
IBOutlet NSButton *_skipUpdatesButton;
}
- (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SPUUserUpdateChoice))reply
{
self = [super initWithNibName:@"SUInstallUpdateViewController" bundle:nil];
if (self != nil) {
_appcastItem = appcastItem;
self.reply = reply;
_reply = [reply copy];
} else {
assert(false);
}
@@ -42,14 +35,14 @@
{
[super viewDidLoad];
[[self.textView enclosingScrollView] setDrawsBackground:NO];
[self.textView setDrawsBackground:NO];
[[_textView enclosingScrollView] setDrawsBackground:NO];
[_textView setDrawsBackground:NO];
if (self.preloadedReleaseNotes != nil) {
[self displayReleaseNotes:self.preloadedReleaseNotes];
self.preloadedReleaseNotes = nil;
} else if (self.appcastItem.releaseNotesURL == nil) {
NSString *descriptionHTML = self.appcastItem.itemDescription;
if (_preloadedReleaseNotes != nil) {
[self displayReleaseNotes:_preloadedReleaseNotes];
_preloadedReleaseNotes = nil;
} else if (_appcastItem.releaseNotesURL == nil) {
NSString *descriptionHTML = _appcastItem.itemDescription;
if (descriptionHTML != nil) {
NSData *htmlData = [descriptionHTML dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTML:htmlData documentAttributes:NULL];
@@ -58,22 +51,22 @@
}
}
- (void)displayReleaseNotes:(NSAttributedString *)releaseNotes
- (void)displayReleaseNotes:(NSAttributedString *)releaseNotes SPU_OBJC_DIRECT
{
if (self.textView == nil) {
self.preloadedReleaseNotes = releaseNotes;
if (_textView == nil) {
_preloadedReleaseNotes = releaseNotes;
} else {
[self.textView.textStorage setAttributedString:releaseNotes];
[_textView.textStorage setAttributedString:releaseNotes];
}
}
- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes
- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes SPU_OBJC_DIRECT
{
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTML:releaseNotes documentAttributes:NULL];
[self displayReleaseNotes:attributedString];
}
- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding
- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding SPU_OBJC_DIRECT
{
NSString *string = [[NSString alloc] initWithData:releaseNotes encoding:encoding];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:nil];
@@ -105,25 +98,25 @@
- (IBAction)installUpdate:(id)__unused sender
{
if (self.reply != nil) {
self.reply(SPUUserUpdateChoiceInstall);
self.reply = nil;
if (_reply != nil) {
_reply(SPUUserUpdateChoiceInstall);
_reply = nil;
}
}
- (IBAction)installUpdateLater:(id)__unused sender
{
if (self.reply != nil) {
self.reply(SPUUserUpdateChoiceDismiss);
self.reply = nil;
if (_reply != nil) {
_reply(SPUUserUpdateChoiceDismiss);
_reply = nil;
}
}
- (IBAction)skipUpdate:(id)__unused sender
{
if (self.reply != nil) {
self.reply(SPUUserUpdateChoiceSkip);
self.reply = nil;
if (_reply != nil) {
_reply(SPUUserUpdateChoiceSkip);
_reply = nil;
}
}
@@ -1,14 +1,15 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="9532" systemVersion="15D21" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="9532"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="SUInstallUpdateViewController">
<connections>
<outlet property="skipUpdatesButton" destination="GnO-99-FrA" id="3lg-83-oGn"/>
<outlet property="textView" destination="hvq-rZ-gUG" id="U5Y-SK-7E5"/>
<outlet property="_skipUpdatesButton" destination="GnO-99-FrA" id="WO4-cT-KGm"/>
<outlet property="_textView" destination="hvq-rZ-gUG" id="x7h-XU-cqB"/>
<outlet property="view" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
</connections>
</customObject>
@@ -20,6 +21,7 @@
<subviews>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="JaG-xU-cSv">
<rect key="frame" x="128" y="6" width="114" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Install Later" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="vGh-C9-cmI">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -33,6 +35,7 @@ Gw
</button>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="GnO-99-FrA">
<rect key="frame" x="14" y="6" width="114" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Skip Update" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="Q9S-re-mYe">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -43,34 +46,34 @@ Gw
</button>
<scrollView fixedFrame="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3Cj-JW-f43">
<rect key="frame" x="0.0" y="46" width="370" height="136"/>
<clipView key="contentView" ambiguous="YES" id="CIT-u4-hRg">
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<clipView key="contentView" drawsBackground="NO" id="CIT-u4-hRg">
<rect key="frame" x="1" y="1" width="368" height="134"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView ambiguous="YES" editable="NO" importsGraphics="NO" findStyle="panel" verticallyResizable="YES" allowsNonContiguousLayout="YES" id="hvq-rZ-gUG">
<textView editable="NO" importsGraphics="NO" verticallyResizable="YES" findStyle="panel" allowsNonContiguousLayout="YES" id="hvq-rZ-gUG">
<rect key="frame" x="0.0" y="0.0" width="368" height="134"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
<size key="minSize" width="368" height="134"/>
<size key="maxSize" width="463" height="10000000"/>
<color key="insertionPointColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<size key="minSize" width="368" height="134"/>
<size key="maxSize" width="463" height="10000000"/>
</textView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</clipView>
<scroller key="horizontalScroller" hidden="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="t2X-nw-Cy5">
<scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="t2X-nw-Cy5">
<rect key="frame" x="-100" y="-100" width="87" height="18"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
<scroller key="verticalScroller" verticalHuggingPriority="750" horizontal="NO" id="dth-jh-Csr">
<scroller key="verticalScroller" wantsLayer="YES" verticalHuggingPriority="750" horizontal="NO" id="dth-jh-Csr">
<rect key="frame" x="353" y="1" width="16" height="134"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="cYY-dW-0o8">
<rect key="frame" x="242" y="6" width="114" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Install Update" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="AoI-0t-LLU">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
+1 -1
View File
@@ -11,7 +11,7 @@
@class NSWindow;
@interface SUPopUpTitlebarUserDriver : NSObject <SPUUserDriver>
SPU_OBJC_DIRECT_MEMBERS @interface SUPopUpTitlebarUserDriver : NSObject <SPUUserDriver>
- (instancetype)initWithWindow:(NSWindow *)window;
+55 -61
View File
@@ -10,29 +10,20 @@
#import "SUInstallUpdateViewController.h"
#import <AppKit/AppKit.h>
@interface SUPopUpTitlebarUserDriver()
@property (nonatomic, readonly) NSWindow *window;
@property (nonatomic, nullable) SUInstallUpdateViewController *installUpdateViewController;
@property (nonatomic) NSTitlebarAccessoryViewController *accessoryViewController;
@property (nonatomic) BOOL addedAccessory;
@property (nonatomic) NSButton *updateButton;
@property (nonatomic, copy) void (^updateButtonAction)(NSButton *);
@property (nonatomic) uint64_t expectedContentLength;
@property (nonatomic) uint64_t contentLengthDownloaded;
@end
@implementation SUPopUpTitlebarUserDriver
@synthesize window = _window;
@synthesize installUpdateViewController = _installUpdateViewController;
@synthesize accessoryViewController = _accessoryViewController;
@synthesize addedAccessory = _addedAccessory;
@synthesize updateButton = _updateButton;
@synthesize updateButtonAction = _updateButtonAction;
@synthesize expectedContentLength = _expectedContentLength;
@synthesize contentLengthDownloaded = _contentLengthDownloaded;
{
void (^_updateButtonAction)(NSButton *);
NSWindow *_window;
SUInstallUpdateViewController *_installUpdateViewController;
NSTitlebarAccessoryViewController *_accessoryViewController;
NSButton *_updateButton;
uint64_t _expectedContentLength;
uint64_t _contentLengthDownloaded;
BOOL _addedAccessory;
}
- (instancetype)initWithWindow:(NSWindow *)window
{
@@ -43,58 +34,58 @@
return self;
}
- (void)addUpdateButtonWithTitle:(NSString *)title
- (void)addUpdateButtonWithTitle:(NSString *)title SPU_OBJC_DIRECT
{
[self addUpdateButtonWithTitle:title action:nil];
}
- (void)addUpdateButtonWithTitle:(NSString *)title action:(void (^)(NSButton *button))action
- (void)addUpdateButtonWithTitle:(NSString *)title action:(void (^)(NSButton *button))action SPU_OBJC_DIRECT
{
if (self.updateButton == nil) {
if (_updateButton == nil) {
NSButton *updateButton = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 160, 100)];
updateButton.title = title;
updateButton.bezelStyle = NSBezelStyleRecessed;
self.updateButton = updateButton;
_updateButton = updateButton;
} else {
self.updateButton.title = title;
_updateButton.title = title;
}
if (action != nil) {
self.updateButton.target = self;
self.updateButton.action = @selector(updateButtonAction:);
self.updateButtonAction = action;
self.updateButton.enabled = YES;
_updateButton.target = self;
_updateButton.action = @selector(updateButtonAction:);
_updateButtonAction = action;
_updateButton.enabled = YES;
} else {
self.updateButton.enabled = NO;
self.updateButton.target = nil;
self.updateButtonAction = nil;
_updateButton.enabled = NO;
_updateButton.target = nil;
_updateButtonAction = nil;
}
if (self.accessoryViewController == nil) {
self.accessoryViewController = [[NSTitlebarAccessoryViewController alloc] init];
self.accessoryViewController.layoutAttribute = NSLayoutAttributeRight;
self.accessoryViewController.view = self.updateButton;
if (_accessoryViewController == nil) {
_accessoryViewController = [[NSTitlebarAccessoryViewController alloc] init];
_accessoryViewController.layoutAttribute = NSLayoutAttributeRight;
_accessoryViewController.view = _updateButton;
}
if (!self.addedAccessory) {
[self.window addTitlebarAccessoryViewController:self.accessoryViewController];
self.addedAccessory = YES;
if (!_addedAccessory) {
[_window addTitlebarAccessoryViewController:_accessoryViewController];
_addedAccessory = YES;
}
}
- (void)updateButtonAction:(NSButton *)sender
{
if (self.updateButtonAction != nil) {
self.updateButtonAction(sender);
if (_updateButtonAction != nil) {
_updateButtonAction(sender);
}
}
- (void)removeUpdateButton
- (void)removeUpdateButton SPU_OBJC_DIRECT
{
[self.accessoryViewController removeFromParentViewController];
self.addedAccessory = NO;
self.updateButtonAction = nil;
[_accessoryViewController removeFromParentViewController];
_addedAccessory = NO;
_updateButtonAction = nil;
}
#pragma mark Update Permission
@@ -113,7 +104,7 @@
NSPopover *popover = [[NSPopover alloc] init];
popover.behavior = NSPopoverBehaviorTransient;
__weak SUPopUpTitlebarUserDriver *weakSelf = self;
__weak __typeof__(self) weakSelf = self;
__block NSButton *actionButton = nil;
SUInstallUpdateViewController *viewController = [[SUInstallUpdateViewController alloc] initWithAppcastItem:appcastItem reply:^(SPUUserUpdateChoice choice) {
@@ -122,10 +113,13 @@
[popover close];
actionButton.enabled = NO;
weakSelf.installUpdateViewController = nil;
__typeof__(self) strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf->_installUpdateViewController = nil;
}
}];
self.installUpdateViewController = viewController;
_installUpdateViewController = viewController;
[self addUpdateButtonWithTitle:@"Update Available" action:^(NSButton *button) {
actionButton = button;
@@ -151,7 +145,7 @@
- (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData
{
[self.installUpdateViewController showReleaseNotesWithDownloadData:downloadData];
[_installUpdateViewController showReleaseNotesWithDownloadData:downloadData];
}
- (void)showUpdateReleaseNotesFailedToDownloadWithError:(NSError *)__unused error
@@ -160,14 +154,14 @@
- (void)showUpdateInFocus
{
[self.window makeKeyAndOrderFront:nil];
[_window makeKeyAndOrderFront:nil];
if (self.updateButton.enabled) {
if (_updateButton.enabled) {
// Not the proper way to do things but ignoring warnings in Test App.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-messaging-id"
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self.updateButton.target performSelector:self.updateButton.action withObject:self.updateButton];
[_updateButton.target performSelector:_updateButton.action withObject:_updateButton];
#pragma clang diagnostic pop
}
}
@@ -222,21 +216,21 @@
- (void)showDownloadDidReceiveExpectedContentLength:(uint64_t)expectedContentLength
{
[self addUpdateButtonWithTitle:@"Downloading…"];
self.contentLengthDownloaded = 0;
self.expectedContentLength = expectedContentLength;
_contentLengthDownloaded = 0;
_expectedContentLength = expectedContentLength;
}
- (void)showDownloadDidReceiveDataOfLength:(uint64_t)length
{
self.contentLengthDownloaded += length;
_contentLengthDownloaded += length;
// In case our expected content length was incorrect
if (self.contentLengthDownloaded > self.expectedContentLength) {
self.expectedContentLength = self.contentLengthDownloaded;
if (_contentLengthDownloaded > _expectedContentLength) {
_expectedContentLength = _contentLengthDownloaded;
}
if (self.expectedContentLength > 0) {
double progress = (double)self.contentLengthDownloaded / self.expectedContentLength;
if (_expectedContentLength > 0) {
double progress = (double)_contentLengthDownloaded / _expectedContentLength;
[self addUpdateButtonWithTitle:[NSString stringWithFormat:@"Downloading (%0.0f%%)", progress * 100] action:nil];
}
}
+19 -24
View File
@@ -17,20 +17,15 @@
#import "SUBinaryDeltaCreate.h"
@interface SUTestApplicationDelegate () <NSMenuItemValidation, SPUUpdaterDelegate>
@property (nonatomic) SPUUpdater *updater;
@property (nonatomic) SUUpdateSettingsWindowController *updateSettingsWindowController;
@property (nonatomic) SUTestWebServer *webServer;
@property (nonatomic, copy) NSString *testMode;
@end
@implementation SUTestApplicationDelegate
@synthesize updater = _updater;
@synthesize updateSettingsWindowController = _updateSettingsWindowController;
@synthesize webServer = _webServer;
@synthesize testMode = _testMode;
{
SPUUpdater *_updater;
SUUpdateSettingsWindowController *_updateSettingsWindowController;
SUTestWebServer *_webServer;
NSString *_testMode;
}
- (void)applicationDidFinishLaunching:(NSNotification * __unused)notification
{
@@ -44,7 +39,7 @@
testMode = testModeEnv;
}
self.testMode = testMode;
_testMode = testMode;
// Check if we are already up to date
NSString *mainBundleVersion = (NSString *)[mainBundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
@@ -283,13 +278,13 @@
NSLog(@"Failed to create the web server");
abort();
}
self.webServer = webServer;
self->_webServer = webServer;
// Set up updater and the updater settings window
{
self.updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init];
self->_updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init];
NSWindow *settingsWindow = self.updateSettingsWindowController.window;
NSWindow *settingsWindow = self->_updateSettingsWindowController.window;
NSBundle *hostBundle = [NSBundle mainBundle];
NSBundle *applicationBundle = hostBundle;
@@ -307,8 +302,8 @@
SPUUpdater *updater = [[SPUUpdater alloc] initWithHostBundle:hostBundle applicationBundle:applicationBundle userDriver:userDriver delegate:self];
self.updater = updater;
self.updateSettingsWindowController.updater = updater;
self->_updater = updater;
self->_updateSettingsWindowController.updater = updater;
NSError *updaterError = nil;
if (![updater startUpdater:&updaterError]) {
@@ -321,7 +316,7 @@
[alert runModal];
}
[self.updateSettingsWindowController showWindow:nil];
[self->_updateSettingsWindowController showWindow:nil];
}
});
}];
@@ -329,16 +324,16 @@
- (NSSet<NSString *> *)allowedChannelsForUpdater:(SPUUpdater *)updater
{
if ([self.testMode isEqualToString:@"DELTA"]) {
if ([_testMode isEqualToString:@"DELTA"]) {
return [NSSet setWithObject:@"delta"];
} else if ([self.testMode isEqualToString:@"AUTOMATIC"]) {
} else if ([_testMode isEqualToString:@"AUTOMATIC"]) {
return [NSSet setWithObject:@"automatic"];
} else {
return [NSSet set];
}
}
- (void)signApplicationIfRequiredAtPath:(NSString *)applicationPath completion:(void (^)(void))completionBlock
- (void)signApplicationIfRequiredAtPath:(NSString *)applicationPath completion:(void (^)(void))completionBlock SPU_OBJC_DIRECT
{
// This is unfortunately necessary for testing sandboxing
NSXPCConnection *codeSignConnection = [[NSXPCConnection alloc] initWithServiceName:@"org.sparkle-project.TestAppHelper"];
@@ -355,18 +350,18 @@
- (void)applicationWillTerminate:(NSNotification * __unused)notification
{
[self.webServer close];
[_webServer close];
}
- (IBAction)checkForUpdates:(id __unused)sender
{
[self.updater checkForUpdates];
[_updater checkForUpdates];
}
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
if (menuItem.action == @selector(checkForUpdates:)) {
return self.updater.canCheckForUpdates;
return _updater.canCheckForUpdates;
}
return YES;
}
+1 -1
View File
@@ -8,7 +8,7 @@
#import <Foundation/Foundation.h>
@interface SUTestWebServer : NSObject
SPU_OBJC_DIRECT_MEMBERS @interface SUTestWebServer : NSObject
- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory;
+68 -64
View File
@@ -18,26 +18,21 @@
@end
@interface SUTestWebServerConnection : NSObject <NSStreamDelegate>
@property (nonatomic) NSString* workingDirectory;
@property (nonatomic, weak) id<SUTestWebServerConnectionDelegate> delegate;
@property (nonatomic) NSInputStream *inputStream;
@property (nonatomic) NSOutputStream *outputStream;
@property (nonatomic) NSData *dataToWrite;
@property (nonatomic) NSInteger numBytesToWrite;
@end
@implementation SUTestWebServerConnection
{
NSString* _workingDirectory;
NSInputStream *_inputStream;
NSOutputStream *_outputStream;
NSData *_dataToWrite;
NSInteger _numBytesToWrite;
__weak id<SUTestWebServerConnectionDelegate> _delegate;
}
@synthesize workingDirectory = _workingDirectory;
@synthesize delegate = _delegate;
@synthesize inputStream = _inputStream;
@synthesize outputStream = _outputStream;
@synthesize dataToWrite = _dataToWrite;
@synthesize numBytesToWrite = _numBytesToWrite;
- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id<SUTestWebServerConnectionDelegate>)delegate {
- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id<SUTestWebServerConnectionDelegate>)delegate SPU_OBJC_DIRECT
{
self = [super init];
assert(self != nil);
@@ -66,9 +61,10 @@
return self;
}
- (void)close {
NSInputStream *inputStream = self.inputStream;
NSOutputStream *outputStream = self.outputStream;
- (void)close SPU_OBJC_DIRECT
{
NSInputStream *inputStream = _inputStream;
NSOutputStream *outputStream = _outputStream;
if (inputStream == nil) {
assert(outputStream == nil);
return;
@@ -77,19 +73,20 @@
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
self.inputStream = nil;
self.outputStream = nil;
[self.delegate connectionDidClose:self];
_inputStream = nil;
_outputStream = nil;
[_delegate connectionDidClose:self];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
if (eventCode == NSStreamEventEndEncountered) {
[self close];
return;
}
if (aStream == self.inputStream && eventCode == NSStreamEventHasBytesAvailable) {
if (aStream == _inputStream && eventCode == NSStreamEventHasBytesAvailable) {
uint8_t buffer[8096];
const NSInteger numBytes = [self.inputStream read:buffer maxLength:sizeof(buffer)];
const NSInteger numBytes = [_inputStream read:buffer maxLength:sizeof(buffer)];
if (numBytes > 0) {
NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding];
NSArray *lines = [request componentsSeparatedByString:@"\r\n"];
@@ -99,7 +96,7 @@
if ([(NSString *)[parts objectAtIndex:0] isEqualToString:@"GET"]) {
// Use NSURL to strip out query parameters
NSString *path = [NSURL URLWithString:[parts objectAtIndex:1] relativeToURL:nil].path;
NSString *filePath = [self.workingDirectory stringByAppendingString:path];
NSString *filePath = [_workingDirectory stringByAppendingString:path];
BOOL isDir = NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) {
NSLog(@"%@ - 404", requestLine);
@@ -113,17 +110,19 @@
[self write404];
}
}
} else if (aStream == self.outputStream && eventCode == NSStreamEventHasSpaceAvailable && self.dataToWrite != nil) {
} else if (aStream == _outputStream && eventCode == NSStreamEventHasSpaceAvailable && _dataToWrite != nil) {
[self checkIfCanWriteNow];
}
}
- (void)write404 {
- (void)write404 SPU_OBJC_DIRECT
{
NSString *body = @"<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1></body></html>";
[self write:[body dataUsingEncoding:NSUTF8StringEncoding] status:NO];
}
- (void)write:(NSData*)body status:(BOOL)status {
- (void)write:(NSData*)body status:(BOOL)status SPU_OBJC_DIRECT
{
NSString *state = status ? @"200 OK" : @"404 Not Found";
NSString *header = [NSString stringWithFormat:@"HTTP/1.0 %@\r\nContent-Length: %lu\r\n\r\n", state, body.length];
NSMutableData *response = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
@@ -131,37 +130,40 @@
[self queueWrite:response];
}
- (void)queueWrite:(NSData*)data {
assert(self.dataToWrite == nil);
- (void)queueWrite:(NSData*)data SPU_OBJC_DIRECT
{
assert(_dataToWrite == nil);
assert(data != nil);
assert(data.length > 0);
self.dataToWrite = data;
self.numBytesToWrite = (NSInteger)data.length;
_dataToWrite = data;
_numBytesToWrite = (NSInteger)data.length;
[self checkIfCanWriteNow];
}
- (void)checkIfCanWriteNow {
assert(self.dataToWrite != nil);
if (self.numBytesToWrite == 0) {
- (void)checkIfCanWriteNow SPU_OBJC_DIRECT
{
assert(_dataToWrite != nil);
if (_numBytesToWrite == 0) {
// nothing more to write, we're done.
self.dataToWrite = nil;
self.numBytesToWrite = -1;
} else if (self.outputStream.hasSpaceAvailable) {
_dataToWrite = nil;
_numBytesToWrite = -1;
} else if (_outputStream.hasSpaceAvailable) {
[self writeNow];
}
// otherwise wait for space available event
}
- (void)writeNow {
assert(self.outputStream != nil);
assert(self.outputStream.hasSpaceAvailable);
assert(self.dataToWrite != nil);
NSData *dataToWrite = self.dataToWrite;
const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - self.numBytesToWrite);
const NSInteger bytesWritten = [self.outputStream write:bytesOffset maxLength:(NSUInteger)self.numBytesToWrite];
- (void)writeNow SPU_OBJC_DIRECT
{
assert(_outputStream != nil);
assert(_outputStream.hasSpaceAvailable);
assert(_dataToWrite != nil);
NSData *dataToWrite = _dataToWrite;
const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - _numBytesToWrite);
const NSInteger bytesWritten = [_outputStream write:bytesOffset maxLength:(NSUInteger)_numBytesToWrite];
if (bytesWritten > 0) {
self.numBytesToWrite = self.numBytesToWrite - bytesWritten;
assert(self.numBytesToWrite >= 0);
_numBytesToWrite = _numBytesToWrite - bytesWritten;
assert(_numBytesToWrite >= 0);
// wait for next space available event to write more
} else {
NSLog(@"Error: bytes written = %ld (%@)", bytesWritten, [NSString stringWithUTF8String:strerror(errno)]);
@@ -170,7 +172,7 @@
@end
@interface SUTestWebServer () <SUTestWebServerConnectionDelegate> {
SPU_OBJC_DIRECT_MEMBERS @interface SUTestWebServer () <SUTestWebServerConnectionDelegate> {
CFSocketRef _socket;
}
@@ -181,7 +183,8 @@
@end
static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) {
static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info)
{
if (type == kCFSocketAcceptCallBack) {
assert(data != NULL);
assert(info != NULL);
@@ -196,7 +199,8 @@ static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, C
@synthesize connections = _connections;
@synthesize workingDirectory = _workingDirectory;
- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory {
- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory
{
self = [super init];
assert(self != nil);
@@ -231,33 +235,33 @@ static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, C
return self;
}
- (void)connectionDidClose:(SUTestWebServerConnection *)sender {
assert(self.connections != nil);
assert([self.connections containsObject:sender]);
[self.connections removeObject:sender];
- (void)connectionDidClose:(SUTestWebServerConnection *)sender
{
assert(_connections != nil);
assert([_connections containsObject:sender]);
[_connections removeObject:sender];
}
- (void)accept:(CFSocketNativeHandle)address {
SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:self.workingDirectory delegate:self];
- (void)accept:(CFSocketNativeHandle)address
{
SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:_workingDirectory delegate:self];
assert(conn != nil);
if (conn) {
assert(self.connections != nil);
[self.connections addObject:conn];
assert(_connections != nil);
[_connections addObject:conn];
}
}
- (void)close {
for (SUTestWebServerConnection *conn in self.connections) {
- (void)close
{
for (SUTestWebServerConnection *conn in _connections) {
[conn close];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
if (_socket) {
CFSocketInvalidate(_socket);
CFRelease(_socket);
_socket = NULL;
}
#pragma clang diagnostic pop
}
@end