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