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