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