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