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