Add User Timing Experimental Feature
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "BackForwardList.h"
35 #import "DOMCSSStyleDeclarationInternal.h"
36 #import "DOMDocumentInternal.h"
37 #import "DOMInternal.h"
38 #import "DOMNodeInternal.h"
39 #import "DOMRangeInternal.h"
40 #import "StorageThread.h"
41 #import "WebAlternativeTextClient.h"
42 #import "WebApplicationCacheInternal.h"
43 #import "WebArchive.h"
44 #import "WebBackForwardListInternal.h"
45 #import "WebBaseNetscapePluginView.h"
46 #import "WebCache.h"
47 #import "WebChromeClient.h"
48 #import "WebDOMOperationsPrivate.h"
49 #import "WebDataSourceInternal.h"
50 #import "WebDatabaseManagerPrivate.h"
51 #import "WebDatabaseProvider.h"
52 #import "WebDefaultEditingDelegate.h"
53 #import "WebDefaultPolicyDelegate.h"
54 #import "WebDefaultUIDelegate.h"
55 #import "WebDelegateImplementationCaching.h"
56 #import "WebDeviceOrientationClient.h"
57 #import "WebDeviceOrientationProvider.h"
58 #import "WebDocument.h"
59 #import "WebDocumentInternal.h"
60 #import "WebDownload.h"
61 #import "WebDownloadInternal.h"
62 #import "WebDragClient.h"
63 #import "WebDynamicScrollBarsViewInternal.h"
64 #import "WebEditingDelegate.h"
65 #import "WebEditorClient.h"
66 #import "WebFormDelegatePrivate.h"
67 #import "WebFrameInternal.h"
68 #import "WebFrameLoaderClient.h"
69 #import "WebFrameNetworkingContext.h"
70 #import "WebFrameViewInternal.h"
71 #import "WebGeolocationClient.h"
72 #import "WebGeolocationPositionInternal.h"
73 #import "WebHTMLRepresentation.h"
74 #import "WebHTMLViewInternal.h"
75 #import "WebHistoryItemInternal.h"
76 #import "WebIconDatabaseInternal.h"
77 #import "WebInspector.h"
78 #import "WebInspectorClient.h"
79 #import "WebKitErrors.h"
80 #import "WebKitFullScreenListener.h"
81 #import "WebKitLogging.h"
82 #import "WebKitNSStringExtras.h"
83 #import "WebKitStatisticsPrivate.h"
84 #import "WebKitVersionChecks.h"
85 #import "WebLocalizableStrings.h"
86 #import "WebNSDataExtras.h"
87 #import "WebNSDataExtrasPrivate.h"
88 #import "WebNSDictionaryExtras.h"
89 #import "WebNSURLExtras.h"
90 #import "WebNSURLRequestExtras.h"
91 #import "WebNSViewExtras.h"
92 #import "WebNodeHighlight.h"
93 #import "WebNotificationClient.h"
94 #import "WebPDFView.h"
95 #import "WebPaymentCoordinatorClient.h"
96 #import "WebPlatformStrategies.h"
97 #import "WebPluginDatabase.h"
98 #import "WebPluginInfoProvider.h"
99 #import "WebPolicyDelegate.h"
100 #import "WebPreferenceKeysPrivate.h"
101 #import "WebPreferencesPrivate.h"
102 #import "WebProgressTrackerClient.h"
103 #import "WebResourceLoadScheduler.h"
104 #import "WebScriptDebugDelegate.h"
105 #import "WebScriptWorldInternal.h"
106 #import "WebSelectionServiceController.h"
107 #import "WebStorageManagerInternal.h"
108 #import "WebStorageNamespaceProvider.h"
109 #import "WebSystemInterface.h"
110 #import "WebTextCompletionController.h"
111 #import "WebTextIterator.h"
112 #import "WebUIDelegate.h"
113 #import "WebUIDelegatePrivate.h"
114 #import "WebUserMediaClient.h"
115 #import "WebValidationMessageClient.h"
116 #import "WebViewGroup.h"
117 #import "WebVisitedLinkStore.h"
118 #import <CoreFoundation/CFSet.h>
119 #import <Foundation/NSURLConnection.h>
120 #import <JavaScriptCore/APICast.h>
121 #import <JavaScriptCore/Exception.h>
122 #import <JavaScriptCore/JSValueRef.h>
123 #import <WebCore/AlternativeTextUIController.h>
124 #import <WebCore/AnimationController.h>
125 #import <WebCore/ApplicationCacheStorage.h>
126 #import <WebCore/BackForwardController.h>
127 #import <WebCore/CFNetworkSPI.h>
128 #import <WebCore/Chrome.h>
129 #import <WebCore/ColorMac.h>
130 #import <WebCore/DatabaseManager.h>
131 #import <WebCore/DictionaryLookup.h>
132 #import <WebCore/Document.h>
133 #import <WebCore/DocumentLoader.h>
134 #import <WebCore/DragController.h>
135 #import <WebCore/DragData.h>
136 #import <WebCore/Editor.h>
137 #import <WebCore/EventHandler.h>
138 #import <WebCore/FocusController.h>
139 #import <WebCore/FontCache.h>
140 #import <WebCore/FrameLoader.h>
141 #import <WebCore/FrameSelection.h>
142 #import <WebCore/FrameTree.h>
143 #import <WebCore/FrameView.h>
144 #import <WebCore/GCController.h>
145 #import <WebCore/GameControllerGamepadProvider.h>
146 #import <WebCore/GeolocationController.h>
147 #import <WebCore/GeolocationError.h>
148 #import <WebCore/HTMLNames.h>
149 #import <WebCore/HTMLOListElement.h>
150 #import <WebCore/HTMLUListElement.h>
151 #import <WebCore/HTMLVideoElement.h>
152 #import <WebCore/HistoryController.h>
153 #import <WebCore/HistoryItem.h>
154 #import <WebCore/IconDatabase.h>
155 #import <WebCore/JSCSSStyleDeclaration.h>
156 #import <WebCore/JSDocument.h>
157 #import <WebCore/JSElement.h>
158 #import <WebCore/JSNodeList.h>
159 #import <WebCore/JSNotification.h>
160 #import <WebCore/LibWebRTCProvider.h>
161 #import <WebCore/LocalizedStrings.h>
162 #import <WebCore/LogInitialization.h>
163 #import <WebCore/MIMETypeRegistry.h>
164 #import <WebCore/MainFrame.h>
165 #import <WebCore/MemoryCache.h>
166 #import <WebCore/MemoryRelease.h>
167 #import <WebCore/NSSpellCheckerSPI.h>
168 #import <WebCore/NSTouchBarSPI.h>
169 #import <WebCore/NSURLFileTypeMappingsSPI.h>
170 #import <WebCore/NetworkStorageSession.h>
171 #import <WebCore/NodeList.h>
172 #import <WebCore/Notification.h>
173 #import <WebCore/NotificationController.h>
174 #import <WebCore/Page.h>
175 #import <WebCore/PageCache.h>
176 #import <WebCore/PageConfiguration.h>
177 #import <WebCore/PageGroup.h>
178 #import <WebCore/PlatformEventFactoryMac.h>
179 #import <WebCore/ProgressTracker.h>
180 #import <WebCore/RenderView.h>
181 #import <WebCore/RenderWidget.h>
182 #import <WebCore/ResourceHandle.h>
183 #import <WebCore/ResourceLoadObserver.h>
184 #import <WebCore/ResourceRequest.h>
185 #import <WebCore/RuntimeApplicationChecks.h>
186 #import <WebCore/RuntimeEnabledFeatures.h>
187 #import <WebCore/SchemeRegistry.h>
188 #import <WebCore/ScriptController.h>
189 #import <WebCore/SecurityOrigin.h>
190 #import <WebCore/SecurityPolicy.h>
191 #import <WebCore/Settings.h>
192 #import <WebCore/SocketProvider.h>
193 #import <WebCore/StyleProperties.h>
194 #import <WebCore/TextResourceDecoder.h>
195 #import <WebCore/ThreadCheck.h>
196 #import <WebCore/UserAgent.h>
197 #import <WebCore/UserContentController.h>
198 #import <WebCore/UserScript.h>
199 #import <WebCore/UserStyleSheet.h>
200 #import <WebCore/ValidationBubble.h>
201 #import <WebCore/WebCoreObjCExtras.h>
202 #import <WebCore/WebCoreView.h>
203 #import <WebCore/Widget.h>
204 #import <WebCore/htmlediting.h>
205 #import <WebKitLegacy/DOM.h>
206 #import <WebKitLegacy/DOMExtensions.h>
207 #import <WebKitLegacy/DOMPrivate.h>
208 #import <WebKitSystemInterface.h>
209 #import <bindings/ScriptValue.h>
210 #import <mach-o/dyld.h>
211 #import <objc/runtime.h>
212 #import <runtime/ArrayPrototype.h>
213 #import <runtime/DateInstance.h>
214 #import <runtime/InitializeThreading.h>
215 #import <runtime/JSCJSValue.h>
216 #import <runtime/JSLock.h>
217 #import <wtf/Assertions.h>
218 #import <wtf/HashTraits.h>
219 #import <wtf/MainThread.h>
220 #import <wtf/ObjcRuntimeExtras.h>
221 #import <wtf/RAMSize.h>
222 #import <wtf/RefCountedLeakCounter.h>
223 #import <wtf/RefPtr.h>
224 #import <wtf/RunLoop.h>
225 #import <wtf/SetForScope.h>
226 #import <wtf/StdLibExtras.h>
227 #import <wtf/spi/darwin/dyldSPI.h>
228
229 #if !PLATFORM(IOS)
230 #import "WebContextMenuClient.h"
231 #import "WebFullScreenController.h"
232 #import "WebImmediateActionController.h"
233 #import "WebNSEventExtras.h"
234 #import "WebNSObjectExtras.h"
235 #import "WebNSPasteboardExtras.h"
236 #import "WebNSPrintOperationExtras.h"
237 #import "WebPDFView.h"
238 #import <WebCore/AVKitSPI.h>
239 #import <WebCore/LookupSPI.h>
240 #import <WebCore/NSImmediateActionGestureRecognizerSPI.h>
241 #import <WebCore/SoftLinking.h>
242 #import <WebCore/TextIndicator.h>
243 #import <WebCore/TextIndicatorWindow.h>
244 #import <WebCore/WebVideoFullscreenController.h>
245 #else
246 #import "MemoryMeasure.h"
247 #import "WebCaretChangeListener.h"
248 #import "WebChromeClientIOS.h"
249 #import "WebDefaultFormDelegate.h"
250 #import "WebDefaultFrameLoadDelegate.h"
251 #import "WebDefaultResourceLoadDelegate.h"
252 #import "WebDefaultUIKitDelegate.h"
253 #import "WebFixedPositionContent.h"
254 #import "WebMailDelegate.h"
255 #import "WebNSUserDefaultsExtras.h"
256 #import "WebPDFViewIOS.h"
257 #import "WebPlainWhiteView.h"
258 #import "WebPluginController.h"
259 #import "WebPolicyDelegatePrivate.h"
260 #import "WebSQLiteDatabaseTrackerClient.h"
261 #import "WebStorageManagerPrivate.h"
262 #import "WebUIKitSupport.h"
263 #import "WebVisiblePosition.h"
264 #import <WebCore/EventNames.h>
265 #import <WebCore/FontCache.h>
266 #import <WebCore/GraphicsLayer.h>
267 #import <WebCore/IconController.h>
268 #import <WebCore/LegacyTileCache.h>
269 #import <WebCore/MobileGestaltSPI.h>
270 #import <WebCore/NetworkStateNotifier.h>
271 #import <WebCore/PlatformScreen.h>
272 #import <WebCore/ResourceLoadStatistics.h>
273 #import <WebCore/ResourceLoadStatisticsStore.h>
274 #import <WebCore/SQLiteDatabaseTracker.h>
275 #import <WebCore/SmartReplace.h>
276 #import <WebCore/TileControllerMemoryHandlerIOS.h>
277 #import <WebCore/WAKWindow.h>
278 #import <WebCore/WKView.h>
279 #import <WebCore/WebCoreThread.h>
280 #import <WebCore/WebCoreThreadMessage.h>
281 #import <WebCore/WebCoreThreadRun.h>
282 #import <WebCore/WebEvent.h>
283 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
284 #import <libkern/OSAtomic.h>
285 #import <wtf/FastMalloc.h>
286 #endif
287
288 #if ENABLE(DASHBOARD_SUPPORT)
289 #import <WebKitLegacy/WebDashboardRegion.h>
290 #endif
291
292 #if ENABLE(REMOTE_INSPECTOR)
293 #import <JavaScriptCore/RemoteInspector.h>
294 #if PLATFORM(IOS)
295 #import "WebIndicateLayer.h"
296 #endif
297 #endif
298
299 #if USE(QUICK_LOOK)
300 #include <WebCore/QuickLook.h>
301 #endif
302
303 #if ENABLE(IOS_TOUCH_EVENTS)
304 #import <WebCore/WebEventRegion.h>
305 #endif
306
307 #if ENABLE(GAMEPAD)
308 #import <WebCore/HIDGamepadProvider.h>
309 #endif
310
311 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
312 #import "WebMediaPlaybackTargetPicker.h"
313 #import <WebCore/WebMediaSessionManagerMac.h>
314 #endif
315
316
317 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
318 #import <WebCore/WebPlaybackSessionInterfaceMac.h>
319 #import <WebCore/WebPlaybackSessionModelMediaElement.h>
320 #endif
321
322 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
323 SOFT_LINK_FRAMEWORK(AVKit)
324 SOFT_LINK_CLASS(AVKit, AVFunctionBarPlaybackControlsProvider)
325 SOFT_LINK_CLASS(AVKit, AVFunctionBarScrubber)
326 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
327
328 #if PLATFORM(MAC)
329 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
330 #endif
331
332 #if !PLATFORM(IOS)
333
334 @interface NSSpellChecker (WebNSSpellCheckerDetails)
335 - (void)_preflightChosenSpellServer;
336 @end
337
338 @interface NSView (WebNSViewDetails)
339 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
340 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
341 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
342 - (void)_windowChangedKeyState;
343 @end
344
345 @interface NSWindow (WebNSWindowDetails)
346 - (id)_oldFirstResponderBeforeBecoming;
347 - (void)_enableScreenUpdatesIfNeeded;
348 - (BOOL)_wrapsCarbonWindow;
349 - (BOOL)_hasKeyAppearance;
350 @end
351
352 #endif
353
354 using namespace JSC;
355 using namespace Inspector;
356 using namespace WebCore;
357
358 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
359 macro(alignCenter) \
360 macro(alignJustified) \
361 macro(alignLeft) \
362 macro(alignRight) \
363 macro(capitalizeWord) \
364 macro(centerSelectionInVisibleArea) \
365 macro(changeAttributes) \
366 macro(changeBaseWritingDirection) \
367 macro(changeBaseWritingDirectionToLTR) \
368 macro(changeBaseWritingDirectionToRTL) \
369 macro(changeColor) \
370 macro(changeDocumentBackgroundColor) \
371 macro(changeFont) \
372 macro(changeSpelling) \
373 macro(checkSpelling) \
374 macro(complete) \
375 macro(copy) \
376 macro(copyFont) \
377 macro(cut) \
378 macro(delete) \
379 macro(deleteBackward) \
380 macro(deleteBackwardByDecomposingPreviousCharacter) \
381 macro(deleteForward) \
382 macro(deleteToBeginningOfLine) \
383 macro(deleteToBeginningOfParagraph) \
384 macro(deleteToEndOfLine) \
385 macro(deleteToEndOfParagraph) \
386 macro(deleteToMark) \
387 macro(deleteWordBackward) \
388 macro(deleteWordForward) \
389 macro(ignoreSpelling) \
390 macro(indent) \
391 macro(insertBacktab) \
392 macro(insertLineBreak) \
393 macro(insertNewline) \
394 macro(insertNewlineIgnoringFieldEditor) \
395 macro(insertParagraphSeparator) \
396 macro(insertTab) \
397 macro(insertTabIgnoringFieldEditor) \
398 macro(lowercaseWord) \
399 macro(makeBaseWritingDirectionLeftToRight) \
400 macro(makeBaseWritingDirectionRightToLeft) \
401 macro(makeTextWritingDirectionLeftToRight) \
402 macro(makeTextWritingDirectionNatural) \
403 macro(makeTextWritingDirectionRightToLeft) \
404 macro(moveBackward) \
405 macro(moveBackwardAndModifySelection) \
406 macro(moveDown) \
407 macro(moveDownAndModifySelection) \
408 macro(moveForward) \
409 macro(moveForwardAndModifySelection) \
410 macro(moveLeft) \
411 macro(moveLeftAndModifySelection) \
412 macro(moveParagraphBackwardAndModifySelection) \
413 macro(moveParagraphForwardAndModifySelection) \
414 macro(moveRight) \
415 macro(moveRightAndModifySelection) \
416 macro(moveToBeginningOfDocument) \
417 macro(moveToBeginningOfDocumentAndModifySelection) \
418 macro(moveToBeginningOfLine) \
419 macro(moveToBeginningOfLineAndModifySelection) \
420 macro(moveToBeginningOfParagraph) \
421 macro(moveToBeginningOfParagraphAndModifySelection) \
422 macro(moveToBeginningOfSentence) \
423 macro(moveToBeginningOfSentenceAndModifySelection) \
424 macro(moveToEndOfDocument) \
425 macro(moveToEndOfDocumentAndModifySelection) \
426 macro(moveToEndOfLine) \
427 macro(moveToEndOfLineAndModifySelection) \
428 macro(moveToEndOfParagraph) \
429 macro(moveToEndOfParagraphAndModifySelection) \
430 macro(moveToEndOfSentence) \
431 macro(moveToEndOfSentenceAndModifySelection) \
432 macro(moveToLeftEndOfLine) \
433 macro(moveToLeftEndOfLineAndModifySelection) \
434 macro(moveToRightEndOfLine) \
435 macro(moveToRightEndOfLineAndModifySelection) \
436 macro(moveUp) \
437 macro(moveUpAndModifySelection) \
438 macro(moveWordBackward) \
439 macro(moveWordBackwardAndModifySelection) \
440 macro(moveWordForward) \
441 macro(moveWordForwardAndModifySelection) \
442 macro(moveWordLeft) \
443 macro(moveWordLeftAndModifySelection) \
444 macro(moveWordRight) \
445 macro(moveWordRightAndModifySelection) \
446 macro(orderFrontSubstitutionsPanel) \
447 macro(outdent) \
448 macro(overWrite) \
449 macro(pageDown) \
450 macro(pageDownAndModifySelection) \
451 macro(pageUp) \
452 macro(pageUpAndModifySelection) \
453 macro(paste) \
454 macro(pasteAsPlainText) \
455 macro(pasteAsRichText) \
456 macro(pasteFont) \
457 macro(performFindPanelAction) \
458 macro(scrollLineDown) \
459 macro(scrollLineUp) \
460 macro(scrollPageDown) \
461 macro(scrollPageUp) \
462 macro(scrollToBeginningOfDocument) \
463 macro(scrollToEndOfDocument) \
464 macro(selectAll) \
465 macro(selectLine) \
466 macro(selectParagraph) \
467 macro(selectSentence) \
468 macro(selectToMark) \
469 macro(selectWord) \
470 macro(setMark) \
471 macro(showGuessPanel) \
472 macro(startSpeaking) \
473 macro(stopSpeaking) \
474 macro(subscript) \
475 macro(superscript) \
476 macro(swapWithMark) \
477 macro(takeFindStringFromSelection) \
478 macro(toggleBaseWritingDirection) \
479 macro(transpose) \
480 macro(underline) \
481 macro(unscript) \
482 macro(uppercaseWord) \
483 macro(yank) \
484 macro(yankAndSelect) \
485
486 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
487 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
488
489 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
490 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
491
492 static BOOL s_didSetCacheModel;
493 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
494
495 #if PLATFORM(IOS)
496 static Class s_pdfRepresentationClass;
497 static Class s_pdfViewClass;
498 #endif
499
500 #ifndef NDEBUG
501 static const char webViewIsOpen[] = "At least one WebView is still open.";
502 #endif
503
504 #if PLATFORM(IOS)
505 @interface WebView(WebViewPrivate)
506 - (void)_preferencesChanged:(WebPreferences *)preferences;
507 - (void)_updateScreenScaleFromWindow;
508 @end
509
510 @interface NSURLCache (WebPrivate)
511 - (CFURLCacheRef)_CFURLCache;
512 @end
513 #endif
514
515 #if !PLATFORM(IOS)
516 @interface NSObject (WebValidateWithoutDelegate)
517 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
518 @end
519 #endif
520
521 #if PLATFORM(IOS)
522 @class _WebSafeForwarder;
523
524 @interface _WebSafeAsyncForwarder : NSObject {
525     _WebSafeForwarder *_forwarder;
526 }
527 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
528 @end
529 #endif
530
531 @interface _WebSafeForwarder : NSObject
532 {
533     id target; // Non-retained. Don't retain delegates.
534     id defaultTarget;
535 #if PLATFORM(IOS)
536     _WebSafeAsyncForwarder *asyncForwarder;
537     dispatch_once_t asyncForwarderPred;
538 #endif
539 }
540 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
541 #if PLATFORM(IOS)
542 - (void)clearTarget;
543 - (id)asyncForwarder;
544 #endif
545 @end
546
547 FindOptions coreOptions(WebFindOptions options)
548 {
549     return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
550         | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
551         | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
552         | (options & WebFindOptionsBackwards ? Backwards : 0)
553         | (options & WebFindOptionsWrapAround ? WrapAround : 0)
554         | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
555 }
556
557 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
558 {
559     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
560         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
561         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
562 }
563
564 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
565 {
566     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
567         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
568         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
569 }
570
571 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
572 {
573     switch (visibilityState) {
574     case PageVisibilityState::Visible:
575         return WebPageVisibilityStateVisible;
576     case PageVisibilityState::Hidden:
577         return WebPageVisibilityStateHidden;
578     case PageVisibilityState::Prerender:
579         return WebPageVisibilityStatePrerender;
580     }
581
582     ASSERT_NOT_REACHED();
583     return WebPageVisibilityStateVisible;
584 }
585
586 namespace WebKit {
587
588 class DeferredPageDestructor {
589 public:
590     static void createDeferredPageDestructor(std::unique_ptr<Page> page)
591     {
592         new DeferredPageDestructor(WTFMove(page));
593     }
594
595 private:
596     DeferredPageDestructor(std::unique_ptr<Page> page)
597         : m_page(WTFMove(page))
598     {
599         tryDestruction();
600     }
601
602     void tryDestruction()
603     {
604         if (m_page->insideNestedRunLoop()) {
605             m_page->whenUnnested([this] { tryDestruction(); });
606             return;
607         }
608
609         m_page = nullptr;
610         delete this;
611     }
612
613     std::unique_ptr<Page> m_page;
614 };
615
616 } // namespace WebKit
617
618 @interface WebView (WebFileInternal)
619 #if !PLATFORM(IOS)
620 - (float)_deviceScaleFactor;
621 #endif
622 - (BOOL)_isLoading;
623 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
624 - (WebFrame *)_focusedFrame;
625 + (void)_preflightSpellChecker;
626 - (BOOL)_continuousCheckingAllowed;
627 - (NSResponder *)_responderForResponderOperations;
628 @end
629
630 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
631 NSString *WebElementFrameKey =              @"WebElementFrame";
632 NSString *WebElementImageKey =              @"WebElementImage";
633 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
634 NSString *WebElementImageRectKey =          @"WebElementImageRect";
635 NSString *WebElementImageURLKey =           @"WebElementImageURL";
636 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
637 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
638 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
639 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
640 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
641 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
642 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
643 NSString *WebElementTitleKey =              @"WebElementTitle";
644 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
645 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
646 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
647
648 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
649 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
650 #if !PLATFORM(IOS)
651 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
652 #else
653 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
654 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
655 #endif
656
657 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
658 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
659 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
660 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
661 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
662
663 enum { WebViewVersion = 4 };
664
665 #define timedLayoutSize 4096
666
667 static NSMutableSet *schemesWithRepresentationsSet;
668 static WebCore::ResourceLoadStatisticsStore* resourceLoadStatisticsStore;
669
670 #if !PLATFORM(IOS)
671 NSString *_WebCanGoBackKey =            @"canGoBack";
672 NSString *_WebCanGoForwardKey =         @"canGoForward";
673 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
674 NSString *_WebIsLoadingKey =            @"isLoading";
675 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
676 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
677 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
678 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
679 #endif
680
681 #if PLATFORM(IOS)
682 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
683 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
684 #endif
685
686 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
687 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
688
689 #if ENABLE(REMOTE_INSPECTOR)
690 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
691 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
692 #endif
693
694 @interface WebProgressItem : NSObject
695 {
696 @public
697     long long bytesReceived;
698     long long estimatedLength;
699 }
700 @end
701
702 @implementation WebProgressItem
703 @end
704
705 static BOOL continuousSpellCheckingEnabled;
706 #if !PLATFORM(IOS)
707 static BOOL grammarCheckingEnabled;
708 static BOOL automaticQuoteSubstitutionEnabled;
709 static BOOL automaticLinkDetectionEnabled;
710 static BOOL automaticDashSubstitutionEnabled;
711 static BOOL automaticTextReplacementEnabled;
712 static BOOL automaticSpellingCorrectionEnabled;
713 #endif
714
715 #if HAVE(TOUCH_BAR)
716
717 enum class WebListType {
718     None = 0,
719     Ordered,
720     Unordered
721 };
722
723 @interface WebTextListTouchBarViewController : NSViewController {
724 @private
725     WebListType _currentListType;
726     WebView *_webView;
727 }
728
729 @property (nonatomic) WebListType currentListType;
730
731 - (instancetype)initWithWebView:(WebView *)webView;
732
733 @end
734
735 @implementation WebTextListTouchBarViewController
736
737 @synthesize currentListType=_currentListType;
738
739 static const CGFloat listControlSegmentWidth = 67.0;
740
741 static const NSUInteger noListSegment = 0;
742 static const NSUInteger unorderedListSegment = 1;
743 static const NSUInteger orderedListSegment = 2;
744
745 - (instancetype)initWithWebView:(WebView *)webView
746 {
747     if (!(self = [super init]))
748         return nil;
749
750     _webView = webView;
751
752     NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
753     [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
754     [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
755     [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
756     insertListControl.font = [NSFont systemFontOfSize:15];
757
758 #pragma clang diagnostic push
759 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
760     id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
761     NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
762     ASSERT(segments.count == 3);
763     [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
764     [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
765     [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
766 #pragma clang diagnostic pop
767
768     self.view = insertListControl;
769
770     return self;
771 }
772
773 - (void)_selectList:(id)sender
774 {
775     NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
776     if (![documentView isKindOfClass:[WebHTMLView class]])
777         return;
778
779     WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
780     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
781     switch (insertListControl.selectedSegment) {
782     case noListSegment:
783         // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
784         // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
785         // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
786         if (_currentListType == WebListType::Ordered)
787             [webHTMLView _insertOrderedList];
788         else if (_currentListType == WebListType::Unordered)
789             [webHTMLView _insertUnorderedList];
790         break;
791     case unorderedListSegment:
792         [webHTMLView _insertUnorderedList];
793         break;
794     case orderedListSegment:
795         [webHTMLView _insertOrderedList];
796         break;
797     }
798
799     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
800 }
801
802 - (void)setCurrentListType:(WebListType)listType
803 {
804     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
805     switch (listType) {
806     case WebListType::None:
807         [insertListControl setSelected:YES forSegment:noListSegment];
808         break;
809     case WebListType::Ordered:
810         [insertListControl setSelected:YES forSegment:orderedListSegment];
811         break;
812     case WebListType::Unordered:
813         [insertListControl setSelected:YES forSegment:unorderedListSegment];
814         break;
815     }
816
817     _currentListType = listType;
818 }
819
820 @end
821
822 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
823 @private
824     BOOL _textIsBold;
825     BOOL _textIsItalic;
826     BOOL _textIsUnderlined;
827     NSTextAlignment _currentTextAlignment;
828     RetainPtr<NSColor> _textColor;
829     RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
830     WebView *_webView;
831 }
832
833 @property (nonatomic) BOOL textIsBold;
834 @property (nonatomic) BOOL textIsItalic;
835 @property (nonatomic) BOOL textIsUnderlined;
836 @property (nonatomic) NSTextAlignment currentTextAlignment;
837 @property (nonatomic, retain, readwrite) NSColor *textColor;
838
839 - (instancetype)initWithWebView:(WebView *)webView;
840 @end
841
842 @implementation WebTextTouchBarItemController
843
844 @synthesize textIsBold=_textIsBold;
845 @synthesize textIsItalic=_textIsItalic;
846 @synthesize textIsUnderlined=_textIsUnderlined;
847 @synthesize currentTextAlignment=_currentTextAlignment;
848
849 - (instancetype)initWithWebView:(WebView *)webView
850 {
851     if (!(self = [super init]))
852         return nil;
853
854     _webView = webView;
855
856     return self;
857 }
858
859 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
860 {
861     NSTouchBarItem *item = [super itemForIdentifier:identifier];
862     BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
863
864     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
865         self.textStyle.action = @selector(_webChangeTextStyle:);
866
867     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
868         self.textAlignments.action = @selector(_webChangeTextAlignment:);
869
870     NSColorPickerTouchBarItem *colorPickerItem = nil;
871     if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
872         colorPickerItem = (NSColorPickerTouchBarItem *)item;
873     if (isTextFormatItem)
874         colorPickerItem = self.colorPickerItem;
875     if (colorPickerItem) {
876         colorPickerItem.target = self;
877         colorPickerItem.action = @selector(_webChangeColor:);
878         colorPickerItem.showsAlpha = NO;
879     }
880
881     return item;
882 }
883
884 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
885 {
886     return (WebTextListTouchBarViewController *)self.textListViewController;
887 }
888
889 - (void)setTextIsBold:(BOOL)bold
890 {
891     _textIsBold = bold;
892     if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
893         [self.textStyle setSelected:_textIsBold forSegment:0];
894 }
895
896 - (void)setTextIsItalic:(BOOL)italic
897 {
898     _textIsItalic = italic;
899     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
900         [self.textStyle setSelected:_textIsItalic forSegment:1];
901 }
902
903 - (void)setTextIsUnderlined:(BOOL)underlined
904 {
905     _textIsUnderlined = underlined;
906     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
907         [self.textStyle setSelected:_textIsUnderlined forSegment:2];
908 }
909
910 - (void)_webChangeTextStyle:(id)sender
911 {
912     if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
913         _textIsBold = !_textIsBold;
914         [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
915     }
916
917     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
918         _textIsItalic = !_textIsItalic;
919         [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
920     }
921
922     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
923         _textIsUnderlined = !_textIsUnderlined;
924         [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
925     }
926 }
927
928 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
929 {
930     _currentTextAlignment = alignment;
931     [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
932 }
933
934 - (void)_webChangeTextAlignment:(id)sender
935 {
936     NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
937     switch (alignment) {
938     case NSTextAlignmentLeft:
939         _currentTextAlignment = NSTextAlignmentLeft;
940         [_webView alignLeft:sender];
941         break;
942     case NSTextAlignmentRight:
943         _currentTextAlignment = NSTextAlignmentRight;
944         [_webView alignRight:sender];
945         break;
946     case NSTextAlignmentCenter:
947         _currentTextAlignment = NSTextAlignmentCenter;
948         [_webView alignCenter:sender];
949         break;
950     case NSTextAlignmentJustified:
951         _currentTextAlignment = NSTextAlignmentJustified;
952         [_webView alignJustified:sender];
953         break;
954     default:
955         break;
956     }
957
958     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
959 }
960
961 - (NSColor *)textColor
962 {
963     return _textColor.get();
964 }
965
966 - (void)setTextColor:(NSColor *)color
967 {
968     _textColor = color;
969     self.colorPickerItem.color = _textColor.get();
970 }
971
972 - (void)_webChangeColor:(id)sender
973 {
974     _textColor = self.colorPickerItem.color;
975     [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
976 }
977
978 - (NSViewController *)textListViewController
979 {
980     if (!_textListTouchBarViewController)
981         _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
982     return _textListTouchBarViewController.get();
983 }
984
985 @end
986
987 #endif // HAVE(TOUCH_BAR)
988
989 @implementation WebView (AllWebViews)
990
991 static CFSetCallBacks NonRetainingSetCallbacks = {
992     0,
993     NULL,
994     NULL,
995     CFCopyDescription,
996     CFEqual,
997     CFHash
998 };
999
1000 static CFMutableSetRef allWebViewsSet;
1001
1002 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1003 {
1004     if (!allWebViewsSet)
1005         return;
1006
1007     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1008 }
1009
1010 - (void)_removeFromAllWebViewsSet
1011 {
1012     if (allWebViewsSet)
1013         CFSetRemoveValue(allWebViewsSet, self);
1014 }
1015
1016 - (void)_addToAllWebViewsSet
1017 {
1018     if (!allWebViewsSet)
1019         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1020
1021     CFSetSetValue(allWebViewsSet, self);
1022 }
1023
1024 @end
1025
1026 @implementation WebView (WebPrivate)
1027
1028 static String webKitBundleVersionString()
1029 {
1030     return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
1031 }
1032
1033 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1034 {
1035     return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
1036 }
1037
1038 #if PLATFORM(IOS)
1039 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1040 {
1041     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
1042 }
1043
1044 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1045 {
1046     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
1047 }
1048 #endif // PLATFORM(IOS)
1049
1050 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1051 {
1052     if (!exception || !context)
1053         return;
1054
1055     JSC::ExecState* execState = toJS(context);
1056     JSLockHolder lock(execState);
1057
1058     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1059     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1060     if (!toJSDOMWindow(globalObject->vm(), globalObject))
1061         return;
1062
1063     reportException(execState, toJS(execState, exception));
1064 }
1065
1066 static void WebKitInitializeApplicationStatisticsStoragePathIfNecessary()
1067 {
1068     static BOOL initialized = NO;
1069     if (initialized)
1070         return;
1071     
1072     resourceLoadStatisticsStore = &WebCore::ResourceLoadStatisticsStore::create().leakRef();
1073     ResourceLoadObserver::sharedObserver().setStatisticsStore(*resourceLoadStatisticsStore);
1074     
1075     initialized = YES;
1076 }
1077
1078 static bool shouldEnableLoadDeferring()
1079 {
1080 #if PLATFORM(IOS)
1081     return true;
1082 #else
1083     return !MacApplication::isAdobeInstaller();
1084 #endif
1085 }
1086
1087 static bool shouldRestrictWindowFocus()
1088 {
1089 #if PLATFORM(IOS)
1090     return true;
1091 #else
1092     return !MacApplication::isHRBlock();
1093 #endif
1094 }
1095
1096 - (void)_dispatchPendingLoadRequests
1097 {
1098     webResourceLoadScheduler().servePendingRequests();
1099 }
1100
1101 #if !PLATFORM(IOS)
1102
1103 - (void)_registerDraggedTypes
1104 {
1105     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1106     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1107     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1108     [types addObjectsFromArray:URLTypes];
1109     [types addObject:[WebHTMLView _dummyPasteboardType]];
1110     [self registerForDraggedTypes:[types allObjects]];
1111     [types release];
1112 }
1113
1114 static bool needsOutlookQuirksScript()
1115 {
1116     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1117         && MacApplication::isMicrosoftOutlook();
1118     return isOutlookNeedingQuirksScript;
1119 }
1120
1121 static NSString *leakOutlookQuirksUserScriptContents()
1122 {
1123     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1124     NSStringEncoding encoding;
1125     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1126 }
1127
1128 -(void)_injectOutlookQuirksScript
1129 {
1130     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1131     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1132
1133 }
1134 #endif
1135
1136 static bool shouldRespectPriorityInCSSAttributeSetters()
1137 {
1138 #if PLATFORM(IOS)
1139     static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1140         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
1141     return isStanzaNeedingAttributeSetterQuirk;
1142 #else
1143     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1144         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1145     return isIAdProducerNeedingAttributeSetterQuirk;
1146 #endif
1147 }
1148
1149 #if PLATFORM(IOS)
1150 static bool shouldTransformsAffectOverflow()
1151 {
1152     static bool shouldTransformsAffectOverflow = !IOSApplication::isOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
1153     return shouldTransformsAffectOverflow;
1154 }
1155
1156 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
1157 {
1158     static bool shouldDispatchJavaScriptWindowOnErrorEvents = !IOSApplication::isFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
1159     return shouldDispatchJavaScriptWindowOnErrorEvents;
1160 }
1161
1162 static bool isInternalInstall()
1163 {
1164     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1165     return isInternal;
1166 }
1167
1168 static bool didOneTimeInitialization = false;
1169 #endif
1170
1171 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1172 {
1173 #if PLATFORM(IOS)
1174     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1175 #else
1176     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1177         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1178 #endif
1179     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1180 }
1181
1182 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1183 {
1184     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1185     return shouldAllowDisplayAndRunningOfInsecureContent;
1186 }
1187
1188 static bool shouldAllowPictureInPictureMediaPlayback()
1189 {
1190 #if PLATFORM(IOS)
1191     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1192     return shouldAllowPictureInPictureMediaPlayback;
1193 #else
1194     return false;
1195 #endif
1196 }
1197
1198 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1199 {
1200 #if PLATFORM(IOS)
1201     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1202     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1203 #else
1204     return false;
1205 #endif
1206 }
1207
1208 static bool shouldAllowWindowOpenWithoutUserGesture()
1209 {
1210 #if PLATFORM(IOS)
1211     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1212     return shouldAllowWindowOpenWithoutUserGesture;
1213 #else
1214     return false;
1215 #endif
1216 }
1217
1218 static bool shouldConvertInvalidURLsToBlank()
1219 {
1220 #if PLATFORM(IOS)
1221     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1222 #elif PLATFORM(MAC)
1223     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1224 #else
1225     static bool shouldConvertInvalidURLsToBlank = true;
1226 #endif
1227
1228     return shouldConvertInvalidURLsToBlank;
1229 }
1230
1231 static bool shouldRequireUserGestureToLoadVideo()
1232 {
1233 #if PLATFORM(IOS)
1234     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1235     return shouldRequireUserGestureToLoadVideo;
1236 #else
1237     return true;
1238 #endif
1239 }
1240
1241 #if ENABLE(GAMEPAD)
1242 static void WebKitInitializeGamepadProviderIfNecessary()
1243 {
1244     static bool initialized = false;
1245     if (initialized)
1246         return;
1247
1248 #if PLATFORM(MAC)
1249     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1250 #else
1251     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1252 #endif
1253
1254     initialized = true;
1255 }
1256 #endif
1257
1258 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1259 {
1260     WebCoreThreadViolationCheckRoundTwo();
1261
1262 #ifndef NDEBUG
1263     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1264 #endif
1265     
1266     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1267     [standardPreferences willAddToWebView];
1268
1269     _private->preferences = [standardPreferences retain];
1270     _private->mainFrameDocumentReady = NO;
1271     _private->drawsBackground = YES;
1272 #if !PLATFORM(IOS)
1273     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1274 #else
1275     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1276 #endif
1277     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
1278
1279 #if PLATFORM(MAC)
1280     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1281 #endif
1282
1283     NSRect f = [self frame];
1284     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1285     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1286     [self addSubview:frameView];
1287     [frameView release];
1288
1289 #if PLATFORM(MAC)
1290     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1291         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1292         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1293         [recognizer setDelegate:_private->immediateActionController];
1294         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1295     }
1296 #endif
1297
1298     [self updateTouchBar];
1299
1300 #if !PLATFORM(IOS)
1301     static bool didOneTimeInitialization = false;
1302 #endif
1303     if (!didOneTimeInitialization) {
1304 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1305         WebKitInitializeLogChannelsIfNecessary();
1306         WebCore::initializeLogChannelsIfNecessary();
1307 #endif
1308
1309         // Initialize our platform strategies first before invoking the rest
1310         // of the initialization code which may depend on the strategies.
1311         WebPlatformStrategies::initializeIfNecessary();
1312
1313         initializeDOMWrapperHooks();
1314
1315 #if PLATFORM(IOS)
1316         // Set the WebSQLiteDatabaseTrackerClient.
1317         SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1318
1319         if ([standardPreferences databasesEnabled])
1320 #endif
1321         [WebDatabaseManager sharedWebDatabaseManager];
1322
1323 #if PLATFORM(IOS)        
1324         if ([standardPreferences storageTrackerEnabled])
1325 #endif
1326         WebKitInitializeStorageIfNecessary();
1327
1328         WebKitInitializeApplicationStatisticsStoragePathIfNecessary();
1329
1330 #if ENABLE(GAMEPAD)
1331         WebKitInitializeGamepadProviderIfNecessary();
1332 #endif
1333         
1334         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1335
1336 #if PLATFORM(IOS)
1337         if (IOSApplication::isMobileSafari())
1338             Settings::setShouldManageAudioSessionCategory(true);
1339 #endif
1340
1341         didOneTimeInitialization = true;
1342     }
1343
1344     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1345     _private->group->addWebView(self);
1346
1347     PageConfiguration pageConfiguration(
1348         makeUniqueRef<WebEditorClient>(self),
1349         SocketProvider::create(),
1350         makeUniqueRef<WebCore::LibWebRTCProvider>()
1351     );
1352 #if !PLATFORM(IOS)
1353     pageConfiguration.chromeClient = new WebChromeClient(self);
1354     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1355     // FIXME: We should enable this on iOS as well.
1356     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1357 #if ENABLE(DRAG_SUPPORT)
1358     pageConfiguration.dragClient = new WebDragClient(self);
1359 #endif
1360     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1361 #else
1362     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1363     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1364 #endif
1365
1366     pageConfiguration.backForwardClient = BackForwardList::create(self);
1367
1368 #if ENABLE(APPLE_PAY)
1369     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1370 #endif
1371
1372     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1373     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1374     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1375     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1376     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1377     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1378     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1379     pageConfiguration.userContentProvider = &_private->group->userContentController();
1380     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1381     _private->page = new Page(WTFMove(pageConfiguration));
1382
1383     _private->page->setGroupName(groupName);
1384
1385 #if ENABLE(GEOLOCATION)
1386     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
1387 #endif
1388 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
1389     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1390 #endif
1391 #if ENABLE(DEVICE_ORIENTATION)
1392 #if !PLATFORM(IOS)
1393     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1394 #endif
1395 #endif
1396 #if ENABLE(MEDIA_STREAM)
1397     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1398 #endif
1399
1400 #if ENABLE(REMOTE_INSPECTOR)
1401     _private->page->setRemoteInspectionAllowed(true);
1402 #endif
1403
1404     _private->page->setCanStartMedia([self window]);
1405     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1406     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1407
1408 #if !PLATFORM(IOS)
1409     if (needsOutlookQuirksScript()) {
1410         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1411         [self _injectOutlookQuirksScript];
1412     }
1413 #endif
1414
1415 #if PLATFORM(IOS)
1416     // Preserve the behavior we had before <rdar://problem/7580867>
1417     // by enforcing a 5MB limit for session storage.
1418     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1419
1420     [self _updateScreenScaleFromWindow];
1421     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1422     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1423     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1424 #endif
1425
1426     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1427         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1428
1429     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1430
1431 #if PLATFORM(IOS)
1432     NSRunLoop *runLoop = WebThreadNSRunLoop();
1433 #else
1434     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1435 #endif
1436
1437     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1438         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1439     else
1440         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1441
1442     [self _addToAllWebViewsSet];
1443     
1444     // If there's already a next key view (e.g., from a nib), wire it up to our
1445     // contained frame view. In any case, wire our next key view up to the our
1446     // contained frame view. This works together with our becomeFirstResponder 
1447     // and setNextKeyView overrides.
1448     NSView *nextKeyView = [self nextKeyView];
1449     if (nextKeyView && nextKeyView != frameView)
1450         [frameView setNextKeyView:nextKeyView];
1451     [super setNextKeyView:frameView];
1452
1453     if ([[self class] shouldIncludeInWebKitStatistics])
1454         ++WebViewCount;
1455
1456 #if !PLATFORM(IOS)
1457     [self _registerDraggedTypes];
1458 #endif
1459
1460     [self _setIsVisible:[self _isViewVisible]];
1461
1462     WebPreferences *prefs = [self preferences];
1463     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1464                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1465
1466 #if !PLATFORM(IOS)
1467     [self _preferencesChanged:[self preferences]];
1468     [[self preferences] _postPreferencesChangedAPINotification];
1469 #else
1470     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1471     // and prefs need to be changed synchronously <rdar://problem/5841558>
1472     [self _preferencesChanged:prefs];
1473     _private->page->settings().setFontFallbackPrefersPictographs(true);
1474 #endif
1475
1476     WebInstallMemoryPressureHandler();
1477
1478     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1479         // Originally, we allowed all local loads.
1480         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1481     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1482         // Later, we allowed local loads for local URLs and documents loaded
1483         // with substitute data.
1484         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1485     }
1486
1487 #if PLATFORM(MAC)
1488     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1489         ResourceHandle::forceContentSniffing();
1490
1491     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1492 #endif
1493
1494     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1495 }
1496
1497 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1498 {
1499     self = [super initWithFrame:f];
1500     if (!self)
1501         return nil;
1502
1503 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1504     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1505     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1506     // need for Safari to unset it to prevent it from being passed to applications it launches.
1507     // Unsetting it when a WebView is first created is as good a place as any.
1508     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1509     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1510         unsetenv("DYLD_FRAMEWORK_PATH");
1511         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1512     }
1513 #endif
1514
1515     _private = [[WebViewPrivate alloc] init];
1516     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1517     [self setMaintainsBackForwardList: YES];
1518     return self;
1519 }
1520
1521 - (void)_viewWillDrawInternal
1522 {
1523     Frame* frame = [self _mainCoreFrame];
1524     if (frame && frame->view())
1525         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1526 }
1527
1528 + (NSArray *)_supportedMIMETypes
1529 {
1530     // Load the plug-in DB allowing plug-ins to install types.
1531     [WebPluginDatabase sharedDatabase];
1532     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1533 }
1534
1535 #if !PLATFORM(IOS)
1536 + (NSArray *)_supportedFileExtensions
1537 {
1538     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1539     NSArray *MIMETypes = [self _supportedMIMETypes];
1540     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1541     NSString *MIMEType;
1542     while ((MIMEType = [enumerator nextObject]) != nil) {
1543         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1544         if (extensionsForType) {
1545             [extensions addObjectsFromArray:extensionsForType];
1546         }
1547     }
1548     NSArray *uniqueExtensions = [extensions allObjects];
1549     [extensions release];
1550     return uniqueExtensions;
1551 }
1552 #endif
1553
1554 #if PLATFORM(IOS)
1555 + (void)enableWebThread
1556 {
1557     static BOOL isWebThreadEnabled = NO;
1558     if (!isWebThreadEnabled) {
1559         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1560         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1561         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1562         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1563         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1564         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1565         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1566         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1567         WebCoreObjCDeallocOnWebThread([WebView class]);
1568         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1569         if (IOSApplication::isTheEconomistOnIphone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1570             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1571         WebThreadEnable();
1572         isWebThreadEnabled = YES;
1573     }
1574 }
1575
1576 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1577 {
1578     self = [super initWithFrame:frame];
1579     if (!self)
1580         return nil;
1581     
1582     _private = [[WebViewPrivate alloc] init];
1583     
1584 #ifndef NDEBUG
1585     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1586 #endif
1587     
1588     if (!preferences)
1589         preferences = [WebPreferences standardPreferences];
1590     [preferences willAddToWebView];
1591     
1592     _private->preferences = [preferences retain];
1593     _private->mainFrameDocumentReady = NO;
1594     _private->drawsBackground = YES;
1595     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1596
1597     WebFrameView *frameView = nil;
1598     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1599     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1600     [self addSubview:frameView];
1601     [frameView release];
1602
1603     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1604     _private->group->addWebView(self);
1605
1606     PageConfiguration pageConfiguration(
1607         makeUniqueRef<WebEditorClient>(self),
1608         SocketProvider::create(),
1609         makeUniqueRef<WebCore::LibWebRTCProvider>()
1610     );
1611     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1612 #if ENABLE(DRAG_SUPPORT)
1613     pageConfiguration.dragClient = new WebDragClient(self);
1614 #endif
1615
1616 #if ENABLE(APPLE_PAY)
1617     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1618 #endif
1619
1620     pageConfiguration.backForwardClient = BackForwardList::create(self);
1621     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1622     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1623     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1624     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1625     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1626     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1627     pageConfiguration.userContentProvider = &_private->group->userContentController();
1628     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1629     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1630
1631     _private->page = new Page(WTFMove(pageConfiguration));
1632     
1633     [self setSmartInsertDeleteEnabled:YES];
1634     
1635     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1636     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1637     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1638     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1639     _private->page->settings().setMinimumLogicalFontSize(9);
1640     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1641     _private->page->settings().setDefaultFixedFontSize(13);
1642     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1643     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1644     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1645     
1646     _private->page->settings().setFontFallbackPrefersPictographs(true);
1647     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1648     
1649     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1650     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1651     
1652     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1653     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1654
1655     // This is a workaround for <rdar://problem/21309911>.
1656     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1657
1658     _private->page->setGroupName(groupName);
1659
1660 #if ENABLE(REMOTE_INSPECTOR)
1661     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1662 #endif
1663     
1664     [self _updateScreenScaleFromWindow];
1665     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1666     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1667
1668     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1669     
1670     [self _addToAllWebViewsSet];
1671     
1672     ++WebViewCount;
1673     
1674     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1675     
1676     return self;
1677 }
1678
1679 + (void)_handleMemoryWarning
1680 {
1681     ASSERT(WebThreadIsCurrent());
1682     WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1683
1684     // Always peform the following.
1685     [WebView purgeInactiveFontData];
1686
1687     // Only perform the remaining if a non-simple document was created.
1688     if (!didOneTimeInitialization)
1689         return;
1690
1691     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1692
1693     [WebStorageManager closeIdleLocalStorageDatabases];
1694     StorageThread::releaseFastMallocFreeMemoryInAllThreads();
1695
1696     [WebView _releaseMemoryNow];
1697 }
1698
1699 + (void)registerForMemoryNotifications
1700 {
1701     BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::IOSApplication::isMobileSafari();
1702
1703     MemoryPressureHandler::singleton().installMemoryReleaseBlock(^{
1704         [WebView _handleMemoryWarning];
1705     }, shouldAutoClearPressureOnMemoryRelease);
1706
1707     static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, DISPATCH_MEMORYPRESSURE_WARN, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1708     dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1709         // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1710         MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1711     });
1712
1713     dispatch_resume(memoryNotificationEventSource);
1714
1715     if (!shouldAutoClearPressureOnMemoryRelease) {
1716         // Listen to memory status notification to reset the memory pressure flag.
1717         static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE,
1718                                                                                     0,
1719                                                                                     DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_NORMAL,
1720                                                                                     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1721         dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1722             unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1723             if (currentStatus == DISPATCH_MEMORYPRESSURE_NORMAL)
1724                 MemoryPressureHandler::singleton().clearMemoryPressure();
1725             else if (currentStatus == DISPATCH_MEMORYPRESSURE_WARN)
1726                 MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1727         });
1728
1729         dispatch_resume(memoryStatusEventSource);
1730     }
1731 }
1732
1733 + (void)_releaseMemoryNow
1734 {
1735     ASSERT(WebThreadIsCurrent());
1736     [WebView discardAllCompiledCode];
1737     [WebView garbageCollectNow];
1738     [WebView purgeInactiveFontData];
1739     [WebView drainLayerPool];
1740     [WebCache emptyInMemoryResources];
1741     [WebView releaseFastMallocMemoryOnCurrentThread];
1742
1743     dispatch_async(dispatch_get_main_queue(), ^{
1744         // Clear the main thread's TCMalloc thread cache.
1745         [WebView releaseFastMallocMemoryOnCurrentThread];
1746     });
1747 }
1748
1749 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1750 {
1751     Frame* frame = [self _mainCoreFrame];
1752     if (frame)
1753         frame->loader().history().replaceCurrentItem(core(item));
1754 }
1755
1756 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1757 {
1758     WebThreadRun(^{
1759         [WebView _releaseMemoryNow];
1760         dispatch_async(dispatch_get_main_queue(), handler);
1761     });
1762 }
1763
1764 + (void)releaseFastMallocMemoryOnCurrentThread
1765 {
1766     WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1767     WTF::releaseFastMallocFreeMemory();
1768 }
1769
1770 + (void)garbageCollectNow
1771 {
1772     ASSERT(WebThreadIsCurrent());
1773     WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1774     WebCore::GCController::singleton().garbageCollectNow();
1775 }
1776
1777 + (void)purgeInactiveFontData
1778 {
1779     ASSERT(WebThreadIsCurrent());
1780     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1781     FontCache::singleton().purgeInactiveFontData();
1782 }
1783
1784 + (void)drainLayerPool
1785 {
1786     ASSERT(WebThreadIsCurrent());
1787     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1788     WebCore::LegacyTileCache::drainLayerPool();
1789 }
1790
1791 + (void)discardAllCompiledCode
1792 {
1793     ASSERT(WebThreadIsCurrent());
1794     WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1795     WebCore::GCController::singleton().deleteAllCode(PreventCollectionAndDeleteAllCode);
1796 }
1797
1798 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1799 {
1800     return WebCore::isCharacterSmartReplaceExempt(character, b);
1801 }
1802
1803 - (void)updateLayoutIgnorePendingStyleSheets
1804 {
1805     WebThreadRun(^{
1806         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1807             Document *document = frame->document();
1808             if (document)
1809                 document->updateLayoutIgnorePendingStylesheets();
1810         }
1811     });
1812 }
1813 #endif // PLATFORM(IOS)
1814
1815 static NSMutableSet *knownPluginMIMETypes()
1816 {
1817     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1818     
1819     return mimeTypes;
1820 }
1821
1822 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1823 {
1824     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1825     [knownPluginMIMETypes() addObject:MIMEType];
1826 }
1827
1828 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1829 {
1830     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1831     [knownPluginMIMETypes() removeObject:MIMEType];
1832 }
1833
1834 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1835 {
1836     MIMEType = [MIMEType lowercaseString];
1837     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1838     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1839
1840 #if PLATFORM(IOS)
1841 #define WebPDFView ([WebView _getPDFViewClass])
1842 #endif
1843     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1844 #if PLATFORM(IOS)
1845 #undef WebPDFView
1846 #endif
1847         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1848
1849         if (allowPlugins) {
1850             // Load the plug-in DB allowing plug-ins to install types.
1851             [WebPluginDatabase sharedDatabase];
1852         }
1853
1854         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1855         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1856         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1857     }
1858     
1859     if (viewClass && repClass) {
1860         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1861             // Special-case WebHTMLView for text types that shouldn't be shown.
1862             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1863                 return NO;
1864
1865             // If the MIME type is a known plug-in we might not want to load it.
1866             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1867                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1868                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1869                 
1870                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1871                 if (!isSupportedByWebKit)
1872                     return NO;
1873             }
1874         }
1875         if (vClass)
1876             *vClass = viewClass;
1877         if (rClass)
1878             *rClass = repClass;
1879         return YES;
1880     }
1881     
1882     return NO;
1883 }
1884
1885 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1886 {
1887     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1888         return YES;
1889 #if !PLATFORM(IOS)
1890     if (_private->pluginDatabase) {
1891         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1892         if (pluginPackage) {
1893             if (vClass)
1894                 *vClass = [WebHTMLView class];
1895             if (rClass)
1896                 *rClass = [WebHTMLRepresentation class];
1897             return YES;
1898         }
1899     }
1900 #endif
1901     return NO;
1902 }
1903
1904 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1905 {
1906     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
1907 }
1908
1909 + (BOOL)canCloseAllWebViews
1910 {
1911     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1912 }
1913
1914 + (void)closeAllWebViews
1915 {
1916     DOMWindow::dispatchAllPendingUnloadEvents();
1917
1918     // This will close the WebViews in a random order. Change this if close order is important.
1919     // Make a new set to avoid mutating the set we are enumerating.
1920     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1921     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1922     while (WebView *webView = [enumerator nextObject])
1923         [webView close];
1924 }
1925
1926 + (BOOL)canShowFile:(NSString *)path
1927 {
1928     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1929 }
1930
1931 #if !PLATFORM(IOS)
1932 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1933 {
1934     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1935 }
1936 #endif
1937
1938 - (BOOL)_isClosed
1939 {
1940     return !_private || _private->closed;
1941 }
1942
1943 #if PLATFORM(IOS)
1944
1945 - (void)_dispatchUnloadEvent
1946 {
1947     WebThreadRun(^{
1948         WebFrame *mainFrame = [self mainFrame];
1949         Frame *coreMainFrame = core(mainFrame);
1950         if (coreMainFrame) {
1951             Document *document = coreMainFrame->document();
1952             if (document)
1953                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1954         }
1955     });
1956 }
1957
1958 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1959 {
1960     auto* mainFrame = [self _mainCoreFrame];
1961     if (!mainFrame)
1962         return nil;
1963     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
1964     if (!editingStyle)
1965         return nil;
1966     auto* style = editingStyle->style();
1967     if (!style)
1968         return nil;
1969     return kit(style->ensureCSSStyleDeclaration());
1970 }
1971
1972 - (NSUInteger)_renderTreeSize
1973 {
1974     if (!_private->page)
1975         return 0;
1976     return _private->page->renderTreeSize();
1977 }
1978
1979 - (void)_dispatchTileDidDraw:(CALayer*)tile
1980 {
1981     id mailDelegate = [self _webMailDelegate];
1982     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1983         [mailDelegate _webthread_webView:self tileDidDraw:tile];
1984         return;
1985     }
1986
1987 #pragma clang diagnostic push
1988 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1989     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1990         return;
1991 #pragma clang diagnostic pop
1992
1993     WebThreadLock();
1994
1995     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1996 }
1997
1998 - (void)_willStartScrollingOrZooming
1999 {
2000     // Pause timers during top level interaction
2001     if (_private->mainViewIsScrollingOrZooming)
2002         return;
2003     _private->mainViewIsScrollingOrZooming = YES;
2004
2005     [self hideFormValidationMessage];
2006
2007     // This suspends active DOM objects like timers, but not media.
2008     [[self mainFrame] setTimeoutsPaused:YES];
2009
2010     // This defers loading callbacks only.
2011     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2012     [self setDefersCallbacks:YES];
2013 }
2014
2015 - (void)_didFinishScrollingOrZooming
2016 {
2017     if (!_private->mainViewIsScrollingOrZooming)
2018         return;
2019     _private->mainViewIsScrollingOrZooming = NO;
2020     [self setDefersCallbacks:NO];
2021     [[self mainFrame] setTimeoutsPaused:NO];
2022     if (FrameView* view = [self _mainCoreFrame]->view())
2023         view->resumeVisibleImageAnimationsIncludingSubframes();
2024 }
2025
2026 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2027 {
2028     if (suspend)
2029         webResourceLoadScheduler().suspendPendingRequests();
2030     else
2031         webResourceLoadScheduler().resumePendingRequests();
2032 }
2033
2034 + (void)_setAllowCookies:(BOOL)allow
2035 {
2036     ResourceRequestBase::setDefaultAllowCookies(allow);
2037 }
2038
2039 + (BOOL)_allowCookies
2040 {
2041     return ResourceRequestBase::defaultAllowCookies();
2042 }
2043
2044 + (BOOL)_isUnderMemoryPressure
2045 {
2046     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2047 }
2048
2049 + (void)_clearMemoryPressure
2050 {
2051     MemoryPressureHandler::singleton().clearMemoryPressure();
2052 }
2053
2054 + (BOOL)_shouldWaitForMemoryClearMessage
2055 {
2056     return MemoryPressureHandler::singleton().shouldWaitForMemoryClearMessage();
2057 }
2058
2059 #endif // PLATFORM(IOS)
2060
2061 - (void)_closePluginDatabases
2062 {
2063     pluginDatabaseClientCount--;
2064
2065     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2066
2067 #if !PLATFORM(IOS)
2068     // Unload the WebView local plug-in database. 
2069     if (_private->pluginDatabase) {
2070         [_private->pluginDatabase destroyAllPluginInstanceViews];
2071         [_private->pluginDatabase close];
2072         [_private->pluginDatabase release];
2073         _private->pluginDatabase = nil;
2074     }
2075 #endif
2076     
2077     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2078     if (!pluginDatabaseClientCount && applicationIsTerminating)
2079         [WebPluginDatabase closeSharedDatabase];
2080 }
2081
2082 - (void)_closeWithFastTeardown 
2083 {
2084 #ifndef NDEBUG
2085     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2086 #endif
2087
2088 #if !PLATFORM(IOS)
2089     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2090 #endif
2091     [[NSNotificationCenter defaultCenter] removeObserver:self];
2092
2093     [self _closePluginDatabases];
2094 }
2095
2096 static bool fastDocumentTeardownEnabled()
2097 {
2098 #ifdef NDEBUG
2099     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2100 #else
2101     static bool initialized = false;
2102     static bool enabled = false;
2103     if (!initialized) {
2104         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2105         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2106         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2107         if (setting)
2108             enabled = ![setting boolValue];
2109         initialized = true;
2110     }
2111 #endif
2112     return enabled;
2113 }
2114
2115 // _close is here only for backward compatibility; clients and subclasses should use
2116 // public method -close instead.
2117 - (void)_close
2118 {
2119 #if PLATFORM(IOS)
2120     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2121     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2122
2123     [self _clearDelegates];
2124
2125     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2126     WebThreadRun(^{
2127 #endif            
2128
2129     if (!_private || _private->closed)
2130         return;
2131
2132     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2133
2134     _private->closed = YES;
2135     [self _removeFromAllWebViewsSet];
2136
2137 #ifndef NDEBUG
2138     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2139 #endif
2140
2141     // To quit the apps fast we skip document teardown, except plugins
2142     // need to be destroyed and unloaded.
2143     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2144         [self _closeWithFastTeardown];
2145         return;
2146     }
2147
2148 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2149     [self _exitVideoFullscreen];
2150 #endif
2151
2152 #if PLATFORM(IOS)
2153     _private->closing = YES;
2154 #endif
2155
2156     if (Frame* mainFrame = [self _mainCoreFrame])
2157         mainFrame->loader().detachFromParent();
2158
2159     [self setHostWindow:nil];
2160
2161 #if !PLATFORM(IOS)
2162     [self setDownloadDelegate:nil];
2163     [self setEditingDelegate:nil];
2164     [self setFrameLoadDelegate:nil];
2165     [self setPolicyDelegate:nil];
2166     [self setResourceLoadDelegate:nil];
2167     [self setScriptDebugDelegate:nil];
2168     [self setUIDelegate:nil];
2169
2170     [_private->inspector inspectedWebViewClosed];
2171 #endif
2172 #if PLATFORM(MAC)
2173     [_private->immediateActionController webViewClosed];
2174 #endif
2175
2176 #if !PLATFORM(IOS)
2177     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2178     [self removeDragCaret];
2179 #endif
2180
2181     _private->group->removeWebView(self);
2182
2183     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2184     // all the plug-ins in the page cache to break any retain cycles.
2185     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2186     Page* page = _private->page;
2187     _private->page = nullptr;
2188     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2189
2190 #if !PLATFORM(IOS)
2191     if (_private->hasSpellCheckerDocumentTag) {
2192         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2193         _private->hasSpellCheckerDocumentTag = NO;
2194     }
2195 #endif
2196
2197     if (_private->layerFlushController) {
2198         _private->layerFlushController->invalidate();
2199         _private->layerFlushController = nullptr;
2200     }
2201
2202     [[self _notificationProvider] unregisterWebView:self];
2203
2204 #if !PLATFORM(IOS)
2205     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2206 #endif
2207     [[NSNotificationCenter defaultCenter] removeObserver:self];
2208
2209     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2210
2211     WebPreferences *preferences = _private->preferences;
2212     _private->preferences = nil;
2213     [preferences didRemoveFromWebView];
2214     [preferences release];
2215
2216     [self _closePluginDatabases];
2217
2218 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2219     if (_private->m_playbackTargetPicker) {
2220         _private->m_playbackTargetPicker->invalidate();
2221         _private->m_playbackTargetPicker = nullptr;
2222     }
2223 #endif
2224
2225 #ifndef NDEBUG
2226     // Need this to make leak messages accurate.
2227     if (applicationIsTerminating) {
2228         WebCore::GCController::singleton().garbageCollectNow();
2229         [WebCache setDisabled:YES];
2230     }
2231 #endif
2232 #if PLATFORM(IOS)
2233     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2234     });
2235 #endif            
2236 }
2237
2238 // Indicates if the WebView is in the midst of a user gesture.
2239 - (BOOL)_isProcessingUserGesture
2240 {
2241     return ScriptController::processingUserGesture();
2242 }
2243
2244 + (NSString *)_MIMETypeForFile:(NSString *)path
2245 {
2246 #if !PLATFORM(IOS)
2247     NSString *extension = [path pathExtension];
2248 #endif
2249     NSString *MIMEType = nil;
2250
2251 #if !PLATFORM(IOS)
2252     // Get the MIME type from the extension.
2253     if ([extension length] != 0) {
2254         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2255     }
2256 #endif
2257
2258     // If we can't get a known MIME type from the extension, sniff.
2259     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2260         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2261         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2262         [handle closeFile];
2263         if ([data length] != 0) {
2264             MIMEType = [data _webkit_guessedMIMEType];
2265         }
2266         if ([MIMEType length] == 0) {
2267             MIMEType = @"application/octet-stream";
2268         }
2269     }
2270
2271     return MIMEType;
2272 }
2273
2274 - (WebDownload *)_downloadURL:(NSURL *)URL
2275 {
2276     ASSERT(URL);
2277     
2278     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2279     WebDownload *download = [WebDownload _downloadWithRequest:request
2280                                                      delegate:_private->downloadDelegate
2281                                                     directory:nil];
2282     [request release];
2283     
2284     return download;
2285 }
2286
2287 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2288 {
2289     NSDictionary *features = [[NSDictionary alloc] init];
2290     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2291                                             createWebViewWithRequest:nil
2292                                                       windowFeatures:features];
2293     [features release];
2294     if (!newWindowWebView)
2295         return nil;
2296
2297     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2298     return newWindowWebView;
2299 }
2300
2301 - (WebInspector *)inspector
2302 {
2303     if (!_private->inspector)
2304         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2305     return _private->inspector;
2306 }
2307
2308 #if ENABLE(REMOTE_INSPECTOR)
2309 + (void)_enableRemoteInspector
2310 {
2311     RemoteInspector::singleton().start();
2312 }
2313
2314 + (void)_disableRemoteInspector
2315 {
2316     RemoteInspector::singleton().stop();
2317 }
2318
2319 + (void)_disableAutoStartRemoteInspector
2320 {
2321     RemoteInspector::startDisabled();
2322 }
2323
2324 + (BOOL)_isRemoteInspectorEnabled
2325 {
2326     return RemoteInspector::singleton().enabled();
2327 }
2328
2329 + (BOOL)_hasRemoteInspectorSession
2330 {
2331     return RemoteInspector::singleton().hasActiveDebugSession();
2332 }
2333
2334 - (BOOL)allowsRemoteInspection
2335 {
2336     return _private->page->remoteInspectionAllowed();
2337 }
2338
2339 - (void)setAllowsRemoteInspection:(BOOL)allow
2340 {
2341     _private->page->setRemoteInspectionAllowed(allow);
2342 }
2343
2344 - (void)setShowingInspectorIndication:(BOOL)showing
2345 {
2346 #if PLATFORM(IOS)
2347     ASSERT(WebThreadIsLocked());
2348
2349     if (showing) {
2350         if (!_private->indicateLayer) {
2351             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2352             [_private->indicateLayer setNeedsLayout];
2353             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2354         }
2355     } else {
2356         [_private->indicateLayer removeFromSuperlayer];
2357         [_private->indicateLayer release];
2358         _private->indicateLayer = nil;
2359     }
2360 #else
2361     // Implemented in WebCore::InspectorOverlay.
2362 #endif
2363 }
2364
2365 #if PLATFORM(IOS)
2366 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2367 {
2368     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2369     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2370 }
2371 #endif // PLATFORM(IOS)
2372 #endif // ENABLE(REMOTE_INSPECTOR)
2373
2374 - (WebCore::Page*)page
2375 {
2376     return _private->page;
2377 }
2378
2379 #if !PLATFORM(IOS)
2380 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2381 {
2382     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2383     NSArray *menuItems = defaultMenuItems;
2384
2385     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2386     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2387     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2388     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2389         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2390         if (!menuItems)
2391             return nil;
2392     }
2393
2394     unsigned count = [menuItems count];
2395     if (!count)
2396         return nil;
2397
2398     NSMenu *menu = [[NSMenu alloc] init];
2399     for (unsigned i = 0; i < count; i++)
2400         [menu addItem:[menuItems objectAtIndex:i]];
2401
2402     return [menu autorelease];
2403 }
2404 #endif
2405
2406 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2407 {
2408     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2409     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2410     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2411     if (!dictionary)
2412         return;
2413     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2414 }
2415
2416 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2417 {
2418     if (!_private->page)
2419         return;
2420     
2421     if (!otherView->_private->page)
2422         return;
2423     
2424     // It turns out the right combination of behavior is done with the back/forward load
2425     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2426     // in the back forward list, and go to the current one.
2427
2428     BackForwardController& backForward = _private->page->backForward();
2429     ASSERT(!backForward.currentItem()); // destination list should be empty
2430
2431     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2432     if (!otherBackForward.currentItem())
2433         return; // empty back forward list, bail
2434     
2435     HistoryItem* newItemToGoTo = nullptr;
2436
2437     int lastItemIndex = otherBackForward.forwardCount();
2438     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2439         if (i == 0) {
2440             // If this item is showing , save away its current scroll and form state,
2441             // since that might have changed since loading and it is normally not saved
2442             // until we leave that page.
2443             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2444         }
2445         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2446         if (i == 0) 
2447             newItemToGoTo = newItem.ptr();
2448         backForward.client()->addItem(WTFMove(newItem));
2449     }
2450
2451     ASSERT(newItemToGoTo);
2452     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward);
2453 }
2454
2455 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2456 {
2457     _private->formDelegate = delegate;
2458 #if PLATFORM(IOS)
2459     [_private->formDelegateForwarder clearTarget];
2460     [_private->formDelegateForwarder release];
2461     _private->formDelegateForwarder = nil;
2462 #endif
2463 }
2464
2465 - (id<WebFormDelegate>)_formDelegate
2466 {
2467     return _private->formDelegate;
2468 }
2469
2470 #if PLATFORM(IOS)
2471 - (id)_formDelegateForwarder
2472 {
2473     if (_private->closing)
2474         return nil;
2475
2476     if (!_private->formDelegateForwarder)
2477         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2478     return _private->formDelegateForwarder;
2479 }
2480
2481 - (id)_formDelegateForSelector:(SEL)selector
2482 {
2483     id delegate = self->_private->formDelegate;
2484     if ([delegate respondsToSelector:selector])
2485         return delegate;
2486
2487     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2488     if ([delegate respondsToSelector:selector])
2489         return delegate;
2490
2491     return nil;
2492 }
2493 #endif
2494
2495 #if !PLATFORM(IOS)
2496 - (BOOL)_needsAdobeFrameReloadingQuirk
2497 {
2498     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2499         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2500         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2501         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2502         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2503         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2504         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2505         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2506         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2507         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2508
2509     return needsQuirk;
2510 }
2511
2512 - (BOOL)_needsLinkElementTextCSSQuirk
2513 {
2514     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2515         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2516     return needsQuirk;
2517 }
2518
2519 - (BOOL)_needsIsLoadingInAPISenseQuirk
2520 {
2521     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2522     
2523     return needsQuirk;
2524 }
2525
2526 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2527 {
2528     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2529     return needsQuirks;
2530 }
2531
2532 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2533 {
2534     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2535     return needsQuirk;
2536 }
2537
2538 static bool needsSelfRetainWhileLoadingQuirk()
2539 {
2540     static bool needsQuirk = MacApplication::isAperture();
2541     return needsQuirk;
2542 }
2543 #endif // !PLATFORM(IOS)
2544
2545 - (BOOL)_needsPreHTML5ParserQuirks
2546 {    
2547 #if !PLATFORM(IOS)
2548     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2549     // with the new HTML5 parser. If these applications were linked against a
2550     // version of WebKit prior to the introduction of the HTML5 parser, enable
2551     // parser quirks to maintain compatibility. For details, see 
2552     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2553     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2554     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2555         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2556     
2557     // Mail.app must continue to display HTML email that contains quirky markup.
2558     static bool isAppleMail = MacApplication::isAppleMail();
2559
2560     return isApplicationNeedingParserQuirks
2561         || isAppleMail
2562 #if ENABLE(DASHBOARD_SUPPORT)
2563         // Pre-HTML5 parser quirks are required to remain compatible with many
2564         // Dashboard widgets. See <rdar://problem/8175982>.
2565         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2566 #endif
2567         || [[self preferences] usePreHTML5ParserQuirks];
2568 #else
2569     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && IOSApplication::isDaijisenDictionary();
2570     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2571 #endif
2572 }
2573
2574 - (void)_preferencesChangedNotification:(NSNotification *)notification
2575 {
2576 #if PLATFORM(IOS)
2577     // For WebViews that load synchronously, preference changes need to be propagated
2578     // down to WebCore synchronously so that loads in that WebView have the correct
2579     // up-to-date settings.
2580     if (!WebThreadIsLocked())
2581         WebThreadLock();
2582     if ([[self mainFrame] _loadsSynchronously]) {
2583 #endif
2584
2585     WebPreferences *preferences = (WebPreferences *)[notification object];
2586     [self _preferencesChanged:preferences];
2587
2588 #if PLATFORM(IOS)
2589     } else {
2590         WebThreadRun(^{
2591             // It is possible that the prefs object has already changed before the invocation could be called
2592             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2593             WebPreferences *preferences = (WebPreferences *)[notification object];
2594             if (preferences != [self preferences])
2595                 return;
2596             [self _preferencesChanged:preferences];
2597         });
2598     }
2599 #endif
2600 }
2601
2602 - (void)_preferencesChanged:(WebPreferences *)preferences
2603 {    
2604     ASSERT(preferences == [self preferences]);
2605     if (!_private->userAgentOverridden)
2606         _private->userAgent = String();
2607
2608     // Cache this value so we don't have to read NSUserDefaults on each page load
2609     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2610
2611     // Update corresponding WebCore Settings object.
2612     if (!_private->page)
2613         return;
2614
2615 #if PLATFORM(IOS)
2616     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2617     // didOneTimeInitialization is true so that we don't initialize databases
2618     // until the first WebView has been created. This is because database
2619     // initialization current requires disk access to populate the origins
2620     // quota map and we want to do this lazily by waiting until WebKit is
2621     // used to display web content in a WebView. The possible cases are:
2622     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2623     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2624     if (didOneTimeInitialization) {
2625         if ([preferences databasesEnabled])
2626             [WebDatabaseManager sharedWebDatabaseManager];
2627         if ([preferences storageTrackerEnabled])
2628             WebKitInitializeStorageIfNecessary();
2629     }
2630 #endif
2631
2632     Settings& settings = _private->page->settings();
2633
2634     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2635     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2636     settings.setDefaultFontSize([preferences defaultFontSize]);
2637     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2638     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2639     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2640     settings.setFixedFontFamily([preferences fixedFontFamily]);
2641     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2642     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2643     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2644     settings.setJavaEnabled([preferences isJavaEnabled]);
2645     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2646     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2647     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2648     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2649     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2650     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2651     settings.setMinimumFontSize([preferences minimumFontSize]);
2652     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2653     settings.setPictographFontFamily([preferences pictographFontFamily]);
2654     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2655     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2656
2657     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2658     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2659     settings.setSerifFontFamily([preferences serifFontFamily]);
2660     settings.setStandardFontFamily([preferences standardFontFamily]);
2661     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2662     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2663 #if PLATFORM(IOS)
2664     settings.setShouldPrintBackgrounds(true);
2665 #else
2666     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2667 #endif
2668     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2669     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2670     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2671     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2672     settings.setUsesPageCache([self usesPageCache]);
2673     settings.setAllowsPageCacheWithWindowOpener([preferences allowsPageCacheWithWindowOpener]);
2674     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2675     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2676
2677     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2678     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2679     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2680
2681     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2682     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2683     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2684     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2685     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2686     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2687     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2688     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2689
2690     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2691     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2692     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2693     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2694     settings.setShowDebugBorders([preferences showDebugBorders]);
2695     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2696     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2697     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2698     settings.setWebGLEnabled([preferences webGLEnabled]);
2699     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2700
2701     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2702     settings.setPreferLowPowerWebGLRendering([preferences preferLowPowerWebGLRendering]);
2703     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2704     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2705     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2706     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2707     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2708     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2709
2710     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2711     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2712     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2713     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2714     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2715
2716     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2717     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2718     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2719     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2720     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2721     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2722     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2723     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2724     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2725     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2726     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2727     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2728     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2729     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2730     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2731
2732     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2733
2734     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2735     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2736     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2737
2738     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2739
2740     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2741     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2742
2743     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2744     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2745
2746     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2747
2748     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2749
2750     switch ([preferences storageBlockingPolicy]) {
2751     case WebAllowAllStorage:
2752         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2753         break;
2754     case WebBlockThirdPartyStorage:
2755         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2756         break;
2757     case WebBlockAllStorage:
2758         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2759         break;
2760     }
2761
2762     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2763     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2764
2765     settings.setFixedPositionCreatesStackingContext(true);
2766 #if PLATFORM(MAC)
2767     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2768 #endif
2769
2770 #if ENABLE(RUBBER_BANDING)
2771     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2772     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2773 #endif
2774
2775 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2776     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2777 #endif
2778 #if PLATFORM(IOS)
2779     settings.setStandalone([preferences _standalone]);
2780     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2781     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2782     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2783     settings.setMaxParseDuration([preferences _maxParseDuration]);
2784     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2785     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2786     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2787     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2788 #if HAVE(AVKIT)
2789     settings.setAVKitEnabled([preferences avKitEnabled]);
2790 #endif
2791     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2792     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2793
2794     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2795     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2796
2797     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2798     settings.setDelegatesPageScaling(true);
2799
2800 #if ENABLE(TEXT_AUTOSIZING)
2801     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2802     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2803 #endif
2804 #endif // PLATFORM(IOS)
2805
2806 #if PLATFORM(MAC)
2807     if ([preferences userStyleSheetEnabled]) {
2808         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2809         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2810             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2811         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2812     } else
2813         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2814
2815     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2816     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2817     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2818     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2819     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2820     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2821     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2822     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2823     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2824     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2825 #endif // PLATFORM(MAC)
2826
2827     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2828
2829 #if ENABLE(MEDIA_SOURCE)
2830     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2831 #endif
2832
2833 #if ENABLE(SERVICE_CONTROLS)
2834     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2835     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2836 #endif
2837
2838 #if ENABLE(VIDEO_TRACK)
2839     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2840     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2841     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2842 #endif
2843
2844 #if USE(AVFOUNDATION)
2845     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2846     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2847 #endif
2848
2849 #if ENABLE(MEDIA_STREAM)
2850     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2851     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2852     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
2853 #endif
2854
2855 #if ENABLE(WEB_RTC)
2856     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
2857 #endif
2858
2859 #if ENABLE(WEB_AUDIO)
2860     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2861 #endif
2862
2863 #if ENABLE(FULLSCREEN_API)
2864     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2865 #endif
2866
2867     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2868
2869     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2870
2871     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2872
2873 #if ENABLE(GAMEPAD)
2874     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2875 #endif
2876
2877     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2878
2879     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2880
2881     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2882
2883     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2884
2885 #if ENABLE(FETCH_API)
2886     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2887 #endif
2888
2889 #if ENABLE(WEBGL2)
2890     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2891 #endif
2892
2893 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2894     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2895 #endif
2896
2897 #if ENABLE(CSS_GRID_LAYOUT)
2898     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2899 #endif
2900
2901 #if ENABLE(WEB_ANIMATIONS)
2902     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2903 #endif
2904
2905 #if ENABLE(INTERSECTION_OBSERVER)
2906     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
2907 #endif
2908
2909 #if ENABLE(SUBTLE_CRYPTO)
2910     RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled([preferences subtleCryptoEnabled]);
2911 #endif
2912
2913     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
2914
2915     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2916     if (timeout > 0)
2917         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2918
2919     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2920     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2921
2922     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2923     if (_private->zoomsTextOnly != zoomsTextOnly)
2924         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2925
2926 #if PLATFORM(IOS)
2927     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2928     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2929     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2930     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2931 #endif
2932
2933 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2934     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2935 #endif
2936
2937     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2938
2939 #if ENABLE(ATTACHMENT_ELEMENT)
2940     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2941 #endif
2942
2943     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2944
2945     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2946
2947     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
2948     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
2949 }
2950
2951 static inline IMP getMethod(id o, SEL s)
2952 {
2953     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2954 }
2955
2956 #if PLATFORM(IOS)
2957 - (id)_UIKitDelegateForwarder
2958 {
2959     if (_private->closing)
2960         return nil;
2961         
2962     if (!_private->UIKitDelegateForwarder)
2963         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2964     return _private->UIKitDelegateForwarder;
2965 }
2966 #endif
2967
2968 - (void)_cacheResourceLoadDelegateImplementations
2969 {
2970     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2971     id delegate = _private->resourceProgressDelegate;
2972
2973     if (!delegate) {
2974         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2975         return;
2976     }
2977
2978     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2979     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2980     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2981     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2982 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2983     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2984 #endif
2985
2986 #if PLATFORM(IOS)
2987     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2988     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2989     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2990     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2991     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2992     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2993     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2994     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2995     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2996 #endif
2997
2998     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2999     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3000     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3001     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3002     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3003     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3004     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3005     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3006 }
3007
3008 - (void)_cacheFrameLoadDelegateImplementations
3009 {
3010     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3011     id delegate = _private->frameLoadDelegate;
3012
3013     if (!delegate) {
3014         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3015         return;
3016     }
3017
3018     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3019     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3020     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3021     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3022     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3023 #if JSC_OBJC_API_ENABLED
3024     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3025 #endif
3026     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3027     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3028     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3029     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3030     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3031     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3032     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3033     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3034     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3035     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3036     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3037     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3038 #if ENABLE(ICONDATABASE)
3039     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3040 #endif
3041     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3042     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3043     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3044     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3045     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3046     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3047     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3048     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3049     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3050     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3051 #if PLATFORM(IOS)
3052     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3053 #endif
3054
3055     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3056     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3057     // for backwards compatibility.
3058     Page* page = core(self);
3059     if (page) {
3060         unsigned milestones = DidFirstLayout;
3061 #if PLATFORM(IOS)
3062         milestones |= DidFirstVisuallyNonEmptyLayout;
3063 #else
3064         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3065             milestones |= DidFirstVisuallyNonEmptyLayout;
3066 #endif
3067         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3068     }
3069 }
3070
3071 - (void)_cacheScriptDebugDelegateImplementations
3072 {
3073     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3074     id delegate = _private->scriptDebugDelegate;
3075
3076     if (!delegate) {
3077         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3078         return;
3079     }
3080
3081     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3082     if (cache->didParseSourceFunc)
3083         cache->didParseSourceExpectsBaseLineNumber = YES;
3084     else {
3085         cache->didParseSourceExpectsBaseLineNumber = NO;
3086         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3087     }
3088
3089     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3090
3091     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3092     if (cache->exceptionWasRaisedFunc)
3093         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3094     else {
3095         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3096         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3097     }
3098 }
3099
3100 - (void)_cacheHistoryDelegateImplementations
3101 {
3102     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3103     id delegate = _private->historyDelegate;
3104
3105     if (!delegate) {
3106         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3107         return;
3108     }
3109
3110     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3111     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3112     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3113     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3114     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3115     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3116 }
3117
3118 - (id)_policyDelegateForwarder
3119 {
3120 #if PLATFORM(IOS)
3121     if (_private->closing)
3122         return nil;
3123 #endif
3124     if (!_private->policyDelegateForwarder)
3125         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3126     return _private->policyDelegateForwarder;
3127 }
3128
3129 - (id)_UIDelegateForwarder
3130 {
3131 #if PLATFORM(IOS)
3132     if (_private->closing)
3133         return nil;
3134 #endif
3135     if (!_private->UIDelegateForwarder)
3136         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3137     return _private->UIDelegateForwarder;
3138 }
3139
3140 #if PLATFORM(IOS)
3141 - (id)_UIDelegateForSelector:(SEL)selector
3142 {
3143     id delegate = self->_private->UIDelegate;
3144     if ([delegate respondsToSelector:selector])
3145         return delegate;
3146
3147     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3148     if ([delegate respondsToSelector:selector])
3149         return delegate;
3150
3151     return nil;
3152 }
3153 #endif
3154
3155 - (id)_editingDelegateForwarder
3156 {
3157 #if PLATFORM(IOS)
3158     if (_private->closing)
3159         return nil;
3160 #endif    
3161     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3162     // Not sure if that is a bug or not.
3163     if (!_private)
3164         return nil;
3165
3166     if (!_private->editingDelegateForwarder)
3167         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3168     return _private->editingDelegateForwarder;
3169 }
3170
3171 - (void)_closeWindow
3172 {
3173     [[self _UIDelegateForwarder] webViewClose:self];
3174 }
3175
3176 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3177 {
3178     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3179     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3180     
3181     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3182     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3183     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3184     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3185 }
3186
3187 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3188 {
3189     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3190     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3191
3192     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3193     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3194     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3195     if ([viewClass class] == [WebHTMLView class])
3196         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3197     
3198     // This is used to make _representationExistsForURLScheme faster.
3199     // Without this set, we'd have to create the MIME type each time.
3200     if (schemesWithRepresentationsSet == nil) {
3201         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3202     }
3203     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3204 }
3205
3206 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3207 {
3208     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3209 }
3210
3211 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3212 {
3213     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3214 }
3215
3216 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3217 {
3218     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3219     if (!request)
3220         return NO;
3221
3222     if ([NSURLConnection canHandleRequest:request])
3223         return YES;
3224
3225     NSString *scheme = [[request URL] scheme];
3226
3227     // Representations for URL schemes work at the top level.
3228     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3229         return YES;
3230
3231     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3232         return YES;
3233
3234     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3235         return YES;
3236
3237     return NO;
3238 }
3239
3240 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3241 {
3242     return [self _canHandleRequest:request forMainFrame:YES];
3243 }
3244
3245 + (NSString *)_decodeData:(NSData *)data
3246 {
3247     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3248     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3249 }
3250
3251 - (void)_pushPerformingProgrammaticFocus
3252 {
3253     _private->programmaticFocusCount++;
3254 }
3255
3256 - (void)_popPerformingProgrammaticFocus
3257 {
3258     _private->programmaticFocusCount--;
3259 }
3260
3261 - (BOOL)_isPerformingProgrammaticFocus
3262 {
3263     return _private->programmaticFocusCount != 0;
3264 }
3265
3266 #if !PLATFORM(IOS)
3267 - (void)_didChangeValueForKey: (NSString *)key
3268 {
3269     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3270     [self didChangeValueForKey: key];
3271 }
3272
3273 - (void)_willChangeValueForKey: (NSString *)key
3274 {
3275     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3276     [self willChangeValueForKey: key];
3277 }
3278
3279 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3280     static NSSet *manualNotifyKeys = nil;
3281     if (!manualNotifyKeys)
3282         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3283             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3284             nil];
3285     if ([manualNotifyKeys containsObject:key])
3286         return NO;
3287     return YES;
3288 }
3289
3290 - (NSArray *)_declaredKeys {
3291     static NSArray *declaredKeys = nil;
3292     if (!declaredKeys)
3293         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3294             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3295     return declaredKeys;
3296 }
3297
3298 - (void)_willChangeBackForwardKeys
3299 {
3300     [self _willChangeValueForKey: _WebCanGoBackKey];
3301     [self _willChangeValueForKey: _WebCanGoForwardKey];
3302 }
3303
3304 - (void)_didChangeBackForwardKeys
3305 {
3306     [self _didChangeValueForKey: _WebCanGoBackKey];
3307     [self _didChangeValueForKey: _WebCanGoForwardKey];
3308 }
3309
3310 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3311 {
3312     if (needsSelfRetainWhileLoadingQuirk())
3313         [self retain];
3314
3315     [self _willChangeBackForwardKeys];
3316     if (frame == [self mainFrame]){
3317         // Force an observer update by sending a will/did.
3318         [self _willChangeValueForKey: _WebIsLoadingKey];
3319         [self _didChangeValueForKey: _WebIsLoadingKey];
3320
3321         [self _willChangeValueForKey: _WebMainFrameURLKey];
3322
3323         [self hideFormValidationMessage];
3324     }
3325
3326     [NSApp setWindowsNeedUpdate:YES];
3327
3328 #if ENABLE(FULLSCREEN_API)
3329     Document* document = core([frame DOMDocument]);
3330     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3331         SEL selector = @selector(webView:closeFullScreenWithListener:);
3332         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
3333             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3334             CallUIDelegate(self, selector, listener);
3335             [listener release];
3336         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3337             [_private->newFullscreenController close];
3338         }
3339     }
3340 #endif
3341 }
3342
3343 - (void)_checkDidPerformFirstNavigation
3344 {
3345     if (_private->_didPerformFirstNavigation)
3346         return;
3347
3348     Page* page = _private->page;
3349     if (!page)
3350         return;
3351
3352     auto& backForwardController = page->backForward();
3353
3354     if (!backForwardController.backItem())
3355         return;
3356
3357     _private->_didPerformFirstNavigation = YES;
3358
3359     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3360         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3361 }
3362
3363 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3364 {
3365     if (frame == [self mainFrame])
3366         [self _didChangeValueForKey: _WebMainFrameURLKey];
3367
3368     [self _checkDidPerformFirstNavigation];
3369
3370     [NSApp setWindowsNeedUpdate:YES];
3371 }
3372
3373 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3374 {
3375     if (needsSelfRetainWhileLoadingQuirk())
3376         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3377         
3378     [self _didChangeBackForwardKeys];
3379     if (frame == [self mainFrame]){
3380         // Force an observer update by sending a will/did.
3381         [self _willChangeValueForKey: _WebIsLoadingKey];
3382         [self _didChangeValueForKey: _WebIsLoadingKey];
3383     }
3384     [NSApp setWindowsNeedUpdate:YES];
3385 }
3386
3387 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3388 {
3389     if (needsSelfRetainWhileLoadingQuirk())
3390         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3391
3392     [self _didChangeBackForwardKeys];
3393     if (frame == [self mainFrame]){
3394         // Force an observer update by sending a will/did.
3395         [self _willChangeValueForKey: _WebIsLoadingKey];
3396         [self _didChangeValueForKey: _WebIsLoadingKey];
3397     }
3398     [NSApp setWindowsNeedUpdate:YES];
3399 }
3400
3401 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3402 {
3403     if (needsSelfRetainWhileLoadingQuirk())
3404         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3405
3406     [self _didChangeBackForwardKeys];
3407     if (frame == [self mainFrame]){
3408         // Force an observer update by sending a will/did.
3409         [self _willChangeValueForKey: _WebIsLoadingKey];
3410         [self _didChangeValueForKey: _WebIsLoadingKey];
3411         
3412         [self _didChangeValueForKey: _WebMainFrameURLKey];
3413     }
3414     [NSApp setWindowsNeedUpdate:YES];
3415 }
3416
3417 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3418 {
3419     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3420     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3421     NSCachedURLResponse *cachedResponse;
3422
3423     if (!_private->page)
3424         return nil;
3425
3426     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3427         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3428     else
3429         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3430
3431     return cachedResponse;
3432 }
3433
3434 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3435 {
3436     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3437     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3438     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3439                         element:domElement
3440                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3441                           title:[element objectForKey:WebElementImageAltStringKey] 
3442                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3443                           types:types
3444                          source:nil];
3445 }
3446
3447 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3448 {
3449     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3450                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3451                         types:types];
3452 }
3453
3454 #if ENABLE(DRAG_SUPPORT)
3455 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3456 {
3457     if (!_private->page)
3458         return;
3459     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3460 }
3461 #endif
3462
3463 #else
3464
3465 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3466 {
3467     if (frame == [self mainFrame])
3468         _private->didDrawTiles = 0;
3469 }
3470
3471 #endif // PLATFORM(IOS)
3472
3473 #if ENABLE(DASHBOARD_SUPPORT)
3474
3475 #define DASHBOARD_CONTROL_LABEL @"control"
3476
3477 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3478 {
3479     NSRect adjustedBounds = bounds;
3480     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3481     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3482     adjustedBounds.size = bounds.size;
3483
3484     NSRect adjustedClip;
3485     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3486     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3487     adjustedClip.size = clip.size;
3488
3489     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3490         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3491     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3492     if (!scrollerRegions) {
3493         scrollerRegions = [[NSMutableArray alloc] init];
3494         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3495         [scrollerRegions release];
3496     }
3497     [scrollerRegions addObject:region];
3498     [region release];
3499 }
3500
3501 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3502 {    
3503     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3504
3505     for (const auto& widget: frameView->children()) {
3506         if (is<FrameView>(widget)) {
3507             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3508             continue;
3509         }
3510
3511         if (!widget->isScrollbar())
3512             continue;
3513
3514         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3515         // it's not common to need this to be correct in Dashboard widgets.
3516         NSRect bounds = widget->frameRect();
3517         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3518     }
3519 }
3520
3521 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3522 {
3523     // Add scroller regions for NSScroller and WebCore scrollbars
3524     NSUInteger count = [views count];
3525     for (NSUInteger i = 0; i < count; i++) {
3526         NSView *view = [views objectAtIndex:i];
3527         
3528         if ([view isKindOfClass:[WebHTMLView class]]) {
3529             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3530                 if (FrameView* coreView = coreFrame->view())
3531                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3532             }
3533         } else if ([view isKindOfClass:[NSScroller class]]) {
3534             // AppKit places absent scrollers at -100,-100
3535             if ([view frame].origin.y < 0)
3536                 continue;
3537             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3538         }
3539         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3540     }
3541 }
3542
3543 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3544 {
3545     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3546 }
3547
3548 - (NSDictionary *)_dashboardRegions
3549 {
3550     // Only return regions from main frame.
3551     Frame* mainFrame = [self _mainCoreFrame];
3552     if (!mainFrame)
3553         return nil;
3554
3555     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3556     size_t size = regions.size();
3557
3558     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3559     for (size_t i = 0; i < size; i++) {
3560         const AnnotatedRegionValue& region = regions[i];
3561
3562         if (region.type == StyleDashboardRegion::None)
3563             continue;
3564
3565         NSString *label = region.label;
3566         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3567         if (region.type == StyleDashboardRegion::Circle)
3568             type = WebDashboardRegionTypeCircle;
3569         else if (region.type == StyleDashboardRegion::Rectangle)
3570             type = WebDashboardRegionTypeRectangle;
3571         NSMutableArray *regionValues = [webRegions objectForKey:label];
3572         if (!regionValues) {
3573             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3574             [webRegions setObject:regionValues forKey:label];
3575             [regionValues release];
3576         }
3577
3578         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3579         [regionValues addObject:webRegion];
3580         [webRegion release];
3581     }
3582
3583     [self _addScrollerDashboardRegions:webRegions];
3584
3585     return webRegions;
3586 }
3587
3588 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3589 {
3590     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3591     // specific support for the backward compatibility mode flag.
3592     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3593         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3594     
3595     switch (behavior) {
3596         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3597             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3598             break;
3599         }
3600         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3601             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3602             break;
3603         }
3604         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3605             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3606             break;
3607         }
3608         case WebDashboardBehaviorAllowWheelScrolling: {
3609             _private->dashboardBehaviorAllowWheelScrolling = flag;
3610             break;
3611         }
3612         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3613             if (_private->page)
3614                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3615 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3616             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3617 #endif
3618             break;
3619         }
3620     }
3621
3622     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3623     // compatibility mode. See <rdar://problem/8175982>.
3624     if (_private->page)
3625         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3626 }
3627
3628 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3629 {
3630     switch (behavior) {
3631         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3632             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3633         }
3634         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3635             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3636         }
3637         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3638             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3639         }
3640         case WebDashboardBehaviorAllowWheelScrolling: {
3641             return _private->dashboardBehaviorAllowWheelScrolling;
3642         }
3643         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3644             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3645         }
3646     }
3647     return NO;
3648 }
3649
3650 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3651
3652 + (void)_setShouldUseFontSmoothing:(BOOL)f
3653 {
3654     FontCascade::setShouldUseSmoothing(f);
3655 }
3656
3657 + (BOOL)_shouldUseFontSmoothing
3658 {
3659     return FontCascade::shouldUseSmoothing();
3660 }
3661
3662 #if !PLATFORM(IOS)
3663 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3664 {
3665     setUsesTestModeFocusRingColor(f);
3666 }
3667
3668 + (BOOL)_usesTestModeFocusRingColor
3669 {
3670     return usesTestModeFocusRingColor();
3671 }
3672 #endif
3673
3674 #if PLATFORM(IOS)
3675 - (void)_setUIKitDelegate:(id)delegate
3676 {
3677     _private->UIKitDelegate = delegate;
3678     [_private->UIKitDelegateForwarder clearTarget];
3679     [_private->UIKitDelegateForwarder release];
3680     _private->UIKitDelegateForwarder = nil;
3681 }
3682
3683 - (id)_UIKitDelegate
3684 {
3685     return _private->UIKitDelegate;
3686 }
3687
3688 - (void)setWebMailDelegate:(id)delegate
3689 {
3690     _private->WebMailDelegate = delegate;
3691 }
3692
3693 - (id)_webMailDelegate
3694 {
3695     return _private->WebMailDelegate;
3696 }
3697
3698 - (id <WebCaretChangeListener>)caretChangeListener
3699 {
3700     return _private->_caretChangeListener;
3701 }
3702
3703 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3704 {
3705     _private->_caretChangeListener = listener;
3706 }
3707
3708 - (NSSet *)caretChangeListeners
3709 {
3710     return _private->_caretChangeListeners;
3711 }
3712
3713 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3714 {
3715     if (_private->_caretChangeListeners == nil) {
3716         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3717     }
3718     
3719     [_private->_caretChangeListeners addObject:listener];
3720 }
3721
3722 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3723 {
3724     [_private->_caretChangeListeners removeObject:listener];
3725 }
3726
3727 - (void)removeAllCaretChangeListeners
3728 {
3729     [_private->_caretChangeListeners removeAllObjects];
3730 }
3731
3732 - (void)caretChanged
3733 {
3734     [_private->_caretChangeListener caretChanged];
3735     NSSet *copy = [_private->_caretChangeListeners copy];
3736     for (id <WebCaretChangeListener> listener in copy) {
3737         [listener caretChanged];
3738     }
3739     [copy release];
3740 }
3741
3742 - (void)_clearDelegates
3743 {
3744     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3745     
3746     [self _setFormDelegate:nil];
3747     [self _setUIKitDelegate:nil];
3748     [self setCaretChangeListener:nil];
3749     [self removeAllCaretChangeListeners];
3750     [self setWebMailDelegate:nil];
3751     
3752     [self setDownloadDelegate:nil];
3753     [self setEditingDelegate:nil]; 
3754     [self setFrameLoadDelegate:nil];
3755     [self setPolicyDelegate:nil];
3756     [self setResourceLoadDelegate:nil];
3757     [self setScriptDebugDelegate:nil];
3758     [self setUIDelegate:nil];     
3759 }
3760
3761 - (NSURL *)_displayURL
3762 {
3763     WebThreadLock();
3764     WebFrame *frame = [self mainFrame];
3765     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3766     WebDataSource *dataSource = [frame provisionalDataSource];
3767     if (!dataSource)
3768         dataSource = [frame dataSource];
3769     NSURL *unreachableURL = [dataSource unreachableURL];
3770     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3771     [[URL retain] autorelease];
3772     return URL;
3773 }
3774 #endif // PLATFORM(IOS)
3775
3776 #if !PLATFORM(IOS)
3777 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3778 {
3779     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3780     if (flag) {
3781         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3782     } else {
3783         [scrollview setVerticalScrollingModeLocked:NO];
3784         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3785     }
3786 }
3787
3788 - (BOOL)alwaysShowVerticalScroller
3789 {
3790     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3791     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3792 }
3793
3794 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3795 {
3796     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3797     if (flag) {
3798         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3799     } else {
3800         [scrollview setHorizontalScrollingModeLocked:NO];
3801         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3802     }
3803 }
3804
3805 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3806 {
3807     if (Frame* mainFrame = [self _mainCoreFrame])
3808         mainFrame->view()->setProhibitsScrolling(prohibits);
3809 }
3810
3811 - (BOOL)alwaysShowHorizontalScroller
3812 {
3813     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3814     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3815 }
3816 #endif // !PLATFORM(IOS)
3817
3818 - (void)_setUseFastImageScalingMode:(BOOL)flag
3819 {
3820     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3821         _private->page->setInLowQualityImageInterpolationMode(flag);
3822         [self setNeedsDisplay:YES];
3823     }
3824 }
3825
3826 - (BOOL)_inFastImageScalingMode
3827 {
3828     if (_private->page)
3829         return _private->page->inLowQualityImageInterpolationMode();
3830     return NO;
3831 }
3832
3833 - (BOOL)_cookieEnabled
3834 {
3835     if (_private->page)
3836         return _private->page->settings().cookieEnabled();
3837     return YES;
3838 }
3839
3840 - (void)_setCookieEnabled:(BOOL)enable
3841 {
3842     if (_private->page)
3843         _private->page->settings().setCookieEnabled(enable);
3844 }
3845
3846 #if !PLATFORM(IOS)
3847 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3848 {
3849     if (!_private->pluginDatabase)
3850         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3851         
3852     [_private->pluginDatabase setPlugInPaths:newPaths];
3853     [_private->pluginDatabase refresh];
3854 }
3855 #endif
3856
3857 #if PLATFORM(IOS)
3858 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3859 {
3860     // Ask plug-ins in this frame
3861     id <WebDocumentView> documentView = [[frame frameView] documentView];
3862     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3863         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3864             return YES;
3865     }
3866
3867     // Ask plug-ins in child frames
3868     NSArray *childFrames = [frame childFrames];
3869     unsigned childCount = [childFrames count];
3870     unsigned childIndex;
3871     for (childIndex = 0; childIndex < childCount; childIndex++) {
3872         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3873             return YES;
3874     }
3875     
3876     return NO;
3877 }
3878
3879 - (BOOL)_pluginsAreRunning
3880 {
3881     WebThreadLock();
3882     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3883 }
3884
3885 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3886 {
3887     // Send the message to plug-ins in this frame
3888     id <WebDocumentView> documentView = [[frame frameView] documentView];
3889     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3890         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3891
3892     // Send the message to plug-ins in child frames
3893     NSArray *childFrames = [frame childFrames];
3894     unsigned childCount = [childFrames count];
3895     unsigned childIndex;
3896     for (childIndex = 0; childIndex < childCount; childIndex++) {
3897         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3898     }
3899 }
3900
3901 - (void)_destroyAllPlugIns
3902 {
3903     WebThreadLock();
3904     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3905 }
3906
3907 - (void)_startAllPlugIns
3908 {
3909     WebThreadLock();
3910     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3911 }
3912
3913 - (void)_stopAllPlugIns
3914 {
3915     WebThreadLock();
3916     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3917 }
3918
3919 - (void)_stopAllPlugInsForPageCache
3920 {
3921     WebThreadLock();
3922     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3923 }
3924
3925 - (void)_restorePlugInsFromCache
3926 {
3927     WebThreadLock();
3928     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3929 }
3930
3931 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3932 {
3933     WebThreadLock();
3934
3935     Frame* mainCoreFrame = [self _mainCoreFrame];
3936     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3937         FrameView* coreView = frame ? frame->view() : 0;
3938         if (!coreView)
3939             continue;
3940
3941         // Get the GraphicsLayer for this widget.
3942         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3943         if (!layerForWidget)
3944             continue;
3945         
3946         if (layerForWidget->contentsLayerForMedia() != layer) {
3947             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3948             // We need to make sure the layer hierachy change is applied immediately.
3949             if (mainCoreFrame->view())
3950                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3951             return YES;
3952         }
3953     }
3954
3955     return NO;
3956 }
3957
3958 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3959 {
3960     if (_private->page)
3961         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3962 }
3963 #endif // PLATFORM(IOS)
3964
3965 - (void)_attachScriptDebuggerToAllFrames
3966 {
3967     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3968         [kit(frame) _attachScriptDebugger];
3969 }
3970
3971 - (void)_detachScriptDebuggerFromAllFrames
3972 {
3973     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3974         [kit(frame) _detachScriptDebugger];
3975 }
3976
3977 #if !PLATFORM(IOS)
3978 - (void)setBackgroundColor:(NSColor *)backgroundColor
3979 {
3980     if ([_private->backgroundColor isEqual:backgroundColor])
3981         return;
3982
3983     id old = _private->backgroundColor;
3984     _private->backgroundColor = [backgroundColor retain];
3985     [old release];
3986
3987     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3988 }
3989
3990 - (NSColor *)backgroundColor
3991 {
3992     return _private->backgroundColor;
3993 }
3994 #else
3995 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3996 {
3997    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3998         return;
3999
4000     CFTypeRef old = _private->backgroundColor;
4001     CFRetain(backgroundColor);
4002     _private->backgroundColor = backgroundColor;
4003     CFRelease(old);
4004
4005     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
4006 }
4007
4008 - (CGColorRef)backgroundColor
4009 {
4010     return _private->backgroundColor;
4011 }
4012 #endif
4013
4014 - (BOOL)defersCallbacks
4015 {
4016     if (!_private->page)
4017         return NO;
4018     return _private->page->defersLoading();
4019 }
4020
4021 - (void)setDefersCallbacks:(BOOL)defer
4022 {
4023     if (!_private->page)
4024         return;
4025     return _private->page->setDefersLoading(defer);
4026 }
4027
4028 #if PLATFORM(IOS)
4029 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
4030 {
4031 #if USE(QUICK_LOOK)
4032     NSString *uti = qlPreviewConverterUTIForURL(url);
4033     if (!uti)
4034         return nil;
4035
4036     NSString *fileName = qlPreviewConverterFileNameForURL(url);
4037     if (!fileName)
4038         return nil;
4039
4040     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
4041 #else
4042     return nil;
4043 #endif
4044 }
4045
4046 - (BOOL)_isStopping
4047 {
4048     return _private->isStopping;
4049 }
4050
4051 - (BOOL)_isClosing
4052 {
4053     return _private->closing;
4054 }
4055
4056 + (NSArray *)_productivityDocumentMIMETypes
4057 {
4058 #if USE(QUICK_LOOK)
4059     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
4060 #else
4061     return nil;
4062 #endif
4063 }
4064
4065 - (void)_setAllowsMessaging:(BOOL)aFlag
4066 {
4067     _private->allowsMessaging = aFlag;
4068 }
4069
4070 - (BOOL)_allowsMessaging
4071 {
4072     return _private->allowsMessaging;
4073 }
4074
4075 - (void)_setFixedLayoutSize:(CGSize)size
4076 {
4077     ASSERT(WebThreadIsLocked());
4078     _private->fixedLayoutSize = size;
4079     if (Frame* mainFrame = core([self mainFrame])) {
4080         IntSize newSize(size);
4081         mainFrame->view()->setFixedLayoutSize(newSize);
4082         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
4083         [self setNeedsDisplay:YES];
4084     }
4085 }
4086
4087 - (CGSize)_fixedLayoutSize
4088 {
4089     return _private->fixedLayoutSize;
4090 }
4091
4092 - (void)_synchronizeCustomFixedPositionLayoutRect
4093 {
4094     ASSERT(WebThreadIsLocked());
4095
4096     IntRect newRect;
4097     {
4098         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4099         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4100             return;
4101         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
4102         _private->pendingFixedPositionLayoutRect = CGRectNull;
4103     }
4104
4105     if (Frame* mainFrame = core([self mainFrame]))
4106         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
4107 }
4108
4109 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
4110 {
4111     {
4112         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4113         _private->pendingFixedPositionLayoutRect = rect;
4114     }
4115     if (!synchronize)
4116         return;
4117     WebThreadRun(^{
4118         [self _synchronizeCustomFixedPositionLayoutRect];
4119     });
4120 }
4121
4122 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
4123 {
4124     ASSERT(WebThreadIsLocked());
4125     {
4126         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4127         _private->pendingFixedPositionLayoutRect = rect;
4128     }
4129     [self _synchronizeCustomFixedPositionLayoutRect];
4130 }
4131
4132 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
4133 {
4134     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4135     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4136         return false;
4137
4138     *rect = _private->pendingFixedPositionLayoutRect;
4139     _private->pendingFixedPositionLayoutRect = CGRectNull;
4140     return true;
4141 }
4142
4143 - (void)_viewGeometryDidChange
4144 {
4145     ASSERT(WebThreadIsLocked());
4146     
4147     if (Frame* coreFrame = [self _mainCoreFrame])
4148         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
4149 }
4150
4151 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
4152 {
4153     // Find the frame
4154     Node* node = core(domNode);
4155     Frame* frame = node->document().frame();
4156     if (!frame)
4157         return;
4158
4159     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
4160 }
4161
4162 + (void)_doNotStartObservingNetworkReachability
4163 {
4164     Settings::setShouldOptOutOfNetworkStateObservation(true);
4165 }
4166 #endif // PLATFORM(IOS)
4167
4168 #if ENABLE(TOUCH_EVENTS)
4169 - (NSArray *)_touchEventRegions
4170 {
4171     Frame* frame = [self _mainCoreFrame];
4172     if (!frame)
4173         return nil;
4174     
4175     Document* document = frame->document();
4176     if (!document)
4177         return nil;
4178
4179     Vector<IntRect> rects;
4180     document->getTouchRects(rects);
4181
4182     if (rects.size() == 0)
4183         return nil;
4184
4185     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
4186
4187     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
4188     Vector<IntRect>::const_iterator end = rects.end();
4189     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
4190         const IntRect& rect = *it;
4191         if (rect.isEmpty())
4192             continue;
4193
4194         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
4195         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
4196         // convert them here now.
4197         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
4198
4199         // The event region wants this points in this order:
4200         //  p2------p3
4201         //  |       |
4202         //  p1------p4
4203         //
4204         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
4205                                                                             :FloatPoint(viewRect.x(), viewRect.y())
4206                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
4207                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
4208         if (eventRegion) {
4209             [eventRegionArray addObject:eventRegion];
4210             [eventRegion release];
4211         }
4212     }
4213
4214     return eventRegionArray;
4215 }
4216 #endif // ENABLE(TOUCH_EVENTS)
4217
4218 // For backwards compatibility with the WebBackForwardList API, we honor both
4219 // a per-WebView and a per-preferences setting for whether to use the page cache.
4220
4221 - (BOOL)usesPageCache
4222 {
4223     return _private->usesPageCache && [[self preferences] usesPageCache];
4224 }
4225
4226 - (void)setUsesPageCache:(BOOL)usesPageCache
4227 {
4228     _private->usesPageCache = usesPageCache;
4229
4230     // Update our own settings and post the public notification only
4231     [self _preferencesChanged:[self preferences]];
4232     [[self preferences] _postPreferencesChangedAPINotification];
4233 }
4234
4235 - (WebHistoryItem *)_globalHistoryItem
4236 {
4237     if (!_private)
4238         return nil;
4239
4240     return kit(_private->_globalHistoryItem.get());
4241 }
4242
4243 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
4244 {
4245     _private->_globalHistoryItem = historyItem;
4246 }
4247
4248 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
4249 {
4250     IntPoint rectStart(rect.origin.x, rect.origin.y);
4251     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
4252     
4253     Frame* coreFrame = [self _mainCoreFrame];
4254     if (!coreFrame)
4255         return nil;
4256     
4257     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
4258     
4259     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
4260 }
4261