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