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 "DictionaryPopupInfo.h"
39 #import "WebAlternativeTextClient.h"
40 #import "WebApplicationCache.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 "WebDefaultEditingDelegate.h"
49 #import "WebDefaultPolicyDelegate.h"
50 #import "WebDefaultUIDelegate.h"
51 #import "WebDelegateImplementationCaching.h"
52 #import "WebDeviceOrientationClient.h"
53 #import "WebDeviceOrientationProvider.h"
54 #import "WebDocument.h"
55 #import "WebDocumentInternal.h"
56 #import "WebDownload.h"
57 #import "WebDownloadInternal.h"
58 #import "WebDragClient.h"
59 #import "WebDynamicScrollBarsViewInternal.h"
60 #import "WebEditingDelegate.h"
61 #import "WebEditorClient.h"
62 #import "WebFormDelegatePrivate.h"
63 #import "WebFrameInternal.h"
64 #import "WebFrameLoaderClient.h"
65 #import "WebFrameNetworkingContext.h"
66 #import "WebFrameViewInternal.h"
67 #import "WebGeolocationClient.h"
68 #import "WebGeolocationPositionInternal.h"
69 #import "WebHTMLRepresentation.h"
70 #import "WebHTMLViewInternal.h"
71 #import "WebHistoryItemInternal.h"
72 #import "WebIconDatabaseInternal.h"
73 #import "WebInspector.h"
74 #import "WebInspectorClient.h"
75 #import "WebKitErrors.h"
76 #import "WebKitFullScreenListener.h"
77 #import "WebKitLogging.h"
78 #import "WebKitNSStringExtras.h"
79 #import "WebKitStatisticsPrivate.h"
80 #import "WebKitSystemBits.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 "WebPanelAuthenticationHandler.h"
93 #import "WebPlatformStrategies.h"
94 #import "WebPluginDatabase.h"
95 #import "WebPolicyDelegate.h"
96 #import "WebPreferenceKeysPrivate.h"
97 #import "WebPreferencesPrivate.h"
98 #import "WebProgressTrackerClient.h"
99 #import "WebScriptDebugDelegate.h"
100 #import "WebScriptWorldInternal.h"
101 #import "WebSelectionServiceController.h"
102 #import "WebStorageManagerInternal.h"
103 #import "WebSystemInterface.h"
104 #import "WebTextCompletionController.h"
105 #import "WebTextIterator.h"
106 #import "WebUIDelegate.h"
107 #import "WebUIDelegatePrivate.h"
108 #import "WebUserMediaClient.h"
109 #import "WebViewGroup.h"
110 #import "WebVisitedLinkStore.h"
111 #import <CoreFoundation/CFSet.h>
112 #import <Foundation/NSURLConnection.h>
113 #import <JavaScriptCore/APICast.h>
114 #import <JavaScriptCore/JSValueRef.h>
115 #import <WebCore/AlternativeTextUIController.h>
116 #import <WebCore/AnimationController.h>
117 #import <WebCore/ApplicationCacheStorage.h>
118 #import <WebCore/BackForwardController.h>
119 #import <WebCore/BackForwardList.h>
120 #import <WebCore/CFNetworkSPI.h>
121 #import <WebCore/Chrome.h>
122 #import <WebCore/ColorMac.h>
123 #import <WebCore/Cursor.h>
124 #import <WebCore/DatabaseManager.h>
125 #import <WebCore/Document.h>
126 #import <WebCore/DocumentLoader.h>
127 #import <WebCore/DragController.h>
128 #import <WebCore/DragData.h>
129 #import <WebCore/Editor.h>
130 #import <WebCore/EventHandler.h>
131 #import <WebCore/ExceptionHandlers.h>
132 #import <WebCore/FocusController.h>
133 #import <WebCore/FrameLoader.h>
134 #import <WebCore/FrameSelection.h>
135 #import <WebCore/FrameTree.h>
136 #import <WebCore/FrameView.h>
137 #import <WebCore/GCController.h>
138 #import <WebCore/GeolocationController.h>
139 #import <WebCore/GeolocationError.h>
140 #import <WebCore/HTMLNames.h>
141 #import <WebCore/HTMLVideoElement.h>
142 #import <WebCore/HistoryController.h>
143 #import <WebCore/HistoryItem.h>
144 #import <WebCore/IconDatabase.h>
145 #import <WebCore/JSCSSStyleDeclaration.h>
146 #import <WebCore/JSDocument.h>
147 #import <WebCore/JSElement.h>
148 #import <WebCore/JSNodeList.h>
149 #import <WebCore/JSNotification.h>
150 #import <WebCore/Logging.h>
151 #import <WebCore/MIMETypeRegistry.h>
152 #import <WebCore/MainFrame.h>
153 #import <WebCore/MemoryCache.h>
154 #import <WebCore/MemoryPressureHandler.h>
155 #import <WebCore/NSURLFileTypeMappingsSPI.h>
156 #import <WebCore/NodeList.h>
157 #import <WebCore/Notification.h>
158 #import <WebCore/NotificationController.h>
159 #import <WebCore/Page.h>
160 #import <WebCore/PageCache.h>
161 #import <WebCore/PageConfiguration.h>
162 #import <WebCore/PageGroup.h>
163 #import <WebCore/PlatformEventFactoryMac.h>
164 #import <WebCore/ProgressTracker.h>
165 #import <WebCore/RenderView.h>
166 #import <WebCore/RenderWidget.h>
167 #import <WebCore/ResourceHandle.h>
168 #import <WebCore/ResourceLoadScheduler.h>
169 #import <WebCore/ResourceRequest.h>
170 #import <WebCore/RuntimeApplicationChecks.h>
171 #import <WebCore/RuntimeEnabledFeatures.h>
172 #import <WebCore/SchemeRegistry.h>
173 #import <WebCore/ScriptController.h>
174 #import <WebCore/SecurityOrigin.h>
175 #import <WebCore/SecurityPolicy.h>
176 #import <WebCore/Settings.h>
177 #import <WebCore/StyleProperties.h>
178 #import <WebCore/TextResourceDecoder.h>
179 #import <WebCore/ThreadCheck.h>
180 #import <WebCore/UserAgent.h>
181 #import <WebCore/UserContentController.h>
182 #import <WebCore/WebCoreObjCExtras.h>
183 #import <WebCore/WebCoreView.h>
184 #import <WebCore/Widget.h>
185 #import <WebKitLegacy/DOM.h>
186 #import <WebKitLegacy/DOMExtensions.h>
187 #import <WebKitLegacy/DOMPrivate.h>
188 #import <WebKitSystemInterface.h>
189 #import <bindings/ScriptValue.h>
190 #import <mach-o/dyld.h>
191 #import <objc/objc-auto.h>
192 #import <objc/runtime.h>
193 #import <runtime/ArrayPrototype.h>
194 #import <runtime/DateInstance.h>
195 #import <runtime/InitializeThreading.h>
196 #import <runtime/JSCJSValue.h>
197 #import <runtime/JSLock.h>
198 #import <wtf/Assertions.h>
199 #import <wtf/HashTraits.h>
200 #import <wtf/MainThread.h>
201 #import <wtf/ObjcRuntimeExtras.h>
202 #import <wtf/RefCountedLeakCounter.h>
203 #import <wtf/RefPtr.h>
204 #import <wtf/RunLoop.h>
205 #import <wtf/StdLibExtras.h>
208 #import "WebActionMenuController.h"
209 #import "WebContextMenuClient.h"
210 #import "WebFullScreenController.h"
211 #import "WebNSEventExtras.h"
212 #import "WebNSObjectExtras.h"
213 #import "WebNSPasteboardExtras.h"
214 #import "WebNSPrintOperationExtras.h"
215 #import "WebPDFView.h"
216 #import <WebCore/LookupSPI.h>
217 #import <WebCore/NSViewSPI.h>
218 #import <WebCore/SoftLinking.h>
219 #import <WebCore/TextIndicator.h>
220 #import <WebCore/TextIndicatorWindow.h>
221 #import <WebCore/WebVideoFullscreenController.h>
223 #import "MemoryMeasure.h"
224 #import "WebCaretChangeListener.h"
225 #import "WebChromeClientIOS.h"
226 #import "WebDefaultFormDelegate.h"
227 #import "WebDefaultFrameLoadDelegate.h"
228 #import "WebDefaultResourceLoadDelegate.h"
229 #import "WebDefaultUIKitDelegate.h"
230 #import "WebFixedPositionContent.h"
231 #import "WebMailDelegate.h"
232 #import "WebNSUserDefaultsExtras.h"
233 #import "WebPDFViewIOS.h"
234 #import "WebPlainWhiteView.h"
235 #import "WebPluginController.h"
236 #import "WebPolicyDelegatePrivate.h"
237 #import "WebSQLiteDatabaseTrackerClient.h"
238 #import "WebStorageManagerPrivate.h"
239 #import "WebUIKitSupport.h"
240 #import "WebVisiblePosition.h"
241 #import <WebCore/DispatchSPI.h>
242 #import <WebCore/EventNames.h>
243 #import <WebCore/FontCache.h>
244 #import <WebCore/GraphicsLayer.h>
245 #import <WebCore/IconController.h>
246 #import <WebCore/LegacyTileCache.h>
247 #import <WebCore/MobileGestaltSPI.h>
248 #import <WebCore/NetworkStateNotifier.h>
249 #import <WebCore/RuntimeApplicationChecksIOS.h>
250 #import <WebCore/SQLiteDatabaseTracker.h>
251 #import <WebCore/SmartReplace.h>
252 #import <WebCore/TextRun.h>
253 #import <WebCore/TileControllerMemoryHandlerIOS.h>
254 #import <WebCore/WAKWindow.h>
255 #import <WebCore/WKView.h>
256 #import <WebCore/WebCoreThread.h>
257 #import <WebCore/WebCoreThreadMessage.h>
258 #import <WebCore/WebCoreThreadRun.h>
259 #import <WebCore/WebEvent.h>
260 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
261 #import <wtf/FastMalloc.h>
262 #endif // !PLATFORM(IOS)
264 #if ENABLE(DASHBOARD_SUPPORT)
265 #import <WebKitLegacy/WebDashboardRegion.h>
268 #if ENABLE(REMOTE_INSPECTOR)
269 #import <JavaScriptCore/RemoteInspector.h>
271 #import "WebIndicateLayer.h"
280 #include <WebCore/QuickLook.h>
283 #if ENABLE(IOS_TOUCH_EVENTS)
284 #import <WebCore/WebEventRegion.h>
288 #import <WebCore/HIDGamepadProvider.h>
292 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
293 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUTermOptionDisableSearchTermIndicator, NSString *)
297 @interface NSSpellChecker (WebNSSpellCheckerDetails)
298 - (void)_preflightChosenSpellServer;
301 @interface NSView (WebNSViewDetails)
302 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
303 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
304 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
305 - (void)_windowChangedKeyState;
308 @interface NSWindow (WebNSWindowDetails)
309 - (id)_oldFirstResponderBeforeBecoming;
310 - (void)_enableScreenUpdatesIfNeeded;
311 - (BOOL)_wrapsCarbonWindow;
312 - (BOOL)_hasKeyAppearance;
317 using namespace Inspector;
318 using namespace WebCore;
320 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
322 macro(alignJustified) \
325 macro(capitalizeWord) \
326 macro(centerSelectionInVisibleArea) \
327 macro(changeAttributes) \
328 macro(changeBaseWritingDirection) \
329 macro(changeBaseWritingDirectionToLTR) \
330 macro(changeBaseWritingDirectionToRTL) \
332 macro(changeDocumentBackgroundColor) \
334 macro(changeSpelling) \
335 macro(checkSpelling) \
341 macro(deleteBackward) \
342 macro(deleteBackwardByDecomposingPreviousCharacter) \
343 macro(deleteForward) \
344 macro(deleteToBeginningOfLine) \
345 macro(deleteToBeginningOfParagraph) \
346 macro(deleteToEndOfLine) \
347 macro(deleteToEndOfParagraph) \
348 macro(deleteToMark) \
349 macro(deleteWordBackward) \
350 macro(deleteWordForward) \
351 macro(ignoreSpelling) \
353 macro(insertBacktab) \
354 macro(insertLineBreak) \
355 macro(insertNewline) \
356 macro(insertNewlineIgnoringFieldEditor) \
357 macro(insertParagraphSeparator) \
359 macro(insertTabIgnoringFieldEditor) \
360 macro(lowercaseWord) \
361 macro(makeBaseWritingDirectionLeftToRight) \
362 macro(makeBaseWritingDirectionRightToLeft) \
363 macro(makeTextWritingDirectionLeftToRight) \
364 macro(makeTextWritingDirectionNatural) \
365 macro(makeTextWritingDirectionRightToLeft) \
366 macro(moveBackward) \
367 macro(moveBackwardAndModifySelection) \
369 macro(moveDownAndModifySelection) \
371 macro(moveForwardAndModifySelection) \
373 macro(moveLeftAndModifySelection) \
374 macro(moveParagraphBackwardAndModifySelection) \
375 macro(moveParagraphForwardAndModifySelection) \
377 macro(moveRightAndModifySelection) \
378 macro(moveToBeginningOfDocument) \
379 macro(moveToBeginningOfDocumentAndModifySelection) \
380 macro(moveToBeginningOfLine) \
381 macro(moveToBeginningOfLineAndModifySelection) \
382 macro(moveToBeginningOfParagraph) \
383 macro(moveToBeginningOfParagraphAndModifySelection) \
384 macro(moveToBeginningOfSentence) \
385 macro(moveToBeginningOfSentenceAndModifySelection) \
386 macro(moveToEndOfDocument) \
387 macro(moveToEndOfDocumentAndModifySelection) \
388 macro(moveToEndOfLine) \
389 macro(moveToEndOfLineAndModifySelection) \
390 macro(moveToEndOfParagraph) \
391 macro(moveToEndOfParagraphAndModifySelection) \
392 macro(moveToEndOfSentence) \
393 macro(moveToEndOfSentenceAndModifySelection) \
394 macro(moveToLeftEndOfLine) \
395 macro(moveToLeftEndOfLineAndModifySelection) \
396 macro(moveToRightEndOfLine) \
397 macro(moveToRightEndOfLineAndModifySelection) \
399 macro(moveUpAndModifySelection) \
400 macro(moveWordBackward) \
401 macro(moveWordBackwardAndModifySelection) \
402 macro(moveWordForward) \
403 macro(moveWordForwardAndModifySelection) \
404 macro(moveWordLeft) \
405 macro(moveWordLeftAndModifySelection) \
406 macro(moveWordRight) \
407 macro(moveWordRightAndModifySelection) \
408 macro(orderFrontSubstitutionsPanel) \
412 macro(pageDownAndModifySelection) \
414 macro(pageUpAndModifySelection) \
416 macro(pasteAsPlainText) \
417 macro(pasteAsRichText) \
419 macro(performFindPanelAction) \
420 macro(scrollLineDown) \
421 macro(scrollLineUp) \
422 macro(scrollPageDown) \
423 macro(scrollPageUp) \
424 macro(scrollToBeginningOfDocument) \
425 macro(scrollToEndOfDocument) \
428 macro(selectParagraph) \
429 macro(selectSentence) \
430 macro(selectToMark) \
433 macro(showGuessPanel) \
434 macro(startSpeaking) \
435 macro(stopSpeaking) \
438 macro(swapWithMark) \
439 macro(takeFindStringFromSelection) \
440 macro(toggleBaseWritingDirection) \
444 macro(uppercaseWord) \
446 macro(yankAndSelect) \
448 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
449 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
451 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
452 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
454 static BOOL s_didSetCacheModel;
455 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
458 static Class s_pdfRepresentationClass;
459 static Class s_pdfViewClass;
463 static const char webViewIsOpen[] = "At least one WebView is still open.";
467 @interface WebView(WebViewPrivate)
468 - (void)_preferencesChanged:(WebPreferences *)preferences;
469 - (void)_updateScreenScaleFromWindow;
472 @interface NSURLCache (WebPrivate)
473 - (CFURLCacheRef)_CFURLCache;
478 @interface NSObject (WebValidateWithoutDelegate)
479 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
484 @class _WebSafeForwarder;
486 @interface _WebSafeAsyncForwarder : NSObject {
487 _WebSafeForwarder *_forwarder;
489 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
493 @interface _WebSafeForwarder : NSObject
495 id target; // Non-retained. Don't retain delegates.
498 _WebSafeAsyncForwarder *asyncForwarder;
499 dispatch_once_t asyncForwarderPred;
502 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
505 - (id)asyncForwarder;
509 FindOptions coreOptions(WebFindOptions options)
511 return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
512 | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
513 | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
514 | (options & WebFindOptionsBackwards ? Backwards : 0)
515 | (options & WebFindOptionsWrapAround ? WrapAround : 0)
516 | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
519 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
521 return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
522 | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
523 | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
526 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
528 return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
529 | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
530 | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
533 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
535 switch (visibilityState) {
536 case PageVisibilityStateVisible:
537 return WebPageVisibilityStateVisible;
538 case PageVisibilityStateHidden:
539 return WebPageVisibilityStateHidden;
540 case PageVisibilityStatePrerender:
541 return WebPageVisibilityStatePrerender;
544 ASSERT_NOT_REACHED();
545 return WebPageVisibilityStateVisible;
548 @interface WebView (WebFileInternal)
550 - (float)_deviceScaleFactor;
553 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
554 - (WebFrame *)_focusedFrame;
555 + (void)_preflightSpellChecker;
556 - (BOOL)_continuousCheckingAllowed;
557 - (NSResponder *)_responderForResponderOperations;
559 - (void)_clearGlibLoopObserver;
563 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
564 NSString *WebElementFrameKey = @"WebElementFrame";
565 NSString *WebElementImageKey = @"WebElementImage";
566 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
567 NSString *WebElementImageRectKey = @"WebElementImageRect";
568 NSString *WebElementImageURLKey = @"WebElementImageURL";
569 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
570 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
571 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
572 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
573 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
574 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
575 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
576 NSString *WebElementTitleKey = @"WebElementTitle";
577 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
578 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
579 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
581 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
582 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
584 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
586 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
587 NSString * const WebViewProgressBackgroundColorKey = @"WebProgressBackgroundColorKey";
590 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
591 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
592 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
593 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
594 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
596 enum { WebViewVersion = 4 };
598 #define timedLayoutSize 4096
600 static NSMutableSet *schemesWithRepresentationsSet;
603 NSString *_WebCanGoBackKey = @"canGoBack";
604 NSString *_WebCanGoForwardKey = @"canGoForward";
605 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
606 NSString *_WebIsLoadingKey = @"isLoading";
607 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
608 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
609 NSString *_WebMainFrameURLKey = @"mainFrameURL";
610 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
614 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
615 NSString *WebQuickLookUTIKey = @"WebQuickLookUTIKey";
618 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
619 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
621 #if ENABLE(REMOTE_INSPECTOR)
622 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
623 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
626 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
628 @interface WebProgressItem : NSObject
631 long long bytesReceived;
632 long long estimatedLength;
636 @implementation WebProgressItem
639 static BOOL continuousSpellCheckingEnabled;
641 static BOOL grammarCheckingEnabled;
642 static BOOL automaticQuoteSubstitutionEnabled;
643 static BOOL automaticLinkDetectionEnabled;
644 static BOOL automaticDashSubstitutionEnabled;
645 static BOOL automaticTextReplacementEnabled;
646 static BOOL automaticSpellingCorrectionEnabled;
649 @implementation WebView (AllWebViews)
651 static CFSetCallBacks NonRetainingSetCallbacks = {
660 static CFMutableSetRef allWebViewsSet;
662 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
667 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
670 - (void)_removeFromAllWebViewsSet
673 CFSetRemoveValue(allWebViewsSet, self);
676 - (void)_addToAllWebViewsSet
679 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
681 CFSetSetValue(allWebViewsSet, self);
686 @implementation WebView (WebPrivate)
688 static String webKitBundleVersionString()
690 return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
693 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
695 return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
699 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
701 [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
704 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
706 [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
708 #endif // PLATFORM(IOS)
710 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
712 if (!exception || !context)
715 JSC::ExecState* execState = toJS(context);
716 JSLockHolder lock(execState);
718 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
719 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
722 reportException(execState, toJS(execState, exception));
725 static void WebKitInitializeApplicationCachePathIfNecessary()
727 static BOOL initialized = NO;
731 NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
733 appName = [[NSProcessInfo processInfo] processName];
735 if (WebCore::applicationIsMobileSafari() || WebCore::applicationIsWebApp())
736 appName = @"com.apple.WebAppCache";
741 NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
743 cacheStorage().setCacheDirectory(cacheDir);
747 static bool shouldEnableLoadDeferring()
749 return !applicationIsAdobeInstaller();
752 static bool shouldRestrictWindowFocus()
757 return !applicationIsHRBlock();
761 - (void)_dispatchPendingLoadRequests
763 resourceLoadScheduler()->servePendingRequests();
767 - (void)_registerDraggedTypes
769 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
770 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
771 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
772 [types addObjectsFromArray:URLTypes];
773 [self registerForDraggedTypes:[types allObjects]];
777 static bool needsOutlookQuirksScript()
779 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
780 && applicationIsMicrosoftOutlook();
781 return isOutlookNeedingQuirksScript;
784 static NSString *leakOutlookQuirksUserScriptContents()
786 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
787 NSStringEncoding encoding;
788 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
791 -(void)_injectOutlookQuirksScript
793 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
794 _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
799 static bool shouldRespectPriorityInCSSAttributeSetters()
802 static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
803 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
804 return isStanzaNeedingAttributeSetterQuirk;
806 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
807 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
808 return isIAdProducerNeedingAttributeSetterQuirk;
813 static bool shouldTransformsAffectOverflow()
815 static bool shouldTransformsAffectOverflow = !applicationIsOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
816 return shouldTransformsAffectOverflow;
819 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
821 static bool shouldDispatchJavaScriptWindowOnErrorEvents = !applicationIsFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
822 return shouldDispatchJavaScriptWindowOnErrorEvents;
825 static bool isInternalInstall()
827 static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
831 static bool didOneTimeInitialization = false;
834 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
837 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
839 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = applicationIsVersions()
840 && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
842 return shouldUseLegacyBackgroundSizeShorthandBehavior;
846 static void WebKitInitializeGamepadProviderIfNecessary()
848 static bool initialized = false;
852 GamepadProvider::shared().setSharedProvider(HIDGamepadProvider::shared());
857 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
859 WebCoreThreadViolationCheckRoundTwo();
862 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
865 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
866 [standardPreferences willAddToWebView];
868 _private->preferences = [standardPreferences retain];
869 _private->mainFrameDocumentReady = NO;
870 _private->drawsBackground = YES;
872 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
874 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
876 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
878 NSRect f = [self frame];
879 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
880 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
881 [self addSubview:frameView];
884 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
885 if ([self respondsToSelector:@selector(setActionMenu:)]) {
886 RetainPtr<NSMenu> actionMenu = adoptNS([[NSMenu alloc] init]);
887 self.actionMenu = actionMenu.get();
888 _private->actionMenuController = [[WebActionMenuController alloc] initWithWebView:self];
889 self.actionMenu.autoenablesItems = NO;
894 static bool didOneTimeInitialization = false;
896 if (!didOneTimeInitialization) {
898 WebKitInitializeLoggingChannelsIfNecessary();
899 WebCore::initializeLoggingChannelsIfNecessary();
900 #endif // !LOG_DISABLED
902 // Initialize our platform strategies first before invoking the rest
903 // of the initialization code which may depend on the strategies.
904 WebPlatformStrategies::initializeIfNecessary();
906 #if ENABLE(SQL_DATABASE)
908 // Set the WebSQLiteDatabaseTrackerClient.
909 SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
911 if ([standardPreferences databasesEnabled])
913 [WebDatabaseManager sharedWebDatabaseManager];
917 if ([standardPreferences storageTrackerEnabled])
919 WebKitInitializeStorageIfNecessary();
920 WebKitInitializeApplicationCachePathIfNecessary();
922 WebKitInitializeGamepadProviderIfNecessary();
925 Settings::setDefaultMinDOMTimerInterval(0.004);
927 Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
930 if (applicationIsMobileSafari())
931 Settings::setShouldManageAudioSessionCategory(true);
934 didOneTimeInitialization = true;
937 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
938 _private->group->addWebView(self);
940 PageConfiguration pageConfiguration;
942 pageConfiguration.chromeClient = new WebChromeClient(self);
943 pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
944 #if ENABLE(DRAG_SUPPORT)
945 pageConfiguration.dragClient = new WebDragClient(self);
947 pageConfiguration.inspectorClient = new WebInspectorClient(self);
949 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
950 pageConfiguration.inspectorClient = new WebInspectorClient(self);
952 pageConfiguration.editorClient = new WebEditorClient(self);
953 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
954 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
955 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
956 pageConfiguration.userContentController = &_private->group->userContentController();
957 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
958 _private->page = new Page(pageConfiguration);
960 _private->page->setGroupName(groupName);
962 #if ENABLE(GEOLOCATION)
963 WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
965 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
966 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
968 #if ENABLE(DEVICE_ORIENTATION)
970 WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
973 #if ENABLE(MEDIA_STREAM)
974 WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
977 #if ENABLE(REMOTE_INSPECTOR)
978 _private->page->setRemoteInspectionAllowed(true);
981 _private->page->setCanStartMedia([self window]);
982 _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
983 _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
986 if (needsOutlookQuirksScript()) {
987 _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
988 [self _injectOutlookQuirksScript];
993 // Preserve the behavior we had before <rdar://problem/7580867>
994 // by enforcing a 5MB limit for session storage.
995 _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
997 [self _updateScreenScaleFromWindow];
998 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
999 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1000 _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1003 if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1004 [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1006 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1009 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1011 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1012 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1014 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1017 [self _addToAllWebViewsSet];
1019 // If there's already a next key view (e.g., from a nib), wire it up to our
1020 // contained frame view. In any case, wire our next key view up to the our
1021 // contained frame view. This works together with our becomeFirstResponder
1022 // and setNextKeyView overrides.
1023 NSView *nextKeyView = [self nextKeyView];
1024 if (nextKeyView && nextKeyView != frameView)
1025 [frameView setNextKeyView:nextKeyView];
1026 [super setNextKeyView:frameView];
1028 if ([[self class] shouldIncludeInWebKitStatistics])
1032 [self _registerDraggedTypes];
1035 [self _setIsVisible:[self _isViewVisible]];
1037 WebPreferences *prefs = [self preferences];
1038 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1039 name:WebPreferencesChangedInternalNotification object:prefs];
1042 [self _preferencesChanged:[self preferences]];
1043 [[self preferences] _postPreferencesChangedAPINotification];
1045 // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1046 // and prefs need to be changed synchronously <rdar://problem/5841558>
1047 [self _preferencesChanged:prefs];
1048 _private->page->settings().setFontFallbackPrefersPictographs(true);
1051 memoryPressureHandler().install();
1053 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1054 // Originally, we allowed all local loads.
1055 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1056 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1057 // Later, we allowed local loads for local URLs and documents loaded
1058 // with substitute data.
1059 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1063 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1064 ResourceHandle::forceContentSniffing();
1066 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1070 [self _scheduleGlibContextIterations];
1074 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1076 self = [super initWithFrame:f];
1080 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1081 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1082 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1083 // need for Safari to unset it to prevent it from being passed to applications it launches.
1084 // Unsetting it when a WebView is first created is as good a place as any.
1085 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1086 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1087 unsetenv("DYLD_FRAMEWORK_PATH");
1088 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1092 _private = [[WebViewPrivate alloc] init];
1093 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1094 [self setMaintainsBackForwardList: YES];
1098 - (void)_viewWillDrawInternal
1100 Frame* frame = [self _mainCoreFrame];
1101 if (frame && frame->view())
1102 frame->view()->updateLayoutAndStyleIfNeededRecursive();
1105 + (NSArray *)_supportedMIMETypes
1107 // Load the plug-in DB allowing plug-ins to install types.
1108 [WebPluginDatabase sharedDatabase];
1109 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1113 + (NSArray *)_supportedFileExtensions
1115 NSMutableSet *extensions = [[NSMutableSet alloc] init];
1116 NSArray *MIMETypes = [self _supportedMIMETypes];
1117 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1119 while ((MIMEType = [enumerator nextObject]) != nil) {
1120 NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1121 if (extensionsForType) {
1122 [extensions addObjectsFromArray:extensionsForType];
1125 NSArray *uniqueExtensions = [extensions allObjects];
1126 [extensions release];
1127 return uniqueExtensions;
1132 + (void)enableWebThread
1134 static BOOL isWebThreadEnabled = NO;
1135 if (!isWebThreadEnabled) {
1136 WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1137 WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1138 WebCoreObjCDeallocOnWebThread([WebFrame class]);
1139 WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1140 WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1141 WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1142 WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1143 WebCoreObjCDeallocOnWebThread([WebView class]);
1144 WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1145 if (applicationIsTheEconomistOnIPhone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1146 WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1148 isWebThreadEnabled = YES;
1152 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1154 self = [super initWithFrame:frame];
1158 _private = [[WebViewPrivate alloc] init];
1161 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1165 preferences = [WebPreferences standardPreferences];
1166 [preferences willAddToWebView];
1168 _private->preferences = [preferences retain];
1169 _private->mainFrameDocumentReady = NO;
1170 _private->drawsBackground = YES;
1171 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
1173 WebFrameView *frameView = nil;
1174 frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1175 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1176 [self addSubview:frameView];
1177 [frameView release];
1179 _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1180 _private->group->addWebView(self);
1182 PageConfiguration pageConfiguration;
1183 pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1184 #if ENABLE(DRAG_SUPPORT)
1185 pageConfiguration.dragClient = new WebDragClient(self);
1187 pageConfiguration.editorClient = new WebEditorClient(self);
1188 pageConfiguration.inspectorClient = new WebInspectorClient(self);
1189 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1190 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1191 pageConfiguration.userContentController = &_private->group->userContentController();
1192 pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1194 _private->page = new Page(pageConfiguration);
1196 [self setSmartInsertDeleteEnabled:YES];
1198 // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1199 // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1200 // This matches how UIKit sets up the preferences. We need to set default values for fonts though, <rdar://problem/6850611>.
1201 // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1202 _private->page->settings().setMinimumLogicalFontSize(9);
1203 _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1204 _private->page->settings().setDefaultFixedFontSize(13);
1205 _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1206 _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1207 _private->page->settings().setScreenFontSubstitutionEnabled(false);
1209 // FIXME: <rdar://problem/7394370> Always use primary font baseline in text field base line calculation, ignore fallback fonts.
1210 _private->page->settings().setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
1212 _private->page->settings().setFontFallbackPrefersPictographs(true);
1213 _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1215 // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1216 _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1218 // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1219 _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1221 _private->page->setGroupName(groupName);
1223 #if ENABLE(REMOTE_INSPECTOR)
1224 _private->page->setRemoteInspectionAllowed(isInternalInstall());
1227 [self _updateScreenScaleFromWindow];
1228 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1229 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1231 [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1233 [self _addToAllWebViewsSet];
1237 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1242 + (void)_handleMemoryWarning
1244 ASSERT(WebThreadIsCurrent());
1245 WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1247 // Always peform the following.
1248 [WebView purgeInactiveFontData];
1250 // Only perform the remaining if a non-simple document was created.
1251 if (!didOneTimeInitialization)
1254 tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1256 [WebStorageManager closeIdleLocalStorageDatabases];
1258 [WebView _releaseMemoryNow];
1261 + (void)registerForMemoryNotifications
1263 BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::applicationIsMobileSafari();
1265 memoryPressureHandler().installMemoryReleaseBlock(^{
1266 [WebView _handleMemoryWarning];
1267 }, shouldAutoClearPressureOnMemoryRelease);
1269 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1270 static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS, 0, DISPATCH_MEMORYSTATUS_PRESSURE_WARN, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1272 static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0, DISPATCH_VM_PRESSURE, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1274 dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1275 // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1276 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1279 dispatch_resume(memoryNotificationEventSource);
1281 if (!shouldAutoClearPressureOnMemoryRelease) {
1282 // Listen to memory status notification to reset the memory pressure flag.
1283 static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS,
1285 DISPATCH_MEMORYSTATUS_PRESSURE_WARN | DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL,
1286 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1287 dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1288 unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1289 if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL)
1290 memoryPressureHandler().clearMemoryPressure();
1291 else if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_WARN)
1292 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1295 dispatch_resume(memoryStatusEventSource);
1299 + (void)_releaseMemoryNow
1301 ASSERT(WebThreadIsCurrent());
1302 [WebView discardAllCompiledCode];
1303 [WebView garbageCollectNow];
1304 [WebView purgeInactiveFontData];
1305 [WebView drainLayerPool];
1306 [WebCache emptyInMemoryResources];
1307 [WebView releaseFastMallocMemoryOnCurrentThread];
1309 dispatch_async(dispatch_get_main_queue(), ^{
1310 // Clear the main thread's TCMalloc thread cache.
1311 [WebView releaseFastMallocMemoryOnCurrentThread];
1315 + (void)_clearPrivateBrowsingSessionCookieStorage
1317 WebFrameNetworkingContext::clearPrivateBrowsingSessionCookieStorage();
1320 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1322 Frame* frame = [self _mainCoreFrame];
1324 frame->loader().history().replaceCurrentItem(core(item));
1327 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1330 [WebView _releaseMemoryNow];
1331 dispatch_async(dispatch_get_main_queue(), handler);
1335 + (void)releaseFastMallocMemoryOnCurrentThread
1337 WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1338 WTF::releaseFastMallocFreeMemory();
1341 + (void)garbageCollectNow
1343 ASSERT(WebThreadIsCurrent());
1344 WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1345 gcController().garbageCollectNow();
1348 + (void)purgeInactiveFontData
1350 ASSERT(WebThreadIsCurrent());
1351 WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1352 fontCache().purgeInactiveFontData();
1355 + (void)drainLayerPool
1357 ASSERT(WebThreadIsCurrent());
1358 WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1359 WebCore::LegacyTileCache::drainLayerPool();
1362 + (void)discardAllCompiledCode
1364 ASSERT(WebThreadIsCurrent());
1365 WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1366 gcController().discardAllCompiledCode();
1369 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1371 return WebCore::isCharacterSmartReplaceExempt(character, b);
1374 - (void)updateLayoutIgnorePendingStyleSheets
1377 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1378 Document *document = frame->document();
1380 document->updateLayoutIgnorePendingStylesheets();
1384 #endif // PLATFORM(IOS)
1386 static NSMutableSet *knownPluginMIMETypes()
1388 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1393 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1395 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1396 [knownPluginMIMETypes() addObject:MIMEType];
1399 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1401 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1402 [knownPluginMIMETypes() removeObject:MIMEType];
1405 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1407 MIMEType = [MIMEType lowercaseString];
1408 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1409 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1412 #define WebPDFView ([WebView _getPDFViewClass])
1414 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1418 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1421 // Load the plug-in DB allowing plug-ins to install types.
1422 [WebPluginDatabase sharedDatabase];
1425 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1426 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1427 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1430 if (viewClass && repClass) {
1431 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1432 // Special-case WebHTMLView for text types that shouldn't be shown.
1433 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1436 // If the MIME type is a known plug-in we might not want to load it.
1437 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1438 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1439 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1441 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1442 if (!isSupportedByWebKit)
1447 *vClass = viewClass;
1456 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1458 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1461 if (_private->pluginDatabase) {
1462 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1463 if (pluginPackage) {
1465 *vClass = [WebHTMLView class];
1467 *rClass = [WebHTMLRepresentation class];
1475 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1477 Font::setCodePath(f ? Font::Complex : Font::Auto);
1480 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1482 TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1485 + (BOOL)_allowsRoundingHacks
1487 return TextRun::allowsRoundingHacks();
1490 + (BOOL)canCloseAllWebViews
1492 return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1495 + (void)closeAllWebViews
1497 DOMWindow::dispatchAllPendingUnloadEvents();
1499 // This will close the WebViews in a random order. Change this if close order is important.
1500 // Make a new set to avoid mutating the set we are enumerating.
1501 NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet];
1502 NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1503 while (WebView *webView = [enumerator nextObject])
1507 + (BOOL)canShowFile:(NSString *)path
1509 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1513 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1515 return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1521 return !_private || _private->closed;
1525 - (void)_dispatchUnloadEvent
1528 WebFrame *mainFrame = [self mainFrame];
1529 Frame *coreMainFrame = core(mainFrame);
1530 if (coreMainFrame) {
1531 Document *document = coreMainFrame->document();
1533 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1538 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1540 WebFrame *mainFrame = [self mainFrame];
1541 Frame *coreMainFrame = core(mainFrame);
1544 return coreMainFrame->styleAtSelectionStart();
1547 - (NSUInteger)_renderTreeSize
1549 if (!_private->page)
1551 return _private->page->renderTreeSize();
1554 - (void)_dispatchTileDidDraw:(CALayer*)tile
1556 id mailDelegate = [self _webMailDelegate];
1557 if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1558 [mailDelegate _webthread_webView:self tileDidDraw:tile];
1562 if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1567 [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1570 - (void)_willStartScrollingOrZooming
1572 // Pause timers during top level interaction
1573 if (_private->mainViewIsScrollingOrZooming)
1575 _private->mainViewIsScrollingOrZooming = YES;
1577 // This suspends active DOM objects like timers, but not media.
1578 [[self mainFrame] setTimeoutsPaused:YES];
1580 // This defers loading callbacks only.
1581 // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1582 [self setDefersCallbacks:YES];
1585 - (void)_didFinishScrollingOrZooming
1587 if (!_private->mainViewIsScrollingOrZooming)
1589 _private->mainViewIsScrollingOrZooming = NO;
1590 [self setDefersCallbacks:NO];
1591 [[self mainFrame] setTimeoutsPaused:NO];
1592 if (FrameView* view = [self _mainCoreFrame]->view())
1593 view->resumeVisibleImageAnimationsIncludingSubframes();
1596 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1599 resourceLoadScheduler()->suspendPendingRequests();
1601 resourceLoadScheduler()->resumePendingRequests();
1604 + (void)_setAllowCookies:(BOOL)allow
1606 ResourceRequestBase::setDefaultAllowCookies(allow);
1609 + (BOOL)_allowCookies
1611 return ResourceRequestBase::defaultAllowCookies();
1614 + (BOOL)_isUnderMemoryPressure
1616 return memoryPressureHandler().isUnderMemoryPressure();
1619 + (void)_clearMemoryPressure
1621 memoryPressureHandler().clearMemoryPressure();
1624 + (BOOL)_shouldWaitForMemoryClearMessage
1626 return memoryPressureHandler().shouldWaitForMemoryClearMessage();
1628 #endif // PLATFORM(IOS)
1630 - (void)_closePluginDatabases
1632 pluginDatabaseClientCount--;
1634 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1637 // Unload the WebView local plug-in database.
1638 if (_private->pluginDatabase) {
1639 [_private->pluginDatabase destroyAllPluginInstanceViews];
1640 [_private->pluginDatabase close];
1641 [_private->pluginDatabase release];
1642 _private->pluginDatabase = nil;
1646 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1647 if (!pluginDatabaseClientCount && applicationIsTerminating)
1648 [WebPluginDatabase closeSharedDatabase];
1651 - (void)_closeWithFastTeardown
1654 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1658 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1660 [[NSNotificationCenter defaultCenter] removeObserver:self];
1662 [self _closePluginDatabases];
1665 static bool fastDocumentTeardownEnabled()
1668 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1670 static bool initialized = false;
1671 static bool enabled = false;
1673 // This allows debug builds to default to not have fast teardown, so leak checking still works.
1674 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1675 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1677 enabled = ![setting boolValue];
1684 // _close is here only for backward compatibility; clients and subclasses should use
1685 // public method -close instead.
1689 // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1690 // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1692 [self _clearDelegates];
1694 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1698 if (!_private || _private->closed)
1701 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1703 _private->closed = YES;
1704 [self _removeFromAllWebViewsSet];
1707 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1710 // To quit the apps fast we skip document teardown, except plugins
1711 // need to be destroyed and unloaded.
1712 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1713 [self _closeWithFastTeardown];
1717 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1718 [self _exitVideoFullscreen];
1722 _private->closing = YES;
1725 if (Frame* mainFrame = [self _mainCoreFrame])
1726 mainFrame->loader().detachFromParent();
1728 [self setHostWindow:nil];
1731 [self setDownloadDelegate:nil];
1732 [self setEditingDelegate:nil];
1733 [self setFrameLoadDelegate:nil];
1734 [self setPolicyDelegate:nil];
1735 [self setResourceLoadDelegate:nil];
1736 [self setScriptDebugDelegate:nil];
1737 [self setUIDelegate:nil];
1739 [_private->inspector webViewClosed];
1741 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1742 [_private->actionMenuController webViewClosed];
1746 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1747 [self removeDragCaret];
1750 _private->group->removeWebView(self);
1752 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1753 // all the plug-ins in the page cache to break any retain cycles.
1754 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1755 Page* page = _private->page;
1760 if (_private->hasSpellCheckerDocumentTag) {
1761 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1762 _private->hasSpellCheckerDocumentTag = NO;
1766 if (_private->layerFlushController) {
1767 _private->layerFlushController->invalidate();
1768 _private->layerFlushController = nullptr;
1772 [self _clearGlibLoopObserver];
1775 [[self _notificationProvider] unregisterWebView:self];
1778 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1780 [[NSNotificationCenter defaultCenter] removeObserver:self];
1782 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1784 WebPreferences *preferences = _private->preferences;
1785 _private->preferences = nil;
1786 [preferences didRemoveFromWebView];
1787 [preferences release];
1789 [self _closePluginDatabases];
1792 // Need this to make leak messages accurate.
1793 if (applicationIsTerminating) {
1794 gcController().garbageCollectNow();
1795 [WebCache setDisabled:YES];
1799 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1804 // Indicates if the WebView is in the midst of a user gesture.
1805 - (BOOL)_isProcessingUserGesture
1807 return ScriptController::processingUserGesture();
1810 + (NSString *)_MIMETypeForFile:(NSString *)path
1813 NSString *extension = [path pathExtension];
1815 NSString *MIMEType = nil;
1818 // Get the MIME type from the extension.
1819 if ([extension length] != 0) {
1820 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
1824 // If we can't get a known MIME type from the extension, sniff.
1825 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1826 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1827 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1829 if ([data length] != 0) {
1830 MIMEType = [data _webkit_guessedMIMEType];
1832 if ([MIMEType length] == 0) {
1833 MIMEType = @"application/octet-stream";
1840 - (WebDownload *)_downloadURL:(NSURL *)URL
1844 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1845 WebDownload *download = [WebDownload _downloadWithRequest:request
1846 delegate:_private->downloadDelegate
1853 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1855 NSDictionary *features = [[NSDictionary alloc] init];
1856 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1857 createWebViewWithRequest:nil
1858 windowFeatures:features];
1860 if (!newWindowWebView)
1863 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1864 return newWindowWebView;
1867 - (WebInspector *)inspector
1869 if (!_private->inspector)
1870 _private->inspector = [[WebInspector alloc] initWithWebView:self];
1871 return _private->inspector;
1874 #if ENABLE(REMOTE_INSPECTOR)
1875 + (void)_enableRemoteInspector
1877 RemoteInspector::shared().start();
1880 + (void)_disableRemoteInspector
1882 RemoteInspector::shared().stop();
1885 + (void)_disableAutoStartRemoteInspector
1887 RemoteInspector::startDisabled();
1890 + (BOOL)_isRemoteInspectorEnabled
1892 return RemoteInspector::shared().enabled();
1895 + (BOOL)_hasRemoteInspectorSession
1897 return RemoteInspector::shared().hasActiveDebugSession();
1900 - (BOOL)allowsRemoteInspection
1902 return _private->page->remoteInspectionAllowed();
1905 - (void)setAllowsRemoteInspection:(BOOL)allow
1907 _private->page->setRemoteInspectionAllowed(allow);
1910 - (void)setShowingInspectorIndication:(BOOL)showing
1913 ASSERT(WebThreadIsLocked());
1916 if (!_private->indicateLayer) {
1917 _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1918 [_private->indicateLayer setNeedsLayout];
1919 [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1922 [_private->indicateLayer removeFromSuperlayer];
1923 [_private->indicateLayer release];
1924 _private->indicateLayer = nil;
1927 // Implemented in WebCore::InspectorOverlay.
1932 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
1934 RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
1935 RemoteInspector::shared().setParentProcessInformation(pid, auditData);
1937 #endif // PLATFORM(IOS)
1938 #endif // ENABLE(REMOTE_INSPECTOR)
1940 - (WebCore::Page*)page
1942 return _private->page;
1946 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1948 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1949 NSArray *menuItems = defaultMenuItems;
1951 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1952 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1953 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1954 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1955 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1960 unsigned count = [menuItems count];
1964 NSMenu *menu = [[NSMenu alloc] init];
1965 for (unsigned i = 0; i < count; i++)
1966 [menu addItem:[menuItems objectAtIndex:i]];
1968 return [menu autorelease];
1972 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1974 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1975 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1976 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1979 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1982 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1984 if (!_private->page)
1987 if (!otherView->_private->page)
1990 // It turns out the right combination of behavior is done with the back/forward load
1991 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
1992 // in the back forward list, and go to the current one.
1994 BackForwardClient* backForwardClient = _private->page->backForward().client();
1995 ASSERT(!backForwardClient->currentItem()); // destination list should be empty
1997 BackForwardClient* otherBackForwardClient = otherView->_private->page->backForward().client();
1998 if (!otherBackForwardClient->currentItem())
1999 return; // empty back forward list, bail
2001 HistoryItem* newItemToGoTo = 0;
2003 int lastItemIndex = otherBackForwardClient->forwardListCount();
2004 for (int i = -otherBackForwardClient->backListCount(); i <= lastItemIndex; ++i) {
2006 // If this item is showing , save away its current scroll and form state,
2007 // since that might have changed since loading and it is normally not saved
2008 // until we leave that page.
2009 otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2011 RefPtr<HistoryItem> newItem = otherBackForwardClient->itemAtIndex(i)->copy();
2013 newItemToGoTo = newItem.get();
2014 backForwardClient->addItem(newItem.release());
2017 ASSERT(newItemToGoTo);
2018 _private->page->goToItem(newItemToGoTo, FrameLoadType::IndexedBackForward);
2021 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2023 _private->formDelegate = delegate;
2025 [_private->formDelegateForwarder clearTarget];
2026 [_private->formDelegateForwarder release];
2027 _private->formDelegateForwarder = nil;
2031 - (id<WebFormDelegate>)_formDelegate
2033 return _private->formDelegate;
2037 - (id)_formDelegateForwarder
2039 if (_private->closing)
2042 if (!_private->formDelegateForwarder)
2043 _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2044 return _private->formDelegateForwarder;
2047 - (id)_formDelegateForSelector:(SEL)selector
2049 id delegate = self->_private->formDelegate;
2050 if ([delegate respondsToSelector:selector])
2053 delegate = [WebDefaultFormDelegate sharedFormDelegate];
2054 if ([delegate respondsToSelector:selector])
2062 - (BOOL)_needsAdobeFrameReloadingQuirk
2064 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2065 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2066 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2067 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2068 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2069 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2070 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2071 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2072 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2073 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2078 - (BOOL)_needsLinkElementTextCSSQuirk
2080 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2081 && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2085 - (BOOL)_needsIsLoadingInAPISenseQuirk
2087 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2092 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2094 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
2098 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2100 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);
2104 static bool needsSelfRetainWhileLoadingQuirk()
2106 static bool needsQuirk = applicationIsAperture();
2109 #endif // !PLATFORM(IOS)
2111 - (BOOL)_needsPreHTML5ParserQuirks
2114 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2115 // with the new HTML5 parser. If these applications were linked against a
2116 // version of WebKit prior to the introduction of the HTML5 parser, enable
2117 // parser quirks to maintain compatibility. For details, see
2118 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2119 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2120 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2121 && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
2123 // Mail.app must continue to display HTML email that contains quirky markup.
2124 static bool isAppleMail = applicationIsAppleMail();
2126 return isApplicationNeedingParserQuirks
2128 #if ENABLE(DASHBOARD_SUPPORT)
2129 // Pre-HTML5 parser quirks are required to remain compatible with many
2130 // Dashboard widgets. See <rdar://problem/8175982>.
2131 || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2133 || [[self preferences] usePreHTML5ParserQuirks];
2135 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && applicationIsDaijisenDictionary();
2136 return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2140 - (void)_preferencesChangedNotification:(NSNotification *)notification
2143 // For WebViews that load synchronously, preference changes need to be propagated
2144 // down to WebCore synchronously so that loads in that WebView have the correct
2145 // up-to-date settings.
2146 if (!WebThreadIsLocked())
2148 if ([[self mainFrame] _loadsSynchronously]) {
2151 WebPreferences *preferences = (WebPreferences *)[notification object];
2152 [self _preferencesChanged:preferences];
2157 // It is possible that the prefs object has already changed before the invocation could be called
2158 // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2159 WebPreferences *preferences = (WebPreferences *)[notification object];
2160 if (preferences != [self preferences])
2162 [self _preferencesChanged:preferences];
2168 - (void)_preferencesChanged:(WebPreferences *)preferences
2170 ASSERT(preferences == [self preferences]);
2171 if (!_private->userAgentOverridden)
2172 _private->userAgent = String();
2174 // Cache this value so we don't have to read NSUserDefaults on each page load
2175 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2177 // Update corresponding WebCore Settings object.
2178 if (!_private->page)
2182 // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2183 // didOneTimeInitialization is true so that we don't initialize databases
2184 // until the first WebView has been created. This is because database
2185 // initialization current requires disk access to populate the origins
2186 // quota map and we want to do this lazily by waiting until WebKit is
2187 // used to display web content in a WebView. The possible cases are:
2188 // - on one time initialize (the first WebView creation) if databases are enabled (default)
2189 // - when databases are dynamically enabled later, and they were disabled at startup (this case)
2190 if (didOneTimeInitialization) {
2191 if ([preferences databasesEnabled])
2192 [WebDatabaseManager sharedWebDatabaseManager];
2194 if ([preferences storageTrackerEnabled])
2195 WebKitInitializeStorageIfNecessary();
2199 Settings& settings = _private->page->settings();
2201 settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2202 settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2203 settings.setDefaultFontSize([preferences defaultFontSize]);
2204 settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2205 settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2206 settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2207 settings.setFixedFontFamily([preferences fixedFontFamily]);
2208 settings.setScreenFontSubstitutionEnabled(
2209 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2210 [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
2212 [preferences screenFontSubstitutionEnabled]
2214 settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2215 settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2216 settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2217 settings.setJavaEnabled([preferences isJavaEnabled]);
2218 settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2219 settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2220 settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2221 settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2222 settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2223 settings.setMinimumFontSize([preferences minimumFontSize]);
2224 settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2225 settings.setPictographFontFamily([preferences pictographFontFamily]);
2226 settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2227 settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2229 _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2230 settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2231 settings.setSerifFontFamily([preferences serifFontFamily]);
2232 settings.setStandardFontFamily([preferences standardFontFamily]);
2233 settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2234 settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2236 settings.setShouldPrintBackgrounds(true);
2238 settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2240 settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2241 settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2242 settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2243 settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2244 settings.setUsesPageCache([self usesPageCache]);
2245 settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2246 settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2248 settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2249 settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
2250 settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2251 settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
2253 settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2254 settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2255 settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2256 settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2257 settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2258 settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2259 settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2260 settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2262 // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
2263 // Until we fix that, I will comment out the test (CFM)
2264 settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2265 settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2266 settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2267 settings.setShowDebugBorders([preferences showDebugBorders]);
2268 settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2269 settings.setShowRepaintCounter([preferences showRepaintCounter]);
2270 settings.setWebGLEnabled([preferences webGLEnabled]);
2271 settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2273 settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2274 settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2275 settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2276 settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2277 settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2278 settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2279 settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2280 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2281 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2283 settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2284 settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2285 settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2286 settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2287 settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2289 settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
2290 settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
2291 settings.setAllowsAlternateFullscreen([preferences allowsAlternateFullscreen]);
2292 settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2293 settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2294 settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2295 settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2297 settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2299 settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2300 settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2301 settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2303 settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2305 settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2306 settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2308 switch ([preferences storageBlockingPolicy]) {
2309 case WebAllowAllStorage:
2310 settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2312 case WebBlockThirdPartyStorage:
2313 settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2315 case WebBlockAllStorage:
2316 settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2320 settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2322 settings.setFixedPositionCreatesStackingContext(true);
2323 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2324 settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2327 #if ENABLE(RUBBER_BANDING)
2328 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2329 settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2333 settings.setStandalone([preferences _standalone]);
2334 settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2335 settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
2336 settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2337 settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2338 settings.setMaxParseDuration([preferences _maxParseDuration]);
2339 settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2340 settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
2341 settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2342 settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2343 settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2344 settings.setAVKitEnabled([preferences avKitEnabled]);
2345 settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2346 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2348 settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2349 settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2351 ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2352 settings.setDelegatesPageScaling(true);
2354 #if ENABLE(IOS_TEXT_AUTOSIZING)
2355 settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2357 #endif // PLATFORM(IOS)
2360 if ([preferences userStyleSheetEnabled]) {
2361 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2362 if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2363 location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2364 settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2366 settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2368 settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2369 settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2370 settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2371 settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2372 settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2373 settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2374 settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2375 settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2376 settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2377 settings.setQTKitEnabled([preferences isQTKitEnabled]);
2378 #endif // PLATFORM(MAC)
2380 #if ENABLE(SQL_DATABASE)
2381 DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
2384 #if ENABLE(MEDIA_SOURCE)
2385 settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2388 #if ENABLE(SERVICE_CONTROLS)
2389 settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2390 settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2393 #if ENABLE(VIDEO_TRACK)
2394 settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2395 settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2396 settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2399 #if USE(AVFOUNDATION)
2400 settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2403 #if ENABLE(WEB_AUDIO)
2404 settings.setWebAudioEnabled([preferences webAudioEnabled]);
2407 #if ENABLE(FULLSCREEN_API)
2408 settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2411 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2412 settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2415 settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2418 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2421 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2423 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2425 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2426 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2428 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2429 if (_private->zoomsTextOnly != zoomsTextOnly)
2430 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2433 [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2434 [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2435 [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2436 [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2439 #if ENABLE(ENCRYPTED_MEDIA_V2)
2440 settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2444 static inline IMP getMethod(id o, SEL s)
2446 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2450 - (id)_UIKitDelegateForwarder
2452 if (_private->closing)
2455 if (!_private->UIKitDelegateForwarder)
2456 _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2457 return _private->UIKitDelegateForwarder;
2461 - (void)_cacheResourceLoadDelegateImplementations
2463 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2464 id delegate = _private->resourceProgressDelegate;
2467 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2471 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2472 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2473 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2474 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2475 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2476 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2477 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2481 cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2482 cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2483 cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2484 cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2485 cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2486 cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2487 cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2488 cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2489 cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2492 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2493 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2494 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2495 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2496 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2497 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2498 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2499 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2502 - (void)_cacheFrameLoadDelegateImplementations
2504 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2505 id delegate = _private->frameLoadDelegate;
2508 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2512 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2513 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2514 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2515 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2516 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2517 #if JSC_OBJC_API_ENABLED
2518 cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2520 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2521 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2522 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2523 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2524 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2525 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2526 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2527 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2528 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2529 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2530 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2531 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2532 #if ENABLE(ICONDATABASE)
2533 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2535 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2536 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2537 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2538 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2539 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2540 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2541 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2542 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2543 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2544 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2546 cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2549 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2550 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2551 // for backwards compatibility.
2552 Page* page = core(self);
2554 unsigned milestones = DidFirstLayout;
2556 milestones |= DidFirstVisuallyNonEmptyLayout;
2558 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2559 milestones |= DidFirstVisuallyNonEmptyLayout;
2561 page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2565 - (void)_cacheScriptDebugDelegateImplementations
2567 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2568 id delegate = _private->scriptDebugDelegate;
2571 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2575 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2576 if (cache->didParseSourceFunc)
2577 cache->didParseSourceExpectsBaseLineNumber = YES;
2579 cache->didParseSourceExpectsBaseLineNumber = NO;
2580 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2583 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2585 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2586 if (cache->exceptionWasRaisedFunc)
2587 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2589 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2590 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2594 - (void)_cacheHistoryDelegateImplementations
2596 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2597 id delegate = _private->historyDelegate;
2600 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2604 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2605 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2606 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2607 cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2608 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2609 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2612 - (id)_policyDelegateForwarder
2615 if (_private->closing)
2618 if (!_private->policyDelegateForwarder)
2619 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2620 return _private->policyDelegateForwarder;
2623 - (id)_UIDelegateForwarder
2626 if (_private->closing)
2629 if (!_private->UIDelegateForwarder)
2630 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2631 return _private->UIDelegateForwarder;
2635 - (id)_UIDelegateForSelector:(SEL)selector
2637 id delegate = self->_private->UIDelegate;
2638 if ([delegate respondsToSelector:selector])
2641 delegate = [WebDefaultUIDelegate sharedUIDelegate];
2642 if ([delegate respondsToSelector:selector])
2649 - (id)_editingDelegateForwarder
2652 if (_private->closing)
2655 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2656 // Not sure if that is a bug or not.
2660 if (!_private->editingDelegateForwarder)
2661 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2662 return _private->editingDelegateForwarder;
2665 - (void)_closeWindow
2667 [[self _UIDelegateForwarder] webViewClose:self];
2670 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2672 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2673 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2675 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2676 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2677 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2678 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2681 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2683 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2684 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2686 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2687 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2688 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2689 if ([viewClass class] == [WebHTMLView class])
2690 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2692 // This is used to make _representationExistsForURLScheme faster.
2693 // Without this set, we'd have to create the MIME type each time.
2694 if (schemesWithRepresentationsSet == nil) {
2695 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2697 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2700 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2702 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2705 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2707 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2710 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2712 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2716 if ([NSURLConnection canHandleRequest:request])
2719 NSString *scheme = [[request URL] scheme];
2721 // Representations for URL schemes work at the top level.
2722 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2725 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2728 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2734 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2736 return [self _canHandleRequest:request forMainFrame:YES];
2739 + (NSString *)_decodeData:(NSData *)data
2741 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2742 return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2745 - (void)_pushPerformingProgrammaticFocus
2747 _private->programmaticFocusCount++;
2750 - (void)_popPerformingProgrammaticFocus
2752 _private->programmaticFocusCount--;
2755 - (BOOL)_isPerformingProgrammaticFocus
2757 return _private->programmaticFocusCount != 0;
2761 - (void)_didChangeValueForKey: (NSString *)key
2763 LOG (Bindings, "calling didChangeValueForKey: %@", key);
2764 [self didChangeValueForKey: key];
2767 - (void)_willChangeValueForKey: (NSString *)key
2769 LOG (Bindings, "calling willChangeValueForKey: %@", key);
2770 [self willChangeValueForKey: key];
2773 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2774 static NSSet *manualNotifyKeys = nil;
2775 if (!manualNotifyKeys)
2776 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2777 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2779 if ([manualNotifyKeys containsObject:key])
2784 - (NSArray *)_declaredKeys {
2785 static NSArray *declaredKeys = nil;
2787 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2788 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2789 return declaredKeys;
2792 - (void)setObservationInfo:(void *)info
2794 _private->observationInfo = info;
2797 - (void *)observationInfo
2799 return _private->observationInfo;
2802 - (void)_willChangeBackForwardKeys
2804 [self _willChangeValueForKey: _WebCanGoBackKey];
2805 [self _willChangeValueForKey: _WebCanGoForwardKey];
2808 - (void)_didChangeBackForwardKeys
2810 [self _didChangeValueForKey: _WebCanGoBackKey];
2811 [self _didChangeValueForKey: _WebCanGoForwardKey];
2814 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2816 if (needsSelfRetainWhileLoadingQuirk())
2819 [self _willChangeBackForwardKeys];
2820 if (frame == [self mainFrame]){
2821 // Force an observer update by sending a will/did.
2822 [self _willChangeValueForKey: _WebIsLoadingKey];
2823 [self _didChangeValueForKey: _WebIsLoadingKey];
2825 [self _willChangeValueForKey: _WebMainFrameURLKey];
2828 [NSApp setWindowsNeedUpdate:YES];
2830 #if ENABLE(FULLSCREEN_API)
2831 Document* document = core([frame DOMDocument]);
2832 if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2833 SEL selector = @selector(webView:closeFullScreenWithListener:);
2834 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2835 WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2836 CallUIDelegate(self, selector, listener);
2838 } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2839 [_private->newFullscreenController close];
2845 - (void)_checkDidPerformFirstNavigation
2847 if (_private->_didPerformFirstNavigation)
2850 Page* page = _private->page;
2854 auto& backForwardController = page->backForward();
2856 if (!backForwardController.backItem())
2859 _private->_didPerformFirstNavigation = YES;
2861 if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2862 _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2865 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2867 if (frame == [self mainFrame])
2868 [self _didChangeValueForKey: _WebMainFrameURLKey];
2870 [self _checkDidPerformFirstNavigation];
2872 [NSApp setWindowsNeedUpdate:YES];
2875 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2877 if (needsSelfRetainWhileLoadingQuirk())
2878 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2880 [self _didChangeBackForwardKeys];
2881 if (frame == [self mainFrame]){
2882 // Force an observer update by sending a will/did.
2883 [self _willChangeValueForKey: _WebIsLoadingKey];
2884 [self _didChangeValueForKey: _WebIsLoadingKey];
2886 [NSApp setWindowsNeedUpdate:YES];
2889 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2891 if (needsSelfRetainWhileLoadingQuirk())
2892 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2894 [self _didChangeBackForwardKeys];
2895 if (frame == [self mainFrame]){
2896 // Force an observer update by sending a will/did.
2897 [self _willChangeValueForKey: _WebIsLoadingKey];
2898 [self _didChangeValueForKey: _WebIsLoadingKey];
2900 [NSApp setWindowsNeedUpdate:YES];
2903 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2905 if (needsSelfRetainWhileLoadingQuirk())
2906 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2908 [self _didChangeBackForwardKeys];
2909 if (frame == [self mainFrame]){
2910 // Force an observer update by sending a will/did.
2911 [self _willChangeValueForKey: _WebIsLoadingKey];
2912 [self _didChangeValueForKey: _WebIsLoadingKey];
2914 [self _didChangeValueForKey: _WebMainFrameURLKey];
2916 [NSApp setWindowsNeedUpdate:YES];
2919 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2921 RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2922 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2923 NSCachedURLResponse *cachedResponse;
2925 if (!_private->page)
2928 if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2929 cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2931 cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2933 return cachedResponse;
2936 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2938 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2939 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2940 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2942 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2943 title:[element objectForKey:WebElementImageAltStringKey]
2944 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2949 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2951 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2952 andTitle:[element objectForKey:WebElementLinkLabelKey]
2956 #if ENABLE(DRAG_SUPPORT)
2957 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2959 if (!_private->page)
2961 _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2967 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2969 if (frame == [self mainFrame])
2970 _private->didDrawTiles = 0;
2973 #endif // PLATFORM(IOS)
2975 #if ENABLE(DASHBOARD_SUPPORT)
2977 #define DASHBOARD_CONTROL_LABEL @"control"
2979 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2981 NSRect adjustedBounds = bounds;
2982 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2983 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2984 adjustedBounds.size = bounds.size;
2986 NSRect adjustedClip;
2987 adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2988 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2989 adjustedClip.size = clip.size;
2991 WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds
2992 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2993 NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2994 if (!scrollerRegions) {
2995 scrollerRegions = [[NSMutableArray alloc] init];
2996 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2997 [scrollerRegions release];
2999 [scrollerRegions addObject:region];
3003 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3005 NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3007 for (const auto& widget: frameView->children()) {
3008 if (is<FrameView>(*widget)) {
3009 [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3013 if (!widget->isScrollbar())
3016 // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3017 // it's not common to need this to be correct in Dashboard widgets.
3018 NSRect bounds = widget->frameRect();
3019 [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3023 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3025 // Add scroller regions for NSScroller and WebCore scrollbars
3026 NSUInteger count = [views count];
3027 for (NSUInteger i = 0; i < count; i++) {
3028 NSView *view = [views objectAtIndex:i];
3030 if ([view isKindOfClass:[WebHTMLView class]]) {
3031 if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3032 if (FrameView* coreView = coreFrame->view())
3033 [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3035 } else if ([view isKindOfClass:[NSScroller class]]) {
3036 // AppKit places absent scrollers at -100,-100
3037 if ([view frame].origin.y < 0)
3039 [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3041 [self _addScrollerDashboardRegions:regions from:[view subviews]];
3045 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3047 [self _addScrollerDashboardRegions:regions from:[self subviews]];
3050 - (NSDictionary *)_dashboardRegions
3052 // Only return regions from main frame.
3053 Frame* mainFrame = [self _mainCoreFrame];
3057 const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3058 size_t size = regions.size();
3060 NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3061 for (size_t i = 0; i < size; i++) {
3062 const AnnotatedRegionValue& region = regions[i];
3064 if (region.type == StyleDashboardRegion::None)
3067 NSString *label = region.label;
3068 WebDashboardRegionType type = WebDashboardRegionTypeNone;
3069 if (region.type == StyleDashboardRegion::Circle)
3070 type = WebDashboardRegionTypeCircle;
3071 else if (region.type == StyleDashboardRegion::Rectangle)
3072 type = WebDashboardRegionTypeRectangle;
3073 NSMutableArray *regionValues = [webRegions objectForKey:label];
3074 if (!regionValues) {
3075 regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3076 [webRegions setObject:regionValues forKey:label];
3077 [regionValues release];
3080 WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3081 [regionValues addObject:webRegion];
3082 [webRegion release];
3085 [self _addScrollerDashboardRegions:webRegions];
3090 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3092 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
3093 // specific support for the backward compatibility mode flag.
3094 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3095 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3098 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3099 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3102 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3103 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3106 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3107 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3110 case WebDashboardBehaviorAllowWheelScrolling: {
3111 _private->dashboardBehaviorAllowWheelScrolling = flag;
3114 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3116 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3117 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3118 RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3124 // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3125 // compatibility mode. See <rdar://problem/8175982>.
3127 _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3130 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3133 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3134 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3136 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3137 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3139 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3140 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3142 case WebDashboardBehaviorAllowWheelScrolling: {
3143 return _private->dashboardBehaviorAllowWheelScrolling;
3145 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3146 return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3152 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3154 + (void)_setShouldUseFontSmoothing:(BOOL)f
3156 Font::setShouldUseSmoothing(f);
3159 + (BOOL)_shouldUseFontSmoothing
3161 return Font::shouldUseSmoothing();
3165 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3167 setUsesTestModeFocusRingColor(f);
3170 + (BOOL)_usesTestModeFocusRingColor
3172 return usesTestModeFocusRingColor();
3177 - (void)_setUIKitDelegate:(id)delegate
3179 _private->UIKitDelegate = delegate;
3180 [_private->UIKitDelegateForwarder clearTarget];
3181 [_private->UIKitDelegateForwarder release];
3182 _private->UIKitDelegateForwarder = nil;
3185 - (id)_UIKitDelegate
3187 return _private->UIKitDelegate;
3190 - (void)setWebMailDelegate:(id)delegate
3192 _private->WebMailDelegate = delegate;
3195 - (id)_webMailDelegate
3197 return _private->WebMailDelegate;
3200 - (id <WebCaretChangeListener>)caretChangeListener
3202 return _private->_caretChangeListener;
3205 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3207 _private->_caretChangeListener = listener;
3210 - (NSSet *)caretChangeListeners
3212 return _private->_caretChangeListeners;
3215 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3217 if (_private->_caretChangeListeners == nil) {
3218 _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3221 [_private->_caretChangeListeners addObject:listener];
3224 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3226 [_private->_caretChangeListeners removeObject:listener];
3229 - (void)removeAllCaretChangeListeners
3231 [_private->_caretChangeListeners removeAllObjects];
3234 - (void)caretChanged
3236 [_private->_caretChangeListener caretChanged];
3237 NSSet *copy = [_private->_caretChangeListeners copy];
3238 for (id <WebCaretChangeListener> listener in copy) {
3239 [listener caretChanged];
3244 - (void)_clearDelegates
3246 ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3248 [self _setFormDelegate:nil];
3249 [self _setUIKitDelegate:nil];
3250 [self setCaretChangeListener:nil];
3251 [self removeAllCaretChangeListeners];
3252 [self setWebMailDelegate:nil];
3254 [self setDownloadDelegate:nil];
3255 [self setEditingDelegate:nil];
3256 [self setFrameLoadDelegate:nil];
3257 [self setPolicyDelegate:nil];
3258 [self setResourceLoadDelegate:nil];
3259 [self setScriptDebugDelegate:nil];
3260 [self setUIDelegate:nil];
3263 - (NSURL *)_displayURL
3266 WebFrame *frame = [self mainFrame];
3267 // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3268 WebDataSource *dataSource = [frame provisionalDataSource];
3270 dataSource = [frame dataSource];
3271 NSURL *unreachableURL = [dataSource unreachableURL];
3272 NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3273 [[URL retain] autorelease];
3276 #endif // PLATFORM(IOS)
3279 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3281 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3283 [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3285 [scrollview setVerticalScrollingModeLocked:NO];
3286 [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3290 - (BOOL)alwaysShowVerticalScroller
3292 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3293 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3296 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3298 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3300 [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3302 [scrollview setHorizontalScrollingModeLocked:NO];
3303 [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3307 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3309 if (Frame* mainFrame = [self _mainCoreFrame])
3310 mainFrame->view()->setProhibitsScrolling(prohibits);
3313 - (BOOL)alwaysShowHorizontalScroller
3315 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3316 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3318 #endif // !PLATFORM(IOS)
3320 - (void)_setUseFastImageScalingMode:(BOOL)flag
3322 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3323 _private->page->setInLowQualityImageInterpolationMode(flag);
3324 [self setNeedsDisplay:YES];
3328 - (BOOL)_inFastImageScalingMode
3331 return _private->page->inLowQualityImageInterpolationMode();
3335 - (BOOL)_cookieEnabled
3338 return _private->page->settings().cookieEnabled();
3342 - (void)_setCookieEnabled:(BOOL)enable
3345 _private->page->settings().setCookieEnabled(enable);
3349 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3351 if (!_private->pluginDatabase)
3352 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3354 [_private->pluginDatabase setPlugInPaths:newPaths];
3355 [_private->pluginDatabase refresh];
3360 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3362 // Ask plug-ins in this frame
3363 id <WebDocumentView> documentView = [[frame frameView] documentView];
3364 if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3365 if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3369 // Ask plug-ins in child frames
3370 NSArray *childFrames = [frame childFrames];
3371 unsigned childCount = [childFrames count];
3372 unsigned childIndex;
3373 for (childIndex = 0; childIndex < childCount; childIndex++) {
3374 if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3381 - (BOOL)_pluginsAreRunning
3384 return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3387 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3389 // Send the message to plug-ins in this frame
3390 id <WebDocumentView> documentView = [[frame frameView] documentView];
3391 if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3392 [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3394 // Send the message to plug-ins in child frames
3395 NSArray *childFrames = [frame childFrames];
3396 unsigned childCount = [childFrames count];
3397 unsigned childIndex;
3398 for (childIndex = 0; childIndex < childCount; childIndex++) {
3399 [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3403 - (void)_destroyAllPlugIns
3406 [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3409 - (void)_clearBackForwardCache
3412 WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3413 BackForwardList* bfList = core([self backForwardList]);
3417 BOOL didClearBFCache = bfList->clearAllPageCaches();
3418 if (WebKit::MemoryMeasure::isLoggingEnabled())
3419 NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3423 - (void)_startAllPlugIns
3426 [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3429 - (void)_stopAllPlugIns
3432 [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3435 - (void)_stopAllPlugInsForPageCache
3438 [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3441 - (void)_restorePlugInsFromCache
3444 [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3447 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3451 Frame* mainCoreFrame = [self _mainCoreFrame];
3452 for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3453 FrameView* coreView = frame ? frame->view() : 0;
3457 // Get the GraphicsLayer for this widget.
3458 GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3459 if (!layerForWidget)
3462 if (layerForWidget->contentsLayerForMedia() != layer) {
3463 layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3464 // We need to make sure the layer hierachy change is applied immediately.
3465 if (mainCoreFrame->view())
3466 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3474 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3477 _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3479 #endif // PLATFORM(IOS)
3481 - (void)_attachScriptDebuggerToAllFrames
3483 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3484 [kit(frame) _attachScriptDebugger];
3487 - (void)_detachScriptDebuggerFromAllFrames
3489 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3490 [kit(frame) _detachScriptDebugger];
3494 - (void)setBackgroundColor:(NSColor *)backgroundColor
3496 if ([_private->backgroundColor isEqual:backgroundColor])
3499 id old = _private->backgroundColor;
3500 _private->backgroundColor = [backgroundColor retain];
3503 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3506 - (NSColor *)backgroundColor
3508 return _private->backgroundColor;
3511 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3513 if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3516 CFTypeRef old = _private->backgroundColor;
3517 CFRetain(backgroundColor);
3518 _private->backgroundColor = backgroundColor;
3521 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3524 - (CGColorRef)backgroundColor
3526 return _private->backgroundColor;
3530 - (BOOL)defersCallbacks
3532 if (!_private->page)
3534 return _private->page->defersLoading();
3537 - (void)setDefersCallbacks:(BOOL)defer
3539 if (!_private->page)
3541 return _private->page->setDefersLoading(defer);
3544 #if TARGET_OS_IPHONE && USE(QUICK_LOOK)
3545 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3547 NSString *uti = qlPreviewConverterUTIForURL(url);
3551 NSString *fileName = qlPreviewConverterFileNameForURL(url);
3555 return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3562 return _private->isStopping;
3567 return _private->closing;
3570 + (NSArray *)_productivityDocumentMIMETypes
3573 return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3579 - (void)_setAllowsMessaging:(BOOL)aFlag
3581 _private->allowsMessaging = aFlag;
3584 - (BOOL)_allowsMessaging
3586 return _private->allowsMessaging;
3589 - (void)_setFixedLayoutSize:(CGSize)size
3591 ASSERT(WebThreadIsLocked());
3592 _private->fixedLayoutSize = size;
3593 if (Frame* mainFrame = core([self mainFrame])) {
3594 IntSize newSize(size);
3595 mainFrame->view()->setFixedLayoutSize(newSize);
3596 mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3597 [self setNeedsDisplay:YES];
3601 - (CGSize)_fixedLayoutSize
3603 return _private->fixedLayoutSize;
3606 - (void)_synchronizeCustomFixedPositionLayoutRect
3608 ASSERT(WebThreadIsLocked());
3612 MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3613 if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3615 newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3616 _private->pendingFixedPositionLayoutRect = CGRectNull;