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