forked from qt/qtwebkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestController.cpp
More file actions
1924 lines (1584 loc) · 77.5 KB
/
Copy pathTestController.cpp
File metadata and controls
1924 lines (1584 loc) · 77.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010, 2014-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "TestController.h"
#include "EventSenderProxy.h"
#include "Options.h"
#include "PlatformWebView.h"
#include "StringFunctions.h"
#include "TestInvocation.h"
#include <WebKit/WKArray.h>
#include <WebKit/WKAuthenticationChallenge.h>
#include <WebKit/WKAuthenticationDecisionListener.h>
#include <WebKit/WKContextConfigurationRef.h>
#include <WebKit/WKContextPrivate.h>
#include <WebKit/WKCookieManager.h>
#include <WebKit/WKCredential.h>
#include <WebKit/WKIconDatabase.h>
#include <WebKit/WKNavigationResponseRef.h>
#include <WebKit/WKNotification.h>
#include <WebKit/WKNotificationManager.h>
#include <WebKit/WKNotificationPermissionRequest.h>
#include <WebKit/WKNumber.h>
#include <WebKit/WKPageGroup.h>
#include <WebKit/WKPageInjectedBundleClient.h>
#include <WebKit/WKPagePrivate.h>
#include <WebKit/WKPluginInformation.h>
#include <WebKit/WKPreferencesRefPrivate.h>
#include <WebKit/WKProtectionSpace.h>
#include <WebKit/WKRetainPtr.h>
#include <WebKit/WKSecurityOriginRef.h>
#include <WebKit/WKUserMediaPermissionCheck.h>
#include <algorithm>
#include <cstdio>
#include <ctype.h>
#include <fstream>
#include <runtime/InitializeThreading.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <wtf/MainThread.h>
#include <wtf/RunLoop.h>
#include <wtf/TemporaryChange.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#if PLATFORM(COCOA)
#include <WebKit/WKContextPrivateMac.h>
#include <WebKit/WKPagePrivateMac.h>
#endif
#if !PLATFORM(COCOA)
#include <WebKit/WKTextChecker.h>
#endif
namespace WTR {
const unsigned TestController::viewWidth = 800;
const unsigned TestController::viewHeight = 600;
const unsigned TestController::w3cSVGViewWidth = 480;
const unsigned TestController::w3cSVGViewHeight = 360;
#if ASAN_ENABLED
const double TestController::shortTimeout = 10.0;
#else
const double TestController::shortTimeout = 5.0;
#endif
const double TestController::noTimeout = -1;
static WKURLRef blankURL()
{
static WKURLRef staticBlankURL = WKURLCreateWithUTF8CString("about:blank");
return staticBlankURL;
}
static WKDataRef copyWebCryptoMasterKey(WKPageRef, const void*)
{
// Any 128 bit key would do, all we need for testing is to implement the callback.
return WKDataCreate((const uint8_t*)"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16);
}
static TestController* controller;
TestController& TestController::singleton()
{
ASSERT(controller);
return *controller;
}
TestController::TestController(int argc, const char* argv[])
: m_verbose(false)
, m_printSeparators(false)
, m_usingServerMode(false)
, m_gcBetweenTests(false)
, m_shouldDumpPixelsForAllTests(false)
, m_state(Initial)
, m_doneResetting(false)
, m_useWaitToDumpWatchdogTimer(true)
, m_forceNoTimeout(false)
, m_didPrintWebProcessCrashedMessage(false)
, m_shouldExitWhenWebProcessCrashes(true)
, m_beforeUnloadReturnValue(true)
, m_isGeolocationPermissionSet(false)
, m_isGeolocationPermissionAllowed(false)
, m_policyDelegateEnabled(false)
, m_policyDelegatePermissive(false)
, m_handlesAuthenticationChallenges(false)
, m_shouldBlockAllPlugins(false)
, m_forceComplexText(false)
, m_shouldUseAcceleratedDrawing(false)
, m_shouldUseRemoteLayerTree(false)
, m_shouldLogHistoryClientCallbacks(false)
, m_shouldShowWebView(false)
{
initialize(argc, argv);
controller = this;
run();
controller = 0;
}
TestController::~TestController()
{
// The context will be null if WebKitTestRunner was in server mode, but ran no tests.
if (m_context)
WKIconDatabaseClose(WKContextGetIconDatabase(m_context.get()));
platformDestroy();
}
static WKRect getWindowFrame(WKPageRef page, const void* clientInfo)
{
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
return view->windowFrame();
}
static void setWindowFrame(WKPageRef page, WKRect frame, const void* clientInfo)
{
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
view->setWindowFrame(frame);
}
static bool runBeforeUnloadConfirmPanel(WKPageRef page, WKStringRef message, WKFrameRef frame, const void*)
{
printf("CONFIRM NAVIGATION: %s\n", toSTD(message).c_str());
return TestController::singleton().beforeUnloadReturnValue();
}
void TestController::runModal(WKPageRef page, const void* clientInfo)
{
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
view->setWindowIsKey(false);
runModal(view);
view->setWindowIsKey(true);
}
static void closeOtherPage(WKPageRef page, const void* clientInfo)
{
WKPageClose(page);
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
delete view;
}
static void focus(WKPageRef page, const void* clientInfo)
{
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
view->focus();
view->setWindowIsKey(true);
}
static void unfocus(WKPageRef page, const void* clientInfo)
{
PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
view->setWindowIsKey(false);
}
static void decidePolicyForGeolocationPermissionRequest(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKGeolocationPermissionRequestRef permissionRequest, const void* clientInfo)
{
TestController::singleton().handleGeolocationPermissionRequest(permissionRequest);
}
static void decidePolicyForUserMediaPermissionRequest(WKPageRef, WKFrameRef, WKSecurityOriginRef origin, WKUserMediaPermissionRequestRef permissionRequest, const void* clientInfo)
{
TestController::singleton().handleUserMediaPermissionRequest(origin, permissionRequest);
}
static void checkUserMediaPermissionForOrigin(WKPageRef, WKFrameRef, WKSecurityOriginRef origin, WKUserMediaPermissionCheckRef checkRequest, const void*)
{
TestController::singleton().handleCheckOfUserMediaPermissionForOrigin(origin, checkRequest);
}
WKPageRef TestController::createOtherPage(WKPageRef oldPage, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures, const void *clientInfo)
{
PlatformWebView* parentView = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
PlatformWebView* view = platformCreateOtherPage(parentView, configuration, parentView->options());
WKPageRef newPage = view->page();
view->resizeTo(800, 600);
WKPageUIClientV6 otherPageUIClient = {
{ 6, view },
0, // createNewPage_deprecatedForUseWithV0
0, // showPage
closeOtherPage,
0, // takeFocus
focus,
unfocus,
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // setStatusText
0, // mouseDidMoveOverElement_deprecatedForUseWithV0
0, // missingPluginButtonClicked
0, // didNotHandleKeyEvent
0, // didNotHandleWheelEvent
0, // toolbarsAreVisible
0, // setToolbarsAreVisible
0, // menuBarIsVisible
0, // setMenuBarIsVisible
0, // statusBarIsVisible
0, // setStatusBarIsVisible
0, // isResizable
0, // setIsResizable
getWindowFrame,
setWindowFrame,
runBeforeUnloadConfirmPanel,
0, // didDraw
0, // pageDidScroll
0, // exceededDatabaseQuota
0, // runOpenPanel
decidePolicyForGeolocationPermissionRequest,
0, // headerHeight
0, // footerHeight
0, // drawHeader
0, // drawFooter
0, // printFrame
runModal,
0, // didCompleteRubberBandForMainFrame
0, // saveDataToFileInDownloadsFolder
0, // shouldInterruptJavaScript
0, // createNewPage_deprecatedForUseWithV1
0, // mouseDidMoveOverElement
0, // decidePolicyForNotificationPermissionRequest
0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
0, // showColorPicker
0, // hideColorPicker
0, // unavailablePluginButtonClicked
0, // pinnedStateDidChange
0, // didBeginTrackingPotentialLongMousePress
0, // didRecognizeLongMousePress
0, // didCancelTrackingPotentialLongMousePress
0, // isPlayingAudioDidChange
decidePolicyForUserMediaPermissionRequest,
0, // didClickAutofillButton
0, // runJavaScriptAlert
0, // runJavaScriptConfirm
0, // runJavaScriptPrompt
0, // mediaSessionMetadataDidChange
createOtherPage,
0, // runJavaScriptAlert
0, // runJavaScriptConfirm
0, // runJavaScriptPrompt
checkUserMediaPermissionForOrigin,
};
WKPageSetPageUIClient(newPage, &otherPageUIClient.base);
WKPageNavigationClientV0 pageNavigationClient = {
{ 0, &TestController::singleton() },
decidePolicyForNavigationAction,
decidePolicyForNavigationResponse,
decidePolicyForPluginLoad,
0, // didStartProvisionalNavigation
0, // didReceiveServerRedirectForProvisionalNavigation
0, // didFailProvisionalNavigation
0, // didCommitNavigation
0, // didFinishNavigation
0, // didFailNavigation
0, // didFailProvisionalLoadInSubframe
0, // didFinishDocumentLoad
0, // didSameDocumentNavigation
0, // renderingProgressDidChange
canAuthenticateAgainstProtectionSpace,
didReceiveAuthenticationChallenge,
processDidCrash,
copyWebCryptoMasterKey,
didBeginNavigationGesture,
willEndNavigationGesture,
didEndNavigationGesture,
didRemoveNavigationGestureSnapshot
};
WKPageSetPageNavigationClient(newPage, &pageNavigationClient.base);
view->didInitializeClients();
TestController::singleton().updateWindowScaleForTest(view, *TestController::singleton().m_currentInvocation);
WKRetain(newPage);
return newPage;
}
const char* TestController::libraryPathForTesting()
{
// FIXME: This may not be sufficient to prevent interactions/crashes
// when running more than one copy of DumpRenderTree.
// See https://bugs.webkit.org/show_bug.cgi?id=10906
char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
if (dumpRenderTreeTemp)
return dumpRenderTreeTemp;
return platformLibraryPathForTesting();
}
void TestController::initialize(int argc, const char* argv[])
{
JSC::initializeThreading();
WTF::initializeMainThread();
RunLoop::initializeMainRunLoop();
platformInitialize();
Options options;
OptionsHandler optionsHandler(options);
if (argc < 2) {
optionsHandler.printHelp();
exit(1);
}
if (!optionsHandler.parse(argc, argv))
exit(1);
m_useWaitToDumpWatchdogTimer = options.useWaitToDumpWatchdogTimer;
m_forceNoTimeout = options.forceNoTimeout;
m_verbose = options.verbose;
m_gcBetweenTests = options.gcBetweenTests;
m_shouldDumpPixelsForAllTests = options.shouldDumpPixelsForAllTests;
m_forceComplexText = options.forceComplexText;
m_shouldUseAcceleratedDrawing = options.shouldUseAcceleratedDrawing;
m_shouldUseRemoteLayerTree = options.shouldUseRemoteLayerTree;
m_paths = options.paths;
m_allowedHosts = options.allowedHosts;
m_shouldShowWebView = options.shouldShowWebView;
if (options.printSupportedFeatures) {
// FIXME: On Windows, DumpRenderTree uses this to expose whether it supports 3d
// transforms and accelerated compositing. When we support those features, we
// should match DRT's behavior.
exit(0);
}
m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
if (m_usingServerMode)
m_printSeparators = true;
else
m_printSeparators = m_paths.size() > 1;
initializeInjectedBundlePath();
initializeTestPluginDirectory();
WKRetainPtr<WKStringRef> pageGroupIdentifier(AdoptWK, WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));
}
WKRetainPtr<WKContextConfigurationRef> TestController::generateContextConfiguration() const
{
auto configuration = adoptWK(WKContextConfigurationCreate());
WKContextConfigurationSetInjectedBundlePath(configuration.get(), injectedBundlePath());
WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(configuration.get(), true);
if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
const char separator = '/';
WKContextConfigurationSetApplicationCacheDirectory(configuration.get(), toWK(temporaryFolder + separator + "ApplicationCache").get());
WKContextConfigurationSetDiskCacheDirectory(configuration.get(), toWK(temporaryFolder + separator + "Cache").get());
WKContextConfigurationSetIndexedDBDatabaseDirectory(configuration.get(), toWK(temporaryFolder + separator + "Databases" + separator + "IndexedDB").get());
WKContextConfigurationSetLocalStorageDirectory(configuration.get(), toWK(temporaryFolder + separator + "LocalStorage").get());
WKContextConfigurationSetWebSQLDatabaseDirectory(configuration.get(), toWK(temporaryFolder + separator + "Databases" + separator + "WebSQL").get());
WKContextConfigurationSetMediaKeysStorageDirectory(configuration.get(), toWK(temporaryFolder + separator + "MediaKeys").get());
}
return configuration;
}
WKRetainPtr<WKPageConfigurationRef> TestController::generatePageConfiguration(WKContextConfigurationRef configuration)
{
m_context = platformAdjustContext(adoptWK(WKContextCreateWithConfiguration(configuration)).get(), configuration);
m_geolocationProvider = std::make_unique<GeolocationProviderMock>(m_context.get());
if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
// FIXME: This should be migrated to WKContextConfigurationRef.
// Disable icon database to avoid fetching <http://127.0.0.1:8000/favicon.ico> and making tests flaky.
// Invividual tests can enable it using testRunner.setIconDatabaseEnabled, although it's not currently supported in WebKitTestRunner.
WKContextSetIconDatabasePath(m_context.get(), toWK(emptyString()).get());
}
WKContextUseTestingNetworkSession(m_context.get());
WKContextSetCacheModel(m_context.get(), kWKCacheModelDocumentBrowser);
platformInitializeContext();
WKContextInjectedBundleClientV1 injectedBundleClient = {
{ 1, this },
didReceiveMessageFromInjectedBundle,
didReceiveSynchronousMessageFromInjectedBundle,
0 // getInjectedBundleInitializationUserData
};
WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient.base);
WKContextClientV1 contextClient = {
{ 1, this },
0, // plugInAutoStartOriginHashesChanged
networkProcessDidCrash,
0, // plugInInformationBecameAvailable
0, // copyWebCryptoMasterKey
};
WKContextSetClient(m_context.get(), &contextClient.base);
WKContextHistoryClientV0 historyClient = {
{ 0, this },
didNavigateWithNavigationData,
didPerformClientRedirect,
didPerformServerRedirect,
didUpdateHistoryTitle,
0, // populateVisitedLinks
};
WKContextSetHistoryClient(m_context.get(), &historyClient.base);
WKNotificationManagerRef notificationManager = WKContextGetNotificationManager(m_context.get());
WKNotificationProviderV0 notificationKit = m_webNotificationProvider.provider();
WKNotificationManagerSetProvider(notificationManager, ¬ificationKit.base);
if (testPluginDirectory())
WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());
if (m_forceComplexText)
WKContextSetAlwaysUsesComplexTextCodePath(m_context.get(), true);
auto pageConfiguration = adoptWK(WKPageConfigurationCreate());
WKPageConfigurationSetContext(pageConfiguration.get(), m_context.get());
WKPageConfigurationSetPageGroup(pageConfiguration.get(), m_pageGroup.get());
WKPageConfigurationSetUserContentController(pageConfiguration.get(), adoptWK(WKUserContentControllerCreate()).get());
return pageConfiguration;
}
void TestController::createWebViewWithOptions(const TestOptions& options)
{
auto contextConfiguration = generateContextConfiguration();
WKRetainPtr<WKMutableArrayRef> overrideLanguages = adoptWK(WKMutableArrayCreate());
for (auto& language : options.overrideLanguages)
WKArrayAppendItem(overrideLanguages.get(), adoptWK(WKStringCreateWithUTF8CString(language.utf8().data())).get());
WKContextConfigurationSetOverrideLanguages(contextConfiguration.get(), overrideLanguages.get());
auto configuration = generatePageConfiguration(contextConfiguration.get());
// Some preferences (notably mock scroll bars setting) currently cannot be re-applied to an existing view, so we need to set them now.
// FIXME: Migrate these preferences to WKContextConfigurationRef.
resetPreferencesToConsistentValues();
platformCreateWebView(configuration.get(), options);
WKPageUIClientV6 pageUIClient = {
{ 6, m_mainWebView.get() },
0, // createNewPage_deprecatedForUseWithV0
0, // showPage
0, // close
0, // takeFocus
focus,
unfocus,
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // runJavaScriptAlert_deprecatedForUseWithV0
0, // setStatusText
0, // mouseDidMoveOverElement_deprecatedForUseWithV0
0, // missingPluginButtonClicked
0, // didNotHandleKeyEvent
0, // didNotHandleWheelEvent
0, // toolbarsAreVisible
0, // setToolbarsAreVisible
0, // menuBarIsVisible
0, // setMenuBarIsVisible
0, // statusBarIsVisible
0, // setStatusBarIsVisible
0, // isResizable
0, // setIsResizable
getWindowFrame,
setWindowFrame,
runBeforeUnloadConfirmPanel,
0, // didDraw
0, // pageDidScroll
0, // exceededDatabaseQuota,
0, // runOpenPanel
decidePolicyForGeolocationPermissionRequest,
0, // headerHeight
0, // footerHeight
0, // drawHeader
0, // drawFooter
0, // printFrame
runModal,
0, // didCompleteRubberBandForMainFrame
0, // saveDataToFileInDownloadsFolder
0, // shouldInterruptJavaScript
0, // createNewPage_deprecatedForUseWithV1
0, // mouseDidMoveOverElement
decidePolicyForNotificationPermissionRequest, // decidePolicyForNotificationPermissionRequest
0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
0, // showColorPicker
0, // hideColorPicker
unavailablePluginButtonClicked,
0, // pinnedStateDidChange
0, // didBeginTrackingPotentialLongMousePress
0, // didRecognizeLongMousePress
0, // didCancelTrackingPotentialLongMousePress
0, // isPlayingAudioDidChange
decidePolicyForUserMediaPermissionRequest,
0, // didClickAutofillButton
0, // runJavaScriptAlert
0, // runJavaScriptConfirm
0, // runJavaScriptPrompt
0, // mediaSessionMetadataDidChange
createOtherPage,
0, // runJavaScriptAlert
0, // runJavaScriptConfirm
0, // runJavaScriptPrompt
checkUserMediaPermissionForOrigin,
};
WKPageSetPageUIClient(m_mainWebView->page(), &pageUIClient.base);
WKPageNavigationClientV0 pageNavigationClient = {
{ 0, this },
decidePolicyForNavigationAction,
decidePolicyForNavigationResponse,
decidePolicyForPluginLoad,
0, // didStartProvisionalNavigation
0, // didReceiveServerRedirectForProvisionalNavigation
0, // didFailProvisionalNavigation
didCommitNavigation,
didFinishNavigation,
0, // didFailNavigation
0, // didFailProvisionalLoadInSubframe
0, // didFinishDocumentLoad
0, // didSameDocumentNavigation
0, // renderingProgressDidChange
canAuthenticateAgainstProtectionSpace,
didReceiveAuthenticationChallenge,
processDidCrash,
copyWebCryptoMasterKey,
didBeginNavigationGesture,
willEndNavigationGesture,
didEndNavigationGesture,
didRemoveNavigationGestureSnapshot
};
WKPageSetPageNavigationClient(m_mainWebView->page(), &pageNavigationClient.base);
// this should just be done on the page?
WKPageInjectedBundleClientV0 injectedBundleClient = {
{ 0, this },
didReceivePageMessageFromInjectedBundle,
didReceiveSynchronousPageMessageFromInjectedBundle
};
WKPageSetPageInjectedBundleClient(m_mainWebView->page(), &injectedBundleClient.base);
m_mainWebView->didInitializeClients();
// Generally, the tests should default to running at 1x. updateWindowScaleForTest() will adjust the scale to
// something else for specific tests that need to run at a different window scale.
m_mainWebView->changeWindowScaleIfNeeded(1);
}
void TestController::ensureViewSupportsOptionsForTest(const TestInvocation& test)
{
auto options = test.options();
if (m_mainWebView) {
if (m_mainWebView->viewSupportsOptions(options))
return;
WKPageSetPageUIClient(m_mainWebView->page(), nullptr);
WKPageSetPageNavigationClient(m_mainWebView->page(), nullptr);
WKPageClose(m_mainWebView->page());
m_mainWebView = nullptr;
}
createWebViewWithOptions(options);
if (!resetStateToConsistentValues())
TestInvocation::dumpWebProcessUnresponsiveness("<unknown> - TestController::run - Failed to reset state to consistent values\n");
}
void TestController::resetPreferencesToConsistentValues()
{
// Reset preferences
WKPreferencesRef preferences = platformPreferences();
WKPreferencesResetTestRunnerOverrides(preferences);
WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(preferences, false);
WKPreferencesSetOfflineWebApplicationCacheEnabled(preferences, true);
WKPreferencesSetFontSmoothingLevel(preferences, kWKFontSmoothingLevelNoSubpixelAntiAliasing);
WKPreferencesSetAntialiasedFontDilationEnabled(preferences, false);
WKPreferencesSetXSSAuditorEnabled(preferences, false);
WKPreferencesSetWebAudioEnabled(preferences, true);
WKPreferencesSetMediaStreamEnabled(preferences, true);
WKPreferencesSetDeveloperExtrasEnabled(preferences, true);
WKPreferencesSetJavaScriptRuntimeFlags(preferences, kWKJavaScriptRuntimeFlagsAllEnabled);
WKPreferencesSetJavaScriptCanOpenWindowsAutomatically(preferences, true);
WKPreferencesSetJavaScriptCanAccessClipboard(preferences, true);
WKPreferencesSetDOMPasteAllowed(preferences, true);
WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferences, true);
WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
#if ENABLE(FULLSCREEN_API)
WKPreferencesSetFullScreenEnabled(preferences, true);
#endif
WKPreferencesSetPageCacheEnabled(preferences, false);
WKPreferencesSetAsynchronousPluginInitializationEnabled(preferences, false);
WKPreferencesSetAsynchronousPluginInitializationEnabledForAllPlugins(preferences, false);
WKPreferencesSetArtificialPluginInitializationDelayEnabled(preferences, false);
WKPreferencesSetTabToLinksEnabled(preferences, false);
WKPreferencesSetInteractiveFormValidationEnabled(preferences, true);
WKPreferencesSetMockScrollbarsEnabled(preferences, true);
static WKStringRef defaultTextEncoding = WKStringCreateWithUTF8CString("ISO-8859-1");
WKPreferencesSetDefaultTextEncodingName(preferences, defaultTextEncoding);
#if !PLATFORM(QT)
static WKStringRef standardFontFamily = WKStringCreateWithUTF8CString("Times");
static WKStringRef cursiveFontFamily = WKStringCreateWithUTF8CString("Apple Chancery");
static WKStringRef fantasyFontFamily = WKStringCreateWithUTF8CString("Papyrus");
static WKStringRef fixedFontFamily = WKStringCreateWithUTF8CString("Courier");
static WKStringRef pictographFontFamily = WKStringCreateWithUTF8CString("Apple Color Emoji");
static WKStringRef sansSerifFontFamily = WKStringCreateWithUTF8CString("Helvetica");
static WKStringRef serifFontFamily = WKStringCreateWithUTF8CString("Times");
WKPreferencesSetStandardFontFamily(preferences, standardFontFamily);
WKPreferencesSetCursiveFontFamily(preferences, cursiveFontFamily);
WKPreferencesSetFantasyFontFamily(preferences, fantasyFontFamily);
WKPreferencesSetFixedFontFamily(preferences, fixedFontFamily);
WKPreferencesSetPictographFontFamily(preferences, pictographFontFamily);
WKPreferencesSetSansSerifFontFamily(preferences, sansSerifFontFamily);
WKPreferencesSetSerifFontFamily(preferences, serifFontFamily);
#endif
WKPreferencesSetAsynchronousSpellCheckingEnabled(preferences, false);
#if ENABLE(WEB_AUDIO)
WKPreferencesSetMediaSourceEnabled(preferences, true);
#endif
WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(preferences, false);
WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(preferences, false);
WKPreferencesSetAcceleratedDrawingEnabled(preferences, m_shouldUseAcceleratedDrawing);
// FIXME: We should be testing the default.
WKPreferencesSetStorageBlockingPolicy(preferences, kWKAllowAllStorage);
WKPreferencesSetMediaPlaybackAllowsInline(preferences, true);
WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(preferences, false);
WKCookieManagerDeleteAllCookies(WKContextGetCookieManager(m_context.get()));
platformResetPreferencesToConsistentValues();
}
bool TestController::resetStateToConsistentValues()
{
TemporaryChange<State> changeState(m_state, Resetting);
m_beforeUnloadReturnValue = true;
// This setting differs between the antique and modern Mac WebKit2 API.
// For now, maintain the antique behavior, because some tests depend on it!
// FIXME: We should be testing the default.
WKPageSetBackgroundExtendsBeyondPage(m_mainWebView->page(), false);
WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
WKDictionarySetItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
WKRetainPtr<WKStringRef> allowedHostsKey = adoptWK(WKStringCreateWithUTF8CString("AllowedHosts"));
WKRetainPtr<WKMutableArrayRef> allowedHostsValue = adoptWK(WKMutableArrayCreate());
for (auto& host : m_allowedHosts) {
WKRetainPtr<WKStringRef> wkHost = adoptWK(WKStringCreateWithUTF8CString(host.c_str()));
WKArrayAppendItem(allowedHostsValue.get(), wkHost.get());
}
WKDictionarySetItem(resetMessageBody.get(), allowedHostsKey.get(), allowedHostsValue.get());
WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), resetMessageBody.get());
WKContextSetShouldUseFontSmoothing(TestController::singleton().context(), false);
WKContextSetCacheModel(TestController::singleton().context(), kWKCacheModelDocumentBrowser);
WKContextClearCachedCredentials(TestController::singleton().context());
// FIXME: This function should also ensure that there is only one page open.
// Reset the EventSender for each test.
m_eventSenderProxy = std::make_unique<EventSenderProxy>(this);
// FIXME: Is this needed? Nothing in TestController changes preferences during tests, and if there is
// some other code doing this, it should probably be responsible for cleanup too.
resetPreferencesToConsistentValues();
#if !PLATFORM(COCOA)
WKTextCheckerContinuousSpellCheckingEnabledStateChanged(true);
#endif
// In the case that a test using the chrome input field failed, be sure to clean up for the next test.
m_mainWebView->removeChromeInputField();
m_mainWebView->focus();
// Re-set to the default backing scale factor by setting the custom scale factor to 0.
WKPageSetCustomBackingScaleFactor(m_mainWebView->page(), 0);
WKPageClearWheelEventTestTrigger(m_mainWebView->page());
#if PLATFORM(EFL)
// EFL use a real window while other ports such as Qt don't.
// In EFL, we need to resize the window to the original size after calls to window.resizeTo.
WKRect rect = m_mainWebView->windowFrame();
m_mainWebView->setWindowFrame(WKRectMake(rect.origin.x, rect.origin.y, TestController::viewWidth, TestController::viewHeight));
#endif
// Reset notification permissions
m_webNotificationProvider.reset();
// Reset Geolocation permissions.
m_geolocationPermissionRequests.clear();
m_isGeolocationPermissionSet = false;
m_isGeolocationPermissionAllowed = false;
// Reset UserMedia permissions.
m_userMediaPermissionRequests.clear();
m_userMediaOriginPermissions = nullptr;
m_isUserMediaPermissionSet = false;
m_isUserMediaPermissionAllowed = false;
// Reset Custom Policy Delegate.
setCustomPolicyDelegate(false, false);
m_workQueueManager.clearWorkQueue();
m_handlesAuthenticationChallenges = false;
m_authenticationUsername = String();
m_authenticationPassword = String();
m_shouldBlockAllPlugins = false;
m_shouldLogHistoryClientCallbacks = false;
setHidden(false);
platformResetStateToConsistentValues();
// Reset main page back to about:blank
m_doneResetting = false;
m_shouldDecideNavigationPolicyAfterDelay = false;
setNavigationGesturesEnabled(false);
WKPageLoadURL(m_mainWebView->page(), blankURL());
runUntil(m_doneResetting, shortTimeout);
return m_doneResetting;
}
void TestController::terminateWebContentProcess()
{
WKPageTerminate(m_mainWebView->page());
}
void TestController::reattachPageToWebProcess()
{
// Loading a web page is the only way to reattach an existing page to a process.
m_doneResetting = false;
WKPageLoadURL(m_mainWebView->page(), blankURL());
runUntil(m_doneResetting, shortTimeout);
}
const char* TestController::webProcessName()
{
// FIXME: Find a way to not hardcode the process name.
#if PLATFORM(COCOA)
return "com.apple.WebKit.WebContent.Development";
#else
return "WebProcess";
#endif
}
const char* TestController::networkProcessName()
{
// FIXME: Find a way to not hardcode the process name.
#if PLATFORM(COCOA)
return "com.apple.WebKit.Networking.Development";
#else
return "NetworkProcess";
#endif
}
static std::string testPath(WKURLRef url)
{
auto scheme = adoptWK(WKURLCopyScheme(url));
if (WKStringIsEqualToUTF8CStringIgnoringCase(scheme.get(), "file")) {
auto path = adoptWK(WKURLCopyPath(url));
auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(path.get()));
auto length = WKStringGetUTF8CString(path.get(), buffer.data(), buffer.size());
return std::string(buffer.data(), length);
}
return std::string();
}
static WKURLRef createTestURL(const char* pathOrURL)
{
if (strstr(pathOrURL, "http://") || strstr(pathOrURL, "https://") || strstr(pathOrURL, "file://"))
return WKURLCreateWithUTF8CString(pathOrURL);
// Creating from filesytem path.
size_t length = strlen(pathOrURL);
if (!length)
return 0;
const char separator = '/';
bool isAbsolutePath = pathOrURL[0] == separator;
const char* filePrefix = "file://";
static const size_t prefixLength = strlen(filePrefix);
std::unique_ptr<char[]> buffer;
if (isAbsolutePath) {
buffer = std::make_unique<char[]>(prefixLength + length + 1);
strcpy(buffer.get(), filePrefix);
strcpy(buffer.get() + prefixLength, pathOrURL);
} else {
buffer = std::make_unique<char[]>(prefixLength + PATH_MAX + length + 2); // 1 for the separator
strcpy(buffer.get(), filePrefix);
if (!getcwd(buffer.get() + prefixLength, PATH_MAX))
return 0;
size_t numCharacters = strlen(buffer.get());
buffer[numCharacters] = separator;
strcpy(buffer.get() + numCharacters + 1, pathOrURL);
}
return WKURLCreateWithUTF8CString(buffer.get());
}
static bool parseBooleanTestHeaderValue(const std::string& value)
{
if (value == "true")
return true;
if (value == "false")
return false;
LOG_ERROR("Found unexpected value '%s' for boolean option. Expected 'true' or 'false'.", value.c_str());
return false;
}
static void updateTestOptionsFromTestHeader(TestOptions& testOptions, const std::string& pathOrURL)
{
// Gross. Need to reduce conversions between all the string types and URLs.
WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(pathOrURL.c_str()));
std::string filename = testPath(wkURL.get());
if (filename.empty())
return;
std::string options;
std::ifstream testFile(filename.data());
if (!testFile.good())
return;
getline(testFile, options);
std::string beginString("webkit-test-runner [ ");
std::string endString(" ]");
size_t beginLocation = options.find(beginString);
if (beginLocation == std::string::npos)
return;
size_t endLocation = options.find(endString, beginLocation);
if (endLocation == std::string::npos) {
LOG_ERROR("Could not find end of test header in %s", filename.c_str());
return;
}
std::string pairString = options.substr(beginLocation + beginString.size(), endLocation - (beginLocation + beginString.size()));
size_t pairStart = 0;
while (pairStart < pairString.size()) {
size_t pairEnd = pairString.find(" ", pairStart);
if (pairEnd == std::string::npos)
pairEnd = pairString.size();
size_t equalsLocation = pairString.find("=", pairStart);
if (equalsLocation == std::string::npos) {
LOG_ERROR("Malformed option in test header (could not find '=' character) in %s", filename.c_str());
break;
}
auto key = pairString.substr(pairStart, equalsLocation - pairStart);
auto value = pairString.substr(equalsLocation + 1, pairEnd - (equalsLocation + 1));
if (key == "language")
String(value.c_str()).split(",", false, testOptions.overrideLanguages);
if (key == "useThreadedScrolling")
testOptions.useThreadedScrolling = parseBooleanTestHeaderValue(value);
if (key == "useFlexibleViewport")
testOptions.useFlexibleViewport = parseBooleanTestHeaderValue(value);
if (key == "useDataDetection")
testOptions.useDataDetection = parseBooleanTestHeaderValue(value);
pairStart = pairEnd + 1;
}
}
TestOptions TestController::testOptionsForTest(const std::string& pathOrURL) const
{
TestOptions options(pathOrURL);
options.useRemoteLayerTree = m_shouldUseRemoteLayerTree;
options.shouldShowWebView = m_shouldShowWebView;
updatePlatformSpecificTestOptionsForTest(options, pathOrURL);
updateTestOptionsFromTestHeader(options, pathOrURL);
return options;
}
void TestController::updateWebViewSizeForTest(const TestInvocation& test)
{
unsigned width = viewWidth;
unsigned height = viewHeight;
if (test.options().isSVGTest) {
width = w3cSVGViewWidth;
height = w3cSVGViewHeight;
}
mainWebView()->resizeTo(width, height);
}
void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
{
view->changeWindowScaleIfNeeded(test.options().isHiDPITest ? 2 : 1);
}
void TestController::configureViewForTest(const TestInvocation& test)
{
ensureViewSupportsOptionsForTest(test);
updateWebViewSizeForTest(test);
updateWindowScaleForTest(mainWebView(), test);
platformConfigureViewForTest(test);
}
struct TestCommand {
TestCommand() : shouldDumpPixels(false), timeout(0) { }
std::string pathOrURL;
bool shouldDumpPixels;
std::string expectedPixelHash;
int timeout;
};
class CommandTokenizer {
public:
explicit CommandTokenizer(const std::string& input)
: m_input(input)
, m_posNextSeparator(0)
{
pump();
}
bool hasNext() const;
std::string next();
private:
void pump();
static const char kSeparator = '\'';
const std::string& m_input;
std::string m_next;
size_t m_posNextSeparator;
};
void CommandTokenizer::pump()
{
if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {