43487d86c2f364f353dce63188637a6def560292
[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 "WebDownloadInternal.h"
62 #import "WebDragClient.h"
63 #import "WebDynamicScrollBarsViewInternal.h"
64 #import "WebEditingDelegate.h"
65 #import "WebEditorClient.h"
66 #import "WebFormDelegatePrivate.h"
67 #import "WebFrameInternal.h"
68 #import "WebFrameLoaderClient.h"
69 #import "WebFrameNetworkingContext.h"
70 #import "WebFrameViewInternal.h"
71 #import "WebGeolocationClient.h"
72 #import "WebGeolocationPositionInternal.h"
73 #import "WebHTMLRepresentation.h"
74 #import "WebHTMLViewInternal.h"
75 #import "WebHistoryItemInternal.h"
76 #import "WebIconDatabase.h"
77 #import "WebInspector.h"
78 #import "WebInspectorClient.h"
79 #import "WebKitErrors.h"
80 #import "WebKitFullScreenListener.h"
81 #import "WebKitLogging.h"
82 #import "WebKitNSStringExtras.h"
83 #import "WebKitStatisticsPrivate.h"
84 #import "WebKitVersionChecks.h"
85 #import "WebLocalizableStrings.h"
86 #import "WebNSDataExtras.h"
87 #import "WebNSDataExtrasPrivate.h"
88 #import "WebNSDictionaryExtras.h"
89 #import "WebNSURLExtras.h"
90 #import "WebNSURLRequestExtras.h"
91 #import "WebNSViewExtras.h"
92 #import "WebNodeHighlight.h"
93 #import "WebNotificationClient.h"
94 #import "WebPDFView.h"
95 #import "WebPaymentCoordinatorClient.h"
96 #import "WebPlatformStrategies.h"
97 #import "WebPluginDatabase.h"
98 #import "WebPluginInfoProvider.h"
99 #import "WebPolicyDelegate.h"
100 #import "WebPreferenceKeysPrivate.h"
101 #import "WebPreferencesPrivate.h"
102 #import "WebProgressTrackerClient.h"
103 #import "WebResourceLoadScheduler.h"
104 #import "WebScriptDebugDelegate.h"
105 #import "WebScriptWorldInternal.h"
106 #import "WebSelectionServiceController.h"
107 #import "WebStorageManagerInternal.h"
108 #import "WebStorageNamespaceProvider.h"
109 #import "WebTextCompletionController.h"
110 #import "WebTextIterator.h"
111 #import "WebUIDelegate.h"
112 #import "WebUIDelegatePrivate.h"
113 #import "WebUserMediaClient.h"
114 #import "WebValidationMessageClient.h"
115 #import "WebViewGroup.h"
116 #import "WebVisitedLinkStore.h"
117 #import <CoreFoundation/CFSet.h>
118 #import <Foundation/NSURLConnection.h>
119 #import <JavaScriptCore/APICast.h>
120 #import <JavaScriptCore/ArrayPrototype.h>
121 #import <JavaScriptCore/CatchScope.h>
122 #import <JavaScriptCore/DateInstance.h>
123 #import <JavaScriptCore/Exception.h>
124 #import <JavaScriptCore/InitializeThreading.h>
125 #import <JavaScriptCore/JSCJSValue.h>
126 #import <JavaScriptCore/JSLock.h>
127 #import <JavaScriptCore/JSValueRef.h>
128 #import <WebCore/AlternativeTextUIController.h>
129 #import <WebCore/ApplicationCacheStorage.h>
130 #import <WebCore/BackForwardController.h>
131 #import <WebCore/CSSAnimationController.h>
132 #import <WebCore/CacheStorageProvider.h>
133 #import <WebCore/Chrome.h>
134 #import <WebCore/ColorMac.h>
135 #import <WebCore/DatabaseManager.h>
136 #import <WebCore/DeprecatedGlobalSettings.h>
137 #import <WebCore/DictionaryLookup.h>
138 #import <WebCore/Document.h>
139 #import <WebCore/DocumentLoader.h>
140 #import <WebCore/DragController.h>
141 #import <WebCore/DragData.h>
142 #import <WebCore/DragItem.h>
143 #import <WebCore/Editing.h>
144 #import <WebCore/Editor.h>
145 #import <WebCore/Event.h>
146 #import <WebCore/EventHandler.h>
147 #import <WebCore/FileSystem.h>
148 #import <WebCore/FocusController.h>
149 #import <WebCore/FontCache.h>
150 #import <WebCore/Frame.h>
151 #import <WebCore/FrameLoader.h>
152 #import <WebCore/FrameSelection.h>
153 #import <WebCore/FrameTree.h>
154 #import <WebCore/FrameView.h>
155 #import <WebCore/GCController.h>
156 #import <WebCore/GameControllerGamepadProvider.h>
157 #import <WebCore/GeolocationController.h>
158 #import <WebCore/GeolocationError.h>
159 #import <WebCore/HTMLNames.h>
160 #import <WebCore/HTMLOListElement.h>
161 #import <WebCore/HTMLUListElement.h>
162 #import <WebCore/HTMLVideoElement.h>
163 #import <WebCore/HistoryController.h>
164 #import <WebCore/HistoryItem.h>
165 #import <WebCore/JSCSSStyleDeclaration.h>
166 #import <WebCore/JSDocument.h>
167 #import <WebCore/JSElement.h>
168 #import <WebCore/JSNodeList.h>
169 #import <WebCore/JSNotification.h>
170 #import <WebCore/LegacyNSPasteboardTypes.h>
171 #import <WebCore/LibWebRTCProvider.h>
172 #import <WebCore/LocalizedStrings.h>
173 #import <WebCore/LogInitialization.h>
174 #import <WebCore/MIMETypeRegistry.h>
175 #import <WebCore/MemoryCache.h>
176 #import <WebCore/MemoryRelease.h>
177 #import <WebCore/NavigationPolicyCheck.h>
178 #import <WebCore/NetworkStorageSession.h>
179 #import <WebCore/NodeList.h>
180 #import <WebCore/Notification.h>
181 #import <WebCore/NotificationController.h>
182 #import <WebCore/Page.h>
183 #import <WebCore/PageCache.h>
184 #import <WebCore/PageConfiguration.h>
185 #import <WebCore/PageGroup.h>
186 #import <WebCore/PathUtilities.h>
187 #import <WebCore/PlatformEventFactoryMac.h>
188 #import <WebCore/ProgressTracker.h>
189 #import <WebCore/RenderTheme.h>
190 #import <WebCore/RenderView.h>
191 #import <WebCore/RenderWidget.h>
192 #import <WebCore/ResourceHandle.h>
193 #import <WebCore/ResourceLoadObserver.h>
194 #import <WebCore/ResourceRequest.h>
195 #import <WebCore/RuntimeApplicationChecks.h>
196 #import <WebCore/RuntimeEnabledFeatures.h>
197 #import <WebCore/SchemeRegistry.h>
198 #import <WebCore/ScriptController.h>
199 #import <WebCore/SecurityOrigin.h>
200 #import <WebCore/SecurityPolicy.h>
201 #import <WebCore/Settings.h>
202 #import <WebCore/SocketProvider.h>
203 #import <WebCore/StyleProperties.h>
204 #import <WebCore/TextResourceDecoder.h>
205 #import <WebCore/ThreadCheck.h>
206 #import <WebCore/UserAgent.h>
207 #import <WebCore/UserContentController.h>
208 #import <WebCore/UserGestureIndicator.h>
209 #import <WebCore/UserScript.h>
210 #import <WebCore/UserStyleSheet.h>
211 #import <WebCore/ValidationBubble.h>
212 #import <WebCore/WebCoreObjCExtras.h>
213 #import <WebCore/WebCoreView.h>
214 #import <WebCore/Widget.h>
215 #import <WebKitLegacy/DOM.h>
216 #import <WebKitLegacy/DOMExtensions.h>
217 #import <WebKitLegacy/DOMPrivate.h>
218 #import <mach-o/dyld.h>
219 #import <objc/runtime.h>
220 #import <pal/spi/cf/CFNetworkSPI.h>
221 #import <pal/spi/cf/CFUtilitiesSPI.h>
222 #import <pal/spi/cocoa/NSTouchBarSPI.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 "WebVideoFullscreenController.h"
252 #import <WebCore/TextIndicator.h>
253 #import <WebCore/TextIndicatorWindow.h>
254 #import <pal/spi/cocoa/AVKitSPI.h>
255 #import <pal/spi/mac/LookupSPI.h>
256 #import <pal/spi/mac/NSImmediateActionGestureRecognizerSPI.h>
257 #else
258 #import "MemoryMeasure.h"
259 #import "WebCaretChangeListener.h"
260 #import "WebChromeClientIOS.h"
261 #import "WebDefaultFormDelegate.h"
262 #import "WebDefaultFrameLoadDelegate.h"
263 #import "WebDefaultResourceLoadDelegate.h"
264 #import "WebDefaultUIKitDelegate.h"
265 #import "WebFixedPositionContent.h"
266 #import "WebMailDelegate.h"
267 #import "WebNSUserDefaultsExtras.h"
268 #import "WebPDFViewIOS.h"
269 #import "WebPlainWhiteView.h"
270 #import "WebPluginController.h"
271 #import "WebPolicyDelegatePrivate.h"
272 #import "WebStorageManagerPrivate.h"
273 #import "WebUIKitSupport.h"
274 #import "WebVisiblePosition.h"
275 #import <WebCore/EventNames.h>
276 #import <WebCore/FontCache.h>
277 #import <WebCore/GraphicsLayer.h>
278 #import <WebCore/LegacyTileCache.h>
279 #import <WebCore/PlatformScreen.h>
280 #import <WebCore/ResourceLoadStatistics.h>
281 #import <WebCore/SQLiteDatabaseTracker.h>
282 #import <WebCore/SmartReplace.h>
283 #import <WebCore/TileControllerMemoryHandlerIOS.h>
284 #import <WebCore/WAKWindow.h>
285 #import <WebCore/WKView.h>
286 #import <WebCore/WebCoreThread.h>
287 #import <WebCore/WebCoreThreadMessage.h>
288 #import <WebCore/WebCoreThreadRun.h>
289 #import <WebCore/WebEvent.h>
290 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
291 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
292 #import <libkern/OSAtomic.h>
293 #import <pal/spi/ios/MobileGestaltSPI.h>
294 #import <wtf/FastMalloc.h>
295 #endif
296
297 #if ENABLE(DASHBOARD_SUPPORT)
298 #import <WebKitLegacy/WebDashboardRegion.h>
299 #endif
300
301 #if ENABLE(REMOTE_INSPECTOR)
302 #import <JavaScriptCore/RemoteInspector.h>
303 #if PLATFORM(IOS)
304 #import "WebIndicateLayer.h"
305 #endif
306 #endif
307
308 #if USE(QUICK_LOOK)
309 #include <WebCore/QuickLook.h>
310 #endif
311
312 #if ENABLE(IOS_TOUCH_EVENTS)
313 #import <WebCore/WebEventRegion.h>
314 #endif
315
316 #if ENABLE(GAMEPAD)
317 #import <WebCore/HIDGamepadProvider.h>
318 #endif
319
320 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
321 #import "WebMediaPlaybackTargetPicker.h"
322 #import <WebCore/WebMediaSessionManagerMac.h>
323 #endif
324
325
326 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
327 #import <WebCore/PlaybackSessionInterfaceMac.h>
328 #import <WebCore/PlaybackSessionModelMediaElement.h>
329 #endif
330
331 #if ENABLE(DATA_INTERACTION)
332 #import <UIKit/UIBezierPath.h>
333 #import <UIKit/UIColor.h>
334 #import <UIKit/UIImage.h>
335 SOFT_LINK_FRAMEWORK(UIKit)
336 SOFT_LINK_CLASS(UIKit, UIBezierPath)
337 SOFT_LINK_CLASS(UIKit, UIColor)
338 SOFT_LINK_CLASS(UIKit, UIImage)
339 SOFT_LINK(UIKit, UIGraphicsBeginImageContextWithOptions, void, (CGSize size, BOOL opaque, CGFloat scale), (size, opaque, scale))
340 SOFT_LINK(UIKit, UIGraphicsGetCurrentContext, CGContextRef, (void), ())
341 SOFT_LINK(UIKit, UIGraphicsGetImageFromCurrentImageContext, UIImage *, (void), ())
342 SOFT_LINK(UIKit, UIGraphicsEndImageContext, void, (void), ())
343 #endif
344
345 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
346 SOFT_LINK_FRAMEWORK(AVKit)
347 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
348 SOFT_LINK_CLASS(AVKit, AVTouchBarPlaybackControlsProvider)
349 SOFT_LINK_CLASS(AVKit, AVTouchBarScrubber)
350 #else
351 SOFT_LINK_CLASS(AVKit, AVFunctionBarPlaybackControlsProvider)
352 SOFT_LINK_CLASS(AVKit, AVFunctionBarScrubber)
353 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
354 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
355
356 #if PLATFORM(MAC)
357 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
358 #endif
359
360 #if !PLATFORM(IOS)
361
362 @interface NSSpellChecker (WebNSSpellCheckerDetails)
363 - (void)_preflightChosenSpellServer;
364 @end
365
366 @interface NSView (WebNSViewDetails)
367 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
368 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
369 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
370 - (void)_windowChangedKeyState;
371 @end
372
373 @interface NSWindow (WebNSWindowDetails)
374 - (id)_oldFirstResponderBeforeBecoming;
375 - (void)_enableScreenUpdatesIfNeeded;
376 - (BOOL)_wrapsCarbonWindow;
377 - (BOOL)_hasKeyAppearance;
378 @end
379
380 #endif
381
382 using namespace JSC;
383 using namespace Inspector;
384 using namespace WebCore;
385
386 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
387 macro(alignCenter) \
388 macro(alignJustified) \
389 macro(alignLeft) \
390 macro(alignRight) \
391 macro(capitalizeWord) \
392 macro(centerSelectionInVisibleArea) \
393 macro(changeAttributes) \
394 macro(changeBaseWritingDirection) \
395 macro(changeBaseWritingDirectionToLTR) \
396 macro(changeBaseWritingDirectionToRTL) \
397 macro(changeColor) \
398 macro(changeDocumentBackgroundColor) \
399 macro(changeFont) \
400 macro(changeSpelling) \
401 macro(checkSpelling) \
402 macro(complete) \
403 macro(copy) \
404 macro(copyFont) \
405 macro(cut) \
406 macro(delete) \
407 macro(deleteBackward) \
408 macro(deleteBackwardByDecomposingPreviousCharacter) \
409 macro(deleteForward) \
410 macro(deleteToBeginningOfLine) \
411 macro(deleteToBeginningOfParagraph) \
412 macro(deleteToEndOfLine) \
413 macro(deleteToEndOfParagraph) \
414 macro(deleteToMark) \
415 macro(deleteWordBackward) \
416 macro(deleteWordForward) \
417 macro(ignoreSpelling) \
418 macro(indent) \
419 macro(insertBacktab) \
420 macro(insertLineBreak) \
421 macro(insertNewline) \
422 macro(insertNewlineIgnoringFieldEditor) \
423 macro(insertParagraphSeparator) \
424 macro(insertTab) \
425 macro(insertTabIgnoringFieldEditor) \
426 macro(lowercaseWord) \
427 macro(makeBaseWritingDirectionLeftToRight) \
428 macro(makeBaseWritingDirectionRightToLeft) \
429 macro(makeTextWritingDirectionLeftToRight) \
430 macro(makeTextWritingDirectionNatural) \
431 macro(makeTextWritingDirectionRightToLeft) \
432 macro(moveBackward) \
433 macro(moveBackwardAndModifySelection) \
434 macro(moveDown) \
435 macro(moveDownAndModifySelection) \
436 macro(moveForward) \
437 macro(moveForwardAndModifySelection) \
438 macro(moveLeft) \
439 macro(moveLeftAndModifySelection) \
440 macro(moveParagraphBackwardAndModifySelection) \
441 macro(moveParagraphForwardAndModifySelection) \
442 macro(moveRight) \
443 macro(moveRightAndModifySelection) \
444 macro(moveToBeginningOfDocument) \
445 macro(moveToBeginningOfDocumentAndModifySelection) \
446 macro(moveToBeginningOfLine) \
447 macro(moveToBeginningOfLineAndModifySelection) \
448 macro(moveToBeginningOfParagraph) \
449 macro(moveToBeginningOfParagraphAndModifySelection) \
450 macro(moveToBeginningOfSentence) \
451 macro(moveToBeginningOfSentenceAndModifySelection) \
452 macro(moveToEndOfDocument) \
453 macro(moveToEndOfDocumentAndModifySelection) \
454 macro(moveToEndOfLine) \
455 macro(moveToEndOfLineAndModifySelection) \
456 macro(moveToEndOfParagraph) \
457 macro(moveToEndOfParagraphAndModifySelection) \
458 macro(moveToEndOfSentence) \
459 macro(moveToEndOfSentenceAndModifySelection) \
460 macro(moveToLeftEndOfLine) \
461 macro(moveToLeftEndOfLineAndModifySelection) \
462 macro(moveToRightEndOfLine) \
463 macro(moveToRightEndOfLineAndModifySelection) \
464 macro(moveUp) \
465 macro(moveUpAndModifySelection) \
466 macro(moveWordBackward) \
467 macro(moveWordBackwardAndModifySelection) \
468 macro(moveWordForward) \
469 macro(moveWordForwardAndModifySelection) \
470 macro(moveWordLeft) \
471 macro(moveWordLeftAndModifySelection) \
472 macro(moveWordRight) \
473 macro(moveWordRightAndModifySelection) \
474 macro(orderFrontSubstitutionsPanel) \
475 macro(outdent) \
476 macro(overWrite) \
477 macro(pageDown) \
478 macro(pageDownAndModifySelection) \
479 macro(pageUp) \
480 macro(pageUpAndModifySelection) \
481 macro(paste) \
482 macro(pasteAsPlainText) \
483 macro(pasteAsRichText) \
484 macro(pasteFont) \
485 macro(performFindPanelAction) \
486 macro(scrollLineDown) \
487 macro(scrollLineUp) \
488 macro(scrollPageDown) \
489 macro(scrollPageUp) \
490 macro(scrollToBeginningOfDocument) \
491 macro(scrollToEndOfDocument) \
492 macro(selectAll) \
493 macro(selectLine) \
494 macro(selectParagraph) \
495 macro(selectSentence) \
496 macro(selectToMark) \
497 macro(selectWord) \
498 macro(setMark) \
499 macro(showGuessPanel) \
500 macro(startSpeaking) \
501 macro(stopSpeaking) \
502 macro(subscript) \
503 macro(superscript) \
504 macro(swapWithMark) \
505 macro(takeFindStringFromSelection) \
506 macro(toggleBaseWritingDirection) \
507 macro(transpose) \
508 macro(underline) \
509 macro(unscript) \
510 macro(uppercaseWord) \
511 macro(yank) \
512 macro(yankAndSelect) \
513
514 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
515 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
516
517 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
518 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
519
520 static BOOL s_didSetCacheModel;
521 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
522
523 #if PLATFORM(IOS)
524 static Class s_pdfRepresentationClass;
525 static Class s_pdfViewClass;
526 #endif
527
528 #ifndef NDEBUG
529 static const char webViewIsOpen[] = "At least one WebView is still open.";
530 #endif
531
532 #if PLATFORM(IOS)
533 @interface WebView(WebViewPrivate)
534 - (void)_preferencesChanged:(WebPreferences *)preferences;
535 - (void)_updateScreenScaleFromWindow;
536 @end
537 #endif
538
539 #if !PLATFORM(IOS)
540 @interface NSObject (WebValidateWithoutDelegate)
541 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
542 @end
543 #endif
544
545 #if PLATFORM(IOS)
546 @class _WebSafeForwarder;
547
548 @interface _WebSafeAsyncForwarder : NSObject {
549     _WebSafeForwarder *_forwarder;
550 }
551 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
552 @end
553 #endif
554
555 @interface _WebSafeForwarder : NSObject
556 {
557     id target; // Non-retained. Don't retain delegates.
558     id defaultTarget;
559 #if PLATFORM(IOS)
560     _WebSafeAsyncForwarder *asyncForwarder;
561     dispatch_once_t asyncForwarderPred;
562 #endif
563 }
564 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
565 #if PLATFORM(IOS)
566 - (void)clearTarget;
567 - (id)asyncForwarder;
568 #endif
569 @end
570
571 FindOptions coreOptions(WebFindOptions options)
572 {
573     FindOptions findOptions;
574     if (options & WebFindOptionsCaseInsensitive)
575         findOptions |= CaseInsensitive;
576     if (options & WebFindOptionsAtWordStarts)
577         findOptions |= AtWordStarts;
578     if (options & WebFindOptionsTreatMedialCapitalAsWordStart)
579         findOptions |= TreatMedialCapitalAsWordStart;
580     if (options & WebFindOptionsBackwards)
581         findOptions |= Backwards;
582     if (options & WebFindOptionsWrapAround)
583         findOptions |= WrapAround;
584     if (options & WebFindOptionsStartInSelection)
585         findOptions |= StartInSelection;
586     return findOptions;
587 }
588
589 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
590 {
591     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
592         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
593         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
594 }
595
596 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
597 {
598     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
599         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
600         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
601 }
602
603 static WebPageVisibilityState kit(VisibilityState visibilityState)
604 {
605     switch (visibilityState) {
606     case VisibilityState::Visible:
607         return WebPageVisibilityStateVisible;
608     case VisibilityState::Hidden:
609         return WebPageVisibilityStateHidden;
610     case VisibilityState::Prerender:
611         return WebPageVisibilityStatePrerender;
612     }
613
614     ASSERT_NOT_REACHED();
615     return WebPageVisibilityStateVisible;
616 }
617
618 namespace WebKit {
619
620 class DeferredPageDestructor {
621 public:
622     static void createDeferredPageDestructor(std::unique_ptr<Page> page)
623     {
624         new DeferredPageDestructor(WTFMove(page));
625     }
626
627 private:
628     DeferredPageDestructor(std::unique_ptr<Page> page)
629         : m_page(WTFMove(page))
630     {
631         tryDestruction();
632     }
633
634     void tryDestruction()
635     {
636         if (m_page->insideNestedRunLoop()) {
637             m_page->whenUnnested([this] { tryDestruction(); });
638             return;
639         }
640
641         m_page = nullptr;
642         delete this;
643     }
644
645     std::unique_ptr<Page> m_page;
646 };
647
648 } // namespace WebKit
649
650 #if ENABLE(DATA_INTERACTION)
651
652 @implementation WebUITextIndicatorData
653
654 @synthesize dataInteractionImage=_dataInteractionImage;
655 @synthesize selectionRectInRootViewCoordinates=_selectionRectInRootViewCoordinates;
656 @synthesize textBoundingRectInRootViewCoordinates=_textBoundingRectInRootViewCoordinates;
657 @synthesize textRectsInBoundingRectCoordinates=_textRectsInBoundingRectCoordinates;
658 @synthesize contentImageWithHighlight=_contentImageWithHighlight;
659 @synthesize contentImageWithoutSelection=_contentImageWithoutSelection;
660 @synthesize contentImageWithoutSelectionRectInRootViewCoordinates=_contentImageWithoutSelectionRectInRootViewCoordinates;
661 @synthesize contentImage=_contentImage;
662 @synthesize estimatedBackgroundColor=_estimatedBackgroundColor;
663
664 @end
665
666 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
667
668 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(const TextIndicatorData&)indicatorData scale:(CGFloat)scale
669 {
670     if (!(self = [super init]))
671         return nil;
672     
673     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
674     _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
675     _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
676     
677     NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
678     for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
679         [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
680     _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
681     _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
682     if (indicatorData.contentImageWithHighlight)
683         _contentImageWithHighlight = [allocUIImageInstance() initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored];
684     if (indicatorData.contentImage)
685         _contentImage = [allocUIImageInstance() initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationUp];
686
687     if (indicatorData.contentImageWithoutSelection) {
688         auto nativeImage = indicatorData.contentImageWithoutSelection.get()->nativeImage();
689         if (nativeImage) {
690             _contentImageWithoutSelection = [allocUIImageInstance() initWithCGImage:nativeImage.get() scale:scale orientation:UIImageOrientationUp];
691             _contentImageWithoutSelectionRectInRootViewCoordinates = indicatorData.contentImageWithoutSelectionRectInRootViewCoordinates;
692         }
693     }
694
695     if (indicatorData.options & TextIndicatorOptionComputeEstimatedBackgroundColor)
696         _estimatedBackgroundColor = [allocUIColorInstance() initWithCGColor:cachedCGColor(indicatorData.estimatedBackgroundColor)];
697
698     return self;
699 }
700
701 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
702 {
703     if (!(self = [super init]))
704         return nil;
705     
706     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
707     
708     return self;
709 }
710
711 - (void)dealloc
712 {
713     [_dataInteractionImage release];
714     [_textRectsInBoundingRectCoordinates release];
715     [_contentImageWithHighlight release];
716     [_contentImageWithoutSelection release];
717     [_contentImage release];
718     [_estimatedBackgroundColor release];
719     
720     [super dealloc];
721 }
722
723 @end
724 #elif !PLATFORM(MAC)
725 @implementation WebUITextIndicatorData
726 @end
727 #endif // ENABLE(DATA_INTERACTION)
728
729 @interface WebView (WebFileInternal)
730 #if !PLATFORM(IOS)
731 - (float)_deviceScaleFactor;
732 #endif
733 - (BOOL)_isLoading;
734 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
735 - (WebFrame *)_focusedFrame;
736 + (void)_preflightSpellChecker;
737 - (BOOL)_continuousCheckingAllowed;
738 - (NSResponder *)_responderForResponderOperations;
739 @end
740
741 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
742 NSString *WebElementFrameKey =              @"WebElementFrame";
743 NSString *WebElementImageKey =              @"WebElementImage";
744 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
745 NSString *WebElementImageRectKey =          @"WebElementImageRect";
746 NSString *WebElementImageURLKey =           @"WebElementImageURL";
747 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
748 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
749 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
750 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
751 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
752 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
753 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
754 NSString *WebElementTitleKey =              @"WebElementTitle";
755 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
756 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
757 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
758
759 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
760 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
761 #if !PLATFORM(IOS)
762 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
763 #else
764 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
765 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
766 #endif
767
768 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
769 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
770 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
771 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
772 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
773
774 enum { WebViewVersion = 4 };
775
776 #define timedLayoutSize 4096
777
778 static NSMutableSet *schemesWithRepresentationsSet;
779
780 #if !PLATFORM(IOS)
781 NSString *_WebCanGoBackKey =            @"canGoBack";
782 NSString *_WebCanGoForwardKey =         @"canGoForward";
783 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
784 NSString *_WebIsLoadingKey =            @"isLoading";
785 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
786 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
787 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
788 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
789 #endif
790
791 #if PLATFORM(IOS)
792 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
793 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
794 #endif
795
796 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
797 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
798
799 #if ENABLE(REMOTE_INSPECTOR)
800 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
801 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
802 #endif
803
804 @interface WebProgressItem : NSObject
805 {
806 @public
807     long long bytesReceived;
808     long long estimatedLength;
809 }
810 @end
811
812 @implementation WebProgressItem
813 @end
814
815 static BOOL continuousSpellCheckingEnabled;
816 static BOOL iconLoadingEnabled = YES;
817 #if !PLATFORM(IOS)
818 static BOOL grammarCheckingEnabled;
819 static BOOL automaticQuoteSubstitutionEnabled;
820 static BOOL automaticLinkDetectionEnabled;
821 static BOOL automaticDashSubstitutionEnabled;
822 static BOOL automaticTextReplacementEnabled;
823 static BOOL automaticSpellingCorrectionEnabled;
824 #endif
825
826 #if HAVE(TOUCH_BAR)
827
828 enum class WebListType {
829     None = 0,
830     Ordered,
831     Unordered
832 };
833
834 @interface WebTextListTouchBarViewController : NSViewController {
835 @private
836     WebListType _currentListType;
837     WebView *_webView;
838 }
839
840 @property (nonatomic) WebListType currentListType;
841
842 - (instancetype)initWithWebView:(WebView *)webView;
843
844 @end
845
846 @implementation WebTextListTouchBarViewController
847
848 @synthesize currentListType=_currentListType;
849
850 static const CGFloat listControlSegmentWidth = 67.0;
851
852 static const NSUInteger noListSegment = 0;
853 static const NSUInteger unorderedListSegment = 1;
854 static const NSUInteger orderedListSegment = 2;
855
856 - (instancetype)initWithWebView:(WebView *)webView
857 {
858     if (!(self = [super init]))
859         return nil;
860
861     _webView = webView;
862
863     NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
864     [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
865     [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
866     [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
867     insertListControl.font = [NSFont systemFontOfSize:15];
868
869 #pragma clang diagnostic push
870 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
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 #pragma clang diagnostic pop
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     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1119 }
1120
1121 - (void)_removeFromAllWebViewsSet
1122 {
1123     if (allWebViewsSet)
1124         CFSetRemoveValue(allWebViewsSet, self);
1125 }
1126
1127 - (void)_addToAllWebViewsSet
1128 {
1129     if (!allWebViewsSet)
1130         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1131
1132     CFSetSetValue(allWebViewsSet, 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         
1411         DeprecatedGlobalSettings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1412
1413 #if PLATFORM(IOS)
1414         if (IOSApplication::isMobileSafari())
1415             DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
1416 #endif
1417
1418         didOneTimeInitialization = true;
1419     }
1420
1421     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1422     _private->group->addWebView(self);
1423
1424     PageConfiguration pageConfiguration(
1425         makeUniqueRef<WebEditorClient>(self),
1426         SocketProvider::create(),
1427         LibWebRTCProvider::create(),
1428         WebCore::CacheStorageProvider::create()
1429     );
1430 #if !PLATFORM(IOS)
1431     pageConfiguration.chromeClient = new WebChromeClient(self);
1432     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1433     // FIXME: We should enable this on iOS as well.
1434     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1435     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1436 #else
1437     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1438     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1439 #endif
1440
1441 #if ENABLE(DRAG_SUPPORT)
1442     pageConfiguration.dragClient = new WebDragClient(self);
1443 #endif
1444
1445     pageConfiguration.backForwardClient = BackForwardList::create(self);
1446
1447 #if ENABLE(APPLE_PAY)
1448     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1449 #endif
1450
1451     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1452     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1453     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1454     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1455     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1456     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1457     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1458     pageConfiguration.userContentProvider = &_private->group->userContentController();
1459     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1460     _private->page = new Page(WTFMove(pageConfiguration));
1461
1462     _private->page->setGroupName(groupName);
1463
1464 #if ENABLE(GEOLOCATION)
1465     WebCore::provideGeolocationTo(_private->page, *new WebGeolocationClient(self));
1466 #endif
1467 #if ENABLE(NOTIFICATIONS)
1468     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1469 #endif
1470 #if ENABLE(DEVICE_ORIENTATION)
1471 #if !PLATFORM(IOS)
1472     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1473 #endif
1474 #endif
1475 #if ENABLE(MEDIA_STREAM)
1476     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1477 #endif
1478
1479 #if ENABLE(REMOTE_INSPECTOR)
1480     _private->page->setRemoteInspectionAllowed(true);
1481 #endif
1482
1483     _private->page->setCanStartMedia([self window]);
1484     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1485     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1486
1487 #if !PLATFORM(IOS)
1488     if (needsOutlookQuirksScript()) {
1489         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1490         [self _injectOutlookQuirksScript];
1491     }
1492 #endif
1493
1494 #if PLATFORM(IOS)
1495     _private->page->settings().setPassiveTouchListenersAsDefaultOnDocument(linkedOnOrAfter(SDKVersion::FirstThatDefaultsToPassiveTouchListenersOnDocument));
1496 #endif
1497
1498 #if PLATFORM(IOS)
1499     // Preserve the behavior we had before <rdar://problem/7580867>
1500     // by enforcing a 5MB limit for session storage.
1501     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1502
1503     [self _updateScreenScaleFromWindow];
1504     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1505     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1506     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1507 #if ENABLE(ORIENTATION_EVENTS)
1508     _private->deviceOrientation = [[self _UIKitDelegateForwarder] deviceOrientation];
1509 #endif
1510 #endif
1511
1512     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1513         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1514
1515     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1516
1517 #if PLATFORM(IOS)
1518     NSRunLoop *runLoop = WebThreadNSRunLoop();
1519 #else
1520     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1521 #endif
1522
1523     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1524         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1525     else
1526         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1527
1528     [self _addToAllWebViewsSet];
1529     
1530     // If there's already a next key view (e.g., from a nib), wire it up to our
1531     // contained frame view. In any case, wire our next key view up to the our
1532     // contained frame view. This works together with our becomeFirstResponder 
1533     // and setNextKeyView overrides.
1534     NSView *nextKeyView = [self nextKeyView];
1535     if (nextKeyView && nextKeyView != frameView)
1536         [frameView setNextKeyView:nextKeyView];
1537     [super setNextKeyView:frameView];
1538
1539     if ([[self class] shouldIncludeInWebKitStatistics])
1540         ++WebViewCount;
1541
1542 #if !PLATFORM(IOS)
1543     [self _registerDraggedTypes];
1544     [self _updateDefaultAppearance];
1545 #endif
1546
1547     [self _setIsVisible:[self _isViewVisible]];
1548
1549     WebPreferences *prefs = [self preferences];
1550     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1551                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1552
1553 #if !PLATFORM(IOS)
1554     [self _preferencesChanged:[self preferences]];
1555     [[self preferences] _postPreferencesChangedAPINotification];
1556 #else
1557     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1558     // and prefs need to be changed synchronously <rdar://problem/5841558>
1559     [self _preferencesChanged:prefs];
1560     _private->page->settings().setFontFallbackPrefersPictographs(true);
1561 #endif
1562
1563     WebInstallMemoryPressureHandler();
1564
1565 #if !PLATFORM(IOS)
1566     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1567         // Originally, we allowed all local loads.
1568         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1569     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1570         // Later, we allowed local loads for local URLs and documents loaded
1571         // with substitute data.
1572         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1573     }
1574 #endif
1575
1576 #if PLATFORM(MAC)
1577     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1578         ResourceHandle::forceContentSniffing();
1579
1580     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1581     _private->page->setDefaultAppearance([self _defaultAppearance]);
1582 #endif
1583
1584     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1585 }
1586
1587 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1588 {
1589     self = [super initWithFrame:f];
1590     if (!self)
1591         return nil;
1592
1593 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1594     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1595     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1596     // need for Safari to unset it to prevent it from being passed to applications it launches.
1597     // Unsetting it when a WebView is first created is as good a place as any.
1598     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1599     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1600         unsetenv("DYLD_FRAMEWORK_PATH");
1601         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1602     }
1603 #endif
1604
1605     _private = [[WebViewPrivate alloc] init];
1606     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1607     [self setMaintainsBackForwardList: YES];
1608     return self;
1609 }
1610
1611 - (void)_viewWillDrawInternal
1612 {
1613     Frame* frame = [self _mainCoreFrame];
1614     if (frame && frame->view())
1615         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1616 }
1617
1618 + (NSArray *)_supportedMIMETypes
1619 {
1620     // Load the plug-in DB allowing plug-ins to install types.
1621     [WebPluginDatabase sharedDatabase];
1622     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1623 }
1624
1625 #if !PLATFORM(IOS)
1626 + (NSArray *)_supportedFileExtensions
1627 {
1628     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1629     NSArray *MIMETypes = [self _supportedMIMETypes];
1630     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1631     NSString *MIMEType;
1632     while ((MIMEType = [enumerator nextObject]) != nil) {
1633         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1634         if (extensionsForType) {
1635             [extensions addObjectsFromArray:extensionsForType];
1636         }
1637     }
1638     NSArray *uniqueExtensions = [extensions allObjects];
1639     [extensions release];
1640     return uniqueExtensions;
1641 }
1642 #endif
1643
1644 #if PLATFORM(IOS)
1645 + (void)enableWebThread
1646 {
1647     static BOOL isWebThreadEnabled = NO;
1648     if (!isWebThreadEnabled) {
1649         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1650         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1651         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1652         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1653         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1654         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1655         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1656         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1657         WebCoreObjCDeallocOnWebThread([WebView class]);
1658         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1659         WebThreadEnable();
1660         isWebThreadEnabled = YES;
1661     }
1662 }
1663
1664 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1665 {
1666     self = [super initWithFrame:frame];
1667     if (!self)
1668         return nil;
1669     
1670     _private = [[WebViewPrivate alloc] init];
1671     
1672 #ifndef NDEBUG
1673     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1674 #endif
1675     
1676     if (!preferences)
1677         preferences = [WebPreferences standardPreferences];
1678     [preferences willAddToWebView];
1679     
1680     _private->preferences = [preferences retain];
1681     _private->mainFrameDocumentReady = NO;
1682     _private->drawsBackground = YES;
1683     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1684
1685     WebFrameView *frameView = nil;
1686     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1687     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1688     [self addSubview:frameView];
1689     [frameView release];
1690
1691     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1692     _private->group->addWebView(self);
1693
1694     PageConfiguration pageConfiguration(
1695         makeUniqueRef<WebEditorClient>(self),
1696         SocketProvider::create(),
1697         LibWebRTCProvider::create(),
1698         WebCore::CacheStorageProvider::create()
1699     );
1700     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1701 #if ENABLE(DRAG_SUPPORT)
1702     pageConfiguration.dragClient = new WebDragClient(self);
1703 #endif
1704
1705 #if ENABLE(APPLE_PAY)
1706     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1707 #endif
1708
1709     pageConfiguration.backForwardClient = BackForwardList::create(self);
1710     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1711     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1712     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1713     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1714     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1715     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1716     pageConfiguration.userContentProvider = &_private->group->userContentController();
1717     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1718     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1719
1720     _private->page = new Page(WTFMove(pageConfiguration));
1721     
1722     [self setSmartInsertDeleteEnabled:YES];
1723     
1724     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1725     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1726     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1727     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1728     _private->page->settings().setMinimumLogicalFontSize(9);
1729     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1730     _private->page->settings().setDefaultFixedFontSize(13);
1731     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1732     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1733     
1734     _private->page->settings().setFontFallbackPrefersPictographs(true);
1735     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1736     
1737     _private->page->settings().setScriptMarkupEnabled(false);
1738     _private->page->settings().setScriptEnabled(true);
1739     
1740     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1741     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1742     
1743     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1744     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1745
1746     // This is a workaround for <rdar://problem/21309911>.
1747     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1748
1749     _private->page->setGroupName(groupName);
1750
1751 #if ENABLE(REMOTE_INSPECTOR)
1752     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1753 #endif
1754     
1755     [self _updateScreenScaleFromWindow];
1756     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1757     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1758
1759     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1760     
1761     [self _addToAllWebViewsSet];
1762     
1763     ++WebViewCount;
1764     
1765     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1766     
1767     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled(self.preferences.attachmentElementEnabled);
1768
1769     return self;
1770 }
1771
1772 + (void)_releaseMemoryNow
1773 {
1774     WebThreadRun(^{
1775         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1776     });
1777 }
1778
1779 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1780 {
1781     Frame* frame = [self _mainCoreFrame];
1782     if (frame)
1783         frame->loader().history().replaceCurrentItem(core(item));
1784 }
1785
1786 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1787 {
1788     WebThreadRun(^{
1789         [WebView _releaseMemoryNow];
1790         dispatch_async(dispatch_get_main_queue(), handler);
1791     });
1792 }
1793
1794 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1795 {
1796     return WebCore::isCharacterSmartReplaceExempt(character, b);
1797 }
1798
1799 - (void)updateLayoutIgnorePendingStyleSheets
1800 {
1801     WebThreadRun(^{
1802         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1803             Document *document = frame->document();
1804             if (document)
1805                 document->updateLayoutIgnorePendingStylesheets();
1806         }
1807     });
1808 }
1809 #endif
1810
1811 #if PLATFORM(IOS)
1812
1813 #if ENABLE(DRAG_SUPPORT)
1814
1815 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1816 {
1817     WebThreadLock();
1818     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1819 }
1820
1821 - (void)_startDrag:(const DragItem&)dragItem
1822 {
1823     auto& dragImage = dragItem.image;
1824     auto image = dragImage.get().get();
1825     auto indicatorData = dragImage.indicatorData();
1826
1827     if (indicatorData)
1828         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1829     else
1830         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1831     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1832     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1833     _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1834     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1835 }
1836
1837 - (CGRect)_dataInteractionCaretRect
1838 {
1839     WebThreadLock();
1840     if (auto* page = _private->page)
1841         return page->dragCaretController().caretRectInRootViewCoordinates();
1842
1843     return { };
1844 }
1845
1846 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1847 {
1848     return _private->dataOperationTextIndicator.get();
1849 }
1850
1851 - (WebDragSourceAction)_dragSourceAction
1852 {
1853     return _private->dragSourceAction;
1854 }
1855
1856 - (NSString *)_draggedLinkTitle
1857 {
1858     return _private->draggedLinkTitle.get();
1859 }
1860
1861 - (NSURL *)_draggedLinkURL
1862 {
1863     return _private->draggedLinkURL.get();
1864 }
1865
1866 - (CGRect)_draggedElementBounds
1867 {
1868     return _private->dragPreviewFrameInRootViewCoordinates;
1869 }
1870
1871 - (WebUITextIndicatorData *)_getDataInteractionData
1872 {
1873     return _private->textIndicatorData.get();
1874 }
1875
1876 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1877 {
1878     return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1879 }
1880
1881 - (DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1882 {
1883     auto dragOperationMask = static_cast<DragOperation>(operation);
1884     auto dragDestinationMask = static_cast<DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1885     return { session, roundedIntPoint(clientPosition), roundedIntPoint(globalPosition), dragOperationMask, DragApplicationNone, dragDestinationMask };
1886 }
1887
1888 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1889 {
1890     WebThreadLock();
1891     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1892     return _private->page->dragController().dragEntered(dragData);
1893 }
1894
1895 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1896 {
1897     WebThreadLock();
1898     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1899     return _private->page->dragController().dragUpdated(dragData);
1900 }
1901 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1902 {
1903     WebThreadLock();
1904     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1905     _private->page->dragController().dragExited(dragData);
1906 }
1907 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1908 {
1909     [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1910 }
1911
1912 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1913 {
1914     WebThreadLock();
1915     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1916     return _private->page->dragController().performDragOperation(dragData);
1917 }
1918
1919 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1920 {
1921     WebThreadLock();
1922     _private->page->dragController().dragEnded();
1923     _private->dataOperationTextIndicator = nullptr;
1924     _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1925     _private->dragSourceAction = WebDragSourceActionNone;
1926     _private->draggedLinkTitle = nil;
1927     _private->draggedLinkURL = nil;
1928 }
1929
1930 - (void)_didConcludeEditDataInteraction
1931 {
1932     _private->dataOperationTextIndicator = nullptr;
1933     auto* page = _private->page;
1934     if (!page)
1935         return;
1936
1937     static auto defaultEditDragTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | TextIndicatorOptionRespectTextColor;
1938     auto& frame = page->focusController().focusedOrMainFrame();
1939     if (auto range = frame.selection().selection().toNormalizedRange()) {
1940         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
1941             _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1942     }
1943 }
1944
1945 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1946
1947 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1948 {
1949     return NO;
1950 }
1951
1952 - (WebUITextIndicatorData *)_getDataInteractionData
1953 {
1954     return nil;
1955 }
1956
1957 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1958 {
1959     return nil;
1960 }
1961
1962 - (NSUInteger)_dragSourceAction
1963 {
1964     return 0;
1965 }
1966
1967 - (NSString *)_draggedLinkTitle
1968 {
1969     return nil;
1970 }
1971
1972 - (NSURL *)_draggedLinkURL
1973 {
1974     return nil;
1975 }
1976
1977 - (CGRect)_draggedElementBounds
1978 {
1979     return CGRectNull;
1980 }
1981
1982 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1983 {
1984     return 0;
1985 }
1986
1987 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1988 {
1989     return 0;
1990 }
1991
1992 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1993 {
1994 }
1995
1996 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1997 {
1998 }
1999
2000 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2001 {
2002     return NO;
2003 }
2004
2005 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2006 {
2007 }
2008
2009 - (CGRect)_dataInteractionCaretRect
2010 {
2011     return CGRectNull;
2012 }
2013
2014 #endif
2015 #endif // PLATFORM(IOS)
2016
2017 static NSMutableSet *knownPluginMIMETypes()
2018 {
2019     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2020     
2021     return mimeTypes;
2022 }
2023
2024 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2025 {
2026     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2027     [knownPluginMIMETypes() addObject:MIMEType];
2028 }
2029
2030 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2031 {
2032     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2033     [knownPluginMIMETypes() removeObject:MIMEType];
2034 }
2035
2036 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2037 {
2038     MIMEType = [MIMEType lowercaseString];
2039     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2040     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2041
2042 #if PLATFORM(IOS)
2043 #define WebPDFView ([WebView _getPDFViewClass])
2044 #endif
2045     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2046 #if PLATFORM(IOS)
2047 #undef WebPDFView
2048 #endif
2049         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2050
2051         if (allowPlugins) {
2052             // Load the plug-in DB allowing plug-ins to install types.
2053             [WebPluginDatabase sharedDatabase];
2054         }
2055
2056         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2057         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2058         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2059     }
2060     
2061     if (viewClass && repClass) {
2062         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2063             // Special-case WebHTMLView for text types that shouldn't be shown.
2064             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2065                 return NO;
2066
2067             // If the MIME type is a known plug-in we might not want to load it.
2068             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2069                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2070                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2071                 
2072                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2073                 if (!isSupportedByWebKit)
2074                     return NO;
2075             }
2076         }
2077         if (vClass)
2078             *vClass = viewClass;
2079         if (rClass)
2080             *rClass = repClass;
2081         return YES;
2082     }
2083     
2084     return NO;
2085 }
2086
2087 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2088 {
2089     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2090         return YES;
2091 #if !PLATFORM(IOS)
2092     if (_private->pluginDatabase) {
2093         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2094         if (pluginPackage) {
2095             if (vClass)
2096                 *vClass = [WebHTMLView class];
2097             if (rClass)
2098                 *rClass = [WebHTMLRepresentation class];
2099             return YES;
2100         }
2101     }
2102 #endif
2103     return NO;
2104 }
2105
2106 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2107 {
2108     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
2109 }
2110
2111 + (BOOL)canCloseAllWebViews
2112 {
2113     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2114 }
2115
2116 + (void)closeAllWebViews
2117 {
2118     DOMWindow::dispatchAllPendingUnloadEvents();
2119
2120     // This will close the WebViews in a random order. Change this if close order is important.
2121     // Make a new set to avoid mutating the set we are enumerating.
2122     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
2123     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
2124     while (WebView *webView = [enumerator nextObject])
2125         [webView close];
2126 }
2127
2128 + (BOOL)canShowFile:(NSString *)path
2129 {
2130     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2131 }
2132
2133 #if !PLATFORM(IOS)
2134 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2135 {
2136     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2137 }
2138 #endif
2139
2140 - (BOOL)_isClosed
2141 {
2142     return !_private || _private->closed;
2143 }
2144
2145 #if PLATFORM(IOS)
2146
2147 - (void)_dispatchUnloadEvent
2148 {
2149     WebThreadRun(^{
2150         WebFrame *mainFrame = [self mainFrame];
2151         Frame *coreMainFrame = core(mainFrame);
2152         if (coreMainFrame) {
2153             Document *document = coreMainFrame->document();
2154             if (document)
2155                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
2156         }
2157     });
2158 }
2159
2160 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2161 {
2162     auto* mainFrame = [self _mainCoreFrame];
2163     if (!mainFrame)
2164         return nil;
2165     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2166     if (!editingStyle)
2167         return nil;
2168     auto* style = editingStyle->style();
2169     if (!style)
2170         return nil;
2171     return kit(&style->ensureCSSStyleDeclaration());
2172 }
2173
2174 - (NSUInteger)_renderTreeSize
2175 {
2176     if (!_private->page)
2177         return 0;
2178     return _private->page->renderTreeSize();
2179 }
2180
2181 - (void)_dispatchTileDidDraw:(CALayer*)tile
2182 {
2183     id mailDelegate = [self _webMailDelegate];
2184     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2185         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2186         return;
2187     }
2188
2189 #pragma clang diagnostic push
2190 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2191     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2192         return;
2193 #pragma clang diagnostic pop
2194
2195     WebThreadLock();
2196
2197     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2198 }
2199
2200 - (void)_willStartScrollingOrZooming
2201 {
2202     // Pause timers during top level interaction
2203     if (_private->mainViewIsScrollingOrZooming)
2204         return;
2205     _private->mainViewIsScrollingOrZooming = YES;
2206
2207     [self hideFormValidationMessage];
2208
2209     // This suspends active DOM objects like timers, but not media.
2210     [[self mainFrame] setTimeoutsPaused:YES];
2211
2212     // This defers loading callbacks only.
2213     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2214     [self setDefersCallbacks:YES];
2215 }
2216
2217 - (void)_didFinishScrollingOrZooming
2218 {
2219     if (!_private->mainViewIsScrollingOrZooming)
2220         return;
2221     _private->mainViewIsScrollingOrZooming = NO;
2222     [self setDefersCallbacks:NO];
2223     [[self mainFrame] setTimeoutsPaused:NO];
2224     if (FrameView* view = [self _mainCoreFrame]->view())
2225         view->resumeVisibleImageAnimationsIncludingSubframes();
2226 }
2227
2228 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2229 {
2230     if (suspend)
2231         webResourceLoadScheduler().suspendPendingRequests();
2232     else
2233         webResourceLoadScheduler().resumePendingRequests();
2234 }
2235
2236 + (BOOL)_isUnderMemoryPressure
2237 {
2238     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2239 }
2240
2241 #endif // PLATFORM(IOS)
2242
2243 - (void)_closePluginDatabases
2244 {
2245     pluginDatabaseClientCount--;
2246
2247     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2248
2249 #if !PLATFORM(IOS)
2250     // Unload the WebView local plug-in database. 
2251     if (_private->pluginDatabase) {
2252         [_private->pluginDatabase destroyAllPluginInstanceViews];
2253         [_private->pluginDatabase close];
2254         [_private->pluginDatabase release];
2255         _private->pluginDatabase = nil;
2256     }
2257 #endif
2258     
2259     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2260     if (!pluginDatabaseClientCount && applicationIsTerminating)
2261         [WebPluginDatabase closeSharedDatabase];
2262 }
2263
2264 - (void)_closeWithFastTeardown 
2265 {
2266 #ifndef NDEBUG
2267     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2268 #endif
2269
2270 #if !PLATFORM(IOS)
2271     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2272 #endif
2273     [[NSNotificationCenter defaultCenter] removeObserver:self];
2274
2275     [self _closePluginDatabases];
2276 }
2277
2278 static bool fastDocumentTeardownEnabled()
2279 {
2280 #ifdef NDEBUG
2281     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2282 #else
2283     static bool initialized = false;
2284     static bool enabled = false;
2285     if (!initialized) {
2286         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2287         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2288         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2289         if (setting)
2290             enabled = ![setting boolValue];
2291         initialized = true;
2292     }
2293 #endif
2294     return enabled;
2295 }
2296
2297 // _close is here only for backward compatibility; clients and subclasses should use
2298 // public method -close instead.
2299 - (void)_close
2300 {
2301 #if PLATFORM(IOS)
2302     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2303     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2304
2305     [self _clearDelegates];
2306
2307     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2308     WebThreadRun(^{
2309 #endif            
2310
2311     if (!_private || _private->closed)
2312         return;
2313
2314     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2315
2316     _private->closed = YES;
2317     [self _removeFromAllWebViewsSet];
2318
2319 #ifndef NDEBUG
2320     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2321 #endif
2322
2323     // To quit the apps fast we skip document teardown, except plugins
2324     // need to be destroyed and unloaded.
2325     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2326         [self _closeWithFastTeardown];
2327         return;
2328     }
2329
2330 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2331     [self _exitVideoFullscreen];
2332 #endif
2333
2334 #if PLATFORM(IOS)
2335     _private->closing = YES;
2336 #endif
2337
2338     if (Frame* mainFrame = [self _mainCoreFrame])
2339         mainFrame->loader().detachFromParent();
2340
2341     [self setHostWindow:nil];
2342
2343 #if !PLATFORM(IOS)
2344     [self setDownloadDelegate:nil];
2345     [self setEditingDelegate:nil];
2346     [self setFrameLoadDelegate:nil];
2347     [self setPolicyDelegate:nil];
2348     [self setResourceLoadDelegate:nil];
2349     [self setScriptDebugDelegate:nil];
2350     [self setUIDelegate:nil];
2351
2352     [_private->inspector inspectedWebViewClosed];
2353 #endif
2354 #if PLATFORM(MAC)
2355     [_private->immediateActionController webViewClosed];
2356 #endif
2357
2358 #if !PLATFORM(IOS)
2359     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2360     [self removeDragCaret];
2361 #endif
2362
2363     _private->group->removeWebView(self);
2364
2365     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2366     // all the plug-ins in the page cache to break any retain cycles.
2367     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2368     Page* page = _private->page;
2369     _private->page = nullptr;
2370     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2371
2372 #if !PLATFORM(IOS)
2373     if (_private->hasSpellCheckerDocumentTag) {
2374         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2375         _private->hasSpellCheckerDocumentTag = NO;
2376     }
2377 #endif
2378
2379     if (_private->layerFlushController) {
2380         _private->layerFlushController->invalidate();
2381         _private->layerFlushController = nullptr;
2382     }
2383
2384     [[self _notificationProvider] unregisterWebView:self];
2385
2386 #if !PLATFORM(IOS)
2387     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2388 #endif
2389     [[NSNotificationCenter defaultCenter] removeObserver:self];
2390
2391     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2392
2393     WebPreferences *preferences = _private->preferences;
2394     _private->preferences = nil;
2395     [preferences didRemoveFromWebView];
2396     [preferences release];
2397
2398     [self _closePluginDatabases];
2399
2400 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2401     if (_private->m_playbackTargetPicker) {
2402         _private->m_playbackTargetPicker->invalidate();
2403         _private->m_playbackTargetPicker = nullptr;
2404     }
2405 #endif
2406
2407 #ifndef NDEBUG
2408     // Need this to make leak messages accurate.
2409     if (applicationIsTerminating) {
2410         WebCore::GCController::singleton().garbageCollectNow();
2411         [WebCache setDisabled:YES];
2412     }
2413 #endif
2414 #if PLATFORM(IOS)
2415     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2416     });
2417 #endif            
2418 }
2419
2420 // Indicates if the WebView is in the midst of a user gesture.
2421 - (BOOL)_isProcessingUserGesture
2422 {
2423     return UserGestureIndicator::processingUserGesture();
2424 }
2425
2426 + (NSString *)_MIMETypeForFile:(NSString *)path
2427 {
2428 #if !PLATFORM(IOS)
2429     NSString *extension = [path pathExtension];
2430 #endif
2431     NSString *MIMEType = nil;
2432
2433 #if !PLATFORM(IOS)
2434     // Get the MIME type from the extension.
2435     if ([extension length] != 0) {
2436         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2437     }
2438 #endif
2439
2440     // If we can't get a known MIME type from the extension, sniff.
2441     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2442         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2443         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2444         [handle closeFile];
2445         if ([data length] != 0) {
2446             MIMEType = [data _webkit_guessedMIMEType];
2447         }
2448         if ([MIMEType length] == 0) {
2449             MIMEType = @"application/octet-stream";
2450         }
2451     }
2452
2453     return MIMEType;
2454 }
2455
2456 - (WebDownload *)_downloadURL:(NSURL *)URL
2457 {
2458     ASSERT(URL);
2459     
2460     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2461     WebDownload *download = [WebDownload _downloadWithRequest:request
2462                                                      delegate:_private->downloadDelegate
2463                                                     directory:nil];
2464     [request release];
2465     
2466     return download;
2467 }
2468
2469 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2470 {
2471     NSDictionary *features = [[NSDictionary alloc] init];
2472     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2473                                             createWebViewWithRequest:nil
2474                                                       windowFeatures:features];
2475     [features release];
2476     if (!newWindowWebView)
2477         return nil;
2478
2479     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2480     return newWindowWebView;
2481 }
2482
2483 + (void)_setIconLoadingEnabled:(BOOL)enabled
2484 {
2485     iconLoadingEnabled = enabled;
2486 }
2487
2488 + (BOOL)_isIconLoadingEnabled
2489 {
2490     return iconLoadingEnabled;
2491 }
2492
2493 - (WebInspector *)inspector
2494 {
2495     if (!_private->inspector)
2496         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2497     return _private->inspector;
2498 }
2499
2500 #if ENABLE(REMOTE_INSPECTOR)
2501 + (void)_enableRemoteInspector
2502 {
2503     RemoteInspector::singleton().start();
2504 }
2505
2506 + (void)_disableRemoteInspector
2507 {
2508     RemoteInspector::singleton().stop();
2509 }
2510
2511 + (void)_disableAutoStartRemoteInspector
2512 {
2513     RemoteInspector::startDisabled();
2514 }
2515
2516 + (BOOL)_isRemoteInspectorEnabled
2517 {
2518     return RemoteInspector::singleton().enabled();
2519 }
2520
2521 + (BOOL)_hasRemoteInspectorSession
2522 {
2523     return RemoteInspector::singleton().hasActiveDebugSession();
2524 }
2525
2526 - (BOOL)allowsRemoteInspection
2527 {
2528     return _private->page->remoteInspectionAllowed();
2529 }
2530
2531 - (void)setAllowsRemoteInspection:(BOOL)allow
2532 {
2533     _private->page->setRemoteInspectionAllowed(allow);
2534 }
2535
2536 - (void)setShowingInspectorIndication:(BOOL)showing
2537 {
2538 #if PLATFORM(IOS)
2539     ASSERT(WebThreadIsLocked());
2540
2541     if (showing) {
2542         if (!_private->indicateLayer) {
2543             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2544             [_private->indicateLayer setNeedsLayout];
2545             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2546         }
2547     } else {
2548         [_private->indicateLayer removeFromSuperlayer];
2549         [_private->indicateLayer release];
2550         _private->indicateLayer = nil;
2551     }
2552 #else
2553     // Implemented in WebCore::InspectorOverlay.
2554 #endif
2555 }
2556
2557 #if PLATFORM(IOS)
2558 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2559 {
2560     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2561     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2562 }
2563 #endif // PLATFORM(IOS)
2564 #endif // ENABLE(REMOTE_INSPECTOR)
2565
2566 - (WebCore::Page*)page
2567 {
2568     return _private->page;
2569 }
2570
2571 #if !PLATFORM(IOS)
2572 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2573 {
2574     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2575     NSArray *menuItems = defaultMenuItems;
2576
2577     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2578     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2579     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2580     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2581         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2582         if (!menuItems)
2583             return nil;
2584     }
2585
2586     unsigned count = [menuItems count];
2587     if (!count)
2588         return nil;
2589
2590     NSMenu *menu = [[NSMenu alloc] init];
2591     for (unsigned i = 0; i < count; i++)
2592         [menu addItem:[menuItems objectAtIndex:i]];
2593
2594     return [menu autorelease];
2595 }
2596 #endif
2597
2598 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2599 {
2600     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2601     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2602     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2603     if (!dictionary)
2604         return;
2605     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2606 }
2607
2608 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2609 {
2610     if (!_private->page)
2611         return;
2612     
2613     if (!otherView->_private->page)
2614         return;
2615     
2616     // It turns out the right combination of behavior is done with the back/forward load
2617     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2618     // in the back forward list, and go to the current one.
2619
2620     BackForwardController& backForward = _private->page->backForward();
2621     ASSERT(!backForward.currentItem()); // destination list should be empty
2622
2623     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2624     if (!otherBackForward.currentItem())
2625         return; // empty back forward list, bail
2626     
2627     HistoryItem* newItemToGoTo = nullptr;
2628
2629     int lastItemIndex = otherBackForward.forwardCount();
2630     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2631         if (i == 0) {
2632             // If this item is showing , save away its current scroll and form state,
2633             // since that might have changed since loading and it is normally not saved
2634             // until we leave that page.
2635             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2636         }
2637         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2638         if (i == 0) 
2639             newItemToGoTo = newItem.ptr();
2640         backForward.client()->addItem(WTFMove(newItem));
2641     }
2642
2643     ASSERT(newItemToGoTo);
2644     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, NavigationPolicyCheck::Require);
2645 }
2646
2647 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2648 {
2649     _private->formDelegate = delegate;
2650 #if PLATFORM(IOS)
2651     [_private->formDelegateForwarder clearTarget];
2652     [_private->formDelegateForwarder release];
2653     _private->formDelegateForwarder = nil;
2654 #endif
2655 }
2656
2657 - (id<WebFormDelegate>)_formDelegate
2658 {
2659     return _private->formDelegate;
2660 }
2661
2662 #if PLATFORM(IOS)
2663 - (id)_formDelegateForwarder
2664 {
2665     if (_private->closing)
2666         return nil;
2667
2668     if (!_private->formDelegateForwarder)
2669         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2670     return _private->formDelegateForwarder;
2671 }
2672
2673 - (id)_formDelegateForSelector:(SEL)selector
2674 {
2675     id delegate = self->_private->formDelegate;
2676     if ([delegate respondsToSelector:selector])
2677         return delegate;
2678
2679     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2680     if ([delegate respondsToSelector:selector])
2681         return delegate;
2682
2683     return nil;
2684 }
2685 #endif
2686
2687 #if !PLATFORM(IOS)
2688 - (BOOL)_needsAdobeFrameReloadingQuirk
2689 {
2690     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2691         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2692         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2693         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2694         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2695         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2696         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2697         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2698         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2699         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2700
2701     return needsQuirk;
2702 }
2703
2704 - (BOOL)_needsLinkElementTextCSSQuirk
2705 {
2706     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2707         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
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         _private->userAgent = String();
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.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2944
2945     switch ([preferences storageBlockingPolicy]) {
2946     case WebAllowAllStorage:
2947         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2948         break;
2949     case WebBlockThirdPartyStorage:
2950         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2951         break;
2952     case WebBlockAllStorage:
2953         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2954         break;
2955     }
2956
2957     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2958     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2959
2960 #if PLATFORM(MAC)
2961     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2962 #endif
2963
2964 #if ENABLE(RUBBER_BANDING)
2965     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2966     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2967 #endif
2968
2969 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2970     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2971 #endif
2972 #if PLATFORM(IOS)
2973     settings.setStandalone([preferences _standalone]);
2974     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2975     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2976     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2977     settings.setMaxParseDuration([preferences _maxParseDuration]);
2978     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2979     DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2980     DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2981     DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
2982 #if HAVE(AVKIT)
2983     DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
2984 #endif
2985
2986     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2987     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2988
2989     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2990     settings.setDelegatesPageScaling(true);
2991
2992 #if ENABLE(TEXT_AUTOSIZING)
2993     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2994     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2995 #endif
2996 #endif // PLATFORM(IOS)
2997
2998 #if PLATFORM(MAC)
2999     if ([preferences userStyleSheetEnabled]) {
3000         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3001         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
3002             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
3003         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3004     } else
3005         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3006
3007     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3008     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3009     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3010     settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3011     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3012     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3013     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3014     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3015     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3016 #endif // PLATFORM(MAC)
3017
3018     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3019
3020 #if ENABLE(MEDIA_SOURCE)
3021     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3022 #endif
3023
3024 #if ENABLE(SERVICE_CONTROLS)
3025     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
3026     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
3027 #endif
3028
3029 #if ENABLE(VIDEO_TRACK)
3030     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
3031     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
3032     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
3033 #endif
3034
3035 #if USE(AVFOUNDATION)
3036     DeprecatedGlobalSettings::setAVFoundationEnabled([preferences isAVFoundationEnabled]);
3037     DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
3038 #endif
3039
3040 #if ENABLE(MEDIA_STREAM)
3041     DeprecatedGlobalSettings::setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
3042     DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
3043     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
3044     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled([preferences mediaDevicesEnabled]);
3045 #endif
3046
3047 #if ENABLE(WEB_RTC)
3048     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
3049     RuntimeEnabledFeatures::sharedFeatures().setWebRTCLegacyAPIEnabled([preferences webRTCLegacyAPIEnabled]);
3050 #endif
3051
3052 #if ENABLE(WEB_AUDIO)
3053     settings.setWebAudioEnabled([preferences webAudioEnabled]);
3054 #endif
3055
3056 #if ENABLE(FULLSCREEN_API)
3057     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3058 #endif
3059
3060     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3061
3062     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3063
3064     DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3065
3066     settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3067     settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3068
3069 #if ENABLE(GAMEPAD)
3070     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3071 #endif
3072
3073     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3074     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3075     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3076     RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3077
3078 #if ENABLE(ATTACHMENT_ELEMENT)
3079     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3080 #endif
3081
3082     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3083     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3084     RuntimeEnabledFeatures::sharedFeatures().setCSSAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled([preferences cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled]);
3085
3086     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3087     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3088
3089 #if ENABLE(STREAMS_API)
3090     RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3091     RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3092 #endif
3093
3094 #if ENABLE(WEBGL2)
3095     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3096 #endif
3097
3098 #if ENABLE(WEBGPU)
3099     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3100 #endif
3101
3102 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3103     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3104 #endif
3105
3106     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3107
3108 #if ENABLE(INTERSECTION_OBSERVER)
3109     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3110 #endif
3111     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3112
3113     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3114     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3115     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3116     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3117     RuntimeEnabledFeatures::sharedFeatures().setWebAuthenticationEnabled(preferences.webAuthenticationEnabled);
3118     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3119     RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3120     RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3121     RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3122     RuntimeEnabledFeatures::sharedFeatures().setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3123     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3124
3125 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3126     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3127 #endif
3128
3129 #if ENABLE(ENCRYPTED_MEDIA)
3130     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3131 #endif
3132
3133     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3134
3135     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3136
3137     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3138     if (timeout > 0)
3139         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3140
3141     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3142     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3143
3144     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3145     if (_private->zoomsTextOnly != zoomsTextOnly)
3146         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3147
3148 #if PLATFORM(IOS)
3149     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3150     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3151     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3152     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3153 #endif
3154
3155 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3156     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3157 #endif
3158
3159     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3160
3161     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3162
3163     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3164
3165     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3166     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3167 }
3168
3169 static inline IMP getMethod(id o, SEL s)
3170 {
3171     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3172 }
3173
3174 #if PLATFORM(IOS)
3175 - (id)_UIKitDelegateForwarder
3176 {
3177     if (_private->closing)
3178         return nil;
3179         
3180     if (!_private->UIKitDelegateForwarder)
3181         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3182     return _private->UIKitDelegateForwarder;
3183 }
3184 #endif
3185
3186 - (void)_cacheResourceLoadDelegateImplementations
3187 {
3188     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3189     id delegate = _private->resourceProgressDelegate;
3190
3191     if (!delegate) {
3192         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3193         return;
3194     }
3195
3196     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3197     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3198     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3199     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3200 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3201     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3202 #endif
3203
3204 #if PLATFORM(IOS)
3205     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3206     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3207     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3208     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3209     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3210     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3211     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3212     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3213     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3214 #endif
3215
3216     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3217     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3218     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3219     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3220     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3221     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3222     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3223     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3224 }
3225
3226 - (void)_cacheFrameLoadDelegateImplementations
3227 {
3228     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3229     id delegate = _private->frameLoadDelegate;
3230
3231     if (!delegate) {
3232         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3233         return;
3234     }
3235
3236     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3237     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3238     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3239     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3240     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3241 #if JSC_OBJC_API_ENABLED
3242     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3243 #endif
3244     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3245     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3246     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3247     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3248     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3249     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3250     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3251     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3252     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3253     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3254     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3255     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3256 #if ENABLE(ICONDATABASE)
3257     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3258 #endif
3259     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3260     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3261     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3262     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3263     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3264     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3265     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3266     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3267     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3268     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3269 #if PLATFORM(IOS)
3270     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3271 #endif
3272
3273     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3274     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3275     // for backwards compatibility.
3276     Page* page = core(self);
3277     if (page) {
3278         unsigned milestones = DidFirstLayout;
3279 #if PLATFORM(IOS)
3280         milestones |= DidFirstVisuallyNonEmptyLayout;
3281 #else
3282         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3283             milestones |= DidFirstVisuallyNonEmptyLayout;
3284 #endif
3285         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3286     }
3287 }
3288
3289 - (void)_cacheScriptDebugDelegateImplementations
3290 {
3291     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3292     id delegate = _private->scriptDebugDelegate;
3293
3294     if (!delegate) {
3295         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3296         return;
3297     }
3298
3299     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3300     if (cache->didParseSourceFunc)
3301         cache->didParseSourceExpectsBaseLineNumber = YES;
3302     else {
3303         cache->didParseSourceExpectsBaseLineNumber = NO;
3304         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3305     }
3306
3307     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3308
3309     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3310     if (cache->exceptionWasRaisedFunc)
3311         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3312     else {
3313         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3314         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3315     }
3316 }
3317
3318 - (void)_cacheHistoryDelegateImplementations
3319 {
3320     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3321     id delegate = _private->historyDelegate;
3322
3323     if (!delegate) {
3324         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3325         return;
3326     }
3327
3328     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3329     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3330     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3331     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3332     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3333     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3334 }
3335
3336 - (id)_policyDelegateForwarder
3337 {
3338 #if PLATFORM(IOS)
3339     if (_private->closing)
3340         return nil;
3341 #endif
3342     if (!_private->policyDelegateForwarder)
3343         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3344     return _private->policyDelegateForwarder;
3345 }
3346
3347 - (id)_UIDelegateForwarder
3348 {
3349 #if PLATFORM(IOS)
3350     if (_private->closing)
3351         return nil;
3352 #endif
3353     if (!_private->UIDelegateForwarder)
3354         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3355     return _private->UIDelegateForwarder;
3356 }
3357
3358 #if PLATFORM(IOS)
3359 - (id)_UIDelegateForSelector:(SEL)selector
3360 {
3361     id delegate = self->_private->UIDelegate;
3362     if ([delegate respondsToSelector:selector])
3363         return delegate;
3364
3365     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3366     if ([delegate respondsToSelector:selector])
3367         return delegate;
3368
3369     return nil;
3370 }
3371 #endif
3372
3373 - (id)_editingDelegateForwarder
3374 {
3375 #if PLATFORM(IOS)
3376     if (_private->closing)
3377         return nil;
3378 #endif    
3379     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3380     // Not sure if that is a bug or not.
3381     if (!_private)
3382         return nil;
3383
3384     if (!_private->editingDelegateForwarder)
3385         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3386     return _private->editingDelegateForwarder;
3387 }
3388
3389 - (void)_closeWindow
3390 {
3391     [[self _UIDelegateForwarder] webViewClose:self];
3392 }
3393
3394 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3395 {
3396     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3397     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3398     
3399     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3400     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3401     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3402     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3403 }
3404
3405 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3406 {
3407     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3408     [self registerViewClass:viewClass representationClass:representationClass forMIMEType: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     if ([viewClass class] == [WebHTMLView class])
3414         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3415     
3416     // This is used to make _representationExistsForURLScheme faster.
3417     // Without this set, we'd have to create the MIME type each time.
3418     if (schemesWithRepresentationsSet == nil) {
3419         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3420     }
3421     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3422 }
3423
3424 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3425 {
3426     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3427 }
3428
3429 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3430 {
3431     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3432 }
3433
3434 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3435 {
3436     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3437     if (!request)
3438         return NO;
3439
3440     if ([NSURLConnection canHandleRequest:request])
3441         return YES;
3442
3443     NSString *scheme = [[request URL] scheme];
3444
3445     // Representations for URL schemes work at the top level.
3446     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3447         return YES;
3448
3449     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3450         return YES;
3451
3452     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3453         return YES;
3454
3455     return NO;
3456 }
3457
3458 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3459 {
3460     return [self _canHandleRequest:request forMainFrame:YES];
3461 }
3462
3463 + (NSString *)_decodeData:(NSData *)data
3464 {
3465     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3466     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3467 }
3468
3469 - (void)_pushPerformingProgrammaticFocus
3470 {
3471     _private->programmaticFocusCount++;
3472 }
3473
3474 - (void)_popPerformingProgrammaticFocus
3475 {
3476     _private->programmaticFocusCount--;
3477 }
3478
3479 - (BOOL)_isPerformingProgrammaticFocus
3480 {
3481     return _private->programmaticFocusCount != 0;
3482 }
3483
3484 #if !PLATFORM(IOS)
3485 - (void)_didChangeValueForKey: (NSString *)key
3486 {
3487     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3488     [self didChangeValueForKey: key];
3489 }
3490
3491 - (void)_willChangeValueForKey: (NSString *)key
3492 {
3493     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3494     [self willChangeValueForKey: key];
3495 }
3496
3497 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3498     static NSSet *manualNotifyKeys = nil;
3499     if (!manualNotifyKeys)
3500         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3501             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3502             nil];
3503     if ([manualNotifyKeys containsObject:key])
3504         return NO;
3505     return YES;
3506 }
3507
3508 - (NSArray *)_declaredKeys {
3509     static NSArray *declaredKeys = nil;
3510     if (!declaredKeys)
3511         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3512             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3513     return declaredKeys;
3514 }
3515
3516 - (void)_willChangeBackForwardKeys
3517 {
3518     [self _willChangeValueForKey: _WebCanGoBackKey];
3519     [self _willChangeValueForKey: _WebCanGoForwardKey];
3520 }
3521
3522 - (void)_didChangeBackForwardKeys
3523 {
3524     [self _didChangeValueForKey: _WebCanGoBackKey];
3525     [self _didChangeValueForKey: _WebCanGoForwardKey];
3526 }
3527
3528 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3529 {
3530     if (needsSelfRetainWhileLoadingQuirk())
3531         [self retain];
3532
3533     [self _willChangeBackForwardKeys];
3534     if (frame == [self mainFrame]){
3535         // Force an observer update by sending a will/did.
3536         [self _willChangeValueForKey: _WebIsLoadingKey];
3537         [self _didChangeValueForKey: _WebIsLoadingKey];
3538
3539         [self _willChangeValueForKey: _WebMainFrameURLKey];
3540
3541         [self hideFormValidationMessage];
3542     }
3543
3544     [NSApp setWindowsNeedUpdate:YES];
3545
3546 #if ENABLE(FULLSCREEN_API)
3547     Document* document = core([frame DOMDocument]);
3548     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3549         SEL selector = @selector(webView:closeFullScreenWithListener:);
3550         if ([_private->UIDelegate respondsToSelector:selector]) {
3551             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3552             CallUIDelegate(self, selector, listener);
3553             [listener release];
3554         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3555             [_private->newFullscreenController close];
3556         }
3557     }
3558 #endif
3559 }
3560
3561 - (void)_checkDidPerformFirstNavigation
3562 {
3563     if (_private->_didPerformFirstNavigation)
3564         return;
3565
3566     Page* page = _private->page;
3567     if (!page)
3568         return;
3569
3570     auto& backForwardController = page->backForward();
3571
3572     if (!backForwardController.backItem())
3573         return;
3574
3575     _private->_didPerformFirstNavigation = YES;
3576
3577     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3578         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3579 }
3580
3581 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3582 {
3583     if (frame == [self mainFrame])
3584         [self _didChangeValueForKey: _WebMainFrameURLKey];
3585
3586     [self _checkDidPerformFirstNavigation];
3587
3588     [NSApp setWindowsNeedUpdate:YES];
3589 }
3590
3591 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3592 {
3593     if (needsSelfRetainWhileLoadingQuirk())
3594         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3595         
3596     [self _didChangeBackForwardKeys];
3597     if (frame == [self mainFrame]){
3598         // Force an observer update by sending a will/did.
3599         [self _willChangeValueForKey: _WebIsLoadingKey];
3600         [self _didChangeValueForKey: _WebIsLoadingKey];
3601     }
3602     [NSApp setWindowsNeedUpdate:YES];
3603 }
3604
3605 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3606 {
3607     if (needsSelfRetainWhileLoadingQuirk())
3608         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3609
3610     [self _didChangeBackForwardKeys];
3611     if (frame == [self mainFrame]){
3612         // Force an observer update by sending a will/did.
3613         [self _willChangeValueForKey: _WebIsLoadingKey];
3614         [self _didChangeValueForKey: _WebIsLoadingKey];
3615     }
3616     [NSApp setWindowsNeedUpdate:YES];
3617 }
3618
3619 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3620 {
3621     if (needsSelfRetainWhileLoadingQuirk())
3622         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3623
3624     [self _didChangeBackForwardKeys];
3625     if (frame == [self mainFrame]){
3626         // Force an observer update by sending a will/did.
3627         [self _willChangeValueForKey: _WebIsLoadingKey];
3628         [self _didChangeValueForKey: _WebIsLoadingKey];
3629         
3630         [self _didChangeValueForKey: _WebMainFrameURLKey];
3631     }
3632     [NSApp setWindowsNeedUpdate:YES];
3633 }
3634
3635 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3636 {
3637     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3638     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3639     NSCachedURLResponse *cachedResponse;
3640
3641     if (!_private->page)
3642         return nil;
3643
3644     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3645         cachedResponse = cachedResponseForRequest(storageSession, request.get());
3646     else
3647         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3648
3649     return cachedResponse;
3650 }
3651
3652 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3653 {
3654     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3655     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3656     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3657                         element:domElement
3658                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3659                           title:[element objectForKey:WebElementImageAltStringKey] 
3660                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3661                           types:types
3662                          source:nil];
3663 }
3664
3665 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3666 {
3667     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3668                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3669                         types:types];
3670 }
3671
3672 #if ENABLE(DRAG_SUPPORT)
3673 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3674 {
3675     if (!_private->page)
3676         return;
3677     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3678 }
3679 #endif
3680
3681 #else
3682
3683 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3684 {
3685     if (frame == [self mainFrame])
3686         _private->didDrawTiles = 0;
3687 }
3688
3689 #endif // PLATFORM(IOS)
3690
3691 #if ENABLE(DASHBOARD_SUPPORT)
3692
3693 #define DASHBOARD_CONTROL_LABEL @"control"
3694
3695 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3696 {
3697     NSRect adjustedBounds = bounds;
3698     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3699     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3700     adjustedBounds.size = bounds.size;
3701
3702     NSRect adjustedClip;
3703     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3704     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3705     adjustedClip.size = clip.size;
3706
3707     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3708         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3709     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3710     if (!scrollerRegions) {
3711         scrollerRegions = [[NSMutableArray alloc] init];
3712         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3713         [scrollerRegions release];
3714     }
3715     [scrollerRegions addObject:region];
3716     [region release];
3717 }
3718
3719 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3720 {    
3721     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3722
3723     for (const auto& widget: frameView->children()) {
3724         if (is<FrameView>(widget)) {
3725             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3726             continue;
3727         }
3728
3729         if (!widget->isScrollbar())
3730             continue;
3731
3732         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3733         // it's not common to need this to be correct in Dashboard widgets.
3734         NSRect bounds = widget->frameRect();
3735         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3736     }
3737 }
3738
3739 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3740 {
3741     // Add scroller regions for NSScroller and WebCore scrollbars
3742     NSUInteger count = [views count];
3743     for (NSUInteger i = 0; i < count; i++) {
3744         NSView *view = [views objectAtIndex:i];
3745         
3746         if ([view isKindOfClass:[WebHTMLView class]]) {
3747             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3748                 if (FrameView* coreView = coreFrame->view())
3749                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3750             }
3751         } else if ([view isKindOfClass:[NSScroller class]]) {
3752             // AppKit places absent scrollers at -100,-100
3753             if ([view frame].origin.y < 0)
3754                 continue;
3755             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3756         }
3757         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3758     }
3759 }
3760
3761 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3762 {
3763     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3764 }
3765
3766 - (NSDictionary *)_dashboardRegions
3767 {
3768     // Only return regions from main frame.
3769     Frame* mainFrame = [self _mainCoreFrame];
3770     if (!mainFrame)
3771         return nil;
3772
3773     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3774     size_t size = regions.size();
3775
3776     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3777     for (size_t i = 0; i < size; i++) {
3778         const AnnotatedRegionValue& region = regions[i];
3779
3780         if (region.type == StyleDashboardRegion::None)
3781             continue;
3782
3783         NSString *label = region.label;
3784         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3785         if (region.type == StyleDashboardRegion::Circle)
3786             type = WebDashboardRegionTypeCircle;
3787         else if (region.type == StyleDashboardRegion::Rectangle)
3788             type = WebDashboardRegionTypeRectangle;
3789         NSMutableArray *regionValues = [webRegions objectForKey:label];
3790         if (!regionValues) {
3791             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3792             [webRegions setObject:regionValues forKey:label];
3793             [regionValues release];
3794         }
3795
3796         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3797         [regionValues addObject:webRegion];
3798         [webRegion release];
3799     }
3800
3801     [self _addScrollerDashboardRegions:webRegions];
3802
3803     return webRegions;
3804 }
3805
3806 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3807 {
3808     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3809     // specific support for the backward compatibility mode flag.
3810     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3811         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3812     
3813     switch (behavior) {
3814         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3815             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3816             break;
3817         }
3818         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3819             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3820             break;
3821         }
3822         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3823             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3824             break;
3825         }
3826         case WebDashboardBehaviorAllowWheelScrolling: {
3827             _private->dashboardBehaviorAllowWheelScrolling = flag;
3828             break;
3829         }
3830         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3831             if (_private->page)
3832                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3833 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3834             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3835 #endif
3836             break;
3837         }
3838     }
3839
3840     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3841     // compatibility mode. See <rdar://problem/8175982>.
3842     if (_private->page)
3843         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3844 }
3845
3846 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3847 {
3848     switch (behavior) {
3849         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3850             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3851         }
3852         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3853             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3854         }
3855         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3856             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3857         }
3858         case WebDashboardBehaviorAllowWheelScrolling: {
3859             return _private->dashboardBehaviorAllowWheelScrolling;
3860         }
3861         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3862             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3863         }
3864     }
3865     return NO;
3866 }
3867
3868 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3869
3870 + (void)_setShouldUseFontSmoothing:(BOOL)f
3871 {
3872     FontCascade::setShouldUseSmoothing(f);
3873 }
3874
3875 + (BOOL)_shouldUseFontSmoothing
3876 {
3877     return FontCascade::shouldUseSmoothing();
3878 }
3879
3880 #if !PLATFORM(IOS)
3881 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3882 {
3883     setUsesTestModeFocusRingColor(f);
3884 }
3885
3886 + (BOOL)_usesTestModeFocusRingColor
3887 {
3888     return usesTestModeFocusRingColor();
3889 }
3890 #endif
3891
3892 #if PLATFORM(IOS)
3893 - (void)_setUIKitDelegate:(id)delegate
3894 {
3895     _private->UIKitDelegate = delegate;
3896     [_private->UIKitDelegateForwarder clearTarget];
3897     [_private->UIKitDelegateForwarder release];
3898     _private->UIKitDelegateForwarder = nil;
3899 }
3900
3901 - (id)_UIKitDelegate
3902 {
3903     return _private->UIKitDelegate;
3904 }
3905
3906 - (void)setWebMailDelegate:(id)delegate
3907 {
3908     _private->WebMailDelegate = delegate;
3909 }
3910
3911 - (id)_webMailDelegate
3912 {
3913     return _private->WebMailDelegate;
3914 }
3915
3916 - (id <WebCaretChangeListener>)caretChangeListener
3917 {
3918     return _private->_caretChangeListener;
3919 }
3920
3921 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3922 {
3923     _private->_caretChangeListener = listener;
3924 }
3925
3926 - (NSSet *)caretChangeListeners
3927 {
3928     return _private->_caretChangeListeners;
3929 }
3930
3931 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3932 {
3933     if (_private->_caretChangeListeners == nil) {
3934         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3935     }
3936     
3937     [_private->_caretChangeListeners addObject:listener];
3938 }
3939
3940 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3941 {
3942     [_private->_caretChangeListeners removeObject:listener];
3943 }
3944
3945 - (void)removeAllCaretChangeListeners
3946 {
3947     [_private->_caretChangeListeners removeAllObjects];
3948 }
3949
3950 - (void)caretChanged
3951 {
3952     [_private->_caretChangeListener caretChanged];
3953     NSSet *copy = [_private->_caretChangeListeners copy];
3954     for (id <WebCaretChangeListener> listener in copy) {
3955         [listener caretChanged];
3956     }
3957     [copy release];
3958 }
3959
3960 - (void)_clearDelegates
3961 {
3962     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3963     
3964     [self _setFormDelegate:nil];
3965     [self _setUIKitDelegate:nil];
3966     [self setCaretChangeListener:nil];
3967     [self removeAllCaretChangeListeners];
3968     [self setWebMailDelegate:nil];
3969     
3970     [self setDownloadDelegate:nil];
3971     [self setEditingDelegate:nil]; 
3972     [self setFrameLoadDelegate:nil];
3973     [self setPolicyDelegate:nil];
3974     [self setResourceLoadDelegate:nil];
3975     [self setScriptDebugDelegate:nil];
3976     [self setUIDelegate:nil];     
3977 }
3978
3979 - (NSURL *)_displayURL
3980 {
3981     WebThreadLock();
3982     WebFrame *frame = [self mainFrame];
3983     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3984     WebDataSource *dataSource = [frame provisionalDataSource];
3985     if (!dataSource)
3986         dataSource = [frame dataSource];
3987     NSURL *unreachableURL = [dataSource unreachableURL];
3988     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3989     [[URL retain] autorelease];
3990     return URL;
3991 }
3992 #endif // PLATFORM(IOS)
3993
3994 #if !PLATFORM(IOS)
3995 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3996 {
3997     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3998     if (flag) {
3999         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4000     } else {
4001         [scrollview setVerticalScrollingModeLocked:NO];
4002         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
4003     }
4004 }
4005
4006 - (BOOL)alwaysShowVerticalScroller
4007 {
4008     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4009     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
4010 }
4011
4012 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
4013 {
4014     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4015     if (flag) {
4016         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4017     } else {
4018         [scrollview setHorizontalScrollingModeLocked:NO];
4019         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
4020     }
4021 }
4022
4023 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
4024 {
4025     if (Frame* mainFrame = [self _mainCoreFrame])
4026         mainFrame->view()->setProhibitsScrolling(prohibits);
4027 }
4028
4029 - (BOOL)alwaysShowHorizontalScroller
4030 {
4031     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4032     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
4033 }
4034 #endif // !PLATFORM(IOS)
4035
4036 - (void)_setUseFastImageScalingMode:(BOOL)flag
4037 {
4038     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
4039         _private->page->setInLowQualityImageInterpolationMode(flag);
4040         [self setNeedsDisplay:YES];
4041     }
4042 }
4043
4044 - (BOOL)_inFastImageScalingMode
4045 {
4046     if (_private->page)
4047         return _private->page->inLowQualityImageInterpolationMode();
4048     return NO;
4049 }
4050
4051 - (BOOL)_cookieEnabled
4052 {
4053     if (_private->page)
4054         return _private->page->settings().cookieEnabled();
4055     return YES;
4056 }
4057
4058 - (void)_setCookieEnabled:(BOOL)enable
4059 {
4060     if (_private->page)
4061         _private->page->settings().setCookieEnabled(enable);
4062 }
4063
4064 #if !PLATFORM(IOS)
4065 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
4066 {
4067     if (!_private->pluginDatabase)
4068         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
4069         
4070     [_private->pluginDatabase setPlugInPaths:newPaths];
4071     [_private->pluginDatabase refresh];
4072 }
4073 #endif
4074
4075 #if PLATFORM(IOS)
4076 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
4077 {
4078     // Ask plug-ins in this frame
4079     id <WebDocumentView> documentView = [[frame frameView] documentView];
4080     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
4081         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
4082             return YES;
4083     }
4084
4085     // Ask plug-ins in child frames
4086     NSArray *childFrames = [frame childFrames];
4087     unsigned childCount = [childFrames count];
4088     unsigned childIndex;
4089     for (childIndex = 0; childIndex < childCount; childIndex++) {
4090         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
4091             return YES;
4092     }
4093     
4094     return NO;
4095 }
4096
4097 - (BOOL)_pluginsAreRunning
4098 {
4099     WebThreadLock();
4100     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
4101 }
4102
4103 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
4104 {
4105     // Send the message to plug-ins in this frame
4106     id <WebDocumentView> documentView = [[frame frameView] documentView];
4107     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
4108         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
4109
4110     // Send the message to plug-ins in child frames
4111     NSArray *childFrames = [frame childFrames];
4112     unsigned childCount = [childFrames count];
4113     unsigned childIndex;
4114     for (childIndex = 0; childIndex < childCount; childIndex++) {
4115         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
4116     }
4117 }
4118
4119 - (void)_destroyAllPlugIns
4120 {
4121     WebThreadLock();
4122     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
4123 }
4124
4125 - (void)_startAllPlugIns
4126 {
4127     WebThreadLock();
4128     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
4129 }
4130
4131 - (void)_stopAllPlugIns
4132 {
4133     WebThreadLock();
4134     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
4135 }
4136
4137 - (void)_stopAllPlugInsForPageCache
4138 {
4139     WebThreadLock();
4140     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
4141 }
4142
4143 - (void)_restorePlugInsFromCache
4144 {
4145     WebThreadLock();
4146     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
4147 }
4148
4149 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
4150 {
4151     WebThreadLock();
4152
4153     Frame* mainCoreFrame = [self _mainCoreFrame];
4154     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
4155         FrameView* coreView = frame ? frame->view() : 0;
4156         if (!coreView)
4157             continue;
4158
4159         // Get the GraphicsLayer for this widget.
4160         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
4161         if (!layerForWidget)
4162             continue;
4163         
4164         if (layerForWidget->contentsLayerForMedia() != layer) {
4165             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
4166             // We need to make sure the layer hierachy change is applied immediately.
4167             if (mainCoreFrame->view())
4168                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
4169             return YES;
4170         }
4171     }
4172
4173     return NO;
4174 }
4175
4176 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
4177 {