Add a command line default to force WebKitTestRunner to turn on process swap on navig...
[WebKit-https.git] / Tools / WebKitTestRunner / cocoa / TestControllerCocoa.mm
1 /*
2  * Copyright (C) 2015-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "TestController.h"
28
29 #import "CrashReporterInfo.h"
30 #import "PlatformWebView.h"
31 #import "StringFunctions.h"
32 #import "TestInvocation.h"
33 #import "TestRunnerWKWebView.h"
34 #import <Foundation/Foundation.h>
35 #import <WebKit/WKContextConfigurationRef.h>
36 #import <WebKit/WKCookieManager.h>
37 #import <WebKit/WKPreferencesRefPrivate.h>
38 #import <WebKit/WKProcessPoolPrivate.h>
39 #import <WebKit/WKStringCF.h>
40 #import <WebKit/WKUserContentControllerPrivate.h>
41 #import <WebKit/WKWebView.h>
42 #import <WebKit/WKWebViewConfiguration.h>
43 #import <WebKit/WKWebViewConfigurationPrivate.h>
44 #import <WebKit/WKWebViewPrivate.h>
45 #import <WebKit/WKWebsiteDataRecordPrivate.h>
46 #import <WebKit/WKWebsiteDataStorePrivate.h>
47 #import <WebKit/WKWebsiteDataStoreRef.h>
48 #import <WebKit/_WKApplicationManifest.h>
49 #import <WebKit/_WKUserContentExtensionStore.h>
50 #import <WebKit/_WKUserContentExtensionStorePrivate.h>
51 #import <wtf/MainThread.h>
52
53 namespace WTR {
54
55 static WKWebViewConfiguration *globalWebViewConfiguration;
56
57 void initializeWebViewConfiguration(const char* libraryPath, WKStringRef injectedBundlePath, WKContextRef context, WKContextConfigurationRef contextConfiguration)
58 {
59 #if WK_API_ENABLED
60     [globalWebViewConfiguration release];
61     globalWebViewConfiguration = [[WKWebViewConfiguration alloc] init];
62
63     globalWebViewConfiguration.processPool = (__bridge WKProcessPool *)context;
64     globalWebViewConfiguration.websiteDataStore = (__bridge WKWebsiteDataStore *)WKContextGetWebsiteDataStore(context);
65     globalWebViewConfiguration._allowUniversalAccessFromFileURLs = YES;
66     globalWebViewConfiguration._applePayEnabled = YES;
67
68 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || PLATFORM(IOS)
69     WKCookieManagerSetCookieStoragePartitioningEnabled(WKContextGetCookieManager(context), true);
70     WKCookieManagerSetStorageAccessAPIEnabled(WKContextGetCookieManager(context), true);
71 #endif
72
73     WKWebsiteDataStore* poolWebsiteDataStore = (__bridge WKWebsiteDataStore *)WKContextGetWebsiteDataStore((__bridge WKContextRef)globalWebViewConfiguration.processPool);
74     [poolWebsiteDataStore _setCacheStoragePerOriginQuota: 400 * 1024];
75     if (libraryPath) {
76         String cacheStorageDirectory = String(libraryPath) + '/' + "CacheStorage";
77         [poolWebsiteDataStore _setCacheStorageDirectory: cacheStorageDirectory];
78
79         String serviceWorkerRegistrationDirectory = String(libraryPath) + '/' + "ServiceWorkers";
80         [poolWebsiteDataStore _setServiceWorkerRegistrationDirectory: serviceWorkerRegistrationDirectory];
81     }
82
83     [globalWebViewConfiguration.websiteDataStore _setResourceLoadStatisticsEnabled:YES];
84     [globalWebViewConfiguration.websiteDataStore _resourceLoadStatisticsSetShouldSubmitTelemetry:NO];
85
86 #if PLATFORM(IOS)
87     globalWebViewConfiguration.allowsInlineMediaPlayback = YES;
88     globalWebViewConfiguration._inlineMediaPlaybackRequiresPlaysInlineAttribute = NO;
89     globalWebViewConfiguration._invisibleAutoplayNotPermitted = NO;
90     globalWebViewConfiguration._mediaDataLoadsAutomatically = YES;
91     globalWebViewConfiguration.requiresUserActionForMediaPlayback = NO;
92 #endif
93     globalWebViewConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
94 #endif
95 }
96
97 void TestController::cocoaPlatformInitialize()
98 {
99     const char* dumpRenderTreeTemp = libraryPathForTesting();
100     if (!dumpRenderTreeTemp)
101         return;
102
103     String resourceLoadStatisticsFolder = String(dumpRenderTreeTemp) + '/' + "ResourceLoadStatistics";
104     [[NSFileManager defaultManager] createDirectoryAtPath:resourceLoadStatisticsFolder withIntermediateDirectories:YES attributes:nil error: nil];
105     String fullBrowsingSessionResourceLog = resourceLoadStatisticsFolder + '/' + "full_browsing_session_resourceLog.plist";
106     NSDictionary *resourceLogPlist = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"version", nil];
107     if (![resourceLogPlist writeToFile:fullBrowsingSessionResourceLog atomically:YES])
108         WTFCrash();
109     [resourceLogPlist release];
110 }
111
112 WKContextRef TestController::platformContext()
113 {
114 #if WK_API_ENABLED
115     return (__bridge WKContextRef)globalWebViewConfiguration.processPool;
116 #else
117     return nullptr;
118 #endif
119 }
120
121 WKPreferencesRef TestController::platformPreferences()
122 {
123 #if WK_API_ENABLED
124     return (__bridge WKPreferencesRef)globalWebViewConfiguration.preferences;
125 #else
126     return nullptr;
127 #endif
128 }
129
130 void TestController::platformAddTestOptions(TestOptions& options) const
131 {
132     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"EnableProcessSwapOnNavigation"])
133         options.enableProcessSwapOnNavigation = true;
134     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"EnableProcessSwapOnWindowOpen"])
135         options.enableProcessSwapOnWindowOpen = true;
136 }
137
138 void TestController::platformCreateWebView(WKPageConfigurationRef, const TestOptions& options)
139 {
140 #if WK_API_ENABLED
141     RetainPtr<WKWebViewConfiguration> copiedConfiguration = adoptNS([globalWebViewConfiguration copy]);
142
143 #if PLATFORM(IOS)
144     if (options.useDataDetection)
145         [copiedConfiguration setDataDetectorTypes:WKDataDetectorTypeAll];
146     if (options.ignoresViewportScaleLimits)
147         [copiedConfiguration setIgnoresViewportScaleLimits:YES];
148     if (options.useCharacterSelectionGranularity)
149         [copiedConfiguration setSelectionGranularity:WKSelectionGranularityCharacter];
150     if (options.useCharacterSelectionGranularity)
151         [copiedConfiguration setSelectionGranularity:WKSelectionGranularityCharacter];
152 #endif
153
154     if (options.enableAttachmentElement)
155         [copiedConfiguration _setAttachmentElementEnabled: YES];
156
157     if (options.enableColorFilter)
158         [copiedConfiguration _setColorFilterEnabled: YES];
159
160     if (options.applicationManifest.length()) {
161         auto manifestPath = [NSString stringWithUTF8String:options.applicationManifest.c_str()];
162         NSString *text = [NSString stringWithContentsOfFile:manifestPath usedEncoding:nullptr error:nullptr];
163         [copiedConfiguration _setApplicationManifest:[_WKApplicationManifest applicationManifestFromJSON:text manifestURL:nil documentURL:nil]];
164     }
165
166     m_mainWebView = std::make_unique<PlatformWebView>(copiedConfiguration.get(), options);
167 #else
168     m_mainWebView = std::make_unique<PlatformWebView>(globalWebViewConfiguration, options);
169 #endif
170 }
171
172 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef, const TestOptions& options)
173 {
174 #if WK_API_ENABLED
175     WKWebViewConfiguration *newConfiguration = [[globalWebViewConfiguration copy] autorelease];
176     newConfiguration._relatedWebView = static_cast<WKWebView*>(parentView->platformView());
177     return new PlatformWebView(newConfiguration, options);
178 #else
179     return nullptr;
180 #endif
181 }
182
183 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
184 {
185 #if WK_API_ENABLED
186     initializeWebViewConfiguration(libraryPathForTesting(), injectedBundlePath(), context, contextConfiguration);
187     return (__bridge WKContextRef)globalWebViewConfiguration.processPool;
188 #else
189     return nullptr;
190 #endif
191 }
192
193 void TestController::platformRunUntil(bool& done, double timeout)
194 {
195     NSDate *endDate = (timeout > 0) ? [NSDate dateWithTimeIntervalSinceNow:timeout] : [NSDate distantFuture];
196
197     while (!done && [endDate compare:[NSDate date]] == NSOrderedDescending)
198         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:endDate];
199 }
200
201 void TestController::cocoaResetStateToConsistentValues()
202 {
203 #if WK_API_ENABLED
204     __block bool doneRemoving = false;
205     [[_WKUserContentExtensionStore defaultStore] removeContentExtensionForIdentifier:@"TestContentExtensions" completionHandler:^(NSError *error) {
206         doneRemoving = true;
207     }];
208     platformRunUntil(doneRemoving, noTimeout);
209     [[_WKUserContentExtensionStore defaultStore] _removeAllContentExtensions];
210
211     if (PlatformWebView* webView = mainWebView())
212         [webView->platformView().configuration.userContentController _removeAllUserContentFilters];
213 #endif
214 }
215
216 void TestController::platformWillRunTest(const TestInvocation& testInvocation)
217 {
218     setCrashReportApplicationSpecificInformationToURL(testInvocation.url());
219 }
220
221 static NSString * const WebArchivePboardType = @"Apple Web Archive pasteboard type";
222 static NSString * const WebSubresourcesKey = @"WebSubresources";
223 static NSString * const WebSubframeArchivesKey = @"WebResourceMIMEType like 'image*'";
224
225 unsigned TestController::imageCountInGeneralPasteboard() const
226 {
227 #if PLATFORM(MAC)
228     NSData *data = [[NSPasteboard generalPasteboard] dataForType:WebArchivePboardType];
229 #elif PLATFORM(IOS)
230     NSData *data = [[UIPasteboard generalPasteboard] valueForPasteboardType:WebArchivePboardType];
231 #endif
232     if (!data)
233         return 0;
234     
235     NSError *error = nil;
236     id webArchive = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:&error];
237     if (error) {
238         NSLog(@"Encountered error while serializing Web Archive pasteboard data: %@", error);
239         return 0;
240     }
241     
242     NSArray *subItems = [NSArray arrayWithArray:[webArchive objectForKey:WebSubresourcesKey]];
243     NSPredicate *predicate = [NSPredicate predicateWithFormat:WebSubframeArchivesKey];
244     NSArray *imagesArray = [subItems filteredArrayUsingPredicate:predicate];
245     
246     if (!imagesArray)
247         return 0;
248     
249     return imagesArray.count;
250 }
251
252 void TestController::removeAllSessionCredentials()
253 {
254 #if WK_API_ENABLED
255     auto types = adoptNS([[NSSet alloc] initWithObjects:_WKWebsiteDataTypeCredentials, nil]);
256     [globalWebViewConfiguration.websiteDataStore removeDataOfTypes:types.get() modifiedSince:[NSDate distantPast] completionHandler:^() {
257         m_currentInvocation->didRemoveAllSessionCredentials();
258     }];
259 #endif
260 }
261
262 void TestController::getAllStorageAccessEntries()
263 {
264 #if WK_API_ENABLED
265     [globalWebViewConfiguration.websiteDataStore _getAllStorageAccessEntries:^(NSArray<NSString *> *nsDomains) {
266         Vector<String> domains;
267         domains.reserveInitialCapacity(nsDomains.count);
268         for (NSString *domain : nsDomains)
269             domains.uncheckedAppend(domain);
270         m_currentInvocation->didReceiveAllStorageAccessEntries(domains);
271     }];
272 #endif
273 }
274
275 } // namespace WTR