[Cocoa] More tweaks and refactoring to prepare for ARC
[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/NetworkStorageSession.h>
177 #import <WebCore/NodeList.h>
178 #import <WebCore/Notification.h>
179 #import <WebCore/NotificationController.h>
180 #import <WebCore/Page.h>
181 #import <WebCore/PageCache.h>
182 #import <WebCore/PageConfiguration.h>
183 #import <WebCore/PageGroup.h>
184 #import <WebCore/PathUtilities.h>
185 #import <WebCore/PlatformEventFactoryMac.h>
186 #import <WebCore/ProgressTracker.h>
187 #import <WebCore/RenderTheme.h>
188 #import <WebCore/RenderView.h>
189 #import <WebCore/RenderWidget.h>
190 #import <WebCore/ResourceHandle.h>
191 #import <WebCore/ResourceLoadObserver.h>
192 #import <WebCore/ResourceRequest.h>
193 #import <WebCore/RuntimeApplicationChecks.h>
194 #import <WebCore/RuntimeEnabledFeatures.h>
195 #import <WebCore/SchemeRegistry.h>
196 #import <WebCore/ScriptController.h>
197 #import <WebCore/SecurityOrigin.h>
198 #import <WebCore/SecurityPolicy.h>
199 #import <WebCore/Settings.h>
200 #import <WebCore/ShouldTreatAsContinuingLoad.h>
201 #import <WebCore/SocketProvider.h>
202 #import <WebCore/StyleProperties.h>
203 #import <WebCore/TextResourceDecoder.h>
204 #import <WebCore/ThreadCheck.h>
205 #import <WebCore/UserAgent.h>
206 #import <WebCore/UserContentController.h>
207 #import <WebCore/UserGestureIndicator.h>
208 #import <WebCore/UserScript.h>
209 #import <WebCore/UserStyleSheet.h>
210 #import <WebCore/ValidationBubble.h>
211 #import <WebCore/WebCoreObjCExtras.h>
212 #import <WebCore/WebCoreView.h>
213 #import <WebCore/Widget.h>
214 #import <WebKitLegacy/DOM.h>
215 #import <WebKitLegacy/DOMExtensions.h>
216 #import <WebKitLegacy/DOMPrivate.h>
217 #import <mach-o/dyld.h>
218 #import <objc/runtime.h>
219 #import <pal/spi/cf/CFNetworkSPI.h>
220 #import <pal/spi/cf/CFUtilitiesSPI.h>
221 #import <pal/spi/cocoa/NSTouchBarSPI.h>
222 #import <pal/spi/cocoa/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 - (void)dealloc
664 {
665     [_dataInteractionImage release];
666     [_textRectsInBoundingRectCoordinates release];
667     [_contentImageWithHighlight release];
668     [_contentImageWithoutSelection release];
669     [_contentImage release];
670     [_estimatedBackgroundColor release];
671
672     [super dealloc];
673 }
674
675 @end
676
677 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
678
679 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(const TextIndicatorData&)indicatorData scale:(CGFloat)scale
680 {
681     if (!(self = [super init]))
682         return nil;
683     
684     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
685     _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
686     _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
687     
688     NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
689     for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
690         [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
691     _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
692     _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
693     if (indicatorData.contentImageWithHighlight)
694         _contentImageWithHighlight = [allocUIImageInstance() initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored];
695     if (indicatorData.contentImage)
696         _contentImage = [allocUIImageInstance() initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationUp];
697
698     if (indicatorData.contentImageWithoutSelection) {
699         auto nativeImage = indicatorData.contentImageWithoutSelection.get()->nativeImage();
700         if (nativeImage) {
701             _contentImageWithoutSelection = [allocUIImageInstance() initWithCGImage:nativeImage.get() scale:scale orientation:UIImageOrientationUp];
702             _contentImageWithoutSelectionRectInRootViewCoordinates = indicatorData.contentImageWithoutSelectionRectInRootViewCoordinates;
703         }
704     }
705
706     if (indicatorData.options & TextIndicatorOptionComputeEstimatedBackgroundColor)
707         _estimatedBackgroundColor = [allocUIColorInstance() initWithCGColor:cachedCGColor(indicatorData.estimatedBackgroundColor)];
708
709     return self;
710 }
711
712 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
713 {
714     if (!(self = [super init]))
715         return nil;
716     
717     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
718     
719     return self;
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     [(__bridge NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1118 }
1119
1120 - (void)_removeFromAllWebViewsSet
1121 {
1122     if (allWebViewsSet)
1123         CFSetRemoveValue(allWebViewsSet, (__bridge CFTypeRef)self);
1124 }
1125
1126 - (void)_addToAllWebViewsSet
1127 {
1128     if (!allWebViewsSet)
1129         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1130
1131     CFSetSetValue(allWebViewsSet, (__bridge CFTypeRef)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 #endif
1541
1542     [self _setIsVisible:[self _isViewVisible]];
1543
1544     WebPreferences *prefs = [self preferences];
1545     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1546                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1547
1548 #if !PLATFORM(IOS)
1549     [self _preferencesChanged:[self preferences]];
1550     [[self preferences] _postPreferencesChangedAPINotification];
1551 #else
1552     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1553     // and prefs need to be changed synchronously <rdar://problem/5841558>
1554     [self _preferencesChanged:prefs];
1555     _private->page->settings().setFontFallbackPrefersPictographs(true);
1556 #endif
1557
1558     WebInstallMemoryPressureHandler();
1559
1560 #if !PLATFORM(IOS)
1561     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1562         // Originally, we allowed all local loads.
1563         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1564     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1565         // Later, we allowed local loads for local URLs and documents loaded
1566         // with substitute data.
1567         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1568     }
1569 #endif
1570
1571 #if PLATFORM(MAC)
1572     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1573         ResourceHandle::forceContentSniffing();
1574
1575     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1576     _private->page->setUseDarkAppearance(self._effectiveAppearanceIsDark);
1577 #endif
1578
1579     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1580 }
1581
1582 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1583 {
1584     self = [super initWithFrame:f];
1585     if (!self)
1586         return nil;
1587
1588 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1589     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1590     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1591     // need for Safari to unset it to prevent it from being passed to applications it launches.
1592     // Unsetting it when a WebView is first created is as good a place as any.
1593     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1594     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1595         unsetenv("DYLD_FRAMEWORK_PATH");
1596         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1597     }
1598 #endif
1599
1600     _private = [[WebViewPrivate alloc] init];
1601     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1602     [self setMaintainsBackForwardList: YES];
1603     return self;
1604 }
1605
1606 - (void)_viewWillDrawInternal
1607 {
1608     Frame* frame = [self _mainCoreFrame];
1609     if (frame && frame->view())
1610         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1611 }
1612
1613 + (NSArray *)_supportedMIMETypes
1614 {
1615     // Load the plug-in DB allowing plug-ins to install types.
1616     [WebPluginDatabase sharedDatabase];
1617     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1618 }
1619
1620 #if !PLATFORM(IOS)
1621 + (NSArray *)_supportedFileExtensions
1622 {
1623     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1624     NSArray *MIMETypes = [self _supportedMIMETypes];
1625     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1626     NSString *MIMEType;
1627     while ((MIMEType = [enumerator nextObject]) != nil) {
1628         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1629         if (extensionsForType) {
1630             [extensions addObjectsFromArray:extensionsForType];
1631         }
1632     }
1633     NSArray *uniqueExtensions = [extensions allObjects];
1634     [extensions release];
1635     return uniqueExtensions;
1636 }
1637 #endif
1638
1639 #if PLATFORM(IOS)
1640 + (void)enableWebThread
1641 {
1642     static BOOL isWebThreadEnabled = NO;
1643     if (!isWebThreadEnabled) {
1644         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1645         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1646         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1647         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1648         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1649         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1650         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1651         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1652         WebCoreObjCDeallocOnWebThread([WebView class]);
1653         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1654         WebThreadEnable();
1655         isWebThreadEnabled = YES;
1656     }
1657 }
1658
1659 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1660 {
1661     self = [super initWithFrame:frame];
1662     if (!self)
1663         return nil;
1664     
1665     _private = [[WebViewPrivate alloc] init];
1666     
1667 #ifndef NDEBUG
1668     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1669 #endif
1670     
1671     if (!preferences)
1672         preferences = [WebPreferences standardPreferences];
1673     [preferences willAddToWebView];
1674     
1675     _private->preferences = [preferences retain];
1676     _private->mainFrameDocumentReady = NO;
1677     _private->drawsBackground = YES;
1678     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1679
1680     WebFrameView *frameView = nil;
1681     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1682     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1683     [self addSubview:frameView];
1684     [frameView release];
1685
1686     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1687     _private->group->addWebView(self);
1688
1689     PageConfiguration pageConfiguration(
1690         makeUniqueRef<WebEditorClient>(self),
1691         SocketProvider::create(),
1692         LibWebRTCProvider::create(),
1693         WebCore::CacheStorageProvider::create()
1694     );
1695     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1696 #if ENABLE(DRAG_SUPPORT)
1697     pageConfiguration.dragClient = new WebDragClient(self);
1698 #endif
1699
1700 #if ENABLE(APPLE_PAY)
1701     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1702 #endif
1703
1704     pageConfiguration.backForwardClient = BackForwardList::create(self);
1705     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1706     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1707     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1708     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1709     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1710     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1711     pageConfiguration.userContentProvider = &_private->group->userContentController();
1712     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1713     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1714
1715     _private->page = new Page(WTFMove(pageConfiguration));
1716     
1717     [self setSmartInsertDeleteEnabled:YES];
1718     
1719     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1720     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1721     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1722     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1723     _private->page->settings().setMinimumLogicalFontSize(9);
1724     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1725     _private->page->settings().setDefaultFixedFontSize(13);
1726     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1727     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1728     
1729     _private->page->settings().setFontFallbackPrefersPictographs(true);
1730     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1731     
1732     _private->page->settings().setScriptMarkupEnabled(false);
1733     _private->page->settings().setScriptEnabled(true);
1734     
1735     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1736     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1737     
1738     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1739     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1740
1741     // This is a workaround for <rdar://problem/21309911>.
1742     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1743
1744     _private->page->setGroupName(groupName);
1745
1746 #if ENABLE(REMOTE_INSPECTOR)
1747     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1748 #endif
1749     
1750     [self _updateScreenScaleFromWindow];
1751     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1752     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1753
1754     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1755     
1756     [self _addToAllWebViewsSet];
1757     
1758     ++WebViewCount;
1759     
1760     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1761     
1762     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled(self.preferences.attachmentElementEnabled);
1763
1764     return self;
1765 }
1766
1767 + (void)_releaseMemoryNow
1768 {
1769     WebThreadRun(^{
1770         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1771     });
1772 }
1773
1774 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1775 {
1776     Frame* frame = [self _mainCoreFrame];
1777     if (frame)
1778         frame->loader().history().replaceCurrentItem(core(item));
1779 }
1780
1781 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1782 {
1783     WebThreadRun(^{
1784         [WebView _releaseMemoryNow];
1785         dispatch_async(dispatch_get_main_queue(), handler);
1786     });
1787 }
1788
1789 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1790 {
1791     return WebCore::isCharacterSmartReplaceExempt(character, b);
1792 }
1793
1794 - (void)updateLayoutIgnorePendingStyleSheets
1795 {
1796     WebThreadRun(^{
1797         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1798             Document *document = frame->document();
1799             if (document)
1800                 document->updateLayoutIgnorePendingStylesheets();
1801         }
1802     });
1803 }
1804 #endif
1805
1806 #if PLATFORM(IOS)
1807
1808 #if ENABLE(DRAG_SUPPORT)
1809
1810 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1811 {
1812     WebThreadLock();
1813     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1814 }
1815
1816 - (void)_startDrag:(const DragItem&)dragItem
1817 {
1818     auto& dragImage = dragItem.image;
1819     auto image = dragImage.get().get();
1820     auto indicatorData = dragImage.indicatorData();
1821
1822     if (indicatorData)
1823         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1824     else
1825         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1826     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1827     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1828     _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1829     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1830 }
1831
1832 - (CGRect)_dataInteractionCaretRect
1833 {
1834     WebThreadLock();
1835     if (auto* page = _private->page)
1836         return page->dragCaretController().caretRectInRootViewCoordinates();
1837
1838     return { };
1839 }
1840
1841 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1842 {
1843     return _private->dataOperationTextIndicator.get();
1844 }
1845
1846 - (WebDragSourceAction)_dragSourceAction
1847 {
1848     return _private->dragSourceAction;
1849 }
1850
1851 - (NSString *)_draggedLinkTitle
1852 {
1853     return _private->draggedLinkTitle.get();
1854 }
1855
1856 - (NSURL *)_draggedLinkURL
1857 {
1858     return _private->draggedLinkURL.get();
1859 }
1860
1861 - (CGRect)_draggedElementBounds
1862 {
1863     return _private->dragPreviewFrameInRootViewCoordinates;
1864 }
1865
1866 - (WebUITextIndicatorData *)_getDataInteractionData
1867 {
1868     return _private->textIndicatorData.get();
1869 }
1870
1871 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1872 {
1873     return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1874 }
1875
1876 - (DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1877 {
1878     auto dragOperationMask = static_cast<DragOperation>(operation);
1879     auto dragDestinationMask = static_cast<DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1880     return { session, roundedIntPoint(clientPosition), roundedIntPoint(globalPosition), dragOperationMask, DragApplicationNone, dragDestinationMask };
1881 }
1882
1883 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1884 {
1885     WebThreadLock();
1886     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1887     return _private->page->dragController().dragEntered(dragData);
1888 }
1889
1890 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1891 {
1892     WebThreadLock();
1893     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1894     return _private->page->dragController().dragUpdated(dragData);
1895 }
1896 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1897 {
1898     WebThreadLock();
1899     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1900     _private->page->dragController().dragExited(dragData);
1901 }
1902 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1903 {
1904     [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1905 }
1906
1907 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1908 {
1909     WebThreadLock();
1910     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1911     return _private->page->dragController().performDragOperation(dragData);
1912 }
1913
1914 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1915 {
1916     WebThreadLock();
1917     _private->page->dragController().dragEnded();
1918     _private->dataOperationTextIndicator = nullptr;
1919     _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1920     _private->dragSourceAction = WebDragSourceActionNone;
1921     _private->draggedLinkTitle = nil;
1922     _private->draggedLinkURL = nil;
1923 }
1924
1925 - (void)_didConcludeEditDataInteraction
1926 {
1927     _private->dataOperationTextIndicator = nullptr;
1928     auto* page = _private->page;
1929     if (!page)
1930         return;
1931
1932     static auto defaultEditDragTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | TextIndicatorOptionRespectTextColor;
1933     auto& frame = page->focusController().focusedOrMainFrame();
1934     if (auto range = frame.selection().selection().toNormalizedRange()) {
1935         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
1936             _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1937     }
1938 }
1939
1940 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1941
1942 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1943 {
1944     return NO;
1945 }
1946
1947 - (WebUITextIndicatorData *)_getDataInteractionData
1948 {
1949     return nil;
1950 }
1951
1952 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1953 {
1954     return nil;
1955 }
1956
1957 - (NSUInteger)_dragSourceAction
1958 {
1959     return 0;
1960 }
1961
1962 - (NSString *)_draggedLinkTitle
1963 {
1964     return nil;
1965 }
1966
1967 - (NSURL *)_draggedLinkURL
1968 {
1969     return nil;
1970 }
1971
1972 - (CGRect)_draggedElementBounds
1973 {
1974     return CGRectNull;
1975 }
1976
1977 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1978 {
1979     return 0;
1980 }
1981
1982 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1983 {
1984     return 0;
1985 }
1986
1987 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1988 {
1989 }
1990
1991 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1992 {
1993 }
1994
1995 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1996 {
1997     return NO;
1998 }
1999
2000 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2001 {
2002 }
2003
2004 - (CGRect)_dataInteractionCaretRect
2005 {
2006     return CGRectNull;
2007 }
2008
2009 #endif
2010 #endif // PLATFORM(IOS)
2011
2012 static NSMutableSet *knownPluginMIMETypes()
2013 {
2014     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2015     
2016     return mimeTypes;
2017 }
2018
2019 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2020 {
2021     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2022     [knownPluginMIMETypes() addObject:MIMEType];
2023 }
2024
2025 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2026 {
2027     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2028     [knownPluginMIMETypes() removeObject:MIMEType];
2029 }
2030
2031 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2032 {
2033     MIMEType = [MIMEType lowercaseString];
2034     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2035     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2036
2037 #if PLATFORM(IOS)
2038 #define WebPDFView ([WebView _getPDFViewClass])
2039 #endif
2040     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2041 #if PLATFORM(IOS)
2042 #undef WebPDFView
2043 #endif
2044         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2045
2046         if (allowPlugins) {
2047             // Load the plug-in DB allowing plug-ins to install types.
2048             [WebPluginDatabase sharedDatabase];
2049         }
2050
2051         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2052         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2053         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2054     }
2055     
2056     if (viewClass && repClass) {
2057         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2058             // Special-case WebHTMLView for text types that shouldn't be shown.
2059             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2060                 return NO;
2061
2062             // If the MIME type is a known plug-in we might not want to load it.
2063             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2064                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2065                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2066                 
2067                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2068                 if (!isSupportedByWebKit)
2069                     return NO;
2070             }
2071         }
2072         if (vClass)
2073             *vClass = viewClass;
2074         if (rClass)
2075             *rClass = repClass;
2076         return YES;
2077     }
2078     
2079     return NO;
2080 }
2081
2082 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2083 {
2084     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2085         return YES;
2086 #if !PLATFORM(IOS)
2087     if (_private->pluginDatabase) {
2088         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2089         if (pluginPackage) {
2090             if (vClass)
2091                 *vClass = [WebHTMLView class];
2092             if (rClass)
2093                 *rClass = [WebHTMLRepresentation class];
2094             return YES;
2095         }
2096     }
2097 #endif
2098     return NO;
2099 }
2100
2101 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2102 {
2103     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
2104 }
2105
2106 + (BOOL)canCloseAllWebViews
2107 {
2108     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2109 }
2110
2111 + (void)closeAllWebViews
2112 {
2113     DOMWindow::dispatchAllPendingUnloadEvents();
2114
2115     // This will close the WebViews in a random order. Change this if close order is important.
2116     for (WebView *webView in [(__bridge NSSet *)allWebViewsSet allObjects])
2117         [webView close];
2118 }
2119
2120 + (BOOL)canShowFile:(NSString *)path
2121 {
2122     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2123 }
2124
2125 #if !PLATFORM(IOS)
2126 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2127 {
2128     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2129 }
2130 #endif
2131
2132 - (BOOL)_isClosed
2133 {
2134     return !_private || _private->closed;
2135 }
2136
2137 #if PLATFORM(IOS)
2138
2139 - (void)_dispatchUnloadEvent
2140 {
2141     WebThreadRun(^{
2142         WebFrame *mainFrame = [self mainFrame];
2143         Frame *coreMainFrame = core(mainFrame);
2144         if (coreMainFrame) {
2145             Document *document = coreMainFrame->document();
2146             if (document)
2147                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
2148         }
2149     });
2150 }
2151
2152 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2153 {
2154     auto* mainFrame = [self _mainCoreFrame];
2155     if (!mainFrame)
2156         return nil;
2157     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2158     if (!editingStyle)
2159         return nil;
2160     auto* style = editingStyle->style();
2161     if (!style)
2162         return nil;
2163     return kit(&style->ensureCSSStyleDeclaration());
2164 }
2165
2166 - (NSUInteger)_renderTreeSize
2167 {
2168     if (!_private->page)
2169         return 0;
2170     return _private->page->renderTreeSize();
2171 }
2172
2173 - (void)_dispatchTileDidDraw:(CALayer*)tile
2174 {
2175     id mailDelegate = [self _webMailDelegate];
2176     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2177         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2178         return;
2179     }
2180
2181 #pragma clang diagnostic push
2182 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2183     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2184         return;
2185 #pragma clang diagnostic pop
2186
2187     WebThreadLock();
2188
2189     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2190 }
2191
2192 - (void)_willStartScrollingOrZooming
2193 {
2194     // Pause timers during top level interaction
2195     if (_private->mainViewIsScrollingOrZooming)
2196         return;
2197     _private->mainViewIsScrollingOrZooming = YES;
2198
2199     [self hideFormValidationMessage];
2200
2201     // This suspends active DOM objects like timers, but not media.
2202     [[self mainFrame] setTimeoutsPaused:YES];
2203
2204     // This defers loading callbacks only.
2205     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2206     [self setDefersCallbacks:YES];
2207 }
2208
2209 - (void)_didFinishScrollingOrZooming
2210 {
2211     if (!_private->mainViewIsScrollingOrZooming)
2212         return;
2213     _private->mainViewIsScrollingOrZooming = NO;
2214     [self setDefersCallbacks:NO];
2215     [[self mainFrame] setTimeoutsPaused:NO];
2216     if (FrameView* view = [self _mainCoreFrame]->view())
2217         view->resumeVisibleImageAnimationsIncludingSubframes();
2218 }
2219
2220 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2221 {
2222     if (suspend)
2223         webResourceLoadScheduler().suspendPendingRequests();
2224     else
2225         webResourceLoadScheduler().resumePendingRequests();
2226 }
2227
2228 + (BOOL)_isUnderMemoryPressure
2229 {
2230     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2231 }
2232
2233 #endif // PLATFORM(IOS)
2234
2235 - (void)_closePluginDatabases
2236 {
2237     pluginDatabaseClientCount--;
2238
2239     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2240
2241 #if !PLATFORM(IOS)
2242     // Unload the WebView local plug-in database. 
2243     if (_private->pluginDatabase) {
2244         [_private->pluginDatabase destroyAllPluginInstanceViews];
2245         [_private->pluginDatabase close];
2246         [_private->pluginDatabase release];
2247         _private->pluginDatabase = nil;
2248     }
2249 #endif
2250     
2251     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2252     if (!pluginDatabaseClientCount && applicationIsTerminating)
2253         [WebPluginDatabase closeSharedDatabase];
2254 }
2255
2256 - (void)_closeWithFastTeardown 
2257 {
2258 #ifndef NDEBUG
2259     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2260 #endif
2261
2262 #if !PLATFORM(IOS)
2263     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2264 #endif
2265     [[NSNotificationCenter defaultCenter] removeObserver:self];
2266
2267     [self _closePluginDatabases];
2268 }
2269
2270 static bool fastDocumentTeardownEnabled()
2271 {
2272 #ifdef NDEBUG
2273     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2274 #else
2275     static bool initialized = false;
2276     static bool enabled = false;
2277     if (!initialized) {
2278         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2279         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2280         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2281         if (setting)
2282             enabled = ![setting boolValue];
2283         initialized = true;
2284     }
2285 #endif
2286     return enabled;
2287 }
2288
2289 // _close is here only for backward compatibility; clients and subclasses should use
2290 // public method -close instead.
2291 - (void)_close
2292 {
2293 #if PLATFORM(IOS)
2294     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2295     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2296
2297     [self _clearDelegates];
2298
2299     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2300     WebThreadRun(^{
2301 #endif            
2302
2303     if (!_private || _private->closed)
2304         return;
2305
2306     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2307
2308     _private->closed = YES;
2309     [self _removeFromAllWebViewsSet];
2310
2311 #ifndef NDEBUG
2312     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2313 #endif
2314
2315     // To quit the apps fast we skip document teardown, except plugins
2316     // need to be destroyed and unloaded.
2317     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2318         [self _closeWithFastTeardown];
2319         return;
2320     }
2321
2322 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2323     [self _exitVideoFullscreen];
2324 #endif
2325
2326 #if PLATFORM(IOS)
2327     _private->closing = YES;
2328 #endif
2329
2330     if (Frame* mainFrame = [self _mainCoreFrame])
2331         mainFrame->loader().detachFromParent();
2332
2333     [self setHostWindow:nil];
2334
2335 #if !PLATFORM(IOS)
2336     [self setDownloadDelegate:nil];
2337     [self setEditingDelegate:nil];
2338     [self setFrameLoadDelegate:nil];
2339     [self setPolicyDelegate:nil];
2340     [self setResourceLoadDelegate:nil];
2341     [self setScriptDebugDelegate:nil];
2342     [self setUIDelegate:nil];
2343
2344     [_private->inspector inspectedWebViewClosed];
2345 #endif
2346 #if PLATFORM(MAC)
2347     [_private->immediateActionController webViewClosed];
2348 #endif
2349
2350 #if !PLATFORM(IOS)
2351     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2352     [self removeDragCaret];
2353 #endif
2354
2355     _private->group->removeWebView(self);
2356
2357     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2358     // all the plug-ins in the page cache to break any retain cycles.
2359     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2360     Page* page = _private->page;
2361     _private->page = nullptr;
2362     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2363
2364 #if !PLATFORM(IOS)
2365     if (_private->hasSpellCheckerDocumentTag) {
2366         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2367         _private->hasSpellCheckerDocumentTag = NO;
2368     }
2369 #endif
2370
2371     if (_private->layerFlushController) {
2372         _private->layerFlushController->invalidate();
2373         _private->layerFlushController = nullptr;
2374     }
2375
2376     [[self _notificationProvider] unregisterWebView:self];
2377
2378 #if !PLATFORM(IOS)
2379     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2380 #endif
2381     [[NSNotificationCenter defaultCenter] removeObserver:self];
2382
2383     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2384
2385     WebPreferences *preferences = _private->preferences;
2386     _private->preferences = nil;
2387     [preferences didRemoveFromWebView];
2388     [preferences release];
2389
2390     [self _closePluginDatabases];
2391
2392 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2393     if (_private->m_playbackTargetPicker) {
2394         _private->m_playbackTargetPicker->invalidate();
2395         _private->m_playbackTargetPicker = nullptr;
2396     }
2397 #endif
2398
2399 #ifndef NDEBUG
2400     // Need this to make leak messages accurate.
2401     if (applicationIsTerminating) {
2402         WebCore::GCController::singleton().garbageCollectNow();
2403         [WebCache setDisabled:YES];
2404     }
2405 #endif
2406 #if PLATFORM(IOS)
2407     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2408     });
2409 #endif            
2410 }
2411
2412 // Indicates if the WebView is in the midst of a user gesture.
2413 - (BOOL)_isProcessingUserGesture
2414 {
2415     return UserGestureIndicator::processingUserGesture();
2416 }
2417
2418 + (NSString *)_MIMETypeForFile:(NSString *)path
2419 {
2420 #if !PLATFORM(IOS)
2421     NSString *extension = [path pathExtension];
2422 #endif
2423     NSString *MIMEType = nil;
2424
2425 #if !PLATFORM(IOS)
2426     // Get the MIME type from the extension.
2427     if ([extension length] != 0) {
2428         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2429     }
2430 #endif
2431
2432     // If we can't get a known MIME type from the extension, sniff.
2433     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2434         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2435         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2436         [handle closeFile];
2437         if ([data length] != 0) {
2438             MIMEType = [data _webkit_guessedMIMEType];
2439         }
2440         if ([MIMEType length] == 0) {
2441             MIMEType = @"application/octet-stream";
2442         }
2443     }
2444
2445     return MIMEType;
2446 }
2447
2448 - (WebDownload *)_downloadURL:(NSURL *)URL
2449 {
2450     ASSERT(URL);
2451     
2452     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2453     WebDownload *download = [WebDownload _downloadWithRequest:request
2454                                                      delegate:_private->downloadDelegate
2455                                                     directory:nil];
2456     [request release];
2457     
2458     return download;
2459 }
2460
2461 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2462 {
2463     NSDictionary *features = [[NSDictionary alloc] init];
2464     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2465                                             createWebViewWithRequest:nil
2466                                                       windowFeatures:features];
2467     [features release];
2468     if (!newWindowWebView)
2469         return nil;
2470
2471     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2472     return newWindowWebView;
2473 }
2474
2475 + (void)_setIconLoadingEnabled:(BOOL)enabled
2476 {
2477     iconLoadingEnabled = enabled;
2478 }
2479
2480 + (BOOL)_isIconLoadingEnabled
2481 {
2482     return iconLoadingEnabled;
2483 }
2484
2485 - (WebInspector *)inspector
2486 {
2487     if (!_private->inspector)
2488         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2489     return _private->inspector;
2490 }
2491
2492 #if ENABLE(REMOTE_INSPECTOR)
2493 + (void)_enableRemoteInspector
2494 {
2495     RemoteInspector::singleton().start();
2496 }
2497
2498 + (void)_disableRemoteInspector
2499 {
2500     RemoteInspector::singleton().stop();
2501 }
2502
2503 + (void)_disableAutoStartRemoteInspector
2504 {
2505     RemoteInspector::startDisabled();
2506 }
2507
2508 + (BOOL)_isRemoteInspectorEnabled
2509 {
2510     return RemoteInspector::singleton().enabled();
2511 }
2512
2513 + (BOOL)_hasRemoteInspectorSession
2514 {
2515     return RemoteInspector::singleton().hasActiveDebugSession();
2516 }
2517
2518 - (BOOL)allowsRemoteInspection
2519 {
2520     return _private->page->remoteInspectionAllowed();
2521 }
2522
2523 - (void)setAllowsRemoteInspection:(BOOL)allow
2524 {
2525     _private->page->setRemoteInspectionAllowed(allow);
2526 }
2527
2528 - (void)setShowingInspectorIndication:(BOOL)showing
2529 {
2530 #if PLATFORM(IOS)
2531     ASSERT(WebThreadIsLocked());
2532
2533     if (showing) {
2534         if (!_private->indicateLayer) {
2535             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2536             [_private->indicateLayer setNeedsLayout];
2537             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2538         }
2539     } else {
2540         [_private->indicateLayer removeFromSuperlayer];
2541         [_private->indicateLayer release];
2542         _private->indicateLayer = nil;
2543     }
2544 #else
2545     // Implemented in WebCore::InspectorOverlay.
2546 #endif
2547 }
2548
2549 #if PLATFORM(IOS)
2550 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2551 {
2552     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2553     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2554 }
2555 #endif // PLATFORM(IOS)
2556 #endif // ENABLE(REMOTE_INSPECTOR)
2557
2558 - (WebCore::Page*)page
2559 {
2560     return _private->page;
2561 }
2562
2563 #if !PLATFORM(IOS)
2564 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2565 {
2566     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2567     NSArray *menuItems = defaultMenuItems;
2568
2569     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2570     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2571     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2572     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2573         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2574         if (!menuItems)
2575             return nil;
2576     }
2577
2578     unsigned count = [menuItems count];
2579     if (!count)
2580         return nil;
2581
2582     NSMenu *menu = [[NSMenu alloc] init];
2583     for (unsigned i = 0; i < count; i++)
2584         [menu addItem:[menuItems objectAtIndex:i]];
2585
2586     return [menu autorelease];
2587 }
2588 #endif
2589
2590 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2591 {
2592     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2593     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2594     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2595     if (!dictionary)
2596         return;
2597     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2598 }
2599
2600 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2601 {
2602     if (!_private->page)
2603         return;
2604     
2605     if (!otherView->_private->page)
2606         return;
2607     
2608     // It turns out the right combination of behavior is done with the back/forward load
2609     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2610     // in the back forward list, and go to the current one.
2611
2612     BackForwardController& backForward = _private->page->backForward();
2613     ASSERT(!backForward.currentItem()); // destination list should be empty
2614
2615     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2616     if (!otherBackForward.currentItem())
2617         return; // empty back forward list, bail
2618     
2619     HistoryItem* newItemToGoTo = nullptr;
2620
2621     int lastItemIndex = otherBackForward.forwardCount();
2622     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2623         if (i == 0) {
2624             // If this item is showing , save away its current scroll and form state,
2625             // since that might have changed since loading and it is normally not saved
2626             // until we leave that page.
2627             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2628         }
2629         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2630         if (i == 0) 
2631             newItemToGoTo = newItem.ptr();
2632         backForward.client()->addItem(WTFMove(newItem));
2633     }
2634
2635     ASSERT(newItemToGoTo);
2636     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, ShouldTreatAsContinuingLoad::No);
2637 }
2638
2639 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2640 {
2641     _private->formDelegate = delegate;
2642 #if PLATFORM(IOS)
2643     [_private->formDelegateForwarder clearTarget];
2644     [_private->formDelegateForwarder release];
2645     _private->formDelegateForwarder = nil;
2646 #endif
2647 }
2648
2649 - (id<WebFormDelegate>)_formDelegate
2650 {
2651     return _private->formDelegate;
2652 }
2653
2654 #if PLATFORM(IOS)
2655 - (id)_formDelegateForwarder
2656 {
2657     if (_private->closing)
2658         return nil;
2659
2660     if (!_private->formDelegateForwarder)
2661         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2662     return _private->formDelegateForwarder;
2663 }
2664
2665 - (id)_formDelegateForSelector:(SEL)selector
2666 {
2667     id delegate = self->_private->formDelegate;
2668     if ([delegate respondsToSelector:selector])
2669         return delegate;
2670
2671     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2672     if ([delegate respondsToSelector:selector])
2673         return delegate;
2674
2675     return nil;
2676 }
2677 #endif
2678
2679 #if !PLATFORM(IOS)
2680 - (BOOL)_needsAdobeFrameReloadingQuirk
2681 {
2682     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2683         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2684         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2685         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2686         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2687         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2688         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2689         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2690         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2691         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2692
2693     return needsQuirk;
2694 }
2695
2696 - (BOOL)_needsLinkElementTextCSSQuirk
2697 {
2698     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2699         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2700     return needsQuirk;
2701 }
2702
2703 - (BOOL)_needsFrameNameFallbackToIdQuirk
2704 {
2705     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2706     return needsQuirk;
2707 }
2708
2709 - (BOOL)_needsIsLoadingInAPISenseQuirk
2710 {
2711     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2712     
2713     return needsQuirk;
2714 }
2715
2716 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2717 {
2718     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2719     return needsQuirks;
2720 }
2721
2722 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2723 {
2724     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2725     return needsQuirk;
2726 }
2727
2728 static bool needsSelfRetainWhileLoadingQuirk()
2729 {
2730     static bool needsQuirk = MacApplication::isAperture();
2731     return needsQuirk;
2732 }
2733 #endif // !PLATFORM(IOS)
2734
2735 - (BOOL)_needsPreHTML5ParserQuirks
2736 {    
2737 #if !PLATFORM(IOS)
2738     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2739     // with the new HTML5 parser. If these applications were linked against a
2740     // version of WebKit prior to the introduction of the HTML5 parser, enable
2741     // parser quirks to maintain compatibility. For details, see 
2742     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2743     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2744     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2745         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2746     
2747     // Mail.app must continue to display HTML email that contains quirky markup.
2748     static bool isAppleMail = MacApplication::isAppleMail();
2749
2750     return isApplicationNeedingParserQuirks
2751         || isAppleMail
2752 #if ENABLE(DASHBOARD_SUPPORT)
2753         // Pre-HTML5 parser quirks are required to remain compatible with many
2754         // Dashboard widgets. See <rdar://problem/8175982>.
2755         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2756 #endif
2757         || [[self preferences] usePreHTML5ParserQuirks];
2758 #else
2759     return [[self preferences] usePreHTML5ParserQuirks];
2760 #endif
2761 }
2762
2763 - (void)_preferencesChangedNotification:(NSNotification *)notification
2764 {
2765 #if PLATFORM(IOS)
2766     // For WebViews that load synchronously, preference changes need to be propagated
2767     // down to WebCore synchronously so that loads in that WebView have the correct
2768     // up-to-date settings.
2769     if (!WebThreadIsLocked())
2770         WebThreadLock();
2771     if ([[self mainFrame] _loadsSynchronously]) {
2772 #endif
2773
2774     WebPreferences *preferences = (WebPreferences *)[notification object];
2775     [self _preferencesChanged:preferences];
2776
2777 #if PLATFORM(IOS)
2778     } else {
2779         WebThreadRun(^{
2780             // It is possible that the prefs object has already changed before the invocation could be called
2781             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2782             WebPreferences *preferences = (WebPreferences *)[notification object];
2783             if (preferences != [self preferences])
2784                 return;
2785             [self _preferencesChanged:preferences];
2786         });
2787     }
2788 #endif
2789 }
2790
2791 - (void)_preferencesChanged:(WebPreferences *)preferences
2792 {    
2793     ASSERT(preferences == [self preferences]);
2794     if (!_private->userAgentOverridden)
2795         [self _invalidateUserAgentCache];
2796
2797     // Cache this value so we don't have to read NSUserDefaults on each page load
2798     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2799
2800     // Update corresponding WebCore Settings object.
2801     if (!_private->page)
2802         return;
2803
2804 #if PLATFORM(IOS)
2805     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2806     // didOneTimeInitialization is true so that we don't initialize databases
2807     // until the first WebView has been created. This is because database
2808     // initialization current requires disk access to populate the origins
2809     // quota map and we want to do this lazily by waiting until WebKit is
2810     // used to display web content in a WebView. The possible cases are:
2811     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2812     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2813     if (didOneTimeInitialization) {
2814         if ([preferences databasesEnabled])
2815             [WebDatabaseManager sharedWebDatabaseManager];
2816         if ([preferences storageTrackerEnabled])
2817             WebKitInitializeStorageIfNecessary();
2818     }
2819 #endif
2820
2821     Settings& settings = _private->page->settings();
2822
2823     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2824     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2825     settings.setDefaultFontSize([preferences defaultFontSize]);
2826     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2827     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2828     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2829     settings.setFixedFontFamily([preferences fixedFontFamily]);
2830     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2831     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2832     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2833     settings.setJavaEnabled([preferences isJavaEnabled]);
2834     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2835     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2836     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2837     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2838     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2839     settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2840     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2841     settings.setMinimumFontSize([preferences minimumFontSize]);
2842     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2843     settings.setPictographFontFamily([preferences pictographFontFamily]);
2844     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2845     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2846
2847     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2848     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2849     settings.setSerifFontFamily([preferences serifFontFamily]);
2850     settings.setStandardFontFamily([preferences standardFontFamily]);
2851     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2852     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2853 #if PLATFORM(IOS)
2854     settings.setShouldPrintBackgrounds(true);
2855 #else
2856     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2857 #endif
2858     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2859     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2860     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2861     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2862     settings.setUsesPageCache([self usesPageCache]);
2863     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2864     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2865
2866     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2867     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2868     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2869
2870     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2871     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2872     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2873     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2874     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2875     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2876     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2877     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2878
2879     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2880     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2881     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2882     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2883     settings.setShowDebugBorders([preferences showDebugBorders]);
2884     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2885     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2886     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2887     settings.setWebGLEnabled([preferences webGLEnabled]);
2888     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2889     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2890
2891     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2892     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2893     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2894     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2895     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2896     settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2897     settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2898     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2899     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2900
2901     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2902     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2903     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2904     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2905     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2906
2907     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2908     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2909     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2910     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2911     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2912     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2913     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2914     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2915     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2916     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2917     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2918     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2919     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2920     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2921     DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2922
2923     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2924
2925     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2926     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2927     DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2928
2929     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2930
2931     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2932     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2933
2934     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2935     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2936
2937     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2938
2939     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2940     settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2941     settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2942
2943     switch ([preferences storageBlockingPolicy]) {
2944     case WebAllowAllStorage:
2945         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2946         break;
2947     case WebBlockThirdPartyStorage:
2948         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2949         break;
2950     case WebBlockAllStorage:
2951         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2952         break;
2953     }
2954
2955     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2956     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2957     settings.setColorFilterEnabled([preferences colorFilterEnabled]);
2958     settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
2959
2960 #if PLATFORM(MAC)
2961     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2962 #endif
2963
2964 #if ENABLE(RUBBER_BANDING)
2965     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2966     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2967 #endif
2968
2969 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2970     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2971 #endif
2972 #if PLATFORM(IOS)
2973     settings.setStandalone([preferences _standalone]);
2974     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2975     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2976     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2977     settings.setMaxParseDuration([preferences _maxParseDuration]);
2978     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2979     DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2980     DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2981     DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
2982 #if HAVE(AVKIT)
2983     DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
2984 #endif
2985
2986     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2987     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2988
2989     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2990     settings.setDelegatesPageScaling(true);
2991
2992 #if ENABLE(TEXT_AUTOSIZING)
2993     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2994     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2995 #endif
2996 #endif // PLATFORM(IOS)
2997
2998 #if PLATFORM(MAC)
2999     // This parses the user stylesheet synchronously so anything that may affect it should be done first.
3000     if ([preferences userStyleSheetEnabled]) {
3001         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3002         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
3003             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
3004         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3005     } else
3006         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3007
3008     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3009     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3010     settings.setNeedsFrameNameFallbackToIdQuirk([self _needsFrameNameFallbackToIdQuirk]);
3011     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3012     settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3013     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3014     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3015     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3016     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3017     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3018 #endif // PLATFORM(MAC)
3019
3020     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3021
3022 #if ENABLE(MEDIA_SOURCE)
3023     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3024 #endif
3025
3026 #if ENABLE(SERVICE_CONTROLS)
3027     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
3028     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
3029 #endif
3030
3031 #if ENABLE(VIDEO_TRACK)
3032     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
3033     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
3034     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
3035 #endif
3036
3037 #if USE(AVFOUNDATION)
3038     DeprecatedGlobalSettings::setAVFoundationEnabled([preferences isAVFoundationEnabled]);
3039     DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
3040 #endif
3041
3042 #if ENABLE(MEDIA_STREAM)
3043     DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(false);
3044     DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(true);
3045     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(false);
3046     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(false);
3047 #endif
3048
3049 #if ENABLE(WEB_RTC)
3050     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
3051     RuntimeEnabledFeatures::sharedFeatures().setWebRTCLegacyAPIEnabled([preferences webRTCLegacyAPIEnabled]);
3052 #endif
3053
3054 #if ENABLE(WEB_AUDIO)
3055     settings.setWebAudioEnabled([preferences webAudioEnabled]);
3056 #endif
3057
3058 #if ENABLE(FULLSCREEN_API)
3059     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3060 #endif
3061
3062     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3063
3064     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3065
3066     DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3067
3068     settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3069     settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3070     settings.setCrossOriginWindowPolicySupportEnabled([preferences crossOriginWindowPolicySupportEnabled]);
3071
3072 #if ENABLE(GAMEPAD)
3073     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3074 #endif
3075
3076     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3077     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3078     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3079     RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3080
3081 #if ENABLE(ATTACHMENT_ELEMENT)
3082     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3083 #endif
3084
3085     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3086     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3087     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsCSSIntegrationEnabled([preferences webAnimationsCSSIntegrationEnabled]);
3088
3089     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3090     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3091
3092 #if ENABLE(STREAMS_API)
3093     RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3094     RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3095 #endif
3096
3097 #if ENABLE(WEBGL2)
3098     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3099 #endif
3100
3101 #if ENABLE(WEBGPU)
3102     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3103 #endif
3104
3105 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3106     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3107 #endif
3108
3109     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3110
3111 #if ENABLE(INTERSECTION_OBSERVER)
3112     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3113 #endif
3114     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3115
3116     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3117     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3118     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3119     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3120     RuntimeEnabledFeatures::sharedFeatures().setWebAuthenticationEnabled(preferences.webAuthenticationEnabled);
3121     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3122     RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3123     RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3124     RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3125     RuntimeEnabledFeatures::sharedFeatures().setAriaReflectionEnabled([preferences ariaReflectionEnabled]);
3126     RuntimeEnabledFeatures::sharedFeatures().setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3127     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3128
3129 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3130     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3131 #endif
3132
3133 #if ENABLE(ENCRYPTED_MEDIA)
3134     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3135 #endif
3136
3137     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3138
3139     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3140
3141     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3142     if (timeout > 0)
3143         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3144
3145     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3146     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3147
3148     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3149     if (_private->zoomsTextOnly != zoomsTextOnly)
3150         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3151
3152 #if PLATFORM(IOS)
3153     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3154     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3155     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3156     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3157 #endif
3158
3159 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3160     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3161 #endif
3162
3163     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3164
3165     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3166
3167     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3168
3169     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3170     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3171
3172     RuntimeEnabledFeatures::sharedFeatures().setServerTimingEnabled([preferences serverTimingEnabled]);
3173 }
3174
3175 static inline IMP getMethod(id o, SEL s)
3176 {
3177     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3178 }
3179
3180 #if PLATFORM(IOS)
3181 - (id)_UIKitDelegateForwarder
3182 {
3183     if (_private->closing)
3184         return nil;
3185         
3186     if (!_private->UIKitDelegateForwarder)
3187         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3188     return _private->UIKitDelegateForwarder;
3189 }
3190 #endif
3191
3192 - (void)_cacheResourceLoadDelegateImplementations
3193 {
3194     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3195     id delegate = _private->resourceProgressDelegate;
3196
3197     if (!delegate) {
3198         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3199         return;
3200     }
3201
3202     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3203     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3204     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3205     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3206 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3207     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3208 #endif
3209
3210 #if PLATFORM(IOS)
3211     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3212     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3213     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3214     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3215     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3216     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3217     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3218     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3219     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3220 #endif
3221
3222     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3223     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3224     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3225     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3226     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3227     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3228     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3229     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3230 }
3231
3232 - (void)_cacheFrameLoadDelegateImplementations
3233 {
3234     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3235     id delegate = _private->frameLoadDelegate;
3236
3237     if (!delegate) {
3238         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3239         return;
3240     }
3241
3242     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3243     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3244     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3245     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3246     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3247 #if JSC_OBJC_API_ENABLED
3248     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3249 #endif
3250     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3251     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3252     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3253     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3254     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3255     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3256     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3257     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3258     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3259     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3260     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3261     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3262 #if ENABLE(ICONDATABASE)
3263     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3264 #endif
3265     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3266     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3267     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3268     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3269     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3270     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3271     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3272     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3273     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3274     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3275 #if PLATFORM(IOS)
3276     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3277 #endif
3278
3279     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3280     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3281     // for backwards compatibility.
3282     Page* page = core(self);
3283     if (page) {
3284         unsigned milestones = DidFirstLayout;
3285 #if PLATFORM(IOS)
3286         milestones |= DidFirstVisuallyNonEmptyLayout;
3287 #else
3288         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3289             milestones |= DidFirstVisuallyNonEmptyLayout;
3290 #endif
3291         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3292     }
3293 }
3294
3295 - (void)_cacheScriptDebugDelegateImplementations
3296 {
3297     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3298     id delegate = _private->scriptDebugDelegate;
3299
3300     if (!delegate) {
3301         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3302         return;
3303     }
3304
3305     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3306     if (cache->didParseSourceFunc)
3307         cache->didParseSourceExpectsBaseLineNumber = YES;
3308     else {
3309         cache->didParseSourceExpectsBaseLineNumber = NO;
3310         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3311     }
3312
3313     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3314
3315     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3316     if (cache->exceptionWasRaisedFunc)
3317         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3318     else {
3319         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3320         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3321     }
3322 }
3323
3324 - (void)_cacheHistoryDelegateImplementations
3325 {
3326     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3327     id delegate = _private->historyDelegate;
3328
3329     if (!delegate) {
3330         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3331         return;
3332     }
3333
3334     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3335     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3336     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3337     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3338     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3339     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3340 }
3341
3342 - (id)_policyDelegateForwarder
3343 {
3344 #if PLATFORM(IOS)
3345     if (_private->closing)
3346         return nil;
3347 #endif
3348     if (!_private->policyDelegateForwarder)
3349         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3350     return _private->policyDelegateForwarder;
3351 }
3352
3353 - (id)_UIDelegateForwarder
3354 {
3355 #if PLATFORM(IOS)
3356     if (_private->closing)
3357         return nil;
3358 #endif
3359     if (!_private->UIDelegateForwarder)
3360         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3361     return _private->UIDelegateForwarder;
3362 }
3363
3364 #if PLATFORM(IOS)
3365 - (id)_UIDelegateForSelector:(SEL)selector
3366 {
3367     id delegate = self->_private->UIDelegate;
3368     if ([delegate respondsToSelector:selector])
3369         return delegate;
3370
3371     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3372     if ([delegate respondsToSelector:selector])
3373         return delegate;
3374
3375     return nil;
3376 }
3377 #endif
3378
3379 - (id)_editingDelegateForwarder
3380 {
3381 #if PLATFORM(IOS)
3382     if (_private->closing)
3383         return nil;
3384 #endif    
3385     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3386     // Not sure if that is a bug or not.
3387     if (!_private)
3388         return nil;
3389
3390     if (!_private->editingDelegateForwarder)
3391         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3392     return _private->editingDelegateForwarder;
3393 }
3394
3395 - (void)_closeWindow
3396 {
3397     [[self _UIDelegateForwarder] webViewClose:self];
3398 }
3399
3400 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3401 {
3402     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3403     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3404     
3405     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3406     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3407     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3408     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3409 }
3410
3411 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3412 {
3413     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3414     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3415
3416     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3417     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3418     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3419     if ([viewClass class] == [WebHTMLView class])
3420         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3421     
3422     // This is used to make _representationExistsForURLScheme faster.
3423     // Without this set, we'd have to create the MIME type each time.
3424     if (schemesWithRepresentationsSet == nil) {
3425         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3426     }
3427     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3428 }
3429
3430 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3431 {
3432     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3433 }
3434
3435 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3436 {
3437     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3438 }
3439
3440 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3441 {
3442     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3443     if (!request)
3444         return NO;
3445
3446     if ([NSURLConnection canHandleRequest:request])
3447         return YES;
3448
3449     NSString *scheme = [[request URL] scheme];
3450
3451     // Representations for URL schemes work at the top level.
3452     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3453         return YES;
3454
3455     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3456         return YES;
3457
3458     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3459         return YES;
3460
3461     return NO;
3462 }
3463
3464 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3465 {
3466     return [self _canHandleRequest:request forMainFrame:YES];
3467 }
3468
3469 + (NSString *)_decodeData:(NSData *)data
3470 {
3471     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3472     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3473 }
3474
3475 - (void)_pushPerformingProgrammaticFocus
3476 {
3477     _private->programmaticFocusCount++;
3478 }
3479
3480 - (void)_popPerformingProgrammaticFocus
3481 {
3482     _private->programmaticFocusCount--;
3483 }
3484
3485 - (BOOL)_isPerformingProgrammaticFocus
3486 {
3487     return _private->programmaticFocusCount != 0;
3488 }
3489
3490 #if !PLATFORM(IOS)
3491 - (void)_didChangeValueForKey: (NSString *)key
3492 {
3493     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3494     [self didChangeValueForKey: key];
3495 }
3496
3497 - (void)_willChangeValueForKey: (NSString *)key
3498 {
3499     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3500     [self willChangeValueForKey: key];
3501 }
3502
3503 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3504     static NSSet *manualNotifyKeys = nil;
3505     if (!manualNotifyKeys)
3506         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3507             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3508             nil];
3509     if ([manualNotifyKeys containsObject:key])
3510         return NO;
3511     return YES;
3512 }
3513
3514 - (NSArray *)_declaredKeys {
3515     static NSArray *declaredKeys = nil;
3516     if (!declaredKeys)
3517         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3518             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3519     return declaredKeys;
3520 }
3521
3522 - (void)_willChangeBackForwardKeys
3523 {
3524     [self _willChangeValueForKey: _WebCanGoBackKey];
3525     [self _willChangeValueForKey: _WebCanGoForwardKey];
3526 }
3527
3528 - (void)_didChangeBackForwardKeys
3529 {
3530     [self _didChangeValueForKey: _WebCanGoBackKey];
3531     [self _didChangeValueForKey: _WebCanGoForwardKey];
3532 }
3533
3534 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3535 {
3536     if (needsSelfRetainWhileLoadingQuirk())
3537         [self retain];
3538
3539     [self _willChangeBackForwardKeys];
3540     if (frame == [self mainFrame]){
3541         // Force an observer update by sending a will/did.
3542         [self _willChangeValueForKey: _WebIsLoadingKey];
3543         [self _didChangeValueForKey: _WebIsLoadingKey];
3544
3545         [self _willChangeValueForKey: _WebMainFrameURLKey];
3546
3547         [self hideFormValidationMessage];
3548     }
3549
3550     [NSApp setWindowsNeedUpdate:YES];
3551
3552 #if ENABLE(FULLSCREEN_API)
3553     Document* document = core([frame DOMDocument]);
3554     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3555         SEL selector = @selector(webView:closeFullScreenWithListener:);
3556         if ([_private->UIDelegate respondsToSelector:selector]) {
3557             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3558             CallUIDelegate(self, selector, listener);
3559             [listener release];
3560         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3561             [_private->newFullscreenController close];
3562         }
3563     }
3564 #endif
3565 }
3566
3567 - (void)_checkDidPerformFirstNavigation
3568 {
3569     if (_private->_didPerformFirstNavigation)
3570         return;
3571
3572     Page* page = _private->page;
3573     if (!page)
3574         return;
3575
3576     auto& backForwardController = page->backForward();
3577
3578     if (!backForwardController.backItem())
3579         return;
3580
3581     _private->_didPerformFirstNavigation = YES;
3582
3583     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3584         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3585 }
3586
3587 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3588 {
3589     if (frame == [self mainFrame])
3590         [self _didChangeValueForKey: _WebMainFrameURLKey];
3591
3592     [self _checkDidPerformFirstNavigation];
3593
3594     [NSApp setWindowsNeedUpdate:YES];
3595 }
3596
3597 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3598 {
3599     if (needsSelfRetainWhileLoadingQuirk())
3600         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3601         
3602     [self _didChangeBackForwardKeys];
3603     if (frame == [self mainFrame]){
3604         // Force an observer update by sending a will/did.
3605         [self _willChangeValueForKey: _WebIsLoadingKey];
3606         [self _didChangeValueForKey: _WebIsLoadingKey];
3607     }
3608     [NSApp setWindowsNeedUpdate:YES];
3609 }
3610
3611 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3612 {
3613     if (needsSelfRetainWhileLoadingQuirk())
3614         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3615
3616     [self _didChangeBackForwardKeys];
3617     if (frame == [self mainFrame]){
3618         // Force an observer update by sending a will/did.
3619         [self _willChangeValueForKey: _WebIsLoadingKey];
3620         [self _didChangeValueForKey: _WebIsLoadingKey];
3621     }
3622     [NSApp setWindowsNeedUpdate:YES];
3623 }
3624
3625 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3626 {
3627     if (needsSelfRetainWhileLoadingQuirk())
3628         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3629
3630     [self _didChangeBackForwardKeys];
3631     if (frame == [self mainFrame]){
3632         // Force an observer update by sending a will/did.
3633         [self _willChangeValueForKey: _WebIsLoadingKey];
3634         [self _didChangeValueForKey: _WebIsLoadingKey];
3635         
3636         [self _didChangeValueForKey: _WebMainFrameURLKey];
3637     }
3638     [NSApp setWindowsNeedUpdate:YES];
3639 }
3640
3641 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3642 {
3643     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3644     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3645     NSCachedURLResponse *cachedResponse;
3646
3647     if (!_private->page)
3648         return nil;
3649
3650     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3651         cachedResponse = cachedResponseForRequest(storageSession, request.get());
3652     else
3653         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3654
3655     return cachedResponse;
3656 }
3657
3658 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3659 {
3660     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3661     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3662     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3663                         element:domElement
3664                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3665                           title:[element objectForKey:WebElementImageAltStringKey] 
3666                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3667                           types:types
3668                          source:nil];
3669 }
3670
3671 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3672 {
3673     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3674                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3675                         types:types];
3676 }
3677
3678 #if ENABLE(DRAG_SUPPORT)
3679 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3680 {
3681     if (!_private->page)
3682         return;
3683     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3684 }
3685 #endif
3686
3687 #else
3688
3689 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3690 {
3691     if (frame == [self mainFrame])
3692         _private->didDrawTiles = 0;
3693 }
3694
3695 #endif // PLATFORM(IOS)
3696
3697 #if ENABLE(DASHBOARD_SUPPORT)
3698
3699 #define DASHBOARD_CONTROL_LABEL @"control"
3700
3701 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3702 {
3703     NSRect adjustedBounds = bounds;
3704     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3705     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3706     adjustedBounds.size = bounds.size;
3707
3708     NSRect adjustedClip;
3709     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3710     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3711     adjustedClip.size = clip.size;
3712
3713     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3714         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3715     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3716     if (!scrollerRegions) {
3717         scrollerRegions = [[NSMutableArray alloc] init];
3718         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3719         [scrollerRegions release];
3720     }
3721     [scrollerRegions addObject:region];
3722     [region release];
3723 }
3724
3725 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3726 {    
3727     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3728
3729     for (const auto& widget: frameView->children()) {
3730         if (is<FrameView>(widget)) {
3731             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3732             continue;
3733         }
3734
3735         if (!widget->isScrollbar())
3736             continue;
3737
3738         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3739         // it's not common to need this to be correct in Dashboard widgets.
3740         NSRect bounds = widget->frameRect();
3741         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3742     }
3743 }
3744
3745 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3746 {
3747     // Add scroller regions for NSScroller and WebCore scrollbars
3748     NSUInteger count = [views count];
3749     for (NSUInteger i = 0; i < count; i++) {
3750         NSView *view = [views objectAtIndex:i];
3751         
3752         if ([view isKindOfClass:[WebHTMLView class]]) {
3753             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3754                 if (FrameView* coreView = coreFrame->view())
3755                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3756             }
3757         } else if ([view isKindOfClass:[NSScroller class]]) {
3758             // AppKit places absent scrollers at -100,-100
3759             if ([view frame].origin.y < 0)
3760                 continue;
3761             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3762         }
3763         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3764     }
3765 }
3766
3767 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3768 {
3769     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3770 }
3771
3772 - (NSDictionary *)_dashboardRegions
3773 {
3774     // Only return regions from main frame.
3775     Frame* mainFrame = [self _mainCoreFrame];
3776     if (!mainFrame)
3777         return nil;
3778
3779     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3780     size_t size = regions.size();
3781
3782     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3783     for (size_t i = 0; i < size; i++) {
3784         const AnnotatedRegionValue& region = regions[i];
3785
3786         if (region.type == StyleDashboardRegion::None)
3787             continue;
3788
3789         NSString *label = region.label;
3790         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3791         if (region.type == StyleDashboardRegion::Circle)
3792             type = WebDashboardRegionTypeCircle;
3793         else if (region.type == StyleDashboardRegion::Rectangle)
3794             type = WebDashboardRegionTypeRectangle;
3795         NSMutableArray *regionValues = [webRegions objectForKey:label];
3796         if (!regionValues) {
3797             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3798             [webRegions setObject:regionValues forKey:label];
3799             [regionValues release];
3800         }
3801
3802         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3803         [regionValues addObject:webRegion];
3804         [webRegion release];
3805     }
3806
3807     [self _addScrollerDashboardRegions:webRegions];
3808
3809     return webRegions;
3810 }
3811
3812 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3813 {
3814     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3815     // specific support for the backward compatibility mode flag.
3816     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3817         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3818     
3819     switch (behavior) {
3820         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3821             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3822             break;
3823         }
3824         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3825             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3826             break;
3827         }
3828         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3829             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3830             break;
3831         }
3832         case WebDashboardBehaviorAllowWheelScrolling: {
3833             _private->dashboardBehaviorAllowWheelScrolling = flag;
3834             break;
3835         }
3836         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3837             if (_private->page)
3838                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3839 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3840             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3841 #endif
3842             break;
3843         }
3844     }
3845
3846     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3847     // compatibility mode. See <rdar://problem/8175982>.
3848     if (_private->page)
3849         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3850 }
3851
3852 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3853 {
3854     switch (behavior) {
3855         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3856             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3857         }
3858         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3859             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3860         }
3861         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3862             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3863         }
3864         case WebDashboardBehaviorAllowWheelScrolling: {
3865             return _private->dashboardBehaviorAllowWheelScrolling;
3866         }
3867         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3868             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3869         }
3870     }
3871     return NO;
3872 }
3873
3874 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3875
3876 + (void)_setShouldUseFontSmoothing:(BOOL)f
3877 {
3878     FontCascade::setShouldUseSmoothing(f);
3879 }
3880
3881 + (BOOL)_shouldUseFontSmoothing
3882 {
3883     return FontCascade::shouldUseSmoothing();
3884 }
3885
3886 #if !PLATFORM(IOS)
3887 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3888 {
3889     setUsesTestModeFocusRingColor(f);
3890 }
3891
3892 + (BOOL)_usesTestModeFocusRingColor
3893 {
3894     return usesTestModeFocusRingColor();
3895 }
3896 #endif
3897
3898 #if PLATFORM(IOS)
3899 - (void)_setUIKitDelegate:(id)delegate
3900 {
3901     _private->UIKitDelegate = delegate;
3902     [_private->UIKitDelegateForwarder clearTarget];
3903     [_private->UIKitDelegateForwarder release];
3904     _private->UIKitDelegateForwarder = nil;
3905 }
3906
3907 - (id)_UIKitDelegate
3908 {
3909     return _private->UIKitDelegate;
3910 }
3911
3912 - (void)setWebMailDelegate:(id)delegate
3913 {
3914     _private->WebMailDelegate = delegate;
3915 }
3916
3917 - (id)_webMailDelegate
3918 {
3919     return _private->WebMailDelegate;
3920 }
3921
3922 - (id <WebCaretChangeListener>)caretChangeListener
3923 {
3924     return _private->_caretChangeListener;
3925 }
3926
3927 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3928 {
3929     _private->_caretChangeListener = listener;
3930 }
3931
3932 - (NSSet *)caretChangeListeners
3933 {
3934     return _private->_caretChangeListeners;
3935 }
3936
3937 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3938 {
3939     if (_private->_caretChangeListeners == nil) {
3940         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3941     }
3942     
3943     [_private->_caretChangeListeners addObject:listener];
3944 }
3945
3946 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3947 {
3948     [_private->_caretChangeListeners removeObject:listener];
3949 }
3950
3951 - (void)removeAllCaretChangeListeners
3952 {
3953     [_private->_caretChangeListeners removeAllObjects];
3954 }
3955
3956 - (void)caretChanged
3957 {
3958     [_private->_caretChangeListener caretChanged];
3959     NSSet *copy = [_private->_caretChangeListeners copy];
3960     for (id <WebCaretChangeListener> listener in copy) {
3961         [listener caretChanged];
3962     }
3963     [copy release];
3964 }
3965
3966 - (void)_clearDelegates
3967 {
3968     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3969     
3970     [self _setFormDelegate:nil];
3971     [self _setUIKitDelegate:nil];
3972     [self setCaretChangeListener:nil];
3973     [self removeAllCaretChangeListeners];
3974     [self setWebMailDelegate:nil];
3975     
3976     [self setDownloadDelegate:nil];
3977     [self setEditingDelegate:nil]; 
3978     [self setFrameLoadDelegate:nil];
3979     [self setPolicyDelegate:nil];
3980     [self setResourceLoadDelegate:nil];
3981     [self setScriptDebugDelegate:nil];
3982     [self setUIDelegate:nil];     
3983 }
3984
3985 - (NSURL *)_displayURL
3986 {
3987     WebThreadLock();
3988     WebFrame *frame = [self mainFrame];
3989     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3990     WebDataSource *dataSource = [frame provisionalDataSource];
3991     if (!dataSource)
3992         dataSource = [frame dataSource];
3993     NSURL *unreachableURL = [dataSource unreachableURL];
3994     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3995     [[URL retain] autorelease];
3996     return URL;
3997 }
3998 #endif // PLATFORM(IOS)
3999
4000 #if !PLATFORM(IOS)
4001 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
4002 {
4003     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4004     if (flag) {
4005         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4006     } else {
4007         [scrollview setVerticalScrollingModeLocked:NO];
4008         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
4009     }
4010 }
4011
4012 - (BOOL)alwaysShowVerticalScroller
4013 {
4014     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4015     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
4016 }
4017
4018 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
4019 {
4020     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4021     if (flag) {
4022         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4023     } else {
4024         [scrollview setHorizontalScrollingModeLocked:NO];
4025         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
4026     }
4027 }
4028
4029 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
4030 {
4031     if (Frame* mainFrame = [self _mainCoreFrame])
4032         mainFrame->view()->setProhibitsScrolling(prohibits);
4033 }
4034
4035 - (BOOL)alwaysShowHorizontalScroller
4036 {
4037     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4038     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
4039 }
4040 #endif // !PLATFORM(IOS)
4041
4042 - (void)_setUseFastImageScalingMode:(BOOL)flag
4043 {
4044     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
4045         _private->page->setInLowQualityImageInterpolationMode(flag);
4046         [self setNeedsDisplay:YES];
4047     }
4048 }
4049
4050 - (BOOL)_inFastImageScalingMode
4051 {
4052     if (_private->page)
4053         return _private->page->inLowQualityImageInterpolationMode();
4054     return NO;
4055 }
4056
4057 - (BOOL)_cookieEnabled
4058 {
4059     if (_private->page)
4060         return _private->page->settings().cookieEnabled();
4061     return YES;
4062 }
4063
4064 - (void)_setCookieEnabled:(BOOL)enable
4065 {
4066     if (_private->page)
4067         _private->page->settings().setCookieEnabled(enable);
4068 }
4069
4070 #if !PLATFORM(IOS)
4071 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
4072 {
4073     if (!_private->pluginDatabase)
4074         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
4075         
4076     [_private->pluginDatabase setPlugInPaths:newPaths];
4077     [_private->pluginDatabase refresh];
4078 }
4079 #endif
4080
4081 #if PLATFORM(IOS)
4082 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
4083 {
4084     // Ask plug-ins in this frame
4085     id <WebDocumentView> documentView = [[frame frameView] documentView];
4086     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
4087         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
4088             return YES;
4089     }
4090
4091     // Ask plug-ins in child frames
4092     NSArray *childFrames = [frame childFrames];
4093     unsigned childCount = [childFrames count];
4094     unsigned childIndex;
4095     for (childIndex = 0; childIndex < childCount; childIndex++) {
4096         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
4097             return YES;
4098     }
4099     
4100     return NO;
4101 }
4102
4103 - (BOOL)_pluginsAreRunning
4104 {
4105     WebThreadLock();
4106     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
4107 }
4108
4109 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
4110 {
4111     // Send the message to plug-ins in this frame
4112     id <WebDocumentView> documentView = [[frame frameView] documentView];
4113     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
4114         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
4115
4116     // Send the message to plug-ins in child frames
4117     NSArray *childFrames = [frame childFrames];
4118     unsigned childCount = [childFrames count];
4119     unsigned childIndex;
4120     for (childIndex = 0; childIndex < childCount; childIndex++) {
4121         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
4122     }
4123 }
4124
4125 - (void)_destroyAllPlugIns
4126 {
4127     WebThreadLock();
4128     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
4129 }
4130
4131 - (void)_startAllPlugIns
4132 {
4133     WebThreadLock();
4134     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
4135 }
4136
4137 - (void)_stopAllPlugIns
4138 {
4139     WebThreadLock();
4140     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
4141 }
4142
4143 - (void)_stopAllPlugInsForPageCache
4144 {
4145     WebThreadLock();
4146     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
4147 }
4148
4149 - (void)_restorePlugInsFromCache
4150 {
4151     WebThreadLock();
4152     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
4153 }
4154
4155 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
4156 {
4157     WebThreadLock();