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