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