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