diff --git a/Resources/ReleaseNotesColorStyle.css b/Resources/ReleaseNotesColorStyle.css new file mode 100644 index 00000000..ac5dc3f6 --- /dev/null +++ b/Resources/ReleaseNotesColorStyle.css @@ -0,0 +1,12 @@ +@media (prefers-color-scheme: dark) { + html { + color: white; + background: transparent; + } + :link { + color: #419CFF; + } + :link:active { + color: #FF1919; + } +} diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index e05f9a05..d3ddf893 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -278,6 +278,14 @@ 72AC6B2C1B9AB0EE00F62325 /* SparkleTestCodeSignApp.tar.xz in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B2B1B9AB0EE00F62325 /* SparkleTestCodeSignApp.tar.xz */; }; 72AC6B2E1B9B218C00F62325 /* SparkleTestCodeSignApp.dmg in Resources */ = {isa = PBXBuildFile; fileRef = 72AC6B2D1B9B218C00F62325 /* SparkleTestCodeSignApp.dmg */; }; 72D4DAA11AD7632900B211E2 /* SUBinaryDeltaCreate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */; }; + 72E1D7DD25A3E3AD0001BA6D /* SUWebViewCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = 72E1D7D625A3E3AC0001BA6D /* SUWebViewCommon.m */; }; + 72E1D7DE25A3E3AD0001BA6D /* SUWebViewCommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E1D7D725A3E3AC0001BA6D /* SUWebViewCommon.h */; }; + 72E1D7DF25A3E3AD0001BA6D /* SUWKWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E1D7D825A3E3AC0001BA6D /* SUWKWebView.h */; }; + 72E1D7E025A3E3AD0001BA6D /* SUWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E1D7D925A3E3AC0001BA6D /* SUWebView.h */; }; + 72E1D7E125A3E3AD0001BA6D /* SULegacyWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = 72E1D7DA25A3E3AC0001BA6D /* SULegacyWebView.m */; }; + 72E1D7E225A3E3AD0001BA6D /* SUWKWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = 72E1D7DB25A3E3AD0001BA6D /* SUWKWebView.m */; }; + 72E1D7E325A3E3AD0001BA6D /* SULegacyWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E1D7DC25A3E3AD0001BA6D /* SULegacyWebView.h */; }; + 72E1D82225A3E40F0001BA6D /* ReleaseNotesColorStyle.css in Resources */ = {isa = PBXBuildFile; fileRef = 72E1D82125A3E40F0001BA6D /* ReleaseNotesColorStyle.css */; }; 72E45CF31B640CDD005C701A /* SUTestApplicationDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 72E45CF21B640CDD005C701A /* SUTestApplicationDelegate.m */; }; 72E45CF71B640DAE005C701A /* SUUpdateSettingsWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 72E45CF51B640DAE005C701A /* SUUpdateSettingsWindowController.m */; }; 72E45CF81B640DAE005C701A /* SUUpdateSettingsWindowController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 72E45CF61B640DAE005C701A /* SUUpdateSettingsWindowController.xib */; }; @@ -293,7 +301,6 @@ C23E885B1BE7B24F0050BB73 /* SparkleTestCodeSignApp.enc.dmg in Resources */ = {isa = PBXBuildFile; fileRef = C23E88591BE7AF890050BB73 /* SparkleTestCodeSignApp.enc.dmg */; }; E1545EC51E1D7E0200FAECE8 /* SUTouchBarButtonGroup.h in Headers */ = {isa = PBXBuildFile; fileRef = E1545EC31E1D7E0200FAECE8 /* SUTouchBarButtonGroup.h */; }; E1545EC61E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = E1545EC41E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m */; }; - E1D4DDF921C1C5F8003D32E7 /* DarkAqua.css in Resources */ = {isa = PBXBuildFile; fileRef = E1D4DDF821C1C5F8003D32E7 /* DarkAqua.css */; }; E1EC2A301E21667000245715 /* SUTouchBarButtonGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = E1545EC41E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m */; }; EA1E27F722B60B25004AA304 /* bscommon.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = 723B252C1CEAB3A600909873 /* bscommon.h */; }; EA1E27F822B60B25004AA304 /* bspatch.h in Copy Headers */ = {isa = PBXBuildFile; fileRef = 611142E810FB1BE5009810AA /* bspatch.h */; }; @@ -1005,6 +1012,14 @@ 72AC6B2B1B9AB0EE00F62325 /* SparkleTestCodeSignApp.tar.xz */ = {isa = PBXFileReference; lastKnownFileType = file; path = SparkleTestCodeSignApp.tar.xz; sourceTree = ""; }; 72AC6B2D1B9B218C00F62325 /* SparkleTestCodeSignApp.dmg */ = {isa = PBXFileReference; lastKnownFileType = file; path = SparkleTestCodeSignApp.dmg; sourceTree = ""; }; 72AFC6121B9A944200F6B565 /* Sparkle Unit Tests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Sparkle Unit Tests-Bridging-Header.h"; sourceTree = ""; }; + 72E1D7D625A3E3AC0001BA6D /* SUWebViewCommon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUWebViewCommon.m; sourceTree = ""; }; + 72E1D7D725A3E3AC0001BA6D /* SUWebViewCommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUWebViewCommon.h; sourceTree = ""; }; + 72E1D7D825A3E3AC0001BA6D /* SUWKWebView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUWKWebView.h; sourceTree = ""; }; + 72E1D7D925A3E3AC0001BA6D /* SUWebView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUWebView.h; sourceTree = ""; }; + 72E1D7DA25A3E3AC0001BA6D /* SULegacyWebView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SULegacyWebView.m; sourceTree = ""; }; + 72E1D7DB25A3E3AD0001BA6D /* SUWKWebView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUWKWebView.m; sourceTree = ""; }; + 72E1D7DC25A3E3AD0001BA6D /* SULegacyWebView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SULegacyWebView.h; sourceTree = ""; }; + 72E1D82125A3E40F0001BA6D /* ReleaseNotesColorStyle.css */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.css; name = ReleaseNotesColorStyle.css; path = Resources/ReleaseNotesColorStyle.css; sourceTree = SOURCE_ROOT; }; 72E45CF11B640CDD005C701A /* SUTestApplicationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUTestApplicationDelegate.h; sourceTree = ""; }; 72E45CF21B640CDD005C701A /* SUTestApplicationDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUTestApplicationDelegate.m; sourceTree = ""; }; 72E45CF41B640DAE005C701A /* SUUpdateSettingsWindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUpdateSettingsWindowController.h; sourceTree = ""; }; @@ -1024,7 +1039,6 @@ E1545EC31E1D7E0200FAECE8 /* SUTouchBarButtonGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUTouchBarButtonGroup.h; sourceTree = ""; }; E1545EC41E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUTouchBarButtonGroup.m; sourceTree = ""; }; E19CA4901E2E7E4D009D4D18 /* SUTouchBarForwardDeclarations.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUTouchBarForwardDeclarations.h; sourceTree = ""; }; - E1D4DDF821C1C5F8003D32E7 /* DarkAqua.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = DarkAqua.css; sourceTree = ""; }; EA4311A0229D5FBC00A5503D /* libed25519.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libed25519.a; sourceTree = BUILT_PRODUCTS_DIR; }; EA4311C7229D612A00A5503D /* ed25519-Shared.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "ed25519-Shared.xcconfig"; sourceTree = ""; }; EA4311C8229D613B00A5503D /* ed25519-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "ed25519-Release.xcconfig"; sourceTree = ""; }; @@ -1247,7 +1261,7 @@ 089C1665FE841158C02AAC07 /* Framework Resources */ = { isa = PBXGroup; children = ( - E1D4DDF821C1C5F8003D32E7 /* DarkAqua.css */, + 72E1D82125A3E40F0001BA6D /* ReleaseNotesColorStyle.css */, 8DC2EF5A0486A6940098B216 /* Sparkle-Info.plist */, 61AAE8220A321A7F00D8810D /* Sparkle.strings */, 55C14BD8136EF00C00649790 /* SUStatus.xib */, @@ -1525,6 +1539,7 @@ E19CA4901E2E7E4D009D4D18 /* SUTouchBarForwardDeclarations.h */, 61B5FCA009C5228F00B25A18 /* SUUpdateAlert.h */, 61B5FCA109C5228F00B25A18 /* SUUpdateAlert.m */, + 72E1D7F025A3E3B50001BA6D /* Web View */, 612DCBAD0D488BC60015DBEA /* SUUpdatePermissionPrompt.h */, 612DCBAE0D488BC60015DBEA /* SUUpdatePermissionPrompt.m */, 7205C42F1E1215AD00E370AE /* SUUpdatePermissionResponse.h */, @@ -1668,6 +1683,20 @@ path = UITests; sourceTree = ""; }; + 72E1D7F025A3E3B50001BA6D /* Web View */ = { + isa = PBXGroup; + children = ( + 72E1D7D925A3E3AC0001BA6D /* SUWebView.h */, + 72E1D7D725A3E3AC0001BA6D /* SUWebViewCommon.h */, + 72E1D7D625A3E3AC0001BA6D /* SUWebViewCommon.m */, + 72E1D7D825A3E3AC0001BA6D /* SUWKWebView.h */, + 72E1D7DB25A3E3AD0001BA6D /* SUWKWebView.m */, + 72E1D7DC25A3E3AD0001BA6D /* SULegacyWebView.h */, + 72E1D7DA25A3E3AC0001BA6D /* SULegacyWebView.m */, + ); + name = "Web View"; + sourceTree = ""; + }; FA1941C40D94A6EA00DD942E /* Configurations */ = { isa = PBXGroup; children = ( @@ -1728,8 +1757,10 @@ 5AB8F185214D564C00A1187F /* ed25519.h in Headers */, 5AB8F184214D564C00A1187F /* fe.h in Headers */, A3AD648D24D283F400058938 /* SUGlobalUpdateLock.h in Headers */, + 72E1D7E325A3E3AD0001BA6D /* SULegacyWebView.h in Headers */, 5AB8F18A214D564C00A1187F /* fixedint.h in Headers */, 5AB8F18B214D564C00A1187F /* ge.h in Headers */, + 72E1D7DE25A3E3AD0001BA6D /* SUWebViewCommon.h in Headers */, 5AB8F187214D564C00A1187F /* precomp_data.h in Headers */, 5AB8F18F214D564C00A1187F /* sc.h in Headers */, 5AB8F181214D564C00A1187F /* sha512.h in Headers */, @@ -1742,6 +1773,7 @@ 34074B961FEABD24001CB3A5 /* SPULocalCacheDirectory.h in Headers */, 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */, 61B5FC0D09C4FC8200B25A18 /* SUAppcast.h in Headers */, + 72E1D7E025A3E3AD0001BA6D /* SUWebView.h in Headers */, 61B5FC7009C51F4A00B25A18 /* SUAppcastItem.h in Headers */, 72316BDE1E0E17910039EFD9 /* SUApplicationInfo.h in Headers */, 6120721209CC5C4B007FE0F6 /* SUAutomaticUpdateAlert.h in Headers */, @@ -1756,6 +1788,7 @@ 14652F8419A978C200959E44 /* SUExport.h in Headers */, 7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */, 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */, + 72E1D7DF25A3E3AD0001BA6D /* SUWKWebView.h in Headers */, 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */, 61EF67590E25C5B400F754E0 /* SUHost.h in Headers */, 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */, @@ -2233,11 +2266,11 @@ files = ( 723ABAC5259A5A2300BDB4FA /* SUUpdatePermissionPrompt.xib in Resources */, 723ABA8A259A593900BDB4FA /* SUAutomaticUpdateAlert.xib in Resources */, - E1D4DDF921C1C5F8003D32E7 /* DarkAqua.css in Resources */, 61AAE8280A321A7F00D8810D /* Sparkle.strings in Resources */, 615AE3D00D64DC40001CA7BD /* SUModelTranslation.plist in Resources */, 55C14BEF136EF21700649790 /* SUStatus.xib in Resources */, 723ABA4F259A579D00BDB4FA /* SUUpdateAlert.xib in Resources */, + 72E1D82225A3E40F0001BA6D /* ReleaseNotesColorStyle.css in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2445,6 +2478,7 @@ files = ( 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */, 34074B901FEABD08001CB3A5 /* SPUDownloader.m in Sources */, + 72E1D7DD25A3E3AD0001BA6D /* SUWebViewCommon.m in Sources */, 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */, 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */, 34074B9A1FEABD49001CB3A5 /* SPUURLRequest.m in Sources */, @@ -2471,6 +2505,7 @@ 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */, 61D85D6D0E10B2ED00F9B4A9 /* SUPipedUnarchiver.m in Sources */, 618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */, + 72E1D7E225A3E3AD0001BA6D /* SUWKWebView.m in Sources */, 6101347C0DD2541A0049ACDF /* SUProbingUpdateDriver.m in Sources */, 61B93C0A0DD112FF00DCD2F8 /* SUScheduledUpdateDriver.m in Sources */, 5AF04878214D2E5F00B5789F /* SUSignatures.m in Sources */, @@ -2482,6 +2517,7 @@ A3AD648C24D283F400058938 /* SUGlobalUpdateLock.m in Sources */, E1545EC61E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m in Sources */, 61B93A3D0DD02D7000DCD2F8 /* SUUIBasedUpdateDriver.m in Sources */, + 72E1D7E125A3E3AD0001BA6D /* SULegacyWebView.m in Sources */, 61299A8E09CA790200B7442F /* SUUnarchiver.m in Sources */, 722589DB1E0B19F4005EA0B9 /* SUUnarchiverNotifier.m in Sources */, 61B5FCDE09C52A9F00B25A18 /* SUUpdateAlert.m in Sources */, diff --git a/Sparkle/Base.lproj/SUUpdateAlert.xib b/Sparkle/Base.lproj/SUUpdateAlert.xib index a9861d6d..f9d5d104 100644 --- a/Sparkle/Base.lproj/SUUpdateAlert.xib +++ b/Sparkle/Base.lproj/SUUpdateAlert.xib @@ -3,7 +3,6 @@ - @@ -13,8 +12,8 @@ + - @@ -81,27 +80,8 @@ - - - - - - - - - - NSNegateBoolean - - - - - - - - - diff --git a/Sparkle/DarkAqua.css b/Sparkle/DarkAqua.css deleted file mode 100644 index a41e0f28..00000000 --- a/Sparkle/DarkAqua.css +++ /dev/null @@ -1,9 +0,0 @@ -html { - color: #FFFFFFD8; -} -:link { - color: #419CFF; -} -:link:active { - color: #FF1919; -} diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index 4b160c4f..4d00f845 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -30,6 +30,7 @@ typedef NS_ENUM(OSStatus, SUError) { SUAppcastError = 1002, SURunningFromDiskImageError = 1003, SURunningTranslocated = 1004, + SUWebKitTerminationError = 1005, // Download phase errors. SUTemporaryDirectoryError = 2000, diff --git a/Sparkle/SULegacyWebView.h b/Sparkle/SULegacyWebView.h new file mode 100644 index 00000000..90ac25ee --- /dev/null +++ b/Sparkle/SULegacyWebView.h @@ -0,0 +1,20 @@ +// +// SULegacyWebView.h +// Sparkle +// +// Created by Mayur Pawashe on 12/30/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import +#import "SUWebView.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface SULegacyWebView : NSObject + +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SULegacyWebView.m b/Sparkle/SULegacyWebView.m new file mode 100644 index 00000000..88001013 --- /dev/null +++ b/Sparkle/SULegacyWebView.m @@ -0,0 +1,168 @@ +// +// SULegacyWebView.m +// Sparkle +// +// Created by Mayur Pawashe on 12/30/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import "SULegacyWebView.h" +#import "SUWebViewCommon.h" +#import "SULog.h" +#import + +// WebKit protocols are not explicitly declared until 10.11 SDK, so +// declare dummy protocols to keep the build working on earlier SDKs. +#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101100 +@protocol WebFrameLoadDelegate +@end +@protocol WebPolicyDelegate +@end +#endif + +@interface SULegacyWebView () + +@property (nonatomic, readonly) WebView *webView; +@property (nonatomic) void (^completionHandler)(NSError * _Nullable); + +@end + +@implementation SULegacyWebView + +@synthesize webView = _webView; +@synthesize completionHandler = _completionHandler; + +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled +{ + self = [super init]; + if (self != nil) { + _webView = [[WebView alloc] initWithFrame:NSZeroRect]; + + WebPreferences *preferences = _webView.preferences; + preferences.javaScriptEnabled = javaScriptEnabled; + preferences.javaEnabled = NO; + preferences.plugInsEnabled = NO; + + // Mimicking settings when WebView used to be in SUUpdateAlert nib + preferences.loadsImagesAutomatically = YES; + preferences.allowsAnimatedImages = YES; + preferences.allowsAnimatedImageLooping = YES; + + // Settings for default style + preferences.userStyleSheetEnabled = YES; + preferences.userStyleSheetLocation = colorStyleSheetLocation; + preferences.standardFontFamily = fontFamily; + preferences.defaultFontSize = fontPointSize; + + _webView.preferences = preferences; + _webView.policyDelegate = self; + _webView.frameLoadDelegate = self; + } + return self; +} + +- (NSView *)view +{ + return self.webView; +} + +- (void)loadHTMLString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler +{ + self.completionHandler = [completionHandler copy]; + [[self.webView mainFrame] loadHTMLString:htmlString baseURL:baseURL]; +} + +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler +{ + self.completionHandler = [completionHandler copy]; + [[self.webView mainFrame] loadData:data MIMEType:MIMEType textEncodingName:textEncodingName baseURL:baseURL]; +} + +- (void)stopLoading +{ + self.completionHandler = nil; + [self.webView stopLoading:self]; +} + +- (void)setDrawsBackground:(BOOL)drawsBackground +{ + self.webView.drawsBackground = drawsBackground; +} + +- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame +{ + if ([frame parentFrame] == nil) { + if (self.completionHandler != nil) { + self.completionHandler(nil); + self.completionHandler = nil; + } + [sender display]; // necessary to prevent weird scroll bar artifacting + } +} + +- (void)webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame +{ + if ([frame parentFrame] == nil) { + if (self.completionHandler != nil) { + self.completionHandler(error); + self.completionHandler = nil; + } + } +} + +- (void)webView:(WebView *)__unused sender decidePolicyForNavigationAction:(NSDictionary *)__unused actionInformation request:(NSURLRequest *)request frame:(WebFrame *)__unused frame decisionListener:(id)listener +{ + NSURL *requestURL = request.URL; + BOOL safeURL = SUWebViewIsSafeURL(requestURL); + + // Do not allow redirects to dangerous protocols such as file:// + if (!safeURL) { + SULog(SULogLevelDefault, @"Blocked display of %@ URL which may be dangerous", requestURL.scheme); + [listener ignore]; + return; + } + + // Ensure we are finished loading + if (self.completionHandler == nil) { + if (requestURL) { + [[NSWorkspace sharedWorkspace] openURL:requestURL]; + } + + [listener ignore]; + } + else { + [listener use]; + } +} + +// Clean up the contextual menu. +- (NSArray *)webView:(WebView *)__unused sender contextMenuItemsForElement:(NSDictionary *)__unused element defaultMenuItems:(NSArray *)defaultMenuItems +{ + NSMutableArray *webViewMenuItems = [defaultMenuItems mutableCopy]; + + if (webViewMenuItems) + { + for (NSMenuItem *menuItem in defaultMenuItems) + { + 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]; + } + } + } + + return webViewMenuItems; +} + +@end diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 37b7bfc1..11518300 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -13,7 +13,9 @@ #import "SUUpdateAlert.h" #import "SUHost.h" -#import +#import "SUWebView.h" +#import "SUWKWebView.h" +#import "SULegacyWebView.h" #import "SUConstants.h" #import "SULog.h" @@ -27,35 +29,26 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUUpdateAlert"; -// WebKit protocols are not explicitly declared until 10.11 SDK, so -// declare dummy protocols to keep the build working on earlier SDKs. -#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101100 -@protocol WebFrameLoadDelegate -@end -@protocol WebPolicyDelegate -@end -@protocol WebUIDelegate -@end -#endif - -@interface SUUpdateAlert () +@interface SUUpdateAlert () @property (strong) SUAppcastItem *updateItem; @property (strong) SUHost *host; @property (strong) void(^completionBlock)(SUUpdateAlertChoice); @property (strong) NSProgressIndicator *releaseNotesSpinner; -@property (assign) BOOL webViewFinishedLoading; @property (assign) BOOL observingAppearance; - -@property (weak) IBOutlet WebView *releaseNotesView; @property (weak) IBOutlet NSView *releaseNotesContainerView; +@property (weak) IBOutlet NSBox *releaseNotesBoxView; @property (weak) IBOutlet NSTextField *descriptionField; @property (weak) IBOutlet NSButton *automaticallyInstallUpdatesButton; @property (weak) IBOutlet NSButton *installButton; @property (weak) IBOutlet NSButton *skipButton; @property (weak) IBOutlet NSButton *laterButton; +@property (strong) NSBox *darkBackgroundView; + +@property (nonatomic) id webView; + @end @implementation SUUpdateAlert @@ -67,17 +60,20 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @synthesize host; @synthesize releaseNotesSpinner; -@synthesize webViewFinishedLoading; @synthesize observingAppearance; -@synthesize releaseNotesView; @synthesize releaseNotesContainerView; +@synthesize releaseNotesBoxView = _releaseNotesBoxView; @synthesize descriptionField; @synthesize automaticallyInstallUpdatesButton; @synthesize installButton; @synthesize skipButton; @synthesize laterButton; +@synthesize darkBackgroundView = _darkBackgroundView; + +@synthesize webView = _webView; + - (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost completionBlock:(void (^)(SUUpdateAlertChoice))block { self = [super initWithWindowNibName:@"SUUpdateAlert"]; @@ -87,30 +83,31 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE 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; -} - -- (void)dealloc { -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 - if (SUAVAILABLE(10, 14)) { - if (self.observingAppearance) { - [self.window removeObserver:self forKeyPath:@"effectiveAppearance"]; - self.observingAppearance = NO; + + NSURL *colorStyleURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"ReleaseNotesColorStyle" withExtension:@"css"]; + + // "-apple-system-font" is a reference to the system UI font. "-apple-system" is the new recommended token, but for backward compatibility we can't use it. + NSString *defaultFontFamily = @"-apple-system-font"; + int defaultFontSize = (int)[NSFont systemFontSize]; + + BOOL javaScriptEnabled = [host boolForInfoDictionaryKey:SUEnableJavaScriptKey]; + + BOOL useWKWebView; + if (@available(macOS 10.11, *)) { + useWKWebView = YES; + } else { + // Never use WKWebView prior to macOS 10.11. Details are in SUWKWebView.m + // Note: 2.x has another case where we fall back to using legacy WKWebView due to certain sandboxing issues. + useWKWebView = NO; + } + + if (useWKWebView) { + _webView = [[SUWKWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; + } else { + _webView = [[SULegacyWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; } } -#endif -} - -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__attribute__((unused)) NSDictionary *)change context:(__attribute__((unused)) void *)context { - if (object == self.window && [keyPath isEqualToString:@"effectiveAppearance"]) { - [self adaptReleaseNotesAppearance]; - } + return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } @@ -121,11 +118,8 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)endWithSelection:(SUUpdateAlertChoice)choice { - [self.releaseNotesView stopLoading:self]; - self.releaseNotesView.frameLoadDelegate = nil; - self.releaseNotesView.policyDelegate = nil; - self.releaseNotesView.UIDelegate = nil; - [self.releaseNotesView removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. + [self.webView stopLoading]; + [self.webView.view removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. [self close]; self.completionBlock(choice); self.completionBlock = nil; @@ -153,58 +147,96 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)displayReleaseNotes { - self.releaseNotesView.preferencesIdentifier = SUBundleIdentifier; - WebPreferences *prefs = [self.releaseNotesView preferences]; - prefs.plugInsEnabled = NO; - prefs.javaEnabled = NO; - prefs.javaScriptEnabled = [self.host boolForInfoDictionaryKey:SUEnableJavaScriptKey]; - self.releaseNotesView.frameLoadDelegate = self; - self.releaseNotesView.policyDelegate = self; - self.releaseNotesView.UIDelegate = self; + [self adaptReleaseNotesAppearance]; - // Set the default font - // "-apple-system-font" is a reference to the system UI font. "-apple-system" is the new recommended token, but for backward compatibility we can't use it. - prefs.standardFontFamily = @"-apple-system-font"; - prefs.defaultFontSize = (int)[NSFont systemFontSize]; - -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 - if (SUAVAILABLE(10, 14)) - { - NSBox *darkBackgroundView = [[NSBox alloc] initWithFrame:self.releaseNotesView.frame]; - darkBackgroundView.boxType = NSBoxCustom; - darkBackgroundView.fillColor = [NSColor textBackgroundColor]; - darkBackgroundView.borderColor = [NSColor clearColor]; - // Using auto-resizing mask instead of contraints works well enough - darkBackgroundView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; - [self.releaseNotesView.superview addSubview:darkBackgroundView positioned:NSWindowBelow relativeTo:self.releaseNotesView]; - self.releaseNotesView.drawsBackground = NO; - - prefs.userStyleSheetLocation = [[NSBundle bundleForClass:[self class]] URLForResource:@"DarkAqua" withExtension:@"css"]; - if (!self.observingAppearance) { - [self.window addObserver:self forKeyPath:@"effectiveAppearance" options:NSKeyValueObservingOptionInitial context:nil]; - self.observingAppearance = YES; - } - } -#endif // Stick a nice big spinner in the middle of the web view until the page is loaded. - NSRect frame = [[self.releaseNotesView superview] frame]; + NSRect frame = [[self.webView.view 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]; + [[self.webView.view 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 ([self.updateItem releaseNotesURL]) { - [[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]; + __weak __typeof__(self) weakSelf = self; + [self.webView loadHTMLString:[self.updateItem itemDescription] baseURL:nil completionHandler:^(NSError * _Nullable error) { + if (error != nil) { + SULog(SULogLevelError, @"Failed to load HTML string from web view: %@", error); + } + [weakSelf stopReleaseNotesSpinner]; + }]; } } +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__attribute__((unused)) NSDictionary *)change context:(__attribute__((unused)) void *)context { +#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if (@available(macOS 10.14, *)) { + if (object == self.webView.view && [keyPath isEqualToString:@"effectiveAppearance"]) { + [self adaptReleaseNotesAppearance]; + } + } +#endif +} + +- (void)dealloc { +#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if (@available(macOS 10.14, *)) { + if (self.observingAppearance) { + [self.webView.view removeObserver:self forKeyPath:@"effectiveAppearance"]; + self.observingAppearance = NO; + } + } +#endif +} + +- (void)adaptReleaseNotesAppearance +{ +#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if (@available(macOS 10.14, *)) + { + NSAppearanceName bestAppearance = [self.webView.view.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; + if ([bestAppearance isEqualToString:NSAppearanceNameDarkAqua]) + { + // Remove web view background... + [self.webView setDrawsBackground:NO]; + // ... and use NSBox to get the dynamically colored background + if (self.darkBackgroundView == nil) + { + self.darkBackgroundView = [[NSBox alloc] initWithFrame:self.webView.view.frame]; + self.darkBackgroundView.boxType = NSBoxCustom; + self.darkBackgroundView.fillColor = [NSColor textBackgroundColor]; + self.darkBackgroundView.borderColor = [NSColor clearColor]; + // Using auto-resizing mask instead of contraints works well enough + self.darkBackgroundView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + [self.webView.view.superview addSubview:self.darkBackgroundView positioned:NSWindowBelow relativeTo:self.webView.view]; + + // The release note user stylesheet will not adjust to the user changing the theme until adaptReleaseNoteAppearance is called again. + // So lock the appearance of the background to keep the text readable if the system theme changes. + self.darkBackgroundView.appearance = self.darkBackgroundView.effectiveAppearance; + } + } + else + { + // Restore standard dark on light appearance + [self.darkBackgroundView removeFromSuperview]; + self.darkBackgroundView = nil; + [self.webView setDrawsBackground:YES]; + } + } +#endif +} + +- (void)stopReleaseNotesSpinner +{ + [self.releaseNotesSpinner stopAnimation:self]; + [self.releaseNotesSpinner setHidden:YES]; +} + - (BOOL)showsReleaseNotes { NSNumber *shouldShowReleaseNotes = [self.host objectForInfoDictionaryKey:SUShowReleaseNotesKey]; @@ -228,6 +260,13 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)windowDidLoad { BOOL showReleaseNotes = [self showsReleaseNotes]; + + NSView *boxContentView = self.releaseNotesBoxView.contentView; + [boxContentView addSubview:self.webView.view]; + + self.webView.view.frame = boxContentView.bounds; + self.webView.view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + self.webView.view.hidden = !showReleaseNotes; [self.window setFrameAutosaveName: showReleaseNotes ? @"SUUpdateAlert" : @"SUUpdateAlertSmall" ]; @@ -323,86 +362,6 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE return finalString; } -- (void)adaptReleaseNotesAppearance -{ -#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 - if (SUAVAILABLE(10, 14)) - { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunguarded-availability" - NSAppearanceName bestAppearance = [self.window.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; - BOOL isDarkAqua = ([bestAppearance isEqualToString:NSAppearanceNameDarkAqua]); - self.releaseNotesView.preferences.userStyleSheetEnabled = isDarkAqua; -#pragma clang diagnostic pop - } -#endif -} - -- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame -{ - if ([frame parentFrame] == nil) { - self.webViewFinishedLoading = YES; - [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 -{ - NSURL *requestURL = request.URL; - NSString *scheme = requestURL.scheme; - BOOL isAboutBlank = [requestURL.absoluteString isEqualToString:@"about:blank"]; - BOOL whitelistedSafe = isAboutBlank || [@[@"http", @"https", @"macappstore", @"macappstores", @"itms-apps", @"itms-appss"] containsObject:scheme]; - - // Do not allow redirects to dangerous protocols such as file:// - if (!whitelistedSafe) { - SULog(SULogLevelDefault, @"Blocked display of %@ URL which may be dangerous", scheme); - [listener ignore]; - return; - } - - if (self.webViewFinishedLoading) { - if (requestURL && !isAboutBlank) { - [[NSWorkspace sharedWorkspace] openURL:requestURL]; - } - - [listener ignore]; - } - else { - [listener use]; - } -} - -// Clean up the contextual menu. -- (NSArray *)webView:(WebView *)__unused sender contextMenuItemsForElement:(NSDictionary *)__unused element defaultMenuItems:(NSArray *)defaultMenuItems -{ - NSMutableArray *webViewMenuItems = [defaultMenuItems mutableCopy]; - - if (webViewMenuItems) - { - for (NSMenuItem *menuItem in defaultMenuItems) - { - 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]; - } - } - } - - return webViewMenuItems; -} - - (NSTouchBar *)makeTouchBar { NSTouchBar *touchBar = [(NSTouchBar *)[NSClassFromString(@"NSTouchBar") alloc] init]; diff --git a/Sparkle/SUWKWebView.h b/Sparkle/SUWKWebView.h new file mode 100644 index 00000000..c7f0738d --- /dev/null +++ b/Sparkle/SUWKWebView.h @@ -0,0 +1,21 @@ +// +// SUWKWebView.h +// Sparkle +// +// Created by Mayur Pawashe on 12/30/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import +#import "SUWebView.h" + +NS_ASSUME_NONNULL_BEGIN + +// Only use this class on macOS 10.11 or later (see implementation for rationale) +@interface SUWKWebView : NSObject + +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUWKWebView.m b/Sparkle/SUWKWebView.m new file mode 100644 index 00000000..4ff3957e --- /dev/null +++ b/Sparkle/SUWKWebView.m @@ -0,0 +1,235 @@ +// +// SUWKWebView.m +// Sparkle +// +// Created by Mayur Pawashe on 12/30/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import "SUWKWebView.h" +#import "SUWebViewCommon.h" +#import "SULog.h" +#import "SUErrors.h" +#import + +@interface WKWebView (Private) + +- (void)_setDrawsBackground:(BOOL)drawsBackground; +- (void)_setDrawsTransparentBackground:(BOOL)drawsTransparentBackground; + +@end + +@interface SUWKWebView () + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +@property (nonatomic, readonly) WKWebView *webView; +@property (nonatomic) WKNavigation *currentNavigation; +#pragma clang diagnostic pop +@property (nonatomic) void (^completionHandler)(NSError * _Nullable); +@property (nonatomic) BOOL drawsWebViewBackground; + +@end + +@implementation SUWKWebView + +@synthesize webView = _webView; +@synthesize currentNavigation = _currentNavigation; +@synthesize completionHandler = _completionHandler; +@synthesize drawsWebViewBackground = _drawsWebViewBackground; + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +static WKUserScript *_userScriptWithInjectedStyleSource(NSString *styleSource) +{ + // We must remove newlines when inserting the style source in this interpolated string below + NSString *strippedStyleSource = [styleSource stringByReplacingOccurrencesOfString:@"\n" withString:@""]; + + NSString *scriptSource = [NSString stringWithFormat: + @"var style = document.createElement('style');\n" + @"style.innerHTML = '%@'\n" + @"var head = document.head;\n" + @"if (head.firstChild) {" + @"\tdocument.head.insertBefore(style, document.head.firstChild);\n" + @"} else {\n" + @"\tdocument.head.appendChild(style)\n" + @"}", strippedStyleSource]; + + return [[WKUserScript alloc] initWithSource:scriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; +} +#pragma clang diagnostic pop + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled +{ + self = [super init]; + if (self != nil) { + // Synchronize with web view defaulting to drawing background to avoid unnecessary invocations in -setDrawsBackground: + _drawsWebViewBackground = YES; + + WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; + + // Note: this javaScriptEnabled property is deprecated in favor of another webpage preference property, + // that involves implementing a delegate method that is only available on macOS 11.. to get it properly working. + // To simplify things, just rely on deprecated property for now. + // Future reader: if you change how JS is disabled, please be sure to test that JS code is properly disabled in HTML release notes. + configuration.preferences.javaScriptEnabled = javaScriptEnabled; + configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO; + + NSError *colorStyleContentsError = nil; + NSString *colorStyleContents = [NSString stringWithContentsOfURL:colorStyleSheetLocation encoding:NSUTF8StringEncoding error:&colorStyleContentsError]; + + WKUserContentController *userContentController = [[WKUserContentController alloc] init]; + + NSString *fontStyleContents = [NSString stringWithFormat:@"body { font-family: %@; font-size: %dpt; }", fontFamily, fontPointSize]; + + NSString *finalStyleContents; + if (colorStyleContents == nil) { + SULog(SULogLevelError, @"Failed to load style contents from %@ with %@", colorStyleSheetLocation, colorStyleContentsError); + + finalStyleContents = fontStyleContents; + } else { + finalStyleContents = [NSString stringWithFormat:@"%@ %@", fontStyleContents, colorStyleContents]; + } + + // Note: we can still execute javascript via WKUserScript even if javascript is otherwise disabled from the web content + // In fact, we must execute javascript to properly inject our default CSS style into the DOM + // Legacy WebView has exposed methods for custom stylesheets and default fonts, + // but WKWebView seems to forgo that type of API surface in favor of user scripts like this + [userContentController addUserScript:_userScriptWithInjectedStyleSource(finalStyleContents)]; + configuration.userContentController = userContentController; + + _webView = [[WKWebView alloc] initWithFrame:NSZeroRect configuration:configuration]; + _webView.navigationDelegate = self; + } + return self; +} +#pragma clang diagnostic pop + +- (NSView *)view +{ + return self.webView; +} + +- (void)loadHTMLString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler +{ + self.completionHandler = [completionHandler copy]; + + self.currentNavigation = [self.webView loadHTMLString:htmlString baseURL:baseURL]; +} + +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler +{ + self.completionHandler = [completionHandler copy]; + + // Remove when minimum system requirement is 10.11+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + // Note: This API requires macOS 10.11 + // Rather than figuring out a bad workaround for 10.10, it is simpler to just require 10.11 for this class + self.currentNavigation = [self.webView loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL]; +#pragma clang diagnostic pop +} + +- (void)setDrawsBackground:(BOOL)drawsBackground +{ + if (self.drawsWebViewBackground != drawsBackground) { + // Unfortunately we have to rely on a private API + // FB7539179: https://github.com/feedback-assistant/reports/issues/81 | https://bugs.webkit.org/show_bug.cgi?id=155550 + // But it seems like others are already relying on it, passed App Review, and apps couldn't be broken due to compatibility + if (@available(macOS 10.12, *)) { + if ([self.webView respondsToSelector:@selector(_setDrawsBackground:)]) { + [self.webView _setDrawsBackground:drawsBackground]; + } + } else { + if ([self.webView respondsToSelector:@selector(_setDrawsTransparentBackground:)]) { + [self.webView _setDrawsTransparentBackground:!drawsBackground]; + } + } + + self.drawsWebViewBackground = drawsBackground; + } +} + +- (void)stopLoading +{ + self.completionHandler = nil; + [self.webView stopLoading]; +} + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation +#pragma clang diagnostic pop +{ + if (navigation == self.currentNavigation) { + if (self.completionHandler != nil) { + self.completionHandler(nil); + self.completionHandler = nil; + } + self.currentNavigation = nil; + } +} + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error +#pragma clang diagnostic pop +{ + if (navigation == self.currentNavigation) { + if (self.completionHandler != nil) { + self.completionHandler(error); + self.completionHandler = nil; + } + self.currentNavigation = nil; + } +} + +// Remove when minimum system requirement is 10.10+ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView +#pragma clang diagnostic pop +{ + if (self.currentNavigation != nil) { + if (self.completionHandler != nil) { + self.completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUWebKitTerminationError userInfo:nil]); + self.completionHandler = nil; + } + + self.currentNavigation = nil; + } +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler +{ + NSURLRequest *request = navigationAction.request; + NSURL *requestURL = request.URL; + BOOL safeURL = SUWebViewIsSafeURL(requestURL); + + // Do not allow redirects to dangerous protocols such as file:// + if (!safeURL) { + SULog(SULogLevelDefault, @"Blocked display of %@ URL which may be dangerous", requestURL.scheme); + decisionHandler(WKNavigationActionPolicyCancel); + } else { + // Ensure we're finished loading + if (self.completionHandler == nil) { + [[NSWorkspace sharedWorkspace] openURL:requestURL]; + + decisionHandler(WKNavigationActionPolicyCancel); + } else { + decisionHandler(WKNavigationActionPolicyAllow); + } + } +} +#pragma clang diagnostic pop + +@end diff --git a/Sparkle/SUWebView.h b/Sparkle/SUWebView.h new file mode 100644 index 00000000..253536ed --- /dev/null +++ b/Sparkle/SUWebView.h @@ -0,0 +1,29 @@ +// +// SUWebView.h +// Sparkle +// +// Created by Mayur Pawashe on 12/30/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import + +@class NSView; + +NS_ASSUME_NONNULL_BEGIN + +@protocol SUWebView + +@property (nonatomic, readonly) NSView *view; + +- (void)loadHTMLString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler; + +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler; + +- (void)stopLoading; + +- (void)setDrawsBackground:(BOOL)drawsBackground; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUWebViewCommon.h b/Sparkle/SUWebViewCommon.h new file mode 100644 index 00000000..79beed2e --- /dev/null +++ b/Sparkle/SUWebViewCommon.h @@ -0,0 +1,15 @@ +// +// SUWebViewCommon.h +// Sparkle +// +// Created by Mayur Pawashe on 12/31/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +BOOL SUWebViewIsSafeURL(NSURL *url); + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUWebViewCommon.m b/Sparkle/SUWebViewCommon.m new file mode 100644 index 00000000..e1ea0561 --- /dev/null +++ b/Sparkle/SUWebViewCommon.m @@ -0,0 +1,17 @@ +// +// SUWebViewCommon.m +// Sparkle +// +// Created by Mayur Pawashe on 12/31/20. +// Copyright © 2020 Sparkle Project. All rights reserved. +// + +#import "SUWebViewCommon.h" + +BOOL SUWebViewIsSafeURL(NSURL *url) +{ + NSString *scheme = url.scheme; + BOOL isAboutBlank = [url.absoluteString isEqualToString:@"about:blank"]; + BOOL whitelistedSafe = isAboutBlank || [@[@"http", @"https", @"macappstore", @"macappstores", @"itms-apps", @"itms-appss"] containsObject:scheme]; + return whitelistedSafe; +}