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