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