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