8d35fc10aa5aba4e72542df68fef1e25143597f0
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "BackForwardList.h"
35 #import "DOMCSSStyleDeclarationInternal.h"
36 #import "DOMDocumentInternal.h"
37 #import "DOMInternal.h"
38 #import "DOMNodeInternal.h"
39 #import "DOMRangeInternal.h"
40 #import "StorageThread.h"
41 #import "WebAlternativeTextClient.h"
42 #import "WebApplicationCacheInternal.h"
43 #import "WebArchive.h"
44 #import "WebBackForwardListInternal.h"
45 #import "WebBaseNetscapePluginView.h"
46 #import "WebCache.h"
47 #import "WebChromeClient.h"
48 #import "WebDOMOperationsPrivate.h"
49 #import "WebDataSourceInternal.h"
50 #import "WebDatabaseManagerPrivate.h"
51 #import "WebDatabaseProvider.h"
52 #import "WebDefaultEditingDelegate.h"
53 #import "WebDefaultPolicyDelegate.h"
54 #import "WebDefaultUIDelegate.h"
55 #import "WebDelegateImplementationCaching.h"
56 #import "WebDeviceOrientationClient.h"
57 #import "WebDeviceOrientationProvider.h"
58 #import "WebDocument.h"
59 #import "WebDocumentInternal.h"
60 #import "WebDownload.h"
61 #import "WebDownloadInternal.h"
62 #import "WebDragClient.h"
63 #import "WebDynamicScrollBarsViewInternal.h"
64 #import "WebEditingDelegate.h"
65 #import "WebEditorClient.h"
66 #import "WebFormDelegatePrivate.h"
67 #import "WebFrameInternal.h"
68 #import "WebFrameLoaderClient.h"
69 #import "WebFrameNetworkingContext.h"
70 #import "WebFrameViewInternal.h"
71 #import "WebGeolocationClient.h"
72 #import "WebGeolocationPositionInternal.h"
73 #import "WebHTMLRepresentation.h"
74 #import "WebHTMLViewInternal.h"
75 #import "WebHistoryItemInternal.h"
76 #import "WebIconDatabaseInternal.h"
77 #import "WebInspector.h"
78 #import "WebInspectorClient.h"
79 #import "WebKitErrors.h"
80 #import "WebKitFullScreenListener.h"
81 #import "WebKitLogging.h"
82 #import "WebKitNSStringExtras.h"
83 #import "WebKitStatisticsPrivate.h"
84 #import "WebKitVersionChecks.h"
85 #import "WebLocalizableStrings.h"
86 #import "WebNSDataExtras.h"
87 #import "WebNSDataExtrasPrivate.h"
88 #import "WebNSDictionaryExtras.h"
89 #import "WebNSURLExtras.h"
90 #import "WebNSURLRequestExtras.h"
91 #import "WebNSViewExtras.h"
92 #import "WebNodeHighlight.h"
93 #import "WebNotificationClient.h"
94 #import "WebPDFView.h"
95 #import "WebPaymentCoordinatorClient.h"
96 #import "WebPlatformStrategies.h"
97 #import "WebPluginDatabase.h"
98 #import "WebPluginInfoProvider.h"
99 #import "WebPolicyDelegate.h"
100 #import "WebPreferenceKeysPrivate.h"
101 #import "WebPreferencesPrivate.h"
102 #import "WebProgressTrackerClient.h"
103 #import "WebResourceLoadScheduler.h"
104 #import "WebScriptDebugDelegate.h"
105 #import "WebScriptWorldInternal.h"
106 #import "WebSelectionServiceController.h"
107 #import "WebStorageManagerInternal.h"
108 #import "WebStorageNamespaceProvider.h"
109 #import "WebSystemInterface.h"
110 #import "WebTextCompletionController.h"
111 #import "WebTextIterator.h"
112 #import "WebUIDelegate.h"
113 #import "WebUIDelegatePrivate.h"
114 #import "WebUserMediaClient.h"
115 #import "WebValidationMessageClient.h"
116 #import "WebViewGroup.h"
117 #import "WebVisitedLinkStore.h"
118 #import <CoreFoundation/CFSet.h>
119 #import <Foundation/NSURLConnection.h>
120 #import <JavaScriptCore/APICast.h>
121 #import <JavaScriptCore/Exception.h>
122 #import <JavaScriptCore/JSValueRef.h>
123 #import <WebCore/AlternativeTextUIController.h>
124 #import <WebCore/ApplicationCacheStorage.h>
125 #import <WebCore/BackForwardController.h>
126 #import <WebCore/CFNetworkSPI.h>
127 #import <WebCore/CSSAnimationController.h>
128 #import <WebCore/Chrome.h>
129 #import <WebCore/ColorMac.h>
130 #import <WebCore/DatabaseManager.h>
131 #import <WebCore/DictionaryLookup.h>
132 #import <WebCore/Document.h>
133 #import <WebCore/DocumentLoader.h>
134 #import <WebCore/DragController.h>
135 #import <WebCore/DragData.h>
136 #import <WebCore/Editing.h>
137 #import <WebCore/Editor.h>
138 #import <WebCore/EventHandler.h>
139 #import <WebCore/FocusController.h>
140 #import <WebCore/FontCache.h>
141 #import <WebCore/FrameLoader.h>
142 #import <WebCore/FrameSelection.h>
143 #import <WebCore/FrameTree.h>
144 #import <WebCore/FrameView.h>
145 #import <WebCore/GCController.h>
146 #import <WebCore/GameControllerGamepadProvider.h>
147 #import <WebCore/GeolocationController.h>
148 #import <WebCore/GeolocationError.h>
149 #import <WebCore/HTMLNames.h>
150 #import <WebCore/HTMLOListElement.h>
151 #import <WebCore/HTMLUListElement.h>
152 #import <WebCore/HTMLVideoElement.h>
153 #import <WebCore/HistoryController.h>
154 #import <WebCore/HistoryItem.h>
155 #import <WebCore/IconDatabase.h>
156 #import <WebCore/JSCSSStyleDeclaration.h>
157 #import <WebCore/JSDocument.h>
158 #import <WebCore/JSElement.h>
159 #import <WebCore/JSNodeList.h>
160 #import <WebCore/JSNotification.h>
161 #import <WebCore/LibWebRTCProvider.h>
162 #import <WebCore/LocalizedStrings.h>
163 #import <WebCore/LogInitialization.h>
164 #import <WebCore/MIMETypeRegistry.h>
165 #import <WebCore/MainFrame.h>
166 #import <WebCore/MemoryCache.h>
167 #import <WebCore/MemoryRelease.h>
168 #import <WebCore/NSSpellCheckerSPI.h>
169 #import <WebCore/NSTouchBarSPI.h>
170 #import <WebCore/NSURLFileTypeMappingsSPI.h>
171 #import <WebCore/NetworkStorageSession.h>
172 #import <WebCore/NodeList.h>
173 #import <WebCore/Notification.h>
174 #import <WebCore/NotificationController.h>
175 #import <WebCore/Page.h>
176 #import <WebCore/PageCache.h>
177 #import <WebCore/PageConfiguration.h>
178 #import <WebCore/PageGroup.h>
179 #import <WebCore/PlatformEventFactoryMac.h>
180 #import <WebCore/ProgressTracker.h>
181 #import <WebCore/RenderView.h>
182 #import <WebCore/RenderWidget.h>
183 #import <WebCore/ResourceHandle.h>
184 #import <WebCore/ResourceLoadObserver.h>
185 #import <WebCore/ResourceRequest.h>
186 #import <WebCore/RuntimeApplicationChecks.h>
187 #import <WebCore/RuntimeEnabledFeatures.h>
188 #import <WebCore/SchemeRegistry.h>
189 #import <WebCore/ScriptController.h>
190 #import <WebCore/SecurityOrigin.h>
191 #import <WebCore/SecurityPolicy.h>
192 #import <WebCore/Settings.h>
193 #import <WebCore/SocketProvider.h>
194 #import <WebCore/SoftLinking.h>
195 #import <WebCore/StyleProperties.h>
196 #import <WebCore/TextResourceDecoder.h>
197 #import <WebCore/ThreadCheck.h>
198 #import <WebCore/UserAgent.h>
199 #import <WebCore/UserContentController.h>
200 #import <WebCore/UserScript.h>
201 #import <WebCore/UserStyleSheet.h>
202 #import <WebCore/ValidationBubble.h>
203 #import <WebCore/WebCoreObjCExtras.h>
204 #import <WebCore/WebCoreView.h>
205 #import <WebCore/Widget.h>
206 #import <WebKitLegacy/DOM.h>
207 #import <WebKitLegacy/DOMExtensions.h>
208 #import <WebKitLegacy/DOMPrivate.h>
209 #import <WebKitSystemInterface.h>
210 #import <bindings/ScriptValue.h>
211 #import <mach-o/dyld.h>
212 #import <objc/runtime.h>
213 #import <runtime/ArrayPrototype.h>
214 #import <runtime/DateInstance.h>
215 #import <runtime/InitializeThreading.h>
216 #import <runtime/JSCJSValue.h>
217 #import <runtime/JSLock.h>
218 #import <wtf/Assertions.h>
219 #import <wtf/HashTraits.h>
220 #import <wtf/MainThread.h>
221 #import <wtf/ObjcRuntimeExtras.h>
222 #import <wtf/RAMSize.h>
223 #import <wtf/RefCountedLeakCounter.h>
224 #import <wtf/RefPtr.h>
225 #import <wtf/RunLoop.h>
226 #import <wtf/SetForScope.h>
227 #import <wtf/StdLibExtras.h>
228 #import <wtf/spi/darwin/dyldSPI.h>
229
230 #if !PLATFORM(IOS)
231 #import "WebContextMenuClient.h"
232 #import "WebFullScreenController.h"
233 #import "WebImmediateActionController.h"
234 #import "WebNSEventExtras.h"
235 #import "WebNSObjectExtras.h"
236 #import "WebNSPasteboardExtras.h"
237 #import "WebNSPrintOperationExtras.h"
238 #import "WebPDFView.h"
239 #import <WebCore/AVKitSPI.h>
240 #import <WebCore/LookupSPI.h>
241 #import <WebCore/NSImmediateActionGestureRecognizerSPI.h>
242 #import <WebCore/TextIndicator.h>
243 #import <WebCore/TextIndicatorWindow.h>
244 #import <WebCore/WebVideoFullscreenController.h>
245 #else
246 #import "MemoryMeasure.h"
247 #import "WebCaretChangeListener.h"
248 #import "WebChromeClientIOS.h"
249 #import "WebDefaultFormDelegate.h"
250 #import "WebDefaultFrameLoadDelegate.h"
251 #import "WebDefaultResourceLoadDelegate.h"
252 #import "WebDefaultUIKitDelegate.h"
253 #import "WebFixedPositionContent.h"
254 #import "WebMailDelegate.h"
255 #import "WebNSUserDefaultsExtras.h"
256 #import "WebPDFViewIOS.h"
257 #import "WebPlainWhiteView.h"
258 #import "WebPluginController.h"
259 #import "WebPolicyDelegatePrivate.h"
260 #import "WebStorageManagerPrivate.h"
261 #import "WebUIKitSupport.h"
262 #import "WebVisiblePosition.h"
263 #import <WebCore/EventNames.h>
264 #import <WebCore/FontCache.h>
265 #import <WebCore/GraphicsLayer.h>
266 #import <WebCore/IconController.h>
267 #import <WebCore/LegacyTileCache.h>
268 #import <WebCore/MobileGestaltSPI.h>
269 #import <WebCore/NetworkStateNotifier.h>
270 #import <WebCore/PlatformScreen.h>
271 #import <WebCore/ResourceLoadStatistics.h>
272 #import <WebCore/ResourceLoadStatisticsStore.h>
273 #import <WebCore/SQLiteDatabaseTracker.h>
274 #import <WebCore/SmartReplace.h>
275 #import <WebCore/TileControllerMemoryHandlerIOS.h>
276 #import <WebCore/WAKWindow.h>
277 #import <WebCore/WKView.h>
278 #import <WebCore/WebCoreThread.h>
279 #import <WebCore/WebCoreThreadMessage.h>
280 #import <WebCore/WebCoreThreadRun.h>
281 #import <WebCore/WebEvent.h>
282 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
283 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
284 #import <libkern/OSAtomic.h>
285 #import <wtf/FastMalloc.h>
286 #endif
287
288 #if ENABLE(DASHBOARD_SUPPORT)
289 #import <WebKitLegacy/WebDashboardRegion.h>
290 #endif
291
292 #if ENABLE(REMOTE_INSPECTOR)
293 #import <JavaScriptCore/RemoteInspector.h>
294 #if PLATFORM(IOS)
295 #import "WebIndicateLayer.h"
296 #endif
297 #endif
298
299 #if USE(QUICK_LOOK)
300 #include <WebCore/QuickLook.h>
301 #endif
302
303 #if ENABLE(IOS_TOUCH_EVENTS)
304 #import <WebCore/WebEventRegion.h>
305 #endif
306
307 #if ENABLE(GAMEPAD)
308 #import <WebCore/HIDGamepadProvider.h>
309 #endif
310
311 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
312 #import "WebMediaPlaybackTargetPicker.h"
313 #import <WebCore/WebMediaSessionManagerMac.h>
314 #endif
315
316
317 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
318 #import <WebCore/WebPlaybackSessionInterfaceMac.h>
319 #import <WebCore/WebPlaybackSessionModelMediaElement.h>
320 #endif
321
322 #if ENABLE(DATA_INTERACTION)
323 #import <UIKit/UIImage.h>
324 SOFT_LINK_FRAMEWORK(UIKit)
325 SOFT_LINK_CLASS(UIKit, UIImage)
326 #endif
327
328 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
329 SOFT_LINK_FRAMEWORK(AVKit)
330 SOFT_LINK_CLASS(AVKit, AVFunctionBarPlaybackControlsProvider)
331 SOFT_LINK_CLASS(AVKit, AVFunctionBarScrubber)
332 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
333
334 #if PLATFORM(MAC)
335 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
336 #endif
337
338 #if !PLATFORM(IOS)
339
340 @interface NSSpellChecker (WebNSSpellCheckerDetails)
341 - (void)_preflightChosenSpellServer;
342 @end
343
344 @interface NSView (WebNSViewDetails)
345 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
346 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
347 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
348 - (void)_windowChangedKeyState;
349 @end
350
351 @interface NSWindow (WebNSWindowDetails)
352 - (id)_oldFirstResponderBeforeBecoming;
353 - (void)_enableScreenUpdatesIfNeeded;
354 - (BOOL)_wrapsCarbonWindow;
355 - (BOOL)_hasKeyAppearance;
356 @end
357
358 #endif
359
360 using namespace JSC;
361 using namespace Inspector;
362 using namespace WebCore;
363
364 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
365 macro(alignCenter) \
366 macro(alignJustified) \
367 macro(alignLeft) \
368 macro(alignRight) \
369 macro(capitalizeWord) \
370 macro(centerSelectionInVisibleArea) \
371 macro(changeAttributes) \
372 macro(changeBaseWritingDirection) \
373 macro(changeBaseWritingDirectionToLTR) \
374 macro(changeBaseWritingDirectionToRTL) \
375 macro(changeColor) \
376 macro(changeDocumentBackgroundColor) \
377 macro(changeFont) \
378 macro(changeSpelling) \
379 macro(checkSpelling) \
380 macro(complete) \
381 macro(copy) \
382 macro(copyFont) \
383 macro(cut) \
384 macro(delete) \
385 macro(deleteBackward) \
386 macro(deleteBackwardByDecomposingPreviousCharacter) \
387 macro(deleteForward) \
388 macro(deleteToBeginningOfLine) \
389 macro(deleteToBeginningOfParagraph) \
390 macro(deleteToEndOfLine) \
391 macro(deleteToEndOfParagraph) \
392 macro(deleteToMark) \
393 macro(deleteWordBackward) \
394 macro(deleteWordForward) \
395 macro(ignoreSpelling) \
396 macro(indent) \
397 macro(insertBacktab) \
398 macro(insertLineBreak) \
399 macro(insertNewline) \
400 macro(insertNewlineIgnoringFieldEditor) \
401 macro(insertParagraphSeparator) \
402 macro(insertTab) \
403 macro(insertTabIgnoringFieldEditor) \
404 macro(lowercaseWord) \
405 macro(makeBaseWritingDirectionLeftToRight) \
406 macro(makeBaseWritingDirectionRightToLeft) \
407 macro(makeTextWritingDirectionLeftToRight) \
408 macro(makeTextWritingDirectionNatural) \
409 macro(makeTextWritingDirectionRightToLeft) \
410 macro(moveBackward) \
411 macro(moveBackwardAndModifySelection) \
412 macro(moveDown) \
413 macro(moveDownAndModifySelection) \
414 macro(moveForward) \
415 macro(moveForwardAndModifySelection) \
416 macro(moveLeft) \
417 macro(moveLeftAndModifySelection) \
418 macro(moveParagraphBackwardAndModifySelection) \
419 macro(moveParagraphForwardAndModifySelection) \
420 macro(moveRight) \
421 macro(moveRightAndModifySelection) \
422 macro(moveToBeginningOfDocument) \
423 macro(moveToBeginningOfDocumentAndModifySelection) \
424 macro(moveToBeginningOfLine) \
425 macro(moveToBeginningOfLineAndModifySelection) \
426 macro(moveToBeginningOfParagraph) \
427 macro(moveToBeginningOfParagraphAndModifySelection) \
428 macro(moveToBeginningOfSentence) \
429 macro(moveToBeginningOfSentenceAndModifySelection) \
430 macro(moveToEndOfDocument) \
431 macro(moveToEndOfDocumentAndModifySelection) \
432 macro(moveToEndOfLine) \
433 macro(moveToEndOfLineAndModifySelection) \
434 macro(moveToEndOfParagraph) \
435 macro(moveToEndOfParagraphAndModifySelection) \
436 macro(moveToEndOfSentence) \
437 macro(moveToEndOfSentenceAndModifySelection) \
438 macro(moveToLeftEndOfLine) \
439 macro(moveToLeftEndOfLineAndModifySelection) \
440 macro(moveToRightEndOfLine) \
441 macro(moveToRightEndOfLineAndModifySelection) \
442 macro(moveUp) \
443 macro(moveUpAndModifySelection) \
444 macro(moveWordBackward) \
445 macro(moveWordBackwardAndModifySelection) \
446 macro(moveWordForward) \
447 macro(moveWordForwardAndModifySelection) \
448 macro(moveWordLeft) \
449 macro(moveWordLeftAndModifySelection) \
450 macro(moveWordRight) \
451 macro(moveWordRightAndModifySelection) \
452 macro(orderFrontSubstitutionsPanel) \
453 macro(outdent) \
454 macro(overWrite) \
455 macro(pageDown) \
456 macro(pageDownAndModifySelection) \
457 macro(pageUp) \
458 macro(pageUpAndModifySelection) \
459 macro(paste) \
460 macro(pasteAsPlainText) \
461 macro(pasteAsRichText) \
462 macro(pasteFont) \
463 macro(performFindPanelAction) \
464 macro(scrollLineDown) \
465 macro(scrollLineUp) \
466 macro(scrollPageDown) \
467 macro(scrollPageUp) \
468 macro(scrollToBeginningOfDocument) \
469 macro(scrollToEndOfDocument) \
470 macro(selectAll) \
471 macro(selectLine) \
472 macro(selectParagraph) \
473 macro(selectSentence) \
474 macro(selectToMark) \
475 macro(selectWord) \
476 macro(setMark) \
477 macro(showGuessPanel) \
478 macro(startSpeaking) \
479 macro(stopSpeaking) \
480 macro(subscript) \
481 macro(superscript) \
482 macro(swapWithMark) \
483 macro(takeFindStringFromSelection) \
484 macro(toggleBaseWritingDirection) \
485 macro(transpose) \
486 macro(underline) \
487 macro(unscript) \
488 macro(uppercaseWord) \
489 macro(yank) \
490 macro(yankAndSelect) \
491
492 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
493 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
494
495 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
496 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
497
498 static BOOL s_didSetCacheModel;
499 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
500
501 #if PLATFORM(IOS)
502 static Class s_pdfRepresentationClass;
503 static Class s_pdfViewClass;
504 #endif
505
506 #ifndef NDEBUG
507 static const char webViewIsOpen[] = "At least one WebView is still open.";
508 #endif
509
510 #if PLATFORM(IOS)
511 @interface WebView(WebViewPrivate)
512 - (void)_preferencesChanged:(WebPreferences *)preferences;
513 - (void)_updateScreenScaleFromWindow;
514 @end
515 #endif
516
517 #if !PLATFORM(IOS)
518 @interface NSObject (WebValidateWithoutDelegate)
519 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
520 @end
521 #endif
522
523 #if PLATFORM(IOS)
524 @class _WebSafeForwarder;
525
526 @interface _WebSafeAsyncForwarder : NSObject {
527     _WebSafeForwarder *_forwarder;
528 }
529 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
530 @end
531 #endif
532
533 @interface _WebSafeForwarder : NSObject
534 {
535     id target; // Non-retained. Don't retain delegates.
536     id defaultTarget;
537 #if PLATFORM(IOS)
538     _WebSafeAsyncForwarder *asyncForwarder;
539     dispatch_once_t asyncForwarderPred;
540 #endif
541 }
542 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
543 #if PLATFORM(IOS)
544 - (void)clearTarget;
545 - (id)asyncForwarder;
546 #endif
547 @end
548
549 FindOptions coreOptions(WebFindOptions options)
550 {
551     return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
552         | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
553         | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
554         | (options & WebFindOptionsBackwards ? Backwards : 0)
555         | (options & WebFindOptionsWrapAround ? WrapAround : 0)
556         | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
557 }
558
559 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
560 {
561     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
562         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
563         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
564 }
565
566 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
567 {
568     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
569         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
570         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
571 }
572
573 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
574 {
575     switch (visibilityState) {
576     case PageVisibilityState::Visible:
577         return WebPageVisibilityStateVisible;
578     case PageVisibilityState::Hidden:
579         return WebPageVisibilityStateHidden;
580     case PageVisibilityState::Prerender:
581         return WebPageVisibilityStatePrerender;
582     }
583
584     ASSERT_NOT_REACHED();
585     return WebPageVisibilityStateVisible;
586 }
587
588 namespace WebKit {
589
590 class DeferredPageDestructor {
591 public:
592     static void createDeferredPageDestructor(std::unique_ptr<Page> page)
593     {
594         new DeferredPageDestructor(WTFMove(page));
595     }
596
597 private:
598     DeferredPageDestructor(std::unique_ptr<Page> page)
599         : m_page(WTFMove(page))
600     {
601         tryDestruction();
602     }
603
604     void tryDestruction()
605     {
606         if (m_page->insideNestedRunLoop()) {
607             m_page->whenUnnested([this] { tryDestruction(); });
608             return;
609         }
610
611         m_page = nullptr;
612         delete this;
613     }
614
615     std::unique_ptr<Page> m_page;
616 };
617
618 } // namespace WebKit
619
620 #if ENABLE(DATA_INTERACTION)
621
622 @implementation WebUITextIndicatorData
623
624 @synthesize dataInteractionImage=_dataInteractionImage;
625 @synthesize selectionRectInRootViewCoordinates=_selectionRectInRootViewCoordinates;
626 @synthesize textBoundingRectInRootViewCoordinates=_textBoundingRectInRootViewCoordinates;
627 @synthesize textRectsInBoundingRectCoordinates=_textRectsInBoundingRectCoordinates;
628 @synthesize contentImageWithHighlight=_contentImageWithHighlight;
629 @synthesize contentImage=_contentImage;
630
631 @end
632
633 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
634
635 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(WebCore::TextIndicatorData &)indicatorData scale:(CGFloat)scale
636 {
637     if (!(self = [super init]))
638         return nil;
639     
640     _dataInteractionImage = [[[getUIImageClass() alloc] initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored] retain];
641     _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
642     _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
643     
644     NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
645     for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
646         [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
647     _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
648     _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
649     if (indicatorData.contentImageWithHighlight)
650         _contentImageWithHighlight = [[[getUIImageClass() alloc] initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored] retain];
651     if (indicatorData.contentImage)
652         _contentImage = [[[getUIImageClass() alloc] initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored] retain];
653     
654     return self;
655 }
656
657 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
658 {
659     if (!(self = [super init]))
660         return nil;
661     
662     _dataInteractionImage = [[getUIImageClass() alloc] initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
663     
664     return self;
665 }
666
667 - (void)dealloc
668 {
669     [_dataInteractionImage release];
670     [_textRectsInBoundingRectCoordinates release];
671     [_contentImageWithHighlight release];
672     [_contentImage release];
673     
674     [super dealloc];
675 }
676
677 @end
678 #elif !PLATFORM(MAC)
679 @implementation WebUITextIndicatorData
680 @end
681 #endif // ENABLE(DATA_INTERACTION)
682
683 @interface WebView (WebFileInternal)
684 #if !PLATFORM(IOS)
685 - (float)_deviceScaleFactor;
686 #endif
687 - (BOOL)_isLoading;
688 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
689 - (WebFrame *)_focusedFrame;
690 + (void)_preflightSpellChecker;
691 - (BOOL)_continuousCheckingAllowed;
692 - (NSResponder *)_responderForResponderOperations;
693 @end
694
695 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
696 NSString *WebElementFrameKey =              @"WebElementFrame";
697 NSString *WebElementImageKey =              @"WebElementImage";
698 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
699 NSString *WebElementImageRectKey =          @"WebElementImageRect";
700 NSString *WebElementImageURLKey =           @"WebElementImageURL";
701 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
702 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
703 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
704 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
705 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
706 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
707 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
708 NSString *WebElementTitleKey =              @"WebElementTitle";
709 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
710 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
711 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
712
713 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
714 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
715 #if !PLATFORM(IOS)
716 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
717 #else
718 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
719 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
720 #endif
721
722 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
723 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
724 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
725 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
726 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
727
728 enum { WebViewVersion = 4 };
729
730 #define timedLayoutSize 4096
731
732 static NSMutableSet *schemesWithRepresentationsSet;
733 static WebCore::ResourceLoadStatisticsStore* resourceLoadStatisticsStore;
734
735 #if !PLATFORM(IOS)
736 NSString *_WebCanGoBackKey =            @"canGoBack";
737 NSString *_WebCanGoForwardKey =         @"canGoForward";
738 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
739 NSString *_WebIsLoadingKey =            @"isLoading";
740 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
741 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
742 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
743 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
744 #endif
745
746 #if PLATFORM(IOS)
747 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
748 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
749 #endif
750
751 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
752 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
753
754 #if ENABLE(REMOTE_INSPECTOR)
755 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
756 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
757 #endif
758
759 @interface WebProgressItem : NSObject
760 {
761 @public
762     long long bytesReceived;
763     long long estimatedLength;
764 }
765 @end
766
767 @implementation WebProgressItem
768 @end
769
770 static BOOL continuousSpellCheckingEnabled;
771 #if !PLATFORM(IOS)
772 static BOOL grammarCheckingEnabled;
773 static BOOL automaticQuoteSubstitutionEnabled;
774 static BOOL automaticLinkDetectionEnabled;
775 static BOOL automaticDashSubstitutionEnabled;
776 static BOOL automaticTextReplacementEnabled;
777 static BOOL automaticSpellingCorrectionEnabled;
778 #endif
779
780 #if HAVE(TOUCH_BAR)
781
782 enum class WebListType {
783     None = 0,
784     Ordered,
785     Unordered
786 };
787
788 @interface WebTextListTouchBarViewController : NSViewController {
789 @private
790     WebListType _currentListType;
791     WebView *_webView;
792 }
793
794 @property (nonatomic) WebListType currentListType;
795
796 - (instancetype)initWithWebView:(WebView *)webView;
797
798 @end
799
800 @implementation WebTextListTouchBarViewController
801
802 @synthesize currentListType=_currentListType;
803
804 static const CGFloat listControlSegmentWidth = 67.0;
805
806 static const NSUInteger noListSegment = 0;
807 static const NSUInteger unorderedListSegment = 1;
808 static const NSUInteger orderedListSegment = 2;
809
810 - (instancetype)initWithWebView:(WebView *)webView
811 {
812     if (!(self = [super init]))
813         return nil;
814
815     _webView = webView;
816
817     NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
818     [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
819     [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
820     [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
821     insertListControl.font = [NSFont systemFontOfSize:15];
822
823 #pragma clang diagnostic push
824 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
825     id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
826     NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
827     ASSERT(segments.count == 3);
828     [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
829     [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
830     [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
831 #pragma clang diagnostic pop
832
833     self.view = insertListControl;
834
835     return self;
836 }
837
838 - (void)_selectList:(id)sender
839 {
840     NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
841     if (![documentView isKindOfClass:[WebHTMLView class]])
842         return;
843
844     WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
845     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
846     switch (insertListControl.selectedSegment) {
847     case noListSegment:
848         // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
849         // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
850         // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
851         if (_currentListType == WebListType::Ordered)
852             [webHTMLView _insertOrderedList];
853         else if (_currentListType == WebListType::Unordered)
854             [webHTMLView _insertUnorderedList];
855         break;
856     case unorderedListSegment:
857         [webHTMLView _insertUnorderedList];
858         break;
859     case orderedListSegment:
860         [webHTMLView _insertOrderedList];
861         break;
862     }
863
864     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
865 }
866
867 - (void)setCurrentListType:(WebListType)listType
868 {
869     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
870     switch (listType) {
871     case WebListType::None:
872         [insertListControl setSelected:YES forSegment:noListSegment];
873         break;
874     case WebListType::Ordered:
875         [insertListControl setSelected:YES forSegment:orderedListSegment];
876         break;
877     case WebListType::Unordered:
878         [insertListControl setSelected:YES forSegment:unorderedListSegment];
879         break;
880     }
881
882     _currentListType = listType;
883 }
884
885 @end
886
887 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
888 @private
889     BOOL _textIsBold;
890     BOOL _textIsItalic;
891     BOOL _textIsUnderlined;
892     NSTextAlignment _currentTextAlignment;
893     RetainPtr<NSColor> _textColor;
894     RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
895     WebView *_webView;
896 }
897
898 @property (nonatomic) BOOL textIsBold;
899 @property (nonatomic) BOOL textIsItalic;
900 @property (nonatomic) BOOL textIsUnderlined;
901 @property (nonatomic) NSTextAlignment currentTextAlignment;
902 @property (nonatomic, retain, readwrite) NSColor *textColor;
903
904 - (instancetype)initWithWebView:(WebView *)webView;
905 @end
906
907 @implementation WebTextTouchBarItemController
908
909 @synthesize textIsBold=_textIsBold;
910 @synthesize textIsItalic=_textIsItalic;
911 @synthesize textIsUnderlined=_textIsUnderlined;
912 @synthesize currentTextAlignment=_currentTextAlignment;
913
914 - (instancetype)initWithWebView:(WebView *)webView
915 {
916     if (!(self = [super init]))
917         return nil;
918
919     _webView = webView;
920
921     return self;
922 }
923
924 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
925 {
926     NSTouchBarItem *item = [super itemForIdentifier:identifier];
927     BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
928
929     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
930         self.textStyle.action = @selector(_webChangeTextStyle:);
931
932     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
933         self.textAlignments.action = @selector(_webChangeTextAlignment:);
934
935     NSColorPickerTouchBarItem *colorPickerItem = nil;
936     if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
937         colorPickerItem = (NSColorPickerTouchBarItem *)item;
938     if (isTextFormatItem)
939         colorPickerItem = self.colorPickerItem;
940     if (colorPickerItem) {
941         colorPickerItem.target = self;
942         colorPickerItem.action = @selector(_webChangeColor:);
943         colorPickerItem.showsAlpha = NO;
944     }
945
946     return item;
947 }
948
949 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
950 {
951     return (WebTextListTouchBarViewController *)self.textListViewController;
952 }
953
954 - (void)setTextIsBold:(BOOL)bold
955 {
956     _textIsBold = bold;
957     if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
958         [self.textStyle setSelected:_textIsBold forSegment:0];
959 }
960
961 - (void)setTextIsItalic:(BOOL)italic
962 {
963     _textIsItalic = italic;
964     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
965         [self.textStyle setSelected:_textIsItalic forSegment:1];
966 }
967
968 - (void)setTextIsUnderlined:(BOOL)underlined
969 {
970     _textIsUnderlined = underlined;
971     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
972         [self.textStyle setSelected:_textIsUnderlined forSegment:2];
973 }
974
975 - (void)_webChangeTextStyle:(id)sender
976 {
977     if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
978         _textIsBold = !_textIsBold;
979         [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
980     }
981
982     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
983         _textIsItalic = !_textIsItalic;
984         [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
985     }
986
987     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
988         _textIsUnderlined = !_textIsUnderlined;
989         [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
990     }
991 }
992
993 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
994 {
995     _currentTextAlignment = alignment;
996     [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
997 }
998
999 - (void)_webChangeTextAlignment:(id)sender
1000 {
1001     NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
1002     switch (alignment) {
1003     case NSTextAlignmentLeft:
1004         _currentTextAlignment = NSTextAlignmentLeft;
1005         [_webView alignLeft:sender];
1006         break;
1007     case NSTextAlignmentRight:
1008         _currentTextAlignment = NSTextAlignmentRight;
1009         [_webView alignRight:sender];
1010         break;
1011     case NSTextAlignmentCenter:
1012         _currentTextAlignment = NSTextAlignmentCenter;
1013         [_webView alignCenter:sender];
1014         break;
1015     case NSTextAlignmentJustified:
1016         _currentTextAlignment = NSTextAlignmentJustified;
1017         [_webView alignJustified:sender];
1018         break;
1019     default:
1020         break;
1021     }
1022
1023     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
1024 }
1025
1026 - (NSColor *)textColor
1027 {
1028     return _textColor.get();
1029 }
1030
1031 - (void)setTextColor:(NSColor *)color
1032 {
1033     _textColor = color;
1034     self.colorPickerItem.color = _textColor.get();
1035 }
1036
1037 - (void)_webChangeColor:(id)sender
1038 {
1039     _textColor = self.colorPickerItem.color;
1040     [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
1041 }
1042
1043 - (NSViewController *)textListViewController
1044 {
1045     if (!_textListTouchBarViewController)
1046         _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
1047     return _textListTouchBarViewController.get();
1048 }
1049
1050 @end
1051
1052 #endif // HAVE(TOUCH_BAR)
1053
1054 @implementation WebView (AllWebViews)
1055
1056 static CFSetCallBacks NonRetainingSetCallbacks = {
1057     0,
1058     NULL,
1059     NULL,
1060     CFCopyDescription,
1061     CFEqual,
1062     CFHash
1063 };
1064
1065 static CFMutableSetRef allWebViewsSet;
1066
1067 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1068 {
1069     if (!allWebViewsSet)
1070         return;
1071
1072     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1073 }
1074
1075 - (void)_removeFromAllWebViewsSet
1076 {
1077     if (allWebViewsSet)
1078         CFSetRemoveValue(allWebViewsSet, self);
1079 }
1080
1081 - (void)_addToAllWebViewsSet
1082 {
1083     if (!allWebViewsSet)
1084         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1085
1086     CFSetSetValue(allWebViewsSet, self);
1087 }
1088
1089 @end
1090
1091 @implementation WebView (WebPrivate)
1092
1093 static String webKitBundleVersionString()
1094 {
1095     return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
1096 }
1097
1098 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1099 {
1100     return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
1101 }
1102
1103 #if PLATFORM(IOS)
1104 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1105 {
1106     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
1107 }
1108
1109 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1110 {
1111     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
1112 }
1113 #endif // PLATFORM(IOS)
1114
1115 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1116 {
1117     if (!exception || !context)
1118         return;
1119
1120     JSC::ExecState* execState = toJS(context);
1121     JSLockHolder lock(execState);
1122
1123     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1124     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1125     if (!toJSDOMWindow(globalObject->vm(), globalObject))
1126         return;
1127
1128     reportException(execState, toJS(execState, exception));
1129 }
1130
1131 static void WebKitInitializeApplicationStatisticsStoragePathIfNecessary()
1132 {
1133     static BOOL initialized = NO;
1134     if (initialized)
1135         return;
1136     
1137     resourceLoadStatisticsStore = &WebCore::ResourceLoadStatisticsStore::create().leakRef();
1138     ResourceLoadObserver::sharedObserver().setStatisticsStore(*resourceLoadStatisticsStore);
1139     
1140     initialized = YES;
1141 }
1142
1143 static bool shouldEnableLoadDeferring()
1144 {
1145 #if PLATFORM(IOS)
1146     return true;
1147 #else
1148     return !MacApplication::isAdobeInstaller();
1149 #endif
1150 }
1151
1152 static bool shouldRestrictWindowFocus()
1153 {
1154 #if PLATFORM(IOS)
1155     return true;
1156 #else
1157     return !MacApplication::isHRBlock();
1158 #endif
1159 }
1160
1161 - (void)_dispatchPendingLoadRequests
1162 {
1163     webResourceLoadScheduler().servePendingRequests();
1164 }
1165
1166 #if !PLATFORM(IOS)
1167
1168 - (void)_registerDraggedTypes
1169 {
1170     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1171     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1172     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1173     [types addObjectsFromArray:URLTypes];
1174     [types addObject:[WebHTMLView _dummyPasteboardType]];
1175     [self registerForDraggedTypes:[types allObjects]];
1176     [types release];
1177 }
1178
1179 static bool needsOutlookQuirksScript()
1180 {
1181     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1182         && MacApplication::isMicrosoftOutlook();
1183     return isOutlookNeedingQuirksScript;
1184 }
1185
1186 static NSString *leakOutlookQuirksUserScriptContents()
1187 {
1188     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1189     NSStringEncoding encoding;
1190     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1191 }
1192
1193 -(void)_injectOutlookQuirksScript
1194 {
1195     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1196     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1197
1198 }
1199 #endif
1200
1201 static bool shouldRespectPriorityInCSSAttributeSetters()
1202 {
1203 #if PLATFORM(IOS)
1204     static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1205         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
1206     return isStanzaNeedingAttributeSetterQuirk;
1207 #else
1208     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1209         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1210     return isIAdProducerNeedingAttributeSetterQuirk;
1211 #endif
1212 }
1213
1214 #if PLATFORM(IOS)
1215 static bool shouldTransformsAffectOverflow()
1216 {
1217     static bool shouldTransformsAffectOverflow = !IOSApplication::isOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
1218     return shouldTransformsAffectOverflow;
1219 }
1220
1221 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
1222 {
1223     static bool shouldDispatchJavaScriptWindowOnErrorEvents = !IOSApplication::isFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
1224     return shouldDispatchJavaScriptWindowOnErrorEvents;
1225 }
1226
1227 static bool isInternalInstall()
1228 {
1229     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1230     return isInternal;
1231 }
1232
1233 static bool didOneTimeInitialization = false;
1234 #endif
1235
1236 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1237 {
1238 #if PLATFORM(IOS)
1239     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1240 #else
1241     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1242         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1243 #endif
1244     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1245 }
1246
1247 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1248 {
1249     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1250     return shouldAllowDisplayAndRunningOfInsecureContent;
1251 }
1252
1253 static bool shouldAllowPictureInPictureMediaPlayback()
1254 {
1255 #if PLATFORM(IOS)
1256     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1257     return shouldAllowPictureInPictureMediaPlayback;
1258 #else
1259     return false;
1260 #endif
1261 }
1262
1263 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1264 {
1265 #if PLATFORM(IOS)
1266     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1267     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1268 #else
1269     return false;
1270 #endif
1271 }
1272
1273 static bool shouldAllowWindowOpenWithoutUserGesture()
1274 {
1275 #if PLATFORM(IOS)
1276     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1277     return shouldAllowWindowOpenWithoutUserGesture;
1278 #else
1279     return false;
1280 #endif
1281 }
1282
1283 static bool shouldConvertInvalidURLsToBlank()
1284 {
1285 #if PLATFORM(IOS)
1286     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1287 #elif PLATFORM(MAC)
1288     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1289 #else
1290     static bool shouldConvertInvalidURLsToBlank = true;
1291 #endif
1292
1293     return shouldConvertInvalidURLsToBlank;
1294 }
1295
1296 static bool shouldRequireUserGestureToLoadVideo()
1297 {
1298 #if PLATFORM(IOS)
1299     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1300     return shouldRequireUserGestureToLoadVideo;
1301 #else
1302     return true;
1303 #endif
1304 }
1305
1306 #if ENABLE(GAMEPAD)
1307 static void WebKitInitializeGamepadProviderIfNecessary()
1308 {
1309     static bool initialized = false;
1310     if (initialized)
1311         return;
1312
1313 #if PLATFORM(MAC)
1314     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1315 #else
1316     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1317 #endif
1318
1319     initialized = true;
1320 }
1321 #endif
1322
1323 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1324 {
1325     WebCoreThreadViolationCheckRoundTwo();
1326
1327 #ifndef NDEBUG
1328     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1329 #endif
1330     
1331     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1332     [standardPreferences willAddToWebView];
1333
1334     _private->preferences = [standardPreferences retain];
1335     _private->mainFrameDocumentReady = NO;
1336     _private->drawsBackground = YES;
1337 #if !PLATFORM(IOS)
1338     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1339 #else
1340     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1341 #endif
1342     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
1343
1344 #if PLATFORM(MAC)
1345     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1346 #endif
1347
1348     NSRect f = [self frame];
1349     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1350     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1351     [self addSubview:frameView];
1352     [frameView release];
1353
1354 #if PLATFORM(MAC)
1355     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1356         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1357         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1358         [recognizer setDelegate:_private->immediateActionController];
1359         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1360     }
1361 #endif
1362
1363     [self updateTouchBar];
1364
1365 #if !PLATFORM(IOS)
1366     static bool didOneTimeInitialization = false;
1367 #endif
1368     if (!didOneTimeInitialization) {
1369 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1370         WebKitInitializeLogChannelsIfNecessary();
1371         WebCore::initializeLogChannelsIfNecessary();
1372 #endif
1373
1374         // Initialize our platform strategies first before invoking the rest
1375         // of the initialization code which may depend on the strategies.
1376         WebPlatformStrategies::initializeIfNecessary();
1377
1378         initializeDOMWrapperHooks();
1379
1380 #if PLATFORM(IOS)
1381         // Set the WebSQLiteDatabaseTrackerClient.
1382         SQLiteDatabaseTracker::setClient(&WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1383
1384         if ([standardPreferences databasesEnabled])
1385 #endif
1386         [WebDatabaseManager sharedWebDatabaseManager];
1387
1388 #if PLATFORM(IOS)        
1389         if ([standardPreferences storageTrackerEnabled])
1390 #endif
1391         WebKitInitializeStorageIfNecessary();
1392
1393         WebKitInitializeApplicationStatisticsStoragePathIfNecessary();
1394
1395 #if ENABLE(GAMEPAD)
1396         WebKitInitializeGamepadProviderIfNecessary();
1397 #endif
1398         
1399         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1400
1401 #if PLATFORM(IOS)
1402         if (IOSApplication::isMobileSafari())
1403             Settings::setShouldManageAudioSessionCategory(true);
1404 #endif
1405
1406         didOneTimeInitialization = true;
1407     }
1408
1409     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1410     _private->group->addWebView(self);
1411
1412     PageConfiguration pageConfiguration(
1413         makeUniqueRef<WebEditorClient>(self),
1414         SocketProvider::create(),
1415         makeUniqueRef<WebCore::LibWebRTCProvider>()
1416     );
1417 #if !PLATFORM(IOS)
1418     pageConfiguration.chromeClient = new WebChromeClient(self);
1419     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1420     // FIXME: We should enable this on iOS as well.
1421     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1422     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1423 #else
1424     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1425     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1426 #endif
1427
1428 #if ENABLE(DRAG_SUPPORT)
1429     pageConfiguration.dragClient = new WebDragClient(self);
1430 #endif
1431
1432     pageConfiguration.backForwardClient = BackForwardList::create(self);
1433
1434 #if ENABLE(APPLE_PAY)
1435     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1436 #endif
1437
1438     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1439     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1440     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1441     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1442     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1443     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1444     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1445     pageConfiguration.userContentProvider = &_private->group->userContentController();
1446     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1447     _private->page = new Page(WTFMove(pageConfiguration));
1448
1449     _private->page->setGroupName(groupName);
1450
1451 #if ENABLE(GEOLOCATION)
1452     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
1453 #endif
1454 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
1455     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1456 #endif
1457 #if ENABLE(DEVICE_ORIENTATION)
1458 #if !PLATFORM(IOS)
1459     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1460 #endif
1461 #endif
1462 #if ENABLE(MEDIA_STREAM)
1463     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1464 #endif
1465
1466 #if ENABLE(REMOTE_INSPECTOR)
1467     _private->page->setRemoteInspectionAllowed(true);
1468 #endif
1469
1470     _private->page->setCanStartMedia([self window]);
1471     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1472     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1473
1474 #if !PLATFORM(IOS)
1475     if (needsOutlookQuirksScript()) {
1476         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1477         [self _injectOutlookQuirksScript];
1478     }
1479 #endif
1480
1481 #if PLATFORM(IOS)
1482     // Preserve the behavior we had before <rdar://problem/7580867>
1483     // by enforcing a 5MB limit for session storage.
1484     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1485
1486     [self _updateScreenScaleFromWindow];
1487     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1488     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1489     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1490 #endif
1491
1492     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1493         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1494
1495     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1496
1497 #if PLATFORM(IOS)
1498     NSRunLoop *runLoop = WebThreadNSRunLoop();
1499 #else
1500     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1501 #endif
1502
1503     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1504         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1505     else
1506         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1507
1508     [self _addToAllWebViewsSet];
1509     
1510     // If there's already a next key view (e.g., from a nib), wire it up to our
1511     // contained frame view. In any case, wire our next key view up to the our
1512     // contained frame view. This works together with our becomeFirstResponder 
1513     // and setNextKeyView overrides.
1514     NSView *nextKeyView = [self nextKeyView];
1515     if (nextKeyView && nextKeyView != frameView)
1516         [frameView setNextKeyView:nextKeyView];
1517     [super setNextKeyView:frameView];
1518
1519     if ([[self class] shouldIncludeInWebKitStatistics])
1520         ++WebViewCount;
1521
1522 #if !PLATFORM(IOS)
1523     [self _registerDraggedTypes];
1524 #endif
1525
1526     [self _setIsVisible:[self _isViewVisible]];
1527
1528     WebPreferences *prefs = [self preferences];
1529     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1530                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1531
1532 #if !PLATFORM(IOS)
1533     [self _preferencesChanged:[self preferences]];
1534     [[self preferences] _postPreferencesChangedAPINotification];
1535 #else
1536     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1537     // and prefs need to be changed synchronously <rdar://problem/5841558>
1538     [self _preferencesChanged:prefs];
1539     _private->page->settings().setFontFallbackPrefersPictographs(true);
1540 #endif
1541
1542     WebInstallMemoryPressureHandler();
1543
1544     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1545         // Originally, we allowed all local loads.
1546         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1547     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1548         // Later, we allowed local loads for local URLs and documents loaded
1549         // with substitute data.
1550         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1551     }
1552
1553 #if PLATFORM(MAC)
1554     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1555         ResourceHandle::forceContentSniffing();
1556
1557     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1558 #endif
1559
1560     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1561 }
1562
1563 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1564 {
1565     self = [super initWithFrame:f];
1566     if (!self)
1567         return nil;
1568
1569 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1570     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1571     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1572     // need for Safari to unset it to prevent it from being passed to applications it launches.
1573     // Unsetting it when a WebView is first created is as good a place as any.
1574     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1575     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1576         unsetenv("DYLD_FRAMEWORK_PATH");
1577         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1578     }
1579 #endif
1580
1581     _private = [[WebViewPrivate alloc] init];
1582     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1583     [self setMaintainsBackForwardList: YES];
1584     return self;
1585 }
1586
1587 - (void)_viewWillDrawInternal
1588 {
1589     Frame* frame = [self _mainCoreFrame];
1590     if (frame && frame->view())
1591         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1592 }
1593
1594 + (NSArray *)_supportedMIMETypes
1595 {
1596     // Load the plug-in DB allowing plug-ins to install types.
1597     [WebPluginDatabase sharedDatabase];
1598     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1599 }
1600
1601 #if !PLATFORM(IOS)
1602 + (NSArray *)_supportedFileExtensions
1603 {
1604     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1605     NSArray *MIMETypes = [self _supportedMIMETypes];
1606     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1607     NSString *MIMEType;
1608     while ((MIMEType = [enumerator nextObject]) != nil) {
1609         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1610         if (extensionsForType) {
1611             [extensions addObjectsFromArray:extensionsForType];
1612         }
1613     }
1614     NSArray *uniqueExtensions = [extensions allObjects];
1615     [extensions release];
1616     return uniqueExtensions;
1617 }
1618 #endif
1619
1620 #if PLATFORM(IOS)
1621 + (void)enableWebThread
1622 {
1623     static BOOL isWebThreadEnabled = NO;
1624     if (!isWebThreadEnabled) {
1625         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1626         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1627         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1628         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1629         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1630         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1631         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1632         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1633         WebCoreObjCDeallocOnWebThread([WebView class]);
1634         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1635         if (IOSApplication::isTheEconomistOnIphone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1636             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1637         WebThreadEnable();
1638         isWebThreadEnabled = YES;
1639     }
1640 }
1641
1642 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1643 {
1644     self = [super initWithFrame:frame];
1645     if (!self)
1646         return nil;
1647     
1648     _private = [[WebViewPrivate alloc] init];
1649     
1650 #ifndef NDEBUG
1651     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1652 #endif
1653     
1654     if (!preferences)
1655         preferences = [WebPreferences standardPreferences];
1656     [preferences willAddToWebView];
1657     
1658     _private->preferences = [preferences retain];
1659     _private->mainFrameDocumentReady = NO;
1660     _private->drawsBackground = YES;
1661     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1662
1663     WebFrameView *frameView = nil;
1664     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1665     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1666     [self addSubview:frameView];
1667     [frameView release];
1668
1669     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1670     _private->group->addWebView(self);
1671
1672     PageConfiguration pageConfiguration(
1673         makeUniqueRef<WebEditorClient>(self),
1674         SocketProvider::create(),
1675         makeUniqueRef<WebCore::LibWebRTCProvider>()
1676     );
1677     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1678 #if ENABLE(DRAG_SUPPORT)
1679     pageConfiguration.dragClient = new WebDragClient(self);
1680 #endif
1681
1682 #if ENABLE(APPLE_PAY)
1683     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1684 #endif
1685
1686     pageConfiguration.backForwardClient = BackForwardList::create(self);
1687     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1688     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1689     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1690     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1691     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1692     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1693     pageConfiguration.userContentProvider = &_private->group->userContentController();
1694     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1695     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1696
1697     _private->page = new Page(WTFMove(pageConfiguration));
1698     
1699     [self setSmartInsertDeleteEnabled:YES];
1700     
1701     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1702     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1703     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1704     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1705     _private->page->settings().setMinimumLogicalFontSize(9);
1706     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1707     _private->page->settings().setDefaultFixedFontSize(13);
1708     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1709     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1710     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1711     
1712     _private->page->settings().setFontFallbackPrefersPictographs(true);
1713     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1714     
1715     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1716     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1717     
1718     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1719     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1720
1721     // This is a workaround for <rdar://problem/21309911>.
1722     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1723
1724     _private->page->setGroupName(groupName);
1725
1726 #if ENABLE(REMOTE_INSPECTOR)
1727     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1728 #endif
1729     
1730     [self _updateScreenScaleFromWindow];
1731     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1732     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1733
1734     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1735     
1736     [self _addToAllWebViewsSet];
1737     
1738     ++WebViewCount;
1739     
1740     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1741     
1742     return self;
1743 }
1744
1745 + (void)_releaseMemoryNow
1746 {
1747     WebThreadRun(^{
1748         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1749     });
1750 }
1751
1752 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1753 {
1754     Frame* frame = [self _mainCoreFrame];
1755     if (frame)
1756         frame->loader().history().replaceCurrentItem(core(item));
1757 }
1758
1759 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1760 {
1761     WebThreadRun(^{
1762         [WebView _releaseMemoryNow];
1763         dispatch_async(dispatch_get_main_queue(), handler);
1764     });
1765 }
1766
1767 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1768 {
1769     return WebCore::isCharacterSmartReplaceExempt(character, b);
1770 }
1771
1772 - (void)updateLayoutIgnorePendingStyleSheets
1773 {
1774     WebThreadRun(^{
1775         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1776             Document *document = frame->document();
1777             if (document)
1778                 document->updateLayoutIgnorePendingStylesheets();
1779         }
1780     });
1781 }
1782 #endif
1783
1784 #if ENABLE(DATA_INTERACTION) && defined(__cplusplus)
1785 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1786 {
1787     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1788 }
1789
1790 - (void)_setDataInteractionData:(CGImageRef)image textIndicator:(std::optional<TextIndicatorData>)indicatorData atClientPosition:(CGPoint)clientPosition anchorPoint:(CGPoint)anchorPoint action:(uint64_t)action
1791 {
1792     if (indicatorData)
1793         _private->textIndicatorData = [[[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()] retain];
1794     else
1795         _private->textIndicatorData = [[[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()] retain];
1796 }
1797
1798 - (WebUITextIndicatorData *)_getDataInteractionData
1799 {
1800     return _private->textIndicatorData;
1801 }
1802
1803 #if USE(APPLE_INTERNAL_SDK) && __has_include(<WebKitAdditions/WebViewAdditions.mm>)
1804 #include <WebKitAdditions/WebViewAdditions.mm>
1805 #endif
1806
1807 #else
1808 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1809 {
1810     return NO;
1811 }
1812 - (void)_setDataInteractionData:(CGImageRef)image textIndicator:(TextIndicatorData&)indicatorData atClientPosition:(CGPoint)clientPosition anchorPoint:(CGPoint)anchorPoint action:(uint64_t)action
1813 {
1814 }
1815 - (WebUITextIndicatorData *)_getDataInteractionData
1816 {
1817     return nil;
1818 }
1819 - (uint64_t)_enteredDataInteraction:(id)dataInteraction client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1820 {
1821     return 0;
1822 }
1823
1824 - (uint64_t)_updatedDataInteraction:(id)dataInteraction client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1825 {
1826     return 0;
1827 }
1828 - (void)_exitedDataInteraction:(id)dataInteraction client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1829 {
1830 }
1831 - (void)_performDataInteraction:(id)dataInteraction client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1832 {
1833 }
1834 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1835 {
1836 }
1837 #endif // ENABLE(DATA_INTERACTION) && defined(__cplusplus)
1838
1839 static NSMutableSet *knownPluginMIMETypes()
1840 {
1841     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1842     
1843     return mimeTypes;
1844 }
1845
1846 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1847 {
1848     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1849     [knownPluginMIMETypes() addObject:MIMEType];
1850 }
1851
1852 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1853 {
1854     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1855     [knownPluginMIMETypes() removeObject:MIMEType];
1856 }
1857
1858 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1859 {
1860     MIMEType = [MIMEType lowercaseString];
1861     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1862     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1863
1864 #if PLATFORM(IOS)
1865 #define WebPDFView ([WebView _getPDFViewClass])
1866 #endif
1867     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1868 #if PLATFORM(IOS)
1869 #undef WebPDFView
1870 #endif
1871         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1872
1873         if (allowPlugins) {
1874             // Load the plug-in DB allowing plug-ins to install types.
1875             [WebPluginDatabase sharedDatabase];
1876         }
1877
1878         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1879         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1880         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1881     }
1882     
1883     if (viewClass && repClass) {
1884         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1885             // Special-case WebHTMLView for text types that shouldn't be shown.
1886             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1887                 return NO;
1888
1889             // If the MIME type is a known plug-in we might not want to load it.
1890             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1891                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1892                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1893                 
1894                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1895                 if (!isSupportedByWebKit)
1896                     return NO;
1897             }
1898         }
1899         if (vClass)
1900             *vClass = viewClass;
1901         if (rClass)
1902             *rClass = repClass;
1903         return YES;
1904     }
1905     
1906     return NO;
1907 }
1908
1909 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1910 {
1911     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1912         return YES;
1913 #if !PLATFORM(IOS)
1914     if (_private->pluginDatabase) {
1915         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1916         if (pluginPackage) {
1917             if (vClass)
1918                 *vClass = [WebHTMLView class];
1919             if (rClass)
1920                 *rClass = [WebHTMLRepresentation class];
1921             return YES;
1922         }
1923     }
1924 #endif
1925     return NO;
1926 }
1927
1928 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1929 {
1930     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
1931 }
1932
1933 + (BOOL)canCloseAllWebViews
1934 {
1935     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1936 }
1937
1938 + (void)closeAllWebViews
1939 {
1940     DOMWindow::dispatchAllPendingUnloadEvents();
1941
1942     // This will close the WebViews in a random order. Change this if close order is important.
1943     // Make a new set to avoid mutating the set we are enumerating.
1944     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1945     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1946     while (WebView *webView = [enumerator nextObject])
1947         [webView close];
1948 }
1949
1950 + (BOOL)canShowFile:(NSString *)path
1951 {
1952     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1953 }
1954
1955 #if !PLATFORM(IOS)
1956 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1957 {
1958     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1959 }
1960 #endif
1961
1962 - (BOOL)_isClosed
1963 {
1964     return !_private || _private->closed;
1965 }
1966
1967 #if PLATFORM(IOS)
1968
1969 - (void)_dispatchUnloadEvent
1970 {
1971     WebThreadRun(^{
1972         WebFrame *mainFrame = [self mainFrame];
1973         Frame *coreMainFrame = core(mainFrame);
1974         if (coreMainFrame) {
1975             Document *document = coreMainFrame->document();
1976             if (document)
1977                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1978         }
1979     });
1980 }
1981
1982 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1983 {
1984     auto* mainFrame = [self _mainCoreFrame];
1985     if (!mainFrame)
1986         return nil;
1987     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
1988     if (!editingStyle)
1989         return nil;
1990     auto* style = editingStyle->style();
1991     if (!style)
1992         return nil;
1993     return kit(style->ensureCSSStyleDeclaration());
1994 }
1995
1996 - (NSUInteger)_renderTreeSize
1997 {
1998     if (!_private->page)
1999         return 0;
2000     return _private->page->renderTreeSize();
2001 }
2002
2003 - (void)_dispatchTileDidDraw:(CALayer*)tile
2004 {
2005     id mailDelegate = [self _webMailDelegate];
2006     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2007         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2008         return;
2009     }
2010
2011 #pragma clang diagnostic push
2012 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2013     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2014         return;
2015 #pragma clang diagnostic pop
2016
2017     WebThreadLock();
2018
2019     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2020 }
2021
2022 - (void)_willStartScrollingOrZooming
2023 {
2024     // Pause timers during top level interaction
2025     if (_private->mainViewIsScrollingOrZooming)
2026         return;
2027     _private->mainViewIsScrollingOrZooming = YES;
2028
2029     [self hideFormValidationMessage];
2030
2031     // This suspends active DOM objects like timers, but not media.
2032     [[self mainFrame] setTimeoutsPaused:YES];
2033
2034     // This defers loading callbacks only.
2035     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2036     [self setDefersCallbacks:YES];
2037 }
2038
2039 - (void)_didFinishScrollingOrZooming
2040 {
2041     if (!_private->mainViewIsScrollingOrZooming)
2042         return;
2043     _private->mainViewIsScrollingOrZooming = NO;
2044     [self setDefersCallbacks:NO];
2045     [[self mainFrame] setTimeoutsPaused:NO];
2046     if (FrameView* view = [self _mainCoreFrame]->view())
2047         view->resumeVisibleImageAnimationsIncludingSubframes();
2048 }
2049
2050 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2051 {
2052     if (suspend)
2053         webResourceLoadScheduler().suspendPendingRequests();
2054     else
2055         webResourceLoadScheduler().resumePendingRequests();
2056 }
2057
2058 + (void)_setAllowCookies:(BOOL)allow
2059 {
2060     ResourceRequestBase::setDefaultAllowCookies(allow);
2061 }
2062
2063 + (BOOL)_allowCookies
2064 {
2065     return ResourceRequestBase::defaultAllowCookies();
2066 }
2067
2068 + (BOOL)_isUnderMemoryPressure
2069 {
2070     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2071 }
2072
2073 #endif // PLATFORM(IOS)
2074
2075 - (void)_closePluginDatabases
2076 {
2077     pluginDatabaseClientCount--;
2078
2079     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2080
2081 #if !PLATFORM(IOS)
2082     // Unload the WebView local plug-in database. 
2083     if (_private->pluginDatabase) {
2084         [_private->pluginDatabase destroyAllPluginInstanceViews];
2085         [_private->pluginDatabase close];
2086         [_private->pluginDatabase release];
2087         _private->pluginDatabase = nil;
2088     }
2089 #endif
2090     
2091     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2092     if (!pluginDatabaseClientCount && applicationIsTerminating)
2093         [WebPluginDatabase closeSharedDatabase];
2094 }
2095
2096 - (void)_closeWithFastTeardown 
2097 {
2098 #ifndef NDEBUG
2099     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2100 #endif
2101
2102 #if !PLATFORM(IOS)
2103     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2104 #endif
2105     [[NSNotificationCenter defaultCenter] removeObserver:self];
2106
2107     [self _closePluginDatabases];
2108 }
2109
2110 static bool fastDocumentTeardownEnabled()
2111 {
2112 #ifdef NDEBUG
2113     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2114 #else
2115     static bool initialized = false;
2116     static bool enabled = false;
2117     if (!initialized) {
2118         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2119         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2120         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2121         if (setting)
2122             enabled = ![setting boolValue];
2123         initialized = true;
2124     }
2125 #endif
2126     return enabled;
2127 }
2128
2129 // _close is here only for backward compatibility; clients and subclasses should use
2130 // public method -close instead.
2131 - (void)_close
2132 {
2133 #if PLATFORM(IOS)
2134     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2135     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2136
2137     [self _clearDelegates];
2138
2139     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2140     WebThreadRun(^{
2141 #endif            
2142
2143     if (!_private || _private->closed)
2144         return;
2145
2146     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2147
2148     _private->closed = YES;
2149     [self _removeFromAllWebViewsSet];
2150
2151 #ifndef NDEBUG
2152     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2153 #endif
2154
2155     // To quit the apps fast we skip document teardown, except plugins
2156     // need to be destroyed and unloaded.
2157     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2158         [self _closeWithFastTeardown];
2159         return;
2160     }
2161
2162 #if ENABLE(VIDEO) && !PLATFORM(IOS)
2163     [self _exitVideoFullscreen];
2164 #endif
2165
2166 #if PLATFORM(IOS)
2167     _private->closing = YES;
2168 #endif
2169
2170     if (Frame* mainFrame = [self _mainCoreFrame])
2171         mainFrame->loader().detachFromParent();
2172
2173     [self setHostWindow:nil];
2174
2175 #if !PLATFORM(IOS)
2176     [self setDownloadDelegate:nil];
2177     [self setEditingDelegate:nil];
2178     [self setFrameLoadDelegate:nil];
2179     [self setPolicyDelegate:nil];
2180     [self setResourceLoadDelegate:nil];
2181     [self setScriptDebugDelegate:nil];
2182     [self setUIDelegate:nil];
2183
2184     [_private->inspector inspectedWebViewClosed];
2185 #endif
2186 #if PLATFORM(MAC)
2187     [_private->immediateActionController webViewClosed];
2188 #endif
2189
2190 #if !PLATFORM(IOS)
2191     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2192     [self removeDragCaret];
2193 #endif
2194
2195     _private->group->removeWebView(self);
2196
2197     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2198     // all the plug-ins in the page cache to break any retain cycles.
2199     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2200     Page* page = _private->page;
2201     _private->page = nullptr;
2202     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2203
2204 #if !PLATFORM(IOS)
2205     if (_private->hasSpellCheckerDocumentTag) {
2206         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2207         _private->hasSpellCheckerDocumentTag = NO;
2208     }
2209 #endif
2210
2211     if (_private->layerFlushController) {
2212         _private->layerFlushController->invalidate();
2213         _private->layerFlushController = nullptr;
2214     }
2215
2216     [[self _notificationProvider] unregisterWebView:self];
2217
2218 #if !PLATFORM(IOS)
2219     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2220 #endif
2221     [[NSNotificationCenter defaultCenter] removeObserver:self];
2222
2223     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2224
2225     WebPreferences *preferences = _private->preferences;
2226     _private->preferences = nil;
2227     [preferences didRemoveFromWebView];
2228     [preferences release];
2229
2230     [self _closePluginDatabases];
2231
2232 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
2233     if (_private->m_playbackTargetPicker) {
2234         _private->m_playbackTargetPicker->invalidate();
2235         _private->m_playbackTargetPicker = nullptr;
2236     }
2237 #endif
2238
2239 #ifndef NDEBUG
2240     // Need this to make leak messages accurate.
2241     if (applicationIsTerminating) {
2242         WebCore::GCController::singleton().garbageCollectNow();
2243         [WebCache setDisabled:YES];
2244     }
2245 #endif
2246 #if PLATFORM(IOS)
2247     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2248     });
2249 #endif            
2250 }
2251
2252 // Indicates if the WebView is in the midst of a user gesture.
2253 - (BOOL)_isProcessingUserGesture
2254 {
2255     return ScriptController::processingUserGesture();
2256 }
2257
2258 + (NSString *)_MIMETypeForFile:(NSString *)path
2259 {
2260 #if !PLATFORM(IOS)
2261     NSString *extension = [path pathExtension];
2262 #endif
2263     NSString *MIMEType = nil;
2264
2265 #if !PLATFORM(IOS)
2266     // Get the MIME type from the extension.
2267     if ([extension length] != 0) {
2268         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2269     }
2270 #endif
2271
2272     // If we can't get a known MIME type from the extension, sniff.
2273     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2274         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2275         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2276         [handle closeFile];
2277         if ([data length] != 0) {
2278             MIMEType = [data _webkit_guessedMIMEType];
2279         }
2280         if ([MIMEType length] == 0) {
2281             MIMEType = @"application/octet-stream";
2282         }
2283     }
2284
2285     return MIMEType;
2286 }
2287
2288 - (WebDownload *)_downloadURL:(NSURL *)URL
2289 {
2290     ASSERT(URL);
2291     
2292     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2293     WebDownload *download = [WebDownload _downloadWithRequest:request
2294                                                      delegate:_private->downloadDelegate
2295                                                     directory:nil];
2296     [request release];
2297     
2298     return download;
2299 }
2300
2301 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2302 {
2303     NSDictionary *features = [[NSDictionary alloc] init];
2304     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2305                                             createWebViewWithRequest:nil
2306                                                       windowFeatures:features];
2307     [features release];
2308     if (!newWindowWebView)
2309         return nil;
2310
2311     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2312     return newWindowWebView;
2313 }
2314
2315 - (WebInspector *)inspector
2316 {
2317     if (!_private->inspector)
2318         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2319     return _private->inspector;
2320 }
2321
2322 #if ENABLE(REMOTE_INSPECTOR)
2323 + (void)_enableRemoteInspector
2324 {
2325     RemoteInspector::singleton().start();
2326 }
2327
2328 + (void)_disableRemoteInspector
2329 {
2330     RemoteInspector::singleton().stop();
2331 }
2332
2333 + (void)_disableAutoStartRemoteInspector
2334 {
2335     RemoteInspector::startDisabled();
2336 }
2337
2338 + (BOOL)_isRemoteInspectorEnabled
2339 {
2340     return RemoteInspector::singleton().enabled();
2341 }
2342
2343 + (BOOL)_hasRemoteInspectorSession
2344 {
2345     return RemoteInspector::singleton().hasActiveDebugSession();
2346 }
2347
2348 - (BOOL)allowsRemoteInspection
2349 {
2350     return _private->page->remoteInspectionAllowed();
2351 }
2352
2353 - (void)setAllowsRemoteInspection:(BOOL)allow
2354 {
2355     _private->page->setRemoteInspectionAllowed(allow);
2356 }
2357
2358 - (void)setShowingInspectorIndication:(BOOL)showing
2359 {
2360 #if PLATFORM(IOS)
2361     ASSERT(WebThreadIsLocked());
2362
2363     if (showing) {
2364         if (!_private->indicateLayer) {
2365             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2366             [_private->indicateLayer setNeedsLayout];
2367             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2368         }
2369     } else {
2370         [_private->indicateLayer removeFromSuperlayer];
2371         [_private->indicateLayer release];
2372         _private->indicateLayer = nil;
2373     }
2374 #else
2375     // Implemented in WebCore::InspectorOverlay.
2376 #endif
2377 }
2378
2379 #if PLATFORM(IOS)
2380 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2381 {
2382     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2383     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2384 }
2385 #endif // PLATFORM(IOS)
2386 #endif // ENABLE(REMOTE_INSPECTOR)
2387
2388 - (WebCore::Page*)page
2389 {
2390     return _private->page;
2391 }
2392
2393 #if !PLATFORM(IOS)
2394 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2395 {
2396     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2397     NSArray *menuItems = defaultMenuItems;
2398
2399     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2400     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2401     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2402     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2403         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2404         if (!menuItems)
2405             return nil;
2406     }
2407
2408     unsigned count = [menuItems count];
2409     if (!count)
2410         return nil;
2411
2412     NSMenu *menu = [[NSMenu alloc] init];
2413     for (unsigned i = 0; i < count; i++)
2414         [menu addItem:[menuItems objectAtIndex:i]];
2415
2416     return [menu autorelease];
2417 }
2418 #endif
2419
2420 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2421 {
2422     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2423     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2424     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2425     if (!dictionary)
2426         return;
2427     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2428 }
2429
2430 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2431 {
2432     if (!_private->page)
2433         return;
2434     
2435     if (!otherView->_private->page)
2436         return;
2437     
2438     // It turns out the right combination of behavior is done with the back/forward load
2439     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2440     // in the back forward list, and go to the current one.
2441
2442     BackForwardController& backForward = _private->page->backForward();
2443     ASSERT(!backForward.currentItem()); // destination list should be empty
2444
2445     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2446     if (!otherBackForward.currentItem())
2447         return; // empty back forward list, bail
2448     
2449     HistoryItem* newItemToGoTo = nullptr;
2450
2451     int lastItemIndex = otherBackForward.forwardCount();
2452     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2453         if (i == 0) {
2454             // If this item is showing , save away its current scroll and form state,
2455             // since that might have changed since loading and it is normally not saved
2456             // until we leave that page.
2457             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2458         }
2459         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2460         if (i == 0) 
2461             newItemToGoTo = newItem.ptr();
2462         backForward.client()->addItem(WTFMove(newItem));
2463     }
2464
2465     ASSERT(newItemToGoTo);
2466     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward);
2467 }
2468
2469 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2470 {
2471     _private->formDelegate = delegate;
2472 #if PLATFORM(IOS)
2473     [_private->formDelegateForwarder clearTarget];
2474     [_private->formDelegateForwarder release];
2475     _private->formDelegateForwarder = nil;
2476 #endif
2477 }
2478
2479 - (id<WebFormDelegate>)_formDelegate
2480 {
2481     return _private->formDelegate;
2482 }
2483
2484 #if PLATFORM(IOS)
2485 - (id)_formDelegateForwarder
2486 {
2487     if (_private->closing)
2488         return nil;
2489
2490     if (!_private->formDelegateForwarder)
2491         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2492     return _private->formDelegateForwarder;
2493 }
2494
2495 - (id)_formDelegateForSelector:(SEL)selector
2496 {
2497     id delegate = self->_private->formDelegate;
2498     if ([delegate respondsToSelector:selector])
2499         return delegate;
2500
2501     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2502     if ([delegate respondsToSelector:selector])
2503         return delegate;
2504
2505     return nil;
2506 }
2507 #endif
2508
2509 #if !PLATFORM(IOS)
2510 - (BOOL)_needsAdobeFrameReloadingQuirk
2511 {
2512     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2513         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2514         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2515         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2516         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2517         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2518         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2519         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2520         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2521         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2522
2523     return needsQuirk;
2524 }
2525
2526 - (BOOL)_needsLinkElementTextCSSQuirk
2527 {
2528     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2529         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2530     return needsQuirk;
2531 }
2532
2533 - (BOOL)_needsIsLoadingInAPISenseQuirk
2534 {
2535     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2536     
2537     return needsQuirk;
2538 }
2539
2540 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2541 {
2542     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2543     return needsQuirks;
2544 }
2545
2546 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2547 {
2548     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2549     return needsQuirk;
2550 }
2551
2552 static bool needsSelfRetainWhileLoadingQuirk()
2553 {
2554     static bool needsQuirk = MacApplication::isAperture();
2555     return needsQuirk;
2556 }
2557 #endif // !PLATFORM(IOS)
2558
2559 - (BOOL)_needsPreHTML5ParserQuirks
2560 {    
2561 #if !PLATFORM(IOS)
2562     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2563     // with the new HTML5 parser. If these applications were linked against a
2564     // version of WebKit prior to the introduction of the HTML5 parser, enable
2565     // parser quirks to maintain compatibility. For details, see 
2566     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2567     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2568     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2569         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2570     
2571     // Mail.app must continue to display HTML email that contains quirky markup.
2572     static bool isAppleMail = MacApplication::isAppleMail();
2573
2574     return isApplicationNeedingParserQuirks
2575         || isAppleMail
2576 #if ENABLE(DASHBOARD_SUPPORT)
2577         // Pre-HTML5 parser quirks are required to remain compatible with many
2578         // Dashboard widgets. See <rdar://problem/8175982>.
2579         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2580 #endif
2581         || [[self preferences] usePreHTML5ParserQuirks];
2582 #else
2583     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && IOSApplication::isDaijisenDictionary();
2584     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2585 #endif
2586 }
2587
2588 - (void)_preferencesChangedNotification:(NSNotification *)notification
2589 {
2590 #if PLATFORM(IOS)
2591     // For WebViews that load synchronously, preference changes need to be propagated
2592     // down to WebCore synchronously so that loads in that WebView have the correct
2593     // up-to-date settings.
2594     if (!WebThreadIsLocked())
2595         WebThreadLock();
2596     if ([[self mainFrame] _loadsSynchronously]) {
2597 #endif
2598
2599     WebPreferences *preferences = (WebPreferences *)[notification object];
2600     [self _preferencesChanged:preferences];
2601
2602 #if PLATFORM(IOS)
2603     } else {
2604         WebThreadRun(^{
2605             // It is possible that the prefs object has already changed before the invocation could be called
2606             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2607             WebPreferences *preferences = (WebPreferences *)[notification object];
2608             if (preferences != [self preferences])
2609                 return;
2610             [self _preferencesChanged:preferences];
2611         });
2612     }
2613 #endif
2614 }
2615
2616 - (void)_preferencesChanged:(WebPreferences *)preferences
2617 {    
2618     ASSERT(preferences == [self preferences]);
2619     if (!_private->userAgentOverridden)
2620         _private->userAgent = String();
2621
2622     // Cache this value so we don't have to read NSUserDefaults on each page load
2623     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2624
2625     // Update corresponding WebCore Settings object.
2626     if (!_private->page)
2627         return;
2628
2629 #if PLATFORM(IOS)
2630     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2631     // didOneTimeInitialization is true so that we don't initialize databases
2632     // until the first WebView has been created. This is because database
2633     // initialization current requires disk access to populate the origins
2634     // quota map and we want to do this lazily by waiting until WebKit is
2635     // used to display web content in a WebView. The possible cases are:
2636     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2637     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2638     if (didOneTimeInitialization) {
2639         if ([preferences databasesEnabled])
2640             [WebDatabaseManager sharedWebDatabaseManager];
2641         if ([preferences storageTrackerEnabled])
2642             WebKitInitializeStorageIfNecessary();
2643     }
2644 #endif
2645
2646     Settings& settings = _private->page->settings();
2647
2648     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2649     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2650     settings.setDefaultFontSize([preferences defaultFontSize]);
2651     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2652     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2653     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2654     settings.setFixedFontFamily([preferences fixedFontFamily]);
2655     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2656     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2657     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2658     settings.setJavaEnabled([preferences isJavaEnabled]);
2659     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2660     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2661     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2662     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2663     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2664     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2665     settings.setMinimumFontSize([preferences minimumFontSize]);
2666     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2667     settings.setPictographFontFamily([preferences pictographFontFamily]);
2668     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2669     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2670
2671     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2672     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2673     settings.setSerifFontFamily([preferences serifFontFamily]);
2674     settings.setStandardFontFamily([preferences standardFontFamily]);
2675     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2676     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2677 #if PLATFORM(IOS)
2678     settings.setShouldPrintBackgrounds(true);
2679 #else
2680     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2681 #endif
2682     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2683     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2684     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2685     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2686     settings.setUsesPageCache([self usesPageCache]);
2687     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2688     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2689
2690     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2691     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2692     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2693
2694     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2695     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2696     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2697     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2698     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2699     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2700     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2701     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2702
2703     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2704     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2705     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2706     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2707     settings.setShowDebugBorders([preferences showDebugBorders]);
2708     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2709     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2710     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2711     settings.setWebGLEnabled([preferences webGLEnabled]);
2712     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2713     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2714
2715     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2716     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2717     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2718     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2719     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2720     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2721     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2722     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2723
2724     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2725     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2726     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2727     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2728     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2729
2730     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2731     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2732     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2733     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2734     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2735     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2736     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2737     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2738     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2739     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2740     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2741     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2742     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2743     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2744     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2745
2746     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2747
2748     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2749     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2750     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2751
2752     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2753
2754     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2755     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2756
2757     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2758     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2759
2760     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2761
2762     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2763
2764     switch ([preferences storageBlockingPolicy]) {
2765     case WebAllowAllStorage:
2766         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2767         break;
2768     case WebBlockThirdPartyStorage:
2769         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2770         break;
2771     case WebBlockAllStorage:
2772         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2773         break;
2774     }
2775
2776     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2777     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2778
2779 #if PLATFORM(MAC)
2780     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2781 #endif
2782
2783 #if ENABLE(RUBBER_BANDING)
2784     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2785     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2786 #endif
2787
2788 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2789     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2790 #endif
2791 #if PLATFORM(IOS)
2792     settings.setStandalone([preferences _standalone]);
2793     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2794     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2795     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2796     settings.setMaxParseDuration([preferences _maxParseDuration]);
2797     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2798     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2799     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2800     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2801 #if HAVE(AVKIT)
2802     settings.setAVKitEnabled([preferences avKitEnabled]);
2803 #endif
2804     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2805     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2806
2807     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2808     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2809
2810     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2811     settings.setDelegatesPageScaling(true);
2812
2813 #if ENABLE(TEXT_AUTOSIZING)
2814     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2815     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2816 #endif
2817 #endif // PLATFORM(IOS)
2818
2819 #if PLATFORM(MAC)
2820     if ([preferences userStyleSheetEnabled]) {
2821         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2822         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2823             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2824         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2825     } else
2826         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2827
2828     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2829     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2830     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2831     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2832     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2833     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2834     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2835     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2836     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2837     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2838 #endif // PLATFORM(MAC)
2839
2840     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2841
2842 #if ENABLE(MEDIA_SOURCE)
2843     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2844 #endif
2845
2846 #if ENABLE(SERVICE_CONTROLS)
2847     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2848     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2849 #endif
2850
2851 #if ENABLE(VIDEO_TRACK)
2852     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2853     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2854     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2855 #endif
2856
2857 #if USE(AVFOUNDATION)
2858     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2859     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2860 #endif
2861
2862 #if ENABLE(MEDIA_STREAM)
2863     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2864     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2865     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
2866 #endif
2867
2868 #if ENABLE(WEB_RTC)
2869     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
2870 #endif
2871
2872 #if ENABLE(WEB_AUDIO)
2873     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2874 #endif
2875
2876 #if ENABLE(FULLSCREEN_API)
2877     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2878 #endif
2879
2880     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2881
2882     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2883
2884     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2885
2886 #if ENABLE(GAMEPAD)
2887     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2888 #endif
2889
2890     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2891
2892     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2893
2894     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2895
2896     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2897
2898 #if ENABLE(FETCH_API)
2899     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2900 #endif
2901
2902 #if ENABLE(WEBGL2)
2903     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2904 #endif
2905
2906 #if ENABLE(WEBGPU)
2907     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
2908 #endif
2909
2910 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2911     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2912 #endif
2913
2914     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2915
2916 #if ENABLE(WEB_ANIMATIONS)
2917     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2918 #endif
2919
2920 #if ENABLE(INTERSECTION_OBSERVER)
2921     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
2922 #endif
2923
2924 #if ENABLE(SUBTLE_CRYPTO)
2925     RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled([preferences subtleCryptoEnabled]);
2926 #endif
2927
2928     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
2929     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
2930     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
2931     RuntimeEnabledFeatures::sharedFeatures().setCredentialManagementEnabled(preferences.credentialManagementEnabled);
2932
2933     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2934     if (timeout > 0)
2935         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2936
2937     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2938     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2939
2940     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2941     if (_private->zoomsTextOnly != zoomsTextOnly)
2942         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2943
2944 #if PLATFORM(IOS)
2945     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2946     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2947     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2948     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2949 #endif
2950
2951 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2952     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2953 #endif
2954
2955     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2956
2957 #if ENABLE(ATTACHMENT_ELEMENT)
2958     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2959 #endif
2960
2961     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2962
2963     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2964
2965     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
2966     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
2967 }
2968
2969 static inline IMP getMethod(id o, SEL s)
2970 {
2971     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2972 }
2973
2974 #if PLATFORM(IOS)
2975 - (id)_UIKitDelegateForwarder
2976 {
2977     if (_private->closing)
2978         return nil;
2979         
2980     if (!_private->UIKitDelegateForwarder)
2981         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2982     return _private->UIKitDelegateForwarder;
2983 }
2984 #endif
2985
2986 - (void)_cacheResourceLoadDelegateImplementations
2987 {
2988     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2989     id delegate = _private->resourceProgressDelegate;
2990
2991     if (!delegate) {
2992         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2993         return;
2994     }
2995
2996     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2997     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2998     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2999     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3000 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3001     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3002 #endif
3003
3004 #if PLATFORM(IOS)
3005     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3006     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3007     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3008     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3009     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3010     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3011     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3012     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3013     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3014 #endif
3015
3016     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3017     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3018     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3019     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3020     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3021     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3022     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3023     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3024 }
3025
3026 - (void)_cacheFrameLoadDelegateImplementations
3027 {
3028     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3029     id delegate = _private->frameLoadDelegate;
3030
3031     if (!delegate) {
3032         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3033         return;
3034     }
3035
3036     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3037     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3038     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3039     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3040     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3041 #if JSC_OBJC_API_ENABLED
3042     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3043 #endif
3044     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3045     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3046     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3047     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3048     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3049     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3050     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3051     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3052     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3053     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3054     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3055     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3056 #if ENABLE(ICONDATABASE)
3057     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3058 #endif
3059     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3060     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3061     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3062     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3063     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3064     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3065     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3066     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3067     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3068     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3069 #if PLATFORM(IOS)
3070     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3071 #endif
3072
3073     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3074     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3075     // for backwards compatibility.
3076     Page* page = core(self);
3077     if (page) {
3078         unsigned milestones = DidFirstLayout;
3079 #if PLATFORM(IOS)
3080         milestones |= DidFirstVisuallyNonEmptyLayout;
3081 #else
3082         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3083             milestones |= DidFirstVisuallyNonEmptyLayout;
3084 #endif
3085         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3086     }
3087 }
3088
3089 - (void)_cacheScriptDebugDelegateImplementations
3090 {
3091     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3092     id delegate = _private->scriptDebugDelegate;
3093
3094     if (!delegate) {
3095         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3096         return;
3097     }
3098
3099     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3100     if (cache->didParseSourceFunc)
3101         cache->didParseSourceExpectsBaseLineNumber = YES;
3102     else {
3103         cache->didParseSourceExpectsBaseLineNumber = NO;
3104         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3105     }
3106
3107     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3108
3109     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3110     if (cache->exceptionWasRaisedFunc)
3111         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3112     else {
3113         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3114         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3115     }
3116 }
3117
3118 - (void)_cacheHistoryDelegateImplementations
3119 {
3120     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3121     id delegate = _private->historyDelegate;
3122
3123     if (!delegate) {
3124         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3125         return;
3126     }
3127
3128     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3129     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3130     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3131     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3132     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3133     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3134 }
3135
3136 - (id)_policyDelegateForwarder
3137 {
3138 #if PLATFORM(IOS)
3139     if (_private->closing)
3140         return nil;
3141 #endif
3142     if (!_private->policyDelegateForwarder)
3143         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3144     return _private->policyDelegateForwarder;
3145 }
3146
3147 - (id)_UIDelegateForwarder
3148 {
3149 #if PLATFORM(IOS)
3150     if (_private->closing)
3151         return nil;
3152 #endif
3153     if (!_private->UIDelegateForwarder)
3154         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3155     return _private->UIDelegateForwarder;
3156 }
3157
3158 #if PLATFORM(IOS)
3159 - (id)_UIDelegateForSelector:(SEL)selector
3160 {
3161     id delegate = self->_private->UIDelegate;
3162     if ([delegate respondsToSelector:selector])
3163         return delegate;
3164
3165     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3166     if ([delegate respondsToSelector:selector])
3167         return delegate;
3168
3169     return nil;
3170 }
3171 #endif
3172
3173 - (id)_editingDelegateForwarder
3174 {
3175 #if PLATFORM(IOS)
3176     if (_private->closing)
3177         return nil;
3178 #endif    
3179     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3180     // Not sure if that is a bug or not.
3181     if (!_private)
3182         return nil;
3183
3184     if (!_private->editingDelegateForwarder)
3185         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3186     return _private->editingDelegateForwarder;
3187 }
3188
3189 - (void)_closeWindow
3190 {
3191     [[self _UIDelegateForwarder] webViewClose:self];
3192 }
3193
3194 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3195 {
3196     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3197     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3198     
3199     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3200     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3201     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3202     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3203 }
3204
3205 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3206 {
3207     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3208     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3209
3210     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3211     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3212     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3213     if ([viewClass class] == [WebHTMLView class])
3214         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3215     
3216     // This is used to make _representationExistsForURLScheme faster.
3217     // Without this set, we'd have to create the MIME type each time.
3218     if (schemesWithRepresentationsSet == nil) {
3219         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3220     }
3221     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3222 }
3223
3224 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3225 {
3226     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3227 }
3228
3229 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3230 {
3231     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3232 }
3233
3234 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3235 {
3236     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3237     if (!request)
3238         return NO;
3239
3240     if ([NSURLConnection canHandleRequest:request])
3241         return YES;
3242
3243     NSString *scheme = [[request URL] scheme];
3244
3245     // Representations for URL schemes work at the top level.
3246     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3247         return YES;
3248
3249     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3250         return YES;
3251
3252     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3253         return YES;
3254
3255     return NO;
3256 }
3257
3258 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3259 {
3260     return [self _canHandleRequest:request forMainFrame:YES];
3261 }
3262
3263 + (NSString *)_decodeData:(NSData *)data
3264 {
3265     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3266     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3267 }
3268
3269 - (void)_pushPerformingProgrammaticFocus
3270 {
3271     _private->programmaticFocusCount++;
3272 }
3273
3274 - (void)_popPerformingProgrammaticFocus
3275 {
3276     _private->programmaticFocusCount--;
3277 }
3278
3279 - (BOOL)_isPerformingProgrammaticFocus
3280 {
3281     return _private->programmaticFocusCount != 0;
3282 }
3283
3284 #if !PLATFORM(IOS)
3285 - (void)_didChangeValueForKey: (NSString *)key
3286 {
3287     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3288     [self didChangeValueForKey: key];
3289 }
3290
3291 - (void)_willChangeValueForKey: (NSString *)key
3292 {
3293     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3294     [self willChangeValueForKey: key];
3295 }
3296
3297 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3298     static NSSet *manualNotifyKeys = nil;
3299     if (!manualNotifyKeys)
3300         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3301             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3302             nil];
3303     if ([manualNotifyKeys containsObject:key])
3304         return NO;
3305     return YES;
3306 }
3307
3308 - (NSArray *)_declaredKeys {
3309     static NSArray *declaredKeys = nil;
3310     if (!declaredKeys)
3311         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3312             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3313     return declaredKeys;
3314 }
3315
3316 - (void)_willChangeBackForwardKeys
3317 {
3318     [self _willChangeValueForKey: _WebCanGoBackKey];
3319     [self _willChangeValueForKey: _WebCanGoForwardKey];
3320 }
3321
3322 - (void)_didChangeBackForwardKeys
3323 {
3324     [self _didChangeValueForKey: _WebCanGoBackKey];
3325     [self _didChangeValueForKey: _WebCanGoForwardKey];
3326 }
3327
3328 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3329 {
3330     if (needsSelfRetainWhileLoadingQuirk())
3331         [self retain];
3332
3333     [self _willChangeBackForwardKeys];
3334     if (frame == [self mainFrame]){
3335         // Force an observer update by sending a will/did.
3336         [self _willChangeValueForKey: _WebIsLoadingKey];
3337         [self _didChangeValueForKey: _WebIsLoadingKey];
3338
3339         [self _willChangeValueForKey: _WebMainFrameURLKey];
3340
3341         [self hideFormValidationMessage];
3342     }
3343
3344     [NSApp setWindowsNeedUpdate:YES];
3345
3346 #if ENABLE(FULLSCREEN_API)
3347     Document* document = core([frame DOMDocument]);
3348     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3349         SEL selector = @selector(webView:closeFullScreenWithListener:);
3350         if ([_private->UIDelegate respondsToSelector:selector]) {
3351             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3352             CallUIDelegate(self, selector, listener);
3353             [listener release];
3354         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3355             [_private->newFullscreenController close];
3356         }
3357     }
3358 #endif
3359 }
3360
3361 - (void)_checkDidPerformFirstNavigation
3362 {
3363     if (_private->_didPerformFirstNavigation)
3364         return;
3365
3366     Page* page = _private->page;
3367     if (!page)
3368         return;
3369
3370     auto& backForwardController = page->backForward();
3371
3372     if (!backForwardController.backItem())
3373         return;
3374
3375     _private->_didPerformFirstNavigation = YES;
3376
3377     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3378         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3379 }
3380
3381 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3382 {
3383     if (frame == [self mainFrame])
3384         [self _didChangeValueForKey: _WebMainFrameURLKey];
3385
3386     [self _checkDidPerformFirstNavigation];
3387
3388     [NSApp setWindowsNeedUpdate:YES];
3389 }
3390
3391 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3392 {
3393     if (needsSelfRetainWhileLoadingQuirk())
3394         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3395         
3396     [self _didChangeBackForwardKeys];
3397     if (frame == [self mainFrame]){
3398         // Force an observer update by sending a will/did.
3399         [self _willChangeValueForKey: _WebIsLoadingKey];
3400         [self _didChangeValueForKey: _WebIsLoadingKey];
3401     }
3402     [NSApp setWindowsNeedUpdate:YES];
3403 }
3404
3405 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3406 {
3407     if (needsSelfRetainWhileLoadingQuirk())
3408         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3409
3410     [self _didChangeBackForwardKeys];
3411     if (frame == [self mainFrame]){
3412         // Force an observer update by sending a will/did.
3413         [self _willChangeValueForKey: _WebIsLoadingKey];
3414         [self _didChangeValueForKey: _WebIsLoadingKey];
3415     }
3416     [NSApp setWindowsNeedUpdate:YES];
3417 }
3418
3419 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3420 {
3421     if (needsSelfRetainWhileLoadingQuirk())
3422         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3423
3424     [self _didChangeBackForwardKeys];
3425     if (frame == [self mainFrame]){
3426         // Force an observer update by sending a will/did.
3427         [self _willChangeValueForKey: _WebIsLoadingKey];
3428         [self _didChangeValueForKey: _WebIsLoadingKey];
3429         
3430         [self _didChangeValueForKey: _WebMainFrameURLKey];
3431     }
3432     [NSApp setWindowsNeedUpdate:YES];
3433 }
3434
3435 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3436 {
3437     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3438     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3439     NSCachedURLResponse *cachedResponse;
3440
3441     if (!_private->page)
3442         return nil;
3443
3444     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3445         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3446     else
3447         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3448
3449     return cachedResponse;
3450 }
3451
3452 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3453 {
3454     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3455     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3456     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3457                         element:domElement
3458                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3459                           title:[element objectForKey:WebElementImageAltStringKey] 
3460                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3461                           types:types
3462                          source:nil];
3463 }
3464
3465 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3466 {
3467     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3468                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3469                         types:types];
3470 }
3471
3472 #if ENABLE(DRAG_SUPPORT)
3473 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3474 {
3475     if (!_private->page)
3476         return;
3477     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3478 }
3479 #endif
3480
3481 #else
3482
3483 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3484 {
3485     if (frame == [self mainFrame])
3486         _private->didDrawTiles = 0;
3487 }
3488
3489 #endif // PLATFORM(IOS)
3490
3491 #if ENABLE(DASHBOARD_SUPPORT)
3492
3493 #define DASHBOARD_CONTROL_LABEL @"control"
3494
3495 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3496 {
3497     NSRect adjustedBounds = bounds;
3498     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3499     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3500     adjustedBounds.size = bounds.size;
3501
3502     NSRect adjustedClip;
3503     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3504     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3505     adjustedClip.size = clip.size;
3506
3507     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3508         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3509     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3510     if (!scrollerRegions) {
3511         scrollerRegions = [[NSMutableArray alloc] init];
3512         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3513         [scrollerRegions release];
3514     }
3515     [scrollerRegions addObject:region];
3516     [region release];
3517 }
3518
3519 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3520 {    
3521     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3522
3523     for (const auto& widget: frameView->children()) {
3524         if (is<FrameView>(widget)) {
3525             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3526             continue;
3527         }
3528
3529         if (!widget->isScrollbar())
3530             continue;
3531
3532         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3533         // it's not common to need this to be correct in Dashboard widgets.
3534         NSRect bounds = widget->frameRect();
3535         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3536     }
3537 }
3538
3539 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3540 {
3541     // Add scroller regions for NSScroller and WebCore scrollbars
3542     NSUInteger count = [views count];
3543     for (NSUInteger i = 0; i < count; i++) {
3544         NSView *view = [views objectAtIndex:i];
3545         
3546         if ([view isKindOfClass:[WebHTMLView class]]) {
3547             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3548                 if (FrameView* coreView = coreFrame->view())
3549                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3550             }
3551         } else if ([view isKindOfClass:[NSScroller class]]) {
3552             // AppKit places absent scrollers at -100,-100
3553             if ([view frame].origin.y < 0)
3554                 continue;
3555             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3556         }
3557         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3558     }
3559 }
3560
3561 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3562 {
3563     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3564 }
3565
3566 - (NSDictionary *)_dashboardRegions
3567 {
3568     // Only return regions from main frame.
3569     Frame* mainFrame = [self _mainCoreFrame];
3570     if (!mainFrame)
3571         return nil;
3572
3573     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3574     size_t size = regions.size();
3575
3576     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3577     for (size_t i = 0; i < size; i++) {
3578         const AnnotatedRegionValue& region = regions[i];
3579
3580         if (region.type == StyleDashboardRegion::None)
3581             continue;
3582
3583         NSString *label = region.label;
3584         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3585         if (region.type == StyleDashboardRegion::Circle)
3586             type = WebDashboardRegionTypeCircle;
3587         else if (region.type == StyleDashboardRegion::Rectangle)
3588             type = WebDashboardRegionTypeRectangle;
3589         NSMutableArray *regionValues = [webRegions objectForKey:label];
3590         if (!regionValues) {
3591             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3592             [webRegions setObject:regionValues forKey:label];
3593             [regionValues release];
3594         }
3595
3596         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3597         [regionValues addObject:webRegion];
3598         [webRegion release];
3599     }
3600
3601     [self _addScrollerDashboardRegions:webRegions];
3602
3603     return webRegions;
3604 }
3605
3606 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3607 {
3608     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3609     // specific support for the backward compatibility mode flag.
3610     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3611         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3612     
3613     switch (behavior) {
3614         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3615             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3616             break;
3617         }
3618         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3619             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3620             break;
3621         }
3622         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3623             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3624             break;
3625         }
3626         case WebDashboardBehaviorAllowWheelScrolling: {
3627             _private->dashboardBehaviorAllowWheelScrolling = flag;
3628             break;
3629         }
3630         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3631             if (_private->page)
3632                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3633 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3634             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3635 #endif
3636             break;
3637         }
3638     }
3639
3640     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3641     // compatibility mode. See <rdar://problem/8175982>.
3642     if (_private->page)
3643         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3644 }
3645
3646 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3647 {
3648     switch (behavior) {
3649         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3650             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3651         }
3652         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3653             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3654         }
3655         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3656             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3657         }
3658         case WebDashboardBehaviorAllowWheelScrolling: {
3659             return _private->dashboardBehaviorAllowWheelScrolling;
3660         }
3661         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3662             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3663         }
3664     }
3665     return NO;
3666 }
3667
3668 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3669
3670 + (void)_setShouldUseFontSmoothing:(BOOL)f
3671 {
3672     FontCascade::setShouldUseSmoothing(f);
3673 }
3674
3675 + (BOOL)_shouldUseFontSmoothing
3676 {
3677     return FontCascade::shouldUseSmoothing();
3678 }
3679
3680 #if !PLATFORM(IOS)
3681 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3682 {
3683     setUsesTestModeFocusRingColor(f);
3684 }
3685
3686 + (BOOL)_usesTestModeFocusRingColor
3687 {
3688     return usesTestModeFocusRingColor();
3689 }
3690 #endif
3691
3692 #if PLATFORM(IOS)
3693 - (void)_setUIKitDelegate:(id)delegate
3694 {
3695     _private->UIKitDelegate = delegate;
3696     [_private->UIKitDelegateForwarder clearTarget];
3697     [_private->UIKitDelegateForwarder release];
3698     _private->UIKitDelegateForwarder = nil;
3699 }
3700
3701 - (id)_UIKitDelegate
3702 {
3703     return _private->UIKitDelegate;
3704 }
3705
3706 - (void)setWebMailDelegate:(id)delegate
3707 {
3708     _private->WebMailDelegate = delegate;
3709 }
3710
3711 - (id)_webMailDelegate
3712 {
3713     return _private->WebMailDelegate;
3714 }
3715
3716 - (id <WebCaretChangeListener>)caretChangeListener
3717 {
3718     return _private->_caretChangeListener;
3719 }
3720
3721 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3722 {
3723     _private->_caretChangeListener = listener;
3724 }
3725
3726 - (NSSet *)caretChangeListeners
3727 {
3728     return _private->_caretChangeListeners;
3729 }
3730
3731 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3732 {
3733     if (_private->_caretChangeListeners == nil) {
3734         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3735     }
3736     
3737     [_private->_caretChangeListeners addObject:listener];
3738 }
3739
3740 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3741 {
3742     [_private->_caretChangeListeners removeObject:listener];
3743 }
3744
3745 - (void)removeAllCaretChangeListeners
3746 {
3747     [_private->_caretChangeListeners removeAllObjects];
3748 }
3749
3750 - (void)caretChanged
3751 {
3752     [_private->_caretChangeListener caretChanged];
3753     NSSet *copy = [_private->_caretChangeListeners copy];
3754     for (id <WebCaretChangeListener> listener in copy) {
3755         [listener caretChanged];
3756     }
3757     [copy release];
3758 }
3759
3760 - (void)_clearDelegates
3761 {
3762     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3763     
3764     [self _setFormDelegate:nil];
3765     [self _setUIKitDelegate:nil];
3766     [self setCaretChangeListener:nil];
3767     [self removeAllCaretChangeListeners];
3768     [self setWebMailDelegate:nil];
3769     
3770     [self setDownloadDelegate:nil];
3771     [self setEditingDelegate:nil]; 
3772     [self setFrameLoadDelegate:nil];
3773     [self setPolicyDelegate:nil];
3774     [self setResourceLoadDelegate:nil];
3775     [self setScriptDebugDelegate:nil];
3776     [self setUIDelegate:nil];     
3777 }
3778
3779 - (NSURL *)_displayURL
3780 {
3781     WebThreadLock();
3782     WebFrame *frame = [self mainFrame];
3783     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3784     WebDataSource *dataSource = [frame provisionalDataSource];
3785     if (!dataSource)
3786         dataSource = [frame dataSource];
3787     NSURL *unreachableURL = [dataSource unreachableURL];
3788     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3789     [[URL retain] autorelease];
3790     return URL;
3791 }
3792 #endif // PLATFORM(IOS)
3793
3794 #if !PLATFORM(IOS)
3795 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3796 {
3797     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3798     if (flag) {
3799         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3800     } else {
3801         [scrollview setVerticalScrollingModeLocked:NO];
3802         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3803     }
3804 }
3805
3806 - (BOOL)alwaysShowVerticalScroller
3807 {
3808     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3809     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3810 }
3811
3812 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3813 {
3814     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3815     if (flag) {
3816         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3817     } else {
3818         [scrollview setHorizontalScrollingModeLocked:NO];
3819         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3820     }
3821 }
3822
3823 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3824 {
3825     if (Frame* mainFrame = [self _mainCoreFrame])
3826         mainFrame->view()->setProhibitsScrolling(prohibits);
3827 }
3828
3829 - (BOOL)alwaysShowHorizontalScroller
3830 {
3831     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3832     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3833 }
3834 #endif // !PLATFORM(IOS)
3835
3836 - (void)_setUseFastImageScalingMode:(BOOL)flag
3837 {
3838     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3839         _private->page->setInLowQualityImageInterpolationMode(flag);
3840         [self setNeedsDisplay:YES];
3841     }
3842 }
3843
3844 - (BOOL)_inFastImageScalingMode
3845 {
3846     if (_private->page)
3847         return _private->page->inLowQualityImageInterpolationMode();
3848     return NO;
3849 }
3850
3851 - (BOOL)_cookieEnabled
3852 {
3853     if (_private->page)
3854         return _private->page->settings().cookieEnabled();
3855     return YES;
3856 }
3857
3858 - (void)_setCookieEnabled:(BOOL)enable
3859 {
3860     if (_private->page)
3861         _private->page->settings().setCookieEnabled(enable);
3862 }
3863
3864 #if !PLATFORM(IOS)
3865 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3866 {
3867     if (!_private->pluginDatabase)
3868         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3869         
3870     [_private->pluginDatabase setPlugInPaths:newPaths];
3871     [_private->pluginDatabase refresh];
3872 }
3873 #endif
3874
3875 #if PLATFORM(IOS)
3876 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3877 {
3878     // Ask plug-ins in this frame
3879     id <WebDocumentView> documentView = [[frame frameView] documentView];
3880     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3881         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3882             return YES;
3883     }
3884
3885     // Ask plug-ins in child frames
3886     NSArray *childFrames = [frame childFrames];
3887     unsigned childCount = [childFrames count];
3888     unsigned childIndex;
3889     for (childIndex = 0; childIndex < childCount; childIndex++) {
3890         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3891             return YES;
3892     }
3893     
3894     return NO;
3895 }
3896
3897 - (BOOL)_pluginsAreRunning
3898 {
3899     WebThreadLock();
3900     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3901 }
3902
3903 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3904 {
3905     // Send the message to plug-ins in this frame
3906     id <WebDocumentView> documentView = [[frame frameView] documentView];
3907     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3908         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3909
3910     // Send the message to plug-ins in child frames
3911     NSArray *childFrames = [frame childFrames];
3912     unsigned childCount = [childFrames count];
3913     unsigned childIndex;
3914     for (childIndex = 0; childIndex < childCount; childIndex++) {
3915         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3916     }
3917 }
3918
3919 - (void)_destroyAllPlugIns
3920 {
3921     WebThreadLock();
3922     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3923 }
3924
3925 - (void)_startAllPlugIns
3926 {
3927     WebThreadLock();
3928     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3929 }
3930
3931 - (void)_stopAllPlugIns
3932 {
3933     WebThreadLock();
3934     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3935 }
3936
3937 - (void)_stopAllPlugInsForPageCache
3938 {
3939     WebThreadLock();
3940     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3941 }
3942
3943 - (void)_restorePlugInsFromCache
3944 {
3945     WebThreadLock();
3946     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3947 }
3948
3949 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3950 {
3951     WebThreadLock();
3952
3953     Frame* mainCoreFrame = [self _mainCoreFrame];
3954     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3955         FrameView* coreView = frame ? frame->view() : 0;
3956         if (!coreView)
3957             continue;
3958
3959         // Get the GraphicsLayer for this widget.
3960         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3961         if (!layerForWidget)
3962             continue;
3963         
3964         if (layerForWidget->contentsLayerForMedia() != layer) {
3965             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3966             // We need to make sure the layer hierachy change is applied immediately.
3967             if (mainCoreFrame->view())
3968                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3969             return YES;
3970         }
3971     }
3972
3973     return NO;
3974 }
3975
3976 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3977 {
3978     if (_private->page)
3979         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3980 }
3981 #endif // PLATFORM(IOS)
3982
3983 - (void)_attachScriptDebuggerToAllFrames
3984 {
3985     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3986         [kit(frame) _attachScriptDebugger];
3987 }
3988
3989 - (void)_detachScriptDebuggerFromAllFrames
3990 {
3991     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3992         [kit(frame) _detachScriptDebugger];
3993 }
3994
3995 #if !PLATFORM(IOS)
3996 - (void)setBackgroundColor:(NSColor *)backgroundColor
3997 {
3998     if ([_private->backgroundColor isEqual:backgroundColor])
3999         return;
4000
4001     id old = _private->backgroundColor;
4002     _private->backgroundColor = [backgroundColor retain];
4003     [old release];
4004
4005     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
4006 }
4007
4008 - (NSColor *)backgroundColor
4009 {
4010     return _private->backgroundColor;
4011 }
4012 #else
4013 - (void)setBackgroundColor:(CGColorRef)backgroundColor
4014 {
4015    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
4016         return;
4017
4018     CFTypeRef old = _private->backgroundColor;
4019     CFRetain(backgroundColor);
4020     _private->backgroundColor = backgroundColor;
4021     CFRelease(old);
4022
4023     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
4024 }
4025
4026 - (CGColorRef)backgroundColor
4027 {
4028     return _private->backgroundColor;
4029 }
4030 #endif
4031
4032 - (BOOL)defersCallbacks
4033 {
4034     if (!_private->page)
4035         return NO;
4036     return _private->page->defersLoading();
4037 }
4038
4039 - (void)setDefersCallbacks:(BOOL)defer
4040 {
4041     if (!_private->page)
4042         return;
4043     return _private->page->setDefersLoading(defer);
4044 }
4045
4046 #if PLATFORM(IOS)
4047 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
4048 {
4049     return nil;
4050 }
4051
4052 - (BOOL)_isStopping
4053 {
4054     return _private->isStopping;
4055 }
4056
4057 - (BOOL)_isClosing
4058 {
4059     return _private->closing;
4060 }
4061
4062 + (NSArray *)_productivityDocumentMIMETypes
4063 {
4064 #if USE(QUICK_LOOK)
4065     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
4066 #else
4067     return nil;
4068 #endif
4069 }
4070
4071 - (void)_setAllowsMessaging:(BOOL)aFlag
4072 {
4073     _private->allowsMessaging = aFlag;
4074 }
4075
4076 - (BOOL)_allowsMessaging
4077 {
4078     return _private->allowsMessaging;
4079 }
4080
4081 - (void)_setFixedLayoutSize:(CGSize)size
4082 {
4083     ASSERT(WebThreadIsLocked());
4084     _private->fixedLayoutSize = size;
4085     if (Frame* mainFrame = core([self mainFrame])) {
4086         IntSize newSize(size);
4087         mainFrame->view()->setFixedLayoutSize(newSize);
4088         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
4089         [self setNeedsDisplay:YES];
4090     }
4091 }
4092
4093 - (CGSize)_fixedLayoutSize
4094 {
4095     return _private->fixedLayoutSize;
4096 }
4097
4098 - (void)_synchronizeCustomFixedPositionLayoutRect
4099 {
4100     ASSERT(WebThreadIsLocked());
4101
4102     IntRect newRect;
4103     {
4104         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4105         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4106             return;
4107         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
4108         _private->pendingFixedPositionLayoutRect = CGRectNull;
4109     }
4110
4111     if (Frame* mainFrame = core([self mainFrame]))
4112         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
4113 }
4114
4115 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
4116 {
4117     {
4118         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4119         _private->pendingFixedPositionLayoutRect = rect;
4120     }
4121     if (!synchronize)
4122         return;
4123     WebThreadRun(^{
4124         [self _synchronizeCustomFixedPositionLayoutRect];
4125     });
4126 }
4127
4128 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
4129 {
4130     ASSERT(WebThreadIsLocked());
4131     {
4132         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4133         _private->pendingFixedPositionLayoutRect = rect;
4134     }
4135     [self _synchronizeCustomFixedPositionLayoutRect];
4136 }
4137
4138 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
4139 {
4140     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4141     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4142         return false;
4143
4144     *rect = _private->pendingFixedPositionLayoutRect;
4145     _private->pendingFixedPositionLayoutRect = CGRectNull;
4146     return true;
4147 }
4148
4149 - (void)_viewGeometryDidChange
4150 {
4151     ASSERT(WebThreadIsLocked());
4152     
4153     if (Frame* coreFrame = [self _mainCoreFrame])
4154         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
4155 }
4156
4157 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
4158 {
4159     // Find the frame
4160     Node* node = core(domNode);
4161     Frame* frame = node->document().frame();
4162     if (!frame)
4163         return;
4164
4165     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
4166 }
4167
4168 + (void)_doNotStartObservingNetworkReachability
4169 {
4170     Settings::setShouldOptOutOfNetworkStateObservation(true);
4171 }
4172 #endif // PLATFORM(IOS)
4173
4174 #if ENABLE(TOUCH_EVENTS)
4175 - (NSArray *)_touchEventRegions
4176 {
4177     Frame* frame = [self _mainCoreFrame];
4178     if (!frame)
4179         return nil;
4180     
4181     Document* document = frame->document();
4182     if (!document)
4183         return nil;
4184
4185     Vector<IntRect> rects;
4186     document->getTouchRects(rects);
4187
4188     if (rects.size() == 0)
4189         return nil;
4190
4191     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
4192
4193     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
4194     Vector<IntRect>::const_iterator end = rects.end();
4195     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
4196         const IntRect& rect = *it;
4197         if (rect.isEmpty())
4198             continue;
4199
4200         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
4201         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
4202         // convert them here now.
4203         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
4204
4205         // The event region wants this points in this order:
4206         //  p2------p3
4207         //  |       |
4208         //  p1------p4
4209         //
4210         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
4211                                                                             :FloatPoint(viewRect.x(), viewRect.y())
4212                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
4213                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
4214         if (eventRegion) {
4215             [eventRegionArray addObject:eventRegion];
4216             [eventRegion release];
4217         }
4218     }
4219
4220     return eventRegionArray;
4221 }
4222 #endif // ENABLE(TOUCH_EVENTS)
4223
4224 // For backwards compatibility with the WebBackForwardList API, we honor both
4225 // a per-WebView and a per-preferences setting for whether to use the page cache.
4226
4227 - (BOOL)usesPageCache
4228 {
4229     return _private->usesPageCache && [[self preferences] usesPageCache];
4230 }
4231
4232 - (void)setUsesPageCache:(BOOL)usesPageCache
4233 {
4234     _private->usesPageCache = usesPageCache;
4235
4236     // Update our own settings and post the public notification only
4237     [self _preferencesChanged:[self preferences]];
4238     [[self preferences] _postPreferencesChangedAPINotification];
4239 }
4240
4241 - (WebHistoryItem *)_globalHistoryItem
4242 {
4243     if (!_private)
4244         return nil;
4245
4246     return kit(_private->_globalHistoryItem.get());
4247 }
4248
4249 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
4250 {
4251     _private->_globalHistoryItem = historyItem;
4252 }
4253
4254 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
4255 {
4256     IntPoint rectStart(rect.origin.x, rect.origin.y);
4257     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
4258     
4259     Frame* coreFrame = [self _mainCoreFrame];
4260     if (!coreFrame)
4261         return nil;
4262     
4263     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
4264     
4265     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
4266 }
4267
4268 #if !PLATFORM(IOS)
4269 - (void)_clearUndoRedoOperations
4270 {
4271     if (!_private->page)
4272         return;
4273     _private->page->clearUndoRedoOperations();
4274 }
4275 #endif
4276
4277 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
4278 {
4279     Frame* coreFrame = [self _mainCoreFrame];
4280     if (!coreFrame)
4281         return;
4282     coreFrame->editor().command(name).execute(value);
4283 }
4284
4285 - (void)_clearMainFrameName
4286 {
4287     _private->page->mainFrame().tree().clearName();
4288 }
4289
4290 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
4291 {
4292     if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
4293         _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);