Uncaught Exception: SyntaxError: Invalid regular expression: \ at end of pattern
[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 #if PLATFORM(IOS)
1124     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1125 #endif
1126 }
1127
1128 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1129 {
1130     self = [super initWithFrame:f];
1131     if (!self)
1132         return nil;
1133
1134 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1135     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1136     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1137     // need for Safari to unset it to prevent it from being passed to applications it launches.
1138     // Unsetting it when a WebView is first created is as good a place as any.
1139     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1140     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1141         unsetenv("DYLD_FRAMEWORK_PATH");
1142         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1143     }
1144 #endif
1145
1146     _private = [[WebViewPrivate alloc] init];
1147     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1148     [self setMaintainsBackForwardList: YES];
1149     return self;
1150 }
1151
1152 - (void)_viewWillDrawInternal
1153 {
1154     Frame* frame = [self _mainCoreFrame];
1155     if (frame && frame->view())
1156         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1157 }
1158
1159 + (NSArray *)_supportedMIMETypes
1160 {
1161     // Load the plug-in DB allowing plug-ins to install types.
1162     [WebPluginDatabase sharedDatabase];
1163     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1164 }
1165
1166 #if !PLATFORM(IOS)
1167 + (NSArray *)_supportedFileExtensions
1168 {
1169     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1170     NSArray *MIMETypes = [self _supportedMIMETypes];
1171     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1172     NSString *MIMEType;
1173     while ((MIMEType = [enumerator nextObject]) != nil) {
1174         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1175         if (extensionsForType) {
1176             [extensions addObjectsFromArray:extensionsForType];
1177         }
1178     }
1179     NSArray *uniqueExtensions = [extensions allObjects];
1180     [extensions release];
1181     return uniqueExtensions;
1182 }
1183 #endif
1184
1185 #if PLATFORM(IOS)
1186 + (void)enableWebThread
1187 {
1188     static BOOL isWebThreadEnabled = NO;
1189     if (!isWebThreadEnabled) {
1190         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1191         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1192         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1193         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1194         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1195         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1196         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1197         WebCoreObjCDeallocOnWebThread([WebView class]);
1198         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1199         if (IOSApplication::isTheEconomistOnIphone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1200             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1201         WebThreadEnable();
1202         isWebThreadEnabled = YES;
1203     }
1204 }
1205
1206 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1207 {
1208     self = [super initWithFrame:frame];
1209     if (!self)
1210         return nil;
1211     
1212     _private = [[WebViewPrivate alloc] init];
1213     
1214 #ifndef NDEBUG
1215     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1216 #endif
1217     
1218     if (!preferences)
1219         preferences = [WebPreferences standardPreferences];
1220     [preferences willAddToWebView];
1221     
1222     _private->preferences = [preferences retain];
1223     _private->mainFrameDocumentReady = NO;
1224     _private->drawsBackground = YES;
1225     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1226
1227     WebFrameView *frameView = nil;
1228     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1229     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1230     [self addSubview:frameView];
1231     [frameView release];
1232
1233     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1234     _private->group->addWebView(self);
1235
1236     PageConfiguration pageConfiguration;
1237     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1238 #if ENABLE(DRAG_SUPPORT)
1239     pageConfiguration.dragClient = new WebDragClient(self);
1240 #endif
1241
1242 #if USE(APPLE_INTERNAL_SDK)
1243 #import <WebKitAdditions/WebViewInitialization.mm>
1244 #endif
1245
1246     pageConfiguration.editorClient = new WebEditorClient(self);
1247     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1248     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1249     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1250     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1251     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1252     pageConfiguration.userContentProvider = &_private->group->userContentController();
1253     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1254
1255     _private->page = new Page(pageConfiguration);
1256     
1257     [self setSmartInsertDeleteEnabled:YES];
1258     
1259     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1260     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1261     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1262     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1263     _private->page->settings().setMinimumLogicalFontSize(9);
1264     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1265     _private->page->settings().setDefaultFixedFontSize(13);
1266     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1267     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1268     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1269     
1270     _private->page->settings().setFontFallbackPrefersPictographs(true);
1271     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1272     
1273     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1274     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1275     
1276     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1277     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1278
1279     // This is a workaround for <rdar://problem/21309911>.
1280     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1281
1282     _private->page->setGroupName(groupName);
1283
1284 #if ENABLE(REMOTE_INSPECTOR)
1285     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1286 #endif
1287     
1288     [self _updateScreenScaleFromWindow];
1289     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1290     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1291
1292     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1293     
1294     [self _addToAllWebViewsSet];
1295     
1296     ++WebViewCount;
1297     
1298     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1299     
1300     return self;
1301 }
1302
1303 + (void)_handleMemoryWarning
1304 {
1305     ASSERT(WebThreadIsCurrent());
1306     WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1307
1308     // Always peform the following.
1309     [WebView purgeInactiveFontData];
1310
1311     // Only perform the remaining if a non-simple document was created.
1312     if (!didOneTimeInitialization)
1313         return;
1314
1315     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1316
1317     [WebStorageManager closeIdleLocalStorageDatabases];
1318     StorageThread::releaseFastMallocFreeMemoryInAllThreads();
1319
1320     [WebView _releaseMemoryNow];
1321 }
1322
1323 + (void)registerForMemoryNotifications
1324 {
1325     BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::IOSApplication::isMobileSafari();
1326
1327     MemoryPressureHandler::singleton().installMemoryReleaseBlock(^{
1328         [WebView _handleMemoryWarning];
1329     }, shouldAutoClearPressureOnMemoryRelease);
1330
1331     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));
1332     dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1333         // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1334         MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1335     });
1336
1337     dispatch_resume(memoryNotificationEventSource);
1338
1339     if (!shouldAutoClearPressureOnMemoryRelease) {
1340         // Listen to memory status notification to reset the memory pressure flag.
1341         static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE,
1342                                                                                     0,
1343                                                                                     DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_NORMAL,
1344                                                                                     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1345         dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1346             unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1347             if (currentStatus == DISPATCH_MEMORYPRESSURE_NORMAL)
1348                 MemoryPressureHandler::singleton().clearMemoryPressure();
1349             else if (currentStatus == DISPATCH_MEMORYPRESSURE_WARN)
1350                 MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1351         });
1352
1353         dispatch_resume(memoryStatusEventSource);
1354     }
1355 }
1356
1357 + (void)_releaseMemoryNow
1358 {
1359     ASSERT(WebThreadIsCurrent());
1360     [WebView discardAllCompiledCode];
1361     [WebView garbageCollectNow];
1362     [WebView purgeInactiveFontData];
1363     [WebView drainLayerPool];
1364     [WebCache emptyInMemoryResources];
1365     [WebView releaseFastMallocMemoryOnCurrentThread];
1366
1367     dispatch_async(dispatch_get_main_queue(), ^{
1368         // Clear the main thread's TCMalloc thread cache.
1369         [WebView releaseFastMallocMemoryOnCurrentThread];
1370     });
1371 }
1372
1373 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1374 {
1375     Frame* frame = [self _mainCoreFrame];
1376     if (frame)
1377         frame->loader().history().replaceCurrentItem(core(item));
1378 }
1379
1380 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1381 {
1382     WebThreadRun(^{
1383         [WebView _releaseMemoryNow];
1384         dispatch_async(dispatch_get_main_queue(), handler);
1385     });
1386 }
1387
1388 + (void)releaseFastMallocMemoryOnCurrentThread
1389 {
1390     WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1391     WTF::releaseFastMallocFreeMemory();
1392 }
1393
1394 + (void)garbageCollectNow
1395 {
1396     ASSERT(WebThreadIsCurrent());
1397     WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1398     GCController::singleton().garbageCollectNow();
1399 }
1400
1401 + (void)purgeInactiveFontData
1402 {
1403     ASSERT(WebThreadIsCurrent());
1404     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1405     FontCache::singleton().purgeInactiveFontData();
1406 }
1407
1408 + (void)drainLayerPool
1409 {
1410     ASSERT(WebThreadIsCurrent());
1411     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1412     WebCore::LegacyTileCache::drainLayerPool();
1413 }
1414
1415 + (void)discardAllCompiledCode
1416 {
1417     ASSERT(WebThreadIsCurrent());
1418     WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1419     GCController::singleton().deleteAllCode();
1420 }
1421
1422 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1423 {
1424     return WebCore::isCharacterSmartReplaceExempt(character, b);
1425 }
1426
1427 - (void)updateLayoutIgnorePendingStyleSheets
1428 {
1429     WebThreadRun(^{
1430         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1431             Document *document = frame->document();
1432             if (document)
1433                 document->updateLayoutIgnorePendingStylesheets();
1434         }
1435     });
1436 }
1437 #endif // PLATFORM(IOS)
1438
1439 static NSMutableSet *knownPluginMIMETypes()
1440 {
1441     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1442     
1443     return mimeTypes;
1444 }
1445
1446 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1447 {
1448     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1449     [knownPluginMIMETypes() addObject:MIMEType];
1450 }
1451
1452 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1453 {
1454     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1455     [knownPluginMIMETypes() removeObject:MIMEType];
1456 }
1457
1458 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1459 {
1460     MIMEType = [MIMEType lowercaseString];
1461     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1462     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1463
1464 #if PLATFORM(IOS)
1465 #define WebPDFView ([WebView _getPDFViewClass])
1466 #endif
1467     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1468 #if PLATFORM(IOS)
1469 #undef WebPDFView
1470 #endif
1471         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1472
1473         if (allowPlugins) {
1474             // Load the plug-in DB allowing plug-ins to install types.
1475             [WebPluginDatabase sharedDatabase];
1476         }
1477
1478         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1479         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1480         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1481     }
1482     
1483     if (viewClass && repClass) {
1484         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1485             // Special-case WebHTMLView for text types that shouldn't be shown.
1486             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1487                 return NO;
1488
1489             // If the MIME type is a known plug-in we might not want to load it.
1490             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1491                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1492                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1493                 
1494                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1495                 if (!isSupportedByWebKit)
1496                     return NO;
1497             }
1498         }
1499         if (vClass)
1500             *vClass = viewClass;
1501         if (rClass)
1502             *rClass = repClass;
1503         return YES;
1504     }
1505     
1506     return NO;
1507 }
1508
1509 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1510 {
1511     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1512         return YES;
1513 #if !PLATFORM(IOS)
1514     if (_private->pluginDatabase) {
1515         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1516         if (pluginPackage) {
1517             if (vClass)
1518                 *vClass = [WebHTMLView class];
1519             if (rClass)
1520                 *rClass = [WebHTMLRepresentation class];
1521             return YES;
1522         }
1523     }
1524 #endif
1525     return NO;
1526 }
1527
1528 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1529 {
1530     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
1531 }
1532
1533 + (BOOL)canCloseAllWebViews
1534 {
1535     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1536 }
1537
1538 + (void)closeAllWebViews
1539 {
1540     DOMWindow::dispatchAllPendingUnloadEvents();
1541
1542     // This will close the WebViews in a random order. Change this if close order is important.
1543     // Make a new set to avoid mutating the set we are enumerating.
1544     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1545     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1546     while (WebView *webView = [enumerator nextObject])
1547         [webView close];
1548 }
1549
1550 + (BOOL)canShowFile:(NSString *)path
1551 {
1552     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1553 }
1554
1555 #if !PLATFORM(IOS)
1556 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1557 {
1558     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1559 }
1560 #endif
1561
1562 - (BOOL)_isClosed
1563 {
1564     return !_private || _private->closed;
1565 }
1566
1567 #if PLATFORM(IOS)
1568 - (void)_dispatchUnloadEvent
1569 {
1570     WebThreadRun(^{
1571         WebFrame *mainFrame = [self mainFrame];
1572         Frame *coreMainFrame = core(mainFrame);
1573         if (coreMainFrame) {
1574             Document *document = coreMainFrame->document();
1575             if (document)
1576                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1577         }
1578     });
1579 }
1580
1581 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1582 {
1583     WebFrame *mainFrame = [self mainFrame];
1584     Frame *coreMainFrame = core(mainFrame);
1585     if (!coreMainFrame)
1586         return nil;
1587     return coreMainFrame->styleAtSelectionStart();
1588 }
1589
1590 - (NSUInteger)_renderTreeSize
1591 {
1592     if (!_private->page)
1593         return 0;
1594     return _private->page->renderTreeSize();
1595 }
1596
1597 // FIXME: This is incorrectly named, and should be removed <rdar://problem/22242515>.
1598 - (NSSize)_contentsSizeRespectingOverflow
1599 {
1600     return [[[[self mainFrame] frameView] documentView] bounds].size;
1601 }
1602
1603 - (void)_dispatchTileDidDraw:(CALayer*)tile
1604 {
1605     id mailDelegate = [self _webMailDelegate];
1606     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1607         [mailDelegate _webthread_webView:self tileDidDraw:tile];
1608         return;
1609     }
1610
1611     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1612         return;
1613
1614     WebThreadLock();
1615
1616     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1617 }
1618
1619 - (void)_willStartScrollingOrZooming
1620 {
1621     // Pause timers during top level interaction
1622     if (_private->mainViewIsScrollingOrZooming)
1623         return;
1624     _private->mainViewIsScrollingOrZooming = YES;
1625
1626     // This suspends active DOM objects like timers, but not media.
1627     [[self mainFrame] setTimeoutsPaused:YES];
1628
1629     // This defers loading callbacks only.
1630     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1631     [self setDefersCallbacks:YES];
1632 }
1633
1634 - (void)_didFinishScrollingOrZooming
1635 {
1636     if (!_private->mainViewIsScrollingOrZooming)
1637         return;
1638     _private->mainViewIsScrollingOrZooming = NO;
1639     [self setDefersCallbacks:NO];
1640     [[self mainFrame] setTimeoutsPaused:NO];
1641     if (FrameView* view = [self _mainCoreFrame]->view())
1642         view->resumeVisibleImageAnimationsIncludingSubframes();
1643 }
1644
1645 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1646 {
1647     if (suspend)
1648         webResourceLoadScheduler().suspendPendingRequests();
1649     else
1650         webResourceLoadScheduler().resumePendingRequests();
1651 }
1652
1653 + (void)_setAllowCookies:(BOOL)allow
1654 {
1655     ResourceRequestBase::setDefaultAllowCookies(allow);
1656 }
1657
1658 + (BOOL)_allowCookies
1659 {
1660     return ResourceRequestBase::defaultAllowCookies();
1661 }
1662
1663 + (BOOL)_isUnderMemoryPressure
1664 {
1665     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
1666 }
1667
1668 + (void)_clearMemoryPressure
1669 {
1670     MemoryPressureHandler::singleton().clearMemoryPressure();
1671 }
1672
1673 + (BOOL)_shouldWaitForMemoryClearMessage
1674 {
1675     return MemoryPressureHandler::singleton().shouldWaitForMemoryClearMessage();
1676 }
1677 #endif // PLATFORM(IOS)
1678
1679 - (void)_closePluginDatabases
1680 {
1681     pluginDatabaseClientCount--;
1682
1683     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1684
1685 #if !PLATFORM(IOS)
1686     // Unload the WebView local plug-in database. 
1687     if (_private->pluginDatabase) {
1688         [_private->pluginDatabase destroyAllPluginInstanceViews];
1689         [_private->pluginDatabase close];
1690         [_private->pluginDatabase release];
1691         _private->pluginDatabase = nil;
1692     }
1693 #endif
1694     
1695     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1696     if (!pluginDatabaseClientCount && applicationIsTerminating)
1697         [WebPluginDatabase closeSharedDatabase];
1698 }
1699
1700 - (void)_closeWithFastTeardown 
1701 {
1702 #ifndef NDEBUG
1703     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1704 #endif
1705
1706 #if !PLATFORM(IOS)
1707     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1708 #endif
1709     [[NSNotificationCenter defaultCenter] removeObserver:self];
1710
1711     [self _closePluginDatabases];
1712 }
1713
1714 static bool fastDocumentTeardownEnabled()
1715 {
1716 #ifdef NDEBUG
1717     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1718 #else
1719     static bool initialized = false;
1720     static bool enabled = false;
1721     if (!initialized) {
1722         // This allows debug builds to default to not have fast teardown, so leak checking still works.
1723         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1724         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1725         if (setting)
1726             enabled = ![setting boolValue];
1727         initialized = true;
1728     }
1729 #endif
1730     return enabled;
1731 }
1732
1733 // _close is here only for backward compatibility; clients and subclasses should use
1734 // public method -close instead.
1735 - (void)_close
1736 {
1737 #if PLATFORM(IOS)
1738     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1739     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1740
1741     [self _clearDelegates];
1742
1743     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1744     WebThreadRun(^{
1745 #endif            
1746
1747     if (!_private || _private->closed)
1748         return;
1749
1750     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1751
1752     _private->closed = YES;
1753     [self _removeFromAllWebViewsSet];
1754
1755 #ifndef NDEBUG
1756     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1757 #endif
1758
1759     // To quit the apps fast we skip document teardown, except plugins
1760     // need to be destroyed and unloaded.
1761     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1762         [self _closeWithFastTeardown];
1763         return;
1764     }
1765
1766 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1767     [self _exitVideoFullscreen];
1768 #endif
1769
1770 #if PLATFORM(IOS)
1771     _private->closing = YES;
1772 #endif
1773
1774     if (Frame* mainFrame = [self _mainCoreFrame])
1775         mainFrame->loader().detachFromParent();
1776
1777     [self setHostWindow:nil];
1778
1779 #if !PLATFORM(IOS)
1780     [self setDownloadDelegate:nil];
1781     [self setEditingDelegate:nil];
1782     [self setFrameLoadDelegate:nil];
1783     [self setPolicyDelegate:nil];
1784     [self setResourceLoadDelegate:nil];
1785     [self setScriptDebugDelegate:nil];
1786     [self setUIDelegate:nil];
1787
1788     [_private->inspector inspectedWebViewClosed];
1789 #endif
1790 #if PLATFORM(MAC)
1791     [_private->immediateActionController webViewClosed];
1792 #endif
1793
1794 #if !PLATFORM(IOS)
1795     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1796     [self removeDragCaret];
1797 #endif
1798
1799     _private->group->removeWebView(self);
1800
1801     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1802     // all the plug-ins in the page cache to break any retain cycles.
1803     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1804     Page* page = _private->page;
1805     _private->page = 0;
1806     delete page;
1807
1808 #if !PLATFORM(IOS)
1809     if (_private->hasSpellCheckerDocumentTag) {
1810         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1811         _private->hasSpellCheckerDocumentTag = NO;
1812     }
1813 #endif
1814
1815     if (_private->layerFlushController) {
1816         _private->layerFlushController->invalidate();
1817         _private->layerFlushController = nullptr;
1818     }
1819
1820     [[self _notificationProvider] unregisterWebView:self];
1821
1822 #if !PLATFORM(IOS)
1823     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1824 #endif
1825     [[NSNotificationCenter defaultCenter] removeObserver:self];
1826
1827     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1828
1829     WebPreferences *preferences = _private->preferences;
1830     _private->preferences = nil;
1831     [preferences didRemoveFromWebView];
1832     [preferences release];
1833
1834     [self _closePluginDatabases];
1835
1836 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
1837     if (_private->m_playbackTargetPicker) {
1838         _private->m_playbackTargetPicker->invalidate();
1839         _private->m_playbackTargetPicker = nullptr;
1840     }
1841 #endif
1842
1843 #ifndef NDEBUG
1844     // Need this to make leak messages accurate.
1845     if (applicationIsTerminating) {
1846         GCController::singleton().garbageCollectNow();
1847         [WebCache setDisabled:YES];
1848     }
1849 #endif
1850 #if PLATFORM(IOS)
1851     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1852     });
1853 #endif            
1854 }
1855
1856 // Indicates if the WebView is in the midst of a user gesture.
1857 - (BOOL)_isProcessingUserGesture
1858 {
1859     return ScriptController::processingUserGesture();
1860 }
1861
1862 + (NSString *)_MIMETypeForFile:(NSString *)path
1863 {
1864 #if !PLATFORM(IOS)
1865     NSString *extension = [path pathExtension];
1866 #endif
1867     NSString *MIMEType = nil;
1868
1869 #if !PLATFORM(IOS)
1870     // Get the MIME type from the extension.
1871     if ([extension length] != 0) {
1872         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
1873     }
1874 #endif
1875
1876     // If we can't get a known MIME type from the extension, sniff.
1877     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1878         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1879         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1880         [handle closeFile];
1881         if ([data length] != 0) {
1882             MIMEType = [data _webkit_guessedMIMEType];
1883         }
1884         if ([MIMEType length] == 0) {
1885             MIMEType = @"application/octet-stream";
1886         }
1887     }
1888
1889     return MIMEType;
1890 }
1891
1892 - (WebDownload *)_downloadURL:(NSURL *)URL
1893 {
1894     ASSERT(URL);
1895     
1896     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1897     WebDownload *download = [WebDownload _downloadWithRequest:request
1898                                                      delegate:_private->downloadDelegate
1899                                                     directory:nil];
1900     [request release];
1901     
1902     return download;
1903 }
1904
1905 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1906 {
1907     NSDictionary *features = [[NSDictionary alloc] init];
1908     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1909                                             createWebViewWithRequest:nil
1910                                                       windowFeatures:features];
1911     [features release];
1912     if (!newWindowWebView)
1913         return nil;
1914
1915     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1916     return newWindowWebView;
1917 }
1918
1919 - (WebInspector *)inspector
1920 {
1921     if (!_private->inspector)
1922         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
1923     return _private->inspector;
1924 }
1925
1926 #if ENABLE(REMOTE_INSPECTOR)
1927 + (void)_enableRemoteInspector
1928 {
1929     RemoteInspector::singleton().start();
1930 }
1931
1932 + (void)_disableRemoteInspector
1933 {
1934     RemoteInspector::singleton().stop();
1935 }
1936
1937 + (void)_disableAutoStartRemoteInspector
1938 {
1939     RemoteInspector::startDisabled();
1940 }
1941
1942 + (BOOL)_isRemoteInspectorEnabled
1943 {
1944     return RemoteInspector::singleton().enabled();
1945 }
1946
1947 + (BOOL)_hasRemoteInspectorSession
1948 {
1949     return RemoteInspector::singleton().hasActiveDebugSession();
1950 }
1951
1952 - (BOOL)allowsRemoteInspection
1953 {
1954     return _private->page->remoteInspectionAllowed();
1955 }
1956
1957 - (void)setAllowsRemoteInspection:(BOOL)allow
1958 {
1959     _private->page->setRemoteInspectionAllowed(allow);
1960 }
1961
1962 - (void)setShowingInspectorIndication:(BOOL)showing
1963 {
1964 #if PLATFORM(IOS)
1965     ASSERT(WebThreadIsLocked());
1966
1967     if (showing) {
1968         if (!_private->indicateLayer) {
1969             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1970             [_private->indicateLayer setNeedsLayout];
1971             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1972         }
1973     } else {
1974         [_private->indicateLayer removeFromSuperlayer];
1975         [_private->indicateLayer release];
1976         _private->indicateLayer = nil;
1977     }
1978 #else
1979     // Implemented in WebCore::InspectorOverlay.
1980 #endif
1981 }
1982
1983 #if PLATFORM(IOS)
1984 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
1985 {
1986     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
1987     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
1988 }
1989 #endif // PLATFORM(IOS)
1990 #endif // ENABLE(REMOTE_INSPECTOR)
1991
1992 - (WebCore::Page*)page
1993 {
1994     return _private->page;
1995 }
1996
1997 #if !PLATFORM(IOS)
1998 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1999 {
2000     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2001     NSArray *menuItems = defaultMenuItems;
2002
2003     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2004     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2005     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2006     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2007         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2008         if (!menuItems)
2009             return nil;
2010     }
2011
2012     unsigned count = [menuItems count];
2013     if (!count)
2014         return nil;
2015
2016     NSMenu *menu = [[NSMenu alloc] init];
2017     for (unsigned i = 0; i < count; i++)
2018         [menu addItem:[menuItems objectAtIndex:i]];
2019
2020     return [menu autorelease];
2021 }
2022 #endif
2023
2024 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2025 {
2026     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2027     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2028     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2029     if (!dictionary)
2030         return;
2031     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2032 }
2033
2034 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2035 {
2036     if (!_private->page)
2037         return;
2038     
2039     if (!otherView->_private->page)
2040         return;
2041     
2042     // It turns out the right combination of behavior is done with the back/forward load
2043     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2044     // in the back forward list, and go to the current one.
2045
2046     BackForwardController& backForward = _private->page->backForward();
2047     ASSERT(!backForward.currentItem()); // destination list should be empty
2048
2049     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2050     if (!otherBackForward.currentItem())
2051         return; // empty back forward list, bail
2052     
2053     HistoryItem* newItemToGoTo = nullptr;
2054
2055     int lastItemIndex = otherBackForward.forwardCount();
2056     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2057         if (i == 0) {
2058             // If this item is showing , save away its current scroll and form state,
2059             // since that might have changed since loading and it is normally not saved
2060             // until we leave that page.
2061             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2062         }
2063         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2064         if (i == 0) 
2065             newItemToGoTo = newItem.ptr();
2066         backForward.client()->addItem(WTFMove(newItem));
2067     }
2068
2069     ASSERT(newItemToGoTo);
2070     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward);
2071 }
2072
2073 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2074 {
2075     _private->formDelegate = delegate;
2076 #if PLATFORM(IOS)
2077     [_private->formDelegateForwarder clearTarget];
2078     [_private->formDelegateForwarder release];
2079     _private->formDelegateForwarder = nil;
2080 #endif
2081 }
2082
2083 - (id<WebFormDelegate>)_formDelegate
2084 {
2085     return _private->formDelegate;
2086 }
2087
2088 #if PLATFORM(IOS)
2089 - (id)_formDelegateForwarder
2090 {
2091     if (_private->closing)
2092         return nil;
2093
2094     if (!_private->formDelegateForwarder)
2095         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2096     return _private->formDelegateForwarder;
2097 }
2098
2099 - (id)_formDelegateForSelector:(SEL)selector
2100 {
2101     id delegate = self->_private->formDelegate;
2102     if ([delegate respondsToSelector:selector])
2103         return delegate;
2104
2105     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2106     if ([delegate respondsToSelector:selector])
2107         return delegate;
2108
2109     return nil;
2110 }
2111 #endif
2112
2113 #if !PLATFORM(IOS)
2114 - (BOOL)_needsAdobeFrameReloadingQuirk
2115 {
2116     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2117         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2118         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2119         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2120         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2121         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2122         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2123         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2124         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2125         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2126
2127     return needsQuirk;
2128 }
2129
2130 - (BOOL)_needsLinkElementTextCSSQuirk
2131 {
2132     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2133         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2134     return needsQuirk;
2135 }
2136
2137 - (BOOL)_needsIsLoadingInAPISenseQuirk
2138 {
2139     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2140     
2141     return needsQuirk;
2142 }
2143
2144 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2145 {
2146     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2147     return needsQuirks;
2148 }
2149
2150 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2151 {
2152     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2153     return needsQuirk;
2154 }
2155
2156 static bool needsSelfRetainWhileLoadingQuirk()
2157 {
2158     static bool needsQuirk = MacApplication::isAperture();
2159     return needsQuirk;
2160 }
2161 #endif // !PLATFORM(IOS)
2162
2163 - (BOOL)_needsPreHTML5ParserQuirks
2164 {    
2165 #if !PLATFORM(IOS)
2166     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2167     // with the new HTML5 parser. If these applications were linked against a
2168     // version of WebKit prior to the introduction of the HTML5 parser, enable
2169     // parser quirks to maintain compatibility. For details, see 
2170     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2171     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2172     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2173         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2174     
2175     // Mail.app must continue to display HTML email that contains quirky markup.
2176     static bool isAppleMail = MacApplication::isAppleMail();
2177
2178     return isApplicationNeedingParserQuirks
2179         || isAppleMail
2180 #if ENABLE(DASHBOARD_SUPPORT)
2181         // Pre-HTML5 parser quirks are required to remain compatible with many
2182         // Dashboard widgets. See <rdar://problem/8175982>.
2183         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2184 #endif
2185         || [[self preferences] usePreHTML5ParserQuirks];
2186 #else
2187     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && IOSApplication::isDaijisenDictionary();
2188     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2189 #endif
2190 }
2191
2192 - (void)_preferencesChangedNotification:(NSNotification *)notification
2193 {
2194 #if PLATFORM(IOS)
2195     // For WebViews that load synchronously, preference changes need to be propagated
2196     // down to WebCore synchronously so that loads in that WebView have the correct
2197     // up-to-date settings.
2198     if (!WebThreadIsLocked())
2199         WebThreadLock();
2200     if ([[self mainFrame] _loadsSynchronously]) {
2201 #endif
2202
2203     WebPreferences *preferences = (WebPreferences *)[notification object];
2204     [self _preferencesChanged:preferences];
2205
2206 #if PLATFORM(IOS)
2207     } else {
2208         WebThreadRun(^{
2209             // It is possible that the prefs object has already changed before the invocation could be called
2210             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2211             WebPreferences *preferences = (WebPreferences *)[notification object];
2212             if (preferences != [self preferences])
2213                 return;
2214             [self _preferencesChanged:preferences];
2215         });
2216     }
2217 #endif
2218 }
2219
2220 - (void)_preferencesChanged:(WebPreferences *)preferences
2221 {    
2222     ASSERT(preferences == [self preferences]);
2223     if (!_private->userAgentOverridden)
2224         _private->userAgent = String();
2225
2226     // Cache this value so we don't have to read NSUserDefaults on each page load
2227     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2228
2229     // Update corresponding WebCore Settings object.
2230     if (!_private->page)
2231         return;
2232
2233 #if PLATFORM(IOS)
2234     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2235     // didOneTimeInitialization is true so that we don't initialize databases
2236     // until the first WebView has been created. This is because database
2237     // initialization current requires disk access to populate the origins
2238     // quota map and we want to do this lazily by waiting until WebKit is
2239     // used to display web content in a WebView. The possible cases are:
2240     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2241     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2242     if (didOneTimeInitialization) {
2243         if ([preferences databasesEnabled])
2244             [WebDatabaseManager sharedWebDatabaseManager];
2245         
2246         if ([preferences storageTrackerEnabled])
2247             WebKitInitializeStorageIfNecessary();
2248     }
2249 #endif
2250     
2251     Settings& settings = _private->page->settings();
2252
2253     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2254     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2255     settings.setDefaultFontSize([preferences defaultFontSize]);
2256     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2257     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2258     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2259     settings.setFixedFontFamily([preferences fixedFontFamily]);
2260     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2261     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2262     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2263     settings.setJavaEnabled([preferences isJavaEnabled]);
2264     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2265     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2266     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2267     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2268     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2269     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2270     settings.setMinimumFontSize([preferences minimumFontSize]);
2271     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2272     settings.setPictographFontFamily([preferences pictographFontFamily]);
2273     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2274     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2275
2276     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2277     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2278     settings.setSerifFontFamily([preferences serifFontFamily]);
2279     settings.setStandardFontFamily([preferences standardFontFamily]);
2280     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2281     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2282 #if PLATFORM(IOS)
2283     settings.setShouldPrintBackgrounds(true);
2284 #else
2285     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2286 #endif
2287     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2288     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2289     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2290     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2291     settings.setUsesPageCache([self usesPageCache]);
2292     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2293     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2294
2295     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2296     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2297     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2298
2299     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2300     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2301     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2302     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2303     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2304     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2305     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2306     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2307     
2308     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2309     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2310     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2311     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2312     settings.setShowDebugBorders([preferences showDebugBorders]);
2313     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2314     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2315     settings.setWebGLEnabled([preferences webGLEnabled]);
2316     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2317
2318     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2319     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2320     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2321     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2322     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2323     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2324     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2325     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2326     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2327
2328     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2329     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2330     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2331     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2332     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2333
2334     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2335     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2336     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2337     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2338     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2339     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2340     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2341     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2342     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2343     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2344     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2345     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2346     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2347
2348     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2349
2350     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2351     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2352     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2353
2354     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2355
2356     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2357     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2358
2359     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2360     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2361
2362     switch ([preferences storageBlockingPolicy]) {
2363     case WebAllowAllStorage:
2364         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2365         break;
2366     case WebBlockThirdPartyStorage:
2367         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2368         break;
2369     case WebBlockAllStorage:
2370         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2371         break;
2372     }
2373
2374     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2375     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2376
2377     settings.setFixedPositionCreatesStackingContext(true);
2378 #if PLATFORM(MAC)
2379     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2380 #endif
2381
2382 #if ENABLE(RUBBER_BANDING)
2383     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2384     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2385 #endif
2386
2387 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2388     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2389 #endif
2390 #if PLATFORM(IOS)
2391     settings.setStandalone([preferences _standalone]);
2392     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2393     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2394     settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2395     settings.setMaxParseDuration([preferences _maxParseDuration]);
2396     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2397     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2398     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2399     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2400 #if HAVE(AVKIT)
2401     settings.setAVKitEnabled([preferences avKitEnabled]);
2402 #endif
2403     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2404     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2405
2406     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2407     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2408
2409     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2410     settings.setDelegatesPageScaling(true);
2411
2412 #if ENABLE(IOS_TEXT_AUTOSIZING)
2413     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2414 #endif
2415 #endif // PLATFORM(IOS)
2416
2417 #if PLATFORM(MAC)
2418     if ([preferences userStyleSheetEnabled]) {
2419         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2420         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2421             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2422         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2423     } else
2424         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2425
2426     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2427     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2428     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2429     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2430     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2431     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2432     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2433     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2434     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2435     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2436 #endif // PLATFORM(MAC)
2437
2438     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2439
2440 #if ENABLE(MEDIA_SOURCE)
2441     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2442 #endif
2443
2444 #if ENABLE(SERVICE_CONTROLS)
2445     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2446     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2447 #endif
2448
2449 #if ENABLE(VIDEO_TRACK)
2450     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2451     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2452     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2453 #endif
2454
2455 #if USE(AVFOUNDATION)
2456     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2457     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2458 #endif
2459
2460 #if ENABLE(MEDIA_STREAM)
2461     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2462 #endif
2463
2464 #if ENABLE(WEB_AUDIO)
2465     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2466 #endif
2467
2468 #if ENABLE(FULLSCREEN_API)
2469     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2470 #endif
2471
2472     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2473
2474     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2475
2476     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2477
2478 #if ENABLE(GAMEPAD)
2479     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2480 #endif
2481
2482 #if ENABLE(INDEXED_DATABASE)
2483     RuntimeEnabledFeatures::sharedFeatures().setWebkitIndexedDBEnabled(true);
2484 #endif
2485
2486 #if ENABLE(SHADOW_DOM)
2487     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2488 #endif
2489 #if ENABLE(CUSTOM_ELEMENTS)
2490     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2491 #endif
2492
2493
2494     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2495     if (timeout > 0)
2496         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2497
2498     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2499     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2500
2501     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2502     if (_private->zoomsTextOnly != zoomsTextOnly)
2503         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2504
2505 #if PLATFORM(IOS)
2506     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2507     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2508     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2509     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2510 #endif
2511
2512 #if ENABLE(ENCRYPTED_MEDIA_V2)
2513     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2514 #endif
2515
2516     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2517     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2518 }
2519
2520 static inline IMP getMethod(id o, SEL s)
2521 {
2522     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2523 }
2524
2525 #if PLATFORM(IOS)
2526 - (id)_UIKitDelegateForwarder
2527 {
2528     if (_private->closing)
2529         return nil;
2530         
2531     if (!_private->UIKitDelegateForwarder)
2532         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2533     return _private->UIKitDelegateForwarder;
2534 }
2535 #endif
2536
2537 - (void)_cacheResourceLoadDelegateImplementations
2538 {
2539     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2540     id delegate = _private->resourceProgressDelegate;
2541
2542     if (!delegate) {
2543         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2544         return;
2545     }
2546
2547     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2548     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2549     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2550     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2551     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2552 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2553     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2554 #endif
2555
2556 #if PLATFORM(IOS)
2557     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2558     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2559     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2560     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2561     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2562     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2563     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2564     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2565     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2566 #endif
2567
2568     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2569     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2570     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2571     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2572     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2573     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2574     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2575     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2576 }
2577
2578 - (void)_cacheFrameLoadDelegateImplementations
2579 {
2580     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2581     id delegate = _private->frameLoadDelegate;
2582
2583     if (!delegate) {
2584         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2585         return;
2586     }
2587
2588     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2589     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2590     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2591     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2592     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2593 #if JSC_OBJC_API_ENABLED
2594     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2595 #endif
2596     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2597     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2598     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2599     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2600     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2601     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2602     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2603     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2604     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2605     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2606     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2607     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2608 #if ENABLE(ICONDATABASE)
2609     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2610 #endif
2611     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2612     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2613     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2614     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2615     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2616     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2617     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2618     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2619     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2620     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2621 #if PLATFORM(IOS)
2622     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2623 #endif
2624
2625     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2626     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2627     // for backwards compatibility.
2628     Page* page = core(self);
2629     if (page) {
2630         unsigned milestones = DidFirstLayout;
2631 #if PLATFORM(IOS)
2632         milestones |= DidFirstVisuallyNonEmptyLayout;
2633 #else
2634         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2635             milestones |= DidFirstVisuallyNonEmptyLayout;
2636 #endif
2637         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2638     }
2639 }
2640
2641 - (void)_cacheScriptDebugDelegateImplementations
2642 {
2643     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2644     id delegate = _private->scriptDebugDelegate;
2645
2646     if (!delegate) {
2647         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2648         return;
2649     }
2650
2651     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2652     if (cache->didParseSourceFunc)
2653         cache->didParseSourceExpectsBaseLineNumber = YES;
2654     else {
2655         cache->didParseSourceExpectsBaseLineNumber = NO;
2656         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2657     }
2658
2659     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2660
2661     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2662     if (cache->exceptionWasRaisedFunc)
2663         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2664     else {
2665         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2666         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2667     }
2668 }
2669
2670 - (void)_cacheHistoryDelegateImplementations
2671 {
2672     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2673     id delegate = _private->historyDelegate;
2674
2675     if (!delegate) {
2676         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2677         return;
2678     }
2679
2680     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2681     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2682     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2683     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2684     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2685     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2686 }
2687
2688 - (id)_policyDelegateForwarder
2689 {
2690 #if PLATFORM(IOS)
2691     if (_private->closing)
2692         return nil;
2693 #endif
2694     if (!_private->policyDelegateForwarder)
2695         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2696     return _private->policyDelegateForwarder;
2697 }
2698
2699 - (id)_UIDelegateForwarder
2700 {
2701 #if PLATFORM(IOS)
2702     if (_private->closing)
2703         return nil;
2704 #endif
2705     if (!_private->UIDelegateForwarder)
2706         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2707     return _private->UIDelegateForwarder;
2708 }
2709
2710 #if PLATFORM(IOS)
2711 - (id)_UIDelegateForSelector:(SEL)selector
2712 {
2713     id delegate = self->_private->UIDelegate;
2714     if ([delegate respondsToSelector:selector])
2715         return delegate;
2716
2717     delegate = [WebDefaultUIDelegate sharedUIDelegate];
2718     if ([delegate respondsToSelector:selector])
2719         return delegate;
2720
2721     return nil;
2722 }
2723 #endif
2724
2725 - (id)_editingDelegateForwarder
2726 {
2727 #if PLATFORM(IOS)
2728     if (_private->closing)
2729         return nil;
2730 #endif    
2731     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2732     // Not sure if that is a bug or not.
2733     if (!_private)
2734         return nil;
2735
2736     if (!_private->editingDelegateForwarder)
2737         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2738     return _private->editingDelegateForwarder;
2739 }
2740
2741 - (void)_closeWindow
2742 {
2743     [[self _UIDelegateForwarder] webViewClose:self];
2744 }
2745
2746 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2747 {
2748     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2749     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2750     
2751     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2752     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2753     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2754     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2755 }
2756
2757 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2758 {
2759     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2760     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2761
2762     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2763     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2764     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2765     if ([viewClass class] == [WebHTMLView class])
2766         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2767     
2768     // This is used to make _representationExistsForURLScheme faster.
2769     // Without this set, we'd have to create the MIME type each time.
2770     if (schemesWithRepresentationsSet == nil) {
2771         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2772     }
2773     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2774 }
2775
2776 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2777 {
2778     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2779 }
2780
2781 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2782 {
2783     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2784 }
2785
2786 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2787 {
2788     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2789     if (!request)
2790         return NO;
2791
2792     if ([NSURLConnection canHandleRequest:request])
2793         return YES;
2794
2795     NSString *scheme = [[request URL] scheme];
2796
2797     // Representations for URL schemes work at the top level.
2798     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2799         return YES;
2800
2801     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2802         return YES;
2803
2804     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2805         return YES;
2806
2807     return NO;
2808 }
2809
2810 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2811 {
2812     return [self _canHandleRequest:request forMainFrame:YES];
2813 }
2814
2815 + (NSString *)_decodeData:(NSData *)data
2816 {
2817     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2818     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2819 }
2820
2821 - (void)_pushPerformingProgrammaticFocus
2822 {
2823     _private->programmaticFocusCount++;
2824 }
2825
2826 - (void)_popPerformingProgrammaticFocus
2827 {
2828     _private->programmaticFocusCount--;
2829 }
2830
2831 - (BOOL)_isPerformingProgrammaticFocus
2832 {
2833     return _private->programmaticFocusCount != 0;
2834 }
2835
2836 #if !PLATFORM(IOS)
2837 - (void)_didChangeValueForKey: (NSString *)key
2838 {
2839     LOG (Bindings, "calling didChangeValueForKey: %@", key);
2840     [self didChangeValueForKey: key];
2841 }
2842
2843 - (void)_willChangeValueForKey: (NSString *)key
2844 {
2845     LOG (Bindings, "calling willChangeValueForKey: %@", key);
2846     [self willChangeValueForKey: key];
2847 }
2848
2849 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2850     static NSSet *manualNotifyKeys = nil;
2851     if (!manualNotifyKeys)
2852         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2853             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2854             nil];
2855     if ([manualNotifyKeys containsObject:key])
2856         return NO;
2857     return YES;
2858 }
2859
2860 - (NSArray *)_declaredKeys {
2861     static NSArray *declaredKeys = nil;
2862     if (!declaredKeys)
2863         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2864             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2865     return declaredKeys;
2866 }
2867
2868 - (void)setObservationInfo:(void *)info
2869 {
2870     _private->observationInfo = info;
2871 }
2872
2873 - (void *)observationInfo
2874 {
2875     return _private->observationInfo;
2876 }
2877
2878 - (void)_willChangeBackForwardKeys
2879 {
2880     [self _willChangeValueForKey: _WebCanGoBackKey];
2881     [self _willChangeValueForKey: _WebCanGoForwardKey];
2882 }
2883
2884 - (void)_didChangeBackForwardKeys
2885 {
2886     [self _didChangeValueForKey: _WebCanGoBackKey];
2887     [self _didChangeValueForKey: _WebCanGoForwardKey];
2888 }
2889
2890 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2891 {
2892     if (needsSelfRetainWhileLoadingQuirk())
2893         [self retain];
2894
2895     [self _willChangeBackForwardKeys];
2896     if (frame == [self mainFrame]){
2897         // Force an observer update by sending a will/did.
2898         [self _willChangeValueForKey: _WebIsLoadingKey];
2899         [self _didChangeValueForKey: _WebIsLoadingKey];
2900
2901         [self _willChangeValueForKey: _WebMainFrameURLKey];
2902     }
2903
2904     [NSApp setWindowsNeedUpdate:YES];
2905
2906 #if ENABLE(FULLSCREEN_API)
2907     Document* document = core([frame DOMDocument]);
2908     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2909         SEL selector = @selector(webView:closeFullScreenWithListener:);
2910         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2911             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2912             CallUIDelegate(self, selector, listener);
2913             [listener release];
2914         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2915             [_private->newFullscreenController close];
2916         }
2917     }
2918 #endif
2919 }
2920
2921 - (void)_checkDidPerformFirstNavigation
2922 {
2923     if (_private->_didPerformFirstNavigation)
2924         return;
2925
2926     Page* page = _private->page;
2927     if (!page)
2928         return;
2929
2930     auto& backForwardController = page->backForward();
2931
2932     if (!backForwardController.backItem())
2933         return;
2934
2935     _private->_didPerformFirstNavigation = YES;
2936
2937     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2938         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2939 }
2940
2941 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2942 {
2943     if (frame == [self mainFrame])
2944         [self _didChangeValueForKey: _WebMainFrameURLKey];
2945
2946     [self _checkDidPerformFirstNavigation];
2947
2948     [NSApp setWindowsNeedUpdate:YES];
2949 }
2950
2951 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2952 {
2953     if (needsSelfRetainWhileLoadingQuirk())
2954         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2955         
2956     [self _didChangeBackForwardKeys];
2957     if (frame == [self mainFrame]){
2958         // Force an observer update by sending a will/did.
2959         [self _willChangeValueForKey: _WebIsLoadingKey];
2960         [self _didChangeValueForKey: _WebIsLoadingKey];
2961     }
2962     [NSApp setWindowsNeedUpdate:YES];
2963 }
2964
2965 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2966 {
2967     if (needsSelfRetainWhileLoadingQuirk())
2968         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2969
2970     [self _didChangeBackForwardKeys];
2971     if (frame == [self mainFrame]){
2972         // Force an observer update by sending a will/did.
2973         [self _willChangeValueForKey: _WebIsLoadingKey];
2974         [self _didChangeValueForKey: _WebIsLoadingKey];
2975     }
2976     [NSApp setWindowsNeedUpdate:YES];
2977 }
2978
2979 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2980 {
2981     if (needsSelfRetainWhileLoadingQuirk())
2982         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2983
2984     [self _didChangeBackForwardKeys];
2985     if (frame == [self mainFrame]){
2986         // Force an observer update by sending a will/did.
2987         [self _willChangeValueForKey: _WebIsLoadingKey];
2988         [self _didChangeValueForKey: _WebIsLoadingKey];
2989         
2990         [self _didChangeValueForKey: _WebMainFrameURLKey];
2991     }
2992     [NSApp setWindowsNeedUpdate:YES];
2993 }
2994
2995 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2996 {
2997     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2998     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2999     NSCachedURLResponse *cachedResponse;
3000
3001     if (!_private->page)
3002         return nil;
3003
3004     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3005         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3006     else
3007         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3008
3009     return cachedResponse;
3010 }
3011
3012 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3013 {
3014     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3015     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3016     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3017                         element:domElement
3018                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3019                           title:[element objectForKey:WebElementImageAltStringKey] 
3020                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3021                           types:types
3022                          source:nil];
3023 }
3024
3025 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3026 {
3027     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3028                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3029                         types:types];
3030 }
3031
3032 #if ENABLE(DRAG_SUPPORT)
3033 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3034 {
3035     if (!_private->page)
3036         return;
3037     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3038 }
3039 #endif
3040
3041 #else
3042
3043 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3044 {
3045     if (frame == [self mainFrame])
3046         _private->didDrawTiles = 0;
3047 }
3048
3049 #endif // PLATFORM(IOS)
3050
3051 #if ENABLE(DASHBOARD_SUPPORT)
3052
3053 #define DASHBOARD_CONTROL_LABEL @"control"
3054
3055 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3056 {
3057     NSRect adjustedBounds = bounds;
3058     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3059     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3060     adjustedBounds.size = bounds.size;
3061
3062     NSRect adjustedClip;
3063     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3064     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3065     adjustedClip.size = clip.size;
3066
3067     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3068         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3069     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3070     if (!scrollerRegions) {
3071         scrollerRegions = [[NSMutableArray alloc] init];
3072         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3073         [scrollerRegions release];
3074     }
3075     [scrollerRegions addObject:region];
3076     [region release];
3077 }
3078
3079 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3080 {    
3081     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3082
3083     for (const auto& widget: frameView->children()) {
3084         if (is<FrameView>(*widget)) {
3085             [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3086             continue;
3087         }
3088
3089         if (!widget->isScrollbar())
3090             continue;
3091
3092         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3093         // it's not common to need this to be correct in Dashboard widgets.
3094         NSRect bounds = widget->frameRect();
3095         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3096     }
3097 }
3098
3099 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3100 {
3101     // Add scroller regions for NSScroller and WebCore scrollbars
3102     NSUInteger count = [views count];
3103     for (NSUInteger i = 0; i < count; i++) {
3104         NSView *view = [views objectAtIndex:i];
3105         
3106         if ([view isKindOfClass:[WebHTMLView class]]) {
3107             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3108                 if (FrameView* coreView = coreFrame->view())
3109                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3110             }
3111         } else if ([view isKindOfClass:[NSScroller class]]) {
3112             // AppKit places absent scrollers at -100,-100
3113             if ([view frame].origin.y < 0)
3114                 continue;
3115             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3116         }
3117         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3118     }
3119 }
3120
3121 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3122 {
3123     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3124 }
3125
3126 - (NSDictionary *)_dashboardRegions
3127 {
3128     // Only return regions from main frame.
3129     Frame* mainFrame = [self _mainCoreFrame];
3130     if (!mainFrame)
3131         return nil;
3132
3133     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3134     size_t size = regions.size();
3135
3136     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3137     for (size_t i = 0; i < size; i++) {
3138         const AnnotatedRegionValue& region = regions[i];
3139
3140         if (region.type == StyleDashboardRegion::None)
3141             continue;
3142
3143         NSString *label = region.label;
3144         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3145         if (region.type == StyleDashboardRegion::Circle)
3146             type = WebDashboardRegionTypeCircle;
3147         else if (region.type == StyleDashboardRegion::Rectangle)
3148             type = WebDashboardRegionTypeRectangle;
3149         NSMutableArray *regionValues = [webRegions objectForKey:label];
3150         if (!regionValues) {
3151             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3152             [webRegions setObject:regionValues forKey:label];
3153             [regionValues release];
3154         }
3155
3156         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3157         [regionValues addObject:webRegion];
3158         [webRegion release];
3159     }
3160
3161     [self _addScrollerDashboardRegions:webRegions];
3162
3163     return webRegions;
3164 }
3165
3166 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3167 {
3168     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3169     // specific support for the backward compatibility mode flag.
3170     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3171         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3172     
3173     switch (behavior) {
3174         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3175             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3176             break;
3177         }
3178         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3179             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3180             break;
3181         }
3182         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3183             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3184             break;
3185         }
3186         case WebDashboardBehaviorAllowWheelScrolling: {
3187             _private->dashboardBehaviorAllowWheelScrolling = flag;
3188             break;
3189         }
3190         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3191             if (_private->page)
3192                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3193 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3194             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3195 #endif
3196             break;
3197         }
3198     }
3199
3200     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3201     // compatibility mode. See <rdar://problem/8175982>.
3202     if (_private->page)
3203         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3204 }
3205
3206 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3207 {
3208     switch (behavior) {
3209         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3210             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3211         }
3212         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3213             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3214         }
3215         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3216             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3217         }
3218         case WebDashboardBehaviorAllowWheelScrolling: {
3219             return _private->dashboardBehaviorAllowWheelScrolling;
3220         }
3221         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3222             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3223         }
3224     }
3225     return NO;
3226 }
3227
3228 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3229
3230 + (void)_setShouldUseFontSmoothing:(BOOL)f
3231 {
3232     FontCascade::setShouldUseSmoothing(f);
3233 }
3234
3235 + (BOOL)_shouldUseFontSmoothing
3236 {
3237     return FontCascade::shouldUseSmoothing();
3238 }
3239
3240 #if !PLATFORM(IOS)
3241 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3242 {
3243     setUsesTestModeFocusRingColor(f);
3244 }
3245
3246 + (BOOL)_usesTestModeFocusRingColor
3247 {
3248     return usesTestModeFocusRingColor();
3249 }
3250 #endif
3251
3252 #if PLATFORM(IOS)
3253 - (void)_setUIKitDelegate:(id)delegate
3254 {
3255     _private->UIKitDelegate = delegate;
3256     [_private->UIKitDelegateForwarder clearTarget];
3257     [_private->UIKitDelegateForwarder release];
3258     _private->UIKitDelegateForwarder = nil;
3259 }
3260
3261 - (id)_UIKitDelegate
3262 {
3263     return _private->UIKitDelegate;
3264 }
3265
3266 - (void)setWebMailDelegate:(id)delegate
3267 {
3268     _private->WebMailDelegate = delegate;
3269 }
3270
3271 - (id)_webMailDelegate
3272 {
3273     return _private->WebMailDelegate;
3274 }
3275
3276 - (id <WebCaretChangeListener>)caretChangeListener
3277 {
3278     return _private->_caretChangeListener;
3279 }
3280
3281 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3282 {
3283     _private->_caretChangeListener = listener;
3284 }
3285
3286 - (NSSet *)caretChangeListeners
3287 {
3288     return _private->_caretChangeListeners;
3289 }
3290
3291 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3292 {
3293     if (_private->_caretChangeListeners == nil) {
3294         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3295     }
3296     
3297     [_private->_caretChangeListeners addObject:listener];
3298 }
3299
3300 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3301 {
3302     [_private->_caretChangeListeners removeObject:listener];
3303 }
3304
3305 - (void)removeAllCaretChangeListeners
3306 {
3307     [_private->_caretChangeListeners removeAllObjects];
3308 }
3309
3310 - (void)caretChanged
3311 {
3312     [_private->_caretChangeListener caretChanged];
3313     NSSet *copy = [_private->_caretChangeListeners copy];
3314     for (id <WebCaretChangeListener> listener in copy) {
3315         [listener caretChanged];
3316     }
3317     [copy release];
3318 }
3319
3320 - (void)_clearDelegates
3321 {
3322     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3323     
3324     [self _setFormDelegate:nil];
3325     [self _setUIKitDelegate:nil];
3326     [self setCaretChangeListener:nil];
3327     [self removeAllCaretChangeListeners];
3328     [self setWebMailDelegate:nil];
3329     
3330     [self setDownloadDelegate:nil];
3331     [self setEditingDelegate:nil]; 
3332     [self setFrameLoadDelegate:nil];
3333     [self setPolicyDelegate:nil];
3334     [self setResourceLoadDelegate:nil];
3335     [self setScriptDebugDelegate:nil];
3336     [self setUIDelegate:nil];     
3337 }
3338
3339 - (NSURL *)_displayURL
3340 {
3341     WebThreadLock();
3342     WebFrame *frame = [self mainFrame];
3343     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3344     WebDataSource *dataSource = [frame provisionalDataSource];
3345     if (!dataSource)
3346         dataSource = [frame dataSource];
3347     NSURL *unreachableURL = [dataSource unreachableURL];
3348     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3349     [[URL retain] autorelease];
3350     return URL;
3351 }
3352 #endif // PLATFORM(IOS)
3353
3354 #if !PLATFORM(IOS)
3355 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3356 {
3357     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3358     if (flag) {
3359         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3360     } else {
3361         [scrollview setVerticalScrollingModeLocked:NO];
3362         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3363     }
3364 }
3365
3366 - (BOOL)alwaysShowVerticalScroller
3367 {
3368     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3369     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3370 }
3371
3372 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3373 {
3374     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3375     if (flag) {
3376         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3377     } else {
3378         [scrollview setHorizontalScrollingModeLocked:NO];
3379         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3380     }
3381 }
3382
3383 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3384 {
3385     if (Frame* mainFrame = [self _mainCoreFrame])
3386         mainFrame->view()->setProhibitsScrolling(prohibits);
3387 }
3388
3389 - (BOOL)alwaysShowHorizontalScroller
3390 {
3391     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3392     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3393 }
3394 #endif // !PLATFORM(IOS)
3395
3396 - (void)_setUseFastImageScalingMode:(BOOL)flag
3397 {
3398     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3399         _private->page->setInLowQualityImageInterpolationMode(flag);
3400         [self setNeedsDisplay:YES];
3401     }
3402 }
3403
3404 - (BOOL)_inFastImageScalingMode
3405 {
3406     if (_private->page)
3407         return _private->page->inLowQualityImageInterpolationMode();
3408     return NO;
3409 }
3410
3411 - (BOOL)_cookieEnabled
3412 {
3413     if (_private->page)
3414         return _private->page->settings().cookieEnabled();
3415     return YES;
3416 }
3417
3418 - (void)_setCookieEnabled:(BOOL)enable
3419 {
3420     if (_private->page)
3421         _private->page->settings().setCookieEnabled(enable);
3422 }
3423
3424 #if !PLATFORM(IOS)
3425 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3426 {
3427     if (!_private->pluginDatabase)
3428         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3429         
3430     [_private->pluginDatabase setPlugInPaths:newPaths];
3431     [_private->pluginDatabase refresh];
3432 }
3433 #endif
3434
3435 #if PLATFORM(IOS)
3436 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3437 {
3438     // Ask plug-ins in this frame
3439     id <WebDocumentView> documentView = [[frame frameView] documentView];
3440     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3441         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3442             return YES;
3443     }
3444
3445     // Ask plug-ins in child frames
3446     NSArray *childFrames = [frame childFrames];
3447     unsigned childCount = [childFrames count];
3448     unsigned childIndex;
3449     for (childIndex = 0; childIndex < childCount; childIndex++) {
3450         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3451             return YES;
3452     }
3453     
3454     return NO;
3455 }
3456
3457 - (BOOL)_pluginsAreRunning
3458 {
3459     WebThreadLock();
3460     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3461 }
3462
3463 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3464 {
3465     // Send the message to plug-ins in this frame
3466     id <WebDocumentView> documentView = [[frame frameView] documentView];
3467     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3468         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3469
3470     // Send the message to plug-ins in child frames
3471     NSArray *childFrames = [frame childFrames];
3472     unsigned childCount = [childFrames count];
3473     unsigned childIndex;
3474     for (childIndex = 0; childIndex < childCount; childIndex++) {
3475         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3476     }
3477 }
3478
3479 - (void)_destroyAllPlugIns
3480 {
3481     WebThreadLock();
3482     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3483 }
3484
3485 - (void)_clearBackForwardCache
3486 {
3487     WebThreadRun(^{
3488         WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3489         BackForwardList* bfList = core([self backForwardList]);
3490         if (!bfList)
3491             return;
3492
3493         BOOL didClearBFCache = bfList->clearAllPageCaches();
3494         if (WebKit::MemoryMeasure::isLoggingEnabled())
3495             NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3496     });
3497 }
3498
3499 - (void)_startAllPlugIns
3500 {
3501     WebThreadLock();
3502     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3503 }
3504
3505 - (void)_stopAllPlugIns
3506 {
3507     WebThreadLock();
3508     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3509 }
3510
3511 - (void)_stopAllPlugInsForPageCache
3512 {
3513     WebThreadLock();
3514     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3515 }
3516
3517 - (void)_restorePlugInsFromCache
3518 {
3519     WebThreadLock();
3520     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3521 }
3522
3523 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3524 {
3525     WebThreadLock();
3526
3527     Frame* mainCoreFrame = [self _mainCoreFrame];
3528     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3529         FrameView* coreView = frame ? frame->view() : 0;
3530         if (!coreView)
3531             continue;
3532
3533         // Get the GraphicsLayer for this widget.
3534         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3535         if (!layerForWidget)
3536             continue;
3537         
3538         if (layerForWidget->contentsLayerForMedia() != layer) {
3539             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3540             // We need to make sure the layer hierachy change is applied immediately.
3541             if (mainCoreFrame->view())
3542                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3543             return YES;
3544         }
3545     }
3546
3547     return NO;
3548 }
3549
3550 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3551 {
3552     if (_private->page)
3553         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3554 }
3555 #endif // PLATFORM(IOS)
3556
3557 - (void)_attachScriptDebuggerToAllFrames
3558 {
3559     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3560         [kit(frame) _attachScriptDebugger];
3561 }
3562
3563 - (void)_detachScriptDebuggerFromAllFrames
3564 {
3565     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3566         [kit(frame) _detachScriptDebugger];
3567 }
3568
3569 #if !PLATFORM(IOS)
3570 - (void)setBackgroundColor:(NSColor *)backgroundColor
3571 {
3572     if ([_private->backgroundColor isEqual:backgroundColor])
3573         return;
3574
3575     id old = _private->backgroundColor;
3576     _private->backgroundColor = [backgroundColor retain];
3577     [old release];
3578
3579     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3580 }
3581
3582 - (NSColor *)backgroundColor
3583 {
3584     return _private->backgroundColor;
3585 }
3586 #else
3587 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3588 {
3589    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3590         return;
3591
3592     CFTypeRef old = _private->backgroundColor;
3593     CFRetain(backgroundColor);
3594     _private->backgroundColor = backgroundColor;
3595     CFRelease(old);
3596
3597     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3598 }
3599
3600 - (CGColorRef)backgroundColor
3601 {
3602     return _private->backgroundColor;
3603 }
3604 #endif
3605
3606 - (BOOL)defersCallbacks
3607 {
3608     if (!_private->page)
3609         return NO;
3610     return _private->page->defersLoading();
3611 }
3612
3613 - (void)setDefersCallbacks:(BOOL)defer