Refactor drag and drop implementation on Mac
[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     if (!toJSDOMWindow(execState->lexicalGlobalObject()))
1060         return;
1061
1062     reportException(execState, toJS(execState, exception));
1063 }
1064
1065 static void WebKitInitializeApplicationStatisticsStoragePathIfNecessary()
1066 {
1067     static BOOL initialized = NO;
1068     if (initialized)
1069         return;
1070     
1071     resourceLoadStatisticsStore = &WebCore::ResourceLoadStatisticsStore::create().leakRef();
1072     ResourceLoadObserver::sharedObserver().setStatisticsStore(*resourceLoadStatisticsStore);
1073     
1074     initialized = YES;
1075 }
1076
1077 static bool shouldEnableLoadDeferring()
1078 {
1079 #if PLATFORM(IOS)
1080     return true;
1081 #else
1082     return !MacApplication::isAdobeInstaller();
1083 #endif
1084 }
1085
1086 static bool shouldRestrictWindowFocus()
1087 {
1088 #if PLATFORM(IOS)
1089     return true;
1090 #else
1091     return !MacApplication::isHRBlock();
1092 #endif
1093 }
1094
1095 - (void)_dispatchPendingLoadRequests
1096 {
1097     webResourceLoadScheduler().servePendingRequests();
1098 }
1099
1100 #if !PLATFORM(IOS)
1101
1102 - (void)_registerDraggedTypes
1103 {
1104     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1105     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1106     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1107     [types addObjectsFromArray:URLTypes];
1108     [types addObject:[WebHTMLView _dummyPasteboardType]];
1109     [self registerForDraggedTypes:[types allObjects]];
1110     [types release];
1111 }
1112
1113 static bool needsOutlookQuirksScript()
1114 {
1115     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1116         && MacApplication::isMicrosoftOutlook();
1117     return isOutlookNeedingQuirksScript;
1118 }
1119
1120 static NSString *leakOutlookQuirksUserScriptContents()
1121 {
1122     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1123     NSStringEncoding encoding;
1124     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1125 }
1126
1127 -(void)_injectOutlookQuirksScript
1128 {
1129     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1130     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1131
1132 }
1133 #endif
1134
1135 static bool shouldRespectPriorityInCSSAttributeSetters()
1136 {
1137 #if PLATFORM(IOS)
1138     static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1139         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
1140     return isStanzaNeedingAttributeSetterQuirk;
1141 #else
1142     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1143         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1144     return isIAdProducerNeedingAttributeSetterQuirk;
1145 #endif
1146 }
1147
1148 #if PLATFORM(IOS)
1149 static bool shouldTransformsAffectOverflow()
1150 {
1151     static bool shouldTransformsAffectOverflow = !IOSApplication::isOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
1152     return shouldTransformsAffectOverflow;
1153 }
1154
1155 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
1156 {
1157     static bool shouldDispatchJavaScriptWindowOnErrorEvents = !IOSApplication::isFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
1158     return shouldDispatchJavaScriptWindowOnErrorEvents;
1159 }
1160
1161 static bool isInternalInstall()
1162 {
1163     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1164     return isInternal;
1165 }
1166
1167 static bool didOneTimeInitialization = false;
1168 #endif
1169
1170 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1171 {
1172 #if PLATFORM(IOS)
1173     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1174 #else
1175     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1176         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1177 #endif
1178     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1179 }
1180
1181 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1182 {
1183     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1184     return shouldAllowDisplayAndRunningOfInsecureContent;
1185 }
1186
1187 static bool shouldAllowPictureInPictureMediaPlayback()
1188 {
1189 #if PLATFORM(IOS)
1190     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1191     return shouldAllowPictureInPictureMediaPlayback;
1192 #else
1193     return false;
1194 #endif
1195 }
1196
1197 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1198 {
1199 #if PLATFORM(IOS)
1200     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1201     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1202 #else
1203     return false;
1204 #endif
1205 }
1206
1207 static bool shouldAllowWindowOpenWithoutUserGesture()
1208 {
1209 #if PLATFORM(IOS)
1210     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1211     return shouldAllowWindowOpenWithoutUserGesture;
1212 #else
1213     return false;
1214 #endif
1215 }
1216
1217 static bool shouldConvertInvalidURLsToBlank()
1218 {
1219 #if PLATFORM(IOS)
1220     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1221 #elif PLATFORM(MAC)
1222     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1223 #else
1224     static bool shouldConvertInvalidURLsToBlank = true;
1225 #endif
1226
1227     return shouldConvertInvalidURLsToBlank;
1228 }
1229
1230 static bool shouldRequireUserGestureToLoadVideo()
1231 {
1232 #if PLATFORM(IOS)
1233     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1234     return shouldRequireUserGestureToLoadVideo;
1235 #else
1236     return true;
1237 #endif
1238 }
1239
1240 #if ENABLE(GAMEPAD)
1241 static void WebKitInitializeGamepadProviderIfNecessary()
1242 {
1243     static bool initialized = false;
1244     if (initialized)
1245         return;
1246
1247 #if PLATFORM(MAC)
1248     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1249 #else
1250     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1251 #endif
1252
1253     initialized = true;
1254 }
1255 #endif
1256
1257 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1258 {
1259     WebCoreThreadViolationCheckRoundTwo();
1260
1261 #ifndef NDEBUG
1262     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1263 #endif
1264     
1265     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1266     [standardPreferences willAddToWebView];
1267
1268     _private->preferences = [standardPreferences retain];
1269     _private->mainFrameDocumentReady = NO;
1270     _private->drawsBackground = YES;
1271 #if !PLATFORM(IOS)
1272     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1273 #else
1274     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1275 #endif
1276     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
1277
1278 #if PLATFORM(MAC)
1279     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1280 #endif
1281
1282     NSRect f = [self frame];
1283     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1284     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1285     [self addSubview:frameView];
1286     [frameView release];
1287
1288 #if PLATFORM(MAC)
1289     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1290         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1291         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1292         [recognizer setDelegate:_private->immediateActionController];
1293         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1294     }
1295 #endif
1296
1297     [self updateTouchBar];
1298
1299 #if !PLATFORM(IOS)
1300     static bool didOneTimeInitialization = false;
1301 #endif
1302     if (!didOneTimeInitialization) {
1303 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1304         WebKitInitializeLogChannelsIfNecessary();
1305         WebCore::initializeLogChannelsIfNecessary();
1306 #endif
1307
1308         // Initialize our platform strategies first before invoking the rest
1309         // of the initialization code which may depend on the strategies.
1310         WebPlatformStrategies::initializeIfNecessary();
1311
1312         initializeDOMWrapperHooks();
1313
1314 #if PLATFORM(IOS)
1315         // Set the WebSQLiteDatabaseTrackerClient.
1316         SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1317
1318         if ([standardPreferences databasesEnabled])
1319 #endif
1320         [WebDatabaseManager sharedWebDatabaseManager];
1321
1322 #if PLATFORM(IOS)        
1323         if ([standardPreferences storageTrackerEnabled])
1324 #endif
1325         WebKitInitializeStorageIfNecessary();
1326
1327         WebKitInitializeApplicationStatisticsStoragePathIfNecessary();
1328
1329 #if ENABLE(GAMEPAD)
1330         WebKitInitializeGamepadProviderIfNecessary();
1331 #endif
1332         
1333         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1334
1335 #if PLATFORM(IOS)
1336         if (IOSApplication::isMobileSafari())
1337             Settings::setShouldManageAudioSessionCategory(true);
1338 #endif
1339
1340         didOneTimeInitialization = true;
1341     }
1342
1343     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1344     _private->group->addWebView(self);
1345
1346     PageConfiguration pageConfiguration(
1347         makeUniqueRef<WebEditorClient>(self),
1348         SocketProvider::create(),
1349         makeUniqueRef<WebCore::LibWebRTCProvider>()
1350     );
1351 #if !PLATFORM(IOS)
1352     pageConfiguration.chromeClient = new WebChromeClient(self);
1353     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1354     // FIXME: We should enable this on iOS as well.
1355     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1356 #if ENABLE(DRAG_SUPPORT)
1357     pageConfiguration.dragClient = new WebDragClient(self);
1358 #endif
1359     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1360 #else
1361     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1362     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1363 #endif
1364
1365     pageConfiguration.backForwardClient = BackForwardList::create(self);
1366
1367 #if ENABLE(APPLE_PAY)
1368     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1369 #endif
1370
1371     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1372     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1373     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1374     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1375     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1376     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1377     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1378     pageConfiguration.userContentProvider = &_private->group->userContentController();
1379     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1380     _private->page = new Page(WTFMove(pageConfiguration));
1381
1382     _private->page->setGroupName(groupName);
1383
1384 #if ENABLE(GEOLOCATION)
1385     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
1386 #endif
1387 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
1388     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1389 #endif
1390 #if ENABLE(DEVICE_ORIENTATION)
1391 #if !PLATFORM(IOS)
1392     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1393 #endif
1394 #endif
1395 #if ENABLE(MEDIA_STREAM)
1396     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1397 #endif
1398
1399 #if ENABLE(REMOTE_INSPECTOR)
1400     _private->page->setRemoteInspectionAllowed(true);
1401 #endif
1402
1403     _private->page->setCanStartMedia([self window]);
1404     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1405     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1406
1407 #if !PLATFORM(IOS)
1408     if (needsOutlookQuirksScript()) {
1409         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1410         [self _injectOutlookQuirksScript];
1411     }
1412 #endif
1413
1414 #if PLATFORM(IOS)
1415     // Preserve the behavior we had before <rdar://problem/7580867>
1416     // by enforcing a 5MB limit for session storage.
1417     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1418
1419     [self _updateScreenScaleFromWindow];
1420     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1421     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1422     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1423 #endif
1424
1425     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1426         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1427
1428     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1429
1430 #if PLATFORM(IOS)
1431     NSRunLoop *runLoop = WebThreadNSRunLoop();
1432 #else
1433     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1434 #endif
1435
1436     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1437         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1438     else
1439         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1440
1441     [self _addToAllWebViewsSet];
1442     
1443     // If there's already a next key view (e.g., from a nib), wire it up to our
1444     // contained frame view. In any case, wire our next key view up to the our
1445     // contained frame view. This works together with our becomeFirstResponder 
1446     // and setNextKeyView overrides.
1447     NSView *nextKeyView = [self nextKeyView];
1448     if (nextKeyView && nextKeyView != frameView)
1449         [frameView setNextKeyView:nextKeyView];
1450     [super setNextKeyView:frameView];
1451
1452     if ([[self class] shouldIncludeInWebKitStatistics])
1453         ++WebViewCount;
1454
1455 #if !PLATFORM(IOS)
1456     [self _registerDraggedTypes];
1457 #endif
1458
1459     [self _setIsVisible:[self _isViewVisible]];
1460
1461     WebPreferences *prefs = [self preferences];
1462     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1463                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1464
1465 #if !PLATFORM(IOS)
1466     [self _preferencesChanged:[self preferences]];
1467     [[self preferences] _postPreferencesChangedAPINotification];
1468 #else
1469     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1470     // and prefs need to be changed synchronously <rdar://problem/5841558>
1471     [self _preferencesChanged:prefs];
1472     _private->page->settings().setFontFallbackPrefersPictographs(true);
1473 #endif
1474
1475     WebInstallMemoryPressureHandler();
1476
1477     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1478         // Originally, we allowed all local loads.
1479         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1480     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1481         // Later, we allowed local loads for local URLs and documents loaded
1482         // with substitute data.
1483         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1484     }
1485
1486 #if PLATFORM(MAC)
1487     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1488         ResourceHandle::forceContentSniffing();
1489
1490     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1491 #endif
1492
1493     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1494 }
1495
1496 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1497 {
1498     self = [super initWithFrame:f];
1499     if (!self)
1500         return nil;
1501
1502 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1503     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1504     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1505     // need for Safari to unset it to prevent it from being passed to applications it launches.
1506     // Unsetting it when a WebView is first created is as good a place as any.
1507     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1508     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1509         unsetenv("DYLD_FRAMEWORK_PATH");
1510         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1511     }
1512 #endif
1513
1514     _private = [[WebViewPrivate alloc] init];
1515     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1516     [self setMaintainsBackForwardList: YES];
1517     return self;
1518 }
1519
1520 - (void)_viewWillDrawInternal
1521 {
1522     Frame* frame = [self _mainCoreFrame];
1523     if (frame && frame->view())
1524         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1525 }
1526
1527 + (NSArray *)_supportedMIMETypes
1528 {
1529     // Load the plug-in DB allowing plug-ins to install types.
1530     [WebPluginDatabase sharedDatabase];
1531     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1532 }
1533
1534 #if !PLATFORM(IOS)
1535 + (NSArray *)_supportedFileExtensions
1536 {
1537     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1538     NSArray *MIMETypes = [self _supportedMIMETypes];
1539     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1540     NSString *MIMEType;
1541     while ((MIMEType = [enumerator nextObject]) != nil) {
1542         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1543         if (extensionsForType) {
1544             [extensions addObjectsFromArray:extensionsForType];
1545         }
1546     }
1547     NSArray *uniqueExtensions = [extensions allObjects];
1548     [extensions release];
1549     return uniqueExtensions;
1550 }
1551 #endif
1552
1553 #if PLATFORM(IOS)
1554 + (void)enableWebThread
1555 {
1556     static BOOL isWebThreadEnabled = NO;
1557     if (!isWebThreadEnabled) {
1558         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1559         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1560         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1561         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1562         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1563         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1564         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1565         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1566         WebCoreObjCDeallocOnWebThread([WebView class]);
1567         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1568         if (IOSApplication::isTheEconomistOnIphone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1569             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1570         WebThreadEnable();
1571         isWebThreadEnabled = YES;
1572     }
1573 }
1574
1575 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1576 {
1577     self = [super initWithFrame:frame];
1578     if (!self)
1579         return nil;
1580     
1581     _private = [[WebViewPrivate alloc] init];
1582     
1583 #ifndef NDEBUG
1584     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1585 #endif
1586     
1587     if (!preferences)
1588         preferences = [WebPreferences standardPreferences];
1589     [preferences willAddToWebView];
1590     
1591     _private->preferences = [preferences retain];
1592     _private->mainFrameDocumentReady = NO;
1593     _private->drawsBackground = YES;
1594     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1595
1596     WebFrameView *frameView = nil;
1597     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1598     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1599     [self addSubview:frameView];
1600     [frameView release];
1601
1602     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1603     _private->group->addWebView(self);
1604
1605     PageConfiguration pageConfiguration(
1606         makeUniqueRef<WebEditorClient>(self),
1607         SocketProvider::create(),
1608         makeUniqueRef<WebCore::LibWebRTCProvider>()
1609     );
1610     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1611 #if ENABLE(DRAG_SUPPORT) && PLATFORM(MAC)
1612     pageConfiguration.dragClient = new WebDragClient(self);
1613 #endif
1614
1615 #if ENABLE(APPLE_PAY)
1616     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1617 #endif
1618
1619     pageConfiguration.backForwardClient = BackForwardList::create(self);
1620     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1621     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1622     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1623     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1624     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1625     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1626     pageConfiguration.userContentProvider = &_private->group->userContentController();
1627     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1628     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1629
1630     _private->page = new Page(WTFMove(pageConfiguration));
1631     
1632     [self setSmartInsertDeleteEnabled:YES];
1633     
1634     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1635     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1636     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1637     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1638     _private->page->settings().setMinimumLogicalFontSize(9);
1639     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1640     _private->page->settings().setDefaultFixedFontSize(13);
1641     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1642     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1643     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1644     
1645     _private->page->settings().setFontFallbackPrefersPictographs(true);
1646     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1647     
1648     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1649     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1650     
1651     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1652     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1653
1654     // This is a workaround for <rdar://problem/21309911>.
1655     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1656
1657     _private->page->setGroupName(groupName);
1658
1659 #if ENABLE(REMOTE_INSPECTOR)
1660     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1661 #endif
1662     
1663     [self _updateScreenScaleFromWindow];
1664     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1665     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1666
1667     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1668     
1669     [self _addToAllWebViewsSet];
1670     
1671     ++WebViewCount;
1672     
1673     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1674     
1675     return self;
1676 }
1677
1678 + (void)_handleMemoryWarning
1679 {
1680     ASSERT(WebThreadIsCurrent());
1681     WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1682
1683     // Always peform the following.
1684     [WebView purgeInactiveFontData];
1685
1686     // Only perform the remaining if a non-simple document was created.
1687     if (!didOneTimeInitialization)
1688         return;
1689
1690     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1691
1692     [WebStorageManager closeIdleLocalStorageDatabases];
1693     StorageThread::releaseFastMallocFreeMemoryInAllThreads();
1694
1695     [WebView _releaseMemoryNow];
1696 }
1697
1698 + (void)registerForMemoryNotifications
1699 {
1700     BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::IOSApplication::isMobileSafari();
1701
1702     MemoryPressureHandler::singleton().installMemoryReleaseBlock(^{
1703         [WebView _handleMemoryWarning];
1704     }, shouldAutoClearPressureOnMemoryRelease);
1705
1706     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));
1707     dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1708         // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1709         MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1710     });
1711
1712     dispatch_resume(memoryNotificationEventSource);
1713
1714     if (!shouldAutoClearPressureOnMemoryRelease) {
1715         // Listen to memory status notification to reset the memory pressure flag.
1716         static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE,
1717                                                                                     0,
1718                                                                                     DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_NORMAL,
1719                                                                                     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1720         dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1721             unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1722             if (currentStatus == DISPATCH_MEMORYPRESSURE_NORMAL)
1723                 MemoryPressureHandler::singleton().clearMemoryPressure();
1724             else if (currentStatus == DISPATCH_MEMORYPRESSURE_WARN)
1725                 MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1726         });
1727
1728         dispatch_resume(memoryStatusEventSource);
1729     }
1730 }
1731
1732 + (void)_releaseMemoryNow
1733 {
1734     ASSERT(WebThreadIsCurrent());
1735     [WebView discardAllCompiledCode];
1736     [WebView garbageCollectNow];
1737     [WebView purgeInactiveFontData];
1738     [WebView drainLayerPool];
1739     [WebCache emptyInMemoryResources];
1740     [WebView releaseFastMallocMemoryOnCurrentThread];
1741
1742     dispatch_async(dispatch_get_main_queue(), ^{
1743         // Clear the main thread's TCMalloc thread cache.
1744         [WebView releaseFastMallocMemoryOnCurrentThread];
1745     });
1746 }
1747
1748 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1749 {
1750     Frame* frame = [self _mainCoreFrame];
1751     if (frame)
1752         frame->loader().history().replaceCurrentItem(core(item));
1753 }
1754
1755 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1756 {
1757     WebThreadRun(^{
1758         [WebView _releaseMemoryNow];
1759         dispatch_async(dispatch_get_main_queue(), handler);
1760     });
1761 }
1762
1763 + (void)releaseFastMallocMemoryOnCurrentThread
1764 {
1765     WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1766     WTF::releaseFastMallocFreeMemory();
1767 }
1768
1769 + (void)garbageCollectNow
1770 {
1771     ASSERT(WebThreadIsCurrent());
1772     WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1773     WebCore::GCController::singleton().garbageCollectNow();
1774 }
1775
1776 + (void)purgeInactiveFontData
1777 {
1778     ASSERT(WebThreadIsCurrent());
1779     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1780     FontCache::singleton().purgeInactiveFontData();
1781 }
1782
1783 + (void)drainLayerPool
1784 {
1785     ASSERT(WebThreadIsCurrent());
1786     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1787     WebCore::LegacyTileCache::drainLayerPool();
1788 }
1789
1790 + (void)discardAllCompiledCode
1791 {
1792     ASSERT(WebThreadIsCurrent());
1793     WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1794     WebCore::GCController::singleton().deleteAllCode(PreventCollectionAndDeleteAllCode);
1795 }
1796
1797 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1798 {
1799     return WebCore::isCharacterSmartReplaceExempt(character, b);
1800 }
1801
1802 - (void)updateLayoutIgnorePendingStyleSheets
1803 {
1804     WebThreadRun(^{
1805         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1806             Document *document = frame->document();
1807             if (document)
1808                 document->updateLayoutIgnorePendingStylesheets();
1809         }
1810     });
1811 }
1812 #endif // PLATFORM(IOS)
1813
1814 static NSMutableSet *knownPluginMIMETypes()
1815 {
1816     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1817     
1818     return mimeTypes;
1819 }
1820
1821 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1822 {
1823     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1824     [knownPluginMIMETypes() addObject:MIMEType];
1825 }
1826
1827 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1828 {
1829     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1830     [knownPluginMIMETypes() removeObject:MIMEType];
1831 }
1832
1833 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1834 {
1835     MIMEType = [MIMEType lowercaseString];
1836     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1837     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1838
1839 #if PLATFORM(IOS)
1840 #define WebPDFView ([WebView _getPDFViewClass])
1841 #endif
1842     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1843 #if PLATFORM(IOS)
1844 #undef WebPDFView
1845 #endif
1846         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1847
1848         if (allowPlugins) {
1849             // Load the plug-in DB allowing plug-ins to install types.
1850             [WebPluginDatabase sharedDatabase];
1851         }
1852
1853         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1854         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1855         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1856     }
1857     
1858     if (viewClass && repClass) {
1859         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1860             // Special-case WebHTMLView for text types that shouldn't be shown.
1861             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1862                 return NO;
1863
1864             // If the MIME type is a known plug-in we might not want to load it.
1865             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1866                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1867                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1868                 
1869                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1870                 if (!isSupportedByWebKit)
1871                     return NO;
1872             }
1873         }
1874         if (vClass)
1875             *vClass = viewClass;
1876         if (rClass)
1877             *rClass = repClass;
1878         return YES;
1879     }
1880     
1881     return NO;
1882 }
1883
1884 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1885 {
1886     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1887         return YES;
1888 #if !PLATFORM(IOS)
1889     if (_private->pluginDatabase) {
1890         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1891         if (pluginPackage) {
1892             if (vClass)
1893                 *vClass = [WebHTMLView class];
1894             if (rClass)
1895                 *rClass = [WebHTMLRepresentation class];
1896             return YES;
1897         }
1898     }
1899 #endif
1900     return NO;
1901 }
1902
1903 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1904 {
1905     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
1906 }
1907
1908 + (BOOL)canCloseAllWebViews
1909 {
1910     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1911 }
1912
1913 + (void)closeAllWebViews
1914 {
1915     DOMWindow::dispatchAllPendingUnloadEvents();
1916
1917     // This will close the WebViews in a random order. Change this if close order is important.
1918     // Make a new set to avoid mutating the set we are enumerating.
1919     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1920     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1921     while (WebView *webView = [enumerator nextObject])
1922         [webView close];
1923 }
1924
1925 + (BOOL)canShowFile:(NSString *)path
1926 {
1927     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1928 }
1929
1930 #if !PLATFORM(IOS)
1931 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1932 {
1933     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1934 }
1935 #endif
1936
1937 - (BOOL)_isClosed
1938 {
1939     return !_private || _private->closed;
1940 }
1941
1942 #if PLATFORM(IOS)
1943
1944 - (void)_dispatchUnloadEvent
1945 {
1946     WebThreadRun(^{
1947         WebFrame *mainFrame = [self mainFrame];
1948         Frame *coreMainFrame = core(mainFrame);
1949         if (coreMainFrame) {
1950             Document *document = coreMainFrame->document();
1951             if (document)
1952                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1953         }
1954     });
1955 }
1956
1957 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1958 {
1959     auto* mainFrame = [self _mainCoreFrame];
1960     if (!mainFrame)
1961         return nil;
1962     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
1963     if (!editingStyle)
1964         return nil;
1965     auto* style = editingStyle->style();
1966     if (!style)
1967         return nil;
1968     return kit(style->ensureCSSStyleDeclaration());
1969 }
1970
1971 - (NSUInteger)_renderTreeSize
1972 {
1973     if (!_private->page)
1974         return 0;
1975     return _private->page->renderTreeSize();
1976 }
1977
1978 - (void)_dispatchTileDidDraw:(CALayer*)tile
1979 {
1980     id mailDelegate = [self _webMailDelegate];
1981     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1982         [mailDelegate _webthread_webView:self tileDidDraw:tile];
1983         return;
1984     }
1985
1986 #pragma clang diagnostic push
1987 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1988     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1989         return;
1990 #pragma clang diagnostic pop
1991
1992     WebThreadLock();
1993
1994     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1995 }
1996
1997 - (void)_willStartScrollingOrZooming
1998 {
1999     // Pause timers during top level interaction
2000     if (_private->mainViewIsScrollingOrZooming)
2001         return;
2002     _private->mainViewIsScrollingOrZooming = YES;
2003
2004     [self hideFormValidationMessage];
2005
2006     // This suspends active DOM objects like timers, but not media.
2007     [[self mainFrame] setTimeoutsPaused:YES];
2008
2009     // This defers loading callbacks only.
2010     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2011     [self setDefersCallbacks:YES];
2012 }
2013
2014 - (void)_didFinishScrollingOrZooming
2015 {
2016     if (!_private->mainViewIsScrollingOrZooming)
2017         return;
2018     _private->mainViewIsScrollingOrZooming = NO;
2019     [self setDefersCallbacks:NO];
2020     [[self mainFrame] setTimeoutsPaused:NO];
2021     if (FrameView* view = [self _mainCoreFrame]->view())
2022         view->resumeVisibleImageAnimationsIncludingSubframes();
2023 }
2024
2025 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2026 {
2027     if (suspend)
2028         webResourceLoadScheduler().suspendPendingRequests();
2029     else
2030         webResourceLoadScheduler().resumePendingRequests();
2031 }
2032
2033 + (void)_setAllowCookies:(BOOL)allow
2034 {
2035     ResourceRequestBase::setDefaultAllowCookies(allow);
2036 }
2037
2038 + (BOOL)_allowCookies
2039 {
2040     return ResourceRequestBase::defaultAllowCookies();
2041 }
2042
2043 + (BOOL)_isUnderMemoryPressure
2044 {
2045     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2046 }
2047
2048 + (void)_clearMemoryPressure
2049 {
2050     MemoryPressureHandler::singleton().clearMemoryPressure();
2051 }
2052
2053 + (BOOL)_shouldWaitForMemoryClearMessage
2054 {
2055     return MemoryPressureHandler::singleton().shouldWaitForMemoryClearMessage();
2056 }
2057
2058 #endif // PLATFORM(IOS)
2059
2060 - (void)_closePluginDatabases
2061 {
2062     pluginDatabaseClientCount--;
2063
2064     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2065
2066 #if !PLATFORM(IOS)
2067     // Unload the WebView local plug-in database. 
2068     if (_private->pluginDatabase) {
2069         [_private->pluginDatabase destroyAllPluginInstanceViews];
2070         [_private->pluginDatabase close];
2071         [_private->pluginDatabase release];
2072         _private->pluginDatabase = nil;
2073     }
2074 #endif
2075     
2076     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2077     if (!pluginDatabaseClientCount && applicationIsTerminating)
2078         [WebPluginDatabase closeSharedDatabase];
2079 }
2080
2081 - (void)_closeWithFastTeardown 
2082 {
2083 #ifndef NDEBUG
2084     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2085 #endif
2086
2087 #if !PLATFORM(IOS)
2088     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2089 #endif
2090     [[NSNotificationCenter defaultCenter] removeObserver:self];
2091
2092     [self _closePluginDatabases];
2093 }
2094
2095 static bool fastDocumentTeardownEnabled()
2096 {
2097 #ifdef NDEBUG
2098     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2099 #else
2100     static bool initialized = false;
2101     static bool enabled = false;
2102     if (!initialized) {
2103         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2104         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2105         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2106         if (setting)
2107             enabled = ![setting boolValue];
2108         initialized = true;
2109     }
2110 #endif
2111     return enabled;
2112 }
2113
2114 // _close is here only for backward compatibility; clients and subclasses should use
2115 // public method -close instead.
2116 - (void)_close
2117 {
2118 #if PLATFORM(IOS)
2119     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2120     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2121
2122     [self _clearDelegates];
2123
2124     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2125     WebThreadRun(^{
2126 #endif            
2127
2128     if (!_private || _private->closed)
2129         return;
2130
2131     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2132
2133     _private->closed = YES;
2134     [self _removeFromAllWebViewsSet];
2135
2136 #ifndef NDEBUG
2137     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2138 #endif
2139
2140     // To quit the apps fast we skip document teardown, except plugins
2141     // need to be destroyed and unloaded.
2142     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2143         [self _closeWithFastTeardown];
2144         return;
2145     }
2146
2147 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2148     [self _exitVideoFullscreen];
2149 #endif
2150
2151 #if PLATFORM(IOS)
2152     _private->closing = YES;
2153 #endif
2154
2155     if (Frame* mainFrame = [self _mainCoreFrame])
2156         mainFrame->loader().detachFromParent();
2157
2158     [self setHostWindow:nil];
2159
2160 #if !PLATFORM(IOS)
2161     [self setDownloadDelegate:nil];
2162     [self setEditingDelegate:nil];
2163     [self setFrameLoadDelegate:nil];
2164     [self setPolicyDelegate:nil];
2165     [self setResourceLoadDelegate:nil];
2166     [self setScriptDebugDelegate:nil];
2167     [self setUIDelegate:nil];
2168
2169     [_private->inspector inspectedWebViewClosed];
2170 #endif
2171 #if PLATFORM(MAC)
2172     [_private->immediateActionController webViewClosed];
2173 #endif
2174
2175 #if !PLATFORM(IOS)
2176     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2177     [self removeDragCaret];
2178 #endif
2179
2180     _private->group->removeWebView(self);
2181
2182     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2183     // all the plug-ins in the page cache to break any retain cycles.
2184     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2185     Page* page = _private->page;
2186     _private->page = nullptr;
2187     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2188
2189 #if !PLATFORM(IOS)
2190     if (_private->hasSpellCheckerDocumentTag) {
2191         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2192         _private->hasSpellCheckerDocumentTag = NO;
2193     }
2194 #endif
2195
2196     if (_private->layerFlushController) {
2197         _private->layerFlushController->invalidate();
2198         _private->layerFlushController = nullptr;
2199     }
2200
2201     [[self _notificationProvider] unregisterWebView:self];
2202
2203 #if !PLATFORM(IOS)
2204     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2205 #endif
2206     [[NSNotificationCenter defaultCenter] removeObserver:self];
2207
2208     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2209
2210     WebPreferences *preferences = _private->preferences;
2211     _private->preferences = nil;
2212     [preferences didRemoveFromWebView];
2213     [preferences release];
2214
2215     [self _closePluginDatabases];
2216
2217 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2218     if (_private->m_playbackTargetPicker) {
2219         _private->m_playbackTargetPicker->invalidate();
2220         _private->m_playbackTargetPicker = nullptr;
2221     }
2222 #endif
2223
2224 #ifndef NDEBUG
2225     // Need this to make leak messages accurate.
2226     if (applicationIsTerminating) {
2227         WebCore::GCController::singleton().garbageCollectNow();
2228         [WebCache setDisabled:YES];
2229     }
2230 #endif
2231 #if PLATFORM(IOS)
2232     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2233     });
2234 #endif            
2235 }
2236
2237 // Indicates if the WebView is in the midst of a user gesture.
2238 - (BOOL)_isProcessingUserGesture
2239 {
2240     return ScriptController::processingUserGesture();
2241 }
2242
2243 + (NSString *)_MIMETypeForFile:(NSString *)path
2244 {
2245 #if !PLATFORM(IOS)
2246     NSString *extension = [path pathExtension];
2247 #endif
2248     NSString *MIMEType = nil;
2249
2250 #if !PLATFORM(IOS)
2251     // Get the MIME type from the extension.
2252     if ([extension length] != 0) {
2253         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2254     }
2255 #endif
2256
2257     // If we can't get a known MIME type from the extension, sniff.
2258     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2259         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2260         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2261         [handle closeFile];
2262         if ([data length] != 0) {
2263             MIMEType = [data _webkit_guessedMIMEType];
2264         }
2265         if ([MIMEType length] == 0) {
2266             MIMEType = @"application/octet-stream";
2267         }
2268     }
2269
2270     return MIMEType;
2271 }
2272
2273 - (WebDownload *)_downloadURL:(NSURL *)URL
2274 {
2275     ASSERT(URL);
2276     
2277     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2278     WebDownload *download = [WebDownload _downloadWithRequest:request
2279                                                      delegate:_private->downloadDelegate
2280                                                     directory:nil];
2281     [request release];
2282     
2283     return download;
2284 }
2285
2286 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2287 {
2288     NSDictionary *features = [[NSDictionary alloc] init];
2289     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2290                                             createWebViewWithRequest:nil
2291                                                       windowFeatures:features];
2292     [features release];
2293     if (!newWindowWebView)
2294         return nil;
2295
2296     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2297     return newWindowWebView;
2298 }
2299
2300 - (WebInspector *)inspector
2301 {
2302     if (!_private->inspector)
2303         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2304     return _private->inspector;
2305 }
2306
2307 #if ENABLE(REMOTE_INSPECTOR)
2308 + (void)_enableRemoteInspector
2309 {
2310     RemoteInspector::singleton().start();
2311 }
2312
2313 + (void)_disableRemoteInspector
2314 {
2315     RemoteInspector::singleton().stop();
2316 }
2317
2318 + (void)_disableAutoStartRemoteInspector
2319 {
2320     RemoteInspector::startDisabled();
2321 }
2322
2323 + (BOOL)_isRemoteInspectorEnabled
2324 {
2325     return RemoteInspector::singleton().enabled();
2326 }
2327
2328 + (BOOL)_hasRemoteInspectorSession
2329 {
2330     return RemoteInspector::singleton().hasActiveDebugSession();
2331 }
2332
2333 - (BOOL)allowsRemoteInspection
2334 {
2335     return _private->page->remoteInspectionAllowed();
2336 }
2337
2338 - (void)setAllowsRemoteInspection:(BOOL)allow
2339 {
2340     _private->page->setRemoteInspectionAllowed(allow);
2341 }
2342
2343 - (void)setShowingInspectorIndication:(BOOL)showing
2344 {
2345 #if PLATFORM(IOS)
2346     ASSERT(WebThreadIsLocked());
2347
2348     if (showing) {
2349         if (!_private->indicateLayer) {
2350             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2351             [_private->indicateLayer setNeedsLayout];
2352             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2353         }
2354     } else {
2355         [_private->indicateLayer removeFromSuperlayer];
2356         [_private->indicateLayer release];
2357         _private->indicateLayer = nil;
2358     }
2359 #else
2360     // Implemented in WebCore::InspectorOverlay.
2361 #endif
2362 }
2363
2364 #if PLATFORM(IOS)
2365 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2366 {
2367     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2368     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2369 }
2370 #endif // PLATFORM(IOS)
2371 #endif // ENABLE(REMOTE_INSPECTOR)
2372
2373 - (WebCore::Page*)page
2374 {
2375     return _private->page;
2376 }
2377
2378 #if !PLATFORM(IOS)
2379 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2380 {
2381     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2382     NSArray *menuItems = defaultMenuItems;
2383
2384     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2385     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2386     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2387     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2388         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2389         if (!menuItems)
2390             return nil;
2391     }
2392
2393     unsigned count = [menuItems count];
2394     if (!count)
2395         return nil;
2396
2397     NSMenu *menu = [[NSMenu alloc] init];
2398     for (unsigned i = 0; i < count; i++)
2399         [menu addItem:[menuItems objectAtIndex:i]];
2400
2401     return [menu autorelease];
2402 }
2403 #endif
2404
2405 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2406 {
2407     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2408     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2409     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2410     if (!dictionary)
2411         return;
2412     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2413 }
2414
2415 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2416 {
2417     if (!_private->page)
2418         return;
2419     
2420     if (!otherView->_private->page)
2421         return;
2422     
2423     // It turns out the right combination of behavior is done with the back/forward load
2424     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2425     // in the back forward list, and go to the current one.
2426
2427     BackForwardController& backForward = _private->page->backForward();
2428     ASSERT(!backForward.currentItem()); // destination list should be empty
2429
2430     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2431     if (!otherBackForward.currentItem())
2432         return; // empty back forward list, bail
2433     
2434     HistoryItem* newItemToGoTo = nullptr;
2435
2436     int lastItemIndex = otherBackForward.forwardCount();
2437     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2438         if (i == 0) {
2439             // If this item is showing , save away its current scroll and form state,
2440             // since that might have changed since loading and it is normally not saved
2441             // until we leave that page.
2442             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2443         }
2444         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2445         if (i == 0) 
2446             newItemToGoTo = newItem.ptr();
2447         backForward.client()->addItem(WTFMove(newItem));
2448     }
2449
2450     ASSERT(newItemToGoTo);
2451     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward);
2452 }
2453
2454 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2455 {
2456     _private->formDelegate = delegate;
2457 #if PLATFORM(IOS)
2458     [_private->formDelegateForwarder clearTarget];
2459     [_private->formDelegateForwarder release];
2460     _private->formDelegateForwarder = nil;
2461 #endif
2462 }
2463
2464 - (id<WebFormDelegate>)_formDelegate
2465 {
2466     return _private->formDelegate;
2467 }
2468
2469 #if PLATFORM(IOS)
2470 - (id)_formDelegateForwarder
2471 {
2472     if (_private->closing)
2473         return nil;
2474
2475     if (!_private->formDelegateForwarder)
2476         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2477     return _private->formDelegateForwarder;
2478 }
2479
2480 - (id)_formDelegateForSelector:(SEL)selector
2481 {
2482     id delegate = self->_private->formDelegate;
2483     if ([delegate respondsToSelector:selector])
2484         return delegate;
2485
2486     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2487     if ([delegate respondsToSelector:selector])
2488         return delegate;
2489
2490     return nil;
2491 }
2492 #endif
2493
2494 #if !PLATFORM(IOS)
2495 - (BOOL)_needsAdobeFrameReloadingQuirk
2496 {
2497     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2498         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2499         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2500         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2501         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2502         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2503         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2504         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2505         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2506         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2507
2508     return needsQuirk;
2509 }
2510
2511 - (BOOL)_needsLinkElementTextCSSQuirk
2512 {
2513     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2514         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2515     return needsQuirk;
2516 }
2517
2518 - (BOOL)_needsIsLoadingInAPISenseQuirk
2519 {
2520     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2521     
2522     return needsQuirk;
2523 }
2524
2525 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2526 {
2527     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2528     return needsQuirks;
2529 }
2530
2531 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2532 {
2533     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2534     return needsQuirk;
2535 }
2536
2537 static bool needsSelfRetainWhileLoadingQuirk()
2538 {
2539     static bool needsQuirk = MacApplication::isAperture();
2540     return needsQuirk;
2541 }
2542 #endif // !PLATFORM(IOS)
2543
2544 - (BOOL)_needsPreHTML5ParserQuirks
2545 {    
2546 #if !PLATFORM(IOS)
2547     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2548     // with the new HTML5 parser. If these applications were linked against a
2549     // version of WebKit prior to the introduction of the HTML5 parser, enable
2550     // parser quirks to maintain compatibility. For details, see 
2551     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2552     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2553     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2554         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2555     
2556     // Mail.app must continue to display HTML email that contains quirky markup.
2557     static bool isAppleMail = MacApplication::isAppleMail();
2558
2559     return isApplicationNeedingParserQuirks
2560         || isAppleMail
2561 #if ENABLE(DASHBOARD_SUPPORT)
2562         // Pre-HTML5 parser quirks are required to remain compatible with many
2563         // Dashboard widgets. See <rdar://problem/8175982>.
2564         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2565 #endif
2566         || [[self preferences] usePreHTML5ParserQuirks];
2567 #else
2568     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && IOSApplication::isDaijisenDictionary();
2569     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2570 #endif
2571 }
2572
2573 - (void)_preferencesChangedNotification:(NSNotification *)notification
2574 {
2575 #if PLATFORM(IOS)
2576     // For WebViews that load synchronously, preference changes need to be propagated
2577     // down to WebCore synchronously so that loads in that WebView have the correct
2578     // up-to-date settings.
2579     if (!WebThreadIsLocked())
2580         WebThreadLock();
2581     if ([[self mainFrame] _loadsSynchronously]) {
2582 #endif
2583
2584     WebPreferences *preferences = (WebPreferences *)[notification object];
2585     [self _preferencesChanged:preferences];
2586
2587 #if PLATFORM(IOS)
2588     } else {
2589         WebThreadRun(^{
2590             // It is possible that the prefs object has already changed before the invocation could be called
2591             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2592             WebPreferences *preferences = (WebPreferences *)[notification object];
2593             if (preferences != [self preferences])
2594                 return;
2595             [self _preferencesChanged:preferences];
2596         });
2597     }
2598 #endif
2599 }
2600
2601 - (void)_preferencesChanged:(WebPreferences *)preferences
2602 {    
2603     ASSERT(preferences == [self preferences]);
2604     if (!_private->userAgentOverridden)
2605         _private->userAgent = String();
2606
2607     // Cache this value so we don't have to read NSUserDefaults on each page load
2608     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2609
2610     // Update corresponding WebCore Settings object.
2611     if (!_private->page)
2612         return;
2613
2614 #if PLATFORM(IOS)
2615     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2616     // didOneTimeInitialization is true so that we don't initialize databases
2617     // until the first WebView has been created. This is because database
2618     // initialization current requires disk access to populate the origins
2619     // quota map and we want to do this lazily by waiting until WebKit is
2620     // used to display web content in a WebView. The possible cases are:
2621     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2622     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2623     if (didOneTimeInitialization) {
2624         if ([preferences databasesEnabled])
2625             [WebDatabaseManager sharedWebDatabaseManager];
2626         if ([preferences storageTrackerEnabled])
2627             WebKitInitializeStorageIfNecessary();
2628     }
2629 #endif
2630
2631     Settings& settings = _private->page->settings();
2632
2633     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2634     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2635     settings.setDefaultFontSize([preferences defaultFontSize]);
2636     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2637     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2638     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2639     settings.setFixedFontFamily([preferences fixedFontFamily]);
2640     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2641     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2642     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2643     settings.setJavaEnabled([preferences isJavaEnabled]);
2644     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2645     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2646     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2647     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2648     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2649     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2650     settings.setMinimumFontSize([preferences minimumFontSize]);
2651     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2652     settings.setPictographFontFamily([preferences pictographFontFamily]);
2653     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2654     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2655
2656     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2657     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2658     settings.setSerifFontFamily([preferences serifFontFamily]);
2659     settings.setStandardFontFamily([preferences standardFontFamily]);
2660     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2661     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2662 #if PLATFORM(IOS)
2663     settings.setShouldPrintBackgrounds(true);
2664 #else
2665     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2666 #endif
2667     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2668     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2669     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2670     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2671     settings.setUsesPageCache([self usesPageCache]);
2672     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2673     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2674
2675     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2676     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2677     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2678
2679     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2680     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2681     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2682     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2683     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2684     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2685     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2686     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2687
2688     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2689     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2690     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2691     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2692     settings.setShowDebugBorders([preferences showDebugBorders]);
2693     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2694     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2695     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2696     settings.setWebGLEnabled([preferences webGLEnabled]);
2697     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2698
2699     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2700     settings.setPreferLowPowerWebGLRendering([preferences preferLowPowerWebGLRendering]);
2701     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2702     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2703     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2704     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2705     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2706     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2707
2708     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2709     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2710     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2711     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2712     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2713
2714     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2715     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2716     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2717     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2718     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2719     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2720     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2721     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2722     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2723     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2724     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2725     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2726     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2727     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2728     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2729
2730     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2731
2732     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2733     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2734     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2735
2736     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2737
2738     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2739     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2740
2741     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2742     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2743
2744     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2745
2746     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2747
2748     switch ([preferences storageBlockingPolicy]) {
2749     case WebAllowAllStorage:
2750         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2751         break;
2752     case WebBlockThirdPartyStorage:
2753         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2754         break;
2755     case WebBlockAllStorage:
2756         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2757         break;
2758     }
2759
2760     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2761     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2762
2763     settings.setFixedPositionCreatesStackingContext(true);
2764 #if PLATFORM(MAC)
2765     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2766 #endif
2767
2768 #if ENABLE(RUBBER_BANDING)
2769     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2770     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2771 #endif
2772
2773 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2774     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2775 #endif
2776 #if PLATFORM(IOS)
2777     settings.setStandalone([preferences _standalone]);
2778     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2779     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2780     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2781     settings.setMaxParseDuration([preferences _maxParseDuration]);
2782     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2783     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2784     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2785     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2786 #if HAVE(AVKIT)
2787     settings.setAVKitEnabled([preferences avKitEnabled]);
2788 #endif
2789     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2790     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2791
2792     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2793     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2794
2795     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2796     settings.setDelegatesPageScaling(true);
2797
2798 #if ENABLE(TEXT_AUTOSIZING)
2799     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2800     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2801 #endif
2802 #endif // PLATFORM(IOS)
2803
2804 #if PLATFORM(MAC)
2805     if ([preferences userStyleSheetEnabled]) {
2806         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2807         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2808             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2809         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2810     } else
2811         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2812
2813     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2814     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2815     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2816     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2817     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2818     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2819     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2820     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2821     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2822     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2823 #endif // PLATFORM(MAC)
2824
2825     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2826
2827 #if ENABLE(MEDIA_SOURCE)
2828     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2829 #endif
2830
2831 #if ENABLE(SERVICE_CONTROLS)
2832     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2833     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2834 #endif
2835
2836 #if ENABLE(VIDEO_TRACK)
2837     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2838     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2839     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2840 #endif
2841
2842 #if USE(AVFOUNDATION)
2843     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2844     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2845 #endif
2846
2847 #if ENABLE(MEDIA_STREAM)
2848     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2849     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2850     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
2851 #endif
2852
2853 #if ENABLE(WEB_RTC)
2854     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
2855 #endif
2856
2857 #if ENABLE(WEB_AUDIO)
2858     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2859 #endif
2860
2861 #if ENABLE(FULLSCREEN_API)
2862     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2863 #endif
2864
2865     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2866
2867     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2868
2869     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2870
2871 #if ENABLE(GAMEPAD)
2872     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2873 #endif
2874
2875     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2876
2877     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2878
2879     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2880
2881     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2882
2883 #if ENABLE(FETCH_API)
2884     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2885 #endif
2886
2887 #if ENABLE(WEBGL2)
2888     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2889 #endif
2890
2891 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2892     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2893 #endif
2894
2895 #if ENABLE(CSS_GRID_LAYOUT)
2896     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2897 #endif
2898
2899 #if ENABLE(WEB_ANIMATIONS)
2900     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2901 #endif
2902
2903 #if ENABLE(INTERSECTION_OBSERVER)
2904     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
2905 #endif
2906
2907 #if ENABLE(SUBTLE_CRYPTO)
2908     RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled([preferences subtleCryptoEnabled]);
2909 #endif
2910
2911     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2912     if (timeout > 0)
2913         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2914
2915     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2916     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2917
2918     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2919     if (_private->zoomsTextOnly != zoomsTextOnly)
2920         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2921
2922 #if PLATFORM(IOS)
2923     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2924     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2925     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2926     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2927 #endif
2928
2929 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2930     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2931 #endif
2932
2933     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2934
2935 #if ENABLE(ATTACHMENT_ELEMENT)
2936     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2937 #endif
2938
2939     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2940
2941     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2942
2943     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
2944     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
2945 }
2946
2947 static inline IMP getMethod(id o, SEL s)
2948 {
2949     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2950 }
2951
2952 #if PLATFORM(IOS)
2953 - (id)_UIKitDelegateForwarder
2954 {
2955     if (_private->closing)
2956         return nil;
2957         
2958     if (!_private->UIKitDelegateForwarder)
2959         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2960     return _private->UIKitDelegateForwarder;
2961 }
2962 #endif
2963
2964 - (void)_cacheResourceLoadDelegateImplementations
2965 {
2966     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2967     id delegate = _private->resourceProgressDelegate;
2968
2969     if (!delegate) {
2970         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2971         return;
2972     }
2973
2974     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2975     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2976     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2977     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2978 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2979     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2980 #endif
2981
2982 #if PLATFORM(IOS)
2983     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2984     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2985     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2986     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2987     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2988     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2989     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2990     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2991     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2992 #endif
2993
2994     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2995     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2996     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2997     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2998     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2999     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3000     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3001     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3002 }
3003
3004 - (void)_cacheFrameLoadDelegateImplementations
3005 {
3006     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3007     id delegate = _private->frameLoadDelegate;
3008
3009     if (!delegate) {
3010         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3011         return;
3012     }
3013
3014     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3015     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3016     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3017     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3018     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3019 #if JSC_OBJC_API_ENABLED
3020     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3021 #endif
3022     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3023     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3024     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3025     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3026     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3027     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3028     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3029     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3030     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3031     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3032     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3033     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3034 #if ENABLE(ICONDATABASE)
3035     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3036 #endif
3037     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3038     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3039     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3040     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3041     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3042     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3043     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3044     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3045     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3046     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3047 #if PLATFORM(IOS)
3048     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3049 #endif
3050
3051     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3052     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3053     // for backwards compatibility.
3054     Page* page = core(self);
3055     if (page) {
3056         unsigned milestones = DidFirstLayout;
3057 #if PLATFORM(IOS)
3058         milestones |= DidFirstVisuallyNonEmptyLayout;
3059 #else
3060         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3061             milestones |= DidFirstVisuallyNonEmptyLayout;
3062 #endif
3063         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3064     }
3065 }
3066
3067 - (void)_cacheScriptDebugDelegateImplementations
3068 {
3069     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3070     id delegate = _private->scriptDebugDelegate;
3071
3072     if (!delegate) {
3073         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3074         return;
3075     }
3076
3077     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3078     if (cache->didParseSourceFunc)
3079         cache->didParseSourceExpectsBaseLineNumber = YES;
3080     else {
3081         cache->didParseSourceExpectsBaseLineNumber = NO;
3082         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3083     }
3084
3085     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3086
3087     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3088     if (cache->exceptionWasRaisedFunc)
3089         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3090     else {
3091         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3092         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3093     }
3094 }
3095
3096 - (void)_cacheHistoryDelegateImplementations
3097 {
3098     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3099     id delegate = _private->historyDelegate;
3100
3101     if (!delegate) {
3102         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3103         return;
3104     }
3105
3106     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3107     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3108     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3109     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3110     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3111     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3112 }
3113
3114 - (id)_policyDelegateForwarder
3115 {
3116 #if PLATFORM(IOS)
3117     if (_private->closing)
3118         return nil;
3119 #endif
3120     if (!_private->policyDelegateForwarder)
3121         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3122     return _private->policyDelegateForwarder;
3123 }
3124
3125 - (id)_UIDelegateForwarder
3126 {
3127 #if PLATFORM(IOS)
3128     if (_private->closing)
3129         return nil;
3130 #endif
3131     if (!_private->UIDelegateForwarder)
3132         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3133     return _private->UIDelegateForwarder;
3134 }
3135
3136 #if PLATFORM(IOS)
3137 - (id)_UIDelegateForSelector:(SEL)selector
3138 {
3139     id delegate = self->_private->UIDelegate;
3140     if ([delegate respondsToSelector:selector])
3141         return delegate;
3142
3143     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3144     if ([delegate respondsToSelector:selector])
3145         return delegate;
3146
3147     return nil;
3148 }
3149 #endif
3150
3151 - (id)_editingDelegateForwarder
3152 {
3153 #if PLATFORM(IOS)
3154     if (_private->closing)
3155         return nil;
3156 #endif    
3157     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3158     // Not sure if that is a bug or not.
3159     if (!_private)
3160         return nil;
3161
3162     if (!_private->editingDelegateForwarder)
3163         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3164     return _private->editingDelegateForwarder;
3165 }
3166
3167 - (void)_closeWindow
3168 {
3169     [[self _UIDelegateForwarder] webViewClose:self];
3170 }
3171
3172 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3173 {
3174     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3175     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3176     
3177     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3178     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3179     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3180     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3181 }
3182
3183 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3184 {
3185     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3186     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3187
3188     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3189     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3190     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3191     if ([viewClass class] == [WebHTMLView class])
3192         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3193     
3194     // This is used to make _representationExistsForURLScheme faster.
3195     // Without this set, we'd have to create the MIME type each time.
3196     if (schemesWithRepresentationsSet == nil) {
3197         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3198     }
3199     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3200 }
3201
3202 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3203 {
3204     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3205 }
3206
3207 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3208 {
3209     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3210 }
3211
3212 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3213 {
3214     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3215     if (!request)
3216         return NO;
3217
3218     if ([NSURLConnection canHandleRequest:request])
3219         return YES;
3220
3221     NSString *scheme = [[request URL] scheme];
3222
3223     // Representations for URL schemes work at the top level.
3224     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3225         return YES;
3226
3227     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3228         return YES;
3229
3230     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3231         return YES;
3232
3233     return NO;
3234 }
3235
3236 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3237 {
3238     return [self _canHandleRequest:request forMainFrame:YES];
3239 }
3240
3241 + (NSString *)_decodeData:(NSData *)data
3242 {
3243     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3244     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3245 }
3246
3247 - (void)_pushPerformingProgrammaticFocus
3248 {
3249     _private->programmaticFocusCount++;
3250 }
3251
3252 - (void)_popPerformingProgrammaticFocus
3253 {
3254     _private->programmaticFocusCount--;
3255 }
3256
3257 - (BOOL)_isPerformingProgrammaticFocus
3258 {
3259     return _private->programmaticFocusCount != 0;
3260 }
3261
3262 #if !PLATFORM(IOS)
3263 - (void)_didChangeValueForKey: (NSString *)key
3264 {
3265     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3266     [self didChangeValueForKey: key];
3267 }
3268
3269 - (void)_willChangeValueForKey: (NSString *)key
3270 {
3271     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3272     [self willChangeValueForKey: key];
3273 }
3274
3275 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3276     static NSSet *manualNotifyKeys = nil;
3277     if (!manualNotifyKeys)
3278         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3279             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3280             nil];
3281     if ([manualNotifyKeys containsObject:key])
3282         return NO;
3283     return YES;
3284 }
3285
3286 - (NSArray *)_declaredKeys {
3287     static NSArray *declaredKeys = nil;
3288     if (!declaredKeys)
3289         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3290             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3291     return declaredKeys;
3292 }
3293
3294 - (void)_willChangeBackForwardKeys
3295 {
3296     [self _willChangeValueForKey: _WebCanGoBackKey];
3297     [self _willChangeValueForKey: _WebCanGoForwardKey];
3298 }
3299
3300 - (void)_didChangeBackForwardKeys
3301 {
3302     [self _didChangeValueForKey: _WebCanGoBackKey];
3303     [self _didChangeValueForKey: _WebCanGoForwardKey];
3304 }
3305
3306 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3307 {
3308     if (needsSelfRetainWhileLoadingQuirk())
3309         [self retain];
3310
3311     [self _willChangeBackForwardKeys];
3312     if (frame == [self mainFrame]){
3313         // Force an observer update by sending a will/did.
3314         [self _willChangeValueForKey: _WebIsLoadingKey];
3315         [self _didChangeValueForKey: _WebIsLoadingKey];
3316
3317         [self _willChangeValueForKey: _WebMainFrameURLKey];
3318
3319         [self hideFormValidationMessage];
3320     }
3321
3322     [NSApp setWindowsNeedUpdate:YES];
3323
3324 #if ENABLE(FULLSCREEN_API)
3325     Document* document = core([frame DOMDocument]);
3326     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3327         SEL selector = @selector(webView:closeFullScreenWithListener:);
3328         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
3329             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3330             CallUIDelegate(self, selector, listener);
3331             [listener release];
3332         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3333             [_private->newFullscreenController close];
3334         }
3335     }
3336 #endif
3337 }
3338
3339 - (void)_checkDidPerformFirstNavigation
3340 {
3341     if (_private->_didPerformFirstNavigation)
3342         return;
3343
3344     Page* page = _private->page;
3345     if (!page)
3346         return;
3347
3348     auto& backForwardController = page->backForward();
3349
3350     if (!backForwardController.backItem())
3351         return;
3352
3353     _private->_didPerformFirstNavigation = YES;
3354
3355     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3356         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3357 }
3358
3359 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3360 {
3361     if (frame == [self mainFrame])
3362         [self _didChangeValueForKey: _WebMainFrameURLKey];
3363
3364     [self _checkDidPerformFirstNavigation];
3365
3366     [NSApp setWindowsNeedUpdate:YES];
3367 }
3368
3369 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3370 {
3371     if (needsSelfRetainWhileLoadingQuirk())
3372         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3373         
3374     [self _didChangeBackForwardKeys];
3375     if (frame == [self mainFrame]){
3376         // Force an observer update by sending a will/did.
3377         [self _willChangeValueForKey: _WebIsLoadingKey];
3378         [self _didChangeValueForKey: _WebIsLoadingKey];
3379     }
3380     [NSApp setWindowsNeedUpdate:YES];
3381 }
3382
3383 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3384 {
3385     if (needsSelfRetainWhileLoadingQuirk())
3386         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3387
3388     [self _didChangeBackForwardKeys];
3389     if (frame == [self mainFrame]){
3390         // Force an observer update by sending a will/did.
3391         [self _willChangeValueForKey: _WebIsLoadingKey];
3392         [self _didChangeValueForKey: _WebIsLoadingKey];
3393     }
3394     [NSApp setWindowsNeedUpdate:YES];
3395 }
3396
3397 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3398 {
3399     if (needsSelfRetainWhileLoadingQuirk())
3400         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3401
3402     [self _didChangeBackForwardKeys];
3403     if (frame == [self mainFrame]){
3404         // Force an observer update by sending a will/did.
3405         [self _willChangeValueForKey: _WebIsLoadingKey];
3406         [self _didChangeValueForKey: _WebIsLoadingKey];
3407         
3408         [self _didChangeValueForKey: _WebMainFrameURLKey];
3409     }
3410     [NSApp setWindowsNeedUpdate:YES];
3411 }
3412
3413 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3414 {
3415     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3416     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3417     NSCachedURLResponse *cachedResponse;
3418
3419     if (!_private->page)
3420         return nil;
3421
3422     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3423         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3424     else
3425         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3426
3427     return cachedResponse;
3428 }
3429
3430 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3431 {
3432     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3433     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3434     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3435                         element:domElement
3436                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3437                           title:[element objectForKey:WebElementImageAltStringKey] 
3438                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3439                           types:types
3440                          source:nil];
3441 }
3442
3443 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3444 {
3445     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3446                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3447                         types:types];
3448 }
3449
3450 #if ENABLE(DRAG_SUPPORT)
3451 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3452 {
3453     if (!_private->page)
3454         return;
3455     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3456 }
3457 #endif
3458
3459 #else
3460
3461 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3462 {
3463     if (frame == [self mainFrame])
3464         _private->didDrawTiles = 0;
3465 }
3466
3467 #endif // PLATFORM(IOS)
3468
3469 #if ENABLE(DASHBOARD_SUPPORT)
3470
3471 #define DASHBOARD_CONTROL_LABEL @"control"
3472
3473 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3474 {
3475     NSRect adjustedBounds = bounds;
3476     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3477     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3478     adjustedBounds.size = bounds.size;
3479
3480     NSRect adjustedClip;
3481     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3482     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3483     adjustedClip.size = clip.size;
3484
3485     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3486         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3487     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3488     if (!scrollerRegions) {
3489         scrollerRegions = [[NSMutableArray alloc] init];
3490         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3491         [scrollerRegions release];
3492     }
3493     [scrollerRegions addObject:region];
3494     [region release];
3495 }
3496
3497 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3498 {    
3499     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3500
3501     for (const auto& widget: frameView->children()) {
3502         if (is<FrameView>(widget)) {
3503             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3504             continue;
3505         }
3506
3507         if (!widget->isScrollbar())
3508             continue;
3509
3510         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3511         // it's not common to need this to be correct in Dashboard widgets.
3512         NSRect bounds = widget->frameRect();
3513         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3514     }
3515 }
3516
3517 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3518 {
3519     // Add scroller regions for NSScroller and WebCore scrollbars
3520     NSUInteger count = [views count];
3521     for (NSUInteger i = 0; i < count; i++) {
3522         NSView *view = [views objectAtIndex:i];
3523         
3524         if ([view isKindOfClass:[WebHTMLView class]]) {
3525             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3526                 if (FrameView* coreView = coreFrame->view())
3527                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3528             }
3529         } else if ([view isKindOfClass:[NSScroller class]]) {
3530             // AppKit places absent scrollers at -100,-100
3531             if ([view frame].origin.y < 0)
3532                 continue;
3533             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3534         }
3535         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3536     }
3537 }
3538
3539 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3540 {
3541     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3542 }
3543
3544 - (NSDictionary *)_dashboardRegions
3545 {
3546     // Only return regions from main frame.
3547     Frame* mainFrame = [self _mainCoreFrame];
3548     if (!mainFrame)
3549         return nil;
3550
3551     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3552     size_t size = regions.size();
3553
3554     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3555     for (size_t i = 0; i < size; i++) {
3556         const AnnotatedRegionValue& region = regions[i];
3557
3558         if (region.type == StyleDashboardRegion::None)
3559             continue;
3560
3561         NSString *label = region.label;
3562         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3563         if (region.type == StyleDashboardRegion::Circle)
3564             type = WebDashboardRegionTypeCircle;
3565         else if (region.type == StyleDashboardRegion::Rectangle)
3566             type = WebDashboardRegionTypeRectangle;
3567         NSMutableArray *regionValues = [webRegions objectForKey:label];
3568         if (!regionValues) {
3569             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3570             [webRegions setObject:regionValues forKey:label];
3571             [regionValues release];
3572         }
3573
3574         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3575         [regionValues addObject:webRegion];
3576         [webRegion release];
3577     }
3578
3579     [self _addScrollerDashboardRegions:webRegions];
3580
3581     return webRegions;
3582 }
3583
3584 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3585 {
3586     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3587     // specific support for the backward compatibility mode flag.
3588     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3589         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3590     
3591     switch (behavior) {
3592         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3593             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3594             break;
3595         }
3596         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3597             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3598             break;
3599         }
3600         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3601             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3602             break;
3603         }
3604         case WebDashboardBehaviorAllowWheelScrolling: {
3605             _private->dashboardBehaviorAllowWheelScrolling = flag;
3606             break;
3607         }
3608         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3609             if (_private->page)
3610                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3611 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3612             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3613 #endif
3614             break;
3615         }
3616     }
3617
3618     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3619     // compatibility mode. See <rdar://problem/8175982>.
3620     if (_private->page)
3621         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3622 }
3623
3624 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3625 {
3626     switch (behavior) {
3627         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3628             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3629         }
3630         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3631             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3632         }
3633         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3634             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3635         }
3636         case WebDashboardBehaviorAllowWheelScrolling: {
3637             return _private->dashboardBehaviorAllowWheelScrolling;
3638         }
3639         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3640             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3641         }
3642     }
3643     return NO;
3644 }
3645
3646 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3647
3648 + (void)_setShouldUseFontSmoothing:(BOOL)f
3649 {
3650     FontCascade::setShouldUseSmoothing(f);
3651 }
3652
3653 + (BOOL)_shouldUseFontSmoothing
3654 {
3655     return FontCascade::shouldUseSmoothing();
3656 }
3657
3658 #if !PLATFORM(IOS)
3659 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3660 {
3661     setUsesTestModeFocusRingColor(f);
3662 }
3663
3664 + (BOOL)_usesTestModeFocusRingColor
3665 {
3666     return usesTestModeFocusRingColor();
3667 }
3668 #endif
3669
3670 #if PLATFORM(IOS)
3671 - (void)_setUIKitDelegate:(id)delegate
3672 {
3673     _private->UIKitDelegate = delegate;
3674     [_private->UIKitDelegateForwarder clearTarget];
3675     [_private->UIKitDelegateForwarder release];
3676     _private->UIKitDelegateForwarder = nil;
3677 }
3678
3679 - (id)_UIKitDelegate
3680 {
3681     return _private->UIKitDelegate;
3682 }
3683
3684 - (void)setWebMailDelegate:(id)delegate
3685 {
3686     _private->WebMailDelegate = delegate;
3687 }
3688
3689 - (id)_webMailDelegate
3690 {
3691     return _private->WebMailDelegate;
3692 }
3693
3694 - (id <WebCaretChangeListener>)caretChangeListener
3695 {
3696     return _private->_caretChangeListener;
3697 }
3698
3699 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3700 {
3701     _private->_caretChangeListener = listener;
3702 }
3703
3704 - (NSSet *)caretChangeListeners
3705 {
3706     return _private->_caretChangeListeners;
3707 }
3708
3709 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3710 {
3711     if (_private->_caretChangeListeners == nil) {
3712         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3713     }
3714     
3715     [_private->_caretChangeListeners addObject:listener];
3716 }
3717
3718 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3719 {
3720     [_private->_caretChangeListeners removeObject:listener];
3721 }
3722
3723 - (void)removeAllCaretChangeListeners
3724 {
3725     [_private->_caretChangeListeners removeAllObjects];
3726 }
3727
3728 - (void)caretChanged
3729 {
3730     [_private->_caretChangeListener caretChanged];
3731     NSSet *copy = [_private->_caretChangeListeners copy];
3732     for (id <WebCaretChangeListener> listener in copy) {
3733         [listener caretChanged];
3734     }
3735     [copy release];
3736 }
3737
3738 - (void)_clearDelegates
3739 {
3740     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3741     
3742     [self _setFormDelegate:nil];
3743     [self _setUIKitDelegate:nil];
3744     [self setCaretChangeListener:nil];
3745     [self removeAllCaretChangeListeners];
3746     [self setWebMailDelegate:nil];
3747     
3748     [self setDownloadDelegate:nil];
3749     [self setEditingDelegate:nil]; 
3750     [self setFrameLoadDelegate:nil];
3751     [self setPolicyDelegate:nil];
3752     [self setResourceLoadDelegate:nil];
3753     [self setScriptDebugDelegate:nil];
3754     [self setUIDelegate:nil];     
3755 }
3756
3757 - (NSURL *)_displayURL
3758 {
3759     WebThreadLock();
3760     WebFrame *frame = [self mainFrame];
3761     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3762     WebDataSource *dataSource = [frame provisionalDataSource];
3763     if (!dataSource)
3764         dataSource = [frame dataSource];
3765     NSURL *unreachableURL = [dataSource unreachableURL];
3766     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3767     [[URL retain] autorelease];
3768     return URL;
3769 }
3770 #endif // PLATFORM(IOS)
3771
3772 #if !PLATFORM(IOS)
3773 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3774 {
3775     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3776     if (flag) {
3777         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3778     } else {
3779         [scrollview setVerticalScrollingModeLocked:NO];
3780         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3781     }
3782 }
3783
3784 - (BOOL)alwaysShowVerticalScroller
3785 {
3786     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3787     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3788 }
3789
3790 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3791 {
3792     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3793     if (flag) {
3794         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3795     } else {
3796         [scrollview setHorizontalScrollingModeLocked:NO];
3797         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3798     }
3799 }
3800
3801 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3802 {
3803     if (Frame* mainFrame = [self _mainCoreFrame])
3804         mainFrame->view()->setProhibitsScrolling(prohibits);
3805 }
3806
3807 - (BOOL)alwaysShowHorizontalScroller
3808 {
3809     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3810     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3811 }
3812 #endif // !PLATFORM(IOS)
3813
3814 - (void)_setUseFastImageScalingMode:(BOOL)flag
3815 {
3816     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3817         _private->page->setInLowQualityImageInterpolationMode(flag);
3818         [self setNeedsDisplay:YES];
3819     }
3820 }
3821
3822 - (BOOL)_inFastImageScalingMode
3823 {
3824     if (_private->page)
3825         return _private->page->inLowQualityImageInterpolationMode();
3826     return NO;
3827 }
3828
3829 - (BOOL)_cookieEnabled
3830 {
3831     if (_private->page)
3832         return _private->page->settings().cookieEnabled();
3833     return YES;
3834 }
3835
3836 - (void)_setCookieEnabled:(BOOL)enable
3837 {
3838     if (_private->page)
3839         _private->page->settings().setCookieEnabled(enable);
3840 }
3841
3842 #if !PLATFORM(IOS)
3843 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3844 {
3845     if (!_private->pluginDatabase)
3846         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3847         
3848     [_private->pluginDatabase setPlugInPaths:newPaths];
3849     [_private->pluginDatabase refresh];
3850 }
3851 #endif
3852
3853 #if PLATFORM(IOS)
3854 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3855 {
3856     // Ask plug-ins in this frame
3857     id <WebDocumentView> documentView = [[frame frameView] documentView];
3858     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3859         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3860             return YES;
3861     }
3862
3863     // Ask plug-ins in child frames
3864     NSArray *childFrames = [frame childFrames];
3865     unsigned childCount = [childFrames count];
3866     unsigned childIndex;
3867     for (childIndex = 0; childIndex < childCount; childIndex++) {
3868         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3869             return YES;
3870     }
3871     
3872     return NO;
3873 }
3874
3875 - (BOOL)_pluginsAreRunning
3876 {
3877     WebThreadLock();
3878     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3879 }
3880
3881 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3882 {
3883     // Send the message to plug-ins in this frame
3884     id <WebDocumentView> documentView = [[frame frameView] documentView];
3885     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3886         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3887
3888     // Send the message to plug-ins in child frames
3889     NSArray *childFrames = [frame childFrames];
3890     unsigned childCount = [childFrames count];
3891     unsigned childIndex;
3892     for (childIndex = 0; childIndex < childCount; childIndex++) {
3893         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3894     }
3895 }
3896
3897 - (void)_destroyAllPlugIns
3898 {
3899     WebThreadLock();
3900     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3901 }
3902
3903 - (void)_startAllPlugIns
3904 {
3905     WebThreadLock();
3906     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3907 }
3908
3909 - (void)_stopAllPlugIns
3910 {
3911     WebThreadLock();
3912     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3913 }
3914
3915 - (void)_stopAllPlugInsForPageCache
3916 {
3917     WebThreadLock();
3918     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3919 }
3920
3921 - (void)_restorePlugInsFromCache
3922 {
3923     WebThreadLock();
3924     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3925 }
3926
3927 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3928 {
3929     WebThreadLock();
3930
3931     Frame* mainCoreFrame = [self _mainCoreFrame];
3932     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3933         FrameView* coreView = frame ? frame->view() : 0;
3934         if (!coreView)
3935             continue;
3936
3937         // Get the GraphicsLayer for this widget.
3938         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3939         if (!layerForWidget)
3940             continue;
3941         
3942         if (layerForWidget->contentsLayerForMedia() != layer) {
3943             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3944             // We need to make sure the layer hierachy change is applied immediately.
3945             if (mainCoreFrame->view())
3946                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3947             return YES;
3948         }
3949     }
3950
3951     return NO;
3952 }
3953
3954 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3955 {
3956     if (_private->page)
3957         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3958 }
3959 #endif // PLATFORM(IOS)
3960
3961 - (void)_attachScriptDebuggerToAllFrames
3962 {
3963     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3964         [kit(frame) _attachScriptDebugger];
3965 }
3966
3967 - (void)_detachScriptDebuggerFromAllFrames
3968 {
3969     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3970         [kit(frame) _detachScriptDebugger];
3971 }
3972
3973 #if !PLATFORM(IOS)
3974 - (void)setBackgroundColor:(NSColor *)backgroundColor
3975 {
3976     if ([_private->backgroundColor isEqual:backgroundColor])
3977         return;
3978
3979     id old = _private->backgroundColor;
3980     _private->backgroundColor = [backgroundColor retain];
3981     [old release];
3982
3983     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3984 }
3985
3986 - (NSColor *)backgroundColor
3987 {
3988     return _private->backgroundColor;
3989 }
3990 #else
3991 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3992 {
3993    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3994         return;
3995
3996     CFTypeRef old = _private->backgroundColor;
3997     CFRetain(backgroundColor);
3998     _private->backgroundColor = backgroundColor;
3999     CFRelease(old);
4000
4001     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
4002 }
4003
4004 - (CGColorRef)backgroundColor
4005 {
4006     return _private->backgroundColor;
4007 }
4008 #endif
4009
4010 - (BOOL)defersCallbacks
4011 {
4012     if (!_private->page)
4013         return NO;
4014     return _private->page->defersLoading();
4015 }
4016
4017 - (void)setDefersCallbacks:(BOOL)defer
4018 {
4019     if (!_private->page)
4020         return;
4021     return _private->page->setDefersLoading(defer);
4022 }
4023
4024 #if PLATFORM(IOS)
4025 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
4026 {
4027 #if USE(QUICK_LOOK)
4028     NSString *uti = qlPreviewConverterUTIForURL(url);
4029     if (!uti)
4030         return nil;
4031
4032     NSString *fileName = qlPreviewConverterFileNameForURL(url);
4033     if (!fileName)
4034         return nil;
4035
4036     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
4037 #else
4038     return nil;
4039 #endif
4040 }
4041
4042 - (BOOL)_isStopping
4043 {
4044     return _private->isStopping;
4045 }
4046
4047 - (BOOL)_isClosing
4048 {
4049     return _private->closing;
4050 }
4051
4052 + (NSArray *)_productivityDocumentMIMETypes
4053 {
4054 #if USE(QUICK_LOOK)
4055     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
4056 #else
4057     return nil;
4058 #endif
4059 }
4060
4061 - (void)_setAllowsMessaging:(BOOL)aFlag
4062 {
4063     _private->allowsMessaging = aFlag;
4064 }
4065
4066 - (BOOL)_allowsMessaging
4067 {
4068     return _private->allowsMessaging;
4069 }
4070
4071 - (void)_setFixedLayoutSize:(CGSize)size
4072 {
4073     ASSERT(WebThreadIsLocked());
4074     _private->fixedLayoutSize = size;
4075     if (Frame* mainFrame = core([self mainFrame])) {
4076         IntSize newSize(size);
4077         mainFrame->view()->setFixedLayoutSize(newSize);
4078         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
4079         [self setNeedsDisplay:YES];
4080     }
4081 }
4082
4083 - (CGSize)_fixedLayoutSize
4084 {
4085     return _private->fixedLayoutSize;
4086 }
4087
4088 - (void)_synchronizeCustomFixedPositionLayoutRect
4089 {
4090     ASSERT(WebThreadIsLocked());
4091
4092     IntRect newRect;
4093     {
4094         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4095         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4096             return;
4097         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
4098         _private->pendingFixedPositionLayoutRect = CGRectNull;
4099     }
4100
4101     if (Frame* mainFrame = core([self mainFrame]))
4102         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
4103 }
4104
4105 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
4106 {
4107     {
4108         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4109         _private->pendingFixedPositionLayoutRect = rect;
4110     }
4111     if (!synchronize)
4112         return;
4113     WebThreadRun(^{
4114         [self _synchronizeCustomFixedPositionLayoutRect];
4115     });
4116 }
4117
4118 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
4119 {
4120     ASSERT(WebThreadIsLocked());
4121     {
4122         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4123         _private->pendingFixedPositionLayoutRect = rect;
4124     }
4125     [self _synchronizeCustomFixedPositionLayoutRect];
4126 }
4127
4128 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
4129 {
4130     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4131     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4132         return false;
4133
4134     *rect = _private->pendingFixedPositionLayoutRect;
4135     _private->pendingFixedPositionLayoutRect = CGRectNull;
4136     return true;
4137 }
4138
4139 - (void)_viewGeometryDidChange
4140 {
4141     ASSERT(WebThreadIsLocked());
4142     
4143     if (Frame* coreFrame = [self _mainCoreFrame])
4144         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
4145 }
4146
4147 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
4148 {
4149     // Find the frame
4150     Node* node = core(domNode);
4151     Frame* frame = node->document().frame();
4152     if (!frame)
4153         return;
4154
4155     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
4156 }
4157
4158 + (void)_doNotStartObservingNetworkReachability
4159 {
4160     Settings::setShouldOptOutOfNetworkStateObservation(true);
4161 }
4162 #endif // PLATFORM(IOS)
4163
4164 #if ENABLE(TOUCH_EVENTS)
4165 - (NSArray *)_touchEventRegions
4166 {
4167     Frame* frame = [self _mainCoreFrame];
4168     if (!frame)
4169         return nil;
4170     
4171     Document* document = frame->document();
4172     if (!document)
4173         return nil;
4174
4175     Vector<IntRect> rects;
4176     document->getTouchRects(rects);
4177
4178     if (rects.size() == 0)
4179         return nil;
4180
4181     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
4182
4183     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
4184     Vector<IntRect>::const_iterator end = rects.end();
4185     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
4186         const IntRect& rect = *it;
4187         if (rect.isEmpty())
4188             continue;
4189
4190         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
4191         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
4192         // convert them here now.
4193         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
4194
4195         // The event region wants this points in this order:
4196         //  p2------p3
4197         //  |       |
4198         //  p1------p4
4199         //
4200         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
4201                                                                             :FloatPoint(viewRect.x(), viewRect.y())
4202                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
4203                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
4204         if (eventRegion) {
4205             [eventRegionArray addObject:eventRegion];
4206             [eventRegion release];
4207         }
4208     }
4209
4210     return eventRegionArray;
4211 }
4212 #endif // ENABLE(TOUCH_EVENTS)
4213
4214 // For backwards compatibility with the WebBackForwardList API, we honor both
4215 // a per-WebView and a per-preferences setting for whether to use the page cache.
4216
4217 - (BOOL)usesPageCache
4218 {
4219     return _private->usesPageCache && [[self preferences] usesPageCache];
4220 }
4221
4222 - (void)setUsesPageCache:(BOOL)usesPageCache
4223 {
4224     _private->usesPageCache = usesPageCache;
4225
4226     // Update our own settings and post the public notification only
4227     [self _preferencesChanged:[self preferences]];
4228     [[self preferences] _postPreferencesChangedAPINotification];
4229 }
4230
4231 - (WebHistoryItem *)_globalHistoryItem
4232 {
4233     if (!_private)
4234         return nil;
4235
4236     return kit(_private->_globalHistoryItem.get());
4237 }
4238
4239 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
4240 {
4241     _private->_globalHistoryItem = historyItem;
4242 }
4243
4244 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
4245 {
4246     IntPoint rectStart(rect.origin.x, rect.origin.y);
4247     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
4248     
4249     Frame* coreFrame = [self _mainCoreFrame];
4250     if (!coreFrame)
4251         return nil;
4252     
4253     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
4254     
4255     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
4256 }
4257
4258 #if !PLATFORM(IOS)
4259 - (void)_clearUndoRedoOperations
4260 {
4261     if (!_private->page)
4262         return;