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