Add IGNORE_WARNING_.* macros
[WebKit-https.git] / Source / WebKitLegacy / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2018 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "BackForwardList.h"
35 #import "DOMCSSStyleDeclarationInternal.h"
36 #import "DOMDocumentInternal.h"
37 #import "DOMInternal.h"
38 #import "DOMNodeInternal.h"
39 #import "DOMRangeInternal.h"
40 #import "StorageThread.h"
41 #import "WebAlternativeTextClient.h"
42 #import "WebApplicationCacheInternal.h"
43 #import "WebArchive.h"
44 #import "WebBackForwardListInternal.h"
45 #import "WebBaseNetscapePluginView.h"
46 #import "WebCache.h"
47 #import "WebChromeClient.h"
48 #import "WebDOMOperationsPrivate.h"
49 #import "WebDataSourceInternal.h"
50 #import "WebDatabaseManagerPrivate.h"
51 #import "WebDatabaseProvider.h"
52 #import "WebDefaultEditingDelegate.h"
53 #import "WebDefaultPolicyDelegate.h"
54 #import "WebDefaultUIDelegate.h"
55 #import "WebDelegateImplementationCaching.h"
56 #import "WebDeviceOrientationClient.h"
57 #import "WebDeviceOrientationProvider.h"
58 #import "WebDocument.h"
59 #import "WebDocumentInternal.h"
60 #import "WebDownload.h"
61 #import "WebDragClient.h"
62 #import "WebDynamicScrollBarsViewInternal.h"
63 #import "WebEditingDelegate.h"
64 #import "WebEditorClient.h"
65 #import "WebFormDelegatePrivate.h"
66 #import "WebFrameInternal.h"
67 #import "WebFrameLoaderClient.h"
68 #import "WebFrameNetworkingContext.h"
69 #import "WebFrameViewInternal.h"
70 #import "WebGeolocationClient.h"
71 #import "WebGeolocationPositionInternal.h"
72 #import "WebHTMLRepresentation.h"
73 #import "WebHTMLViewInternal.h"
74 #import "WebHistoryItemInternal.h"
75 #import "WebIconDatabase.h"
76 #import "WebInspector.h"
77 #import "WebInspectorClient.h"
78 #import "WebKitErrors.h"
79 #import "WebKitFullScreenListener.h"
80 #import "WebKitLogging.h"
81 #import "WebKitNSStringExtras.h"
82 #import "WebKitStatisticsPrivate.h"
83 #import "WebKitVersionChecks.h"
84 #import "WebLocalizableStrings.h"
85 #import "WebNSDataExtras.h"
86 #import "WebNSDataExtrasPrivate.h"
87 #import "WebNSDictionaryExtras.h"
88 #import "WebNSURLExtras.h"
89 #import "WebNSURLRequestExtras.h"
90 #import "WebNSViewExtras.h"
91 #import "WebNodeHighlight.h"
92 #import "WebNotificationClient.h"
93 #import "WebPDFView.h"
94 #import "WebPaymentCoordinatorClient.h"
95 #import "WebPlatformStrategies.h"
96 #import "WebPluginDatabase.h"
97 #import "WebPluginInfoProvider.h"
98 #import "WebPolicyDelegate.h"
99 #import "WebPreferenceKeysPrivate.h"
100 #import "WebPreferencesPrivate.h"
101 #import "WebProgressTrackerClient.h"
102 #import "WebResourceLoadScheduler.h"
103 #import "WebScriptDebugDelegate.h"
104 #import "WebScriptWorldInternal.h"
105 #import "WebSelectionServiceController.h"
106 #import "WebStorageManagerInternal.h"
107 #import "WebStorageNamespaceProvider.h"
108 #import "WebTextCompletionController.h"
109 #import "WebTextIterator.h"
110 #import "WebUIDelegate.h"
111 #import "WebUIDelegatePrivate.h"
112 #import "WebValidationMessageClient.h"
113 #import "WebViewGroup.h"
114 #import "WebVisitedLinkStore.h"
115 #import <CoreFoundation/CFSet.h>
116 #import <Foundation/NSURLConnection.h>
117 #import <JavaScriptCore/APICast.h>
118 #import <JavaScriptCore/ArrayPrototype.h>
119 #import <JavaScriptCore/CatchScope.h>
120 #import <JavaScriptCore/DateInstance.h>
121 #import <JavaScriptCore/Exception.h>
122 #import <JavaScriptCore/InitializeThreading.h>
123 #import <JavaScriptCore/JSCJSValue.h>
124 #import <JavaScriptCore/JSLock.h>
125 #import <JavaScriptCore/JSValueRef.h>
126 #import <WebCore/AlternativeTextUIController.h>
127 #import <WebCore/ApplicationCacheStorage.h>
128 #import <WebCore/BackForwardController.h>
129 #import <WebCore/CSSAnimationController.h>
130 #import <WebCore/CacheStorageProvider.h>
131 #import <WebCore/Chrome.h>
132 #import <WebCore/ColorMac.h>
133 #import <WebCore/DatabaseManager.h>
134 #import <WebCore/DeprecatedGlobalSettings.h>
135 #import <WebCore/DictionaryLookup.h>
136 #import <WebCore/Document.h>
137 #import <WebCore/DocumentLoader.h>
138 #import <WebCore/DragController.h>
139 #import <WebCore/DragData.h>
140 #import <WebCore/DragItem.h>
141 #import <WebCore/Editing.h>
142 #import <WebCore/Editor.h>
143 #import <WebCore/Event.h>
144 #import <WebCore/EventHandler.h>
145 #import <WebCore/FileSystem.h>
146 #import <WebCore/FocusController.h>
147 #import <WebCore/FontCache.h>
148 #import <WebCore/Frame.h>
149 #import <WebCore/FrameLoader.h>
150 #import <WebCore/FrameSelection.h>
151 #import <WebCore/FrameTree.h>
152 #import <WebCore/FrameView.h>
153 #import <WebCore/GCController.h>
154 #import <WebCore/GameControllerGamepadProvider.h>
155 #import <WebCore/GeolocationController.h>
156 #import <WebCore/GeolocationError.h>
157 #import <WebCore/HTMLNames.h>
158 #import <WebCore/HTMLOListElement.h>
159 #import <WebCore/HTMLUListElement.h>
160 #import <WebCore/HTMLVideoElement.h>
161 #import <WebCore/HistoryController.h>
162 #import <WebCore/HistoryItem.h>
163 #import <WebCore/JSCSSStyleDeclaration.h>
164 #import <WebCore/JSDocument.h>
165 #import <WebCore/JSElement.h>
166 #import <WebCore/JSNodeList.h>
167 #import <WebCore/JSNotification.h>
168 #import <WebCore/LegacyNSPasteboardTypes.h>
169 #import <WebCore/LibWebRTCProvider.h>
170 #import <WebCore/LocalizedStrings.h>
171 #import <WebCore/LogInitialization.h>
172 #import <WebCore/MIMETypeRegistry.h>
173 #import <WebCore/MemoryCache.h>
174 #import <WebCore/MemoryRelease.h>
175 #import <WebCore/NetworkStorageSession.h>
176 #import <WebCore/NodeList.h>
177 #import <WebCore/Notification.h>
178 #import <WebCore/NotificationController.h>
179 #import <WebCore/Page.h>
180 #import <WebCore/PageCache.h>
181 #import <WebCore/PageConfiguration.h>
182 #import <WebCore/PageGroup.h>
183 #import <WebCore/PathUtilities.h>
184 #import <WebCore/PlatformEventFactoryMac.h>
185 #import <WebCore/ProgressTracker.h>
186 #import <WebCore/RenderTheme.h>
187 #import <WebCore/RenderView.h>
188 #import <WebCore/RenderWidget.h>
189 #import <WebCore/ResourceHandle.h>
190 #import <WebCore/ResourceLoadObserver.h>
191 #import <WebCore/ResourceRequest.h>
192 #import <WebCore/RuntimeApplicationChecks.h>
193 #import <WebCore/RuntimeEnabledFeatures.h>
194 #import <WebCore/SchemeRegistry.h>
195 #import <WebCore/ScriptController.h>
196 #import <WebCore/SecurityOrigin.h>
197 #import <WebCore/SecurityPolicy.h>
198 #import <WebCore/Settings.h>
199 #import <WebCore/ShouldTreatAsContinuingLoad.h>
200 #import <WebCore/SocketProvider.h>
201 #import <WebCore/StyleProperties.h>
202 #import <WebCore/TextResourceDecoder.h>
203 #import <WebCore/ThreadCheck.h>
204 #import <WebCore/UserAgent.h>
205 #import <WebCore/UserContentController.h>
206 #import <WebCore/UserGestureIndicator.h>
207 #import <WebCore/UserScript.h>
208 #import <WebCore/UserStyleSheet.h>
209 #import <WebCore/ValidationBubble.h>
210 #import <WebCore/WebCoreObjCExtras.h>
211 #import <WebCore/WebCoreView.h>
212 #import <WebCore/Widget.h>
213 #import <WebKitLegacy/DOM.h>
214 #import <WebKitLegacy/DOMExtensions.h>
215 #import <WebKitLegacy/DOMPrivate.h>
216 #import <mach-o/dyld.h>
217 #import <objc/runtime.h>
218 #import <pal/spi/cf/CFNetworkSPI.h>
219 #import <pal/spi/cf/CFUtilitiesSPI.h>
220 #import <pal/spi/cocoa/NSTouchBarSPI.h>
221 #import <pal/spi/cocoa/NSURLDownloadSPI.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.add(CaseInsensitive);
575     if (options & WebFindOptionsAtWordStarts)
576         findOptions.add(AtWordStarts);
577     if (options & WebFindOptionsTreatMedialCapitalAsWordStart)
578         findOptions.add(TreatMedialCapitalAsWordStart);
579     if (options & WebFindOptionsBackwards)
580         findOptions.add(Backwards);
581     if (options & WebFindOptionsWrapAround)
582         findOptions.add(WrapAround);
583     if (options & WebFindOptionsStartInSelection)
584         findOptions.add(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     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
869     id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
870     NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
871     ASSERT(segments.count == 3);
872     [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
873     [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
874     [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
875     ALLOW_DEPRECATED_DECLARATIONS_END
876
877     self.view = insertListControl;
878
879     return self;
880 }
881
882 - (void)_selectList:(id)sender
883 {
884     NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
885     if (![documentView isKindOfClass:[WebHTMLView class]])
886         return;
887
888     WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
889     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
890     switch (insertListControl.selectedSegment) {
891     case noListSegment:
892         // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
893         // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
894         // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
895         if (_currentListType == WebListType::Ordered)
896             [webHTMLView _insertOrderedList];
897         else if (_currentListType == WebListType::Unordered)
898             [webHTMLView _insertUnorderedList];
899         break;
900     case unorderedListSegment:
901         [webHTMLView _insertUnorderedList];
902         break;
903     case orderedListSegment:
904         [webHTMLView _insertOrderedList];
905         break;
906     }
907
908     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
909 }
910
911 - (void)setCurrentListType:(WebListType)listType
912 {
913     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
914     switch (listType) {
915     case WebListType::None:
916         [insertListControl setSelected:YES forSegment:noListSegment];
917         break;
918     case WebListType::Ordered:
919         [insertListControl setSelected:YES forSegment:orderedListSegment];
920         break;
921     case WebListType::Unordered:
922         [insertListControl setSelected:YES forSegment:unorderedListSegment];
923         break;
924     }
925
926     _currentListType = listType;
927 }
928
929 @end
930
931 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
932 @private
933     BOOL _textIsBold;
934     BOOL _textIsItalic;
935     BOOL _textIsUnderlined;
936     NSTextAlignment _currentTextAlignment;
937     RetainPtr<NSColor> _textColor;
938     RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
939     WebView *_webView;
940 }
941
942 @property (nonatomic) BOOL textIsBold;
943 @property (nonatomic) BOOL textIsItalic;
944 @property (nonatomic) BOOL textIsUnderlined;
945 @property (nonatomic) NSTextAlignment currentTextAlignment;
946 @property (nonatomic, retain, readwrite) NSColor *textColor;
947
948 - (instancetype)initWithWebView:(WebView *)webView;
949 @end
950
951 @implementation WebTextTouchBarItemController
952
953 @synthesize textIsBold=_textIsBold;
954 @synthesize textIsItalic=_textIsItalic;
955 @synthesize textIsUnderlined=_textIsUnderlined;
956 @synthesize currentTextAlignment=_currentTextAlignment;
957
958 - (instancetype)initWithWebView:(WebView *)webView
959 {
960     if (!(self = [super init]))
961         return nil;
962
963     _webView = webView;
964
965     return self;
966 }
967
968 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
969 {
970     NSTouchBarItem *item = [super itemForIdentifier:identifier];
971     BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
972
973     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
974         self.textStyle.action = @selector(_webChangeTextStyle:);
975
976     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
977         self.textAlignments.action = @selector(_webChangeTextAlignment:);
978
979     NSColorPickerTouchBarItem *colorPickerItem = nil;
980     if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
981         colorPickerItem = (NSColorPickerTouchBarItem *)item;
982     if (isTextFormatItem)
983         colorPickerItem = self.colorPickerItem;
984     if (colorPickerItem) {
985         colorPickerItem.target = self;
986         colorPickerItem.action = @selector(_webChangeColor:);
987         colorPickerItem.showsAlpha = NO;
988     }
989
990     return item;
991 }
992
993 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
994 {
995     return (WebTextListTouchBarViewController *)self.textListViewController;
996 }
997
998 - (void)setTextIsBold:(BOOL)bold
999 {
1000     _textIsBold = bold;
1001     if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
1002         [self.textStyle setSelected:_textIsBold forSegment:0];
1003 }
1004
1005 - (void)setTextIsItalic:(BOOL)italic
1006 {
1007     _textIsItalic = italic;
1008     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
1009         [self.textStyle setSelected:_textIsItalic forSegment:1];
1010 }
1011
1012 - (void)setTextIsUnderlined:(BOOL)underlined
1013 {
1014     _textIsUnderlined = underlined;
1015     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
1016         [self.textStyle setSelected:_textIsUnderlined forSegment:2];
1017 }
1018
1019 - (void)_webChangeTextStyle:(id)sender
1020 {
1021     if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
1022         _textIsBold = !_textIsBold;
1023         [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
1024     }
1025
1026     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
1027         _textIsItalic = !_textIsItalic;
1028         [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
1029     }
1030
1031     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
1032         _textIsUnderlined = !_textIsUnderlined;
1033         [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
1034     }
1035 }
1036
1037 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
1038 {
1039     _currentTextAlignment = alignment;
1040     [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
1041 }
1042
1043 - (void)_webChangeTextAlignment:(id)sender
1044 {
1045     NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
1046     switch (alignment) {
1047     case NSTextAlignmentLeft:
1048         _currentTextAlignment = NSTextAlignmentLeft;
1049         [_webView alignLeft:sender];
1050         break;
1051     case NSTextAlignmentRight:
1052         _currentTextAlignment = NSTextAlignmentRight;
1053         [_webView alignRight:sender];
1054         break;
1055     case NSTextAlignmentCenter:
1056         _currentTextAlignment = NSTextAlignmentCenter;
1057         [_webView alignCenter:sender];
1058         break;
1059     case NSTextAlignmentJustified:
1060         _currentTextAlignment = NSTextAlignmentJustified;
1061         [_webView alignJustified:sender];
1062         break;
1063     default:
1064         break;
1065     }
1066
1067     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
1068 }
1069
1070 - (NSColor *)textColor
1071 {
1072     return _textColor.get();
1073 }
1074
1075 - (void)setTextColor:(NSColor *)color
1076 {
1077     _textColor = color;
1078     self.colorPickerItem.color = _textColor.get();
1079 }
1080
1081 - (void)_webChangeColor:(id)sender
1082 {
1083     _textColor = self.colorPickerItem.color;
1084     [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
1085 }
1086
1087 - (NSViewController *)textListViewController
1088 {
1089     if (!_textListTouchBarViewController)
1090         _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
1091     return _textListTouchBarViewController.get();
1092 }
1093
1094 @end
1095
1096 #endif // HAVE(TOUCH_BAR)
1097
1098 @implementation WebView (AllWebViews)
1099
1100 static CFSetCallBacks NonRetainingSetCallbacks = {
1101     0,
1102     NULL,
1103     NULL,
1104     CFCopyDescription,
1105     CFEqual,
1106     CFHash
1107 };
1108
1109 static CFMutableSetRef allWebViewsSet;
1110
1111 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1112 {
1113     if (!allWebViewsSet)
1114         return;
1115
1116     [(__bridge NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1117 }
1118
1119 - (void)_removeFromAllWebViewsSet
1120 {
1121     if (allWebViewsSet)
1122         CFSetRemoveValue(allWebViewsSet, (__bridge CFTypeRef)self);
1123 }
1124
1125 - (void)_addToAllWebViewsSet
1126 {
1127     if (!allWebViewsSet)
1128         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1129
1130     CFSetSetValue(allWebViewsSet, (__bridge CFTypeRef)self);
1131 }
1132
1133 @end
1134
1135 @implementation WebView (WebPrivate)
1136
1137 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1138 {
1139     return standardUserAgentWithApplicationName(applicationName);
1140 }
1141
1142 #if PLATFORM(IOS)
1143 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1144 {
1145     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
1146 }
1147
1148 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1149 {
1150     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
1151 }
1152 #endif // PLATFORM(IOS)
1153
1154 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1155 {
1156     if (!exception || !context)
1157         return;
1158
1159     JSC::ExecState* execState = toJS(context);
1160     JSLockHolder lock(execState);
1161
1162     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1163     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1164     if (!toJSDOMWindow(globalObject->vm(), globalObject))
1165         return;
1166
1167     reportException(execState, toJS(execState, exception));
1168 }
1169
1170 static bool shouldEnableLoadDeferring()
1171 {
1172 #if PLATFORM(IOS)
1173     return true;
1174 #else
1175     return !MacApplication::isAdobeInstaller();
1176 #endif
1177 }
1178
1179 static bool shouldRestrictWindowFocus()
1180 {
1181 #if PLATFORM(IOS)
1182     return true;
1183 #else
1184     return !MacApplication::isHRBlock();
1185 #endif
1186 }
1187
1188 - (void)_dispatchPendingLoadRequests
1189 {
1190     webResourceLoadScheduler().servePendingRequests();
1191 }
1192
1193 #if !PLATFORM(IOS)
1194
1195 - (void)_registerDraggedTypes
1196 {
1197     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1198     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1199     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1200     [types addObjectsFromArray:URLTypes];
1201     [types addObject:[WebHTMLView _dummyPasteboardType]];
1202     [self registerForDraggedTypes:[types allObjects]];
1203     [types release];
1204 }
1205
1206 static bool needsOutlookQuirksScript()
1207 {
1208     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1209         && MacApplication::isMicrosoftOutlook();
1210     return isOutlookNeedingQuirksScript;
1211 }
1212
1213 static NSString *leakOutlookQuirksUserScriptContents()
1214 {
1215     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1216     NSStringEncoding encoding;
1217     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1218 }
1219
1220 -(void)_injectOutlookQuirksScript
1221 {
1222     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1223     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1224
1225 }
1226 #endif
1227
1228 static bool shouldRespectPriorityInCSSAttributeSetters()
1229 {
1230 #if PLATFORM(IOS)
1231     return false;
1232 #else
1233     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1234         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1235     return isIAdProducerNeedingAttributeSetterQuirk;
1236 #endif
1237 }
1238
1239 #if PLATFORM(IOS)
1240 static bool isInternalInstall()
1241 {
1242     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1243     return isInternal;
1244 }
1245
1246 static bool didOneTimeInitialization = false;
1247 #endif
1248
1249 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1250 {
1251 #if PLATFORM(IOS)
1252     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1253 #else
1254     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1255         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1256 #endif
1257     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1258 }
1259
1260 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1261 {
1262     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1263     return shouldAllowDisplayAndRunningOfInsecureContent;
1264 }
1265
1266 static bool shouldAllowPictureInPictureMediaPlayback()
1267 {
1268 #if PLATFORM(IOS)
1269     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1270     return shouldAllowPictureInPictureMediaPlayback;
1271 #else
1272     return false;
1273 #endif
1274 }
1275
1276 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1277 {
1278 #if PLATFORM(IOS)
1279     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1280     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1281 #else
1282     return false;
1283 #endif
1284 }
1285
1286 static bool shouldAllowWindowOpenWithoutUserGesture()
1287 {
1288 #if PLATFORM(IOS)
1289     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1290     return shouldAllowWindowOpenWithoutUserGesture;
1291 #else
1292     return false;
1293 #endif
1294 }
1295
1296 static bool shouldConvertInvalidURLsToBlank()
1297 {
1298 #if PLATFORM(IOS)
1299     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1300 #elif PLATFORM(MAC)
1301     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1302 #else
1303     static bool shouldConvertInvalidURLsToBlank = true;
1304 #endif
1305
1306     return shouldConvertInvalidURLsToBlank;
1307 }
1308
1309 static bool shouldRequireUserGestureToLoadVideo()
1310 {
1311 #if PLATFORM(IOS)
1312     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1313     return shouldRequireUserGestureToLoadVideo;
1314 #else
1315     return false;
1316 #endif
1317 }
1318
1319 #if ENABLE(GAMEPAD)
1320 static void WebKitInitializeGamepadProviderIfNecessary()
1321 {
1322     static bool initialized = false;
1323     if (initialized)
1324         return;
1325
1326 #if PLATFORM(MAC)
1327     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1328 #else
1329     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1330 #endif
1331
1332     initialized = true;
1333 }
1334 #endif
1335
1336 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1337 {
1338     WebCoreThreadViolationCheckRoundTwo();
1339
1340 #ifndef NDEBUG
1341     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1342 #endif
1343     
1344     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1345     [standardPreferences willAddToWebView];
1346
1347     _private->preferences = [standardPreferences retain];
1348     _private->mainFrameDocumentReady = NO;
1349     _private->drawsBackground = YES;
1350 #if !PLATFORM(IOS)
1351     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1352 #else
1353     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1354 #endif
1355
1356 #if PLATFORM(MAC)
1357     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1358 #endif
1359
1360     NSRect f = [self frame];
1361     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1362     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1363     [self addSubview:frameView];
1364     [frameView release];
1365
1366 #if PLATFORM(MAC)
1367     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1368         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1369         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1370         [recognizer setDelegate:_private->immediateActionController];
1371         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1372     }
1373 #endif
1374
1375     [self updateTouchBar];
1376
1377 #if !PLATFORM(IOS)
1378     static bool didOneTimeInitialization = false;
1379 #endif
1380     if (!didOneTimeInitialization) {
1381 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1382         WebKitInitializeLogChannelsIfNecessary();
1383         WebCore::initializeLogChannelsIfNecessary();
1384 #endif
1385
1386         // Initialize our platform strategies first before invoking the rest
1387         // of the initialization code which may depend on the strategies.
1388         WebPlatformStrategies::initializeIfNecessary();
1389
1390         initializeDOMWrapperHooks();
1391
1392 #if PLATFORM(IOS)
1393         // Set the WebSQLiteDatabaseTrackerClient.
1394         SQLiteDatabaseTracker::setClient(&WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1395
1396         if ([standardPreferences databasesEnabled])
1397 #endif
1398         [WebDatabaseManager sharedWebDatabaseManager];
1399
1400 #if PLATFORM(IOS)        
1401         if ([standardPreferences storageTrackerEnabled])
1402 #endif
1403         WebKitInitializeStorageIfNecessary();
1404
1405 #if ENABLE(GAMEPAD)
1406         WebKitInitializeGamepadProviderIfNecessary();
1407 #endif
1408         
1409         DeprecatedGlobalSettings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1410
1411 #if PLATFORM(IOS)
1412         if (IOSApplication::isMobileSafari())
1413             DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
1414 #endif
1415
1416         didOneTimeInitialization = true;
1417     }
1418
1419     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1420     _private->group->addWebView(self);
1421
1422     PageConfiguration pageConfiguration(
1423         makeUniqueRef<WebEditorClient>(self),
1424         SocketProvider::create(),
1425         LibWebRTCProvider::create(),
1426         WebCore::CacheStorageProvider::create()
1427     );
1428 #if !PLATFORM(IOS)
1429     pageConfiguration.chromeClient = new WebChromeClient(self);
1430     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1431     // FIXME: We should enable this on iOS as well.
1432     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1433     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1434 #else
1435     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1436     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1437 #endif
1438
1439 #if ENABLE(DRAG_SUPPORT)
1440     pageConfiguration.dragClient = new WebDragClient(self);
1441 #endif
1442
1443     pageConfiguration.backForwardClient = BackForwardList::create(self);
1444
1445 #if ENABLE(APPLE_PAY)
1446     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1447 #endif
1448
1449     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1450     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1451     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1452     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1453     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1454     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1455     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1456     pageConfiguration.userContentProvider = &_private->group->userContentController();
1457     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1458     _private->page = new Page(WTFMove(pageConfiguration));
1459
1460     _private->page->setGroupName(groupName);
1461
1462 #if ENABLE(GEOLOCATION)
1463     WebCore::provideGeolocationTo(_private->page, *new WebGeolocationClient(self));
1464 #endif
1465 #if ENABLE(NOTIFICATIONS)
1466     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1467 #endif
1468 #if ENABLE(DEVICE_ORIENTATION)
1469 #if !PLATFORM(IOS)
1470     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1471 #endif
1472 #endif
1473
1474 #if ENABLE(REMOTE_INSPECTOR)
1475     _private->page->setRemoteInspectionAllowed(true);
1476 #endif
1477
1478     _private->page->setCanStartMedia([self window]);
1479     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1480     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1481
1482 #if !PLATFORM(IOS)
1483     if (needsOutlookQuirksScript()) {
1484         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1485         [self _injectOutlookQuirksScript];
1486     }
1487 #endif
1488
1489 #if PLATFORM(IOS)
1490     _private->page->settings().setPassiveTouchListenersAsDefaultOnDocument(linkedOnOrAfter(SDKVersion::FirstThatDefaultsToPassiveTouchListenersOnDocument));
1491 #endif
1492
1493 #if PLATFORM(IOS)
1494     // Preserve the behavior we had before <rdar://problem/7580867>
1495     // by enforcing a 5MB limit for session storage.
1496     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1497
1498     [self _updateScreenScaleFromWindow];
1499     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1500     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1501     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1502 #if ENABLE(ORIENTATION_EVENTS)
1503     _private->deviceOrientation = [[self _UIKitDelegateForwarder] deviceOrientation];
1504 #endif
1505 #endif
1506
1507     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1508         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1509
1510     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1511
1512 #if PLATFORM(IOS)
1513     NSRunLoop *runLoop = WebThreadNSRunLoop();
1514 #else
1515     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1516 #endif
1517
1518     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1519         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1520     else
1521         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1522
1523     [self _addToAllWebViewsSet];
1524     
1525     // If there's already a next key view (e.g., from a nib), wire it up to our
1526     // contained frame view. In any case, wire our next key view up to the our
1527     // contained frame view. This works together with our becomeFirstResponder 
1528     // and setNextKeyView overrides.
1529     NSView *nextKeyView = [self nextKeyView];
1530     if (nextKeyView && nextKeyView != frameView)
1531         [frameView setNextKeyView:nextKeyView];
1532     [super setNextKeyView:frameView];
1533
1534     if ([[self class] shouldIncludeInWebKitStatistics])
1535         ++WebViewCount;
1536
1537 #if !PLATFORM(IOS)
1538     [self _registerDraggedTypes];
1539 #endif
1540
1541     [self _setIsVisible:[self _isViewVisible]];
1542
1543     WebPreferences *prefs = [self preferences];
1544     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1545                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1546
1547 #if !PLATFORM(IOS)
1548     [self _preferencesChanged:[self preferences]];
1549     [[self preferences] _postPreferencesChangedAPINotification];
1550 #else
1551     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1552     // and prefs need to be changed synchronously <rdar://problem/5841558>
1553     [self _preferencesChanged:prefs];
1554     _private->page->settings().setFontFallbackPrefersPictographs(true);
1555 #endif
1556
1557     WebInstallMemoryPressureHandler();
1558
1559 #if !PLATFORM(IOS)
1560     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1561         // Originally, we allowed all local loads.
1562         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1563     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1564         // Later, we allowed local loads for local URLs and documents loaded
1565         // with substitute data.
1566         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1567     }
1568 #endif
1569
1570 #if PLATFORM(MAC)
1571     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1572         ResourceHandle::forceContentSniffing();
1573
1574     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1575     _private->page->setUseDarkAppearance(self._effectiveAppearanceIsDark);
1576 #endif
1577
1578     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1579 }
1580
1581 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1582 {
1583     self = [super initWithFrame:f];
1584     if (!self)
1585         return nil;
1586
1587 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1588     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1589     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1590     // need for Safari to unset it to prevent it from being passed to applications it launches.
1591     // Unsetting it when a WebView is first created is as good a place as any.
1592     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1593     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1594         unsetenv("DYLD_FRAMEWORK_PATH");
1595         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1596     }
1597 #endif
1598
1599     _private = [[WebViewPrivate alloc] init];
1600     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1601     [self setMaintainsBackForwardList: YES];
1602     return self;
1603 }
1604
1605 - (void)_viewWillDrawInternal
1606 {
1607     Frame* frame = [self _mainCoreFrame];
1608     if (frame && frame->view())
1609         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1610 }
1611
1612 + (NSArray *)_supportedMIMETypes
1613 {
1614     // Load the plug-in DB allowing plug-ins to install types.
1615     [WebPluginDatabase sharedDatabase];
1616     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1617 }
1618
1619 #if !PLATFORM(IOS)
1620 + (NSArray *)_supportedFileExtensions
1621 {
1622     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1623     NSArray *MIMETypes = [self _supportedMIMETypes];
1624     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1625     NSString *MIMEType;
1626     while ((MIMEType = [enumerator nextObject]) != nil) {
1627         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1628         if (extensionsForType) {
1629             [extensions addObjectsFromArray:extensionsForType];
1630         }
1631     }
1632     NSArray *uniqueExtensions = [extensions allObjects];
1633     [extensions release];
1634     return uniqueExtensions;
1635 }
1636 #endif
1637
1638 #if PLATFORM(IOS)
1639 + (void)enableWebThread
1640 {
1641     static BOOL isWebThreadEnabled = NO;
1642     if (!isWebThreadEnabled) {
1643         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1644         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1645         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1646         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1647         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1648         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1649         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1650         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1651         WebCoreObjCDeallocOnWebThread([WebView class]);
1652         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1653         WebThreadEnable();
1654         isWebThreadEnabled = YES;
1655     }
1656 }
1657
1658 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1659 {
1660     self = [super initWithFrame:frame];
1661     if (!self)
1662         return nil;
1663     
1664     _private = [[WebViewPrivate alloc] init];
1665     
1666 #ifndef NDEBUG
1667     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1668 #endif
1669     
1670     if (!preferences)
1671         preferences = [WebPreferences standardPreferences];
1672     [preferences willAddToWebView];
1673     
1674     _private->preferences = [preferences retain];
1675     _private->mainFrameDocumentReady = NO;
1676     _private->drawsBackground = YES;
1677     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1678
1679     WebFrameView *frameView = nil;
1680     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1681     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1682     [self addSubview:frameView];
1683     [frameView release];
1684
1685     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1686     _private->group->addWebView(self);
1687
1688     PageConfiguration pageConfiguration(
1689         makeUniqueRef<WebEditorClient>(self),
1690         SocketProvider::create(),
1691         LibWebRTCProvider::create(),
1692         WebCore::CacheStorageProvider::create()
1693     );
1694     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1695 #if ENABLE(DRAG_SUPPORT)
1696     pageConfiguration.dragClient = new WebDragClient(self);
1697 #endif
1698
1699 #if ENABLE(APPLE_PAY)
1700     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1701 #endif
1702
1703     pageConfiguration.backForwardClient = BackForwardList::create(self);
1704     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1705     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1706     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1707     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1708     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1709     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1710     pageConfiguration.userContentProvider = &_private->group->userContentController();
1711     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1712     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1713
1714     _private->page = new Page(WTFMove(pageConfiguration));
1715     
1716     [self setSmartInsertDeleteEnabled:YES];
1717     
1718     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1719     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1720     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1721     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1722     _private->page->settings().setMinimumLogicalFontSize(9);
1723     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1724     _private->page->settings().setDefaultFixedFontSize(13);
1725     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1726     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1727     
1728     _private->page->settings().setFontFallbackPrefersPictographs(true);
1729     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1730     
1731     _private->page->settings().setScriptMarkupEnabled(false);
1732     _private->page->settings().setScriptEnabled(true);
1733     
1734     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1735     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1736     
1737     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1738     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1739
1740     // This is a workaround for <rdar://problem/21309911>.
1741     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1742
1743     _private->page->setGroupName(groupName);
1744
1745 #if ENABLE(REMOTE_INSPECTOR)
1746     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1747 #endif
1748     
1749     [self _updateScreenScaleFromWindow];
1750     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1751     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1752
1753     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1754     
1755     [self _addToAllWebViewsSet];
1756     
1757     ++WebViewCount;
1758     
1759     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1760     
1761     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled(self.preferences.attachmentElementEnabled);
1762
1763     return self;
1764 }
1765
1766 + (void)_releaseMemoryNow
1767 {
1768     WebThreadRun(^{
1769         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1770     });
1771 }
1772
1773 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1774 {
1775     Frame* frame = [self _mainCoreFrame];
1776     if (frame)
1777         frame->loader().history().replaceCurrentItem(core(item));
1778 }
1779
1780 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1781 {
1782     WebThreadRun(^{
1783         [WebView _releaseMemoryNow];
1784         dispatch_async(dispatch_get_main_queue(), handler);
1785     });
1786 }
1787
1788 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1789 {
1790     return WebCore::isCharacterSmartReplaceExempt(character, b);
1791 }
1792
1793 - (void)updateLayoutIgnorePendingStyleSheets
1794 {
1795     WebThreadRun(^{
1796         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1797             Document *document = frame->document();
1798             if (document)
1799                 document->updateLayoutIgnorePendingStylesheets();
1800         }
1801     });
1802 }
1803 #endif
1804
1805 #if PLATFORM(IOS)
1806
1807 #if ENABLE(DRAG_SUPPORT)
1808
1809 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1810 {
1811     WebThreadLock();
1812     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1813 }
1814
1815 - (void)_startDrag:(const DragItem&)dragItem
1816 {
1817     auto& dragImage = dragItem.image;
1818     auto image = dragImage.get().get();
1819     auto indicatorData = dragImage.indicatorData();
1820
1821     if (indicatorData)
1822         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1823     else
1824         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1825     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1826     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1827     _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1828     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1829 }
1830
1831 - (CGRect)_dataInteractionCaretRect
1832 {
1833     WebThreadLock();
1834     if (auto* page = _private->page)
1835         return page->dragCaretController().caretRectInRootViewCoordinates();
1836
1837     return { };
1838 }
1839
1840 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1841 {
1842     return _private->dataOperationTextIndicator.get();
1843 }
1844
1845 - (WebDragSourceAction)_dragSourceAction
1846 {
1847     return _private->dragSourceAction;
1848 }
1849
1850 - (NSString *)_draggedLinkTitle
1851 {
1852     return _private->draggedLinkTitle.get();
1853 }
1854
1855 - (NSURL *)_draggedLinkURL
1856 {
1857     return _private->draggedLinkURL.get();
1858 }
1859
1860 - (CGRect)_draggedElementBounds
1861 {
1862     return _private->dragPreviewFrameInRootViewCoordinates;
1863 }
1864
1865 - (WebUITextIndicatorData *)_getDataInteractionData
1866 {
1867     return _private->textIndicatorData.get();
1868 }
1869
1870 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1871 {
1872     return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1873 }
1874
1875 - (DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1876 {
1877     auto dragOperationMask = static_cast<DragOperation>(operation);
1878     auto dragDestinationMask = static_cast<DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1879     return { session, roundedIntPoint(clientPosition), roundedIntPoint(globalPosition), dragOperationMask, DragApplicationNone, dragDestinationMask };
1880 }
1881
1882 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1883 {
1884     WebThreadLock();
1885     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1886     return _private->page->dragController().dragEntered(dragData);
1887 }
1888
1889 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1890 {
1891     WebThreadLock();
1892     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1893     return _private->page->dragController().dragUpdated(dragData);
1894 }
1895 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1896 {
1897     WebThreadLock();
1898     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1899     _private->page->dragController().dragExited(dragData);
1900 }
1901 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1902 {
1903     [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1904 }
1905
1906 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1907 {
1908     WebThreadLock();
1909     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1910     return _private->page->dragController().performDragOperation(dragData);
1911 }
1912
1913 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1914 {
1915     WebThreadLock();
1916     _private->page->dragController().dragEnded();
1917     _private->dataOperationTextIndicator = nullptr;
1918     _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1919     _private->dragSourceAction = WebDragSourceActionNone;
1920     _private->draggedLinkTitle = nil;
1921     _private->draggedLinkURL = nil;
1922 }
1923
1924 - (void)_didConcludeEditDataInteraction
1925 {
1926     _private->dataOperationTextIndicator = nullptr;
1927     auto* page = _private->page;
1928     if (!page)
1929         return;
1930
1931     static auto defaultEditDragTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | TextIndicatorOptionRespectTextColor;
1932     auto& frame = page->focusController().focusedOrMainFrame();
1933     if (auto range = frame.selection().selection().toNormalizedRange()) {
1934         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
1935             _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1936     }
1937 }
1938
1939 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1940
1941 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1942 {
1943     return NO;
1944 }
1945
1946 - (WebUITextIndicatorData *)_getDataInteractionData
1947 {
1948     return nil;
1949 }
1950
1951 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1952 {
1953     return nil;
1954 }
1955
1956 - (NSUInteger)_dragSourceAction
1957 {
1958     return 0;
1959 }
1960
1961 - (NSString *)_draggedLinkTitle
1962 {
1963     return nil;
1964 }
1965
1966 - (NSURL *)_draggedLinkURL
1967 {
1968     return nil;
1969 }
1970
1971 - (CGRect)_draggedElementBounds
1972 {
1973     return CGRectNull;
1974 }
1975
1976 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1977 {
1978     return 0;
1979 }
1980
1981 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1982 {
1983     return 0;
1984 }
1985
1986 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1987 {
1988 }
1989
1990 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1991 {
1992 }
1993
1994 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1995 {
1996     return NO;
1997 }
1998
1999 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2000 {
2001 }
2002
2003 - (CGRect)_dataInteractionCaretRect
2004 {
2005     return CGRectNull;
2006 }
2007
2008 #endif
2009 #endif // PLATFORM(IOS)
2010
2011 static NSMutableSet *knownPluginMIMETypes()
2012 {
2013     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2014     
2015     return mimeTypes;
2016 }
2017
2018 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2019 {
2020     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2021     [knownPluginMIMETypes() addObject:MIMEType];
2022 }
2023
2024 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2025 {
2026     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2027     [knownPluginMIMETypes() removeObject:MIMEType];
2028 }
2029
2030 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2031 {
2032     MIMEType = [MIMEType lowercaseString];
2033     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2034     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2035
2036 #if PLATFORM(IOS)
2037 #define WebPDFView ([WebView _getPDFViewClass])
2038 #endif
2039     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2040 #if PLATFORM(IOS)
2041 #undef WebPDFView
2042 #endif
2043         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2044
2045         if (allowPlugins) {
2046             // Load the plug-in DB allowing plug-ins to install types.
2047             [WebPluginDatabase sharedDatabase];
2048         }
2049
2050         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2051         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2052         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2053     }
2054     
2055     if (viewClass && repClass) {
2056         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2057             // Special-case WebHTMLView for text types that shouldn't be shown.
2058             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2059                 return NO;
2060
2061             // If the MIME type is a known plug-in we might not want to load it.
2062             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2063                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2064                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2065                 
2066                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2067                 if (!isSupportedByWebKit)
2068                     return NO;
2069             }
2070         }
2071         if (vClass)
2072             *vClass = viewClass;
2073         if (rClass)
2074             *rClass = repClass;
2075         return YES;
2076     }
2077     
2078     return NO;
2079 }
2080
2081 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2082 {
2083     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2084         return YES;
2085 #if !PLATFORM(IOS)
2086     if (_private->pluginDatabase) {
2087         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2088         if (pluginPackage) {
2089             if (vClass)
2090                 *vClass = [WebHTMLView class];
2091             if (rClass)
2092                 *rClass = [WebHTMLRepresentation class];
2093             return YES;
2094         }
2095     }
2096 #endif
2097     return NO;
2098 }
2099
2100 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2101 {
2102     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
2103 }
2104
2105 + (BOOL)canCloseAllWebViews
2106 {
2107     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2108 }
2109
2110 + (void)closeAllWebViews
2111 {
2112     DOMWindow::dispatchAllPendingUnloadEvents();
2113
2114     // This will close the WebViews in a random order. Change this if close order is important.
2115     for (WebView *webView in [(__bridge NSSet *)allWebViewsSet allObjects])
2116         [webView close];
2117 }
2118
2119 + (BOOL)canShowFile:(NSString *)path
2120 {
2121     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2122 }
2123
2124 #if !PLATFORM(IOS)
2125 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2126 {
2127     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2128 }
2129 #endif
2130
2131 - (BOOL)_isClosed
2132 {
2133     return !_private || _private->closed;
2134 }
2135
2136 #if PLATFORM(IOS)
2137
2138 - (void)_dispatchUnloadEvent
2139 {
2140     WebThreadRun(^{
2141         WebFrame *mainFrame = [self mainFrame];
2142         Frame *coreMainFrame = core(mainFrame);
2143         if (coreMainFrame) {
2144             Document *document = coreMainFrame->document();
2145             if (document)
2146                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, Event::CanBubble::No, Event::IsCancelable::No));
2147         }
2148     });
2149 }
2150
2151 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2152 {
2153     auto* mainFrame = [self _mainCoreFrame];
2154     if (!mainFrame)
2155         return nil;
2156     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2157     if (!editingStyle)
2158         return nil;
2159     auto* style = editingStyle->style();
2160     if (!style)
2161         return nil;
2162     return kit(&style->ensureCSSStyleDeclaration());
2163 }
2164
2165 - (NSUInteger)_renderTreeSize
2166 {
2167     if (!_private->page)
2168         return 0;
2169     return _private->page->renderTreeSize();
2170 }
2171
2172 - (void)_dispatchTileDidDraw:(CALayer*)tile
2173 {
2174     id mailDelegate = [self _webMailDelegate];
2175     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2176         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2177         return;
2178     }
2179
2180     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2181     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2182         return;
2183     ALLOW_DEPRECATED_DECLARATIONS_END
2184
2185     WebThreadLock();
2186
2187     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2188 }
2189
2190 - (void)_willStartScrollingOrZooming
2191 {
2192     // Pause timers during top level interaction
2193     if (_private->mainViewIsScrollingOrZooming)
2194         return;
2195     _private->mainViewIsScrollingOrZooming = YES;
2196
2197     [self hideFormValidationMessage];
2198
2199     // This suspends active DOM objects like timers, but not media.
2200     [[self mainFrame] setTimeoutsPaused:YES];
2201
2202     // This defers loading callbacks only.
2203     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2204     [self setDefersCallbacks:YES];
2205 }
2206
2207 - (void)_didFinishScrollingOrZooming
2208 {
2209     if (!_private->mainViewIsScrollingOrZooming)
2210         return;
2211     _private->mainViewIsScrollingOrZooming = NO;
2212     [self setDefersCallbacks:NO];
2213     [[self mainFrame] setTimeoutsPaused:NO];
2214     if (FrameView* view = [self _mainCoreFrame]->view())
2215         view->resumeVisibleImageAnimationsIncludingSubframes();
2216 }
2217
2218 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2219 {
2220     if (suspend)
2221         webResourceLoadScheduler().suspendPendingRequests();
2222     else
2223         webResourceLoadScheduler().resumePendingRequests();
2224 }
2225
2226 + (BOOL)_isUnderMemoryPressure
2227 {
2228     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2229 }
2230
2231 #endif // PLATFORM(IOS)
2232
2233 - (void)_closePluginDatabases
2234 {
2235     pluginDatabaseClientCount--;
2236
2237     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2238
2239 #if !PLATFORM(IOS)
2240     // Unload the WebView local plug-in database. 
2241     if (_private->pluginDatabase) {
2242         [_private->pluginDatabase destroyAllPluginInstanceViews];
2243         [_private->pluginDatabase close];
2244         [_private->pluginDatabase release];
2245         _private->pluginDatabase = nil;
2246     }
2247 #endif
2248     
2249     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2250     if (!pluginDatabaseClientCount && applicationIsTerminating)
2251         [WebPluginDatabase closeSharedDatabase];
2252 }
2253
2254 - (void)_closeWithFastTeardown 
2255 {
2256 #ifndef NDEBUG
2257     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2258 #endif
2259
2260 #if !PLATFORM(IOS)
2261     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2262 #endif
2263     [[NSNotificationCenter defaultCenter] removeObserver:self];
2264
2265     [self _closePluginDatabases];
2266 }
2267
2268 static bool fastDocumentTeardownEnabled()
2269 {
2270 #ifdef NDEBUG
2271     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2272 #else
2273     static bool initialized = false;
2274     static bool enabled = false;
2275     if (!initialized) {
2276         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2277         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2278         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2279         if (setting)
2280             enabled = ![setting boolValue];
2281         initialized = true;
2282     }
2283 #endif
2284     return enabled;
2285 }
2286
2287 // _close is here only for backward compatibility; clients and subclasses should use
2288 // public method -close instead.
2289 - (void)_close
2290 {
2291 #if PLATFORM(IOS)
2292     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2293     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2294
2295     [self _clearDelegates];
2296
2297     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2298     WebThreadRun(^{
2299 #endif            
2300
2301     if (!_private || _private->closed)
2302         return;
2303
2304     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2305
2306     _private->closed = YES;
2307     [self _removeFromAllWebViewsSet];
2308
2309 #ifndef NDEBUG
2310     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2311 #endif
2312
2313     // To quit the apps fast we skip document teardown, except plugins
2314     // need to be destroyed and unloaded.
2315     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2316         [self _closeWithFastTeardown];
2317         return;
2318     }
2319
2320 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2321     [self _exitVideoFullscreen];
2322 #endif
2323
2324 #if PLATFORM(IOS)
2325     _private->closing = YES;
2326 #endif
2327
2328     if (Frame* mainFrame = [self _mainCoreFrame])
2329         mainFrame->loader().detachFromParent();
2330
2331     [self setHostWindow:nil];
2332
2333 #if !PLATFORM(IOS)
2334     [self setDownloadDelegate:nil];
2335     [self setEditingDelegate:nil];
2336     [self setFrameLoadDelegate:nil];
2337     [self setPolicyDelegate:nil];
2338     [self setResourceLoadDelegate:nil];
2339     [self setScriptDebugDelegate:nil];
2340     [self setUIDelegate:nil];
2341
2342     [_private->inspector inspectedWebViewClosed];
2343 #endif
2344 #if PLATFORM(MAC)
2345     [_private->immediateActionController webViewClosed];
2346 #endif
2347
2348 #if !PLATFORM(IOS)
2349     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2350     [self removeDragCaret];
2351 #endif
2352
2353     _private->group->removeWebView(self);
2354
2355     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2356     // all the plug-ins in the page cache to break any retain cycles.
2357     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2358     Page* page = _private->page;
2359     _private->page = nullptr;
2360     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2361
2362 #if !PLATFORM(IOS)
2363     if (_private->hasSpellCheckerDocumentTag) {
2364         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2365         _private->hasSpellCheckerDocumentTag = NO;
2366     }
2367 #endif
2368
2369     if (_private->layerFlushController) {
2370         _private->layerFlushController->invalidate();
2371         _private->layerFlushController = nullptr;
2372     }
2373
2374     [[self _notificationProvider] unregisterWebView:self];
2375
2376 #if !PLATFORM(IOS)
2377     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2378 #endif
2379     [[NSNotificationCenter defaultCenter] removeObserver:self];
2380
2381     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2382
2383     WebPreferences *preferences = _private->preferences;
2384     _private->preferences = nil;
2385     [preferences didRemoveFromWebView];
2386     [preferences release];
2387
2388     [self _closePluginDatabases];
2389
2390 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2391     if (_private->m_playbackTargetPicker) {
2392         _private->m_playbackTargetPicker->invalidate();
2393         _private->m_playbackTargetPicker = nullptr;
2394     }
2395 #endif
2396
2397 #ifndef NDEBUG
2398     // Need this to make leak messages accurate.
2399     if (applicationIsTerminating) {
2400         WebCore::GCController::singleton().garbageCollectNow();
2401         [WebCache setDisabled:YES];
2402     }
2403 #endif
2404 #if PLATFORM(IOS)
2405     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2406     });
2407 #endif            
2408 }
2409
2410 // Indicates if the WebView is in the midst of a user gesture.
2411 - (BOOL)_isProcessingUserGesture
2412 {
2413     return UserGestureIndicator::processingUserGesture();
2414 }
2415
2416 + (NSString *)_MIMETypeForFile:(NSString *)path
2417 {
2418 #if !PLATFORM(IOS)
2419     NSString *extension = [path pathExtension];
2420 #endif
2421     NSString *MIMEType = nil;
2422
2423 #if !PLATFORM(IOS)
2424     // Get the MIME type from the extension.
2425     if ([extension length] != 0) {
2426         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2427     }
2428 #endif
2429
2430     // If we can't get a known MIME type from the extension, sniff.
2431     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2432         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2433         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2434         [handle closeFile];
2435         if ([data length] != 0) {
2436             MIMEType = [data _webkit_guessedMIMEType];
2437         }
2438         if ([MIMEType length] == 0) {
2439             MIMEType = @"application/octet-stream";
2440         }
2441     }
2442
2443     return MIMEType;
2444 }
2445
2446 - (WebDownload *)_downloadURL:(NSURL *)URL
2447 {
2448     ASSERT(URL);
2449     
2450     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2451 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2452     WebDownload *download = [WebDownload _downloadWithRequest:request delegate:_private->downloadDelegate directory:nil];
2453 ALLOW_DEPRECATED_DECLARATIONS_END
2454     [request release];
2455
2456     return download;
2457 }
2458
2459 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2460 {
2461     NSDictionary *features = [[NSDictionary alloc] init];
2462     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2463                                             createWebViewWithRequest:nil
2464                                                       windowFeatures:features];
2465     [features release];
2466     if (!newWindowWebView)
2467         return nil;
2468
2469     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2470     return newWindowWebView;
2471 }
2472
2473 + (void)_setIconLoadingEnabled:(BOOL)enabled
2474 {
2475     iconLoadingEnabled = enabled;
2476 }
2477
2478 + (BOOL)_isIconLoadingEnabled
2479 {
2480     return iconLoadingEnabled;
2481 }
2482
2483 - (WebInspector *)inspector
2484 {
2485     if (!_private->inspector)
2486         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2487     return _private->inspector;
2488 }
2489
2490 #if ENABLE(REMOTE_INSPECTOR)
2491 + (void)_enableRemoteInspector
2492 {
2493     RemoteInspector::singleton().start();
2494 }
2495
2496 + (void)_disableRemoteInspector
2497 {
2498     RemoteInspector::singleton().stop();
2499 }
2500
2501 + (void)_disableAutoStartRemoteInspector
2502 {
2503     RemoteInspector::startDisabled();
2504 }
2505
2506 + (BOOL)_isRemoteInspectorEnabled
2507 {
2508     return RemoteInspector::singleton().enabled();
2509 }
2510
2511 + (BOOL)_hasRemoteInspectorSession
2512 {
2513     return RemoteInspector::singleton().hasActiveDebugSession();
2514 }
2515
2516 - (BOOL)allowsRemoteInspection
2517 {
2518     return _private->page->remoteInspectionAllowed();
2519 }
2520
2521 - (void)setAllowsRemoteInspection:(BOOL)allow
2522 {
2523     _private->page->setRemoteInspectionAllowed(allow);
2524 }
2525
2526 - (void)setShowingInspectorIndication:(BOOL)showing
2527 {
2528 #if PLATFORM(IOS)
2529     ASSERT(WebThreadIsLocked());
2530
2531     if (showing) {
2532         if (!_private->indicateLayer) {
2533             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2534             [_private->indicateLayer setNeedsLayout];
2535             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2536         }
2537     } else {
2538         [_private->indicateLayer removeFromSuperlayer];
2539         [_private->indicateLayer release];
2540         _private->indicateLayer = nil;
2541     }
2542 #else
2543     // Implemented in WebCore::InspectorOverlay.
2544 #endif
2545 }
2546
2547 #if PLATFORM(IOS)
2548 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2549 {
2550     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2551     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2552 }
2553 #endif // PLATFORM(IOS)
2554 #endif // ENABLE(REMOTE_INSPECTOR)
2555
2556 - (WebCore::Page*)page
2557 {
2558     return _private->page;
2559 }
2560
2561 #if !PLATFORM(IOS)
2562 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2563 {
2564     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2565     NSArray *menuItems = defaultMenuItems;
2566
2567     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2568     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2569     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2570     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2571         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2572         if (!menuItems)
2573             return nil;
2574     }
2575
2576     unsigned count = [menuItems count];
2577     if (!count)
2578         return nil;
2579
2580     NSMenu *menu = [[NSMenu alloc] init];
2581     for (unsigned i = 0; i < count; i++)
2582         [menu addItem:[menuItems objectAtIndex:i]];
2583
2584     return [menu autorelease];
2585 }
2586 #endif
2587
2588 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2589 {
2590     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2591     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2592     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2593     if (!dictionary)
2594         return;
2595     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2596 }
2597
2598 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2599 {
2600     if (!_private->page)
2601         return;
2602     
2603     if (!otherView->_private->page)
2604         return;
2605     
2606     // It turns out the right combination of behavior is done with the back/forward load
2607     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2608     // in the back forward list, and go to the current one.
2609
2610     BackForwardController& backForward = _private->page->backForward();
2611     ASSERT(!backForward.currentItem()); // destination list should be empty
2612
2613     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2614     if (!otherBackForward.currentItem())
2615         return; // empty back forward list, bail
2616     
2617     HistoryItem* newItemToGoTo = nullptr;
2618
2619     int lastItemIndex = otherBackForward.forwardCount();
2620     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2621         if (i == 0) {
2622             // If this item is showing , save away its current scroll and form state,
2623             // since that might have changed since loading and it is normally not saved
2624             // until we leave that page.
2625             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2626         }
2627         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2628         if (i == 0) 
2629             newItemToGoTo = newItem.ptr();
2630         backForward.client()->addItem(WTFMove(newItem));
2631     }
2632
2633     ASSERT(newItemToGoTo);
2634     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, ShouldTreatAsContinuingLoad::No);
2635 }
2636
2637 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2638 {
2639     _private->formDelegate = delegate;
2640 #if PLATFORM(IOS)
2641     [_private->formDelegateForwarder clearTarget];
2642     [_private->formDelegateForwarder release];
2643     _private->formDelegateForwarder = nil;
2644 #endif
2645 }
2646
2647 - (id<WebFormDelegate>)_formDelegate
2648 {
2649     return _private->formDelegate;
2650 }
2651
2652 #if PLATFORM(IOS)
2653 - (id)_formDelegateForwarder
2654 {
2655     if (_private->closing)
2656         return nil;
2657
2658     if (!_private->formDelegateForwarder)
2659         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2660     return _private->formDelegateForwarder;
2661 }
2662
2663 - (id)_formDelegateForSelector:(SEL)selector
2664 {
2665     id delegate = self->_private->formDelegate;
2666     if ([delegate respondsToSelector:selector])
2667         return delegate;
2668
2669     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2670     if ([delegate respondsToSelector:selector])
2671         return delegate;
2672
2673     return nil;
2674 }
2675 #endif
2676
2677 #if !PLATFORM(IOS)
2678 - (BOOL)_needsAdobeFrameReloadingQuirk
2679 {
2680     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2681         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2682         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2683         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2684         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2685         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2686         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2687         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2688         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2689         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2690
2691     return needsQuirk;
2692 }
2693
2694 - (BOOL)_needsLinkElementTextCSSQuirk
2695 {
2696     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2697         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2698     return needsQuirk;
2699 }
2700
2701 - (BOOL)_needsFrameNameFallbackToIdQuirk
2702 {
2703     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2704     return needsQuirk;
2705 }
2706
2707 - (BOOL)_needsIsLoadingInAPISenseQuirk
2708 {
2709     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2710     
2711     return needsQuirk;
2712 }
2713
2714 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2715 {
2716     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2717     return needsQuirks;
2718 }
2719
2720 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2721 {
2722     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2723     return needsQuirk;
2724 }
2725
2726 static bool needsSelfRetainWhileLoadingQuirk()
2727 {
2728     static bool needsQuirk = MacApplication::isAperture();
2729     return needsQuirk;
2730 }
2731 #endif // !PLATFORM(IOS)
2732
2733 - (BOOL)_needsPreHTML5ParserQuirks
2734 {    
2735 #if !PLATFORM(IOS)
2736     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2737     // with the new HTML5 parser. If these applications were linked against a
2738     // version of WebKit prior to the introduction of the HTML5 parser, enable
2739     // parser quirks to maintain compatibility. For details, see 
2740     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2741     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2742     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2743         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2744     
2745     // Mail.app must continue to display HTML email that contains quirky markup.
2746     static bool isAppleMail = MacApplication::isAppleMail();
2747
2748     return isApplicationNeedingParserQuirks
2749         || isAppleMail
2750 #if ENABLE(DASHBOARD_SUPPORT)
2751         // Pre-HTML5 parser quirks are required to remain compatible with many
2752         // Dashboard widgets. See <rdar://problem/8175982>.
2753         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2754 #endif
2755         || [[self preferences] usePreHTML5ParserQuirks];
2756 #else
2757     return [[self preferences] usePreHTML5ParserQuirks];
2758 #endif
2759 }
2760
2761 - (void)_preferencesChangedNotification:(NSNotification *)notification
2762 {
2763 #if PLATFORM(IOS)
2764     // For WebViews that load synchronously, preference changes need to be propagated
2765     // down to WebCore synchronously so that loads in that WebView have the correct
2766     // up-to-date settings.
2767     if (!WebThreadIsLocked())
2768         WebThreadLock();
2769     if ([[self mainFrame] _loadsSynchronously]) {
2770 #endif
2771
2772     WebPreferences *preferences = (WebPreferences *)[notification object];
2773     [self _preferencesChanged:preferences];
2774
2775 #if PLATFORM(IOS)
2776     } else {
2777         WebThreadRun(^{
2778             // It is possible that the prefs object has already changed before the invocation could be called
2779             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2780             WebPreferences *preferences = (WebPreferences *)[notification object];
2781             if (preferences != [self preferences])
2782                 return;
2783             [self _preferencesChanged:preferences];
2784         });
2785     }
2786 #endif
2787 }
2788
2789 - (void)_preferencesChanged:(WebPreferences *)preferences
2790 {    
2791     ASSERT(preferences == [self preferences]);
2792     if (!_private->userAgentOverridden)
2793         [self _invalidateUserAgentCache];
2794
2795     // Cache this value so we don't have to read NSUserDefaults on each page load
2796     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2797
2798     // Update corresponding WebCore Settings object.
2799     if (!_private->page)
2800         return;
2801
2802 #if PLATFORM(IOS)
2803     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2804     // didOneTimeInitialization is true so that we don't initialize databases
2805     // until the first WebView has been created. This is because database
2806     // initialization current requires disk access to populate the origins
2807     // quota map and we want to do this lazily by waiting until WebKit is
2808     // used to display web content in a WebView. The possible cases are:
2809     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2810     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2811     if (didOneTimeInitialization) {
2812         if ([preferences databasesEnabled])
2813             [WebDatabaseManager sharedWebDatabaseManager];
2814         if ([preferences storageTrackerEnabled])
2815             WebKitInitializeStorageIfNecessary();
2816     }
2817 #endif
2818
2819     Settings& settings = _private->page->settings();
2820
2821     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2822     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2823     settings.setDefaultFontSize([preferences defaultFontSize]);
2824     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2825     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2826     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2827     settings.setFixedFontFamily([preferences fixedFontFamily]);
2828     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2829     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2830     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2831     settings.setJavaEnabled([preferences isJavaEnabled]);
2832     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2833     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2834     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2835     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2836     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2837     settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2838     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2839     settings.setMinimumFontSize([preferences minimumFontSize]);
2840     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2841     settings.setPictographFontFamily([preferences pictographFontFamily]);
2842     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2843     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2844
2845     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2846     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2847     settings.setSerifFontFamily([preferences serifFontFamily]);
2848     settings.setStandardFontFamily([preferences standardFontFamily]);
2849     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2850     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2851 #if PLATFORM(IOS)
2852     settings.setShouldPrintBackgrounds(true);
2853 #else
2854     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2855 #endif
2856     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2857     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2858     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2859     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2860     settings.setUsesPageCache([self usesPageCache]);
2861     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2862     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2863
2864     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2865     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2866     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2867
2868     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2869     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2870     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2871     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2872     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2873     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2874     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2875     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2876
2877     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2878     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2879     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2880     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2881     settings.setShowDebugBorders([preferences showDebugBorders]);
2882     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2883     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2884     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2885     settings.setWebGLEnabled([preferences webGLEnabled]);
2886     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2887     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2888
2889     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2890     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2891     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2892     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2893     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2894     settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2895     settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2896     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2897     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2898
2899     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2900     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2901     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2902     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2903     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2904
2905     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2906     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2907     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2908     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2909     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2910     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2911     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2912     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2913     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2914     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2915     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2916     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2917     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2918     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2919     DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2920
2921     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2922
2923     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2924     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2925     DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2926
2927     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2928
2929     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2930     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2931
2932     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2933     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2934
2935     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2936
2937     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2938     settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2939     settings.setCSSOMViewScrollingAPIEnabled([preferences CSSOMViewScrollingAPIEnabled]);
2940     settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2941
2942     switch ([preferences storageBlockingPolicy]) {
2943     case WebAllowAllStorage:
2944         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2945         break;
2946     case WebBlockThirdPartyStorage:
2947         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2948         break;
2949     case WebBlockAllStorage:
2950         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2951         break;
2952     }
2953
2954     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2955     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2956     settings.setColorFilterEnabled([preferences colorFilterEnabled]);
2957     settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
2958
2959 #if PLATFORM(MAC)
2960     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2961 #endif
2962
2963 #if ENABLE(RUBBER_BANDING)
2964     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2965     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2966 #endif
2967
2968 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2969     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2970 #endif
2971 #if PLATFORM(IOS)
2972     settings.setStandalone([preferences _standalone]);
2973     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2974     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2975     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2976     settings.setMaxParseDuration([preferences _maxParseDuration]);
2977     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2978     DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2979     DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2980     DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
2981 #if HAVE(AVKIT)
2982     DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
2983 #endif
2984
2985     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2986     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2987
2988     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2989     settings.setDelegatesPageScaling(true);
2990
2991 #if ENABLE(TEXT_AUTOSIZING)
2992     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2993     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2994 #endif
2995 #endif // PLATFORM(IOS)
2996
2997 #if PLATFORM(MAC)
2998     // This parses the user stylesheet synchronously so anything that may affect it should be done first.
2999     if ([preferences userStyleSheetEnabled]) {
3000         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3001         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
3002             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
3003         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3004     } else
3005         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3006
3007     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3008     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3009     settings.setNeedsFrameNameFallbackToIdQuirk([self _needsFrameNameFallbackToIdQuirk]);
3010     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3011     settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3012     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3013     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3014     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3015     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3016     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3017 #endif // PLATFORM(MAC)
3018
3019     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3020
3021 #if ENABLE(MEDIA_SOURCE)
3022     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3023     settings.setSourceBufferChangeTypeEnabled([preferences sourceBufferChangeTypeEnabled]);
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 #endif
3052
3053 #if ENABLE(WEB_AUDIO)
3054     settings.setWebAudioEnabled([preferences webAudioEnabled]);
3055 #endif
3056
3057 #if ENABLE(FULLSCREEN_API)
3058     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3059 #endif
3060
3061     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3062
3063     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3064
3065     DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3066
3067     settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3068     settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3069     settings.setCrossOriginWindowPolicySupportEnabled([preferences crossOriginWindowPolicySupportEnabled]);
3070
3071 #if ENABLE(GAMEPAD)
3072     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3073 #endif
3074
3075     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3076     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3077     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3078     RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3079
3080 #if ENABLE(ATTACHMENT_ELEMENT)
3081     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3082 #endif
3083
3084     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3085     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3086     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsCSSIntegrationEnabled([preferences webAnimationsCSSIntegrationEnabled]);
3087
3088     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3089     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3090
3091 #if ENABLE(STREAMS_API)
3092     RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3093     RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3094 #endif
3095
3096 #if ENABLE(WEBGL2)
3097     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3098 #endif
3099
3100 #if ENABLE(WEBGPU)
3101     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3102 #endif
3103
3104 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3105     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3106 #endif
3107
3108     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3109
3110 #if ENABLE(INTERSECTION_OBSERVER)
3111     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3112 #endif
3113     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3114
3115     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3116     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3117     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3118     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3119     RuntimeEnabledFeatures::sharedFeatures().setWebAuthenticationEnabled(preferences.webAuthenticationEnabled);
3120     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3121     RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3122     RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3123     RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3124     RuntimeEnabledFeatures::sharedFeatures().setAriaReflectionEnabled([preferences ariaReflectionEnabled]);
3125     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3126
3127 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3128     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3129 #endif
3130
3131 #if ENABLE(ENCRYPTED_MEDIA)
3132     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3133 #endif
3134
3135     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3136
3137     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3138
3139     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3140     if (timeout > 0)
3141         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3142
3143     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3144     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3145
3146     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3147     if (_private->zoomsTextOnly != zoomsTextOnly)
3148         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3149
3150 #if PLATFORM(IOS)
3151     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3152     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3153     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3154     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3155 #endif
3156
3157 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3158     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3159 #endif
3160
3161     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3162
3163     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3164
3165     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3166
3167     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3168     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3169     settings.setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3170
3171     RuntimeEnabledFeatures::sharedFeatures().setServerTimingEnabled([preferences serverTimingEnabled]);
3172 }
3173
3174 static inline IMP getMethod(id o, SEL s)
3175 {
3176     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3177 }
3178
3179 #if PLATFORM(IOS)
3180 - (id)_UIKitDelegateForwarder
3181 {
3182     if (_private->closing)
3183         return nil;
3184         
3185     if (!_private->UIKitDelegateForwarder)
3186         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3187     return _private->UIKitDelegateForwarder;
3188 }
3189 #endif
3190
3191 - (void)_cacheResourceLoadDelegateImplementations
3192 {
3193     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3194     id delegate = _private->resourceProgressDelegate;
3195
3196     if (!delegate) {
3197         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3198         return;
3199     }
3200
3201     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3202     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3203     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3204     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3205 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3206     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3207 #endif
3208
3209 #if PLATFORM(IOS)
3210     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3211     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3212     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3213     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3214     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3215     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3216     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3217     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3218     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3219 #endif
3220
3221     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3222     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3223     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3224     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3225     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3226     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3227     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3228     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3229 }
3230
3231 - (void)_cacheFrameLoadDelegateImplementations
3232 {
3233     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3234     id delegate = _private->frameLoadDelegate;
3235
3236     if (!delegate) {
3237         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3238         return;
3239     }
3240
3241     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3242     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3243     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3244     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3245     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3246 #if JSC_OBJC_API_ENABLED
3247     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3248 #endif
3249     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3250     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3251     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3252     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3253     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3254     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3255     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3256     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3257     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3258     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3259     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3260     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3261 #if ENABLE(ICONDATABASE)
3262     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3263 #endif
3264     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3265     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3266     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3267     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3268     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3269     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3270     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3271     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3272     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3273     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3274 #if PLATFORM(IOS)
3275     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3276 #endif
3277
3278     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3279     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3280     // for backwards compatibility.
3281     Page* page = core(self);
3282     if (page) {
3283         unsigned milestones = DidFirstLayout;
3284 #if PLATFORM(IOS)
3285         milestones |= DidFirstVisuallyNonEmptyLayout;
3286 #else
3287         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3288             milestones |= DidFirstVisuallyNonEmptyLayout;
3289 #endif
3290         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3291     }
3292 }
3293
3294 - (void)_cacheScriptDebugDelegateImplementations
3295 {
3296     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3297     id delegate = _private->scriptDebugDelegate;
3298
3299     if (!delegate) {
3300         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3301         return;
3302     }
3303
3304     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3305     if (cache->didParseSourceFunc)
3306         cache->didParseSourceExpectsBaseLineNumber = YES;
3307     else {
3308         cache->didParseSourceExpectsBaseLineNumber = NO;
3309         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3310     }
3311
3312     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3313
3314     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3315     if (cache->exceptionWasRaisedFunc)
3316         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3317     else {
3318         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3319         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3320     }
3321 }
3322
3323 - (void)_cacheHistoryDelegateImplementations
3324 {
3325     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3326     id delegate = _private->historyDelegate;
3327
3328     if (!delegate) {
3329         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3330         return;
3331     }
3332
3333     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3334     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3335     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3336     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3337     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3338     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3339 }
3340
3341 - (id)_policyDelegateForwarder
3342 {
3343 #if PLATFORM(IOS)
3344     if (_private->closing)
3345         return nil;
3346 #endif
3347     if (!_private->policyDelegateForwarder)
3348         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3349     return _private->policyDelegateForwarder;
3350 }
3351
3352 - (id)_UIDelegateForwarder
3353 {
3354 #if PLATFORM(IOS)
3355     if (_private->closing)
3356         return nil;
3357 #endif
3358     if (!_private->UIDelegateForwarder)
3359         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3360     return _private->UIDelegateForwarder;
3361 }
3362
3363 #if PLATFORM(IOS)
3364 - (id)_UIDelegateForSelector:(SEL)selector
3365 {
3366     id delegate = self->_private->UIDelegate;
3367     if ([delegate respondsToSelector:selector])
3368         return delegate;
3369
3370     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3371     if ([delegate respondsToSelector:selector])
3372         return delegate;
3373
3374     return nil;
3375 }
3376 #endif
3377
3378 - (id)_editingDelegateForwarder
3379 {
3380 #if PLATFORM(IOS)
3381     if (_private->closing)
3382         return nil;
3383 #endif    
3384     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3385     // Not sure if that is a bug or not.
3386     if (!_private)
3387         return nil;
3388
3389     if (!_private->editingDelegateForwarder)
3390         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3391     return _private->editingDelegateForwarder;
3392 }
3393
3394 - (void)_closeWindow
3395 {
3396     [[self _UIDelegateForwarder] webViewClose:self];
3397 }
3398
3399 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3400 {
3401     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3402     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3403     
3404     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3405     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3406     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3407     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3408 }
3409
3410 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3411 {
3412     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3413     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3414
3415     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3416     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3417     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3418     if ([viewClass class] == [WebHTMLView class])
3419         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3420     
3421     // This is used to make _representationExistsForURLScheme faster.
3422     // Without this set, we'd have to create the MIME type each time.
3423     if (schemesWithRepresentationsSet == nil) {
3424         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3425     }
3426     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3427 }
3428
3429 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3430 {
3431     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3432 }
3433
3434 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3435 {
3436     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3437 }
3438
3439 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3440 {
3441     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3442     if (!request)
3443         return NO;
3444
3445     if ([NSURLConnection canHandleRequest:request])
3446         return YES;
3447
3448     NSString *scheme = [[request URL] scheme];
3449
3450     // Representations for URL schemes work at the top level.
3451     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3452         return YES;
3453
3454     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3455         return YES;
3456
3457     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3458         return YES;
3459
3460     return NO;
3461 }
3462
3463 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3464 {
3465     return [self _canHandleRequest:request forMainFrame:YES];
3466 }
3467
3468 + (NSString *)_decodeData:(NSData *)data
3469 {
3470     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3471     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3472 }
3473
3474 - (void)_pushPerformingProgrammaticFocus
3475 {
3476     _private->programmaticFocusCount++;
3477 }
3478
3479 - (void)_popPerformingProgrammaticFocus
3480 {
3481     _private->programmaticFocusCount--;
3482 }
3483
3484 - (BOOL)_isPerformingProgrammaticFocus
3485 {
3486     return _private->programmaticFocusCount != 0;
3487 }
3488
3489 #if !PLATFORM(IOS)
3490 - (void)_didChangeValueForKey: (NSString *)key
3491 {
3492     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3493     [self didChangeValueForKey: key];
3494 }
3495
3496 - (void)_willChangeValueForKey: (NSString *)key
3497 {
3498     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3499     [self willChangeValueForKey: key];
3500 }
3501
3502 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3503     static NSSet *manualNotifyKeys = nil;
3504     if (!manualNotifyKeys)
3505         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3506             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3507             nil];
3508     if ([manualNotifyKeys containsObject:key])
3509         return NO;
3510     return YES;
3511 }
3512
3513 - (NSArray *)_declaredKeys {
3514     static NSArray *declaredKeys = nil;
3515     if (!declaredKeys)
3516         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3517             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3518     return declaredKeys;
3519 }
3520
3521 - (void)_willChangeBackForwardKeys
3522 {
3523     [self _willChangeValueForKey: _WebCanGoBackKey];
3524     [self _willChangeValueForKey: _WebCanGoForwardKey];
3525 }
3526
3527 - (void)_didChangeBackForwardKeys
3528 {
3529     [self _didChangeValueForKey: _WebCanGoBackKey];
3530     [self _didChangeValueForKey: _WebCanGoForwardKey];
3531 }
3532
3533 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3534 {
3535     if (needsSelfRetainWhileLoadingQuirk())
3536         [self retain];
3537
3538     [self _willChangeBackForwardKeys];
3539     if (frame == [self mainFrame]){
3540         // Force an observer update by sending a will/did.
3541         [self _willChangeValueForKey: _WebIsLoadingKey];
3542         [self _didChangeValueForKey: _WebIsLoadingKey];
3543
3544         [self _willChangeValueForKey: _WebMainFrameURLKey];
3545
3546         [self hideFormValidationMessage];
3547     }
3548
3549     [NSApp setWindowsNeedUpdate:YES];
3550
3551 #if ENABLE(FULLSCREEN_API)
3552     Document* document = core([frame DOMDocument]);
3553     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3554         SEL selector = @selector(webView:closeFullScreenWithListener:);
3555         if ([_private->UIDelegate respondsToSelector:selector]) {
3556             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3557             CallUIDelegate(self, selector, listener);
3558             [listener release];
3559         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3560             [_private->newFullscreenController close];
3561         }
3562     }
3563 #endif
3564 }
3565
3566 - (void)_checkDidPerformFirstNavigation
3567 {
3568     if (_private->_didPerformFirstNavigation)
3569         return;
3570
3571     Page* page = _private->page;
3572     if (!page)
3573         return;
3574
3575     auto& backForwardController = page->backForward();
3576
3577     if (!backForwardController.backItem())
3578         return;
3579
3580     _private->_didPerformFirstNavigation = YES;
3581
3582     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3583         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3584 }
3585
3586 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3587 {
3588     if (frame == [self mainFrame])
3589         [self _didChangeValueForKey: _WebMainFrameURLKey];
3590
3591     [self _checkDidPerformFirstNavigation];
3592
3593     [NSApp setWindowsNeedUpdate:YES];
3594 }
3595
3596 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3597 {
3598     if (needsSelfRetainWhileLoadingQuirk())
3599         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3600         
3601     [self _didChangeBackForwardKeys];
3602     if (frame == [self mainFrame]){
3603         // Force an observer update by sending a will/did.
3604         [self _willChangeValueForKey: _WebIsLoadingKey];
3605         [self _didChangeValueForKey: _WebIsLoadingKey];
3606     }
3607     [NSApp setWindowsNeedUpdate:YES];
3608 }
3609
3610 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3611 {
3612     if (needsSelfRetainWhileLoadingQuirk())
3613         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3614
3615     [self _didChangeBackForwardKeys];
3616     if (frame == [self mainFrame]){
3617         // Force an observer update by sending a will/did.
3618         [self _willChangeValueForKey: _WebIsLoadingKey];
3619         [self _didChangeValueForKey: _WebIsLoadingKey];
3620     }
3621     [NSApp setWindowsNeedUpdate:YES];
3622 }
3623
3624 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3625 {
3626     if (needsSelfRetainWhileLoadingQuirk())
3627         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3628
3629     [self _didChangeBackForwardKeys];
3630     if (frame == [self mainFrame]){
3631         // Force an observer update by sending a will/did.
3632         [self _willChangeValueForKey: _WebIsLoadingKey];
3633         [self _didChangeValueForKey: _WebIsLoadingKey];
3634         
3635         [self _didChangeValueForKey: _WebMainFrameURLKey];
3636     }
3637     [NSApp setWindowsNeedUpdate:YES];
3638 }
3639
3640 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3641 {
3642     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3643     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3644     NSCachedURLResponse *cachedResponse;
3645
3646     if (!_private->page)
3647         return nil;
3648
3649     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3650         cachedResponse = cachedResponseForRequest(storageSession, request.get());
3651     else
3652         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3653
3654     return cachedResponse;
3655 }
3656
3657 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3658 {
3659     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3660     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3661     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3662                         element:domElement
3663                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3664                           title:[element objectForKey:WebElementImageAltStringKey] 
3665                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3666                           types:types
3667                          source:nil];
3668 }
3669
3670 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3671 {
3672     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3673                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3674                         types:types];
3675 }
3676
3677 #if ENABLE(DRAG_SUPPORT)
3678 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3679 {
3680     if (!_private->page)
3681         return;
3682     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3683 }
3684 #endif
3685
3686 #else
3687
3688 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3689 {
3690     if (frame == [self mainFrame])
3691         _private->didDrawTiles = 0;
3692 }
3693
3694 #endif // PLATFORM(IOS)
3695
3696 #if ENABLE(DASHBOARD_SUPPORT)
3697
3698 #define DASHBOARD_CONTROL_LABEL @"control"
3699
3700 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3701 {
3702     NSRect adjustedBounds = bounds;
3703     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3704     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3705     adjustedBounds.size = bounds.size;
3706
3707     NSRect adjustedClip;
3708     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3709     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3710     adjustedClip.size = clip.size;
3711
3712     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3713         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3714     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3715     if (!scrollerRegions) {
3716         scrollerRegions = [[NSMutableArray alloc] init];
3717         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3718         [scrollerRegions release];
3719     }
3720     [scrollerRegions addObject:region];
3721     [region release];
3722 }
3723
3724 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3725 {    
3726     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3727
3728     for (const auto& widget: frameView->children()) {
3729         if (is<FrameView>(widget)) {
3730             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3731             continue;
3732         }
3733
3734         if (!widget->isScrollbar())
3735             continue;
3736
3737         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3738         // it's not common to need this to be correct in Dashboard widgets.
3739         NSRect bounds = widget->frameRect();
3740         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3741     }
3742 }
3743
3744 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3745 {
3746     // Add scroller regions for NSScroller and WebCore scrollbars
3747     NSUInteger count = [views count];
3748     for (NSUInteger i = 0; i < count; i++) {
3749         NSView *view = [views objectAtIndex:i];
3750         
3751         if ([view isKindOfClass:[WebHTMLView class]]) {
3752             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3753                 if (FrameView* coreView = coreFrame->view())
3754                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3755             }
3756         } else if ([view isKindOfClass:[NSScroller class]]) {
3757             // AppKit places absent scrollers at -100,-100
3758             if ([view frame].origin.y < 0)
3759                 continue;
3760             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3761         }
3762         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3763     }
3764 }
3765
3766 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3767 {
3768     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3769 }
3770
3771 - (NSDictionary *)_dashboardRegions
3772 {
3773     // Only return regions from main frame.
3774     Frame* mainFrame = [self _mainCoreFrame];
3775     if (!mainFrame)
3776         return nil;
3777
3778     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3779     size_t size = regions.size();
3780
3781     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3782     for (size_t i = 0; i < size; i++) {
3783         const AnnotatedRegionValue& region = regions[i];
3784
3785         if (region.type == StyleDashboardRegion::None)
3786             continue;
3787
3788         NSString *label = region.label;
3789         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3790         if (region.type == StyleDashboardRegion::Circle)
3791             type = WebDashboardRegionTypeCircle;
3792         else if (region.type == StyleDashboardRegion::Rectangle)
3793             type = WebDashboardRegionTypeRectangle;
3794         NSMutableArray *regionValues = [webRegions objectForKey:label];
3795         if (!regionValues) {
3796             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3797             [webRegions setObject:regionValues forKey:label];
3798             [regionValues release];
3799         }
3800
3801         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3802         [regionValues addObject:webRegion];
3803         [webRegion release];
3804     }
3805
3806     [self _addScrollerDashboardRegions:webRegions];
3807
3808     return webRegions;
3809 }
3810
3811 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3812 {
3813     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3814     // specific support for the backward compatibility mode flag.
3815     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3816         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3817     
3818     switch (behavior) {
3819         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3820             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3821             break;
3822         }
3823         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3824             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3825             break;
3826         }
3827         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3828             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3829             break;
3830         }
3831         case WebDashboardBehaviorAllowWheelScrolling: {
3832             _private->dashboardBehaviorAllowWheelScrolling = flag;
3833             break;
3834         }
3835         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3836             if (_private->page)
3837                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3838 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3839             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3840 #endif
3841             break;
3842         }
3843     }
3844
3845     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3846     // compatibility mode. See <rdar://problem/8175982>.
3847     if (_private->page)
3848         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3849 }
3850
3851 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3852 {
3853     switch (behavior) {
3854         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3855             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3856         }
3857         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3858             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3859         }
3860         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3861             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3862         }
3863         case WebDashboardBehaviorAllowWheelScrolling: {
3864             return _private->dashboardBehaviorAllowWheelScrolling;
3865         }
3866         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3867             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3868         }
3869     }
3870     return NO;
3871 }
3872
3873 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3874
3875 + (void)_setShouldUseFontSmoothing:(BOOL)f
3876 {
3877     FontCascade::setShouldUseSmoothing(f);
3878 }
3879
3880 + (BOOL)_shouldUseFontSmoothing
3881 {
3882     return FontCascade::shouldUseSmoothing();
3883 }
3884
3885 #if !PLATFORM(IOS)
3886 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3887 {
3888     setUsesTestModeFocusRingColor(f);
3889 }
3890
3891 + (BOOL)_usesTestModeFocusRingColor
3892 {
3893     return usesTestModeFocusRingColor();
3894 }
3895 #endif
3896
3897 #if PLATFORM(IOS)
3898 - (void)_setUIKitDelegate:(id)delegate
3899 {
3900     _private->UIKitDelegate = delegate;
3901     [_private->UIKitDelegateForwarder clearTarget];
3902     [_private->UIKitDelegateForwarder release];
3903     _private->UIKitDelegateForwarder = nil;
3904 }
3905
3906 - (id)_UIKitDelegate
3907 {
3908     return _private->UIKitDelegate;
3909 }
3910
3911 - (void)setWebMailDelegate:(id)delegate
3912 {
3913     _private->WebMailDelegate = delegate;
3914 }
3915
3916 - (id)_webMailDelegate
3917 {
3918     return _private->WebMailDelegate;
3919 }
3920
3921 - (id <WebCaretChangeListener>)caretChangeListener
3922 {
3923     return _private->_caretChangeListener;
3924 }
3925
3926 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3927 {
3928     _private->_caretChangeListener = listener;
3929 }
3930
3931 - (NSSet *)caretChangeListeners
3932 {
3933     return _private->_caretChangeListeners;
3934 }
3935
3936 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3937 {
3938     if (_private->_caretChangeListeners == nil) {
3939         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3940     }
3941     
3942     [_private->_caretChangeListeners addObject:listener];
3943 }
3944
3945 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3946 {
3947     [_private->_caretChangeListeners removeObject:listener];
3948 }
3949
3950 - (void)removeAllCaretChangeListeners
3951 {
3952     [_private->_caretChangeListeners removeAllObjects];
3953 }
3954
3955 - (void)caretChanged
3956 {
3957     [_private->_caretChangeListener caretChanged];
3958     NSSet *copy = [_private->_caretChangeListeners copy];
3959     for (id <WebCaretChangeListener> listener in copy) {
3960         [listener caretChanged];
3961     }
3962     [copy release];
3963 }
3964
3965 - (void)_clearDelegates
3966 {
3967     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3968     
3969     [self _setFormDelegate:nil];
3970     [self _setUIKitDelegate:nil];
3971     [self setCaretChangeListener:nil];
3972     [self removeAllCaretChangeListeners];
3973     [self setWebMailDelegate:nil];
3974     
3975     [self setDownloadDelegate:nil];
3976     [self setEditingDelegate:nil]; 
3977     [self setFrameLoadDelegate:nil];
3978     [self setPolicyDelegate:nil];
3979     [self setResourceLoadDelegate:nil];
3980     [self setScriptDebugDelegate:nil];
3981     [self setUIDelegate:nil];     
3982 }
3983
3984 - (NSURL *)_displayURL
3985 {
3986     WebThreadLock();
3987     WebFrame *frame = [self mainFrame];
3988     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3989     WebDataSource *dataSource = [frame provisionalDataSource];
3990     if (!dataSource)
3991         dataSource = [frame dataSource];
3992     NSURL *unreachableURL = [dataSource unreachableURL];
3993     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3994     [[URL retain] autorelease];
3995     return URL;
3996 }
3997 #endif // PLATFORM(IOS)
3998
3999 #if !PLATFORM(IOS)
4000 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
4001 {
4002     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4003     if (flag) {
4004         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4005     } else {
4006         [scrollview setVerticalScrollingModeLocked:NO];
4007         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
4008     }
4009 }
4010
4011 - (BOOL)alwaysShowVerticalScroller
4012 {
4013     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4014     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
4015 }
4016
4017 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
4018 {
4019     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4020     if (flag) {
4021         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4022     } else {
4023         [scrollview setHorizontalScrollingModeLocked:NO];
4024         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
4025     }
4026 }
4027
4028 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
4029 {
4030     if (Frame* mainFrame = [self _mainCoreFrame])
4031         mainFrame->view()->setProhibitsScrolling(prohibits);
4032 }
4033
4034 - (BOOL)alwaysShowHorizontalScroller
4035 {
4036     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4037     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
4038 }
4039 #endif // !PLATFORM(IOS)
4040
4041 - (void)_setUseFastImageScalingMode:(BOOL)flag
4042 {
4043     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
4044         _private->page->setInLowQualityImageInterpolationMode(flag);
4045         [self setNeedsDisplay:YES];
4046     }
4047 }
4048
4049 - (BOOL)_inFastImageScalingMode
4050 {
4051     if (_private->page)
4052         return _private->page->inLowQualityImageInterpolationMode();
4053     return NO;
4054 }
4055
4056 - (BOOL)_cookieEnabled
4057 {
4058     if (_private->page)
4059         return _private->page->settings().cookieEnabled();
4060     return YES;
4061 }
4062
4063 - (void)_setCookieEnabled:(BOOL)enable
4064 {
4065     if (_private->page)
4066         _private->page->settings().setCookieEnabled(enable);
4067 }
4068
4069 #if !PLATFORM(IOS)
4070 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
4071 {
4072     if (!_private->pluginDatabase)
4073         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
4074         
4075     [_private->pluginDatabase setPlugInPaths:newPaths];
4076     [_private->pluginDatabase refresh];
4077 }
4078 #endif
4079
4080 #if PLATFORM(IOS)
4081 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
4082 {
4083     // Ask plug-ins in this frame
4084     id <WebDocumentView> documentView = [[frame frameView] documentView];
4085     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
4086         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
4087             return YES;
4088     }
4089
4090     // Ask plug-ins in child frames
4091     NSArray *childFrames = [frame childFrames];
4092     unsigned childCount = [childFrames count];
4093     unsigned childIndex;
4094     for (childIndex = 0; childIndex < childCount; childIndex++) {
4095         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
4096             return YES;
4097     }
4098     
4099     return NO;
4100 }
4101
4102 - (BOOL)_pluginsAreRunning
4103 {
4104     WebThreadLock();
4105     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
4106 }
4107
4108 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
4109 {
4110     // Send the message to plug-ins in this frame
4111     id <WebDocumentView> documentView = [[frame frameView] documentView];
4112     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
4113         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
4114
4115     // Send the message to plug-ins in child frames
4116     NSArray *childFrames = [frame childFrames];
4117     unsigned childCount = [childFrames count];
4118     unsigned childIndex;
4119     for (childIndex = 0; childIndex < childCount; childIndex++) {
4120         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
4121     }
4122 }
4123
4124 - (void)_destroyAllPlugIns
4125 {
4126     WebThreadLock();
4127     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
4128 }
4129
4130 - (void)_startAllPlugIns
4131 {
4132     WebThreadLock();
4133     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
4134 }
4135
4136 - (void)_stopAllPlugIns
4137 {
4138     WebThreadLock();
4139     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
4140 }
4141
4142 - (void)_stopAllPlugInsForPageCache
4143 {
4144     WebThreadLock();
4145     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
4146 }
4147
4148 - (void)_restorePlugInsFromCache
4149 {
4150     WebThreadLock();
4151     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
4152 }
4153
4154 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
4155 {
4156     WebThreadLock();
4157
4158     Frame* mainCoreFrame = [self _mainCoreFrame];
4159     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
4160      &