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