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