5f1c220f481caa5662d70207ebcfa3d6aaebf455
[WebKit-https.git] / Tools / WebKitTestRunner / InjectedBundle / InjectedBundle.cpp
1 /*
2  * Copyright (C) 2010-2018 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 #include "config.h"
27 #include "InjectedBundle.h"
28
29 #include "ActivateFonts.h"
30 #include "InjectedBundlePage.h"
31 #include "StringFunctions.h"
32 #include "WebCoreTestSupport.h"
33 #include <JavaScriptCore/Options.h>
34 #include <WebKit/WKBundle.h>
35 #include <WebKit/WKBundlePage.h>
36 #include <WebKit/WKBundlePagePrivate.h>
37 #include <WebKit/WKBundlePrivate.h>
38 #include <WebKit/WKRetainPtr.h>
39 #include <WebKit/WebKit2_C.h>
40 #include <wtf/text/CString.h>
41 #include <wtf/text/StringBuilder.h>
42 #include <wtf/Vector.h>
43
44 namespace WTR {
45
46 static void handleTextDidChangeInTextField(WKBundlePageRef, WKBundleNodeHandleRef, WKBundleFrameRef, const void* context)
47 {
48     static_cast<InjectedBundle*>(const_cast<void*>(context))->textDidChangeInTextField();
49 }
50
51 static void handleTextFieldDidBeginEditing(WKBundlePageRef, WKBundleNodeHandleRef, WKBundleFrameRef, const void* context)
52 {
53     static_cast<InjectedBundle*>(const_cast<void*>(context))->textFieldDidBeginEditing();
54 }
55
56 static void handleTextFieldDidEndEditing(WKBundlePageRef, WKBundleNodeHandleRef, WKBundleFrameRef, const void* context)
57 {
58     static_cast<InjectedBundle*>(const_cast<void*>(context))->textFieldDidEndEditing();
59 }
60
61 InjectedBundle& InjectedBundle::singleton()
62 {
63     static InjectedBundle& shared = *new InjectedBundle;
64     return shared;
65 }
66
67 void InjectedBundle::didCreatePage(WKBundleRef bundle, WKBundlePageRef page, const void* clientInfo)
68 {
69     static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didCreatePage(page);
70 }
71
72 void InjectedBundle::willDestroyPage(WKBundleRef bundle, WKBundlePageRef page, const void* clientInfo)
73 {
74     static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->willDestroyPage(page);
75 }
76
77 void InjectedBundle::didInitializePageGroup(WKBundleRef bundle, WKBundlePageGroupRef pageGroup, const void* clientInfo)
78 {
79     static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didInitializePageGroup(pageGroup);
80 }
81
82 void InjectedBundle::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
83 {
84     static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didReceiveMessage(messageName, messageBody);
85 }
86
87 void InjectedBundle::didReceiveMessageToPage(WKBundleRef bundle, WKBundlePageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
88 {
89     static_cast<InjectedBundle*>(const_cast<void*>(clientInfo))->didReceiveMessageToPage(page, messageName, messageBody);
90 }
91
92 void InjectedBundle::initialize(WKBundleRef bundle, WKTypeRef initializationUserData)
93 {
94     m_bundle = bundle;
95
96     WKBundleClientV1 client = {
97         { 1, this },
98         didCreatePage,
99         willDestroyPage,
100         didInitializePageGroup,
101         didReceiveMessage,
102         didReceiveMessageToPage
103     };
104     WKBundleSetClient(m_bundle, &client.base);
105     WKBundleSetServiceWorkerProxyCreationCallback(m_bundle, WebCoreTestSupport::setupNewlyCreatedServiceWorker);
106     platformInitialize(initializationUserData);
107
108     activateFonts();
109 }
110
111 void InjectedBundle::didCreatePage(WKBundlePageRef page)
112 {
113     bool isMainPage = m_pages.isEmpty();
114     m_pages.append(std::make_unique<InjectedBundlePage>(page));
115
116     setUpInjectedBundleClients(page);
117
118     if (!isMainPage)
119         return;
120
121     WKRetainPtr<WKStringRef> messsageName(AdoptWK, WKStringCreateWithUTF8CString("Initialization"));
122     WKTypeRef result = 0;
123     WKBundlePostSynchronousMessage(m_bundle, messsageName.get(), 0, &result);
124     ASSERT(WKGetTypeID(result) == WKDictionaryGetTypeID());
125     WKDictionaryRef initializationDictionary = static_cast<WKDictionaryRef>(result);
126
127     WKRetainPtr<WKStringRef> resumeTestingKey(AdoptWK, WKStringCreateWithUTF8CString("ResumeTesting"));
128     WKTypeRef resumeTestingValue = WKDictionaryGetItemForKey(initializationDictionary, resumeTestingKey.get());
129     ASSERT(WKGetTypeID(resumeTestingValue) == WKBooleanGetTypeID());
130     if (WKBooleanGetValue(static_cast<WKBooleanRef>(resumeTestingValue)))
131         beginTesting(initializationDictionary, BegingTestingMode::Resume);
132 }
133
134 void InjectedBundle::willDestroyPage(WKBundlePageRef page)
135 {
136     m_pages.removeFirstMatching([page](auto& current) {
137         return current->page() == page;
138     });
139 }
140
141 void InjectedBundle::didInitializePageGroup(WKBundlePageGroupRef pageGroup)
142 {
143     m_pageGroup = pageGroup;
144 }
145
146 void InjectedBundle::setUpInjectedBundleClients(WKBundlePageRef page)
147 {
148     WKBundlePageFormClientV2 formClient = {
149         { 2, this },
150         handleTextFieldDidBeginEditing,
151         handleTextFieldDidEndEditing,
152         handleTextDidChangeInTextField,
153         0, // textDidChangeInTextArea
154         0, // shouldPerformActionInTextField
155         0, // willSubmitForm
156         0, // willSendSubmitEvent
157         0, // didFocusTextField
158         0, // shouldNotifyOnFormChanges
159         0, // didAssociateFormControls
160     };
161     WKBundlePageSetFormClient(page, &formClient.base);
162 }
163
164 InjectedBundlePage* InjectedBundle::page() const
165 {
166     // It might be better to have the UI process send over a reference to the main
167     // page instead of just assuming it's the first one.
168     return m_pages[0].get();
169 }
170
171 void InjectedBundle::resetLocalSettings()
172 {
173     setlocale(LC_ALL, "");
174 }
175
176 void InjectedBundle::didReceiveMessage(WKStringRef messageName, WKTypeRef messageBody)
177 {
178     WKRetainPtr<WKStringRef> errorMessageName(AdoptWK, WKStringCreateWithUTF8CString("Error"));
179     WKRetainPtr<WKStringRef> errorMessageBody(AdoptWK, WKStringCreateWithUTF8CString("Unknown"));
180     WKBundlePostMessage(m_bundle, errorMessageName.get(), errorMessageBody.get());
181 }
182
183 static void postGCTask(void* context)
184 {
185     WKBundlePageRef page = reinterpret_cast<WKBundlePageRef>(context);
186     InjectedBundle::singleton().reportLiveDocuments(page);
187     WKRelease(page);
188 }
189
190 void InjectedBundle::reportLiveDocuments(WKBundlePageRef page)
191 {
192     // Release memory again, after the GC and timer fire. This is necessary to clear entries from CachedResourceLoader's m_documentResources in some scenarios.
193     WKBundleReleaseMemory(m_bundle);
194
195     const bool excludeDocumentsInPageGroup = true;
196     auto documentURLs = adoptWK(WKBundleGetLiveDocumentURLs(m_bundle, m_pageGroup, excludeDocumentsInPageGroup));
197     auto ackMessageName = adoptWK(WKStringCreateWithUTF8CString("LiveDocuments"));
198     WKBundlePagePostMessage(page, ackMessageName.get(), documentURLs.get());
199 }
200
201 void InjectedBundle::didReceiveMessageToPage(WKBundlePageRef page, WKStringRef messageName, WKTypeRef messageBody)
202 {
203     if (WKStringIsEqualToUTF8CString(messageName, "BeginTest")) {
204         ASSERT(messageBody);
205         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
206         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
207
208         WKRetainPtr<WKStringRef> dumpPixelsKey(AdoptWK, WKStringCreateWithUTF8CString("DumpPixels"));
209         m_dumpPixels = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, dumpPixelsKey.get())));
210
211         WKRetainPtr<WKStringRef> useWaitToDumpWatchdogTimerKey(AdoptWK, WKStringCreateWithUTF8CString("UseWaitToDumpWatchdogTimer"));
212         m_useWaitToDumpWatchdogTimer = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, useWaitToDumpWatchdogTimerKey.get())));
213
214         WKRetainPtr<WKStringRef> timeoutKey(AdoptWK, WKStringCreateWithUTF8CString("Timeout"));
215         m_timeout = Seconds::fromMilliseconds(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeoutKey.get()))));
216
217         WKRetainPtr<WKStringRef> dumpJSConsoleLogInStdErrKey(AdoptWK, WKStringCreateWithUTF8CString("DumpJSConsoleLogInStdErr"));
218         m_dumpJSConsoleLogInStdErr = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, dumpJSConsoleLogInStdErrKey.get())));
219
220         WKRetainPtr<WKStringRef> ackMessageName(AdoptWK, WKStringCreateWithUTF8CString("Ack"));
221         WKRetainPtr<WKStringRef> ackMessageBody(AdoptWK, WKStringCreateWithUTF8CString("BeginTest"));
222         WKBundlePagePostMessage(page, ackMessageName.get(), ackMessageBody.get());
223
224         beginTesting(messageBodyDictionary, BegingTestingMode::New);
225         return;
226     }
227
228     if (WKStringIsEqualToUTF8CString(messageName, "Reset")) {
229         ASSERT(messageBody);
230         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
231         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
232         WKRetainPtr<WKStringRef> jscOptionsKey(AdoptWK, WKStringCreateWithUTF8CString("JSCOptions"));
233         WKRetainPtr<WKStringRef> jscOptionsString = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, jscOptionsKey.get()));
234         if (jscOptionsString) {
235             String options = toWTFString(jscOptionsString);
236             JSC::Options::setOptions(options.utf8().data());
237         }
238
239         WKRetainPtr<WKStringRef> shouldGCKey(AdoptWK, WKStringCreateWithUTF8CString("ShouldGC"));
240         bool shouldGC = WKBooleanGetValue(static_cast<WKBooleanRef>(WKDictionaryGetItemForKey(messageBodyDictionary, shouldGCKey.get())));
241         if (shouldGC)
242             WKBundleGarbageCollectJavaScriptObjects(m_bundle);
243
244         WKRetainPtr<WKStringRef> allowedHostsKey(AdoptWK, WKStringCreateWithUTF8CString("AllowedHosts"));
245         WKTypeRef allowedHostsValue = WKDictionaryGetItemForKey(messageBodyDictionary, allowedHostsKey.get());
246         if (allowedHostsValue && WKGetTypeID(allowedHostsValue) == WKArrayGetTypeID()) {
247             m_allowedHosts.clear();
248
249             WKArrayRef allowedHostsArray = static_cast<WKArrayRef>(allowedHostsValue);
250             for (size_t i = 0, size = WKArrayGetSize(allowedHostsArray); i < size; ++i) {
251                 WKTypeRef item = WKArrayGetItemAtIndex(allowedHostsArray, i);
252                 if (item && WKGetTypeID(item) == WKStringGetTypeID())
253                     m_allowedHosts.append(toWTFString(static_cast<WKStringRef>(item)));
254             }
255         }
256
257         m_state = Idle;
258         m_dumpPixels = false;
259         m_pixelResultIsPending = false;
260
261         resetLocalSettings();
262         TestRunner::removeAllWebNotificationPermissions();
263
264         InjectedBundle::page()->resetAfterTest();
265         return;
266     }
267
268     if (WKStringIsEqualToUTF8CString(messageName, "GetLiveDocuments")) {
269         const bool excludeDocumentsInPageGroup = false;
270         auto documentURLs = adoptWK(WKBundleGetLiveDocumentURLs(m_bundle, m_pageGroup, excludeDocumentsInPageGroup));
271         auto ackMessageName = adoptWK(WKStringCreateWithUTF8CString("LiveDocuments"));
272         WKBundlePagePostMessage(page, ackMessageName.get(), documentURLs.get());
273         return;
274     }
275
276     if (WKStringIsEqualToUTF8CString(messageName, "CheckForWorldLeaks")) {
277         WKBundleReleaseMemory(m_bundle);
278
279         WKRetain(page); // Balanced by the release in postGCTask.
280         WKBundlePageCallAfterTasksAndTimers(page, postGCTask, (void*)page);
281         return;
282     }
283
284     if (WKStringIsEqualToUTF8CString(messageName, "CallAddChromeInputFieldCallback")) {
285         m_testRunner->callAddChromeInputFieldCallback();
286         return;
287     }
288
289     if (WKStringIsEqualToUTF8CString(messageName, "CallRemoveChromeInputFieldCallback")) {
290         m_testRunner->callRemoveChromeInputFieldCallback();
291         return;
292     }
293
294     if (WKStringIsEqualToUTF8CString(messageName, "CallFocusWebViewCallback")) {
295         m_testRunner->callFocusWebViewCallback();
296         return;
297     }
298
299     if (WKStringIsEqualToUTF8CString(messageName, "CallSetBackingScaleFactorCallback")) {
300         m_testRunner->callSetBackingScaleFactorCallback();
301         return;
302     }
303
304     if (WKStringIsEqualToUTF8CString(messageName, "CallDidBeginSwipeCallback")) {
305         m_testRunner->callDidBeginSwipeCallback();
306         return;
307     }
308
309     if (WKStringIsEqualToUTF8CString(messageName, "CallWillEndSwipeCallback")) {
310         m_testRunner->callWillEndSwipeCallback();
311         return;
312     }
313
314     if (WKStringIsEqualToUTF8CString(messageName, "CallDidEndSwipeCallback")) {
315         m_testRunner->callDidEndSwipeCallback();
316         return;
317     }
318
319     if (WKStringIsEqualToUTF8CString(messageName, "CallDidRemoveSwipeSnapshotCallback")) {
320         m_testRunner->callDidRemoveSwipeSnapshotCallback();
321         return;
322     }
323
324     if (WKStringIsEqualToUTF8CString(messageName, "CallDidClearStatisticsThroughWebsiteDataRemoval")) {
325         m_testRunner->statisticsCallClearThroughWebsiteDataRemovalCallback();
326         return;
327     }
328
329     if (WKStringIsEqualToUTF8CString(messageName, "CallDidResetStatisticsToConsistentState")) {
330         m_testRunner->statisticsCallDidResetToConsistentStateCallback();
331         return;
332     }
333     
334     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetBlockCookiesForHost")) {
335         m_testRunner->statisticsCallDidSetBlockCookiesForHostCallback();
336         return;
337     }
338
339     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetStatisticsDebugMode")) {
340         m_testRunner->statisticsCallDidSetDebugModeCallback();
341         return;
342     }
343     
344     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetPrevalentResourceForDebugMode")) {
345         m_testRunner->statisticsCallDidSetPrevalentResourceForDebugModeCallback();
346         return;
347     }
348     
349     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetLastSeen")) {
350         m_testRunner->statisticsCallDidSetLastSeenCallback();
351         return;
352     }
353
354     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetPrevalentResource")) {
355         m_testRunner->statisticsCallDidSetPrevalentResourceCallback();
356         return;
357     }
358
359     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetVeryPrevalentResource")) {
360         m_testRunner->statisticsCallDidSetVeryPrevalentResourceCallback();
361         return;
362     }
363
364     if (WKStringIsEqualToUTF8CString(messageName, "CallDidSetHasHadUserInteraction")) {
365         m_testRunner->statisticsCallDidSetHasHadUserInteractionCallback();
366         return;
367     }
368     
369     if (WKStringIsEqualToUTF8CString(messageName, "CallDidReceiveAllStorageAccessEntries")) {
370         ASSERT(messageBody);
371         ASSERT(WKGetTypeID(messageBody) == WKArrayGetTypeID());
372
373         WKArrayRef domainsArray = static_cast<WKArrayRef>(messageBody);
374         auto size = WKArrayGetSize(domainsArray);
375         Vector<String> domains;
376         domains.reserveInitialCapacity(size);
377         for (size_t i = 0; i < size; ++i) {
378             WKTypeRef item = WKArrayGetItemAtIndex(domainsArray, i);
379             if (item && WKGetTypeID(item) == WKStringGetTypeID())
380                 domains.append(toWTFString(static_cast<WKStringRef>(item)));
381         }
382
383         m_testRunner->callDidReceiveAllStorageAccessEntriesCallback(domains);
384         return;
385     }
386
387     if (WKStringIsEqualToUTF8CString(messageName, "CallDidRemoveAllSessionCredentialsCallback")) {
388         m_testRunner->callDidRemoveAllSessionCredentialsCallback();
389         return;
390     }
391
392     if (WKStringIsEqualToUTF8CString(messageName, "NotifyDownloadDone")) {
393         if (m_testRunner->shouldFinishAfterDownload())
394             m_testRunner->notifyDone();
395         return;
396     }
397
398     if (WKStringIsEqualToUTF8CString(messageName, "CallUISideScriptCallback")) {
399         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
400
401         WKRetainPtr<WKStringRef> resultKey(AdoptWK, WKStringCreateWithUTF8CString("Result"));
402         WKRetainPtr<WKStringRef> callbackIDKey(AdoptWK, WKStringCreateWithUTF8CString("CallbackID"));
403
404         unsigned callbackID = (unsigned)WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, callbackIDKey.get())));
405
406         WKStringRef resultString = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, resultKey.get()));
407         auto resultJSString = toJS(resultString);
408
409         m_testRunner->runUIScriptCallback(callbackID, resultJSString.get());
410         return;
411     }
412
413     if (WKStringIsEqualToUTF8CString(messageName, "WorkQueueProcessedCallback")) {
414         if (!topLoadingFrame() && !m_testRunner->shouldWaitUntilDone())
415             InjectedBundle::page()->dump();
416         return;
417     }
418
419     if (WKStringIsEqualToUTF8CString(messageName, "WebsiteDataDeletionForTopPrivatelyOwnedDomainsFinished")) {
420         m_testRunner->statisticsDidModifyDataRecordsCallback();
421         return;
422     }
423
424     if (WKStringIsEqualToUTF8CString(messageName, "WebsiteDataScanForTopPrivatelyControlledDomainsFinished")) {
425         m_testRunner->statisticsDidScanDataRecordsCallback();
426         return;
427     }
428
429     if (WKStringIsEqualToUTF8CString(messageName, "ResourceLoadStatisticsTelemetryFinished")) {
430         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
431         
432         unsigned totalPrevalentResources = (unsigned)WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, WKStringCreateWithUTF8CString("TotalPrevalentResources"))));
433         unsigned totalPrevalentResourcesWithUserInteraction = (unsigned)WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, WKStringCreateWithUTF8CString("TotalPrevalentResourcesWithUserInteraction"))));
434         unsigned top3SubframeUnderTopFrameOrigins = (unsigned)WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, WKStringCreateWithUTF8CString("Top3SubframeUnderTopFrameOrigins"))));
435         
436         m_testRunner->statisticsDidRunTelemetryCallback(totalPrevalentResources, totalPrevalentResourcesWithUserInteraction, top3SubframeUnderTopFrameOrigins);
437         return;
438     }
439     
440     if (WKStringIsEqualToUTF8CString(messageName, "DidGetApplicationManifest")) {
441         m_testRunner->didGetApplicationManifest();
442         return;
443     }
444     
445     WKRetainPtr<WKStringRef> errorMessageName(AdoptWK, WKStringCreateWithUTF8CString("Error"));
446     WKRetainPtr<WKStringRef> errorMessageBody(AdoptWK, WKStringCreateWithUTF8CString("Unknown"));
447     WKBundlePagePostMessage(page, errorMessageName.get(), errorMessageBody.get());
448 }
449
450 bool InjectedBundle::booleanForKey(WKDictionaryRef dictionary, const char* key)
451 {
452     WKRetainPtr<WKStringRef> wkKey(AdoptWK, WKStringCreateWithUTF8CString(key));
453     WKTypeRef value = WKDictionaryGetItemForKey(dictionary, wkKey.get());
454     if (WKGetTypeID(value) != WKBooleanGetTypeID()) {
455         outputText(makeString("Boolean value for key", key, " not found in dictionary\n"));
456         return false;
457     }
458     return WKBooleanGetValue(static_cast<WKBooleanRef>(value));
459 }
460
461 void InjectedBundle::beginTesting(WKDictionaryRef settings, BegingTestingMode testingMode)
462 {
463     m_state = Testing;
464
465     m_pixelResult.clear();
466     m_repaintRects.clear();
467
468     m_testRunner = TestRunner::create();
469     m_gcController = GCController::create();
470     m_eventSendingController = EventSendingController::create();
471     m_textInputController = TextInputController::create();
472 #if HAVE(ACCESSIBILITY)
473     m_accessibilityController = AccessibilityController::create();
474 #endif
475
476     WKBundleSetAllowUniversalAccessFromFileURLs(m_bundle, m_pageGroup, true);
477     WKBundleSetJavaScriptCanAccessClipboard(m_bundle, m_pageGroup, true);
478     WKBundleSetPrivateBrowsingEnabled(m_bundle, m_pageGroup, false);
479     WKBundleSetUseDashboardCompatibilityMode(m_bundle, m_pageGroup, false);
480     WKBundleSetAuthorAndUserStylesEnabled(m_bundle, m_pageGroup, true);
481     WKBundleSetFrameFlatteningEnabled(m_bundle, m_pageGroup, false);
482     WKBundleSetAsyncFrameScrollingEnabled(m_bundle, m_pageGroup, false);
483     WKBundleSetMinimumLogicalFontSize(m_bundle, m_pageGroup, 9);
484     WKBundleSetSpatialNavigationEnabled(m_bundle, m_pageGroup, false);
485     WKBundleSetAllowFileAccessFromFileURLs(m_bundle, m_pageGroup, true);
486     WKBundleSetPopupBlockingEnabled(m_bundle, m_pageGroup, false);
487     WKBundleSetAllowStorageAccessFromFileURLS(m_bundle, m_pageGroup, false);
488
489 #if PLATFORM(IOS)
490     WKBundlePageSetUseTestingViewportConfiguration(page()->page(), !booleanForKey(settings, "UseFlexibleViewport"));
491 #endif
492
493     m_testRunner->setPluginsEnabled(true);
494
495     m_testRunner->setUserStyleSheetEnabled(false);
496     m_testRunner->setXSSAuditorEnabled(false);
497
498     m_testRunner->setWebGL2Enabled(true);
499     m_testRunner->setWebGPUEnabled(true);
500
501     m_testRunner->setWritableStreamAPIEnabled(true);
502     m_testRunner->setReadableByteStreamAPIEnabled(true);
503
504     m_testRunner->setEncryptedMediaAPIEnabled(true);
505
506     m_testRunner->setCloseRemainingWindowsWhenComplete(false);
507     m_testRunner->setAcceptsEditing(true);
508     m_testRunner->setTabKeyCyclesThroughElements(true);
509     m_testRunner->clearTestRunnerCallbacks();
510
511     if (m_timeout > 0_s)
512         m_testRunner->setCustomTimeout(m_timeout);
513
514     page()->prepare();
515
516     if (testingMode != BegingTestingMode::New)
517         return;
518
519     WKBundleClearAllDatabases(m_bundle);
520     WKBundlePageClearApplicationCache(page()->page());
521     WKBundleResetOriginAccessWhitelists(m_bundle);
522     WKBundleClearResourceLoadStatistics(m_bundle);
523
524     // [WK2] REGRESSION(r128623): It made layout tests extremely slow
525     // https://bugs.webkit.org/show_bug.cgi?id=96862
526     // WKBundleSetDatabaseQuota(m_bundle, 5 * 1024 * 1024);
527 }
528
529 void InjectedBundle::done()
530 {
531     m_state = Stopping;
532
533     m_useWorkQueue = false;
534
535     page()->stopLoading();
536     setTopLoadingFrame(0);
537
538     m_testRunner->invalidateWaitToDumpWatchdogTimer();
539
540 #if HAVE(ACCESSIBILITY)
541     m_accessibilityController->resetToConsistentState();
542 #endif
543
544     WKRetainPtr<WKStringRef> doneMessageName(AdoptWK, WKStringCreateWithUTF8CString("Done"));
545     WKRetainPtr<WKMutableDictionaryRef> doneMessageBody(AdoptWK, WKMutableDictionaryCreate());
546
547     WKRetainPtr<WKStringRef> pixelResultIsPendingKey = adoptWK(WKStringCreateWithUTF8CString("PixelResultIsPending"));
548     WKRetainPtr<WKBooleanRef> pixelResultIsPending(AdoptWK, WKBooleanCreate(m_pixelResultIsPending));
549     WKDictionarySetItem(doneMessageBody.get(), pixelResultIsPendingKey.get(), pixelResultIsPending.get());
550
551     if (!m_pixelResultIsPending) {
552         WKRetainPtr<WKStringRef> pixelResultKey = adoptWK(WKStringCreateWithUTF8CString("PixelResult"));
553         WKDictionarySetItem(doneMessageBody.get(), pixelResultKey.get(), m_pixelResult.get());
554     }
555
556     WKRetainPtr<WKStringRef> repaintRectsKey = adoptWK(WKStringCreateWithUTF8CString("RepaintRects"));
557     WKDictionarySetItem(doneMessageBody.get(), repaintRectsKey.get(), m_repaintRects.get());
558
559     WKRetainPtr<WKStringRef> audioResultKey = adoptWK(WKStringCreateWithUTF8CString("AudioResult"));
560     WKDictionarySetItem(doneMessageBody.get(), audioResultKey.get(), m_audioResult.get());
561
562     WKBundlePagePostMessage(page()->page(), doneMessageName.get(), doneMessageBody.get());
563
564     closeOtherPages();
565
566     m_state = Idle;
567 }
568
569 void InjectedBundle::closeOtherPages()
570 {
571     Vector<WKBundlePageRef> pagesToClose;
572     size_t size = m_pages.size();
573     for (size_t i = 1; i < size; ++i)
574         pagesToClose.append(m_pages[i]->page());
575     size = pagesToClose.size();
576     for (size_t i = 0; i < size; ++i)
577         WKBundlePageClose(pagesToClose[i]);
578 }
579
580 void InjectedBundle::dumpBackForwardListsForAllPages(StringBuilder& stringBuilder)
581 {
582     size_t size = m_pages.size();
583     for (size_t i = 0; i < size; ++i)
584         m_pages[i]->dumpBackForwardList(stringBuilder);
585 }
586
587 void InjectedBundle::dumpToStdErr(const String& output)
588 {
589     if (m_state != Testing)
590         return;
591     if (output.isEmpty())
592         return;
593     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DumpToStdErr"));
594     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithUTF8CString(output.utf8().data()));
595     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
596 }
597
598 void InjectedBundle::outputText(const String& output)
599 {
600     if (m_state != Testing)
601         return;
602     if (output.isEmpty())
603         return;
604     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("TextOutput"));
605     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithUTF8CString(output.utf8().data()));
606     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
607 }
608
609 void InjectedBundle::postNewBeforeUnloadReturnValue(bool value)
610 {
611     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("BeforeUnloadReturnValue"));
612     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
613     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
614 }
615
616 void InjectedBundle::postAddChromeInputField()
617 {
618     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("AddChromeInputField"));
619     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
620 }
621
622 void InjectedBundle::postRemoveChromeInputField()
623 {
624     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RemoveChromeInputField"));
625     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
626 }
627
628 void InjectedBundle::postFocusWebView()
629 {
630     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("FocusWebView"));
631     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
632 }
633
634 void InjectedBundle::postSetBackingScaleFactor(double backingScaleFactor)
635 {
636     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBackingScaleFactor"));
637     WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(backingScaleFactor));
638     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
639 }
640
641 void InjectedBundle::postSetWindowIsKey(bool isKey)
642 {
643     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetWindowIsKey"));
644     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(isKey));
645     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), messageBody.get(), 0);
646 }
647
648 void InjectedBundle::postSetViewSize(double width, double height)
649 {
650     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetViewSize"));
651
652     WKRetainPtr<WKStringRef> widthKey(AdoptWK, WKStringCreateWithUTF8CString("width"));
653     WKRetainPtr<WKStringRef> heightKey(AdoptWK, WKStringCreateWithUTF8CString("height"));
654
655     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
656
657     WKRetainPtr<WKDoubleRef> widthWK(AdoptWK, WKDoubleCreate(width));
658     WKDictionarySetItem(messageBody.get(), widthKey.get(), widthWK.get());
659
660     WKRetainPtr<WKDoubleRef> heightWK(AdoptWK, WKDoubleCreate(height));
661     WKDictionarySetItem(messageBody.get(), heightKey.get(), heightWK.get());
662
663     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), messageBody.get(), 0);
664 }
665
666 void InjectedBundle::postSimulateWebNotificationClick(uint64_t notificationID)
667 {
668     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SimulateWebNotificationClick"));
669     WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(notificationID));
670     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
671 }
672
673 void InjectedBundle::postSetAddsVisitedLinks(bool addsVisitedLinks)
674 {
675     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAddsVisitedLinks"));
676     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(addsVisitedLinks));
677     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
678 }
679
680 void InjectedBundle::setGeolocationPermission(bool enabled)
681 {
682     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetGeolocationPermission"));
683     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(enabled));
684     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
685 }
686
687 void InjectedBundle::setMockGeolocationPosition(double latitude, double longitude, double accuracy, bool providesAltitude, double altitude, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed, bool providesFloorLevel, double floorLevel)
688 {
689     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGeolocationPosition"));
690
691     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
692
693     WKRetainPtr<WKStringRef> latitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("latitude"));
694     WKRetainPtr<WKDoubleRef> latitudeWK(AdoptWK, WKDoubleCreate(latitude));
695     WKDictionarySetItem(messageBody.get(), latitudeKeyWK.get(), latitudeWK.get());
696
697     WKRetainPtr<WKStringRef> longitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("longitude"));
698     WKRetainPtr<WKDoubleRef> longitudeWK(AdoptWK, WKDoubleCreate(longitude));
699     WKDictionarySetItem(messageBody.get(), longitudeKeyWK.get(), longitudeWK.get());
700
701     WKRetainPtr<WKStringRef> accuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("accuracy"));
702     WKRetainPtr<WKDoubleRef> accuracyWK(AdoptWK, WKDoubleCreate(accuracy));
703     WKDictionarySetItem(messageBody.get(), accuracyKeyWK.get(), accuracyWK.get());
704
705     WKRetainPtr<WKStringRef> providesAltitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesAltitude"));
706     WKRetainPtr<WKBooleanRef> providesAltitudeWK(AdoptWK, WKBooleanCreate(providesAltitude));
707     WKDictionarySetItem(messageBody.get(), providesAltitudeKeyWK.get(), providesAltitudeWK.get());
708
709     WKRetainPtr<WKStringRef> altitudeKeyWK(AdoptWK, WKStringCreateWithUTF8CString("altitude"));
710     WKRetainPtr<WKDoubleRef> altitudeWK(AdoptWK, WKDoubleCreate(altitude));
711     WKDictionarySetItem(messageBody.get(), altitudeKeyWK.get(), altitudeWK.get());
712
713     WKRetainPtr<WKStringRef> providesAltitudeAccuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesAltitudeAccuracy"));
714     WKRetainPtr<WKBooleanRef> providesAltitudeAccuracyWK(AdoptWK, WKBooleanCreate(providesAltitudeAccuracy));
715     WKDictionarySetItem(messageBody.get(), providesAltitudeAccuracyKeyWK.get(), providesAltitudeAccuracyWK.get());
716
717     WKRetainPtr<WKStringRef> altitudeAccuracyKeyWK(AdoptWK, WKStringCreateWithUTF8CString("altitudeAccuracy"));
718     WKRetainPtr<WKDoubleRef> altitudeAccuracyWK(AdoptWK, WKDoubleCreate(altitudeAccuracy));
719     WKDictionarySetItem(messageBody.get(), altitudeAccuracyKeyWK.get(), altitudeAccuracyWK.get());
720
721     WKRetainPtr<WKStringRef> providesHeadingKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesHeading"));
722     WKRetainPtr<WKBooleanRef> providesHeadingWK(AdoptWK, WKBooleanCreate(providesHeading));
723     WKDictionarySetItem(messageBody.get(), providesHeadingKeyWK.get(), providesHeadingWK.get());
724
725     WKRetainPtr<WKStringRef> headingKeyWK(AdoptWK, WKStringCreateWithUTF8CString("heading"));
726     WKRetainPtr<WKDoubleRef> headingWK(AdoptWK, WKDoubleCreate(heading));
727     WKDictionarySetItem(messageBody.get(), headingKeyWK.get(), headingWK.get());
728
729     WKRetainPtr<WKStringRef> providesSpeedKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesSpeed"));
730     WKRetainPtr<WKBooleanRef> providesSpeedWK(AdoptWK, WKBooleanCreate(providesSpeed));
731     WKDictionarySetItem(messageBody.get(), providesSpeedKeyWK.get(), providesSpeedWK.get());
732
733     WKRetainPtr<WKStringRef> speedKeyWK(AdoptWK, WKStringCreateWithUTF8CString("speed"));
734     WKRetainPtr<WKDoubleRef> speedWK(AdoptWK, WKDoubleCreate(speed));
735     WKDictionarySetItem(messageBody.get(), speedKeyWK.get(), speedWK.get());
736
737     WKRetainPtr<WKStringRef> providesFloorLevelKeyWK(AdoptWK, WKStringCreateWithUTF8CString("providesFloorLevel"));
738     WKRetainPtr<WKBooleanRef> providesFloorLevelWK(AdoptWK, WKBooleanCreate(providesFloorLevel));
739     WKDictionarySetItem(messageBody.get(), providesFloorLevelKeyWK.get(), providesFloorLevelWK.get());
740
741     WKRetainPtr<WKStringRef> floorLevelKeyWK(AdoptWK, WKStringCreateWithUTF8CString("floorLevel"));
742     WKRetainPtr<WKDoubleRef> floorLevelWK(AdoptWK, WKDoubleCreate(floorLevel));
743     WKDictionarySetItem(messageBody.get(), floorLevelKeyWK.get(), floorLevelWK.get());
744
745     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
746 }
747
748 void InjectedBundle::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
749 {
750     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGeolocationPositionUnavailableError"));
751     WKBundlePagePostMessage(page()->page(), messageName.get(), errorMessage);
752 }
753
754 bool InjectedBundle::isGeolocationProviderActive() const
755 {
756     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsGeolocationClientActive"));
757     WKTypeRef resultToPass = 0;
758     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), 0, &resultToPass);
759     WKRetainPtr<WKBooleanRef> isActive(AdoptWK, static_cast<WKBooleanRef>(resultToPass));
760
761     return WKBooleanGetValue(isActive.get());
762 }
763
764 unsigned InjectedBundle::imageCountInGeneralPasteboard() const
765 {
766     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ImageCountInGeneralPasteboard"));
767     WKTypeRef resultToPass = 0;
768     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), 0, &resultToPass);
769     WKRetainPtr<WKUInt64Ref> imageCount(AdoptWK, static_cast<WKUInt64Ref>(resultToPass));
770     
771     return static_cast<unsigned>(WKUInt64GetValue(imageCount.get()));
772 }
773
774 void InjectedBundle::setUserMediaPermission(bool enabled)
775 {
776     auto messageName = adoptWK(WKStringCreateWithUTF8CString("SetUserMediaPermission"));
777     auto messageBody = adoptWK(WKBooleanCreate(enabled));
778     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
779 }
780
781 void InjectedBundle::resetUserMediaPermission()
782 {
783     auto messageName = adoptWK(WKStringCreateWithUTF8CString("ResetUserMediaPermission"));
784     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
785 }
786
787 void InjectedBundle::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef origin, WKStringRef parentOrigin)
788 {
789     auto messageName = adoptWK(WKStringCreateWithUTF8CString("SetUserMediaPersistentPermissionForOrigin"));
790     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
791
792     WKRetainPtr<WKStringRef> permissionKeyWK(AdoptWK, WKStringCreateWithUTF8CString("permission"));
793     WKRetainPtr<WKBooleanRef> permissionWK(AdoptWK, WKBooleanCreate(permission));
794     WKDictionarySetItem(messageBody.get(), permissionKeyWK.get(), permissionWK.get());
795
796     WKRetainPtr<WKStringRef> originKeyWK(AdoptWK, WKStringCreateWithUTF8CString("origin"));
797     WKDictionarySetItem(messageBody.get(), originKeyWK.get(), origin);
798
799     WKRetainPtr<WKStringRef> parentOriginKeyWK(AdoptWK, WKStringCreateWithUTF8CString("parentOrigin"));
800     WKDictionarySetItem(messageBody.get(), parentOriginKeyWK.get(), parentOrigin);
801
802     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
803 }
804
805 unsigned InjectedBundle::userMediaPermissionRequestCountForOrigin(WKStringRef origin, WKStringRef parentOrigin) const
806 {
807     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("UserMediaPermissionRequestCountForOrigin"));
808     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
809
810     WKRetainPtr<WKStringRef> originKeyWK(AdoptWK, WKStringCreateWithUTF8CString("origin"));
811     WKDictionarySetItem(messageBody.get(), originKeyWK.get(), origin);
812
813     WKRetainPtr<WKStringRef> parentOriginKeyWK(AdoptWK, WKStringCreateWithUTF8CString("parentOrigin"));
814     WKDictionarySetItem(messageBody.get(), parentOriginKeyWK.get(), parentOrigin);
815
816     WKTypeRef resultToPass = 0;
817     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), messageBody.get(), &resultToPass);
818     WKRetainPtr<WKUInt64Ref> count(AdoptWK, static_cast<WKUInt64Ref>(resultToPass));
819
820     return static_cast<unsigned>(WKUInt64GetValue(count.get()));
821 }
822
823 void InjectedBundle::resetUserMediaPermissionRequestCountForOrigin(WKStringRef origin, WKStringRef parentOrigin)
824 {
825     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ResetUserMediaPermissionRequestCountForOrigin"));
826     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
827
828     WKRetainPtr<WKStringRef> originKeyWK(AdoptWK, WKStringCreateWithUTF8CString("origin"));
829     WKDictionarySetItem(messageBody.get(), originKeyWK.get(), origin);
830
831     WKRetainPtr<WKStringRef> parentOriginKeyWK(AdoptWK, WKStringCreateWithUTF8CString("parentOrigin"));
832     WKDictionarySetItem(messageBody.get(), parentOriginKeyWK.get(), parentOrigin);
833
834     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
835 }
836
837 void InjectedBundle::setCustomPolicyDelegate(bool enabled, bool permissive)
838 {
839     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetCustomPolicyDelegate"));
840
841     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
842
843     WKRetainPtr<WKStringRef> enabledKeyWK(AdoptWK, WKStringCreateWithUTF8CString("enabled"));
844     WKRetainPtr<WKBooleanRef> enabledWK(AdoptWK, WKBooleanCreate(enabled));
845     WKDictionarySetItem(messageBody.get(), enabledKeyWK.get(), enabledWK.get());
846
847     WKRetainPtr<WKStringRef> permissiveKeyWK(AdoptWK, WKStringCreateWithUTF8CString("permissive"));
848     WKRetainPtr<WKBooleanRef> permissiveWK(AdoptWK, WKBooleanCreate(permissive));
849     WKDictionarySetItem(messageBody.get(), permissiveKeyWK.get(), permissiveWK.get());
850
851     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
852 }
853
854 void InjectedBundle::setHidden(bool hidden)
855 {
856     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetHidden"));
857     WKRetainPtr<WKMutableDictionaryRef> messageBody(AdoptWK, WKMutableDictionaryCreate());
858
859     WKRetainPtr<WKStringRef> isInitialKeyWK(AdoptWK, WKStringCreateWithUTF8CString("hidden"));
860     WKRetainPtr<WKBooleanRef> isInitialWK(AdoptWK, WKBooleanCreate(hidden));
861     WKDictionarySetItem(messageBody.get(), isInitialKeyWK.get(), isInitialWK.get());
862
863     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
864 }
865
866 void InjectedBundle::setCacheModel(int model)
867 {
868     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetCacheModel"));
869     WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(model));
870     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
871 }
872
873 bool InjectedBundle::shouldProcessWorkQueue() const
874 {
875     if (!m_useWorkQueue)
876         return false;
877
878     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsWorkQueueEmpty"));
879     WKTypeRef resultToPass = 0;
880     WKBundlePagePostSynchronousMessageForTesting(page()->page(), messageName.get(), 0, &resultToPass);
881     WKRetainPtr<WKBooleanRef> isEmpty(AdoptWK, static_cast<WKBooleanRef>(resultToPass));
882
883     // The IPC failed. This happens when swapping processes on navigation because the WebPageProxy unregisters itself
884     // as a MessageReceiver from the old WebProcessProxy and register itself with the new WebProcessProxy instead.
885     if (!isEmpty)
886         return false;
887
888     return !WKBooleanGetValue(isEmpty.get());
889 }
890
891 void InjectedBundle::processWorkQueue()
892 {
893     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ProcessWorkQueue"));
894     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
895 }
896
897 void InjectedBundle::queueBackNavigation(unsigned howFarBackward)
898 {
899     m_useWorkQueue = true;
900
901     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueBackNavigation"));
902     WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(howFarBackward));
903     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
904 }
905
906 void InjectedBundle::queueForwardNavigation(unsigned howFarForward)
907 {
908     m_useWorkQueue = true;
909
910     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueForwardNavigation"));
911     WKRetainPtr<WKUInt64Ref> messageBody(AdoptWK, WKUInt64Create(howFarForward));
912     WKBundlePagePostMessage(page()->page(), messageName.get(), messageBody.get());
913 }
914
915 void InjectedBundle::queueLoad(WKStringRef url, WKStringRef target, bool shouldOpenExternalURLs)
916 {
917     m_useWorkQueue = true;
918
919     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoad"));
920
921     WKRetainPtr<WKMutableDictionaryRef> loadData(AdoptWK, WKMutableDictionaryCreate());
922
923     WKRetainPtr<WKStringRef> urlKey(AdoptWK, WKStringCreateWithUTF8CString("url"));
924     WKDictionarySetItem(loadData.get(), urlKey.get(), url);
925
926     WKRetainPtr<WKStringRef> targetKey(AdoptWK, WKStringCreateWithUTF8CString("target"));
927     WKDictionarySetItem(loadData.get(), targetKey.get(), target);
928
929     WKRetainPtr<WKStringRef> shouldOpenExternalURLsKey(AdoptWK, WKStringCreateWithUTF8CString("shouldOpenExternalURLs"));
930     WKRetainPtr<WKBooleanRef> shouldOpenExternalURLsValue(AdoptWK, WKBooleanCreate(shouldOpenExternalURLs));
931     WKDictionarySetItem(loadData.get(), shouldOpenExternalURLsKey.get(), shouldOpenExternalURLsValue.get());
932
933     WKBundlePagePostMessage(page()->page(), messageName.get(), loadData.get());
934 }
935
936 void InjectedBundle::queueLoadHTMLString(WKStringRef content, WKStringRef baseURL, WKStringRef unreachableURL)
937 {
938     m_useWorkQueue = true;
939
940     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoadHTMLString"));
941
942     WKRetainPtr<WKMutableDictionaryRef> loadData(AdoptWK, WKMutableDictionaryCreate());
943
944     WKRetainPtr<WKStringRef> contentKey(AdoptWK, WKStringCreateWithUTF8CString("content"));
945     WKDictionarySetItem(loadData.get(), contentKey.get(), content);
946
947     if (baseURL) {
948         WKRetainPtr<WKStringRef> baseURLKey(AdoptWK, WKStringCreateWithUTF8CString("baseURL"));
949         WKDictionarySetItem(loadData.get(), baseURLKey.get(), baseURL);
950     }
951
952     if (unreachableURL) {
953         WKRetainPtr<WKStringRef> unreachableURLKey(AdoptWK, WKStringCreateWithUTF8CString("unreachableURL"));
954         WKDictionarySetItem(loadData.get(), unreachableURLKey.get(), unreachableURL);
955     }
956
957     WKBundlePagePostMessage(page()->page(), messageName.get(), loadData.get());
958 }
959
960 void InjectedBundle::queueReload()
961 {
962     m_useWorkQueue = true;
963
964     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueReload"));
965     WKBundlePagePostMessage(page()->page(), messageName.get(), 0);
966 }
967
968 void InjectedBundle::queueLoadingScript(WKStringRef script)
969 {
970     m_useWorkQueue = true;
971
972     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueLoadingScript"));
973     WKBundlePagePostMessage(page()->page(), messageName.get(), script);
974 }
975
976 void InjectedBundle::queueNonLoadingScript(WKStringRef script)
977 {
978     m_useWorkQueue = true;
979
980     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("QueueNonLoadingScript"));
981     WKBundlePagePostMessage(page()->page(), messageName.get(), script);
982 }
983
984 bool InjectedBundle::isAllowedHost(WKStringRef host)
985 {
986     if (m_allowedHosts.isEmpty())
987         return false;
988     return m_allowedHosts.contains(toWTFString(host));
989 }
990
991 void InjectedBundle::setAllowsAnySSLCertificate(bool allowsAnySSLCertificate)
992 {
993     WebCoreTestSupport::setAllowsAnySSLCertificate(allowsAnySSLCertificate);
994 }
995
996 void InjectedBundle::statisticsNotifyObserver()
997 {
998     WKBundleResourceLoadStatisticsNotifyObserver(m_bundle);
999 }
1000
1001 void InjectedBundle::textDidChangeInTextField()
1002 {
1003     m_testRunner->textDidChangeInTextFieldCallback();
1004 }
1005
1006 void InjectedBundle::textFieldDidBeginEditing()
1007 {
1008     m_testRunner->textFieldDidBeginEditingCallback();
1009 }
1010
1011 void InjectedBundle::textFieldDidEndEditing()
1012 {
1013     m_testRunner->textFieldDidEndEditingCallback();
1014 }
1015
1016 } // namespace WTR