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