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