2 * Copyright (C) 2005-2019 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4 * Copyright (C) 2010 Igalia S.L
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
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 "PageStorageSessionProvider.h"
41 #import "StorageThread.h"
42 #import "WebAlternativeTextClient.h"
43 #import "WebApplicationCacheInternal.h"
44 #import "WebArchive.h"
45 #import "WebBackForwardListInternal.h"
46 #import "WebBaseNetscapePluginView.h"
48 #import "WebChromeClient.h"
49 #import "WebDOMOperationsPrivate.h"
50 #import "WebDataSourceInternal.h"
51 #import "WebDatabaseManagerPrivate.h"
52 #import "WebDatabaseProvider.h"
53 #import "WebDefaultEditingDelegate.h"
54 #import "WebDefaultPolicyDelegate.h"
55 #import "WebDefaultUIDelegate.h"
56 #import "WebDelegateImplementationCaching.h"
57 #import "WebDeviceOrientationClient.h"
58 #import "WebDeviceOrientationProvider.h"
59 #import "WebDocument.h"
60 #import "WebDocumentInternal.h"
61 #import "WebDownload.h"
62 #import "WebDragClient.h"
63 #import "WebDynamicScrollBarsViewInternal.h"
64 #import "WebEditingDelegate.h"
65 #import "WebEditorClient.h"
66 #import "WebFormDelegatePrivate.h"
67 #import "WebFrameInternal.h"
68 #import "WebFrameLoadDelegatePrivate.h"
69 #import "WebFrameLoaderClient.h"
70 #import "WebFrameNetworkingContext.h"
71 #import "WebFrameViewInternal.h"
72 #import "WebGeolocationClient.h"
73 #import "WebGeolocationPositionInternal.h"
74 #import "WebHTMLRepresentation.h"
75 #import "WebHTMLViewInternal.h"
76 #import "WebHistoryDelegate.h"
77 #import "WebHistoryItemInternal.h"
78 #import "WebIconDatabase.h"
79 #import "WebInspector.h"
80 #import "WebInspectorClient.h"
81 #import "WebKitErrors.h"
82 #import "WebKitFullScreenListener.h"
83 #import "WebKitLogging.h"
84 #import "WebKitNSStringExtras.h"
85 #import "WebKitStatisticsPrivate.h"
86 #import "WebKitVersionChecks.h"
87 #import "WebLocalizableStrings.h"
88 #import "WebNSDataExtras.h"
89 #import "WebNSDataExtrasPrivate.h"
90 #import "WebNSDictionaryExtras.h"
91 #import "WebNSURLExtras.h"
92 #import "WebNSURLRequestExtras.h"
93 #import "WebNSViewExtras.h"
94 #import "WebNodeHighlight.h"
95 #import "WebNotificationClient.h"
96 #import "WebPDFView.h"
97 #import "WebPaymentCoordinatorClient.h"
98 #import "WebPlatformStrategies.h"
99 #import "WebPluginDatabase.h"
100 #import "WebPluginInfoProvider.h"
101 #import "WebPolicyDelegate.h"
102 #import "WebPreferenceKeysPrivate.h"
103 #import "WebPreferencesPrivate.h"
104 #import "WebProgressTrackerClient.h"
105 #import "WebResourceLoadDelegate.h"
106 #import "WebResourceLoadDelegatePrivate.h"
107 #import "WebResourceLoadScheduler.h"
108 #import "WebScriptDebugDelegate.h"
109 #import "WebScriptWorldInternal.h"
110 #import "WebSelectionServiceController.h"
111 #import "WebStorageManagerInternal.h"
112 #import "WebStorageNamespaceProvider.h"
113 #import "WebTextCompletionController.h"
114 #import "WebTextIterator.h"
115 #import "WebUIDelegate.h"
116 #import "WebUIDelegatePrivate.h"
117 #import "WebValidationMessageClient.h"
118 #import "WebViewGroup.h"
119 #import "WebVisitedLinkStore.h"
120 #import <CoreFoundation/CFSet.h>
121 #import <Foundation/NSURLConnection.h>
122 #import <JavaScriptCore/APICast.h>
123 #import <JavaScriptCore/ArrayPrototype.h>
124 #import <JavaScriptCore/CatchScope.h>
125 #import <JavaScriptCore/DateInstance.h>
126 #import <JavaScriptCore/Exception.h>
127 #import <JavaScriptCore/InitializeThreading.h>
128 #import <JavaScriptCore/JSCJSValue.h>
129 #import <JavaScriptCore/JSLock.h>
130 #import <JavaScriptCore/JSValueRef.h>
131 #import <WebCore/AlternativeTextUIController.h>
132 #import <WebCore/ApplicationCacheStorage.h>
133 #import <WebCore/BackForwardController.h>
134 #import <WebCore/CSSAnimationController.h>
135 #import <WebCore/CacheStorageProvider.h>
136 #import <WebCore/Chrome.h>
137 #import <WebCore/ColorMac.h>
138 #import <WebCore/CookieJar.h>
139 #import <WebCore/DatabaseManager.h>
140 #import <WebCore/DeprecatedGlobalSettings.h>
141 #import <WebCore/DictionaryLookup.h>
142 #import <WebCore/Document.h>
143 #import <WebCore/DocumentLoader.h>
144 #import <WebCore/DragController.h>
145 #import <WebCore/DragData.h>
146 #import <WebCore/DragItem.h>
147 #import <WebCore/Editing.h>
148 #import <WebCore/Editor.h>
149 #import <WebCore/Event.h>
150 #import <WebCore/EventHandler.h>
151 #import <WebCore/FocusController.h>
152 #import <WebCore/FontAttributes.h>
153 #import <WebCore/FontCache.h>
154 #import <WebCore/Frame.h>
155 #import <WebCore/FrameLoader.h>
156 #import <WebCore/FrameSelection.h>
157 #import <WebCore/FrameTree.h>
158 #import <WebCore/FrameView.h>
159 #import <WebCore/FullscreenManager.h>
160 #import <WebCore/GCController.h>
161 #import <WebCore/GameControllerGamepadProvider.h>
162 #import <WebCore/GeolocationController.h>
163 #import <WebCore/GeolocationError.h>
164 #import <WebCore/HTMLNames.h>
165 #import <WebCore/HTMLOListElement.h>
166 #import <WebCore/HTMLUListElement.h>
167 #import <WebCore/HTMLVideoElement.h>
168 #import <WebCore/HistoryController.h>
169 #import <WebCore/HistoryItem.h>
170 #import <WebCore/JSCSSStyleDeclaration.h>
171 #import <WebCore/JSDocument.h>
172 #import <WebCore/JSElement.h>
173 #import <WebCore/JSNodeList.h>
174 #import <WebCore/JSNotification.h>
175 #import <WebCore/LegacyNSPasteboardTypes.h>
176 #import <WebCore/LegacySchemeRegistry.h>
177 #import <WebCore/LibWebRTCProvider.h>
178 #import <WebCore/LocalizedStrings.h>
179 #import <WebCore/LogInitialization.h>
180 #import <WebCore/MIMETypeRegistry.h>
181 #import <WebCore/MemoryCache.h>
182 #import <WebCore/MemoryRelease.h>
183 #import <WebCore/NetworkStorageSession.h>
184 #import <WebCore/NodeList.h>
185 #import <WebCore/Notification.h>
186 #import <WebCore/NotificationController.h>
187 #import <WebCore/Page.h>
188 #import <WebCore/PageCache.h>
189 #import <WebCore/PageConfiguration.h>
190 #import <WebCore/PageGroup.h>
191 #import <WebCore/PathUtilities.h>
192 #import <WebCore/PlatformEventFactoryMac.h>
193 #import <WebCore/ProgressTracker.h>
194 #import <WebCore/RenderTheme.h>
195 #import <WebCore/RenderView.h>
196 #import <WebCore/RenderWidget.h>
197 #import <WebCore/ResourceHandle.h>
198 #import <WebCore/ResourceLoadObserver.h>
199 #import <WebCore/ResourceRequest.h>
200 #import <WebCore/RuntimeApplicationChecks.h>
201 #import <WebCore/RuntimeEnabledFeatures.h>
202 #import <WebCore/ScriptController.h>
203 #import <WebCore/SecurityOrigin.h>
204 #import <WebCore/SecurityPolicy.h>
205 #import <WebCore/Settings.h>
206 #import <WebCore/ShouldTreatAsContinuingLoad.h>
207 #import <WebCore/SocketProvider.h>
208 #import <WebCore/SocketStreamHandleImpl.h>
209 #import <WebCore/StringUtilities.h>
210 #import <WebCore/StyleProperties.h>
211 #import <WebCore/TextResourceDecoder.h>
212 #import <WebCore/ThreadCheck.h>
213 #import <WebCore/UTIRegistry.h>
214 #import <WebCore/UserAgent.h>
215 #import <WebCore/UserContentController.h>
216 #import <WebCore/UserGestureIndicator.h>
217 #import <WebCore/UserScript.h>
218 #import <WebCore/UserStyleSheet.h>
219 #import <WebCore/ValidationBubble.h>
220 #import <WebCore/WebCoreObjCExtras.h>
221 #import <WebCore/WebCoreView.h>
222 #import <WebCore/Widget.h>
223 #import <WebKitLegacy/DOM.h>
224 #import <WebKitLegacy/DOMExtensions.h>
225 #import <WebKitLegacy/DOMPrivate.h>
226 #import <mach-o/dyld.h>
227 #import <objc/runtime.h>
228 #import <pal/spi/cf/CFNetworkSPI.h>
229 #import <pal/spi/cf/CFUtilitiesSPI.h>
230 #import <pal/spi/cg/CoreGraphicsSPI.h>
231 #import <pal/spi/cocoa/NSTouchBarSPI.h>
232 #import <pal/spi/cocoa/NSURLDownloadSPI.h>
233 #import <pal/spi/cocoa/NSURLFileTypeMappingsSPI.h>
234 #import <pal/spi/mac/NSResponderSPI.h>
235 #import <pal/spi/mac/NSSpellCheckerSPI.h>
236 #import <pal/spi/mac/NSViewSPI.h>
237 #import <pal/spi/mac/NSWindowSPI.h>
238 #import <wtf/Assertions.h>
239 #import <wtf/FileSystem.h>
240 #import <wtf/HashTraits.h>
241 #import <wtf/MainThread.h>
242 #import <wtf/ObjCRuntimeExtras.h>
243 #import <wtf/ProcessPrivilege.h>
244 #import <wtf/RAMSize.h>
245 #import <wtf/RefCountedLeakCounter.h>
246 #import <wtf/RefPtr.h>
247 #import <wtf/RunLoop.h>
248 #import <wtf/SetForScope.h>
249 #import <wtf/SoftLinking.h>
250 #import <wtf/StdLibExtras.h>
251 #import <wtf/WeakObjCPtr.h>
252 #import <wtf/WorkQueue.h>
253 #import <wtf/spi/darwin/dyldSPI.h>
255 #if !PLATFORM(IOS_FAMILY)
256 #import "WebContextMenuClient.h"
257 #import "WebFullScreenController.h"
258 #import "WebImmediateActionController.h"
259 #import "WebNSEventExtras.h"
260 #import "WebNSObjectExtras.h"
261 #import "WebNSPasteboardExtras.h"
262 #import "WebNSPrintOperationExtras.h"
263 #import "WebPDFView.h"
264 #import "WebSwitchingGPUClient.h"
265 #import "WebVideoFullscreenController.h"
266 #import <WebCore/TextIndicator.h>
267 #import <WebCore/TextIndicatorWindow.h>
268 #import <pal/spi/cocoa/AVKitSPI.h>
269 #import <pal/spi/mac/LookupSPI.h>
270 #import <pal/spi/mac/NSImmediateActionGestureRecognizerSPI.h>
272 #import "MemoryMeasure.h"
273 #import "WebCaretChangeListener.h"
274 #import "WebChromeClientIOS.h"
275 #import "WebDefaultFormDelegate.h"
276 #import "WebDefaultFrameLoadDelegate.h"
277 #import "WebDefaultResourceLoadDelegate.h"
278 #import "WebDefaultUIKitDelegate.h"
279 #import "WebFixedPositionContent.h"
280 #import "WebMailDelegate.h"
281 #import "WebNSUserDefaultsExtras.h"
282 #import "WebPDFViewIOS.h"
283 #import "WebPlainWhiteView.h"
284 #import "WebPluginController.h"
285 #import "WebPolicyDelegatePrivate.h"
286 #import "WebStorageManagerPrivate.h"
287 #import "WebUIKitSupport.h"
288 #import "WebVisiblePosition.h"
289 #import <WebCore/EventNames.h>
290 #import <WebCore/FontCache.h>
291 #import <WebCore/GraphicsLayer.h>
292 #import <WebCore/LegacyTileCache.h>
293 #import <WebCore/PlatformScreen.h>
294 #import <WebCore/ResourceLoadStatistics.h>
295 #import <WebCore/SQLiteDatabaseTracker.h>
296 #import <WebCore/SmartReplace.h>
297 #import <WebCore/TileControllerMemoryHandlerIOS.h>
298 #import <WebCore/WAKWindow.h>
299 #import <WebCore/WKView.h>
300 #import <WebCore/WebCoreThread.h>
301 #import <WebCore/WebCoreThreadMessage.h>
302 #import <WebCore/WebCoreThreadRun.h>
303 #import <WebCore/WebEvent.h>
304 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
305 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
306 #import <libkern/OSAtomic.h>
307 #import <pal/spi/ios/MobileGestaltSPI.h>
308 #import <wtf/FastMalloc.h>
311 #if ENABLE(REMOTE_INSPECTOR)
312 #import <JavaScriptCore/RemoteInspector.h>
313 #if PLATFORM(IOS_FAMILY)
314 #import "WebIndicateLayer.h"
319 #include <WebCore/QuickLook.h>
322 #if ENABLE(IOS_TOUCH_EVENTS)
323 #import <WebCore/WebEventRegion.h>
327 #import <WebCore/HIDGamepadProvider.h>
330 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
331 #import "WebMediaPlaybackTargetPicker.h"
332 #import <WebCore/WebMediaSessionManagerMac.h>
336 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
337 #import <WebCore/PlaybackSessionInterfaceMac.h>
338 #import <WebCore/PlaybackSessionModelMediaElement.h>
341 #if ENABLE(DATA_INTERACTION)
342 #import <UIKit/UIColor.h>
343 #import <UIKit/UIImage.h>
344 #import <pal/ios/UIKitSoftLink.h>
347 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
348 SOFT_LINK_FRAMEWORK(AVKit)
349 SOFT_LINK_CLASS(AVKit, AVTouchBarPlaybackControlsProvider)
350 SOFT_LINK_CLASS(AVKit, AVTouchBarScrubber)
351 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
353 #if !PLATFORM(IOS_FAMILY)
355 @interface NSSpellChecker (WebNSSpellCheckerDetails)
356 - (void)_preflightChosenSpellServer;
359 @interface NSView (WebNSViewDetails)
360 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
361 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
362 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
363 - (void)_windowChangedKeyState;
366 @interface NSWindow (WebNSWindowDetails)
367 - (void)_enableScreenUpdatesIfNeeded;
368 - (BOOL)_wrapsCarbonWindow;
369 - (BOOL)_hasKeyAppearance;
374 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
376 macro(alignJustified) \
379 macro(capitalizeWord) \
380 macro(centerSelectionInVisibleArea) \
381 macro(changeAttributes) \
382 _Pragma("clang diagnostic push") \
383 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
384 macro(changeBaseWritingDirection) \
385 macro(changeBaseWritingDirectionToLTR) \
386 macro(changeBaseWritingDirectionToRTL) \
387 _Pragma("clang diagnostic pop") \
389 macro(changeDocumentBackgroundColor) \
391 macro(changeSpelling) \
392 macro(checkSpelling) \
398 macro(deleteBackward) \
399 macro(deleteBackwardByDecomposingPreviousCharacter) \
400 macro(deleteForward) \
401 macro(deleteToBeginningOfLine) \
402 macro(deleteToBeginningOfParagraph) \
403 macro(deleteToEndOfLine) \
404 macro(deleteToEndOfParagraph) \
405 macro(deleteToMark) \
406 macro(deleteWordBackward) \
407 macro(deleteWordForward) \
408 macro(ignoreSpelling) \
410 macro(insertBacktab) \
411 macro(insertLineBreak) \
412 macro(insertNewline) \
413 macro(insertNewlineIgnoringFieldEditor) \
414 macro(insertParagraphSeparator) \
416 macro(insertTabIgnoringFieldEditor) \
417 macro(lowercaseWord) \
418 macro(makeBaseWritingDirectionLeftToRight) \
419 macro(makeBaseWritingDirectionRightToLeft) \
420 macro(makeTextWritingDirectionLeftToRight) \
421 macro(makeTextWritingDirectionNatural) \
422 macro(makeTextWritingDirectionRightToLeft) \
423 macro(moveBackward) \
424 macro(moveBackwardAndModifySelection) \
426 macro(moveDownAndModifySelection) \
428 macro(moveForwardAndModifySelection) \
430 macro(moveLeftAndModifySelection) \
431 macro(moveParagraphBackwardAndModifySelection) \
432 macro(moveParagraphForwardAndModifySelection) \
434 macro(moveRightAndModifySelection) \
435 macro(moveToBeginningOfDocument) \
436 macro(moveToBeginningOfDocumentAndModifySelection) \
437 macro(moveToBeginningOfLine) \
438 macro(moveToBeginningOfLineAndModifySelection) \
439 macro(moveToBeginningOfParagraph) \
440 macro(moveToBeginningOfParagraphAndModifySelection) \
441 macro(moveToBeginningOfSentence) \
442 macro(moveToBeginningOfSentenceAndModifySelection) \
443 macro(moveToEndOfDocument) \
444 macro(moveToEndOfDocumentAndModifySelection) \
445 macro(moveToEndOfLine) \
446 macro(moveToEndOfLineAndModifySelection) \
447 macro(moveToEndOfParagraph) \
448 macro(moveToEndOfParagraphAndModifySelection) \
449 macro(moveToEndOfSentence) \
450 macro(moveToEndOfSentenceAndModifySelection) \
451 macro(moveToLeftEndOfLine) \
452 macro(moveToLeftEndOfLineAndModifySelection) \
453 macro(moveToRightEndOfLine) \
454 macro(moveToRightEndOfLineAndModifySelection) \
456 macro(moveUpAndModifySelection) \
457 macro(moveWordBackward) \
458 macro(moveWordBackwardAndModifySelection) \
459 macro(moveWordForward) \
460 macro(moveWordForwardAndModifySelection) \
461 macro(moveWordLeft) \
462 macro(moveWordLeftAndModifySelection) \
463 macro(moveWordRight) \
464 macro(moveWordRightAndModifySelection) \
465 macro(orderFrontSubstitutionsPanel) \
469 macro(pageDownAndModifySelection) \
471 macro(pageUpAndModifySelection) \
473 macro(pasteAsPlainText) \
474 macro(pasteAsRichText) \
476 macro(performFindPanelAction) \
477 macro(scrollLineDown) \
478 macro(scrollLineUp) \
479 macro(scrollPageDown) \
480 macro(scrollPageUp) \
481 macro(scrollToBeginningOfDocument) \
482 macro(scrollToEndOfDocument) \
485 macro(selectParagraph) \
486 macro(selectSentence) \
487 macro(selectToMark) \
490 macro(showGuessPanel) \
491 macro(startSpeaking) \
492 macro(stopSpeaking) \
495 macro(swapWithMark) \
496 _Pragma("clang diagnostic push") \
497 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
498 macro(takeFindStringFromSelection) \
499 _Pragma("clang diagnostic pop") \
500 macro(toggleBaseWritingDirection) \
504 macro(uppercaseWord) \
506 _Pragma("clang diagnostic push") \
507 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
508 macro(yankAndSelect) \
509 _Pragma("clang diagnostic pop") \
511 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
512 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
514 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
515 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
517 static BOOL s_didSetCacheModel;
518 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
520 #if PLATFORM(IOS_FAMILY)
521 static Class s_pdfRepresentationClass;
522 static Class s_pdfViewClass;
526 static const char webViewIsOpen[] = "At least one WebView is still open.";
529 #if PLATFORM(IOS_FAMILY)
530 @interface WebView(WebViewPrivate)
531 - (void)_preferencesChanged:(WebPreferences *)preferences;
532 - (void)_updateScreenScaleFromWindow;
536 #if !PLATFORM(IOS_FAMILY)
537 @interface NSObject (WebValidateWithoutDelegate)
538 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
542 #if PLATFORM(IOS_FAMILY)
543 @class _WebSafeForwarder;
545 @interface _WebSafeAsyncForwarder : NSObject {
546 _WebSafeForwarder *_forwarder;
548 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
552 @interface _WebSafeForwarder : NSObject
554 id target; // Non-retained. Don't retain delegates.
556 #if PLATFORM(IOS_FAMILY)
557 _WebSafeAsyncForwarder *asyncForwarder;
558 dispatch_once_t asyncForwarderPred;
561 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
562 #if PLATFORM(IOS_FAMILY)
564 - (id)asyncForwarder;
568 WebCore::FindOptions coreOptions(WebFindOptions options)
570 WebCore::FindOptions findOptions;
571 if (options & WebFindOptionsCaseInsensitive)
572 findOptions.add(WebCore::CaseInsensitive);
573 if (options & WebFindOptionsAtWordStarts)
574 findOptions.add(WebCore::AtWordStarts);
575 if (options & WebFindOptionsTreatMedialCapitalAsWordStart)
576 findOptions.add(WebCore::TreatMedialCapitalAsWordStart);
577 if (options & WebFindOptionsBackwards)
578 findOptions.add(WebCore::Backwards);
579 if (options & WebFindOptionsWrapAround)
580 findOptions.add(WebCore::WrapAround);
581 if (options & WebFindOptionsStartInSelection)
582 findOptions.add(WebCore::StartInSelection);
586 OptionSet<WebCore::LayoutMilestone> coreLayoutMilestones(WebLayoutMilestones milestones)
588 OptionSet<WebCore::LayoutMilestone> layoutMilestone;
589 if (milestones & WebDidFirstLayout)
590 layoutMilestone.add(WebCore::DidFirstLayout);
591 if (milestones & WebDidFirstVisuallyNonEmptyLayout)
592 layoutMilestone.add(WebCore::DidFirstVisuallyNonEmptyLayout);
593 if (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold)
594 layoutMilestone.add(WebCore::DidHitRelevantRepaintedObjectsAreaThreshold);
595 return layoutMilestone;
598 WebLayoutMilestones kitLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
600 return (milestones & WebCore::DidFirstLayout ? WebDidFirstLayout : 0)
601 | (milestones & WebCore::DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
602 | (milestones & WebCore::DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
605 static WebPageVisibilityState kit(WebCore::VisibilityState visibilityState)
607 switch (visibilityState) {
608 case WebCore::VisibilityState::Visible:
609 return WebPageVisibilityStateVisible;
610 case WebCore::VisibilityState::Hidden:
611 return WebPageVisibilityStateHidden;
612 case WebCore::VisibilityState::Prerender:
613 return WebPageVisibilityStatePrerender;
616 ASSERT_NOT_REACHED();
617 return WebPageVisibilityStateVisible;
622 class DeferredPageDestructor {
624 static void createDeferredPageDestructor(std::unique_ptr<WebCore::Page> page)
626 new DeferredPageDestructor(WTFMove(page));
630 DeferredPageDestructor(std::unique_ptr<WebCore::Page> page)
631 : m_page(WTFMove(page))
636 void tryDestruction()
638 if (m_page->insideNestedRunLoop()) {
639 m_page->whenUnnested([this] { tryDestruction(); });
647 std::unique_ptr<WebCore::Page> m_page;
650 } // namespace WebKit
652 #if ENABLE(DATA_INTERACTION)
654 @implementation WebUITextIndicatorData
656 @synthesize dataInteractionImage=_dataInteractionImage;
657 @synthesize selectionRectInRootViewCoordinates=_selectionRectInRootViewCoordinates;
658 @synthesize textBoundingRectInRootViewCoordinates=_textBoundingRectInRootViewCoordinates;
659 @synthesize textRectsInBoundingRectCoordinates=_textRectsInBoundingRectCoordinates;
660 @synthesize contentImageWithHighlight=_contentImageWithHighlight;
661 @synthesize contentImageWithoutSelection=_contentImageWithoutSelection;
662 @synthesize contentImageWithoutSelectionRectInRootViewCoordinates=_contentImageWithoutSelectionRectInRootViewCoordinates;
663 @synthesize contentImage=_contentImage;
664 @synthesize estimatedBackgroundColor=_estimatedBackgroundColor;
668 [_dataInteractionImage release];
669 [_textRectsInBoundingRectCoordinates release];
670 [_contentImageWithHighlight release];
671 [_contentImageWithoutSelection release];
672 [_contentImage release];
673 [_estimatedBackgroundColor release];
680 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
682 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(const WebCore::TextIndicatorData&)indicatorData scale:(CGFloat)scale
684 if (!(self = [super init]))
687 _dataInteractionImage = [PAL::allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
688 _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
689 _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
691 NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
692 for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
693 [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
694 _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
695 _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
696 if (indicatorData.contentImageWithHighlight)
697 _contentImageWithHighlight = [PAL::allocUIImageInstance() initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored];
698 if (indicatorData.contentImage)
699 _contentImage = [PAL::allocUIImageInstance() initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationUp];
701 if (indicatorData.contentImageWithoutSelection) {
702 auto nativeImage = indicatorData.contentImageWithoutSelection.get()->nativeImage();
704 _contentImageWithoutSelection = [PAL::allocUIImageInstance() initWithCGImage:nativeImage.get() scale:scale orientation:UIImageOrientationUp];
705 _contentImageWithoutSelectionRectInRootViewCoordinates = indicatorData.contentImageWithoutSelectionRectInRootViewCoordinates;
709 if (indicatorData.options & WebCore::TextIndicatorOptionComputeEstimatedBackgroundColor)
710 _estimatedBackgroundColor = [PAL::allocUIColorInstance() initWithCGColor:cachedCGColor(indicatorData.estimatedBackgroundColor)];
715 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
717 if (!(self = [super init]))
720 _dataInteractionImage = [PAL::allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
727 @implementation WebUITextIndicatorData
729 #endif // ENABLE(DATA_INTERACTION)
731 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
732 NSString *WebElementFrameKey = @"WebElementFrame";
733 NSString *WebElementImageKey = @"WebElementImage";
734 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
735 NSString *WebElementImageRectKey = @"WebElementImageRect";
736 NSString *WebElementImageURLKey = @"WebElementImageURL";
737 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
738 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
739 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
740 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
741 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
742 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
743 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
744 NSString *WebElementTitleKey = @"WebElementTitle";
745 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
746 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
747 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
749 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
750 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
751 #if !PLATFORM(IOS_FAMILY)
752 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
754 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
755 NSString * const WebViewProgressBackgroundColorKey = @"WebProgressBackgroundColorKey";
758 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
759 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
760 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
761 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
762 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
764 enum { WebViewVersion = 4 };
766 #define timedLayoutSize 4096
768 static NSMutableSet *schemesWithRepresentationsSet;
770 #if !PLATFORM(IOS_FAMILY)
771 NSString *_WebCanGoBackKey = @"canGoBack";
772 NSString *_WebCanGoForwardKey = @"canGoForward";
773 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
774 NSString *_WebIsLoadingKey = @"isLoading";
775 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
776 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
777 NSString *_WebMainFrameURLKey = @"mainFrameURL";
778 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
781 #if PLATFORM(IOS_FAMILY)
782 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
783 NSString *WebQuickLookUTIKey = @"WebQuickLookUTIKey";
786 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
787 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
789 #if ENABLE(REMOTE_INSPECTOR)
790 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
791 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
794 @interface WebProgressItem : NSObject
797 long long bytesReceived;
798 long long estimatedLength;
802 @implementation WebProgressItem
805 static BOOL continuousSpellCheckingEnabled;
806 static BOOL iconLoadingEnabled = YES;
807 #if !PLATFORM(IOS_FAMILY)
808 static BOOL grammarCheckingEnabled;
809 static BOOL automaticQuoteSubstitutionEnabled;
810 static BOOL automaticLinkDetectionEnabled;
811 static BOOL automaticDashSubstitutionEnabled;
812 static BOOL automaticTextReplacementEnabled;
813 static BOOL automaticSpellingCorrectionEnabled;
818 enum class WebListType {
824 @interface WebTextListTouchBarViewController : NSViewController {
826 WebListType _currentListType;
830 @property (nonatomic) WebListType currentListType;
832 - (instancetype)initWithWebView:(WebView *)webView;
836 @implementation WebTextListTouchBarViewController
838 @synthesize currentListType=_currentListType;
840 static const CGFloat listControlSegmentWidth = 67.0;
842 static const NSUInteger noListSegment = 0;
843 static const NSUInteger unorderedListSegment = 1;
844 static const NSUInteger orderedListSegment = 2;
846 - (instancetype)initWithWebView:(WebView *)webView
848 if (!(self = [super init]))
853 NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
854 [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
855 [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
856 [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
857 insertListControl.font = [NSFont systemFontOfSize:15];
859 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
860 id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
861 NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
862 ASSERT(segments.count == 3);
863 [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
864 [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
865 [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
866 ALLOW_DEPRECATED_DECLARATIONS_END
868 self.view = insertListControl;
873 - (void)_selectList:(id)sender
875 NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
876 if (![documentView isKindOfClass:[WebHTMLView class]])
879 WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
880 NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
881 switch (insertListControl.selectedSegment) {
883 // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
884 // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
885 // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
886 if (_currentListType == WebListType::Ordered)
887 [webHTMLView _insertOrderedList];
888 else if (_currentListType == WebListType::Unordered)
889 [webHTMLView _insertUnorderedList];
891 case unorderedListSegment:
892 [webHTMLView _insertUnorderedList];
894 case orderedListSegment:
895 [webHTMLView _insertOrderedList];
899 [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
902 - (void)setCurrentListType:(WebListType)listType
904 NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
906 case WebListType::None:
907 [insertListControl setSelected:YES forSegment:noListSegment];
909 case WebListType::Ordered:
910 [insertListControl setSelected:YES forSegment:orderedListSegment];
912 case WebListType::Unordered:
913 [insertListControl setSelected:YES forSegment:unorderedListSegment];
917 _currentListType = listType;
922 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
926 BOOL _textIsUnderlined;
927 NSTextAlignment _currentTextAlignment;
928 RetainPtr<NSColor> _textColor;
929 RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
933 @property (nonatomic) BOOL textIsBold;
934 @property (nonatomic) BOOL textIsItalic;
935 @property (nonatomic) BOOL textIsUnderlined;
936 @property (nonatomic) NSTextAlignment currentTextAlignment;
937 @property (nonatomic, retain, readwrite) NSColor *textColor;
939 - (instancetype)initWithWebView:(WebView *)webView;
942 @implementation WebTextTouchBarItemController
944 @synthesize textIsBold=_textIsBold;
945 @synthesize textIsItalic=_textIsItalic;
946 @synthesize textIsUnderlined=_textIsUnderlined;
947 @synthesize currentTextAlignment=_currentTextAlignment;
949 - (instancetype)initWithWebView:(WebView *)webView
951 if (!(self = [super init]))
959 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
961 NSTouchBarItem *item = [super itemForIdentifier:identifier];
962 BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
964 if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
965 self.textStyle.action = @selector(_webChangeTextStyle:);
967 if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
968 self.textAlignments.action = @selector(_webChangeTextAlignment:);
970 NSColorPickerTouchBarItem *colorPickerItem = nil;
971 if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
972 colorPickerItem = (NSColorPickerTouchBarItem *)item;
973 if (isTextFormatItem)
974 colorPickerItem = self.colorPickerItem;
975 if (colorPickerItem) {
976 colorPickerItem.target = self;
977 colorPickerItem.action = @selector(_webChangeColor:);
978 colorPickerItem.showsAlpha = NO;
984 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
986 return (WebTextListTouchBarViewController *)self.textListViewController;
989 - (void)setTextIsBold:(BOOL)bold
992 if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
993 [self.textStyle setSelected:_textIsBold forSegment:0];
996 - (void)setTextIsItalic:(BOOL)italic
998 _textIsItalic = italic;
999 if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
1000 [self.textStyle setSelected:_textIsItalic forSegment:1];
1003 - (void)setTextIsUnderlined:(BOOL)underlined
1005 _textIsUnderlined = underlined;
1006 if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
1007 [self.textStyle setSelected:_textIsUnderlined forSegment:2];
1010 - (void)_webChangeTextStyle:(id)sender
1012 if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
1013 _textIsBold = !_textIsBold;
1014 [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
1017 if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
1018 _textIsItalic = !_textIsItalic;
1019 [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
1022 if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
1023 _textIsUnderlined = !_textIsUnderlined;
1024 [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
1028 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
1030 _currentTextAlignment = alignment;
1031 [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
1034 - (void)_webChangeTextAlignment:(id)sender
1036 NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
1037 switch (alignment) {
1038 case NSTextAlignmentLeft:
1039 _currentTextAlignment = NSTextAlignmentLeft;
1040 [_webView alignLeft:sender];
1042 case NSTextAlignmentRight:
1043 _currentTextAlignment = NSTextAlignmentRight;
1044 [_webView alignRight:sender];
1046 case NSTextAlignmentCenter:
1047 _currentTextAlignment = NSTextAlignmentCenter;
1048 [_webView alignCenter:sender];
1050 case NSTextAlignmentJustified:
1051 _currentTextAlignment = NSTextAlignmentJustified;
1052 [_webView alignJustified:sender];
1058 [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
1061 - (NSColor *)textColor
1063 return _textColor.get();
1066 - (void)setTextColor:(NSColor *)color
1069 self.colorPickerItem.color = _textColor.get();
1072 - (void)_webChangeColor:(id)sender
1074 _textColor = self.colorPickerItem.color;
1075 [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
1078 - (NSViewController *)textListViewController
1080 if (!_textListTouchBarViewController)
1081 _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
1082 return _textListTouchBarViewController.get();
1087 #endif // HAVE(TOUCH_BAR)
1089 @interface WebView ()
1090 #if PLATFORM(IOS_FAMILY)
1091 - (void)_wakWindowScreenScaleChanged:(NSNotification *)notification;
1092 - (void)_wakWindowVisibilityChanged:(NSNotification *)notification;
1094 - (float)_deviceScaleFactor;
1098 @implementation WebView (AllWebViews)
1100 static CFSetCallBacks NonRetainingSetCallbacks = {
1109 static CFMutableSetRef allWebViewsSet;
1111 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1113 if (!allWebViewsSet)
1116 [(__bridge NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1119 - (void)_removeFromAllWebViewsSet
1122 CFSetRemoveValue(allWebViewsSet, (__bridge CFTypeRef)self);
1125 - (void)_addToAllWebViewsSet
1127 if (!allWebViewsSet)
1128 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1130 CFSetSetValue(allWebViewsSet, (__bridge CFTypeRef)self);
1135 @implementation WebView (WebPrivate)
1137 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1139 return WebCore::standardUserAgentWithApplicationName(applicationName);
1142 #if PLATFORM(IOS_FAMILY)
1143 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1145 // The web-visible build and bundle versions are frozen to remove a fingerprinting surface
1146 UNUSED_PARAM(buildVersion);
1147 [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/15E148 Safari/%@", productVersion, bundleVersion]];
1150 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1152 UNUSED_PARAM(buildVersion);
1153 [self setApplicationNameForUserAgent:@"Mobile/15E148"];
1155 #endif // PLATFORM(IOS_FAMILY)
1157 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1159 if (!exception || !context)
1162 JSC::ExecState* execState = toJS(context);
1163 JSC::JSLockHolder lock(execState);
1165 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1166 JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1167 if (!WebCore::toJSDOMWindow(globalObject->vm(), globalObject))
1170 WebCore::reportException(execState, toJS(execState, exception));
1173 static bool shouldEnableLoadDeferring()
1175 #if PLATFORM(IOS_FAMILY)
1178 return !WebCore::MacApplication::isAdobeInstaller();
1182 static bool shouldRestrictWindowFocus()
1184 #if PLATFORM(IOS_FAMILY)
1187 return !WebCore::MacApplication::isHRBlock();
1191 - (void)_dispatchPendingLoadRequests
1193 webResourceLoadScheduler().servePendingRequests();
1196 #if !PLATFORM(IOS_FAMILY)
1198 - (void)_registerDraggedTypes
1200 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1201 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1202 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1203 [types addObjectsFromArray:URLTypes];
1204 [types addObject:[WebHTMLView _dummyPasteboardType]];
1205 [self registerForDraggedTypes:[types allObjects]];
1209 static bool needsOutlookQuirksScript()
1211 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1212 && WebCore::MacApplication::isMicrosoftOutlook();
1213 return isOutlookNeedingQuirksScript;
1216 static NSString *leakOutlookQuirksUserScriptContents()
1218 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1219 NSStringEncoding encoding;
1220 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1223 -(void)_injectOutlookQuirksScript
1225 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1226 _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), makeUnique<WebCore::UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), WebCore::InjectAtDocumentEnd, WebCore::InjectInAllFrames));
1231 static bool shouldRespectPriorityInCSSAttributeSetters()
1233 #if PLATFORM(IOS_FAMILY)
1236 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1237 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1238 return isIAdProducerNeedingAttributeSetterQuirk;
1242 #if PLATFORM(IOS_FAMILY)
1243 static bool isInternalInstall()
1245 static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1249 static bool didOneTimeInitialization = false;
1252 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1254 #if PLATFORM(IOS_FAMILY)
1255 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1257 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = WebCore::MacApplication::isVersions()
1258 && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1260 return shouldUseLegacyBackgroundSizeShorthandBehavior;
1263 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1265 static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1266 return shouldAllowDisplayAndRunningOfInsecureContent;
1269 static bool shouldAllowPictureInPictureMediaPlayback()
1271 #if PLATFORM(IOS_FAMILY)
1272 static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1273 return shouldAllowPictureInPictureMediaPlayback;
1279 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1281 #if PLATFORM(IOS_FAMILY)
1282 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1283 return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1289 static bool shouldAllowWindowOpenWithoutUserGesture()
1291 #if PLATFORM(IOS_FAMILY)
1292 static bool shouldAllowWindowOpenWithoutUserGesture = WebCore::IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1293 return shouldAllowWindowOpenWithoutUserGesture;
1299 static bool shouldConvertInvalidURLsToBlank()
1301 #if PLATFORM(IOS_FAMILY)
1302 static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1304 static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1306 static bool shouldConvertInvalidURLsToBlank = true;
1309 return shouldConvertInvalidURLsToBlank;
1312 static bool shouldRequireUserGestureToLoadVideo()
1314 #if PLATFORM(IOS_FAMILY)
1315 static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1316 return shouldRequireUserGestureToLoadVideo;
1323 static void WebKitInitializeGamepadProviderIfNecessary()
1325 static bool initialized = false;
1330 WebCore::GamepadProvider::singleton().setSharedProvider(WebCore::HIDGamepadProvider::singleton());
1332 WebCore::GamepadProvider::singleton().setSharedProvider(WebCore::GameControllerGamepadProvider::singleton());
1339 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1341 WebCoreThreadViolationCheckRoundTwo();
1344 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1347 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1348 [standardPreferences willAddToWebView];
1350 _private->preferences = [standardPreferences retain];
1351 _private->mainFrameDocumentReady = NO;
1352 _private->drawsBackground = YES;
1353 #if !PLATFORM(IOS_FAMILY)
1354 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1356 _private->backgroundColor = CGColorRetain(WebCore::cachedCGColor(WebCore::Color::white));
1360 _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1363 NSRect f = [self frame];
1364 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1365 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1366 [self addSubview:frameView];
1367 [frameView release];
1370 if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1371 RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1372 _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1373 [recognizer setDelegate:_private->immediateActionController];
1374 [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1378 [self updateTouchBar];
1380 #if !PLATFORM(IOS_FAMILY)
1381 static bool didOneTimeInitialization = false;
1383 if (!didOneTimeInitialization) {
1384 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1385 WebKitInitializeLogChannelsIfNecessary();
1386 WebCore::initializeLogChannelsIfNecessary();
1389 // Initialize our platform strategies first before invoking the rest
1390 // of the initialization code which may depend on the strategies.
1391 WebPlatformStrategies::initializeIfNecessary();
1393 initializeDOMWrapperHooks();
1395 #if PLATFORM(IOS_FAMILY)
1396 // Set the WebSQLiteDatabaseTrackerClient.
1397 WebCore::SQLiteDatabaseTracker::setClient(&WebCore::WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1399 if ([standardPreferences databasesEnabled])
1401 [WebDatabaseManager sharedWebDatabaseManager];
1403 #if PLATFORM(IOS_FAMILY)
1404 if ([standardPreferences storageTrackerEnabled])
1406 WebKitInitializeStorageIfNecessary();
1409 WebKitInitializeGamepadProviderIfNecessary();
1412 WebCore::SwitchingGPUClient::setSingleton(WebKit::WebSwitchingGPUClient::singleton());
1414 WebCore::DeprecatedGlobalSettings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1416 #if PLATFORM(IOS_FAMILY)
1417 if (WebCore::IOSApplication::isMobileSafari())
1418 WebCore::DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
1421 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitEnableLegacyTLS"])
1422 WebCore::SocketStreamHandleImpl::setLegacyTLSEnabled(true);
1424 didOneTimeInitialization = true;
1427 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1428 _private->group->addWebView(self);
1430 auto storageProvider = PageStorageSessionProvider::create();
1431 WebCore::PageConfiguration pageConfiguration(
1432 [[self preferences] privateBrowsingEnabled] ? PAL::SessionID::legacyPrivateSessionID() : PAL::SessionID::defaultSessionID(),
1433 makeUniqueRef<WebEditorClient>(self),
1434 WebCore::SocketProvider::create(),
1435 WebCore::LibWebRTCProvider::create(),
1436 WebCore::CacheStorageProvider::create(),
1437 BackForwardList::create(self),
1438 WebCore::CookieJar::create(storageProvider.copyRef())
1440 #if !PLATFORM(IOS_FAMILY)
1441 pageConfiguration.chromeClient = new WebChromeClient(self);
1442 pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1443 // FIXME: We should enable this on iOS as well.
1444 pageConfiguration.validationMessageClient = makeUnique<WebValidationMessageClient>(self);
1445 pageConfiguration.inspectorClient = new WebInspectorClient(self);
1447 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1448 pageConfiguration.inspectorClient = new WebInspectorClient(self);
1451 #if ENABLE(DRAG_SUPPORT)
1452 pageConfiguration.dragClient = new WebDragClient(self);
1455 #if ENABLE(APPLE_PAY)
1456 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1459 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1460 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1461 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1462 pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1463 pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1464 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1465 pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1466 pageConfiguration.userContentProvider = &_private->group->userContentController();
1467 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1468 _private->page = new WebCore::Page(WTFMove(pageConfiguration));
1469 storageProvider->setPage(*_private->page);
1471 _private->page->setGroupName(groupName);
1473 #if ENABLE(GEOLOCATION)
1474 WebCore::provideGeolocationTo(_private->page, *new WebGeolocationClient(self));
1476 #if ENABLE(NOTIFICATIONS)
1477 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1479 #if ENABLE(DEVICE_ORIENTATION) && !PLATFORM(IOS_FAMILY)
1480 WebCore::provideDeviceOrientationTo(*_private->page, *new WebDeviceOrientationClient(self));
1483 #if ENABLE(REMOTE_INSPECTOR)
1484 _private->page->setRemoteInspectionAllowed(true);
1487 _private->page->setCanStartMedia([self window]);
1488 _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1489 _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1491 #if !PLATFORM(IOS_FAMILY)
1492 if (needsOutlookQuirksScript()) {
1493 _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1494 [self _injectOutlookQuirksScript];
1498 #if PLATFORM(IOS_FAMILY)
1499 _private->page->settings().setPassiveTouchListenersAsDefaultOnDocument(linkedOnOrAfter(SDKVersion::FirstThatDefaultsToPassiveTouchListenersOnDocument));
1502 #if PLATFORM(IOS_FAMILY)
1503 // Preserve the behavior we had before <rdar://problem/7580867>
1504 // by enforcing a 5MB limit for session storage.
1505 _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1507 [self _updateScreenScaleFromWindow];
1508 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1509 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1510 _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1511 #if ENABLE(ORIENTATION_EVENTS)
1512 _private->deviceOrientation = [[self _UIKitDelegateForwarder] deviceOrientation];
1516 if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1517 [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1519 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1521 #if PLATFORM(IOS_FAMILY)
1522 NSRunLoop *runLoop = WebThreadNSRunLoop();
1524 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1527 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1528 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1530 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1532 [self _addToAllWebViewsSet];
1534 // If there's already a next key view (e.g., from a nib), wire it up to our
1535 // contained frame view. In any case, wire our next key view up to the our
1536 // contained frame view. This works together with our becomeFirstResponder
1537 // and setNextKeyView overrides.
1538 NSView *nextKeyView = [self nextKeyView];
1539 if (nextKeyView && nextKeyView != frameView)
1540 [frameView setNextKeyView:nextKeyView];
1541 [super setNextKeyView:frameView];
1543 if ([[self class] shouldIncludeInWebKitStatistics])
1546 #if !PLATFORM(IOS_FAMILY)
1547 [self _registerDraggedTypes];
1550 [self _setIsVisible:[self _isViewVisible]];
1552 WebPreferences *prefs = [self preferences];
1553 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1554 name:WebPreferencesChangedInternalNotification object:prefs];
1556 #if !PLATFORM(IOS_FAMILY)
1557 [self _preferencesChanged:[self preferences]];
1558 [[self preferences] _postPreferencesChangedAPINotification];
1560 // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1561 // and prefs need to be changed synchronously <rdar://problem/5841558>
1562 [self _preferencesChanged:prefs];
1563 _private->page->settings().setFontFallbackPrefersPictographs(true);
1566 WebInstallMemoryPressureHandler();
1568 #if !PLATFORM(IOS_FAMILY)
1569 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1570 // Originally, we allowed all local loads.
1571 WebCore::SecurityPolicy::setLocalLoadPolicy(WebCore::SecurityPolicy::AllowLocalLoadsForAll);
1572 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1573 // Later, we allowed local loads for local URLs and documents loaded
1574 // with substitute data.
1575 WebCore::SecurityPolicy::setLocalLoadPolicy(WebCore::SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1580 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1581 WebCore::ResourceHandle::forceContentSniffing();
1583 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1586 #if HAVE(OS_DARK_MODE_SUPPORT) && PLATFORM(MAC)
1587 _private->page->effectiveAppearanceDidChange(self._effectiveAppearanceIsDark, self._effectiveUserInterfaceLevelIsElevated);
1590 _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1593 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1595 self = [super initWithFrame:f];
1599 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1600 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1601 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1602 // need for Safari to unset it to prevent it from being passed to applications it launches.
1603 // Unsetting it when a WebView is first created is as good a place as any.
1604 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1605 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1606 unsetenv("DYLD_FRAMEWORK_PATH");
1607 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1611 _private = [[WebViewPrivate alloc] init];
1612 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1613 [self setMaintainsBackForwardList: YES];
1617 - (void)_viewWillDrawInternal
1620 _private->page->updateRendering();
1623 + (NSArray *)_supportedMIMETypes
1625 // Load the plug-in DB allowing plug-ins to install types.
1626 [WebPluginDatabase sharedDatabase];
1627 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1630 #if !PLATFORM(IOS_FAMILY)
1631 + (NSArray *)_supportedFileExtensions
1633 NSMutableSet *extensions = [[NSMutableSet alloc] init];
1634 NSArray *MIMETypes = [self _supportedMIMETypes];
1635 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1637 while ((MIMEType = [enumerator nextObject]) != nil) {
1638 NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1639 if (extensionsForType) {
1640 [extensions addObjectsFromArray:extensionsForType];
1643 NSArray *uniqueExtensions = [extensions allObjects];
1644 [extensions release];
1645 return uniqueExtensions;
1649 #if PLATFORM(IOS_FAMILY)
1650 + (void)enableWebThread
1652 static BOOL isWebThreadEnabled = NO;
1653 if (!isWebThreadEnabled) {
1654 WebCoreObjCDeallocOnWebThread([DOMObject class]);
1655 WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1656 WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1657 WebCoreObjCDeallocOnWebThread([WebFrame class]);
1658 WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1659 WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1660 WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1661 WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1662 WebCoreObjCDeallocOnWebThread([WebView class]);
1663 WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1665 isWebThreadEnabled = YES;
1669 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1671 self = [super initWithFrame:frame];
1675 _private = [[WebViewPrivate alloc] init];
1678 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1682 preferences = [WebPreferences standardPreferences];
1683 [preferences willAddToWebView];
1685 _private->preferences = [preferences retain];
1686 _private->mainFrameDocumentReady = NO;
1687 _private->drawsBackground = YES;
1688 _private->backgroundColor = CGColorRetain(WebCore::cachedCGColor(WebCore::Color::white));
1690 WebFrameView *frameView = nil;
1691 frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1692 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1693 [self addSubview:frameView];
1694 [frameView release];
1696 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1697 _private->group->addWebView(self);
1699 auto storageProvider = PageStorageSessionProvider::create();
1700 WebCore::PageConfiguration pageConfiguration(
1701 [[self preferences] privateBrowsingEnabled] ? PAL::SessionID::legacyPrivateSessionID() : PAL::SessionID::defaultSessionID(),
1702 makeUniqueRef<WebEditorClient>(self),
1703 WebCore::SocketProvider::create(),
1704 WebCore::LibWebRTCProvider::create(),
1705 WebCore::CacheStorageProvider::create(),
1706 BackForwardList::create(self),
1707 WebCore::CookieJar::create(storageProvider.copyRef())
1709 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1710 #if ENABLE(DRAG_SUPPORT)
1711 pageConfiguration.dragClient = new WebDragClient(self);
1714 #if ENABLE(APPLE_PAY)
1715 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1718 pageConfiguration.inspectorClient = new WebInspectorClient(self);
1719 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1720 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1721 pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1722 pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1723 pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1724 pageConfiguration.userContentProvider = &_private->group->userContentController();
1725 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1726 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1728 _private->page = new WebCore::Page(WTFMove(pageConfiguration));
1729 storageProvider->setPage(*_private->page);
1731 [self setSmartInsertDeleteEnabled:YES];
1733 // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1734 // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1735 // This matches how UIKit sets up the preferences. We need to set default values for fonts though, <rdar://problem/6850611>.
1736 // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1737 _private->page->settings().setMinimumLogicalFontSize(9);
1738 _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1739 _private->page->settings().setDefaultFixedFontSize(13);
1740 _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1741 _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1743 _private->page->settings().setFontFallbackPrefersPictographs(true);
1744 _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1746 _private->page->settings().setScriptMarkupEnabled(false);
1747 _private->page->settings().setScriptEnabled(true);
1749 // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1750 _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1752 // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1753 _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1755 // This is a workaround for <rdar://problem/21309911>.
1756 _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1758 _private->page->setGroupName(groupName);
1760 #if ENABLE(REMOTE_INSPECTOR)
1761 _private->page->setRemoteInspectionAllowed(isInternalInstall());
1764 [self _updateScreenScaleFromWindow];
1765 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1766 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1768 [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1770 [self _addToAllWebViewsSet];
1774 WebCore::SecurityPolicy::setLocalLoadPolicy(WebCore::SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1776 WebCore::RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled(self.preferences.attachmentElementEnabled);
1781 + (void)_releaseMemoryNow
1784 WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1788 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1790 auto* frame = [self _mainCoreFrame];
1792 frame->loader().history().replaceCurrentItem(core(item));
1795 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1798 [WebView _releaseMemoryNow];
1799 dispatch_async(dispatch_get_main_queue(), handler);
1803 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1805 return WebCore::isCharacterSmartReplaceExempt(character, b);
1808 - (void)updateLayoutIgnorePendingStyleSheets
1811 for (auto* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1812 auto *document = frame->document();
1814 document->updateLayoutIgnorePendingStylesheets();
1820 #if PLATFORM(IOS_FAMILY)
1822 #if ENABLE(DRAG_SUPPORT)
1824 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1827 return _private->page->mainFrame().eventHandler().tryToBeginDragAtPoint(WebCore::IntPoint(clientPosition), WebCore::IntPoint(globalPosition));
1830 - (void)_startDrag:(const WebCore::DragItem&)dragItem
1832 auto& dragImage = dragItem.image;
1833 auto image = dragImage.get().get();
1834 auto indicatorData = dragImage.indicatorData();
1837 _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1839 _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1840 _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1841 _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1842 _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1843 _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1846 - (CGRect)_dataInteractionCaretRect
1849 if (auto* page = _private->page)
1850 return page->dragCaretController().caretRectInRootViewCoordinates();
1855 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1857 return _private->dataOperationTextIndicator.get();
1860 - (WebDragSourceAction)_dragSourceAction
1862 return _private->dragSourceAction;
1865 - (NSString *)_draggedLinkTitle
1867 return _private->draggedLinkTitle.get();
1870 - (NSURL *)_draggedLinkURL
1872 return _private->draggedLinkURL.get();
1875 - (CGRect)_draggedElementBounds
1877 return _private->dragPreviewFrameInRootViewCoordinates;
1880 - (WebUITextIndicatorData *)_getDataInteractionData
1882 return _private->textIndicatorData.get();
1885 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1887 return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1890 - (WebCore::DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1892 auto dragOperationMask = static_cast<WebCore::DragOperation>(operation);
1893 auto dragDestinationMask = static_cast<WebCore::DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1894 return { session, WebCore::roundedIntPoint(clientPosition), WebCore::roundedIntPoint(globalPosition), dragOperationMask, WebCore::DragApplicationNone, dragDestinationMask };
1897 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1900 auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1901 return _private->page->dragController().dragEntered(dragData);
1904 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1907 auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1908 return _private->page->dragController().dragUpdated(dragData);
1910 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1913 auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1914 _private->page->dragController().dragExited(dragData);
1916 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1918 [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1921 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1924 auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1925 return _private->page->dragController().performDragOperation(dragData);
1928 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1931 _private->page->dragController().dragEnded();
1932 _private->dataOperationTextIndicator = nullptr;
1933 _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1934 _private->dragSourceAction = WebDragSourceActionNone;
1935 _private->draggedLinkTitle = nil;
1936 _private->draggedLinkURL = nil;
1939 - (void)_didConcludeEditDrag
1941 _private->dataOperationTextIndicator = nullptr;
1942 auto* page = _private->page;
1946 static auto defaultEditDragTextIndicatorOptions = WebCore::TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | WebCore::TextIndicatorOptionExpandClipBeyondVisibleRect | WebCore::TextIndicatorOptionPaintAllContent | WebCore::TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | WebCore::TextIndicatorOptionPaintBackgrounds | WebCore::TextIndicatorOptionUseSelectionRectForSizing | WebCore::TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | WebCore::TextIndicatorOptionRespectTextColor;
1947 auto& frame = page->focusController().focusedOrMainFrame();
1948 if (auto range = frame.selection().selection().toNormalizedRange()) {
1949 if (auto textIndicator = WebCore::TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, WebCore::TextIndicatorPresentationTransition::None, WebCore::FloatSize()))
1950 _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1954 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1956 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1961 - (WebUITextIndicatorData *)_getDataInteractionData
1966 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1971 - (NSUInteger)_dragSourceAction
1976 - (NSString *)_draggedLinkTitle
1981 - (NSURL *)_draggedLinkURL
1986 - (CGRect)_draggedElementBounds
1991 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1996 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2001 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2005 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2009 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2014 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2018 - (CGRect)_dataInteractionCaretRect
2024 #endif // PLATFORM(IOS_FAMILY)
2026 static NSMutableSet *knownPluginMIMETypes()
2028 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2033 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2035 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2036 [knownPluginMIMETypes() addObject:MIMEType];
2039 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2041 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2042 [knownPluginMIMETypes() removeObject:MIMEType];
2045 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2047 MIMEType = [MIMEType lowercaseString];
2048 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2049 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2051 #if PLATFORM(IOS_FAMILY)
2052 #define WebPDFView ([WebView _getPDFViewClass])
2054 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2055 #if PLATFORM(IOS_FAMILY)
2058 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2061 // Load the plug-in DB allowing plug-ins to install types.
2062 [WebPluginDatabase sharedDatabase];
2065 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2066 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2067 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2070 if (viewClass && repClass) {
2071 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2072 // Special-case WebHTMLView for text types that shouldn't be shown.
2073 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2076 // If the MIME type is a known plug-in we might not want to load it.
2077 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2078 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2079 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2081 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2082 if (!isSupportedByWebKit)
2087 *vClass = viewClass;
2096 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2098 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2100 #if !PLATFORM(IOS_FAMILY)
2101 if (_private->pluginDatabase) {
2102 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2103 if (pluginPackage) {
2105 *vClass = [WebHTMLView class];
2107 *rClass = [WebHTMLRepresentation class];
2115 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2117 WebCore::FontCascade::setCodePath(f ? WebCore::FontCascade::Complex : WebCore::FontCascade::Auto);
2120 + (BOOL)canCloseAllWebViews
2122 return WebCore::DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2125 + (void)closeAllWebViews
2127 WebCore::DOMWindow::dispatchAllPendingUnloadEvents();
2129 // This will close the WebViews in a random order. Change this if close order is important.
2130 for (WebView *webView in [(__bridge NSSet *)allWebViewsSet allObjects])
2134 + (BOOL)canShowFile:(NSString *)path
2136 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2139 #if !PLATFORM(IOS_FAMILY)
2140 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2142 return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2148 return !_private || _private->closed;
2151 #if PLATFORM(IOS_FAMILY)
2153 - (void)_dispatchUnloadEvent
2156 WebFrame *mainFrame = [self mainFrame];
2157 auto* coreMainFrame = core(mainFrame);
2158 if (coreMainFrame) {
2159 auto* document = coreMainFrame->document();
2161 document->dispatchWindowEvent(WebCore::Event::create(WebCore::eventNames().unloadEvent, WebCore::Event::CanBubble::No, WebCore::Event::IsCancelable::No));
2166 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2168 auto* mainFrame = [self _mainCoreFrame];
2171 RefPtr<WebCore::EditingStyle> editingStyle = WebCore::EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2174 auto* style = editingStyle->style();
2177 return kit(&style->ensureCSSStyleDeclaration());
2180 - (NSUInteger)_renderTreeSize
2182 if (!_private->page)
2184 return _private->page->renderTreeSize();
2187 - (void)_dispatchTileDidDraw:(CALayer*)tile
2189 id mailDelegate = [self _webMailDelegate];
2190 if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2191 [mailDelegate _webthread_webView:self tileDidDraw:tile];
2195 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2196 if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2198 ALLOW_DEPRECATED_DECLARATIONS_END
2202 [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2205 - (void)_willStartScrollingOrZooming
2207 // Pause timers during top level interaction
2208 if (_private->mainViewIsScrollingOrZooming)
2210 _private->mainViewIsScrollingOrZooming = YES;
2212 [self hideFormValidationMessage];
2214 // This suspends active DOM objects like timers, but not media.
2215 [[self mainFrame] setTimeoutsPaused:YES];
2217 // This defers loading callbacks only.
2218 // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2219 [self setDefersCallbacks:YES];
2222 - (void)_didFinishScrollingOrZooming
2224 if (!_private->mainViewIsScrollingOrZooming)
2226 _private->mainViewIsScrollingOrZooming = NO;
2227 [self setDefersCallbacks:NO];
2228 [[self mainFrame] setTimeoutsPaused:NO];
2229 if (auto* view = [self _mainCoreFrame]->view())
2230 view->resumeVisibleImageAnimationsIncludingSubframes();
2233 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2236 webResourceLoadScheduler().suspendPendingRequests();
2238 webResourceLoadScheduler().resumePendingRequests();
2241 + (BOOL)_isUnderMemoryPressure
2243 return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2246 #endif // PLATFORM(IOS_FAMILY)
2248 - (void)_closePluginDatabases
2250 pluginDatabaseClientCount--;
2252 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2254 #if !PLATFORM(IOS_FAMILY)
2255 // Unload the WebView local plug-in database.
2256 if (_private->pluginDatabase) {
2257 [_private->pluginDatabase destroyAllPluginInstanceViews];
2258 [_private->pluginDatabase close];
2259 [_private->pluginDatabase release];
2260 _private->pluginDatabase = nil;
2264 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2265 if (!pluginDatabaseClientCount && applicationIsTerminating)
2266 [WebPluginDatabase closeSharedDatabase];
2269 - (void)_closeWithFastTeardown
2272 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2275 #if !PLATFORM(IOS_FAMILY)
2276 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2278 [[NSNotificationCenter defaultCenter] removeObserver:self];
2280 [self _closePluginDatabases];
2283 static bool fastDocumentTeardownEnabled()
2286 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2288 static bool initialized = false;
2289 static bool enabled = false;
2291 // This allows debug builds to default to not have fast teardown, so leak checking still works.
2292 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2293 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2295 enabled = ![setting boolValue];
2302 // _close is here only for backward compatibility; clients and subclasses should use
2303 // public method -close instead.
2306 #if PLATFORM(IOS_FAMILY)
2307 // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2308 // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2310 [self _clearDelegates];
2312 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2316 if (!_private || _private->closed)
2319 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2321 _private->closed = YES;
2322 [self _removeFromAllWebViewsSet];
2325 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2328 // To quit the apps fast we skip document teardown, except plugins
2329 // need to be destroyed and unloaded.
2330 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2331 [self _closeWithFastTeardown];
2335 #if ENABLE(VIDEO) && !PLATFORM(IOS_FAMILY)
2336 [self _exitVideoFullscreen];
2339 #if PLATFORM(IOS_FAMILY)
2340 _private->closing = YES;
2343 if (auto* mainFrame = [self _mainCoreFrame])
2344 mainFrame->loader().detachFromParent();
2346 [self setHostWindow:nil];
2348 #if !PLATFORM(IOS_FAMILY)
2349 [self setDownloadDelegate:nil];
2350 [self setEditingDelegate:nil];
2351 [self setFrameLoadDelegate:nil];
2352 [self setPolicyDelegate:nil];
2353 [self setResourceLoadDelegate:nil];
2354 [self setScriptDebugDelegate:nil];
2355 [self setUIDelegate:nil];
2357 [_private->inspector inspectedWebViewClosed];
2360 [_private->immediateActionController webViewClosed];
2363 #if !PLATFORM(IOS_FAMILY)
2364 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2365 [self removeDragCaret];
2368 _private->group->removeWebView(self);
2370 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2371 // all the plug-ins in the page cache to break any retain cycles.
2372 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2373 auto* page = _private->page;
2374 _private->page = nullptr;
2375 WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<WebCore::Page>(page));
2377 #if !PLATFORM(IOS_FAMILY)
2378 if (_private->hasSpellCheckerDocumentTag) {
2379 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2380 _private->hasSpellCheckerDocumentTag = NO;
2384 if (_private->layerFlushController) {
2385 _private->layerFlushController->invalidate();
2386 _private->layerFlushController = nullptr;
2389 [[self _notificationProvider] unregisterWebView:self];
2391 #if !PLATFORM(IOS_FAMILY)
2392 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2394 [[NSNotificationCenter defaultCenter] removeObserver:self];
2396 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2398 WebPreferences *preferences = _private->preferences;
2399 _private->preferences = nil;
2400 [preferences didRemoveFromWebView];
2401 [preferences release];
2403 [self _closePluginDatabases];
2405 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
2406 if (_private->m_playbackTargetPicker) {
2407 _private->m_playbackTargetPicker->invalidate();
2408 _private->m_playbackTargetPicker = nullptr;
2413 // Need this to make leak messages accurate.
2414 if (applicationIsTerminating) {
2415 WebCore::GCController::singleton().garbageCollectNow();
2416 [WebCache setDisabled:YES];
2419 #if PLATFORM(IOS_FAMILY)
2420 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2425 // Indicates if the WebView is in the midst of a user gesture.
2426 - (BOOL)_isProcessingUserGesture
2428 return WebCore::UserGestureIndicator::processingUserGesture();
2431 + (NSString *)_MIMETypeForFile:(NSString *)path
2433 #if !PLATFORM(IOS_FAMILY)
2434 NSString *extension = [path pathExtension];
2436 NSString *MIMEType = nil;
2438 #if !PLATFORM(IOS_FAMILY)
2439 // Get the MIME type from the extension.
2440 if ([extension length] != 0) {
2441 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2445 // If we can't get a known MIME type from the extension, sniff.
2446 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2447 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2448 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2450 if ([data length] != 0) {
2451 MIMEType = [data _webkit_guessedMIMEType];
2453 if ([MIMEType length] == 0) {
2454 MIMEType = @"application/octet-stream";
2461 - (WebDownload *)_downloadURL:(NSURL *)URL
2465 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2466 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2467 WebDownload *download = [WebDownload _downloadWithRequest:request delegate:_private->downloadDelegate directory:nil];
2468 ALLOW_DEPRECATED_DECLARATIONS_END
2474 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2476 NSDictionary *features = [[NSDictionary alloc] init];
2477 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2478 createWebViewWithRequest:nil
2479 windowFeatures:features];
2481 if (!newWindowWebView)
2484 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2485 return newWindowWebView;
2488 - (BOOL)_useDarkAppearance
2490 if (!_private || !_private->page)
2492 return _private->page->useDarkAppearance();
2495 - (void)_setUseDarkAppearance:(BOOL)useDarkAppearance
2497 if (!_private || !_private->page)
2499 [self _setUseDarkAppearance:useDarkAppearance useElevatedUserInterfaceLevel:_private->page->useElevatedUserInterfaceLevel()];
2502 - (BOOL)_useElevatedUserInterfaceLevel
2504 if (!_private || !_private->page)
2506 return _private->page->useElevatedUserInterfaceLevel();
2509 - (void)_setUseElevatedUserInterfaceLevel:(BOOL)useElevatedUserInterfaceLevel
2511 if (!_private || !_private->page)
2513 [self _setUseDarkAppearance:_private->page->useDarkAppearance() useElevatedUserInterfaceLevel:useElevatedUserInterfaceLevel];
2516 - (void)_setUseDarkAppearance:(BOOL)useDarkAppearance useInactiveAppearance:(BOOL)useInactiveAppearance
2518 // FIXME: Remove once UIWebView has moved off this old method.
2519 [self _setUseDarkAppearance:useDarkAppearance useElevatedUserInterfaceLevel:!useInactiveAppearance];
2522 - (void)_setUseDarkAppearance:(BOOL)useDarkAppearance useElevatedUserInterfaceLevel:(BOOL)useElevatedUserInterfaceLevel
2524 if (!_private || !_private->page)
2526 _private->page->effectiveAppearanceDidChange(useDarkAppearance, useElevatedUserInterfaceLevel);
2529 + (void)_setIconLoadingEnabled:(BOOL)enabled
2531 iconLoadingEnabled = enabled;
2534 + (BOOL)_isIconLoadingEnabled
2536 return iconLoadingEnabled;
2539 - (WebInspector *)inspector
2541 if (!_private->inspector)
2542 _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2543 return _private->inspector;
2546 #if ENABLE(REMOTE_INSPECTOR)
2547 + (void)_enableRemoteInspector
2549 Inspector::RemoteInspector::singleton().start();
2552 + (void)_disableRemoteInspector
2554 Inspector::RemoteInspector::singleton().stop();
2557 + (void)_disableAutoStartRemoteInspector
2559 Inspector::RemoteInspector::startDisabled();
2562 + (BOOL)_isRemoteInspectorEnabled
2564 return Inspector::RemoteInspector::singleton().enabled();
2567 + (BOOL)_hasRemoteInspectorSession
2569 return Inspector::RemoteInspector::singleton().hasActiveDebugSession();
2572 - (BOOL)allowsRemoteInspection
2574 return _private->page->remoteInspectionAllowed();
2577 - (void)setAllowsRemoteInspection:(BOOL)allow
2579 _private->page->setRemoteInspectionAllowed(allow);
2582 - (void)setShowingInspectorIndication:(BOOL)showing
2584 #if PLATFORM(IOS_FAMILY)
2585 ASSERT(WebThreadIsLocked());
2588 if (!_private->indicateLayer) {
2589 _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2590 [_private->indicateLayer setNeedsLayout];
2591 [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2594 [_private->indicateLayer removeFromSuperlayer];
2595 [_private->indicateLayer release];
2596 _private->indicateLayer = nil;
2599 // Implemented in WebCore::InspectorOverlay.
2603 #if PLATFORM(IOS_FAMILY)
2604 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2606 RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2607 Inspector::RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2609 #endif // PLATFORM(IOS_FAMILY)
2610 #endif // ENABLE(REMOTE_INSPECTOR)
2612 - (WebCore::Page*)page
2614 return _private->page;
2617 #if !PLATFORM(IOS_FAMILY)
2618 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2620 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2621 NSArray *menuItems = defaultMenuItems;
2623 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2624 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2625 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2626 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2627 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2632 unsigned count = [menuItems count];
2636 NSMenu *menu = [[NSMenu alloc] init];
2637 for (unsigned i = 0; i < count; i++)
2638 [menu addItem:[menuItems objectAtIndex:i]];
2640 return [menu autorelease];
2644 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2646 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2647 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2648 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2651 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2654 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2656 if (!_private->page)
2659 if (!otherView->_private->page)
2662 // It turns out the right combination of behavior is done with the back/forward load
2663 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
2664 // in the back forward list, and go to the current one.
2666 auto& backForward = _private->page->backForward();
2667 ASSERT(!backForward.currentItem()); // destination list should be empty
2669 auto& otherBackForward = otherView->_private->page->backForward();
2670 if (!otherBackForward.currentItem())
2671 return; // empty back forward list, bail
2673 WebCore::HistoryItem* newItemToGoTo = nullptr;
2675 int lastItemIndex = otherBackForward.forwardCount();
2676 for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2678 // If this item is showing , save away its current scroll and form state,
2679 // since that might have changed since loading and it is normally not saved
2680 // until we leave that page.
2681 otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2683 Ref<WebCore::HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2685 newItemToGoTo = newItem.ptr();
2686 backForward.client().addItem(WTFMove(newItem));
2689 ASSERT(newItemToGoTo);
2690 _private->page->goToItem(*newItemToGoTo, WebCore::FrameLoadType::IndexedBackForward, WebCore::ShouldTreatAsContinuingLoad::No);
2693 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2695 _private->formDelegate = delegate;
2696 #if PLATFORM(IOS_FAMILY)
2697 [_private->formDelegateForwarder clearTarget];
2698 [_private->formDelegateForwarder release];
2699 _private->formDelegateForwarder = nil;
2703 - (id<WebFormDelegate>)_formDelegate
2705 return _private->formDelegate;
2708 #if PLATFORM(IOS_FAMILY)
2709 - (id)_formDelegateForwarder
2711 if (_private->closing)
2714 if (!_private->formDelegateForwarder)
2715 _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2716 return _private->formDelegateForwarder;
2719 - (id)_formDelegateForSelector:(SEL)selector
2721 id delegate = self->_private->formDelegate;
2722 if ([delegate respondsToSelector:selector])
2725 delegate = [WebDefaultFormDelegate sharedFormDelegate];
2726 if ([delegate respondsToSelector:selector])
2733 #if !PLATFORM(IOS_FAMILY)
2734 - (BOOL)_needsAdobeFrameReloadingQuirk
2736 static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2737 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2738 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2739 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2740 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2741 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2742 || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2743 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2744 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2745 || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2750 - (BOOL)_needsLinkElementTextCSSQuirk
2752 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2753 && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2757 - (BOOL)_needsFrameNameFallbackToIdQuirk
2759 static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2763 - (BOOL)_needsIsLoadingInAPISenseQuirk
2765 static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2770 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2772 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !WebCore::MacApplication::isSafari();
2776 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2778 static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2782 static bool needsSelfRetainWhileLoadingQuirk()
2784 static bool needsQuirk = WebCore::MacApplication::isAperture();
2787 #endif // !PLATFORM(IOS_FAMILY)
2789 - (BOOL)_needsPreHTML5ParserQuirks
2791 #if !PLATFORM(IOS_FAMILY)
2792 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2793 // with the new HTML5 parser. If these applications were linked against a
2794 // version of WebKit prior to the introduction of the HTML5 parser, enable
2795 // parser quirks to maintain compatibility. For details, see
2796 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2797 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2798 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2799 && (WebCore::MacApplication::isAOLInstantMessenger() || WebCore::MacApplication::isMicrosoftMyDay());
2801 // Mail.app must continue to display HTML email that contains quirky markup.
2802 static bool isAppleMail = WebCore::MacApplication::isAppleMail();
2804 return isApplicationNeedingParserQuirks || isAppleMail || [[self preferences] usePreHTML5ParserQuirks];
2806 return [[self preferences] usePreHTML5ParserQuirks];
2810 - (void)_preferencesChangedNotification:(NSNotification *)notification
2812 #if PLATFORM(IOS_FAMILY)
2813 // For WebViews that load synchronously, preference changes need to be propagated
2814 // down to WebCore synchronously so that loads in that WebView have the correct
2815 // up-to-date settings.
2816 if (!WebThreadIsLocked())
2818 if ([[self mainFrame] _loadsSynchronously]) {
2821 WebPreferences *preferences = (WebPreferences *)[notification object];
2822 [self _preferencesChanged:preferences];
2824 #if PLATFORM(IOS_FAMILY)
2827 // It is possible that the prefs object has already changed before the invocation could be called
2828 // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2829 WebPreferences *preferences = (WebPreferences *)[notification object];
2830 if (preferences != [self preferences])
2832 [self _preferencesChanged:preferences];
2838 - (void)_preferencesChanged:(WebPreferences *)preferences
2840 using namespace WebCore;
2841 ASSERT(preferences == [self preferences]);
2842 if (!_private->userAgentOverridden)
2843 [self _invalidateUserAgentCache];
2845 // Cache this value so we don't have to read NSUserDefaults on each page load
2846 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2848 // Update corresponding WebCore Settings object.
2849 if (!_private->page)
2852 #if PLATFORM(IOS_FAMILY)
2853 // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2854 // didOneTimeInitialization is true so that we don't initialize databases
2855 // until the first WebView has been created. This is because database
2856 // initialization current requires disk access to populate the origins
2857 // quota map and we want to do this lazily by waiting until WebKit is
2858 // used to display web content in a WebView. The possible cases are:
2859 // - on one time initialize (the first WebView creation) if databases are enabled (default)
2860 // - when databases are dynamically enabled later, and they were disabled at startup (this case)
2861 if (didOneTimeInitialization) {
2862 if ([preferences databasesEnabled])
2863 [WebDatabaseManager sharedWebDatabaseManager];
2864 if ([preferences storageTrackerEnabled])
2865 WebKitInitializeStorageIfNecessary();
2869 auto& settings = _private->page->settings();
2871 settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2872 settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2873 settings.setDefaultFontSize([preferences defaultFontSize]);
2874 settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2875 settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2876 settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2877 settings.setFixedFontFamily([preferences fixedFontFamily]);
2878 settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2879 settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2880 settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2881 settings.setJavaEnabled([preferences isJavaEnabled]);
2882 settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2883 settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2884 settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2885 settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2886 settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2887 settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2888 settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2889 settings.setMinimumFontSize([preferences minimumFontSize]);
2890 settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2891 settings.setPictographFontFamily([preferences pictographFontFamily]);
2892 settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2893 settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2895 _private->page->setSessionID([preferences privateBrowsingEnabled] ? PAL::SessionID::legacyPrivateSessionID() : PAL::SessionID::defaultSessionID());
2896 _private->group->storageNamespaceProvider().setSessionIDForTesting([preferences privateBrowsingEnabled] ? PAL::SessionID::legacyPrivateSessionID() : PAL::SessionID::defaultSessionID());
2897 settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2898 settings.setSerifFontFamily([preferences serifFontFamily]);
2899 settings.setStandardFontFamily([preferences standardFontFamily]);
2900 settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2901 settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2903 WebCore::setAdditionalSupportedImageTypes(WebCore::webCoreStringVectorFromNSStringArray([preferences additionalSupportedImageTypes]));
2905 #if PLATFORM(IOS_FAMILY)
2906 settings.setShouldPrintBackgrounds(true);
2908 settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2910 settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2911 settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2912 settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2913 settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2914 settings.setUsesPageCache([self usesPageCache]);
2915 settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2916 settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2918 settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2919 settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2920 settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2922 settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2923 settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2924 settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2925 settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2926 settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2927 settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2928 settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2929 settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2931 settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2932 settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2933 settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2934 settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2935 settings.setShowDebugBorders([preferences showDebugBorders]);
2936 settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2937 settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2938 settings.setShowRepaintCounter([preferences showRepaintCounter]);
2939 settings.setWebGLEnabled([preferences webGLEnabled]);
2940 settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2941 settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2943 settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2944 settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2945 settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2946 settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2947 settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2948 settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2949 settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2950 settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2952 settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2953 settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2954 settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2955 settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2956 settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2958 BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2959 settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2960 settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2961 settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2962 settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2963 settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2964 settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2965 settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2966 settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2967 settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2968 settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2969 settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2970 settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2971 settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2972 WebCore::DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2974 settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2976 settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2977 settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2978 WebCore::DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2980 settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2982 settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2983 settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2985 settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2986 settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2988 settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2990 settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2991 settings.setSyntheticEditingCommandsEnabled([preferences syntheticEditingCommandsEnabled]);
2992 settings.setCSSOMViewScrollingAPIEnabled([preferences CSSOMViewScrollingAPIEnabled]);
2993 settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2995 switch ([preferences storageBlockingPolicy]) {
2996 case WebAllowAllStorage:
2997 settings.setStorageBlockingPolicy(WebCore::SecurityOrigin::AllowAllStorage);
2999 case WebBlockThirdPartyStorage:
3000 settings.setStorageBlockingPolicy(WebCore::SecurityOrigin::BlockThirdPartyStorage);
3002 case WebBlockAllStorage:
3003 settings.setStorageBlockingPolicy(WebCore::SecurityOrigin::BlockAllStorage);
3007 settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
3008 settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
3009 settings.setColorFilterEnabled([preferences colorFilterEnabled]);
3010 settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
3013 settings.setAcceleratedCompositingForFixedPositionEnabled(true);
3016 #if ENABLE(RUBBER_BANDING)
3017 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
3018 settings.setRubberBandingForSubScrollableRegionsEnabled(false);
3021 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3022 settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
3024 #if PLATFORM(IOS_FAMILY)
3025 settings.setVisualViewportEnabled(false);
3026 settings.setVisualViewportAPIEnabled(false);
3027 settings.setStandalone([preferences _standalone]);
3028 settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
3029 settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
3030 settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
3031 settings.setMaxParseDuration([preferences _maxParseDuration]);
3032 settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
3033 settings.setContentChangeObserverEnabled([preferences contentChangeObserverEnabled]);
3034 WebCore::DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
3035 WebCore::DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
3036 WebCore::DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
3038 WebCore::DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
3041 settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
3042 settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
3044 ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
3045 settings.setDelegatesPageScaling(true);
3047 #if ENABLE(TEXT_AUTOSIZING)
3048 settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
3049 settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
3051 #endif // PLATFORM(IOS_FAMILY)
3054 // This parses the user stylesheet synchronously so anything that may affect it should be done first.
3055 if ([preferences userStyleSheetEnabled]) {
3056 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3057 settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3059 settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3061 settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3062 settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3063 settings.setNeedsFrameNameFallbackToIdQuirk([self _needsFrameNameFallbackToIdQuirk]);
3064 settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3065 settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3066 settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3067 settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3068 settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3069 settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3070 settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3071 #endif // PLATFORM(MAC)
3073 DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3075 #if ENABLE(MEDIA_SOURCE)
3076 settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3077 settings.setSourceBufferChangeTypeEnabled([preferences sourceBufferChangeTypeEnabled]);
3080 #if ENABLE(SERVICE_CONTROLS)
3081 settings.setImageControlsEnabled([preferences imageControlsEnabled]);
3082 settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
3085 #if ENABLE(VIDEO_TRACK)
3086 settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
3087 settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
3088 settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
3091 #if USE(AVFOUNDATION)
3092 WebCore::DeprecatedGlobalSettings::setAVFoundationEnabled([preferences isAVFoundationEnabled]);
3093 WebCore::DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
3096 #if ENABLE(MEDIA_STREAM)
3097 settings.setMockCaptureDevicesEnabled(false);
3098 settings.setMediaCaptureRequiresSecureConnection(true);
3099 RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(false);
3100 RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(false);
3101 RuntimeEnabledFeatures::sharedFeatures().setMediaRecorderEnabled(preferences.mediaRecorderEnabled);
3105 RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
3108 #if ENABLE(WEB_AUDIO)
3109 settings.setWebAudioEnabled([preferences webAudioEnabled]);
3112 #if ENABLE(FULLSCREEN_API)
3113 settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3116 RuntimeEnabledFeatures::sharedFeatures().setCSSLogicalEnabled([preferences cssLogicalEnabled]);
3118 RuntimeEnabledFeatures::sharedFeatures().setAdClickAttributionEnabled([preferences adClickAttributionEnabled]);
3120 settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3122 settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3124 WebCore::DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3126 settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3127 settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3130 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3133 RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3134 RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3135 RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3136 RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3138 #if ENABLE(ATTACHMENT_ELEMENT)
3139 RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3142 RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3143 RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3144 RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsCSSIntegrationEnabled([preferences webAnimationsCSSIntegrationEnabled]);
3146 RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3147 RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3149 #if ENABLE(STREAMS_API)
3150 RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3151 RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3155 RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3159 RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3162 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3163 RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3166 RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3168 #if ENABLE(POINTER_EVENTS)
3169 RuntimeEnabledFeatures::sharedFeatures().setPointerEventsEnabled([preferences pointerEventsEnabled]);
3172 #if ENABLE(INTERSECTION_OBSERVER)
3173 RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3175 RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3177 RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3178 RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3179 RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3180 RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3181 RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3182 RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3183 RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3184 RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3185 RuntimeEnabledFeatures::sharedFeatures().setAriaReflectionEnabled([preferences ariaReflectionEnabled]);
3186 RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3187 RuntimeEnabledFeatures::sharedFeatures().setReferrerPolicyAttributeEnabled([preferences referrerPolicyAttributeEnabled]);
3188 RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadResponsiveImagesEnabled([preferences linkPreloadResponsiveImagesEnabled]);
3189 RuntimeEnabledFeatures::sharedFeatures().setDialogElementEnabled([preferences dialogElementEnabled]);
3190 RuntimeEnabledFeatures::sharedFeatures().setKeygenElementEnabled([preferences keygenElementEnabled]);
3191 RuntimeEnabledFeatures::sharedFeatures().setCSSShadowPartsEnabled([preferences cssShadowPartsEnabled]);
3193 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3194 RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3197 #if ENABLE(ENCRYPTED_MEDIA)
3198 RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3201 RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3203 settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3205 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3207 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3209 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3210 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3212 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3213 if (_private->zoomsTextOnly != zoomsTextOnly)
3214 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3216 #if PLATFORM(IOS_FAMILY)
3217 [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3218 [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3219 [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3220 [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3223 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3224 settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3227 settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3229 settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3231 settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3233 settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3234 settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3235 settings.setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3237 settings.setCoreMathMLEnabled([preferences coreMathMLEnabled]);
3238 settings.setRequestIdleCallbackEnabled([preferences requestIdleCallbackEnabled]);
3240 RuntimeEnabledFeatures::sharedFeatures().setServerTimingEnabled([preferences serverTimingEnabled]);
3242 settings.setSelectionAcrossShadowBoundariesEnabled(preferences.selectionAcrossShadowBoundariesEnabled);
3244 #if ENABLE(RESIZE_OBSERVER)
3245 settings.setResizeObserverEnabled([preferences resizeObserverEnabled]);
3249 static inline IMP getMethod(id o, SEL s)
3251 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3254 #if PLATFORM(IOS_FAMILY)
3255 - (id)_UIKitDelegateForwarder
3257 if (_private->closing)
3260 if (!_private->UIKitDelegateForwarder)
3261 _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3262 return _private->UIKitDelegateForwarder;
3266 - (void)_cacheResourceLoadDelegateImplementations
3268 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3269 id delegate = _private->resourceProgressDelegate;
3272 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3276 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3277 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3278 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3279 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3280 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3281 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3284 #if PLATFORM(IOS_FAMILY)
3285 cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3286 cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3287 cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3288 cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3289 cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3290 cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3291 cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3292 cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3293 cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3296 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3297 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3298 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3299 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3300 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3301 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3302 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3303 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3306 - (void)_cacheFrameLoadDelegateImplementations
3308 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3309 id delegate = _private->frameLoadDelegate;
3312 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3316 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3317 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3318 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3319 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3320 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3321 #if JSC_OBJC_API_ENABLED
3322 cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3324 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3325 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3326 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3327 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3328 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3329 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3330 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3331 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3332 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3333 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3334 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3335 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3337 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3339 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3340 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3341 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3342 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3343 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3344 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3345 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3346 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3347 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3348 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3349 #if PLATFORM(IOS_FAMILY)
3350 cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3353 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3354 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3355 // for backwards compatibility.
3356 auto* page = core(self);
3358 OptionSet<WebCore::LayoutMilestone> milestones { WebCore::DidFirstLayout };
3359 #if PLATFORM(IOS_FAMILY)
3360 milestones.add(WebCore::DidFirstVisuallyNonEmptyLayout);
3362 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3363 milestones.add(WebCore::DidFirstVisuallyNonEmptyLayout);
3365 page->addLayoutMilestones(milestones);
3369 - (void)_cacheScriptDebugDelegateImplementations
3371 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3372 id delegate = _private->scriptDebugDelegate;
3375 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3379 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3380 if (cache->didParseSourceFunc)
3381 cache->didParseSourceExpectsBaseLineNumber = YES;
3383 cache->didParseSourceExpectsBaseLineNumber = NO;
3384 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3387 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3389 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3390 if (cache->exceptionWasRaisedFunc)
3391 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3393 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3394 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3398 - (void)_cacheHistoryDelegateImplementations
3400 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3401 id delegate = _private->historyDelegate;
3404 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3408 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3409 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3410 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3411 IGNORE_WARNINGS_BEGIN("undeclared-selector")
3412 cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3414 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3415 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3418 - (id)_policyDelegateForwarder
3420 #if PLATFORM(IOS_FAMILY)
3421 if (_private->closing)
3424 if (!_private->policyDelegateForwarder)
3425 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3426 return _private->policyDelegateForwarder;
3429 - (id)_UIDelegateForwarder
3431 #if PLATFORM(IOS_FAMILY)
3432 if (_private->closing)
3435 if (!_private->UIDelegateForwarder)
3436 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3437 return _private->UIDelegateForwarder;
3440 #if PLATFORM(IOS_FAMILY)
3441 - (id)_UIDelegateForSelector:(SEL)selector
3443 id delegate = self->_private->UIDelegate;
3444 if ([delegate respondsToSelector:selector])
3447 delegate = [WebDefaultUIDelegate sharedUIDelegate];
3448 if ([delegate respondsToSelector:selector])
3455 - (id)_editingDelegateForwarder
3457 #if PLATFORM(IOS_FAMILY)
3458 if (_private->closing)
3461 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3462 // Not sure if that is a bug or not.
3466 if (!_private->editingDelegateForwarder)
3467 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3468 return _private->editingDelegateForwarder;
3471 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3473 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3474 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3476 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3477 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
3478 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3479 WebCore::MIMETypeRegistry::supportedNonImageMIMETypes().remove(MIMEType);
3482 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3484 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3485 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3487 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3488 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
3489 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3490 if ([viewClass class] == [WebHTMLView class])
3491 WebCore::MIMETypeRegistry::supportedNonImageMIMETypes().add(MIMEType);
3493 // This is used to make _representationExistsForURLScheme faster.
3494 // Without this set, we'd have to create the MIME type each time.
3495 if (schemesWithRepresentationsSet == nil) {
3496 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3498 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3501 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3503 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3506 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3508 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3511 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3513 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3517 if ([NSURLConnection canHandleRequest:request])
3520 NSString *scheme = [[request URL] scheme];
3522 // Representations for URL schemes work at the top level.
3523 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3526 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3529 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3535 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3537 return [self _canHandleRequest:request forMainFrame:YES];
3540 + (NSString *)_decodeData:(NSData *)data
3542 WebCore::HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet