classInfo should take a VM so it is not materialized from the object on each call
[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) && PLATFORM(MAC)
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.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2674     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2675
2676     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2677     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2678     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2679
2680     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2681     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2682     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2683     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2684     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2685     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2686     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2687     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2688
2689     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2690     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2691     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2692     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2693     settings.setShowDebugBorders([preferences showDebugBorders]);
2694     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2695     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2696     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2697     settings.setWebGLEnabled([preferences webGLEnabled]);
2698     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2699
2700     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2701     settings.setPreferLowPowerWebGLRendering([preferences preferLowPowerWebGLRendering]);
2702     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2703     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2704     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2705     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2706     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2707     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2708
2709     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2710     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2711     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2712     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2713     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2714
2715     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2716     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2717     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2718     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2719     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2720     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2721     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2722     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2723     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2724     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2725     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2726     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2727     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2728     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2729     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2730
2731     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2732
2733     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2734     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2735     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2736
2737     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2738
2739     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2740     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2741
2742     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2743     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2744
2745     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2746
2747     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2748
2749     switch ([preferences storageBlockingPolicy]) {
2750     case WebAllowAllStorage:
2751         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2752         break;
2753     case WebBlockThirdPartyStorage:
2754         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2755         break;
2756     case WebBlockAllStorage:
2757         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2758         break;
2759     }
2760
2761     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2762     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2763
2764     settings.setFixedPositionCreatesStackingContext(true);
2765 #if PLATFORM(MAC)
2766     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2767 #endif
2768
2769 #if ENABLE(RUBBER_BANDING)
2770     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2771     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2772 #endif
2773
2774 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2775     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2776 #endif
2777 #if PLATFORM(IOS)
2778     settings.setStandalone([preferences _standalone]);
2779     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2780     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2781     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2782     settings.setMaxParseDuration([preferences _maxParseDuration]);
2783     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2784     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2785     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2786     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2787 #if HAVE(AVKIT)
2788     settings.setAVKitEnabled([preferences avKitEnabled]);
2789 #endif
2790     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2791     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2792
2793     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2794     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2795
2796     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2797     settings.setDelegatesPageScaling(true);
2798
2799 #if ENABLE(TEXT_AUTOSIZING)
2800     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2801     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2802 #endif
2803 #endif // PLATFORM(IOS)
2804
2805 #if PLATFORM(MAC)
2806     if ([preferences userStyleSheetEnabled]) {
2807         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2808         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2809             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2810         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2811     } else
2812         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2813
2814     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2815     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2816     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2817     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2818     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2819     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2820     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2821     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2822     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2823     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2824 #endif // PLATFORM(MAC)
2825
2826     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2827
2828 #if ENABLE(MEDIA_SOURCE)
2829     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2830 #endif
2831
2832 #if ENABLE(SERVICE_CONTROLS)
2833     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2834     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2835 #endif
2836
2837 #if ENABLE(VIDEO_TRACK)
2838     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2839     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2840     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2841 #endif
2842
2843 #if USE(AVFOUNDATION)
2844     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2845     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2846 #endif
2847
2848 #if ENABLE(MEDIA_STREAM)
2849     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2850     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2851     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
2852 #endif
2853
2854 #if ENABLE(WEB_RTC)
2855     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
2856 #endif
2857
2858 #if ENABLE(WEB_AUDIO)
2859     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2860 #endif
2861
2862 #if ENABLE(FULLSCREEN_API)
2863     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2864 #endif
2865
2866     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2867
2868     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2869
2870     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2871
2872 #if ENABLE(GAMEPAD)
2873     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2874 #endif
2875
2876     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2877
2878     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2879
2880     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2881
2882     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2883
2884 #if ENABLE(FETCH_API)
2885     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2886 #endif
2887
2888 #if ENABLE(WEBGL2)
2889     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2890 #endif
2891
2892 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2893     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2894 #endif
2895
2896 #if ENABLE(CSS_GRID_LAYOUT)
2897     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2898 #endif
2899
2900 #if ENABLE(WEB_ANIMATIONS)
2901     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2902 #endif
2903
2904 #if ENABLE(INTERSECTION_OBSERVER)
2905     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
2906 #endif
2907
2908 #if ENABLE(SUBTLE_CRYPTO)
2909     RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled([preferences subtleCryptoEnabled]);
2910 #endif
2911
2912     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2913     if (timeout > 0)
2914         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2915
2916     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2917     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2918
2919     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2920     if (_private->zoomsTextOnly != zoomsTextOnly)
2921         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2922
2923 #if PLATFORM(IOS)
2924     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2925     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2926     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2927     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2928 #endif
2929
2930 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2931     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2932 #endif
2933
2934     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2935
2936 #if ENABLE(ATTACHMENT_ELEMENT)
2937     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2938 #endif
2939
2940     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2941
2942     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2943
2944     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
2945     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
2946 }
2947
2948 static inline IMP getMethod(id o, SEL s)
2949 {
2950     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2951 }
2952
2953 #if PLATFORM(IOS)
2954 - (id)_UIKitDelegateForwarder
2955 {
2956     if (_private->closing)
2957         return nil;
2958         
2959     if (!_private->UIKitDelegateForwarder)
2960         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2961     return _private->UIKitDelegateForwarder;
2962 }
2963 #endif
2964
2965 - (void)_cacheResourceLoadDelegateImplementations
2966 {
2967     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2968     id delegate = _private->resourceProgressDelegate;
2969
2970     if (!delegate) {
2971         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2972         return;
2973     }
2974
2975     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2976     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2977     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2978     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2979 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2980     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2981 #endif
2982
2983 #if PLATFORM(IOS)
2984     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2985     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2986     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2987     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2988     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2989     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2990     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2991     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2992     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2993 #endif
2994
2995     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2996     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2997     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2998     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2999     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3000     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3001     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3002     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3003 }
3004
3005 - (void)_cacheFrameLoadDelegateImplementations
3006 {
3007     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3008     id delegate = _private->frameLoadDelegate;
3009
3010     if (!delegate) {
3011         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3012         return;
3013     }
3014
3015     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3016     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3017     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3018     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3019     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3020 #if JSC_OBJC_API_ENABLED
3021     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3022 #endif
3023     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3024     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3025     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3026     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3027     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3028     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3029     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3030     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3031     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3032     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3033     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3034     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3035 #if ENABLE(ICONDATABASE)
3036     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3037 #endif
3038     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3039     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3040     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3041     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3042     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3043     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3044     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3045     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3046     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3047     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3048 #if PLATFORM(IOS)
3049     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3050 #endif
3051
3052     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3053     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3054     // for backwards compatibility.
3055     Page* page = core(self);
3056     if (page) {
3057         unsigned milestones = DidFirstLayout;
3058 #if PLATFORM(IOS)
3059         milestones |= DidFirstVisuallyNonEmptyLayout;
3060 #else
3061         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3062             milestones |= DidFirstVisuallyNonEmptyLayout;
3063 #endif
3064         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3065     }
3066 }
3067
3068 - (void)_cacheScriptDebugDelegateImplementations
3069 {
3070     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3071     id delegate = _private->scriptDebugDelegate;
3072
3073     if (!delegate) {
3074         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3075         return;
3076     }
3077
3078     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3079     if (cache->didParseSourceFunc)
3080         cache->didParseSourceExpectsBaseLineNumber = YES;
3081     else {
3082         cache->didParseSourceExpectsBaseLineNumber = NO;
3083         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3084     }
3085
3086     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3087
3088     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3089     if (cache->exceptionWasRaisedFunc)
3090         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3091     else {
3092         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3093         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3094     }
3095 }
3096
3097 - (void)_cacheHistoryDelegateImplementations
3098 {
3099     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3100     id delegate = _private->historyDelegate;
3101
3102     if (!delegate) {
3103         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3104         return;
3105     }
3106
3107     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3108     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3109     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3110     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3111     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3112     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3113 }
3114
3115 - (id)_policyDelegateForwarder
3116 {
3117 #if PLATFORM(IOS)
3118     if (_private->closing)
3119         return nil;
3120 #endif
3121     if (!_private->policyDelegateForwarder)
3122         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3123     return _private->policyDelegateForwarder;
3124 }
3125
3126 - (id)_UIDelegateForwarder
3127 {
3128 #if PLATFORM(IOS)
3129     if (_private->closing)
3130         return nil;
3131 #endif
3132     if (!_private->UIDelegateForwarder)
3133         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3134     return _private->UIDelegateForwarder;
3135 }
3136
3137 #if PLATFORM(IOS)
3138 - (id)_UIDelegateForSelector:(SEL)selector
3139 {
3140     id delegate = self->_private->UIDelegate;
3141     if ([delegate respondsToSelector:selector])
3142         return delegate;
3143
3144     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3145     if ([delegate respondsToSelector:selector])
3146         return delegate;
3147
3148     return nil;
3149 }
3150 #endif
3151
3152 - (id)_editingDelegateForwarder
3153 {
3154 #if PLATFORM(IOS)
3155     if (_private->closing)
3156         return nil;
3157 #endif    
3158     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3159     // Not sure if that is a bug or not.
3160     if (!_private)
3161         return nil;
3162
3163     if (!_private->editingDelegateForwarder)
3164         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3165     return _private->editingDelegateForwarder;
3166 }
3167
3168 - (void)_closeWindow
3169 {
3170     [[self _UIDelegateForwarder] webViewClose:self];
3171 }
3172
3173 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3174 {
3175     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3176     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3177     
3178     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3179     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3180     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3181     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3182 }
3183
3184 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3185 {
3186     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3187     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3188
3189     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3190     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3191     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3192     if ([viewClass class] == [WebHTMLView class])
3193         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3194     
3195     // This is used to make _representationExistsForURLScheme faster.
3196     // Without this set, we'd have to create the MIME type each time.
3197     if (schemesWithRepresentationsSet == nil) {
3198         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3199     }
3200     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3201 }
3202
3203 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3204 {
3205     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3206 }
3207
3208 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3209 {
3210     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3211 }
3212
3213 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3214 {
3215     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3216     if (!request)
3217         return NO;
3218
3219     if ([NSURLConnection canHandleRequest:request])
3220         return YES;
3221
3222     NSString *scheme = [[request URL] scheme];
3223
3224     // Representations for URL schemes work at the top level.
3225     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3226         return YES;
3227
3228     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3229         return YES;
3230
3231     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3232         return YES;
3233
3234     return NO;
3235 }
3236
3237 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3238 {
3239     return [self _canHandleRequest:request forMainFrame:YES];
3240 }
3241
3242 + (NSString *)_decodeData:(NSData *)data
3243 {
3244     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3245     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3246 }
3247
3248 - (void)_pushPerformingProgrammaticFocus
3249 {
3250     _private->programmaticFocusCount++;
3251 }
3252
3253 - (void)_popPerformingProgrammaticFocus
3254 {
3255     _private->programmaticFocusCount--;
3256 }
3257
3258 - (BOOL)_isPerformingProgrammaticFocus
3259 {
3260     return _private->programmaticFocusCount != 0;
3261 }
3262
3263 #if !PLATFORM(IOS)
3264 - (void)_didChangeValueForKey: (NSString *)key
3265 {
3266     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3267     [self didChangeValueForKey: key];
3268 }
3269
3270 - (void)_willChangeValueForKey: (NSString *)key
3271 {
3272     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3273     [self willChangeValueForKey: key];
3274 }
3275
3276 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3277     static NSSet *manualNotifyKeys = nil;
3278     if (!manualNotifyKeys)
3279         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3280             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3281             nil];
3282     if ([manualNotifyKeys containsObject:key])
3283         return NO;
3284     return YES;
3285 }
3286
3287 - (NSArray *)_declaredKeys {
3288     static NSArray *declaredKeys = nil;
3289     if (!declaredKeys)
3290         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3291             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3292     return declaredKeys;
3293 }
3294
3295 - (void)_willChangeBackForwardKeys
3296 {
3297     [self _willChangeValueForKey: _WebCanGoBackKey];
3298     [self _willChangeValueForKey: _WebCanGoForwardKey];
3299 }
3300
3301 - (void)_didChangeBackForwardKeys
3302 {
3303     [self _didChangeValueForKey: _WebCanGoBackKey];
3304     [self _didChangeValueForKey: _WebCanGoForwardKey];
3305 }
3306
3307 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3308 {
3309     if (needsSelfRetainWhileLoadingQuirk())
3310         [self retain];
3311
3312     [self _willChangeBackForwardKeys];
3313     if (frame == [self mainFrame]){
3314         // Force an observer update by sending a will/did.
3315         [self _willChangeValueForKey: _WebIsLoadingKey];
3316         [self _didChangeValueForKey: _WebIsLoadingKey];
3317
3318         [self _willChangeValueForKey: _WebMainFrameURLKey];
3319
3320         [self hideFormValidationMessage];
3321     }
3322
3323     [NSApp setWindowsNeedUpdate:YES];
3324
3325 #if ENABLE(FULLSCREEN_API)
3326     Document* document = core([frame DOMDocument]);
3327     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3328         SEL selector = @selector(webView:closeFullScreenWithListener:);
3329         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
3330             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3331             CallUIDelegate(self, selector, listener);
3332             [listener release];
3333         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3334             [_private->newFullscreenController close];
3335         }
3336     }
3337 #endif
3338 }
3339
3340 - (void)_checkDidPerformFirstNavigation
3341 {
3342     if (_private->_didPerformFirstNavigation)
3343         return;
3344
3345     Page* page = _private->page;
3346     if (!page)
3347         return;
3348
3349     auto& backForwardController = page->backForward();
3350
3351     if (!backForwardController.backItem())
3352         return;
3353
3354     _private->_didPerformFirstNavigation = YES;
3355
3356     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3357         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3358 }
3359
3360 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3361 {
3362     if (frame == [self mainFrame])
3363         [self _didChangeValueForKey: _WebMainFrameURLKey];
3364
3365     [self _checkDidPerformFirstNavigation];
3366
3367     [NSApp setWindowsNeedUpdate:YES];
3368 }
3369
3370 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3371 {
3372     if (needsSelfRetainWhileLoadingQuirk())
3373         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3374         
3375     [self _didChangeBackForwardKeys];
3376     if (frame == [self mainFrame]){
3377         // Force an observer update by sending a will/did.
3378         [self _willChangeValueForKey: _WebIsLoadingKey];
3379         [self _didChangeValueForKey: _WebIsLoadingKey];
3380     }
3381     [NSApp setWindowsNeedUpdate:YES];
3382 }
3383
3384 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3385 {
3386     if (needsSelfRetainWhileLoadingQuirk())
3387         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3388
3389     [self _didChangeBackForwardKeys];
3390     if (frame == [self mainFrame]){
3391         // Force an observer update by sending a will/did.
3392         [self _willChangeValueForKey: _WebIsLoadingKey];
3393         [self _didChangeValueForKey: _WebIsLoadingKey];
3394     }
3395     [NSApp setWindowsNeedUpdate:YES];
3396 }
3397
3398 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3399 {
3400     if (needsSelfRetainWhileLoadingQuirk())
3401         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3402
3403     [self _didChangeBackForwardKeys];
3404     if (frame == [self mainFrame]){
3405         // Force an observer update by sending a will/did.
3406         [self _willChangeValueForKey: _WebIsLoadingKey];
3407         [self _didChangeValueForKey: _WebIsLoadingKey];
3408         
3409         [self _didChangeValueForKey: _WebMainFrameURLKey];
3410     }
3411     [NSApp setWindowsNeedUpdate:YES];
3412 }
3413
3414 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3415 {
3416     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3417     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3418     NSCachedURLResponse *cachedResponse;
3419
3420     if (!_private->page)
3421         return nil;
3422
3423     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3424         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3425     else
3426         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3427
3428     return cachedResponse;
3429 }
3430
3431 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3432 {
3433     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3434     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3435     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3436                         element:domElement
3437                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3438                           title:[element objectForKey:WebElementImageAltStringKey] 
3439                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3440                           types:types
3441                          source:nil];
3442 }
3443
3444 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3445 {
3446     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3447                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3448                         types:types];
3449 }
3450
3451 #if ENABLE(DRAG_SUPPORT)
3452 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3453 {
3454     if (!_private->page)
3455         return;
3456     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3457 }
3458 #endif
3459
3460 #else
3461
3462 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3463 {
3464     if (frame == [self mainFrame])
3465         _private->didDrawTiles = 0;
3466 }
3467
3468 #endif // PLATFORM(IOS)
3469
3470 #if ENABLE(DASHBOARD_SUPPORT)
3471
3472 #define DASHBOARD_CONTROL_LABEL @"control"
3473
3474 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3475 {
3476     NSRect adjustedBounds = bounds;
3477     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3478     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3479     adjustedBounds.size = bounds.size;
3480
3481     NSRect adjustedClip;
3482     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3483     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3484     adjustedClip.size = clip.size;
3485
3486     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3487         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3488     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3489     if (!scrollerRegions) {
3490         scrollerRegions = [[NSMutableArray alloc] init];
3491         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3492         [scrollerRegions release];
3493     }
3494     [scrollerRegions addObject:region];
3495     [region release];
3496 }
3497
3498 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3499 {    
3500     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3501
3502     for (const auto& widget: frameView->children()) {
3503         if (is<FrameView>(widget)) {
3504             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3505             continue;
3506         }
3507
3508         if (!widget->isScrollbar())
3509             continue;
3510
3511         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3512         // it's not common to need this to be correct in Dashboard widgets.
3513         NSRect bounds = widget->frameRect();
3514         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3515     }
3516 }
3517
3518 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3519 {
3520     // Add scroller regions for NSScroller and WebCore scrollbars
3521     NSUInteger count = [views count];
3522     for (NSUInteger i = 0; i < count; i++) {
3523         NSView *view = [views objectAtIndex:i];
3524         
3525         if ([view isKindOfClass:[WebHTMLView class]]) {
3526             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3527                 if (FrameView* coreView = coreFrame->view())
3528                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3529             }
3530         } else if ([view isKindOfClass:[NSScroller class]]) {
3531             // AppKit places absent scrollers at -100,-100
3532             if ([view frame].origin.y < 0)
3533                 continue;
3534             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3535         }
3536         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3537     }
3538 }
3539
3540 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3541 {
3542     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3543 }
3544
3545 - (NSDictionary *)_dashboardRegions
3546 {
3547     // Only return regions from main frame.
3548     Frame* mainFrame = [self _mainCoreFrame];
3549     if (!mainFrame)
3550         return nil;
3551
3552     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3553     size_t size = regions.size();
3554
3555     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3556     for (size_t i = 0; i < size; i++) {
3557         const AnnotatedRegionValue& region = regions[i];
3558
3559         if (region.type == StyleDashboardRegion::None)
3560             continue;
3561
3562         NSString *label = region.label;
3563         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3564         if (region.type == StyleDashboardRegion::Circle)
3565             type = WebDashboardRegionTypeCircle;
3566         else if (region.type == StyleDashboardRegion::Rectangle)
3567             type = WebDashboardRegionTypeRectangle;
3568         NSMutableArray *regionValues = [webRegions objectForKey:label];
3569         if (!regionValues) {
3570             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3571             [webRegions setObject:regionValues forKey:label];
3572             [regionValues release];
3573         }
3574
3575         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3576         [regionValues addObject:webRegion];
3577         [webRegion release];
3578     }
3579
3580     [self _addScrollerDashboardRegions:webRegions];
3581
3582     return webRegions;
3583 }
3584
3585 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3586 {
3587     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3588     // specific support for the backward compatibility mode flag.
3589     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3590         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3591     
3592     switch (behavior) {
3593         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3594             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3595             break;
3596         }
3597         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3598             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3599             break;
3600         }
3601         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3602             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3603             break;
3604         }
3605         case WebDashboardBehaviorAllowWheelScrolling: {
3606             _private->dashboardBehaviorAllowWheelScrolling = flag;
3607             break;
3608         }
3609         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3610             if (_private->page)
3611                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3612 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3613             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3614 #endif
3615             break;
3616         }
3617     }
3618
3619     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3620     // compatibility mode. See <rdar://problem/8175982>.
3621     if (_private->page)
3622         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3623 }
3624
3625 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3626 {
3627     switch (behavior) {
3628         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3629             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3630         }
3631         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3632             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3633         }
3634         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3635             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3636         }
3637         case WebDashboardBehaviorAllowWheelScrolling: {
3638             return _private->dashboardBehaviorAllowWheelScrolling;
3639         }
3640         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3641             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3642         }
3643     }
3644     return NO;
3645 }
3646
3647 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3648
3649 + (void)_setShouldUseFontSmoothing:(BOOL)f
3650 {
3651     FontCascade::setShouldUseSmoothing(f);
3652 }
3653
3654 + (BOOL)_shouldUseFontSmoothing
3655 {
3656     return FontCascade::shouldUseSmoothing();
3657 }
3658
3659 #if !PLATFORM(IOS)
3660 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3661 {
3662     setUsesTestModeFocusRingColor(f);
3663 }
3664
3665 + (BOOL)_usesTestModeFocusRingColor
3666 {
3667     return usesTestModeFocusRingColor();
3668 }
3669 #endif
3670
3671 #if PLATFORM(IOS)
3672 - (void)_setUIKitDelegate:(id)delegate
3673 {
3674     _private->UIKitDelegate = delegate;
3675     [_private->UIKitDelegateForwarder clearTarget];
3676     [_private->UIKitDelegateForwarder release];
3677     _private->UIKitDelegateForwarder = nil;
3678 }
3679
3680 - (id)_UIKitDelegate
3681 {
3682     return _private->UIKitDelegate;
3683 }
3684
3685 - (void)setWebMailDelegate:(id)delegate
3686 {
3687     _private->WebMailDelegate = delegate;
3688 }
3689
3690 - (id)_webMailDelegate
3691 {
3692     return _private->WebMailDelegate;
3693 }
3694
3695 - (id <WebCaretChangeListener>)caretChangeListener
3696 {
3697     return _private->_caretChangeListener;
3698 }
3699
3700 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3701 {
3702     _private->_caretChangeListener = listener;
3703 }
3704
3705 - (NSSet *)caretChangeListeners
3706 {
3707     return _private->_caretChangeListeners;
3708 }
3709
3710 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3711 {
3712     if (_private->_caretChangeListeners == nil) {
3713         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3714     }
3715     
3716     [_private->_caretChangeListeners addObject:listener];
3717 }
3718
3719 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3720 {
3721     [_private->_caretChangeListeners removeObject:listener];
3722 }
3723
3724 - (void)removeAllCaretChangeListeners
3725 {
3726     [_private->_caretChangeListeners removeAllObjects];
3727 }
3728
3729 - (void)caretChanged
3730 {
3731     [_private->_caretChangeListener caretChanged];
3732     NSSet *copy = [_private->_caretChangeListeners copy];
3733     for (id <WebCaretChangeListener> listener in copy) {
3734         [listener caretChanged];
3735     }
3736     [copy release];
3737 }
3738
3739 - (void)_clearDelegates
3740 {
3741     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3742     
3743     [self _setFormDelegate:nil];
3744     [self _setUIKitDelegate:nil];
3745     [self setCaretChangeListener:nil];
3746     [self removeAllCaretChangeListeners];
3747     [self setWebMailDelegate:nil];
3748     
3749     [self setDownloadDelegate:nil];
3750     [self setEditingDelegate:nil]; 
3751     [self setFrameLoadDelegate:nil];
3752     [self setPolicyDelegate:nil];
3753     [self setResourceLoadDelegate:nil];
3754     [self setScriptDebugDelegate:nil];
3755     [self setUIDelegate:nil];     
3756 }
3757
3758 - (NSURL *)_displayURL
3759 {
3760     WebThreadLock();
3761     WebFrame *frame = [self mainFrame];
3762     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3763     WebDataSource *dataSource = [frame provisionalDataSource];
3764     if (!dataSource)
3765         dataSource = [frame dataSource];
3766     NSURL *unreachableURL = [dataSource unreachableURL];
3767     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3768     [[URL retain] autorelease];
3769     return URL;
3770 }
3771 #endif // PLATFORM(IOS)
3772
3773 #if !PLATFORM(IOS)
3774 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3775 {
3776     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3777     if (flag) {
3778         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3779     } else {
3780         [scrollview setVerticalScrollingModeLocked:NO];
3781         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3782     }
3783 }
3784
3785 - (BOOL)alwaysShowVerticalScroller
3786 {
3787     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3788     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3789 }
3790
3791 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3792 {
3793     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3794     if (flag) {
3795         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3796     } else {
3797         [scrollview setHorizontalScrollingModeLocked:NO];
3798         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3799     }
3800 }
3801
3802 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3803 {
3804     if (Frame* mainFrame = [self _mainCoreFrame])
3805         mainFrame->view()->setProhibitsScrolling(prohibits);
3806 }
3807
3808 - (BOOL)alwaysShowHorizontalScroller
3809 {
3810     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3811     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3812 }
3813 #endif // !PLATFORM(IOS)
3814
3815 - (void)_setUseFastImageScalingMode:(BOOL)flag
3816 {
3817     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3818         _private->page->setInLowQualityImageInterpolationMode(flag);
3819         [self setNeedsDisplay:YES];
3820     }
3821 }
3822
3823 - (BOOL)_inFastImageScalingMode
3824 {
3825     if (_private->page)
3826         return _private->page->inLowQualityImageInterpolationMode();
3827     return NO;
3828 }
3829
3830 - (BOOL)_cookieEnabled
3831 {
3832     if (_private->page)
3833         return _private->page->settings().cookieEnabled();
3834     return YES;
3835 }
3836
3837 - (void)_setCookieEnabled:(BOOL)enable
3838 {
3839     if (_private->page)
3840         _private->page->settings().setCookieEnabled(enable);
3841 }
3842
3843 #if !PLATFORM(IOS)
3844 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3845 {
3846     if (!_private->pluginDatabase)
3847         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3848         
3849     [_private->pluginDatabase setPlugInPaths:newPaths];
3850     [_private->pluginDatabase refresh];
3851 }
3852 #endif
3853
3854 #if PLATFORM(IOS)
3855 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3856 {
3857     // Ask plug-ins in this frame
3858     id <WebDocumentView> documentView = [[frame frameView] documentView];
3859     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3860         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3861             return YES;
3862     }
3863
3864     // Ask plug-ins in child frames
3865     NSArray *childFrames = [frame childFrames];
3866     unsigned childCount = [childFrames count];
3867     unsigned childIndex;
3868     for (childIndex = 0; childIndex < childCount; childIndex++) {
3869         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3870             return YES;
3871     }
3872     
3873     return NO;
3874 }
3875
3876 - (BOOL)_pluginsAreRunning
3877 {
3878     WebThreadLock();
3879     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3880 }
3881
3882 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3883 {
3884     // Send the message to plug-ins in this frame
3885     id <WebDocumentView> documentView = [[frame frameView] documentView];
3886     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3887         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3888
3889     // Send the message to plug-ins in child frames
3890     NSArray *childFrames = [frame childFrames];
3891     unsigned childCount = [childFrames count];
3892     unsigned childIndex;
3893     for (childIndex = 0; childIndex < childCount; childIndex++) {
3894         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3895     }
3896 }
3897
3898 - (void)_destroyAllPlugIns
3899 {
3900     WebThreadLock();
3901     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3902 }
3903
3904 - (void)_startAllPlugIns
3905 {
3906     WebThreadLock();
3907     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3908 }
3909
3910 - (void)_stopAllPlugIns
3911 {
3912     WebThreadLock();
3913     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3914 }
3915
3916 - (void)_stopAllPlugInsForPageCache
3917 {
3918     WebThreadLock();
3919     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3920 }
3921
3922 - (void)_restorePlugInsFromCache
3923 {
3924     WebThreadLock();
3925     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3926 }
3927
3928 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3929 {
3930     WebThreadLock();
3931
3932     Frame* mainCoreFrame = [self _mainCoreFrame];
3933     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3934         FrameView* coreView = frame ? frame->view() : 0;
3935         if (!coreView)
3936             continue;
3937
3938         // Get the GraphicsLayer for this widget.
3939         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3940         if (!layerForWidget)
3941             continue;
3942         
3943         if (layerForWidget->contentsLayerForMedia() != layer) {
3944             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3945             // We need to make sure the layer hierachy change is applied immediately.
3946             if (mainCoreFrame->view())
3947                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3948             return YES;
3949         }
3950     }
3951
3952     return NO;
3953 }
3954
3955 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3956 {
3957     if (_private->page)
3958         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3959 }
3960 #endif // PLATFORM(IOS)
3961
3962 - (void)_attachScriptDebuggerToAllFrames
3963 {
3964     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3965         [kit(frame) _attachScriptDebugger];
3966 }
3967
3968 - (void)_detachScriptDebuggerFromAllFrames
3969 {
3970     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3971         [kit(frame) _detachScriptDebugger];
3972 }
3973
3974 #if !PLATFORM(IOS)
3975 - (void)setBackgroundColor:(NSColor *)backgroundColor
3976 {
3977     if ([_private->backgroundColor isEqual:backgroundColor])
3978         return;
3979
3980     id old = _private->backgroundColor;
3981     _private->backgroundColor = [backgroundColor retain];
3982     [old release];
3983
3984     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3985 }
3986
3987 - (NSColor *)backgroundColor
3988 {
3989     return _private->backgroundColor;
3990 }
3991 #else
3992 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3993 {
3994    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3995         return;
3996
3997     CFTypeRef old = _private->backgroundColor;
3998     CFRetain(backgroundColor);
3999     _private->backgroundColor = backgroundColor;
4000     CFRelease(old);
4001
4002     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
4003 }
4004
4005 - (CGColorRef)backgroundColor
4006 {
4007     return _private->backgroundColor;
4008 }
4009 #endif
4010
4011 - (BOOL)defersCallbacks
4012 {
4013     if (!_private->page)
4014         return NO;
4015     return _private->page->defersLoading();
4016 }
4017
4018 - (void)setDefersCallbacks:(BOOL)defer
4019 {
4020     if (!_private->page)
4021         return;
4022     return _private->page->setDefersLoading(defer);
4023 }
4024
4025 #if PLATFORM(IOS)
4026 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
4027 {
4028 #if USE(QUICK_LOOK)
4029     NSString *uti = qlPreviewConverterUTIForURL(url);
4030     if (!uti)
4031         return nil;
4032
4033     NSString *fileName = qlPreviewConverterFileNameForURL(url);
4034     if (!fileName)
4035         return nil;
4036
4037     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
4038 #else
4039     return nil;
4040 #endif
4041 }
4042
4043 - (BOOL)_isStopping
4044 {
4045     return _private->isStopping;
4046 }
4047
4048 - (BOOL)_isClosing
4049 {
4050     return _private->closing;
4051 }
4052
4053 + (NSArray *)_productivityDocumentMIMETypes
4054 {
4055 #if USE(QUICK_LOOK)
4056     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
4057 #else
4058     return nil;
4059 #endif
4060 }
4061
4062 - (void)_setAllowsMessaging:(BOOL)aFlag
4063 {
4064     _private->allowsMessaging = aFlag;
4065 }
4066
4067 - (BOOL)_allowsMessaging
4068 {
4069     return _private->allowsMessaging;
4070 }
4071
4072 - (void)_setFixedLayoutSize:(CGSize)size
4073 {
4074     ASSERT(WebThreadIsLocked());
4075     _private->fixedLayoutSize = size;
4076     if (Frame* mainFrame = core([self mainFrame])) {
4077         IntSize newSize(size);
4078         mainFrame->view()->setFixedLayoutSize(newSize);
4079         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
4080         [self setNeedsDisplay:YES];
4081     }
4082 }
4083
4084 - (CGSize)_fixedLayoutSize
4085 {
4086     return _private->fixedLayoutSize;
4087 }
4088
4089 - (void)_synchronizeCustomFixedPositionLayoutRect
4090 {
4091     ASSERT(WebThreadIsLocked());
4092
4093     IntRect newRect;
4094     {
4095         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4096         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4097             return;
4098         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
4099         _private->pendingFixedPositionLayoutRect = CGRectNull;
4100     }
4101
4102     if (Frame* mainFrame = core([self mainFrame]))
4103         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
4104 }
4105
4106 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
4107 {
4108     {
4109         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4110         _private->pendingFixedPositionLayoutRect = rect;
4111     }
4112     if (!synchronize)
4113         return;
4114     WebThreadRun(^{
4115         [self _synchronizeCustomFixedPositionLayoutRect];
4116     });
4117 }
4118
4119 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
4120 {
4121     ASSERT(WebThreadIsLocked());
4122     {
4123         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4124         _private->pendingFixedPositionLayoutRect = rect;
4125     }
4126     [self _synchronizeCustomFixedPositionLayoutRect];
4127 }
4128
4129 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
4130 {
4131     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4132     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4133         return false;
4134
4135     *rect = _private->pendingFixedPositionLayoutRect;
4136     _private->pendingFixedPositionLayoutRect = CGRectNull;
4137     return true;
4138 }
4139
4140 - (void)_viewGeometryDidChange
4141 {
4142     ASSERT(WebThreadIsLocked());
4143     
4144     if (Frame* coreFrame = [self _mainCoreFrame])
4145         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
4146 }
4147
4148 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
4149 {
4150     // Find the frame
4151     Node* node = core(domNode);
4152     Frame* frame = node->document().frame();
4153     if (!frame)
4154         return;
4155
4156     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
4157 }
4158
4159 + (void)_doNotStartObservingNetworkReachability
4160 {
4161     Settings::setShouldOptOutOfNetworkStateObservation(true);
4162 }
4163 #endif // PLATFORM(IOS)
4164
4165 #if ENABLE(TOUCH_EVENTS)
4166 - (NSArray *)_touchEventRegions
4167 {
4168     Frame* frame = [self _mainCoreFrame];
4169     if (!frame)
4170         return nil;
4171     
4172     Document* document = frame->document();
4173     if (!document)
4174         return nil;
4175
4176     Vector<IntRect> rects;
4177     document->getTouchRects(rects);
4178
4179     if (rects.size() == 0)
4180         return nil;
4181
4182     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
4183
4184     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
4185     Vector<IntRect>::const_iterator end = rects.end();
4186     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
4187         const IntRect& rect = *it;
4188         if (rect.isEmpty())
4189             continue;
4190
4191         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
4192         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
4193         // convert them here now.
4194         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
4195
4196         // The event region wants this points in this order:
4197         //  p2------p3
4198         //  |       |
4199         //  p1------p4
4200         //
4201         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
4202                                                                             :FloatPoint(viewRect.x(), viewRect.y())
4203                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
4204                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
4205         if (eventRegion) {
4206             [eventRegionArray addObject:eventRegion];
4207             [eventRegion release];
4208         }
4209     }
4210
4211     return eventRegionArray;
4212 }
4213 #endif // ENABLE(TOUCH_EVENTS)
4214
4215 // For backwards compatibility with the WebBackForwardList API, we honor both
4216 // a per-WebView and a per-preferences setting for whether to use the page cache.
4217
4218 - (BOOL)usesPageCache
4219 {
4220     return _private->usesPageCache && [[self preferences] usesPageCache];
4221 }
4222
4223 - (void)setUsesPageCache:(BOOL)usesPageCache
4224 {
4225     _private->usesPageCache = usesPageCache;
4226
4227     // Update our own settings and post the public notification only
4228     [self _preferencesChanged:[self preferences]];
4229     [[self preferences] _postPreferencesChangedAPINotification];
4230 }
4231
4232 - (WebHistoryItem *)_globalHistoryItem
4233 {
4234     if (!_private)
4235         return nil;
4236
4237     return kit(_private->_globalHistoryItem.get());
4238 }
4239
4240 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
4241 {
4242     _private->_globalHistoryItem = historyItem;
4243 }
4244
4245 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
4246 {
4247     IntPoint rectStart(rect.origin.x, rect.origin.y);
4248     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
4249     
4250     Frame* coreFrame = [self _mainCoreFrame];
4251     if (!coreFrame)
4252         return nil;
4253     
4254     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
4255     
4256     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
4257 }
4258
4259 #if !PLATFORM(IOS)
4260 - (void)_clearUndoRedoOperations
4261 {
4262     if (!_private->page)