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