2 * Copyright (C) 2005-2013 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4 * Copyright (C) 2010 Igalia S.L
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
34 #import "DOMCSSStyleDeclarationInternal.h"
35 #import "DOMDocumentInternal.h"
36 #import "DOMNodeInternal.h"
37 #import "DOMRangeInternal.h"
38 #import "StorageThread.h"
39 #import "WebAlternativeTextClient.h"
40 #import "WebApplicationCacheInternal.h"
41 #import "WebBackForwardListInternal.h"
42 #import "WebBaseNetscapePluginView.h"
44 #import "WebChromeClient.h"
45 #import "WebDOMOperationsPrivate.h"
46 #import "WebDataSourceInternal.h"
47 #import "WebDatabaseManagerPrivate.h"
48 #import "WebDatabaseProvider.h"
49 #import "WebDefaultEditingDelegate.h"
50 #import "WebDefaultPolicyDelegate.h"
51 #import "WebDefaultUIDelegate.h"
52 #import "WebDelegateImplementationCaching.h"
53 #import "WebDeviceOrientationClient.h"
54 #import "WebDeviceOrientationProvider.h"
55 #import "WebDocument.h"
56 #import "WebDocumentInternal.h"
57 #import "WebDownload.h"
58 #import "WebDownloadInternal.h"
59 #import "WebDragClient.h"
60 #import "WebDynamicScrollBarsViewInternal.h"
61 #import "WebEditingDelegate.h"
62 #import "WebEditorClient.h"
63 #import "WebFormDelegatePrivate.h"
64 #import "WebFrameInternal.h"
65 #import "WebFrameLoaderClient.h"
66 #import "WebFrameNetworkingContext.h"
67 #import "WebFrameViewInternal.h"
68 #import "WebGeolocationClient.h"
69 #import "WebGeolocationPositionInternal.h"
70 #import "WebHTMLRepresentation.h"
71 #import "WebHTMLViewInternal.h"
72 #import "WebHistoryItemInternal.h"
73 #import "WebIconDatabaseInternal.h"
74 #import "WebInspector.h"
75 #import "WebInspectorClient.h"
76 #import "WebKitErrors.h"
77 #import "WebKitFullScreenListener.h"
78 #import "WebKitLogging.h"
79 #import "WebKitNSStringExtras.h"
80 #import "WebKitStatisticsPrivate.h"
81 #import "WebKitVersionChecks.h"
82 #import "WebLocalizableStrings.h"
83 #import "WebNSDataExtras.h"
84 #import "WebNSDataExtrasPrivate.h"
85 #import "WebNSDictionaryExtras.h"
86 #import "WebNSURLExtras.h"
87 #import "WebNSURLRequestExtras.h"
88 #import "WebNSViewExtras.h"
89 #import "WebNodeHighlight.h"
90 #import "WebNotificationClient.h"
91 #import "WebPDFView.h"
92 #import "WebPlatformStrategies.h"
93 #import "WebPluginDatabase.h"
94 #import "WebPolicyDelegate.h"
95 #import "WebPreferenceKeysPrivate.h"
96 #import "WebPreferencesPrivate.h"
97 #import "WebProgressTrackerClient.h"
98 #import "WebResourceLoadScheduler.h"
99 #import "WebScriptDebugDelegate.h"
100 #import "WebScriptWorldInternal.h"
101 #import "WebSelectionServiceController.h"
102 #import "WebStorageManagerInternal.h"
103 #import "WebStorageNamespaceProvider.h"
104 #import "WebSystemInterface.h"
105 #import "WebTextCompletionController.h"
106 #import "WebTextIterator.h"
107 #import "WebUIDelegate.h"
108 #import "WebUIDelegatePrivate.h"
109 #import "WebUserMediaClient.h"
110 #import "WebViewGroup.h"
111 #import "WebVisitedLinkStore.h"
112 #import <CoreFoundation/CFSet.h>
113 #import <Foundation/NSURLConnection.h>
114 #import <JavaScriptCore/APICast.h>
115 #import <JavaScriptCore/Exception.h>
116 #import <JavaScriptCore/JSValueRef.h>
117 #import <WebCore/AlternativeTextUIController.h>
118 #import <WebCore/AnimationController.h>
119 #import <WebCore/ApplicationCacheStorage.h>
120 #import <WebCore/BackForwardController.h>
121 #import <WebCore/BackForwardList.h>
122 #import <WebCore/CFNetworkSPI.h>
123 #import <WebCore/Chrome.h>
124 #import <WebCore/ColorMac.h>
125 #import <WebCore/DatabaseManager.h>
126 #import <WebCore/DictionaryLookup.h>
127 #import <WebCore/Document.h>
128 #import <WebCore/DocumentLoader.h>
129 #import <WebCore/DragController.h>
130 #import <WebCore/DragData.h>
131 #import <WebCore/Editor.h>
132 #import <WebCore/EventHandler.h>
133 #import <WebCore/ExceptionHandlers.h>
134 #import <WebCore/FocusController.h>
135 #import <WebCore/FontCache.h>
136 #import <WebCore/FrameLoader.h>
137 #import <WebCore/FrameSelection.h>
138 #import <WebCore/FrameTree.h>
139 #import <WebCore/FrameView.h>
140 #import <WebCore/GCController.h>
141 #import <WebCore/GeolocationController.h>
142 #import <WebCore/GeolocationError.h>
143 #import <WebCore/HTMLNames.h>
144 #import <WebCore/HTMLVideoElement.h>
145 #import <WebCore/HistoryController.h>
146 #import <WebCore/HistoryItem.h>
147 #import <WebCore/IconDatabase.h>
148 #import <WebCore/JSCSSStyleDeclaration.h>
149 #import <WebCore/JSDocument.h>
150 #import <WebCore/JSElement.h>
151 #import <WebCore/JSNodeList.h>
152 #import <WebCore/JSNotification.h>
153 #import <WebCore/Logging.h>
154 #import <WebCore/MIMETypeRegistry.h>
155 #import <WebCore/MainFrame.h>
156 #import <WebCore/MemoryCache.h>
157 #import <WebCore/MemoryPressureHandler.h>
158 #import <WebCore/NSURLFileTypeMappingsSPI.h>
159 #import <WebCore/NodeList.h>
160 #import <WebCore/Notification.h>
161 #import <WebCore/NotificationController.h>
162 #import <WebCore/Page.h>
163 #import <WebCore/PageCache.h>
164 #import <WebCore/PageConfiguration.h>
165 #import <WebCore/PageGroup.h>
166 #import <WebCore/PlatformEventFactoryMac.h>
167 #import <WebCore/ProgressTracker.h>
168 #import <WebCore/RenderView.h>
169 #import <WebCore/RenderWidget.h>
170 #import <WebCore/ResourceHandle.h>
171 #import <WebCore/ResourceLoadObserver.h>
172 #import <WebCore/ResourceRequest.h>
173 #import <WebCore/RuntimeApplicationChecks.h>
174 #import <WebCore/RuntimeEnabledFeatures.h>
175 #import <WebCore/SchemeRegistry.h>
176 #import <WebCore/ScriptController.h>
177 #import <WebCore/SecurityOrigin.h>
178 #import <WebCore/SecurityPolicy.h>
179 #import <WebCore/Settings.h>
180 #import <WebCore/StyleProperties.h>
181 #import <WebCore/TextResourceDecoder.h>
182 #import <WebCore/ThreadCheck.h>
183 #import <WebCore/UserAgent.h>
184 #import <WebCore/UserContentController.h>
185 #import <WebCore/UserScript.h>
186 #import <WebCore/UserStyleSheet.h>
187 #import <WebCore/WebCoreObjCExtras.h>
188 #import <WebCore/WebCoreView.h>
189 #import <WebCore/Widget.h>
190 #import <WebKitLegacy/DOM.h>
191 #import <WebKitLegacy/DOMExtensions.h>
192 #import <WebKitLegacy/DOMPrivate.h>
193 #import <WebKitSystemInterface.h>
194 #import <bindings/ScriptValue.h>
195 #import <mach-o/dyld.h>
196 #import <objc/runtime.h>
197 #import <runtime/ArrayPrototype.h>
198 #import <runtime/DateInstance.h>
199 #import <runtime/InitializeThreading.h>
200 #import <runtime/JSCJSValue.h>
201 #import <runtime/JSLock.h>
202 #import <wtf/Assertions.h>
203 #import <wtf/HashTraits.h>
204 #import <wtf/MainThread.h>
205 #import <wtf/ObjcRuntimeExtras.h>
206 #import <wtf/RAMSize.h>
207 #import <wtf/RefCountedLeakCounter.h>
208 #import <wtf/RefPtr.h>
209 #import <wtf/RunLoop.h>
210 #import <wtf/StdLibExtras.h>
213 #import "WebContextMenuClient.h"
214 #import "WebFullScreenController.h"
215 #import "WebImmediateActionController.h"
216 #import "WebNSEventExtras.h"
217 #import "WebNSObjectExtras.h"
218 #import "WebNSPasteboardExtras.h"
219 #import "WebNSPrintOperationExtras.h"
220 #import "WebPDFView.h"
221 #import <WebCore/LookupSPI.h>
222 #import <WebCore/NSImmediateActionGestureRecognizerSPI.h>
223 #import <WebCore/SoftLinking.h>
224 #import <WebCore/TextIndicator.h>
225 #import <WebCore/TextIndicatorWindow.h>
226 #import <WebCore/WebVideoFullscreenController.h>
228 #import "MemoryMeasure.h"
229 #import "WebCaretChangeListener.h"
230 #import "WebChromeClientIOS.h"
231 #import "WebDefaultFormDelegate.h"
232 #import "WebDefaultFrameLoadDelegate.h"
233 #import "WebDefaultResourceLoadDelegate.h"
234 #import "WebDefaultUIKitDelegate.h"
235 #import "WebFixedPositionContent.h"
236 #import "WebMailDelegate.h"
237 #import "WebNSUserDefaultsExtras.h"
238 #import "WebPDFViewIOS.h"
239 #import "WebPlainWhiteView.h"
240 #import "WebPluginController.h"
241 #import "WebPolicyDelegatePrivate.h"
242 #import "WebSQLiteDatabaseTrackerClient.h"
243 #import "WebStorageManagerPrivate.h"
244 #import "WebUIKitSupport.h"
245 #import "WebVisiblePosition.h"
246 #import <WebCore/DynamicLinkerSPI.h>
247 #import <WebCore/EventNames.h>
248 #import <WebCore/FontCache.h>
249 #import <WebCore/GraphicsLayer.h>
250 #import <WebCore/IconController.h>
251 #import <WebCore/LegacyTileCache.h>
252 #import <WebCore/MobileGestaltSPI.h>
253 #import <WebCore/NetworkStateNotifier.h>
254 #import <WebCore/PlatformScreen.h>
255 #import <WebCore/ResourceLoadStatistics.h>
256 #import <WebCore/ResourceLoadStatisticsStore.h>
257 #import <WebCore/SQLiteDatabaseTracker.h>
258 #import <WebCore/SmartReplace.h>
259 #import <WebCore/TextRun.h>
260 #import <WebCore/TileControllerMemoryHandlerIOS.h>
261 #import <WebCore/WAKWindow.h>
262 #import <WebCore/WKView.h>
263 #import <WebCore/WebCoreThread.h>
264 #import <WebCore/WebCoreThreadMessage.h>
265 #import <WebCore/WebCoreThreadRun.h>
266 #import <WebCore/WebEvent.h>
267 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
268 #import <libkern/OSAtomic.h>
269 #import <wtf/FastMalloc.h>
270 #endif // !PLATFORM(IOS)
272 #if ENABLE(DASHBOARD_SUPPORT)
273 #import <WebKitLegacy/WebDashboardRegion.h>
276 #if ENABLE(REMOTE_INSPECTOR)
277 #import <JavaScriptCore/RemoteInspector.h>
279 #import "WebIndicateLayer.h"
284 #include <WebCore/QuickLook.h>
287 #if ENABLE(IOS_TOUCH_EVENTS)
288 #import <WebCore/WebEventRegion.h>
292 #import <WebCore/HIDGamepadProvider.h>
295 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
296 #import "WebMediaPlaybackTargetPicker.h"
297 #import <WebCore/WebMediaSessionManagerMac.h>
300 #if USE(APPLE_INTERNAL_SDK)
301 #import <WebKitAdditions/WebViewIncludes.h>
305 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
309 @interface NSSpellChecker (WebNSSpellCheckerDetails)
310 - (void)_preflightChosenSpellServer;
313 @interface NSView (WebNSViewDetails)
314 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
315 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
316 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
317 - (void)_windowChangedKeyState;
320 @interface NSWindow (WebNSWindowDetails)
321 - (id)_oldFirstResponderBeforeBecoming;
322 - (void)_enableScreenUpdatesIfNeeded;
323 - (BOOL)_wrapsCarbonWindow;
324 - (BOOL)_hasKeyAppearance;
329 using namespace Inspector;
330 using namespace WebCore;
332 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
334 macro(alignJustified) \
337 macro(capitalizeWord) \
338 macro(centerSelectionInVisibleArea) \
339 macro(changeAttributes) \
340 macro(changeBaseWritingDirection) \
341 macro(changeBaseWritingDirectionToLTR) \
342 macro(changeBaseWritingDirectionToRTL) \
344 macro(changeDocumentBackgroundColor) \
346 macro(changeSpelling) \
347 macro(checkSpelling) \
353 macro(deleteBackward) \
354 macro(deleteBackwardByDecomposingPreviousCharacter) \
355 macro(deleteForward) \
356 macro(deleteToBeginningOfLine) \
357 macro(deleteToBeginningOfParagraph) \
358 macro(deleteToEndOfLine) \
359 macro(deleteToEndOfParagraph) \
360 macro(deleteToMark) \
361 macro(deleteWordBackward) \
362 macro(deleteWordForward) \
363 macro(ignoreSpelling) \
365 macro(insertBacktab) \
366 macro(insertLineBreak) \
367 macro(insertNewline) \
368 macro(insertNewlineIgnoringFieldEditor) \
369 macro(insertParagraphSeparator) \
371 macro(insertTabIgnoringFieldEditor) \
372 macro(lowercaseWord) \
373 macro(makeBaseWritingDirectionLeftToRight) \
374 macro(makeBaseWritingDirectionRightToLeft) \
375 macro(makeTextWritingDirectionLeftToRight) \
376 macro(makeTextWritingDirectionNatural) \
377 macro(makeTextWritingDirectionRightToLeft) \
378 macro(moveBackward) \
379 macro(moveBackwardAndModifySelection) \
381 macro(moveDownAndModifySelection) \
383 macro(moveForwardAndModifySelection) \
385 macro(moveLeftAndModifySelection) \
386 macro(moveParagraphBackwardAndModifySelection) \
387 macro(moveParagraphForwardAndModifySelection) \
389 macro(moveRightAndModifySelection) \
390 macro(moveToBeginningOfDocument) \
391 macro(moveToBeginningOfDocumentAndModifySelection) \
392 macro(moveToBeginningOfLine) \
393 macro(moveToBeginningOfLineAndModifySelection) \
394 macro(moveToBeginningOfParagraph) \
395 macro(moveToBeginningOfParagraphAndModifySelection) \
396 macro(moveToBeginningOfSentence) \
397 macro(moveToBeginningOfSentenceAndModifySelection) \
398 macro(moveToEndOfDocument) \
399 macro(moveToEndOfDocumentAndModifySelection) \
400 macro(moveToEndOfLine) \
401 macro(moveToEndOfLineAndModifySelection) \
402 macro(moveToEndOfParagraph) \
403 macro(moveToEndOfParagraphAndModifySelection) \
404 macro(moveToEndOfSentence) \
405 macro(moveToEndOfSentenceAndModifySelection) \
406 macro(moveToLeftEndOfLine) \
407 macro(moveToLeftEndOfLineAndModifySelection) \
408 macro(moveToRightEndOfLine) \
409 macro(moveToRightEndOfLineAndModifySelection) \
411 macro(moveUpAndModifySelection) \
412 macro(moveWordBackward) \
413 macro(moveWordBackwardAndModifySelection) \
414 macro(moveWordForward) \
415 macro(moveWordForwardAndModifySelection) \
416 macro(moveWordLeft) \
417 macro(moveWordLeftAndModifySelection) \
418 macro(moveWordRight) \
419 macro(moveWordRightAndModifySelection) \
420 macro(orderFrontSubstitutionsPanel) \
424 macro(pageDownAndModifySelection) \
426 macro(pageUpAndModifySelection) \
428 macro(pasteAsPlainText) \
429 macro(pasteAsRichText) \
431 macro(performFindPanelAction) \
432 macro(scrollLineDown) \
433 macro(scrollLineUp) \
434 macro(scrollPageDown) \
435 macro(scrollPageUp) \
436 macro(scrollToBeginningOfDocument) \
437 macro(scrollToEndOfDocument) \
440 macro(selectParagraph) \
441 macro(selectSentence) \
442 macro(selectToMark) \
445 macro(showGuessPanel) \
446 macro(startSpeaking) \
447 macro(stopSpeaking) \
450 macro(swapWithMark) \
451 macro(takeFindStringFromSelection) \
452 macro(toggleBaseWritingDirection) \
456 macro(uppercaseWord) \
458 macro(yankAndSelect) \
460 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
461 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
463 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
464 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
466 static BOOL s_didSetCacheModel;
467 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
470 static Class s_pdfRepresentationClass;
471 static Class s_pdfViewClass;
475 static const char webViewIsOpen[] = "At least one WebView is still open.";
479 @interface WebView(WebViewPrivate)
480 - (void)_preferencesChanged:(WebPreferences *)preferences;
481 - (void)_updateScreenScaleFromWindow;
484 @interface NSURLCache (WebPrivate)
485 - (CFURLCacheRef)_CFURLCache;
490 @interface NSObject (WebValidateWithoutDelegate)
491 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
496 @class _WebSafeForwarder;
498 @interface _WebSafeAsyncForwarder : NSObject {
499 _WebSafeForwarder *_forwarder;
501 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
505 @interface _WebSafeForwarder : NSObject
507 id target; // Non-retained. Don't retain delegates.
510 _WebSafeAsyncForwarder *asyncForwarder;
511 dispatch_once_t asyncForwarderPred;
514 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
517 - (id)asyncForwarder;
521 FindOptions coreOptions(WebFindOptions options)
523 return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
524 | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
525 | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
526 | (options & WebFindOptionsBackwards ? Backwards : 0)
527 | (options & WebFindOptionsWrapAround ? WrapAround : 0)
528 | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
531 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
533 return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
534 | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
535 | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
538 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
540 return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
541 | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
542 | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
545 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
547 switch (visibilityState) {
548 case PageVisibilityStateVisible:
549 return WebPageVisibilityStateVisible;
550 case PageVisibilityStateHidden:
551 return WebPageVisibilityStateHidden;
552 case PageVisibilityStatePrerender:
553 return WebPageVisibilityStatePrerender;
556 ASSERT_NOT_REACHED();
557 return WebPageVisibilityStateVisible;
560 @interface WebView (WebFileInternal)
562 - (float)_deviceScaleFactor;
565 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
566 - (WebFrame *)_focusedFrame;
567 + (void)_preflightSpellChecker;
568 - (BOOL)_continuousCheckingAllowed;
569 - (NSResponder *)_responderForResponderOperations;
572 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
573 NSString *WebElementFrameKey = @"WebElementFrame";
574 NSString *WebElementImageKey = @"WebElementImage";
575 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
576 NSString *WebElementImageRectKey = @"WebElementImageRect";
577 NSString *WebElementImageURLKey = @"WebElementImageURL";
578 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
579 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
580 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
581 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
582 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
583 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
584 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
585 NSString *WebElementTitleKey = @"WebElementTitle";
586 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
587 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
588 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
590 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
591 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
593 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
595 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
596 NSString * const WebViewProgressBackgroundColorKey = @"WebProgressBackgroundColorKey";
599 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
600 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
601 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
602 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
603 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
605 enum { WebViewVersion = 4 };
607 #define timedLayoutSize 4096
609 static NSMutableSet *schemesWithRepresentationsSet;
610 static WebCore::ResourceLoadStatisticsStore* resourceLoadStatisticsStore;
613 NSString *_WebCanGoBackKey = @"canGoBack";
614 NSString *_WebCanGoForwardKey = @"canGoForward";
615 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
616 NSString *_WebIsLoadingKey = @"isLoading";
617 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
618 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
619 NSString *_WebMainFrameURLKey = @"mainFrameURL";
620 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
624 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
625 NSString *WebQuickLookUTIKey = @"WebQuickLookUTIKey";
628 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
629 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
631 #if ENABLE(REMOTE_INSPECTOR)
632 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
633 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
636 @interface WebProgressItem : NSObject
639 long long bytesReceived;
640 long long estimatedLength;
644 @implementation WebProgressItem
647 static BOOL continuousSpellCheckingEnabled;
649 static BOOL grammarCheckingEnabled;
650 static BOOL automaticQuoteSubstitutionEnabled;
651 static BOOL automaticLinkDetectionEnabled;
652 static BOOL automaticDashSubstitutionEnabled;
653 static BOOL automaticTextReplacementEnabled;
654 static BOOL automaticSpellingCorrectionEnabled;
657 @implementation WebView (AllWebViews)
659 static CFSetCallBacks NonRetainingSetCallbacks = {
668 static CFMutableSetRef allWebViewsSet;
670 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
675 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
678 - (void)_removeFromAllWebViewsSet
681 CFSetRemoveValue(allWebViewsSet, self);
684 - (void)_addToAllWebViewsSet
687 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
689 CFSetSetValue(allWebViewsSet, self);
694 @implementation WebView (WebPrivate)
696 static String webKitBundleVersionString()
698 return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
701 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
703 return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
707 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
709 [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
712 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
714 [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
716 #endif // PLATFORM(IOS)
718 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
720 if (!exception || !context)
723 JSC::ExecState* execState = toJS(context);
724 JSLockHolder lock(execState);
726 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
727 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
730 reportException(execState, toJS(execState, exception));
733 static void WebKitInitializeApplicationCachePathIfNecessary()
735 static BOOL initialized = NO;
739 NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
741 appName = [[NSProcessInfo processInfo] processName];
743 if (WebCore::IOSApplication::isMobileSafari() || WebCore::IOSApplication::isWebApp())
744 appName = @"com.apple.WebAppCache";
749 NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
751 webApplicationCacheStorage().setCacheDirectory(cacheDir);
756 static void WebKitInitializeApplicationStatisticsStoragePathIfNecessary()
758 static BOOL initialized = NO;
762 resourceLoadStatisticsStore = &WebCore::ResourceLoadStatisticsStore::create().leakRef();
763 ResourceLoadObserver::sharedObserver().setStatisticsStore(*resourceLoadStatisticsStore);
768 static bool shouldEnableLoadDeferring()
773 return !MacApplication::isAdobeInstaller();
777 static bool shouldRestrictWindowFocus()
782 return !MacApplication::isHRBlock();
786 - (void)_dispatchPendingLoadRequests
788 webResourceLoadScheduler().servePendingRequests();
792 - (void)_registerDraggedTypes
794 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
795 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
796 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
797 [types addObjectsFromArray:URLTypes];
798 [self registerForDraggedTypes:[types allObjects]];
802 static bool needsOutlookQuirksScript()
804 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
805 && MacApplication::isMicrosoftOutlook();
806 return isOutlookNeedingQuirksScript;
809 static NSString *leakOutlookQuirksUserScriptContents()
811 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
812 NSStringEncoding encoding;
813 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
816 -(void)_injectOutlookQuirksScript
818 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
819 _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
824 static bool shouldRespectPriorityInCSSAttributeSetters()
827 static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
828 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
829 return isStanzaNeedingAttributeSetterQuirk;
831 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
832 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
833 return isIAdProducerNeedingAttributeSetterQuirk;
838 static bool shouldTransformsAffectOverflow()
840 static bool shouldTransformsAffectOverflow = !IOSApplication::isOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
841 return shouldTransformsAffectOverflow;
844 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
846 static bool shouldDispatchJavaScriptWindowOnErrorEvents = !IOSApplication::isFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
847 return shouldDispatchJavaScriptWindowOnErrorEvents;
850 static bool isInternalInstall()
852 static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
856 static bool didOneTimeInitialization = false;
859 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
862 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
864 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
865 && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
867 return shouldUseLegacyBackgroundSizeShorthandBehavior;
870 static bool shouldAllowDisplayAndRunningOfInsecureContent()
872 static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
873 return shouldAllowDisplayAndRunningOfInsecureContent;
876 static bool shouldAllowPictureInPictureMediaPlayback()
879 static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
880 return shouldAllowPictureInPictureMediaPlayback;
887 static void WebKitInitializeGamepadProviderIfNecessary()
889 static bool initialized = false;
893 GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
898 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
900 WebCoreThreadViolationCheckRoundTwo();
903 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
906 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
907 [standardPreferences willAddToWebView];
909 _private->preferences = [standardPreferences retain];
910 _private->mainFrameDocumentReady = NO;
911 _private->drawsBackground = YES;
913 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
915 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
917 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
920 _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
923 NSRect f = [self frame];
924 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
925 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
926 [self addSubview:frameView];
930 if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
931 RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
932 _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
933 [recognizer setDelegate:_private->immediateActionController];
934 [recognizer setDelaysPrimaryMouseButtonEvents:NO];
938 [self updateWebViewAdditions];
941 static bool didOneTimeInitialization = false;
943 if (!didOneTimeInitialization) {
945 WebKitInitializeLoggingChannelsIfNecessary();
946 WebCore::initializeLoggingChannelsIfNecessary();
947 #endif // !LOG_DISABLED
949 // Initialize our platform strategies first before invoking the rest
950 // of the initialization code which may depend on the strategies.
951 WebPlatformStrategies::initializeIfNecessary();
954 // Set the WebSQLiteDatabaseTrackerClient.
955 SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
957 if ([standardPreferences databasesEnabled])
959 [WebDatabaseManager sharedWebDatabaseManager];
962 if ([standardPreferences storageTrackerEnabled])
964 WebKitInitializeStorageIfNecessary();
965 WebKitInitializeApplicationCachePathIfNecessary();
966 WebKitInitializeApplicationStatisticsStoragePathIfNecessary();
968 WebKitInitializeGamepadProviderIfNecessary();
971 Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
974 if (IOSApplication::isMobileSafari())
975 Settings::setShouldManageAudioSessionCategory(true);
978 didOneTimeInitialization = true;
981 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
982 _private->group->addWebView(self);
984 PageConfiguration pageConfiguration;
986 pageConfiguration.chromeClient = new WebChromeClient(self);
987 pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
988 #if ENABLE(DRAG_SUPPORT)
989 pageConfiguration.dragClient = new WebDragClient(self);
991 pageConfiguration.inspectorClient = new WebInspectorClient(self);
993 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
994 pageConfiguration.inspectorClient = new WebInspectorClient(self);
997 #if USE(APPLE_INTERNAL_SDK)
998 #import <WebKitAdditions/WebViewInitialization.mm>
1001 pageConfiguration.editorClient = new WebEditorClient(self);
1002 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1003 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1004 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1005 pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1006 pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1007 pageConfiguration.userContentProvider = &_private->group->userContentController();
1008 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1009 _private->page = new Page(pageConfiguration);
1011 _private->page->setGroupName(groupName);
1013 #if ENABLE(GEOLOCATION)
1014 WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
1016 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
1017 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1019 #if ENABLE(DEVICE_ORIENTATION)
1021 WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1024 #if ENABLE(MEDIA_STREAM)
1025 WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1028 #if ENABLE(REMOTE_INSPECTOR)
1029 _private->page->setRemoteInspectionAllowed(true);
1032 _private->page->setCanStartMedia([self window]);
1033 _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1034 _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1037 if (needsOutlookQuirksScript()) {
1038 _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1039 [self _injectOutlookQuirksScript];
1044 // Preserve the behavior we had before <rdar://problem/7580867>
1045 // by enforcing a 5MB limit for session storage.
1046 _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1048 [self _updateScreenScaleFromWindow];
1049 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1050 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1051 _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1054 if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1055 [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1057 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1060 NSRunLoop *runLoop = WebThreadNSRunLoop();
1062 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1065 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1066 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1068 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1070 [self _addToAllWebViewsSet];
1072 // If there's already a next key view (e.g., from a nib), wire it up to our
1073 // contained frame view. In any case, wire our next key view up to the our
1074 // contained frame view. This works together with our becomeFirstResponder
1075 // and setNextKeyView overrides.
1076 NSView *nextKeyView = [self nextKeyView];
1077 if (nextKeyView && nextKeyView != frameView)
1078 [frameView setNextKeyView:nextKeyView];
1079 [super setNextKeyView:frameView];
1081 if ([[self class] shouldIncludeInWebKitStatistics])
1085 [self _registerDraggedTypes];
1088 [self _setIsVisible:[self _isViewVisible]];
1090 WebPreferences *prefs = [self preferences];
1091 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1092 name:WebPreferencesChangedInternalNotification object:prefs];
1095 [self _preferencesChanged:[self preferences]];
1096 [[self preferences] _postPreferencesChangedAPINotification];
1098 // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1099 // and prefs need to be changed synchronously <rdar://problem/5841558>
1100 [self _preferencesChanged:prefs];
1101 _private->page->settings().setFontFallbackPrefersPictographs(true);
1104 if (![[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitSuppressMemoryPressureHandler"])
1105 MemoryPressureHandler::singleton().install();
1107 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1108 // Originally, we allowed all local loads.
1109 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1110 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1111 // Later, we allowed local loads for local URLs and documents loaded
1112 // with substitute data.
1113 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1117 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1118 ResourceHandle::forceContentSniffing();
1120 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1123 _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1126 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1128 self = [super initWithFrame:f];
1132 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1133 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1134 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1135 // need for Safari to unset it to prevent it from being passed to applications it launches.
1136 // Unsetting it when a WebView is first created is as good a place as any.
1137 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1138 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1139 unsetenv("DYLD_FRAMEWORK_PATH");
1140 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1144 _private = [[WebViewPrivate alloc] init];
1145 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1146 [self setMaintainsBackForwardList: YES];
1150 - (void)_viewWillDrawInternal
1152 Frame* frame = [self _mainCoreFrame];
1153 if (frame && frame->view())
1154 frame->view()->updateLayoutAndStyleIfNeededRecursive();
1157 + (NSArray *)_supportedMIMETypes
1159 // Load the plug-in DB allowing plug-ins to install types.
1160 [WebPluginDatabase sharedDatabase];
1161 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1165 + (NSArray *)_supportedFileExtensions
1167 NSMutableSet *extensions = [[NSMutableSet alloc] init];
1168 NSArray *MIMETypes = [self _supportedMIMETypes];
1169 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1171 while ((MIMEType = [enumerator nextObject]) != nil) {
1172 NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1173 if (extensionsForType) {
1174 [extensions addObjectsFromArray:extensionsForType];
1177 NSArray *uniqueExtensions = [extensions allObjects];
1178 [extensions release];
1179 return uniqueExtensions;
1184 + (void)enableWebThread
1186 static BOOL isWebThreadEnabled = NO;
1187 if (!isWebThreadEnabled) {
1188 WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1189 WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1190 WebCoreObjCDeallocOnWebThread([WebFrame class]);
1191 WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1192 WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1193 WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1194 WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1195 WebCoreObjCDeallocOnWebThread([WebView class]);
1196 WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1197 if (IOSApplication::isTheEconomistOnIphone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1198 WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1200 isWebThreadEnabled = YES;
1204 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1206 self = [super initWithFrame:frame];
1210 _private = [[WebViewPrivate alloc] init];
1213 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1217 preferences = [WebPreferences standardPreferences];
1218 [preferences willAddToWebView];
1220 _private->preferences = [preferences retain];
1221 _private->mainFrameDocumentReady = NO;
1222 _private->drawsBackground = YES;
1223 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1225 WebFrameView *frameView = nil;
1226 frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1227 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1228 [self addSubview:frameView];
1229 [frameView release];
1231 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1232 _private->group->addWebView(self);
1234 PageConfiguration pageConfiguration;
1235 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1236 #if ENABLE(DRAG_SUPPORT)
1237 pageConfiguration.dragClient = new WebDragClient(self);
1240 #if USE(APPLE_INTERNAL_SDK)
1241 #import <WebKitAdditions/WebViewInitialization.mm>
1244 pageConfiguration.editorClient = new WebEditorClient(self);
1245 pageConfiguration.inspectorClient = new WebInspectorClient(self);
1246 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1247 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1248 pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1249 pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1250 pageConfiguration.userContentProvider = &_private->group->userContentController();
1251 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1253 _private->page = new Page(pageConfiguration);
1255 [self setSmartInsertDeleteEnabled:YES];
1257 // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1258 // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1259 // This matches how UIKit sets up the preferences. We need to set default values for fonts though, <rdar://problem/6850611>.
1260 // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1261 _private->page->settings().setMinimumLogicalFontSize(9);
1262 _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1263 _private->page->settings().setDefaultFixedFontSize(13);
1264 _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1265 _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1266 _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1268 _private->page->settings().setFontFallbackPrefersPictographs(true);
1269 _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1271 // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1272 _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1274 // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1275 _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1277 // This is a workaround for <rdar://problem/21309911>.
1278 _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1280 _private->page->setGroupName(groupName);
1282 #if ENABLE(REMOTE_INSPECTOR)
1283 _private->page->setRemoteInspectionAllowed(isInternalInstall());
1286 [self _updateScreenScaleFromWindow];
1287 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1288 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1290 [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1292 [self _addToAllWebViewsSet];
1296 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1301 + (void)_handleMemoryWarning
1303 ASSERT(WebThreadIsCurrent());
1304 WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1306 // Always peform the following.
1307 [WebView purgeInactiveFontData];
1309 // Only perform the remaining if a non-simple document was created.
1310 if (!didOneTimeInitialization)
1313 tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1315 [WebStorageManager closeIdleLocalStorageDatabases];
1316 StorageThread::releaseFastMallocFreeMemoryInAllThreads();
1318 [WebView _releaseMemoryNow];
1321 + (void)registerForMemoryNotifications
1323 BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::IOSApplication::isMobileSafari();
1325 MemoryPressureHandler::singleton().installMemoryReleaseBlock(^{
1326 [WebView _handleMemoryWarning];
1327 }, shouldAutoClearPressureOnMemoryRelease);
1329 static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, DISPATCH_MEMORYPRESSURE_WARN, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1330 dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1331 // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1332 MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1335 dispatch_resume(memoryNotificationEventSource);
1337 if (!shouldAutoClearPressureOnMemoryRelease) {
1338 // Listen to memory status notification to reset the memory pressure flag.
1339 static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE,
1341 DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_NORMAL,
1342 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1343 dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1344 unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1345 if (currentStatus == DISPATCH_MEMORYPRESSURE_NORMAL)
1346 MemoryPressureHandler::singleton().clearMemoryPressure();
1347 else if (currentStatus == DISPATCH_MEMORYPRESSURE_WARN)
1348 MemoryPressureHandler::singleton().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1351 dispatch_resume(memoryStatusEventSource);
1355 + (void)_releaseMemoryNow
1357 ASSERT(WebThreadIsCurrent());
1358 [WebView discardAllCompiledCode];
1359 [WebView garbageCollectNow];
1360 [WebView purgeInactiveFontData];
1361 [WebView drainLayerPool];
1362 [WebCache emptyInMemoryResources];
1363 [WebView releaseFastMallocMemoryOnCurrentThread];
1365 dispatch_async(dispatch_get_main_queue(), ^{
1366 // Clear the main thread's TCMalloc thread cache.
1367 [WebView releaseFastMallocMemoryOnCurrentThread];
1371 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1373 Frame* frame = [self _mainCoreFrame];
1375 frame->loader().history().replaceCurrentItem(core(item));
1378 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1381 [WebView _releaseMemoryNow];
1382 dispatch_async(dispatch_get_main_queue(), handler);
1386 + (void)releaseFastMallocMemoryOnCurrentThread
1388 WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1389 WTF::releaseFastMallocFreeMemory();
1392 + (void)garbageCollectNow
1394 ASSERT(WebThreadIsCurrent());
1395 WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1396 GCController::singleton().garbageCollectNow();
1399 + (void)purgeInactiveFontData
1401 ASSERT(WebThreadIsCurrent());
1402 WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1403 FontCache::singleton().purgeInactiveFontData();
1406 + (void)drainLayerPool
1408 ASSERT(WebThreadIsCurrent());
1409 WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1410 WebCore::LegacyTileCache::drainLayerPool();
1413 + (void)discardAllCompiledCode
1415 ASSERT(WebThreadIsCurrent());
1416 WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1417 GCController::singleton().deleteAllCode();
1420 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1422 return WebCore::isCharacterSmartReplaceExempt(character, b);
1425 - (void)updateLayoutIgnorePendingStyleSheets
1428 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1429 Document *document = frame->document();
1431 document->updateLayoutIgnorePendingStylesheets();
1435 #endif // PLATFORM(IOS)
1437 static NSMutableSet *knownPluginMIMETypes()
1439 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1444 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1446 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1447 [knownPluginMIMETypes() addObject:MIMEType];
1450 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1452 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1453 [knownPluginMIMETypes() removeObject:MIMEType];
1456 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1458 MIMEType = [MIMEType lowercaseString];
1459 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1460 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1463 #define WebPDFView ([WebView _getPDFViewClass])
1465 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1469 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1472 // Load the plug-in DB allowing plug-ins to install types.
1473 [WebPluginDatabase sharedDatabase];
1476 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1477 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1478 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1481 if (viewClass && repClass) {
1482 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1483 // Special-case WebHTMLView for text types that shouldn't be shown.
1484 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1487 // If the MIME type is a known plug-in we might not want to load it.
1488 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1489 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1490 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1492 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1493 if (!isSupportedByWebKit)
1498 *vClass = viewClass;
1507 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1509 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1512 if (_private->pluginDatabase) {
1513 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1514 if (pluginPackage) {
1516 *vClass = [WebHTMLView class];
1518 *rClass = [WebHTMLRepresentation class];
1526 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1528 FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
1531 + (BOOL)canCloseAllWebViews
1533 return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1536 + (void)closeAllWebViews
1538 DOMWindow::dispatchAllPendingUnloadEvents();
1540 // This will close the WebViews in a random order. Change this if close order is important.
1541 // Make a new set to avoid mutating the set we are enumerating.
1542 NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet];
1543 NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1544 while (WebView *webView = [enumerator nextObject])
1548 + (BOOL)canShowFile:(NSString *)path
1550 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1554 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1556 return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1562 return !_private || _private->closed;
1566 - (void)_dispatchUnloadEvent
1569 WebFrame *mainFrame = [self mainFrame];
1570 Frame *coreMainFrame = core(mainFrame);
1571 if (coreMainFrame) {
1572 Document *document = coreMainFrame->document();
1574 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1579 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1581 WebFrame *mainFrame = [self mainFrame];
1582 Frame *coreMainFrame = core(mainFrame);
1585 return coreMainFrame->styleAtSelectionStart();
1588 - (NSUInteger)_renderTreeSize
1590 if (!_private->page)
1592 return _private->page->renderTreeSize();
1595 // FIXME: This is incorrectly named, and should be removed <rdar://problem/22242515>.
1596 - (NSSize)_contentsSizeRespectingOverflow
1598 return [[[[self mainFrame] frameView] documentView] bounds].size;
1601 - (void)_dispatchTileDidDraw:(CALayer*)tile
1603 id mailDelegate = [self _webMailDelegate];
1604 if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1605 [mailDelegate _webthread_webView:self tileDidDraw:tile];
1609 if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1614 [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1617 - (void)_willStartScrollingOrZooming
1619 // Pause timers during top level interaction
1620 if (_private->mainViewIsScrollingOrZooming)
1622 _private->mainViewIsScrollingOrZooming = YES;
1624 // This suspends active DOM objects like timers, but not media.
1625 [[self mainFrame] setTimeoutsPaused:YES];
1627 // This defers loading callbacks only.
1628 // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1629 [self setDefersCallbacks:YES];
1632 - (void)_didFinishScrollingOrZooming
1634 if (!_private->mainViewIsScrollingOrZooming)
1636 _private->mainViewIsScrollingOrZooming = NO;
1637 [self setDefersCallbacks:NO];
1638 [[self mainFrame] setTimeoutsPaused:NO];
1639 if (FrameView* view = [self _mainCoreFrame]->view())
1640 view->resumeVisibleImageAnimationsIncludingSubframes();
1643 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1646 webResourceLoadScheduler().suspendPendingRequests();
1648 webResourceLoadScheduler().resumePendingRequests();
1651 + (void)_setAllowCookies:(BOOL)allow
1653 ResourceRequestBase::setDefaultAllowCookies(allow);
1656 + (BOOL)_allowCookies
1658 return ResourceRequestBase::defaultAllowCookies();
1661 + (BOOL)_isUnderMemoryPressure
1663 return MemoryPressureHandler::singleton().isUnderMemoryPressure();
1666 + (void)_clearMemoryPressure
1668 MemoryPressureHandler::singleton().clearMemoryPressure();
1671 + (BOOL)_shouldWaitForMemoryClearMessage
1673 return MemoryPressureHandler::singleton().shouldWaitForMemoryClearMessage();
1675 #endif // PLATFORM(IOS)
1677 - (void)_closePluginDatabases
1679 pluginDatabaseClientCount--;
1681 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1684 // Unload the WebView local plug-in database.
1685 if (_private->pluginDatabase) {
1686 [_private->pluginDatabase destroyAllPluginInstanceViews];
1687 [_private->pluginDatabase close];
1688 [_private->pluginDatabase release];
1689 _private->pluginDatabase = nil;
1693 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1694 if (!pluginDatabaseClientCount && applicationIsTerminating)
1695 [WebPluginDatabase closeSharedDatabase];
1698 - (void)_closeWithFastTeardown
1701 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1705 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1707 [[NSNotificationCenter defaultCenter] removeObserver:self];
1709 [self _closePluginDatabases];
1712 static bool fastDocumentTeardownEnabled()
1715 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1717 static bool initialized = false;
1718 static bool enabled = false;
1720 // This allows debug builds to default to not have fast teardown, so leak checking still works.
1721 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1722 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1724 enabled = ![setting boolValue];
1731 // _close is here only for backward compatibility; clients and subclasses should use
1732 // public method -close instead.
1736 // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1737 // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1739 [self _clearDelegates];
1741 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1745 if (!_private || _private->closed)
1748 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1750 _private->closed = YES;
1751 [self _removeFromAllWebViewsSet];
1754 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1757 // To quit the apps fast we skip document teardown, except plugins
1758 // need to be destroyed and unloaded.
1759 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1760 [self _closeWithFastTeardown];
1764 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1765 [self _exitVideoFullscreen];
1769 _private->closing = YES;
1772 if (Frame* mainFrame = [self _mainCoreFrame])
1773 mainFrame->loader().detachFromParent();
1775 [self setHostWindow:nil];
1778 [self setDownloadDelegate:nil];
1779 [self setEditingDelegate:nil];
1780 [self setFrameLoadDelegate:nil];
1781 [self setPolicyDelegate:nil];
1782 [self setResourceLoadDelegate:nil];
1783 [self setScriptDebugDelegate:nil];
1784 [self setUIDelegate:nil];
1786 [_private->inspector inspectedWebViewClosed];
1789 [_private->immediateActionController webViewClosed];
1793 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1794 [self removeDragCaret];
1797 _private->group->removeWebView(self);
1799 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1800 // all the plug-ins in the page cache to break any retain cycles.
1801 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1802 Page* page = _private->page;
1807 if (_private->hasSpellCheckerDocumentTag) {
1808 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1809 _private->hasSpellCheckerDocumentTag = NO;
1813 if (_private->layerFlushController) {
1814 _private->layerFlushController->invalidate();
1815 _private->layerFlushController = nullptr;
1818 [[self _notificationProvider] unregisterWebView:self];
1821 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1823 [[NSNotificationCenter defaultCenter] removeObserver:self];
1825 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1827 WebPreferences *preferences = _private->preferences;
1828 _private->preferences = nil;
1829 [preferences didRemoveFromWebView];
1830 [preferences release];
1832 [self _closePluginDatabases];
1834 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
1835 if (_private->m_playbackTargetPicker) {
1836 _private->m_playbackTargetPicker->invalidate();
1837 _private->m_playbackTargetPicker = nullptr;
1842 // Need this to make leak messages accurate.
1843 if (applicationIsTerminating) {
1844 GCController::singleton().garbageCollectNow();
1845 [WebCache setDisabled:YES];
1849 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1854 // Indicates if the WebView is in the midst of a user gesture.
1855 - (BOOL)_isProcessingUserGesture
1857 return ScriptController::processingUserGesture();
1860 + (NSString *)_MIMETypeForFile:(NSString *)path
1863 NSString *extension = [path pathExtension];
1865 NSString *MIMEType = nil;
1868 // Get the MIME type from the extension.
1869 if ([extension length] != 0) {
1870 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
1874 // If we can't get a known MIME type from the extension, sniff.
1875 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1876 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1877 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1879 if ([data length] != 0) {
1880 MIMEType = [data _webkit_guessedMIMEType];
1882 if ([MIMEType length] == 0) {
1883 MIMEType = @"application/octet-stream";
1890 - (WebDownload *)_downloadURL:(NSURL *)URL
1894 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1895 WebDownload *download = [WebDownload _downloadWithRequest:request
1896 delegate:_private->downloadDelegate
1903 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1905 NSDictionary *features = [[NSDictionary alloc] init];
1906 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1907 createWebViewWithRequest:nil
1908 windowFeatures:features];
1910 if (!newWindowWebView)
1913 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1914 return newWindowWebView;
1917 - (WebInspector *)inspector
1919 if (!_private->inspector)
1920 _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
1921 return _private->inspector;
1924 #if ENABLE(REMOTE_INSPECTOR)
1925 + (void)_enableRemoteInspector
1927 RemoteInspector::singleton().start();
1930 + (void)_disableRemoteInspector
1932 RemoteInspector::singleton().stop();
1935 + (void)_disableAutoStartRemoteInspector
1937 RemoteInspector::startDisabled();
1940 + (BOOL)_isRemoteInspectorEnabled
1942 return RemoteInspector::singleton().enabled();
1945 + (BOOL)_hasRemoteInspectorSession
1947 return RemoteInspector::singleton().hasActiveDebugSession();
1950 - (BOOL)allowsRemoteInspection
1952 return _private->page->remoteInspectionAllowed();
1955 - (void)setAllowsRemoteInspection:(BOOL)allow
1957 _private->page->setRemoteInspectionAllowed(allow);
1960 - (void)setShowingInspectorIndication:(BOOL)showing
1963 ASSERT(WebThreadIsLocked());
1966 if (!_private->indicateLayer) {
1967 _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1968 [_private->indicateLayer setNeedsLayout];
1969 [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1972 [_private->indicateLayer removeFromSuperlayer];
1973 [_private->indicateLayer release];
1974 _private->indicateLayer = nil;
1977 // Implemented in WebCore::InspectorOverlay.
1982 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
1984 RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
1985 RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
1987 #endif // PLATFORM(IOS)
1988 #endif // ENABLE(REMOTE_INSPECTOR)
1990 - (WebCore::Page*)page
1992 return _private->page;
1996 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1998 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1999 NSArray *menuItems = defaultMenuItems;
2001 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2002 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2003 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2004 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2005 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2010 unsigned count = [menuItems count];
2014 NSMenu *menu = [[NSMenu alloc] init];
2015 for (unsigned i = 0; i < count; i++)
2016 [menu addItem:[menuItems objectAtIndex:i]];
2018 return [menu autorelease];
2022 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2024 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2025 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2026 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2029 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2032 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2034 if (!_private->page)
2037 if (!otherView->_private->page)
2040 // It turns out the right combination of behavior is done with the back/forward load
2041 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
2042 // in the back forward list, and go to the current one.
2044 BackForwardController& backForward = _private->page->backForward();
2045 ASSERT(!backForward.currentItem()); // destination list should be empty
2047 BackForwardController& otherBackForward = otherView->_private->page->backForward();
2048 if (!otherBackForward.currentItem())
2049 return; // empty back forward list, bail
2051 HistoryItem* newItemToGoTo = nullptr;
2053 int lastItemIndex = otherBackForward.forwardCount();
2054 for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2056 // If this item is showing , save away its current scroll and form state,
2057 // since that might have changed since loading and it is normally not saved
2058 // until we leave that page.
2059 otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2061 Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2063 newItemToGoTo = newItem.ptr();
2064 backForward.client()->addItem(WTFMove(newItem));
2067 ASSERT(newItemToGoTo);
2068 _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward);
2071 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2073 _private->formDelegate = delegate;
2075 [_private->formDelegateForwarder clearTarget];
2076 [_private->formDelegateForwarder release];
2077 _private->formDelegateForwarder = nil;
2081 - (id<WebFormDelegate>)_formDelegate
2083 return _private->formDelegate;
2087 - (id)_formDelegateForwarder
2089 if (_private->closing)
2092 if (!_private->formDelegateForwarder)
2093 _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2094 return _private->formDelegateForwarder;
2097 - (id)_formDelegateForSelector:(SEL)selector
2099 id delegate = self->_private->formDelegate;
2100 if ([delegate respondsToSelector:selector])
2103 delegate = [WebDefaultFormDelegate sharedFormDelegate];
2104 if ([delegate respondsToSelector:selector])
2112 - (BOOL)_needsAdobeFrameReloadingQuirk
2114 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2115 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2116 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2117 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2118 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2119 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2120 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2121 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2122 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2123 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2128 - (BOOL)_needsLinkElementTextCSSQuirk
2130 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2131 && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2135 - (BOOL)_needsIsLoadingInAPISenseQuirk
2137 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2142 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2144 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2148 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2150 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);
2154 static bool needsSelfRetainWhileLoadingQuirk()
2156 static bool needsQuirk = MacApplication::isAperture();
2159 #endif // !PLATFORM(IOS)
2161 - (BOOL)_needsPreHTML5ParserQuirks
2164 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2165 // with the new HTML5 parser. If these applications were linked against a
2166 // version of WebKit prior to the introduction of the HTML5 parser, enable
2167 // parser quirks to maintain compatibility. For details, see
2168 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2169 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2170 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2171 && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2173 // Mail.app must continue to display HTML email that contains quirky markup.
2174 static bool isAppleMail = MacApplication::isAppleMail();
2176 return isApplicationNeedingParserQuirks
2178 #if ENABLE(DASHBOARD_SUPPORT)
2179 // Pre-HTML5 parser quirks are required to remain compatible with many
2180 // Dashboard widgets. See <rdar://problem/8175982>.
2181 || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2183 || [[self preferences] usePreHTML5ParserQuirks];
2185 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && IOSApplication::isDaijisenDictionary();
2186 return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2190 - (void)_preferencesChangedNotification:(NSNotification *)notification
2193 // For WebViews that load synchronously, preference changes need to be propagated
2194 // down to WebCore synchronously so that loads in that WebView have the correct
2195 // up-to-date settings.
2196 if (!WebThreadIsLocked())
2198 if ([[self mainFrame] _loadsSynchronously]) {
2201 WebPreferences *preferences = (WebPreferences *)[notification object];
2202 [self _preferencesChanged:preferences];
2207 // It is possible that the prefs object has already changed before the invocation could be called
2208 // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2209 WebPreferences *preferences = (WebPreferences *)[notification object];
2210 if (preferences != [self preferences])
2212 [self _preferencesChanged:preferences];
2218 - (void)_preferencesChanged:(WebPreferences *)preferences
2220 ASSERT(preferences == [self preferences]);
2221 if (!_private->userAgentOverridden)
2222 _private->userAgent = String();
2224 // Cache this value so we don't have to read NSUserDefaults on each page load
2225 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2227 // Update corresponding WebCore Settings object.
2228 if (!_private->page)
2232 // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2233 // didOneTimeInitialization is true so that we don't initialize databases
2234 // until the first WebView has been created. This is because database
2235 // initialization current requires disk access to populate the origins
2236 // quota map and we want to do this lazily by waiting until WebKit is
2237 // used to display web content in a WebView. The possible cases are:
2238 // - on one time initialize (the first WebView creation) if databases are enabled (default)
2239 // - when databases are dynamically enabled later, and they were disabled at startup (this case)
2240 if (didOneTimeInitialization) {
2241 if ([preferences databasesEnabled])
2242 [WebDatabaseManager sharedWebDatabaseManager];
2244 if ([preferences storageTrackerEnabled])
2245 WebKitInitializeStorageIfNecessary();
2249 Settings& settings = _private->page->settings();
2251 settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2252 settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2253 settings.setDefaultFontSize([preferences defaultFontSize]);
2254 settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2255 settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2256 settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2257 settings.setFixedFontFamily([preferences fixedFontFamily]);
2258 settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2259 settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2260 settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2261 settings.setJavaEnabled([preferences isJavaEnabled]);
2262 settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2263 settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2264 settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2265 settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2266 settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2267 settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2268 settings.setMinimumFontSize([preferences minimumFontSize]);
2269 settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2270 settings.setPictographFontFamily([preferences pictographFontFamily]);
2271 settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2272 settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2274 _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2275 settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2276 settings.setSerifFontFamily([preferences serifFontFamily]);
2277 settings.setStandardFontFamily([preferences standardFontFamily]);
2278 settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2279 settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2281 settings.setShouldPrintBackgrounds(true);
2283 settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2285 settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2286 settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2287 settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2288 settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2289 settings.setUsesPageCache([self usesPageCache]);
2290 settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2291 settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2293 settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2294 settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2295 settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2297 settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2298 settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2299 settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2300 settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2301 settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2302 settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2303 settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2304 settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2306 settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2307 settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2308 settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2309 settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2310 settings.setShowDebugBorders([preferences showDebugBorders]);
2311 settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2312 settings.setShowRepaintCounter([preferences showRepaintCounter]);
2313 settings.setWebGLEnabled([preferences webGLEnabled]);
2314 settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2316 settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2317 settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2318 settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2319 settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2320 settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2321 settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2322 settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2323 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2324 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2326 settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2327 settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2328 settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2329 settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2330 settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2332 BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2333 settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2334 settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2335 settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2336 settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2337 settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2338 settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2339 settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2340 settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2341 settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2342 settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2343 settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2344 settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2346 settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2348 settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2349 settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2350 settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2352 settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2354 settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2355 settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2357 settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2358 settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2360 switch ([preferences storageBlockingPolicy]) {
2361 case WebAllowAllStorage:
2362 settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2364 case WebBlockThirdPartyStorage:
2365 settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2367 case WebBlockAllStorage:
2368 settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2372 settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2373 settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2375 settings.setFixedPositionCreatesStackingContext(true);
2377 settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2380 #if ENABLE(RUBBER_BANDING)
2381 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2382 settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2385 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2386 settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2389 settings.setStandalone([preferences _standalone]);
2390 settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2391 settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2392 settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2393 settings.setMaxParseDuration([preferences _maxParseDuration]);
2394 settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2395 settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2396 settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2397 settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2399 settings.setAVKitEnabled([preferences avKitEnabled]);
2401 settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2402 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2404 settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2405 settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2407 ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2408 settings.setDelegatesPageScaling(true);
2410 #if ENABLE(IOS_TEXT_AUTOSIZING)
2411 settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2413 #endif // PLATFORM(IOS)
2416 if ([preferences userStyleSheetEnabled]) {
2417 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2418 if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2419 location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2420 settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2422 settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2424 settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2425 settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2426 settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2427 settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2428 settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2429 settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2430 settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2431 settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2432 settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2433 settings.setQTKitEnabled([preferences isQTKitEnabled]);
2434 #endif // PLATFORM(MAC)
2436 DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2438 #if ENABLE(MEDIA_SOURCE)
2439 settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2442 #if ENABLE(SERVICE_CONTROLS)
2443 settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2444 settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2447 #if ENABLE(VIDEO_TRACK)
2448 settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2449 settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2450 settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2453 #if USE(AVFOUNDATION)
2454 settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2455 settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2458 #if ENABLE(MEDIA_STREAM)
2459 settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2462 #if ENABLE(WEB_AUDIO)
2463 settings.setWebAudioEnabled([preferences webAudioEnabled]);
2466 #if ENABLE(FULLSCREEN_API)
2467 settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2470 settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2472 settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2474 settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2477 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2480 #if ENABLE(INDEXED_DATABASE)
2481 RuntimeEnabledFeatures::sharedFeatures().setWebkitIndexedDBEnabled(true);
2484 #if ENABLE(SHADOW_DOM)
2485 RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2487 #if ENABLE(CUSTOM_ELEMENTS)
2488 RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2492 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2494 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2496 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2497 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2499 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2500 if (_private->zoomsTextOnly != zoomsTextOnly)
2501 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2504 [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2505 [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2506 [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2507 [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2510 #if ENABLE(ENCRYPTED_MEDIA_V2)
2511 settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2514 settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2515 settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2518 static inline IMP getMethod(id o, SEL s)
2520 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2524 - (id)_UIKitDelegateForwarder
2526 if (_private->closing)
2529 if (!_private->UIKitDelegateForwarder)
2530 _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2531 return _private->UIKitDelegateForwarder;
2535 - (void)_cacheResourceLoadDelegateImplementations
2537 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2538 id delegate = _private->resourceProgressDelegate;
2541 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2545 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2546 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2547 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2548 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2549 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2550 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2551 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2555 cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2556 cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2557 cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2558 cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2559 cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2560 cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2561 cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2562 cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2563 cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2566 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2567 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2568 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2569 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2570 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2571 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2572 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2573 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2576 - (void)_cacheFrameLoadDelegateImplementations
2578 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2579 id delegate = _private->frameLoadDelegate;
2582 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2586 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2587 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2588 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2589 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2590 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2591 #if JSC_OBJC_API_ENABLED
2592 cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2594 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2595 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2596 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2597 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2598 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2599 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2600 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2601 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2602 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2603 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2604 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2605 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2606 #if ENABLE(ICONDATABASE)
2607 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2609 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2610 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2611 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2612 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2613 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2614 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2615 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2616 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2617 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2618 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2620 cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2623 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2624 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2625 // for backwards compatibility.
2626 Page* page = core(self);
2628 unsigned milestones = DidFirstLayout;
2630 milestones |= DidFirstVisuallyNonEmptyLayout;
2632 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2633 milestones |= DidFirstVisuallyNonEmptyLayout;
2635 page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2639 - (void)_cacheScriptDebugDelegateImplementations
2641 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2642 id delegate = _private->scriptDebugDelegate;
2645 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2649 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2650 if (cache->didParseSourceFunc)
2651 cache->didParseSourceExpectsBaseLineNumber = YES;
2653 cache->didParseSourceExpectsBaseLineNumber = NO;
2654 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2657 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2659 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2660 if (cache->exceptionWasRaisedFunc)
2661 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2663 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2664 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2668 - (void)_cacheHistoryDelegateImplementations
2670 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2671 id delegate = _private->historyDelegate;
2674 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2678 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2679 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2680 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2681 cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2682 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2683 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2686 - (id)_policyDelegateForwarder
2689 if (_private->closing)
2692 if (!_private->policyDelegateForwarder)
2693 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2694 return _private->policyDelegateForwarder;
2697 - (id)_UIDelegateForwarder
2700 if (_private->closing)
2703 if (!_private->UIDelegateForwarder)
2704 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2705 return _private->UIDelegateForwarder;
2709 - (id)_UIDelegateForSelector:(SEL)selector
2711 id delegate = self->_private->UIDelegate;
2712 if ([delegate respondsToSelector:selector])
2715 delegate = [WebDefaultUIDelegate sharedUIDelegate];
2716 if ([delegate respondsToSelector:selector])
2723 - (id)_editingDelegateForwarder
2726 if (_private->closing)
2729 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2730 // Not sure if that is a bug or not.
2734 if (!_private->editingDelegateForwarder)
2735 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2736 return _private->editingDelegateForwarder;
2739 - (void)_closeWindow
2741 [[self _UIDelegateForwarder] webViewClose:self];
2744 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2746 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2747 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2749 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2750 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2751 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2752 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2755 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2757 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2758 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2760 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2761 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2762 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2763 if ([viewClass class] == [WebHTMLView class])
2764 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2766 // This is used to make _representationExistsForURLScheme faster.
2767 // Without this set, we'd have to create the MIME type each time.
2768 if (schemesWithRepresentationsSet == nil) {
2769 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2771 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2774 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2776 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2779 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2781 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2784 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2786 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2790 if ([NSURLConnection canHandleRequest:request])
2793 NSString *scheme = [[request URL] scheme];
2795 // Representations for URL schemes work at the top level.
2796 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2799 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2802 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2808 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2810 return [self _canHandleRequest:request forMainFrame:YES];
2813 + (NSString *)_decodeData:(NSData *)data
2815 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2816 return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2819 - (void)_pushPerformingProgrammaticFocus
2821 _private->programmaticFocusCount++;
2824 - (void)_popPerformingProgrammaticFocus
2826 _private->programmaticFocusCount--;
2829 - (BOOL)_isPerformingProgrammaticFocus
2831 return _private->programmaticFocusCount != 0;
2835 - (void)_didChangeValueForKey: (NSString *)key
2837 LOG (Bindings, "calling didChangeValueForKey: %@", key);
2838 [self didChangeValueForKey: key];
2841 - (void)_willChangeValueForKey: (NSString *)key
2843 LOG (Bindings, "calling willChangeValueForKey: %@", key);
2844 [self willChangeValueForKey: key];
2847 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2848 static NSSet *manualNotifyKeys = nil;
2849 if (!manualNotifyKeys)
2850 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2851 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2853 if ([manualNotifyKeys containsObject:key])
2858 - (NSArray *)_declaredKeys {
2859 static NSArray *declaredKeys = nil;
2861 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2862 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2863 return declaredKeys;
2866 - (void)setObservationInfo:(void *)info
2868 _private->observationInfo = info;
2871 - (void *)observationInfo
2873 return _private->observationInfo;
2876 - (void)_willChangeBackForwardKeys
2878 [self _willChangeValueForKey: _WebCanGoBackKey];
2879 [self _willChangeValueForKey: _WebCanGoForwardKey];
2882 - (void)_didChangeBackForwardKeys
2884 [self _didChangeValueForKey: _WebCanGoBackKey];
2885 [self _didChangeValueForKey: _WebCanGoForwardKey];
2888 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2890 if (needsSelfRetainWhileLoadingQuirk())
2893 [self _willChangeBackForwardKeys];
2894 if (frame == [self mainFrame]){
2895 // Force an observer update by sending a will/did.
2896 [self _willChangeValueForKey: _WebIsLoadingKey];
2897 [self _didChangeValueForKey: _WebIsLoadingKey];
2899 [self _willChangeValueForKey: _WebMainFrameURLKey];
2902 [NSApp setWindowsNeedUpdate:YES];
2904 #if ENABLE(FULLSCREEN_API)
2905 Document* document = core([frame DOMDocument]);
2906 if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2907 SEL selector = @selector(webView:closeFullScreenWithListener:);
2908 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2909 WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2910 CallUIDelegate(self, selector, listener);
2912 } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2913 [_private->newFullscreenController close];
2919 - (void)_checkDidPerformFirstNavigation
2921 if (_private->_didPerformFirstNavigation)
2924 Page* page = _private->page;
2928 auto& backForwardController = page->backForward();
2930 if (!backForwardController.backItem())
2933 _private->_didPerformFirstNavigation = YES;
2935 if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2936 _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2939 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2941 if (frame == [self mainFrame])
2942 [self _didChangeValueForKey: _WebMainFrameURLKey];
2944 [self _checkDidPerformFirstNavigation];
2946 [NSApp setWindowsNeedUpdate:YES];
2949 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2951 if (needsSelfRetainWhileLoadingQuirk())
2952 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2954 [self _didChangeBackForwardKeys];
2955 if (frame == [self mainFrame]){
2956 // Force an observer update by sending a will/did.
2957 [self _willChangeValueForKey: _WebIsLoadingKey];
2958 [self _didChangeValueForKey: _WebIsLoadingKey];
2960 [NSApp setWindowsNeedUpdate:YES];
2963 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2965 if (needsSelfRetainWhileLoadingQuirk())
2966 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2968 [self _didChangeBackForwardKeys];
2969 if (frame == [self mainFrame]){
2970 // Force an observer update by sending a will/did.
2971 [self _willChangeValueForKey: _WebIsLoadingKey];
2972 [self _didChangeValueForKey: _WebIsLoadingKey];
2974 [NSApp setWindowsNeedUpdate:YES];
2977 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2979 if (needsSelfRetainWhileLoadingQuirk())
2980 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2982 [self _didChangeBackForwardKeys];
2983 if (frame == [self mainFrame]){
2984 // Force an observer update by sending a will/did.
2985 [self _willChangeValueForKey: _WebIsLoadingKey];
2986 [self _didChangeValueForKey: _WebIsLoadingKey];
2988 [self _didChangeValueForKey: _WebMainFrameURLKey];
2990 [NSApp setWindowsNeedUpdate:YES];
2993 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2995 RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2996 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2997 NSCachedURLResponse *cachedResponse;
2999 if (!_private->page)
3002 if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3003 cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3005 cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3007 return cachedResponse;
3010 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3012 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3013 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3014 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3016 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3017 title:[element objectForKey:WebElementImageAltStringKey]
3018 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3023 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3025 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3026 andTitle:[element objectForKey:WebElementLinkLabelKey]
3030 #if ENABLE(DRAG_SUPPORT)
3031 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3033 if (!_private->page)
3035 _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3041 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3043 if (frame == [self mainFrame])
3044 _private->didDrawTiles = 0;
3047 #endif // PLATFORM(IOS)
3049 #if ENABLE(DASHBOARD_SUPPORT)
3051 #define DASHBOARD_CONTROL_LABEL @"control"
3053 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3055 NSRect adjustedBounds = bounds;
3056 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3057 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3058 adjustedBounds.size = bounds.size;
3060 NSRect adjustedClip;
3061 adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3062 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3063 adjustedClip.size = clip.size;
3065 WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds
3066 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3067 NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3068 if (!scrollerRegions) {
3069 scrollerRegions = [[NSMutableArray alloc] init];
3070 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3071 [scrollerRegions release];
3073 [scrollerRegions addObject:region];
3077 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3079 NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3081 for (const auto& widget: frameView->children()) {
3082 if (is<FrameView>(*widget)) {
3083 [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3087 if (!widget->isScrollbar())
3090 // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3091 // it's not common to need this to be correct in Dashboard widgets.
3092 NSRect bounds = widget->frameRect();
3093 [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3097 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3099 // Add scroller regions for NSScroller and WebCore scrollbars
3100 NSUInteger count = [views count];
3101 for (NSUInteger i = 0; i < count; i++) {
3102 NSView *view = [views objectAtIndex:i];
3104 if ([view isKindOfClass:[WebHTMLView class]]) {
3105 if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3106 if (FrameView* coreView = coreFrame->view())
3107 [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3109 } else if ([view isKindOfClass:[NSScroller class]]) {
3110 // AppKit places absent scrollers at -100,-100
3111 if ([view frame].origin.y < 0)
3113 [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3115 [self _addScrollerDashboardRegions:regions from:[view subviews]];
3119 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3121 [self _addScrollerDashboardRegions:regions from:[self subviews]];
3124 - (NSDictionary *)_dashboardRegions
3126 // Only return regions from main frame.
3127 Frame* mainFrame = [self _mainCoreFrame];
3131 const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3132 size_t size = regions.size();
3134 NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3135 for (size_t i = 0; i < size; i++) {
3136 const AnnotatedRegionValue& region = regions[i];
3138 if (region.type == StyleDashboardRegion::None)
3141 NSString *label = region.label;
3142 WebDashboardRegionType type = WebDashboardRegionTypeNone;
3143 if (region.type == StyleDashboardRegion::Circle)
3144 type = WebDashboardRegionTypeCircle;
3145 else if (region.type == StyleDashboardRegion::Rectangle)
3146 type = WebDashboardRegionTypeRectangle;
3147 NSMutableArray *regionValues = [webRegions objectForKey:label];
3148 if (!regionValues) {
3149 regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3150 [webRegions setObject:regionValues forKey:label];
3151 [regionValues release];
3154 WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3155 [regionValues addObject:webRegion];
3156 [webRegion release];
3159 [self _addScrollerDashboardRegions:webRegions];
3164 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3166 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
3167 // specific support for the backward compatibility mode flag.
3168 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3169 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3172 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3173 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3176 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3177 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3180 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3181 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3184 case WebDashboardBehaviorAllowWheelScrolling: {
3185 _private->dashboardBehaviorAllowWheelScrolling = flag;
3188 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3190 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3191 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3192 RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3198 // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3199 // compatibility mode. See <rdar://problem/8175982>.
3201 _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3204 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3207 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3208 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3210 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3211 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3213 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3214 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3216 case WebDashboardBehaviorAllowWheelScrolling: {
3217 return _private->dashboardBehaviorAllowWheelScrolling;
3219 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3220 return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3226 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3228 + (void)_setShouldUseFontSmoothing:(BOOL)f
3230 FontCascade::setShouldUseSmoothing(f);
3233 + (BOOL)_shouldUseFontSmoothing
3235 return FontCascade::shouldUseSmoothing();
3239 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3241 setUsesTestModeFocusRingColor(f);
3244 + (BOOL)_usesTestModeFocusRingColor
3246 return usesTestModeFocusRingColor();
3251 - (void)_setUIKitDelegate:(id)delegate
3253 _private->UIKitDelegate = delegate;
3254 [_private->UIKitDelegateForwarder clearTarget];
3255 [_private->UIKitDelegateForwarder release];
3256 _private->UIKitDelegateForwarder = nil;
3259 - (id)_UIKitDelegate
3261 return _private->UIKitDelegate;
3264 - (void)setWebMailDelegate:(id)delegate
3266 _private->WebMailDelegate = delegate;
3269 - (id)_webMailDelegate
3271 return _private->WebMailDelegate;
3274 - (id <WebCaretChangeListener>)caretChangeListener
3276 return _private->_caretChangeListener;
3279 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3281 _private->_caretChangeListener = listener;
3284 - (NSSet *)caretChangeListeners
3286 return _private->_caretChangeListeners;
3289 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3291 if (_private->_caretChangeListeners == nil) {
3292 _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3295 [_private->_caretChangeListeners addObject:listener];
3298 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3300 [_private->_caretChangeListeners removeObject:listener];
3303 - (void)removeAllCaretChangeListeners
3305 [_private->_caretChangeListeners removeAllObjects];
3308 - (void)caretChanged
3310 [_private->_caretChangeListener caretChanged];
3311 NSSet *copy = [_private->_caretChangeListeners copy];
3312 for (id <WebCaretChangeListener> listener in copy) {
3313 [listener caretChanged];
3318 - (void)_clearDelegates
3320 ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3322 [self _setFormDelegate:nil];
3323 [self _setUIKitDelegate:nil];
3324 [self setCaretChangeListener:nil];
3325 [self removeAllCaretChangeListeners];
3326 [self setWebMailDelegate:nil];
3328 [self setDownloadDelegate:nil];
3329 [self setEditingDelegate:nil];
3330 [self setFrameLoadDelegate:nil];
3331 [self setPolicyDelegate:nil];
3332 [self setResourceLoadDelegate:nil];
3333 [self setScriptDebugDelegate:nil];
3334 [self setUIDelegate:nil];
3337 - (NSURL *)_displayURL
3340 WebFrame *frame = [self mainFrame];
3341 // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3342 WebDataSource *dataSource = [frame provisionalDataSource];
3344 dataSource = [frame dataSource];
3345 NSURL *unreachableURL = [dataSource unreachableURL];
3346 NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3347 [[URL retain] autorelease];
3350 #endif // PLATFORM(IOS)
3353 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3355 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3357 [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3359 [scrollview setVerticalScrollingModeLocked:NO];
3360 [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3364 - (BOOL)alwaysShowVerticalScroller
3366 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3367 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3370 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3372 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3374 [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3376 [scrollview setHorizontalScrollingModeLocked:NO];
3377 [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3381 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3383 if (Frame* mainFrame = [self _mainCoreFrame])
3384 mainFrame->view()->setProhibitsScrolling(prohibits);
3387 - (BOOL)alwaysShowHorizontalScroller
3389 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3390 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3392 #endif // !PLATFORM(IOS)
3394 - (void)_setUseFastImageScalingMode:(BOOL)flag
3396 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3397 _private->page->setInLowQualityImageInterpolationMode(flag);
3398 [self setNeedsDisplay:YES];
3402 - (BOOL)_inFastImageScalingMode
3405 return _private->page->inLowQualityImageInterpolationMode();
3409 - (BOOL)_cookieEnabled
3412 return _private->page->settings().cookieEnabled();
3416 - (void)_setCookieEnabled:(BOOL)enable
3419 _private->page->settings().setCookieEnabled(enable);
3423 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3425 if (!_private->pluginDatabase)
3426 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3428 [_private->pluginDatabase setPlugInPaths:newPaths];
3429 [_private->pluginDatabase refresh];
3434 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3436 // Ask plug-ins in this frame
3437 id <WebDocumentView> documentView = [[frame frameView] documentView];
3438 if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3439 if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3443 // Ask plug-ins in child frames
3444 NSArray *childFrames = [frame childFrames];
3445 unsigned childCount = [childFrames count];
3446 unsigned childIndex;
3447 for (childIndex = 0; childIndex < childCount; childIndex++) {
3448 if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3455 - (BOOL)_pluginsAreRunning
3458 return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3461 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3463 // Send the message to plug-ins in this frame
3464 id <WebDocumentView> documentView = [[frame frameView] documentView];
3465 if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3466 [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3468 // Send the message to plug-ins in child frames
3469 NSArray *childFrames = [frame childFrames];
3470 unsigned childCount = [childFrames count];
3471 unsigned childIndex;
3472 for (childIndex = 0; childIndex < childCount; childIndex++) {
3473 [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3477 - (void)_destroyAllPlugIns
3480 [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3483 - (void)_clearBackForwardCache
3486 WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3487 BackForwardList* bfList = core([self backForwardList]);
3491 BOOL didClearBFCache = bfList->clearAllPageCaches();
3492 if (WebKit::MemoryMeasure::isLoggingEnabled())
3493 NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3497 - (void)_startAllPlugIns
3500 [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3503 - (void)_stopAllPlugIns
3506 [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3509 - (void)_stopAllPlugInsForPageCache
3512 [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3515 - (void)_restorePlugInsFromCache
3518 [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3521 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3525 Frame* mainCoreFrame = [self _mainCoreFrame];
3526 for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3527 FrameView* coreView = frame ? frame->view() : 0;
3531 // Get the GraphicsLayer for this widget.
3532 GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3533 if (!layerForWidget)
3536 if (layerForWidget->contentsLayerForMedia() != layer) {
3537 layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3538 // We need to make sure the layer hierachy change is applied immediately.
3539 if (mainCoreFrame->view())
3540 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3548 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3551 _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3553 #endif // PLATFORM(IOS)
3555 - (void)_attachScriptDebuggerToAllFrames
3557 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3558 [kit(frame) _attachScriptDebugger];
3561 - (void)_detachScriptDebuggerFromAllFrames
3563 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3564 [kit(frame) _detachScriptDebugger];
3568 - (void)setBackgroundColor:(NSColor *)backgroundColor
3570 if ([_private->backgroundColor isEqual:backgroundColor])
3573 id old = _private->backgroundColor;
3574 _private->backgroundColor = [backgroundColor retain];
3577 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3580 - (NSColor *)backgroundColor
3582 return _private->backgroundColor;
3585 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3587 if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3590 CFTypeRef old = _private->backgroundColor;
3591 CFRetain(backgroundColor);
3592 _private->backgroundColor = backgroundColor;
3595 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3598 - (CGColorRef)backgroundColor
3600 return _private->backgroundColor;
3604 - (BOOL)defersCallbacks
3606 if (!_private->page)
3608 return _private->page->defersLoading();
3611 - (void)setDefersCallbacks:(BOOL)defer
3613 if (!_private->page)
3615 return _private->page->setDefersLoading(defer);