diff --git a/Resources/DarkAqua.css b/Resources/DarkAqua.css deleted file mode 100644 index 9be7f7a9..00000000 --- a/Resources/DarkAqua.css +++ /dev/null @@ -1,10 +0,0 @@ -html { - color: white; - background: transparent; -} -:link { - color: #419CFF; -} -:link:active { - color: #FF1919; -} 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 86287014..89179381 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -52,7 +52,7 @@ 14950073195FCE4E00BC5B5B /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6B19AEBC530061B14F /* signed-test-file.txt */; }; 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6C19AEBC610061B14F /* test-pubkey.pem */; }; - 1EAA4C8B2132C7BF00604473 /* DarkAqua.css in Resources */ = {isa = PBXBuildFile; fileRef = 1EAA4C8A2132C7BF00604473 /* DarkAqua.css */; }; + 1EAA4C8B2132C7BF00604473 /* ReleaseNotesColorStyle.css in Resources */ = {isa = PBXBuildFile; fileRef = 1EAA4C8A2132C7BF00604473 /* ReleaseNotesColorStyle.css */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BEF136EF21700649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; 55C14F06136EF6DB00649790 /* SULog.h in Headers */ = {isa = PBXBuildFile; fileRef = 55C14F04136EF6DB00649790 /* SULog.h */; }; @@ -167,6 +167,13 @@ 723ABD6C259A9CBC00BDB4FA /* SUUpdatePermissionPrompt.xib in Resources */ = {isa = PBXBuildFile; fileRef = 723ABD6A259A9CBB00BDB4FA /* SUUpdatePermissionPrompt.xib */; }; 723ABDDB259A9E8600BDB4FA /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 723ABDD9259A9E8600BDB4FA /* InfoPlist.strings */; }; 723ABE02259A9E9E00BDB4FA /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 723ABE00259A9E9E00BDB4FA /* MainMenu.xib */; }; + 723ABF1B259D055E00BDB4FA /* SUWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 723ABF1A259D055E00BDB4FA /* SUWebView.h */; }; + 723ABF30259D062F00BDB4FA /* SULegacyWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 723ABF2E259D062F00BDB4FA /* SULegacyWebView.h */; }; + 723ABF31259D062F00BDB4FA /* SULegacyWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = 723ABF2F259D062F00BDB4FA /* SULegacyWebView.m */; }; + 723ABFC4259D4CB300BDB4FA /* SUWKWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = 723ABFC2259D4CB300BDB4FA /* SUWKWebView.h */; }; + 723ABFC5259D4CB300BDB4FA /* SUWKWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = 723ABFC3259D4CB300BDB4FA /* SUWKWebView.m */; }; + 723AC010259DBDAA00BDB4FA /* SUWebViewCommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 723AC00E259DBDAA00BDB4FA /* SUWebViewCommon.h */; }; + 723AC011259DBDAA00BDB4FA /* SUWebViewCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = 723AC00F259DBDAA00BDB4FA /* SUWebViewCommon.m */; }; 723B5DA71CF7AB0100365F95 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 723B5DA01CF7AB0100365F95 /* main.m */; }; 723B5DA91CF7AB0100365F95 /* SPUDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 723B5DA31CF7AB0100365F95 /* SPUDownloader.m */; }; 723B5DAA1CF7AB6A00365F95 /* SPUDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 723B5DA31CF7AB0100365F95 /* SPUDownloader.m */; }; @@ -909,7 +916,7 @@ 14958C6C19AEBC610061B14F /* test-pubkey.pem */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "test-pubkey.pem"; sourceTree = ""; }; 149B78631B7D3A0C00D7D62C /* ConfigCommonCoverage.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigCommonCoverage.xcconfig; sourceTree = ""; }; 149B78641B7D3A4800D7D62C /* ConfigUnitTestCoverage.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigUnitTestCoverage.xcconfig; sourceTree = ""; }; - 1EAA4C8A2132C7BF00604473 /* DarkAqua.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = DarkAqua.css; sourceTree = ""; }; + 1EAA4C8A2132C7BF00604473 /* ReleaseNotesColorStyle.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = ReleaseNotesColorStyle.css; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 525A278F133D6AE900FD8D70 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; @@ -1135,6 +1142,13 @@ 723ABE37259A9F2900BDB4FA /* th */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = th; path = th.lproj/MainMenu.strings; sourceTree = ""; }; 723ABE38259A9F2B00BDB4FA /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/MainMenu.strings; sourceTree = ""; }; 723ABE39259A9F2E00BDB4FA /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/MainMenu.strings; sourceTree = ""; }; + 723ABF1A259D055E00BDB4FA /* SUWebView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUWebView.h; sourceTree = ""; }; + 723ABF2E259D062F00BDB4FA /* SULegacyWebView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SULegacyWebView.h; sourceTree = ""; }; + 723ABF2F259D062F00BDB4FA /* SULegacyWebView.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SULegacyWebView.m; sourceTree = ""; }; + 723ABFC2259D4CB300BDB4FA /* SUWKWebView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUWKWebView.h; sourceTree = ""; }; + 723ABFC3259D4CB300BDB4FA /* SUWKWebView.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SUWKWebView.m; sourceTree = ""; }; + 723AC00E259DBDAA00BDB4FA /* SUWebViewCommon.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUWebViewCommon.h; sourceTree = ""; }; + 723AC00F259DBDAA00BDB4FA /* SUWebViewCommon.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SUWebViewCommon.m; sourceTree = ""; }; 723B5D9F1CF7AB0100365F95 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Downloader/Info.plist; sourceTree = SOURCE_ROOT; }; 723B5DA01CF7AB0100365F95 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = Downloader/main.m; sourceTree = SOURCE_ROOT; }; 723B5DA21CF7AB0100365F95 /* SPUDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPUDownloader.h; path = Downloader/SPUDownloader.h; sourceTree = SOURCE_ROOT; }; @@ -1705,7 +1719,7 @@ 657C5F2B218CBC1700925834 /* INSTALL.markdown */, 14732BB91960EEEE00593899 /* SampleAppcast.xml */, 615AE3CF0D64DC40001CA7BD /* SUModelTranslation.plist */, - 1EAA4C8A2132C7BF00604473 /* DarkAqua.css */, + 1EAA4C8A2132C7BF00604473 /* ReleaseNotesColorStyle.css */, ); path = Resources; sourceTree = ""; @@ -1869,6 +1883,7 @@ 6196CFE409C71ADE000DC222 /* SUStatusController.m */, 61B5FCA009C5228F00B25A18 /* SUUpdateAlert.h */, 61B5FCA109C5228F00B25A18 /* SUUpdateAlert.m */, + 723AC036259DBF1B00BDB4FA /* Web View */, 612DCBAD0D488BC60015DBEA /* SUUpdatePermissionPrompt.h */, 612DCBAE0D488BC60015DBEA /* SUUpdatePermissionPrompt.m */, 720767D21E2EE9C200F9A850 /* SUTouchBarForwardDeclarations.h */, @@ -2057,6 +2072,20 @@ name = Internal; sourceTree = ""; }; + 723AC036259DBF1B00BDB4FA /* Web View */ = { + isa = PBXGroup; + children = ( + 723ABF1A259D055E00BDB4FA /* SUWebView.h */, + 723AC00E259DBDAA00BDB4FA /* SUWebViewCommon.h */, + 723AC00F259DBDAA00BDB4FA /* SUWebViewCommon.m */, + 723ABFC2259D4CB300BDB4FA /* SUWKWebView.h */, + 723ABFC3259D4CB300BDB4FA /* SUWKWebView.m */, + 723ABF2E259D062F00BDB4FA /* SULegacyWebView.h */, + 723ABF2F259D062F00BDB4FA /* SULegacyWebView.m */, + ); + name = "Web View"; + sourceTree = ""; + }; 724BB36D1D31D0B7005D534A /* InstallerConnection */ = { isa = PBXGroup; children = ( @@ -2386,6 +2415,7 @@ 7267E5FD1D3DD1B700D1BF90 /* SPUResumableUpdate.h in Headers */, 7267E5B61D3D8AEE00D1BF90 /* SPUInstallationInfo.h in Headers */, 72B767CE1C9B924900A07552 /* SPUInstallerDriver.h in Headers */, + 723ABF30259D062F00BDB4FA /* SULegacyWebView.h in Headers */, 721BC20E1D1CDE55002BC71E /* SPULocalCacheDirectory.h in Headers */, 7267E5B11D3D8AD500D1BF90 /* SPUMessageTypes.h in Headers */, 728337A61C9E6FF40085AA99 /* SPUProbeInstallStatus.h in Headers */, @@ -2407,6 +2437,7 @@ 726E078D1CA891E9001A286B /* SPUUpdaterSettings.h in Headers */, 72F9EC3F1D5E823F004AC8B6 /* SPUUpdaterTimer.h in Headers */, 72B09CE71CE6BCBD0052EF9E /* SPUURLDownload.h in Headers */, + 723ABFC4259D4CB300BDB4FA /* SUWKWebView.h in Headers */, 7293A1AE1CEE933800B957A7 /* SPUURLRequest.h in Headers */, 725CB9571C7120410064365A /* SPUUserDriver.h in Headers */, 725F977B1C8A896F00265BE4 /* SPUUserDriverCoreComponent.h in Headers */, @@ -2424,9 +2455,11 @@ 7267E5E51D3D90AA00D1BF90 /* SUFileManager.h in Headers */, 72B3DEC91E23472200457642 /* SPUDownloadedUpdate.h in Headers */, 61EF67590E25C5B400F754E0 /* SUHost.h in Headers */, + 723AC010259DBDAA00BDB4FA /* SUWebViewCommon.h in Headers */, 72162B081C82C9600013C1C5 /* SULocalizations.h in Headers */, 55C14F06136EF6DB00649790 /* SULog.h in Headers */, EA1E286E22B665F0004AA304 /* SUSignatures.h in Headers */, + 723ABF1B259D055E00BDB4FA /* SUWebView.h in Headers */, 72B3DECD1E23479000457642 /* SPUInformationalUpdate.h in Headers */, 726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */, 61A225A40D1C4AC000430CCD /* SUStandardVersionComparator.h in Headers */, @@ -3117,7 +3150,7 @@ buildActionMask = 2147483647; files = ( 61AAE8280A321A7F00D8810D /* Sparkle.strings in Resources */, - 1EAA4C8B2132C7BF00604473 /* DarkAqua.css in Resources */, + 1EAA4C8B2132C7BF00604473 /* ReleaseNotesColorStyle.css in Resources */, 723ABD38259A9BA500BDB4FA /* SUUpdateAlert.xib in Resources */, 615AE3D00D64DC40001CA7BD /* SUModelTranslation.plist in Resources */, 55C14BEF136EF21700649790 /* SUStatus.xib in Resources */, @@ -3614,10 +3647,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 723ABF31259D062F00BDB4FA /* SULegacyWebView.m in Sources */, 72B767E71C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m in Sources */, 72B767D71C9C8B5C00A07552 /* SPUBasicUpdateDriver.m in Sources */, 72B767E31C9CE90A00A07552 /* SPUCoreBasedUpdateDriver.m in Sources */, 72F9EC451D5E9ED8004AC8B6 /* SPUDownloadData.m in Sources */, + 723ABFC5259D4CB300BDB4FA /* SUWKWebView.m in Sources */, 7229E1BE1C98EFF200CB50D0 /* SPUDownloadDriver.m in Sources */, 723B5DAA1CF7AB6A00365F95 /* SPUDownloader.m in Sources */, 7267E5B71D3D8AEE00D1BF90 /* SPUInstallationInfo.m in Sources */, @@ -3670,6 +3705,7 @@ 72F9EBE31D517E2F004AC8B6 /* SUUpdater.m in Sources */, 724BB3881D32A167005D534A /* SUXPCInstallerConnection.m in Sources */, 724BB3A91D33461B005D534A /* SUXPCInstallerStatus.m in Sources */, + 723AC011259DBDAA00BDB4FA /* SUWebViewCommon.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Sparkle/Base.lproj/SUUpdateAlert.xib b/Sparkle/Base.lproj/SUUpdateAlert.xib index 0602bf52..a8aec6b8 100644 --- a/Sparkle/Base.lproj/SUUpdateAlert.xib +++ b/Sparkle/Base.lproj/SUUpdateAlert.xib @@ -3,7 +3,6 @@ - @@ -13,8 +12,8 @@ + - @@ -82,27 +81,8 @@ - - - - - - - - - - NSNegateBoolean - - - - - - - - - diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index 15e3e6e0..5f0bc8b1 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -41,6 +41,7 @@ typedef NS_ENUM(OSStatus, SUError) { SURunningFromDiskImageError = 1003, SUResumeAppcastError = 1004, SURunningTranslocated = 1005, + SUWebKitTerminationError = 1006, // 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 dcb074be..484d8d02 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" @@ -25,19 +27,11 @@ #import "SUSystemUpdateInfo.h" #import "SUTouchBarForwardDeclarations.h" #import "SUTouchBarButtonGroup.h" +#import "SPUXPCServiceInfo.h" 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 -#endif - -@interface SUUpdateAlert () +@interface SUUpdateAlert () @property (strong) SUAppcastItem *updateItem; @property (nonatomic) BOOL alreadyDownloaded; @@ -48,10 +42,9 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @property (nonatomic, copy, nullable) void(^informationalCompletionBlock)(SPUInformationalUpdateAlertChoice); @property (strong) NSProgressIndicator *releaseNotesSpinner; -@property (assign) BOOL webViewFinishedLoading; -@property (strong) 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; @@ -61,6 +54,8 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @property (strong) NSBox *darkBackgroundView; @property (assign) BOOL observingAppearance; +@property (nonatomic) id webView; + @end @implementation SUUpdateAlert @@ -76,10 +71,9 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @synthesize allowsAutomaticUpdates = _allowsAutomaticUpdates; @synthesize releaseNotesSpinner; -@synthesize webViewFinishedLoading; -@synthesize releaseNotesView; @synthesize releaseNotesContainerView; +@synthesize releaseNotesBoxView = _releaseNotesBoxView; @synthesize descriptionField; @synthesize automaticallyInstallUpdatesButton; @synthesize installButton; @@ -89,6 +83,8 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE @synthesize darkBackgroundView = _darkBackgroundView; @synthesize observingAppearance; +@synthesize webView = _webView; + - (instancetype)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost versionDisplayer:(id )aVersionDisplayer { self = [super initWithWindowNibName:@"SUUpdateAlert"]; @@ -101,10 +97,32 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE _allowsAutomaticUpdates = updaterSettings.allowsAutomaticUpdates && !item.isInformationOnlyUpdate; [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]; + 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, *)) { + // WKWebView has a bug where it won't work in loading local HTML content in sandboxed apps that do not have an outgoing network entitlement + // FB6993802: https://twitter.com/sindresorhus/status/1160577243929878528 | https://github.com/feedback-assistant/reports/issues/1 + // If the developer is using the downloader XPC service, they are very most likely are a) sandboxed b) do not use outgoing network entitlement. + // In this case, fall back to legacy WebKit view. + // (In theory it is possible for a non-sandboxed app or sandboxed app with outgoing network entitlement to use the XPC service, it's just pretty unlikely. And falling back to a legacy web view would not be too harmful in those cases). + useWKWebView = !SPUXPCServiceExists(@DOWNLOADER_BUNDLE_ID); + } else { + // Never use WKWebView prior to macOS 10.11. Details are in SUWKWebView.m + 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]; + } } return self; } @@ -149,10 +167,8 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)endWithSelection:(SPUUpdateAlertChoice)choice { - [self.releaseNotesView stopLoading:self]; - [self.releaseNotesView setFrameLoadDelegate:nil]; - [self.releaseNotesView setPolicyDelegate:nil]; - [self.releaseNotesView removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. + [self.webView stopLoading]; + [self.webView.view removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. [self close]; if (self.completionBlock != nil) { @@ -208,49 +224,42 @@ 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; - - // 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]; [self adaptReleaseNotesAppearance]; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 if (@available(macOS 10.14, *)) { if (!self.observingAppearance) { - [self.releaseNotesView addObserver:self forKeyPath:@"effectiveAppearance" options:0 context:nil]; + [self.webView.view addObserver:self forKeyPath:@"effectiveAppearance" options:0 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 no release notes URL, just stick the contents of the description into the web view // Otherwise we'll wait until the client wants us to show release notes if (self.updateItem.releaseNotesURL == nil) { - [[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.releaseNotesView && [keyPath isEqualToString:@"effectiveAppearance"]) { + if (object == self.webView.view && [keyPath isEqualToString:@"effectiveAppearance"]) { [self adaptReleaseNotesAppearance]; } } @@ -261,7 +270,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 if (@available(macOS 10.14, *)) { if (self.observingAppearance) { - [self.releaseNotesView removeObserver:self forKeyPath:@"effectiveAppearance"]; + [self.webView.view removeObserver:self forKeyPath:@"effectiveAppearance"]; self.observingAppearance = NO; } } @@ -273,26 +282,21 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 if (@available(macOS 10.14, *)) { - WebPreferences *prefs = [self.releaseNotesView preferences]; - NSAppearanceName bestAppearance = [self.releaseNotesView.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; + NSAppearanceName bestAppearance = [self.webView.view.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; if ([bestAppearance isEqualToString:NSAppearanceNameDarkAqua]) { - // Set user stylesheet adapted to light on dark - prefs.userStyleSheetEnabled = YES; - prefs.userStyleSheetLocation = [[NSBundle bundleForClass:[self class]] URLForResource:@"DarkAqua" withExtension:@"css"]; - // Remove web view background... - self.releaseNotesView.drawsBackground = NO; + [self.webView setDrawsBackground:NO]; // ... and use NSBox to get the dynamically colored background if (self.darkBackgroundView == nil) { - self.darkBackgroundView = [[NSBox alloc] initWithFrame:self.releaseNotesView.frame]; + 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.releaseNotesView.superview addSubview:self.darkBackgroundView positioned:NSWindowBelow relativeTo:self.releaseNotesView]; + [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. @@ -304,8 +308,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE // Restore standard dark on light appearance [self.darkBackgroundView removeFromSuperview]; self.darkBackgroundView = nil; - prefs.userStyleSheetEnabled = NO; - self.releaseNotesView.drawsBackground = YES; + [self.webView setDrawsBackground:YES]; } } #endif @@ -313,21 +316,24 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData { - if (!self.webViewFinishedLoading) { - NSURL *baseURL = self.updateItem.releaseNotesURL.URLByDeletingLastPathComponent; - // If a MIME type isn't provided, we will pick html as the default, as opposed to plain text. Questionable decision.. - NSString *chosenMIMEType = (downloadData.MIMEType != nil) ? downloadData.MIMEType : @"text/html"; - // We'll pick utf-8 as the default text encoding name if one isn't provided which I think is reasonable - NSString *chosenTextEncodingName = (downloadData.textEncodingName != nil) ? downloadData.textEncodingName : @"utf-8"; - - [[self.releaseNotesView mainFrame] loadData:downloadData.data MIMEType:chosenMIMEType textEncodingName:chosenTextEncodingName baseURL:baseURL]; - } + NSURL *baseURL = self.updateItem.releaseNotesURL.URLByDeletingLastPathComponent; + // If a MIME type isn't provided, we will pick html as the default, as opposed to plain text. Questionable decision.. + NSString *chosenMIMEType = (downloadData.MIMEType != nil) ? downloadData.MIMEType : @"text/html"; + // We'll pick utf-8 as the default text encoding name if one isn't provided which I think is reasonable + NSString *chosenTextEncodingName = (downloadData.textEncodingName != nil) ? downloadData.textEncodingName : @"utf-8"; + + __weak __typeof__(self) weakSelf = self; + [self.webView loadData:downloadData.data MIMEType:chosenMIMEType textEncodingName:chosenTextEncodingName baseURL:baseURL completionHandler:^(NSError * _Nullable error) { + if (error != nil) { + SULog(SULogLevelError, @"Failed to load data from web view: %@", error); + } + [weakSelf stopReleaseNotesSpinner]; + }]; } - (void)showReleaseNotesFailedToDownload { [self stopReleaseNotesSpinner]; - self.webViewFinishedLoading = YES; } - (void)stopReleaseNotesSpinner @@ -353,6 +359,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" ]; @@ -466,71 +479,6 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE return finalString; } -- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame -{ - if ([frame parentFrame] == nil) { - [self stopReleaseNotesSpinner]; - self.webViewFinishedLoading = 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) { - [[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; +}