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