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 "WebAlternativeTextClient.h"
39 #import "WebApplicationCache.h"
40 #import "WebBackForwardListInternal.h"
41 #import "WebBaseNetscapePluginView.h"
43 #import "WebChromeClient.h"
44 #import "WebDOMOperationsPrivate.h"
45 #import "WebDataSourceInternal.h"
46 #import "WebDatabaseManagerPrivate.h"
47 #import "WebDefaultEditingDelegate.h"
48 #import "WebDefaultPolicyDelegate.h"
49 #import "WebDefaultUIDelegate.h"
50 #import "WebDelegateImplementationCaching.h"
51 #import "WebDeviceOrientationClient.h"
52 #import "WebDeviceOrientationProvider.h"
53 #import "WebDocument.h"
54 #import "WebDocumentInternal.h"
55 #import "WebDownload.h"
56 #import "WebDownloadInternal.h"
57 #import "WebDragClient.h"
58 #import "WebDynamicScrollBarsViewInternal.h"
59 #import "WebEditingDelegate.h"
60 #import "WebEditorClient.h"
61 #import "WebFormDelegatePrivate.h"
62 #import "WebFrameInternal.h"
63 #import "WebFrameLoaderClient.h"
64 #import "WebFrameNetworkingContext.h"
65 #import "WebFrameViewInternal.h"
66 #import "WebGeolocationClient.h"
67 #import "WebGeolocationPositionInternal.h"
68 #import "WebHTMLRepresentation.h"
69 #import "WebHTMLViewInternal.h"
70 #import "WebHistoryItemInternal.h"
71 #import "WebIconDatabaseInternal.h"
72 #import "WebInspector.h"
73 #import "WebInspectorClient.h"
74 #import "WebKitErrors.h"
75 #import "WebKitFullScreenListener.h"
76 #import "WebKitLogging.h"
77 #import "WebKitNSStringExtras.h"
78 #import "WebKitStatisticsPrivate.h"
79 #import "WebKitSystemBits.h"
80 #import "WebKitVersionChecks.h"
81 #import "WebLocalizableStrings.h"
82 #import "WebNSDataExtras.h"
83 #import "WebNSDataExtrasPrivate.h"
84 #import "WebNSDictionaryExtras.h"
85 #import "WebNSURLExtras.h"
86 #import "WebNSURLRequestExtras.h"
87 #import "WebNSViewExtras.h"
88 #import "WebNodeHighlight.h"
89 #import "WebNotificationClient.h"
90 #import "WebPDFView.h"
91 #import "WebPanelAuthenticationHandler.h"
92 #import "WebPlatformStrategies.h"
93 #import "WebPluginDatabase.h"
94 #import "WebPolicyDelegate.h"
95 #import "WebPreferenceKeysPrivate.h"
96 #import "WebPreferencesPrivate.h"
97 #import "WebProgressTrackerClient.h"
98 #import "WebScriptDebugDelegate.h"
99 #import "WebScriptWorldInternal.h"
100 #import "WebStorageManagerInternal.h"
101 #import "WebSystemInterface.h"
102 #import "WebTextCompletionController.h"
103 #import "WebTextIterator.h"
104 #import "WebUIDelegate.h"
105 #import "WebUIDelegatePrivate.h"
106 #import "WebUserMediaClient.h"
107 #import "WebViewGroup.h"
108 #import <CoreFoundation/CFSet.h>
109 #import <Foundation/NSURLConnection.h>
110 #import <JavaScriptCore/APICast.h>
111 #import <JavaScriptCore/JSValueRef.h>
112 #import <WebCore/AlternativeTextUIController.h>
113 #import <WebCore/AnimationController.h>
114 #import <WebCore/ApplicationCacheStorage.h>
115 #import <WebCore/BackForwardController.h>
116 #import <WebCore/BackForwardList.h>
117 #import <WebCore/MemoryCache.h>
118 #import <WebCore/Chrome.h>
119 #import <WebCore/ColorMac.h>
120 #import <WebCore/Cursor.h>
121 #import <WebCore/DatabaseManager.h>
122 #import <WebCore/Document.h>
123 #import <WebCore/DocumentLoader.h>
124 #import <WebCore/DragController.h>
125 #import <WebCore/DragData.h>
126 #import <WebCore/Editor.h>
127 #import <WebCore/EventHandler.h>
128 #import <WebCore/ExceptionHandlers.h>
129 #import <WebCore/FocusController.h>
130 #import <WebCore/FrameLoader.h>
131 #import <WebCore/FrameSelection.h>
132 #import <WebCore/FrameTree.h>
133 #import <WebCore/FrameView.h>
134 #import <WebCore/GCController.h>
135 #import <WebCore/GeolocationController.h>
136 #import <WebCore/GeolocationError.h>
137 #import <WebCore/HTMLMediaElement.h>
138 #import <WebCore/HTMLNames.h>
139 #import <WebCore/HistoryController.h>
140 #import <WebCore/HistoryItem.h>
141 #import <WebCore/IconDatabase.h>
142 #import <WebCore/JSCSSStyleDeclaration.h>
143 #import <WebCore/JSDocument.h>
144 #import <WebCore/JSElement.h>
145 #import <WebCore/JSNodeList.h>
146 #import <WebCore/JSNotification.h>
147 #import <WebCore/Logging.h>
148 #import <WebCore/MIMETypeRegistry.h>
149 #import <WebCore/MainFrame.h>
150 #import <WebCore/MemoryPressureHandler.h>
151 #import <WebCore/NodeList.h>
152 #import <WebCore/Notification.h>
153 #import <WebCore/NotificationController.h>
154 #import <WebCore/Page.h>
155 #import <WebCore/PageCache.h>
156 #import <WebCore/PageGroup.h>
157 #import <WebCore/PlatformEventFactoryMac.h>
158 #import <WebCore/ProgressTracker.h>
159 #import <WebCore/RenderView.h>
160 #import <WebCore/RenderWidget.h>
161 #import <WebCore/ResourceHandle.h>
162 #import <WebCore/ResourceLoadScheduler.h>
163 #import <WebCore/ResourceRequest.h>
164 #import <WebCore/RuntimeApplicationChecks.h>
165 #import <WebCore/RuntimeEnabledFeatures.h>
166 #import <WebCore/SchemeRegistry.h>
167 #import <WebCore/ScriptController.h>
168 #import <WebCore/SecurityOrigin.h>
169 #import <WebCore/SecurityPolicy.h>
170 #import <WebCore/Settings.h>
171 #import <WebCore/StyleProperties.h>
172 #import <WebCore/TextResourceDecoder.h>
173 #import <WebCore/ThreadCheck.h>
174 #import <WebCore/UserAgent.h>
175 #import <WebCore/WebCoreObjCExtras.h>
176 #import <WebCore/WebCoreView.h>
177 #import <WebCore/Widget.h>
178 #import <WebKitLegacy/DOM.h>
179 #import <WebKitLegacy/DOMExtensions.h>
180 #import <WebKitLegacy/DOMPrivate.h>
181 #import <WebKitSystemInterface.h>
182 #import <bindings/ScriptValue.h>
183 #import <mach-o/dyld.h>
184 #import <objc/objc-auto.h>
185 #import <objc/runtime.h>
186 #import <runtime/ArrayPrototype.h>
187 #import <runtime/DateInstance.h>
188 #import <runtime/InitializeThreading.h>
189 #import <runtime/JSLock.h>
190 #import <runtime/JSCJSValue.h>
191 #import <wtf/Assertions.h>
192 #import <wtf/HashTraits.h>
193 #import <wtf/MainThread.h>
194 #import <wtf/ObjcRuntimeExtras.h>
195 #import <wtf/RefCountedLeakCounter.h>
196 #import <wtf/RefPtr.h>
197 #import <wtf/RunLoop.h>
198 #import <wtf/StdLibExtras.h>
201 #import "WebContextMenuClient.h"
202 #import "WebFullScreenController.h"
203 #import "WebNSEventExtras.h"
204 #import "WebNSObjectExtras.h"
205 #import "WebNSPasteboardExtras.h"
206 #import "WebNSPrintOperationExtras.h"
207 #import "WebPDFView.h"
208 #import <WebCore/WebVideoFullscreenController.h>
210 #import "MemoryMeasure.h"
211 #import "WebCaretChangeListener.h"
212 #import "WebChromeClientIOS.h"
213 #import "WebDefaultFormDelegate.h"
214 #import "WebDefaultFrameLoadDelegate.h"
215 #import "WebDefaultResourceLoadDelegate.h"
216 #import "WebDefaultUIKitDelegate.h"
217 #import "WebFixedPositionContent.h"
218 #import "WebMailDelegate.h"
219 #import "WebNSUserDefaultsExtras.h"
220 #import "WebPDFViewIOS.h"
221 #import "WebPlainWhiteView.h"
222 #import "WebPluginController.h"
223 #import "WebPolicyDelegatePrivate.h"
224 #import "WebSQLiteDatabaseTrackerClient.h"
225 #import "WebStorageManagerPrivate.h"
226 #import "WebUIKitSupport.h"
227 #import "WebVisiblePosition.h"
228 #import <CFNetwork/CFURLCachePriv.h>
229 #import <MobileGestalt.h>
230 #import <WebCore/EventNames.h>
231 #import <WebCore/FontCache.h>
232 #import <WebCore/GraphicsLayer.h>
233 #import <WebCore/IconController.h>
234 #import <WebCore/LegacyTileCache.h>
235 #import <WebCore/NetworkStateNotifier.h>
236 #import <WebCore/RuntimeApplicationChecksIOS.h>
237 #import <WebCore/SQLiteDatabaseTracker.h>
238 #import <WebCore/SmartReplace.h>
239 #import <WebCore/TextRun.h>
240 #import <WebCore/TileControllerMemoryHandlerIOS.h>
241 #import <WebCore/WAKWindow.h>
242 #import <WebCore/WKView.h>
243 #import <WebCore/WebCoreThread.h>
244 #import <WebCore/WebCoreThreadMessage.h>
245 #import <WebCore/WebCoreThreadRun.h>
246 #import <WebCore/WebEvent.h>
247 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
248 #import <dispatch/private.h>
249 #import <wtf/FastMalloc.h>
250 #endif // !PLATFORM(IOS)
252 #if ENABLE(DASHBOARD_SUPPORT)
253 #import <WebKitLegacy/WebDashboardRegion.h>
256 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
257 #import "WebDiskImageCacheClientIOS.h"
258 #import <WebCore/DiskImageCacheIOS.h>
261 #if ENABLE(REMOTE_INSPECTOR)
262 #import <JavaScriptCore/RemoteInspector.h>
264 #import "WebIndicateLayer.h"
273 #include <WebCore/QuickLook.h>
276 #if ENABLE(TOUCH_EVENTS)
277 #import <WebCore/WebEventRegion.h>
280 #if ENABLE(DISK_IMAGE_CACHE)
281 #import "WebDiskImageCacheClientIOS.h"
282 #import <WebCore/DiskImageCacheIOS.h>
286 @interface NSSpellChecker (WebNSSpellCheckerDetails)
287 - (void)_preflightChosenSpellServer;
290 @interface NSView (WebNSViewDetails)
291 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
292 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
293 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
296 @interface NSWindow (WebNSWindowDetails)
297 - (id)_oldFirstResponderBeforeBecoming;
298 - (void)_enableScreenUpdatesIfNeeded;
299 - (BOOL)_wrapsCarbonWindow;
300 - (BOOL)_hasKeyAppearance;
305 using namespace Inspector;
306 using namespace WebCore;
308 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
310 macro(alignJustified) \
313 macro(capitalizeWord) \
314 macro(centerSelectionInVisibleArea) \
315 macro(changeAttributes) \
316 macro(changeBaseWritingDirection) \
317 macro(changeBaseWritingDirectionToLTR) \
318 macro(changeBaseWritingDirectionToRTL) \
320 macro(changeDocumentBackgroundColor) \
322 macro(changeSpelling) \
323 macro(checkSpelling) \
329 macro(deleteBackward) \
330 macro(deleteBackwardByDecomposingPreviousCharacter) \
331 macro(deleteForward) \
332 macro(deleteToBeginningOfLine) \
333 macro(deleteToBeginningOfParagraph) \
334 macro(deleteToEndOfLine) \
335 macro(deleteToEndOfParagraph) \
336 macro(deleteToMark) \
337 macro(deleteWordBackward) \
338 macro(deleteWordForward) \
339 macro(ignoreSpelling) \
341 macro(insertBacktab) \
342 macro(insertLineBreak) \
343 macro(insertNewline) \
344 macro(insertNewlineIgnoringFieldEditor) \
345 macro(insertParagraphSeparator) \
347 macro(insertTabIgnoringFieldEditor) \
348 macro(lowercaseWord) \
349 macro(makeBaseWritingDirectionLeftToRight) \
350 macro(makeBaseWritingDirectionRightToLeft) \
351 macro(makeTextWritingDirectionLeftToRight) \
352 macro(makeTextWritingDirectionNatural) \
353 macro(makeTextWritingDirectionRightToLeft) \
354 macro(moveBackward) \
355 macro(moveBackwardAndModifySelection) \
357 macro(moveDownAndModifySelection) \
359 macro(moveForwardAndModifySelection) \
361 macro(moveLeftAndModifySelection) \
362 macro(moveParagraphBackwardAndModifySelection) \
363 macro(moveParagraphForwardAndModifySelection) \
365 macro(moveRightAndModifySelection) \
366 macro(moveToBeginningOfDocument) \
367 macro(moveToBeginningOfDocumentAndModifySelection) \
368 macro(moveToBeginningOfLine) \
369 macro(moveToBeginningOfLineAndModifySelection) \
370 macro(moveToBeginningOfParagraph) \
371 macro(moveToBeginningOfParagraphAndModifySelection) \
372 macro(moveToBeginningOfSentence) \
373 macro(moveToBeginningOfSentenceAndModifySelection) \
374 macro(moveToEndOfDocument) \
375 macro(moveToEndOfDocumentAndModifySelection) \
376 macro(moveToEndOfLine) \
377 macro(moveToEndOfLineAndModifySelection) \
378 macro(moveToEndOfParagraph) \
379 macro(moveToEndOfParagraphAndModifySelection) \
380 macro(moveToEndOfSentence) \
381 macro(moveToEndOfSentenceAndModifySelection) \
382 macro(moveToLeftEndOfLine) \
383 macro(moveToLeftEndOfLineAndModifySelection) \
384 macro(moveToRightEndOfLine) \
385 macro(moveToRightEndOfLineAndModifySelection) \
387 macro(moveUpAndModifySelection) \
388 macro(moveWordBackward) \
389 macro(moveWordBackwardAndModifySelection) \
390 macro(moveWordForward) \
391 macro(moveWordForwardAndModifySelection) \
392 macro(moveWordLeft) \
393 macro(moveWordLeftAndModifySelection) \
394 macro(moveWordRight) \
395 macro(moveWordRightAndModifySelection) \
396 macro(orderFrontSubstitutionsPanel) \
400 macro(pageDownAndModifySelection) \
402 macro(pageUpAndModifySelection) \
404 macro(pasteAsPlainText) \
405 macro(pasteAsRichText) \
407 macro(performFindPanelAction) \
408 macro(scrollLineDown) \
409 macro(scrollLineUp) \
410 macro(scrollPageDown) \
411 macro(scrollPageUp) \
412 macro(scrollToBeginningOfDocument) \
413 macro(scrollToEndOfDocument) \
416 macro(selectParagraph) \
417 macro(selectSentence) \
418 macro(selectToMark) \
421 macro(showGuessPanel) \
422 macro(startSpeaking) \
423 macro(stopSpeaking) \
426 macro(swapWithMark) \
427 macro(takeFindStringFromSelection) \
428 macro(toggleBaseWritingDirection) \
432 macro(uppercaseWord) \
434 macro(yankAndSelect) \
436 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
437 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
439 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
440 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
442 static BOOL s_didSetCacheModel;
443 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
446 static Class s_pdfRepresentationClass;
447 static Class s_pdfViewClass;
451 static const char webViewIsOpen[] = "At least one WebView is still open.";
455 @interface WebView(WebViewPrivate)
456 - (void)_preferencesChanged:(WebPreferences *)preferences;
457 - (void)_updateScreenScaleFromWindow;
460 @interface NSURLCache (WebPrivate)
461 - (CFURLCacheRef)_CFURLCache;
466 @interface NSObject (WebValidateWithoutDelegate)
467 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
472 @class _WebSafeForwarder;
474 @interface _WebSafeAsyncForwarder : NSObject {
475 _WebSafeForwarder *_forwarder;
477 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
481 @interface _WebSafeForwarder : NSObject
483 id target; // Non-retained. Don't retain delegates.
486 _WebSafeAsyncForwarder *asyncForwarder;
487 dispatch_once_t asyncForwarderPred;
490 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
493 - (id)asyncForwarder;
497 FindOptions coreOptions(WebFindOptions options)
499 return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
500 | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
501 | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
502 | (options & WebFindOptionsBackwards ? Backwards : 0)
503 | (options & WebFindOptionsWrapAround ? WrapAround : 0)
504 | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
507 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
509 return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
510 | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
511 | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
514 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
516 return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
517 | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
518 | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
521 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
523 switch (visibilityState) {
524 case PageVisibilityStateVisible:
525 return WebPageVisibilityStateVisible;
526 case PageVisibilityStateHidden:
527 return WebPageVisibilityStateHidden;
528 case PageVisibilityStatePrerender:
529 return WebPageVisibilityStatePrerender;
532 ASSERT_NOT_REACHED();
533 return WebPageVisibilityStateVisible;
536 @interface WebView (WebFileInternal)
538 - (float)_deviceScaleFactor;
541 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
542 - (WebFrame *)_focusedFrame;
543 + (void)_preflightSpellChecker;
544 - (BOOL)_continuousCheckingAllowed;
545 - (NSResponder *)_responderForResponderOperations;
547 - (void)_clearGlibLoopObserver;
551 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
552 NSString *WebElementFrameKey = @"WebElementFrame";
553 NSString *WebElementImageKey = @"WebElementImage";
554 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
555 NSString *WebElementImageRectKey = @"WebElementImageRect";
556 NSString *WebElementImageURLKey = @"WebElementImageURL";
557 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
558 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
559 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
560 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
561 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
562 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
563 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
564 NSString *WebElementTitleKey = @"WebElementTitle";
565 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
566 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
567 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
569 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
570 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
572 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
574 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
575 NSString * const WebViewProgressBackgroundColorKey = @"WebProgressBackgroundColorKey";
578 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
579 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
580 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
581 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
582 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
584 enum { WebViewVersion = 4 };
586 #define timedLayoutSize 4096
588 static NSMutableSet *schemesWithRepresentationsSet;
591 NSString *_WebCanGoBackKey = @"canGoBack";
592 NSString *_WebCanGoForwardKey = @"canGoForward";
593 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
594 NSString *_WebIsLoadingKey = @"isLoading";
595 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
596 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
597 NSString *_WebMainFrameURLKey = @"mainFrameURL";
598 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
602 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
603 NSString *WebQuickLookUTIKey = @"WebQuickLookUTIKey";
606 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
607 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
609 #if ENABLE(REMOTE_INSPECTOR)
610 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
611 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
614 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
616 @interface WebProgressItem : NSObject
619 long long bytesReceived;
620 long long estimatedLength;
624 @implementation WebProgressItem
627 static BOOL continuousSpellCheckingEnabled;
629 static BOOL grammarCheckingEnabled;
630 static BOOL automaticQuoteSubstitutionEnabled;
631 static BOOL automaticLinkDetectionEnabled;
632 static BOOL automaticDashSubstitutionEnabled;
633 static BOOL automaticTextReplacementEnabled;
634 static BOOL automaticSpellingCorrectionEnabled;
637 @implementation WebView (AllWebViews)
639 static CFSetCallBacks NonRetainingSetCallbacks = {
648 static CFMutableSetRef allWebViewsSet;
650 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
655 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
658 - (void)_removeFromAllWebViewsSet
661 CFSetRemoveValue(allWebViewsSet, self);
664 - (void)_addToAllWebViewsSet
667 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
669 CFSetSetValue(allWebViewsSet, self);
674 @implementation WebView (WebPrivate)
676 static String userVisibleWebKitVersionString()
678 // If the version is longer than 3 digits then the leading digits represent the version of the OS. Our user agent
679 // string should not include the leading digits, so strip them off and report the rest as the version. <rdar://problem/4997547>
680 NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
681 NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
682 if (nonDigitRange.location == NSNotFound && fullVersion.length > 3)
683 return [fullVersion substringFromIndex:fullVersion.length - 3];
684 if (nonDigitRange.location != NSNotFound && nonDigitRange.location > 3)
685 return [fullVersion substringFromIndex:nonDigitRange.location - 3];
689 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
691 return standardUserAgentWithApplicationName(applicationName, userVisibleWebKitVersionString());
695 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
697 [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
700 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
702 [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
704 #endif // PLATFORM(IOS)
706 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
708 if (!exception || !context)
711 JSC::ExecState* execState = toJS(context);
712 JSLockHolder lock(execState);
714 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
715 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
718 reportException(execState, toJS(execState, exception));
721 static void WebKitInitializeApplicationCachePathIfNecessary()
723 static BOOL initialized = NO;
727 NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
729 appName = [[NSProcessInfo processInfo] processName];
731 if (WebCore::applicationIsMobileSafari() || WebCore::applicationIsWebApp())
732 appName = @"com.apple.WebAppCache";
737 NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
739 cacheStorage().setCacheDirectory(cacheDir);
743 static bool shouldEnableLoadDeferring()
745 return !applicationIsAdobeInstaller();
748 static bool shouldRestrictWindowFocus()
753 return !applicationIsHRBlock();
757 - (void)_dispatchPendingLoadRequests
759 resourceLoadScheduler()->servePendingRequests();
763 - (void)_registerDraggedTypes
765 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
766 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
767 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
768 [types addObjectsFromArray:URLTypes];
769 [self registerForDraggedTypes:[types allObjects]];
773 static bool needsOutlookQuirksScript()
775 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
776 && applicationIsMicrosoftOutlook();
777 return isOutlookNeedingQuirksScript;
780 static NSString *leakOutlookQuirksUserScriptContents()
782 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
783 NSStringEncoding encoding;
784 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
787 -(void)_injectOutlookQuirksScript
789 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
790 core(self)->group().addUserScriptToWorld(*core([WebScriptWorld world]),
791 outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames);
795 static bool shouldRespectPriorityInCSSAttributeSetters()
798 static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
799 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
800 return isStanzaNeedingAttributeSetterQuirk;
802 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
803 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
804 return isIAdProducerNeedingAttributeSetterQuirk;
809 static bool shouldTransformsAffectOverflow()
811 static bool shouldTransformsAffectOverflow = !applicationIsOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
812 return shouldTransformsAffectOverflow;
815 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
817 static bool shouldDispatchJavaScriptWindowOnErrorEvents = !applicationIsFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
818 return shouldDispatchJavaScriptWindowOnErrorEvents;
821 static bool isInternalInstall()
823 static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
827 static bool didOneTimeInitialization = false;
830 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
833 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
835 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = applicationIsVersions()
836 && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
838 return shouldUseLegacyBackgroundSizeShorthandBehavior;
841 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
843 WebCoreThreadViolationCheckRoundTwo();
846 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
849 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
850 [standardPreferences willAddToWebView];
852 _private->preferences = [standardPreferences retain];
853 _private->mainFrameDocumentReady = NO;
854 _private->drawsBackground = YES;
856 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
858 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
860 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
862 NSRect f = [self frame];
863 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
864 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
865 [self addSubview:frameView];
869 static bool didOneTimeInitialization = false;
871 if (!didOneTimeInitialization) {
873 WebKitInitializeLoggingChannelsIfNecessary();
874 WebCore::initializeLoggingChannelsIfNecessary();
875 #endif // !LOG_DISABLED
877 // Initialize our platform strategies first before invoking the rest
878 // of the initialization code which may depend on the strategies.
879 WebPlatformStrategies::initializeIfNecessary();
881 #if ENABLE(SQL_DATABASE)
883 // Set the WebSQLiteDatabaseTrackerClient.
884 SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
886 if ([standardPreferences databasesEnabled])
888 [WebDatabaseManager sharedWebDatabaseManager];
892 if ([standardPreferences storageTrackerEnabled])
894 WebKitInitializeStorageIfNecessary();
895 WebKitInitializeApplicationCachePathIfNecessary();
896 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
897 WebKitInitializeWebDiskImageCache();
900 Settings::setDefaultMinDOMTimerInterval(0.004);
902 Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
905 if (applicationIsMobileSafari())
906 Settings::setShouldManageAudioSession(true);
909 didOneTimeInitialization = true;
912 Page::PageClients pageClients;
914 pageClients.chromeClient = new WebChromeClient(self);
915 pageClients.contextMenuClient = new WebContextMenuClient(self);
916 #if ENABLE(DRAG_SUPPORT)
917 pageClients.dragClient = new WebDragClient(self);
919 pageClients.inspectorClient = new WebInspectorClient(self);
921 pageClients.chromeClient = new WebChromeClientIOS(self);
922 pageClients.inspectorClient = new WebInspectorClient(self);
924 pageClients.editorClient = new WebEditorClient(self);
925 pageClients.alternativeTextClient = new WebAlternativeTextClient(self);
926 pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
927 pageClients.progressTrackerClient = new WebProgressTrackerClient(self);
928 _private->page = new Page(pageClients);
929 #if ENABLE(GEOLOCATION)
930 WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
932 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
933 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
935 #if ENABLE(DEVICE_ORIENTATION)
937 WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
940 #if ENABLE(MEDIA_STREAM)
941 WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
944 #if ENABLE(REMOTE_INSPECTOR)
945 _private->page->setRemoteInspectionAllowed(true);
948 _private->page->setCanStartMedia([self window]);
949 _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
950 _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
953 if (needsOutlookQuirksScript()) {
954 _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
955 [self _injectOutlookQuirksScript];
960 // Preserve the behavior we had before <rdar://problem/7580867>
961 // by enforcing a 5MB limit for session storage.
962 _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
964 [self _updateScreenScaleFromWindow];
965 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
966 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
967 _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
970 if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
971 [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
973 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
976 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
978 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
979 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
981 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
984 [self _addToAllWebViewsSet];
985 [self setGroupName:groupName];
987 // If there's already a next key view (e.g., from a nib), wire it up to our
988 // contained frame view. In any case, wire our next key view up to the our
989 // contained frame view. This works together with our becomeFirstResponder
990 // and setNextKeyView overrides.
991 NSView *nextKeyView = [self nextKeyView];
992 if (nextKeyView && nextKeyView != frameView)
993 [frameView setNextKeyView:nextKeyView];
994 [super setNextKeyView:frameView];
996 if ([[self class] shouldIncludeInWebKitStatistics])
1000 [self _registerDraggedTypes];
1003 [self _setIsVisible:[self _isViewVisible]];
1005 WebPreferences *prefs = [self preferences];
1006 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1007 name:WebPreferencesChangedInternalNotification object:prefs];
1010 [self _preferencesChanged:[self preferences]];
1011 [[self preferences] _postPreferencesChangedAPINotification];
1013 // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1014 // and prefs need to be changed synchronously <rdar://problem/5841558>
1015 [self _preferencesChanged:prefs];
1016 _private->page->settings().setFontFallbackPrefersPictographs(true);
1019 memoryPressureHandler().install();
1021 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1022 // Originally, we allowed all local loads.
1023 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1024 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1025 // Later, we allowed local loads for local URLs and documents loaded
1026 // with substitute data.
1027 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1031 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1032 ResourceHandle::forceContentSniffing();
1036 [self _scheduleGlibContextIterations];
1040 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
1042 // FIXME: Remove the usesDocumentViews parameter; it's only here for compatibility with WebKit nightly builds
1043 // running against Safari 5 on Leopard.
1044 ASSERT(usesDocumentViews);
1046 self = [super initWithFrame:f];
1050 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1051 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1052 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1053 // need for Safari to unset it to prevent it from being passed to applications it launches.
1054 // Unsetting it when a WebView is first created is as good a place as any.
1055 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1056 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1057 unsetenv("DYLD_FRAMEWORK_PATH");
1058 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1062 _private = [[WebViewPrivate alloc] init];
1063 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1064 [self setMaintainsBackForwardList: YES];
1066 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1071 - (void)_viewWillDrawInternal
1073 Frame* frame = [self _mainCoreFrame];
1074 if (frame && frame->view())
1075 frame->view()->updateLayoutAndStyleIfNeededRecursive();
1078 + (NSArray *)_supportedMIMETypes
1080 // Load the plug-in DB allowing plug-ins to install types.
1081 [WebPluginDatabase sharedDatabase];
1082 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1086 + (NSArray *)_supportedFileExtensions
1088 NSMutableSet *extensions = [[NSMutableSet alloc] init];
1089 NSArray *MIMETypes = [self _supportedMIMETypes];
1090 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1092 while ((MIMEType = [enumerator nextObject]) != nil) {
1093 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
1094 if (extensionsForType) {
1095 [extensions addObjectsFromArray:extensionsForType];
1098 NSArray *uniqueExtensions = [extensions allObjects];
1099 [extensions release];
1100 return uniqueExtensions;
1105 + (void)enableWebThread
1107 static BOOL isWebThreadEnabled = NO;
1108 if (!isWebThreadEnabled) {
1109 WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1110 WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1111 WebCoreObjCDeallocOnWebThread([WebFrame class]);
1112 WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1113 WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1114 WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1115 WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1116 WebCoreObjCDeallocOnWebThread([WebView class]);
1117 WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1118 if (applicationIsTheEconomistOnIPhone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1119 WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1121 isWebThreadEnabled = YES;
1125 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1127 self = [super initWithFrame:frame];
1131 _private = [[WebViewPrivate alloc] init];
1134 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1138 preferences = [WebPreferences standardPreferences];
1139 [preferences willAddToWebView];
1141 _private->preferences = [preferences retain];
1142 _private->mainFrameDocumentReady = NO;
1143 _private->drawsBackground = YES;
1144 _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
1146 WebFrameView *frameView = nil;
1147 frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1148 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1149 [self addSubview:frameView];
1150 [frameView release];
1153 Page::PageClients pageClients;
1154 pageClients.chromeClient = new WebChromeClientIOS(self);
1155 #if ENABLE(DRAG_SUPPORT)
1156 pageClients.dragClient = new WebDragClient(self);
1158 pageClients.editorClient = new WebEditorClient(self);
1159 pageClients.inspectorClient = new WebInspectorClient(self);
1160 pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
1161 pageClients.progressTrackerClient = new WebProgressTrackerClient(self);
1162 _private->page = new Page(pageClients);
1164 [self setSmartInsertDeleteEnabled:YES];
1166 // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1167 // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1168 // This matches how UIKit sets up the preferences. We need to set default values for fonts though, <rdar://problem/6850611>.
1169 // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1170 _private->page->settings().setMinimumLogicalFontSize(9);
1171 _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1172 _private->page->settings().setDefaultFixedFontSize(13);
1173 _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1174 _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1175 _private->page->settings().setScreenFontSubstitutionEnabled(false);
1177 // FIXME: <rdar://problem/7394370> Always use primary font baseline in text field base line calculation, ignore fallback fonts.
1178 _private->page->settings().setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
1180 _private->page->settings().setFontFallbackPrefersPictographs(true);
1181 _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1183 // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1184 _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1186 // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1187 _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1189 [self setGroupName:groupName];
1191 #if ENABLE(REMOTE_INSPECTOR)
1192 // Production installs always disallow debugging simple HTML documents.
1193 // Internal installs allow debugging simple HTML documents (TextFields) if the Internal Setting is enabled.
1194 if (!isInternalInstall())
1195 _private->page->setRemoteInspectionAllowed(false);
1197 static BOOL textFieldInspectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebKitTextFieldRemoteInspectionEnabledPreferenceKey];
1198 _private->page->setRemoteInspectionAllowed(textFieldInspectionEnabled);
1202 [self _updateScreenScaleFromWindow];
1203 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1204 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1206 [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1208 [self _addToAllWebViewsSet];
1212 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1217 + (void)_handleMemoryWarning
1219 ASSERT(WebThreadIsCurrent());
1220 WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1222 // Always peform the following.
1223 [WebView purgeInactiveFontData];
1225 // Only perform the remaining if a non-simple document was created.
1226 if (!didOneTimeInitialization)
1229 tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1231 #if ENABLE(DISK_IMAGE_CACHE)
1233 WebKit::MemoryMeasure measurer("Memory warning: flushing images to disk.");
1234 WebCore::memoryCache()->flushCachedImagesToDisk();
1238 [WebStorageManager closeIdleLocalStorageDatabases];
1240 [WebView _releaseMemoryNow];
1243 + (void)registerForMemoryNotifications
1245 BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::applicationIsMobileSafari();
1247 memoryPressureHandler().installMemoryReleaseBlock(^{
1248 [WebView _handleMemoryWarning];
1249 }, shouldAutoClearPressureOnMemoryRelease);
1251 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1252 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));
1254 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));
1256 dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1257 // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1258 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1261 dispatch_resume(memoryNotificationEventSource);
1263 if (!shouldAutoClearPressureOnMemoryRelease) {
1264 // Listen to memory status notification to reset the memory pressure flag.
1265 static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS,
1267 DISPATCH_MEMORYSTATUS_PRESSURE_WARN | DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL,
1268 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1269 dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1270 unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1271 if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL)
1272 memoryPressureHandler().clearMemoryPressure();
1273 else if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_WARN)
1274 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1277 dispatch_resume(memoryStatusEventSource);
1281 + (void)_releaseMemoryNow
1283 ASSERT(WebThreadIsCurrent());
1284 [WebView discardAllCompiledCode];
1285 [WebView garbageCollectNow];
1286 [WebView purgeInactiveFontData];
1287 [WebView drainLayerPool];
1288 [WebCache emptyInMemoryResources];
1289 [WebView releaseFastMallocMemoryOnCurrentThread];
1291 dispatch_async(dispatch_get_main_queue(), ^{
1292 // Clear the main thread's TCMalloc thread cache.
1293 [WebView releaseFastMallocMemoryOnCurrentThread];
1297 + (void)_clearPrivateBrowsingSessionCookieStorage
1299 WebFrameNetworkingContext::clearPrivateBrowsingSessionCookieStorage();
1302 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1304 Frame* frame = [self _mainCoreFrame];
1306 frame->loader().history().replaceCurrentItem(core(item));
1309 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1312 [WebView _releaseMemoryNow];
1313 dispatch_async(dispatch_get_main_queue(), handler);
1317 + (void)releaseFastMallocMemoryOnCurrentThread
1319 WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1320 WTF::releaseFastMallocFreeMemory();
1323 + (void)garbageCollectNow
1325 ASSERT(WebThreadIsCurrent());
1326 WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1327 gcController().garbageCollectNow();
1330 + (void)purgeInactiveFontData
1332 ASSERT(WebThreadIsCurrent());
1333 WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1334 fontCache().purgeInactiveFontData();
1337 + (void)drainLayerPool
1339 ASSERT(WebThreadIsCurrent());
1340 WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1341 WebCore::LegacyTileCache::drainLayerPool();
1344 + (void)discardAllCompiledCode
1346 ASSERT(WebThreadIsCurrent());
1347 WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1348 gcController().discardAllCompiledCode();
1351 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1353 return WebCore::isCharacterSmartReplaceExempt(character, b);
1356 - (void)updateLayoutIgnorePendingStyleSheets
1359 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1360 Document *document = frame->document();
1362 document->updateLayoutIgnorePendingStylesheets();
1366 #endif // PLATFORM(IOS)
1368 static NSMutableSet *knownPluginMIMETypes()
1370 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1375 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1377 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1378 [knownPluginMIMETypes() addObject:MIMEType];
1381 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1383 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1384 [knownPluginMIMETypes() removeObject:MIMEType];
1387 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1389 MIMEType = [MIMEType lowercaseString];
1390 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1391 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1394 #define WebPDFView ([WebView _getPDFViewClass])
1396 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1400 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1403 // Load the plug-in DB allowing plug-ins to install types.
1404 [WebPluginDatabase sharedDatabase];
1407 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1408 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1409 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1412 if (viewClass && repClass) {
1413 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1414 // Special-case WebHTMLView for text types that shouldn't be shown.
1415 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1418 // If the MIME type is a known plug-in we might not want to load it.
1419 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1420 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1421 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1423 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1424 if (!isSupportedByWebKit)
1429 *vClass = viewClass;
1438 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1440 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1443 if (_private->pluginDatabase) {
1444 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1445 if (pluginPackage) {
1447 *vClass = [WebHTMLView class];
1449 *rClass = [WebHTMLRepresentation class];
1458 + (void)_setAlwaysUseATSU:(BOOL)f
1460 [self _setAlwaysUsesComplexTextCodePath:f];
1464 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1466 Font::setCodePath(f ? Font::Complex : Font::Auto);
1469 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1471 TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1474 + (BOOL)_allowsRoundingHacks
1476 return TextRun::allowsRoundingHacks();
1479 + (BOOL)canCloseAllWebViews
1481 return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1484 + (void)closeAllWebViews
1486 DOMWindow::dispatchAllPendingUnloadEvents();
1488 // This will close the WebViews in a random order. Change this if close order is important.
1489 // Make a new set to avoid mutating the set we are enumerating.
1490 NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet];
1491 NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1492 while (WebView *webView = [enumerator nextObject])
1496 + (BOOL)canShowFile:(NSString *)path
1498 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1502 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1504 return WKGetPreferredExtensionForMIMEType(type);
1510 return !_private || _private->closed;
1514 - (void)_dispatchUnloadEvent
1517 WebFrame *mainFrame = [self mainFrame];
1518 Frame *coreMainFrame = core(mainFrame);
1519 if (coreMainFrame) {
1520 Document *document = coreMainFrame->document();
1522 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1527 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1529 WebFrame *mainFrame = [self mainFrame];
1530 Frame *coreMainFrame = core(mainFrame);
1533 return coreMainFrame->styleAtSelectionStart();
1536 - (NSUInteger)_renderTreeSize
1538 if (!_private->page)
1540 return _private->page->renderTreeSize();
1543 - (void)_dispatchTileDidDraw:(CALayer*)tile
1545 id mailDelegate = [self _webMailDelegate];
1546 if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1547 [mailDelegate _webthread_webView:self tileDidDraw:tile];
1551 if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1556 [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1559 - (void)_willStartScrollingOrZooming
1561 // Pause timers during top level interaction
1562 if (_private->mainViewIsScrollingOrZooming)
1564 _private->mainViewIsScrollingOrZooming = YES;
1566 // This suspends active DOM objects like timers, but not media.
1567 [[self mainFrame] setTimeoutsPaused:YES];
1569 // This defers loading callbacks only.
1570 // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1571 [self setDefersCallbacks:YES];
1574 - (void)_didFinishScrollingOrZooming
1576 if (!_private->mainViewIsScrollingOrZooming)
1578 _private->mainViewIsScrollingOrZooming = NO;
1579 [self setDefersCallbacks:NO];
1580 [[self mainFrame] setTimeoutsPaused:NO];
1583 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1586 resourceLoadScheduler()->suspendPendingRequests();
1588 resourceLoadScheduler()->resumePendingRequests();
1591 + (void)_setAcceleratedImageDecoding:(BOOL)enabled
1593 ImageSource::setAcceleratedImageDecodingEnabled(enabled);
1596 + (BOOL)_acceleratedImageDecoding
1598 return ImageSource::acceleratedImageDecodingEnabled();
1601 + (void)_setAllowCookies:(BOOL)allow
1603 ResourceRequestBase::setDefaultAllowCookies(allow);
1606 + (BOOL)_allowCookies
1608 return ResourceRequestBase::defaultAllowCookies();
1611 + (BOOL)_isUnderMemoryPressure
1613 return memoryPressureHandler().isUnderMemoryPressure();
1616 + (void)_clearMemoryPressure
1618 memoryPressureHandler().clearMemoryPressure();
1621 + (BOOL)_shouldWaitForMemoryClearMessage
1623 return memoryPressureHandler().shouldWaitForMemoryClearMessage();
1625 #endif // PLATFORM(IOS)
1627 - (void)_closePluginDatabases
1629 pluginDatabaseClientCount--;
1631 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1634 // Unload the WebView local plug-in database.
1635 if (_private->pluginDatabase) {
1636 [_private->pluginDatabase destroyAllPluginInstanceViews];
1637 [_private->pluginDatabase close];
1638 [_private->pluginDatabase release];
1639 _private->pluginDatabase = nil;
1643 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1644 if (!pluginDatabaseClientCount && applicationIsTerminating)
1645 [WebPluginDatabase closeSharedDatabase];
1648 - (void)_closeWithFastTeardown
1651 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1655 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1657 [[NSNotificationCenter defaultCenter] removeObserver:self];
1659 [self _closePluginDatabases];
1662 static bool fastDocumentTeardownEnabled()
1665 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1667 static bool initialized = false;
1668 static bool enabled = false;
1670 // This allows debug builds to default to not have fast teardown, so leak checking still works.
1671 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1672 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1674 enabled = ![setting boolValue];
1681 // _close is here only for backward compatibility; clients and subclasses should use
1682 // public method -close instead.
1686 // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1687 // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1689 [self _clearDelegates];
1691 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1695 if (!_private || _private->closed)
1698 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1700 _private->closed = YES;
1701 [self _removeFromAllWebViewsSet];
1704 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1707 // To quit the apps fast we skip document teardown, except plugins
1708 // need to be destroyed and unloaded.
1709 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1710 [self _closeWithFastTeardown];
1714 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1715 [self _exitFullscreen];
1719 _private->closing = YES;
1722 if (Frame* mainFrame = [self _mainCoreFrame])
1723 mainFrame->loader().detachFromParent();
1725 [self setHostWindow:nil];
1728 [self setDownloadDelegate:nil];
1729 [self setEditingDelegate:nil];
1730 [self setFrameLoadDelegate:nil];
1731 [self setPolicyDelegate:nil];
1732 [self setResourceLoadDelegate:nil];
1733 [self setScriptDebugDelegate:nil];
1734 [self setUIDelegate:nil];
1736 [_private->inspector webViewClosed];
1740 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1741 [self removeDragCaret];
1744 _private->group->removeWebView(self);
1746 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1747 // all the plug-ins in the page cache to break any retain cycles.
1748 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1749 Page* page = _private->page;
1754 if (_private->hasSpellCheckerDocumentTag) {
1755 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1756 _private->hasSpellCheckerDocumentTag = NO;
1760 if (_private->layerFlushController) {
1761 _private->layerFlushController->invalidate();
1762 _private->layerFlushController = nullptr;
1766 [self _clearGlibLoopObserver];
1769 [[self _notificationProvider] unregisterWebView:self];
1772 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1774 [[NSNotificationCenter defaultCenter] removeObserver:self];
1776 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1778 WebPreferences *preferences = _private->preferences;
1779 _private->preferences = nil;
1780 [preferences didRemoveFromWebView];
1781 [preferences release];
1783 [self _closePluginDatabases];
1786 // Need this to make leak messages accurate.
1787 if (applicationIsTerminating) {
1788 gcController().garbageCollectNow();
1789 [WebCache setDisabled:YES];
1793 // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1798 // Indicates if the WebView is in the midst of a user gesture.
1799 - (BOOL)_isProcessingUserGesture
1801 return ScriptController::processingUserGesture();
1804 + (NSString *)_MIMETypeForFile:(NSString *)path
1807 NSString *extension = [path pathExtension];
1809 NSString *MIMEType = nil;
1812 // Get the MIME type from the extension.
1813 if ([extension length] != 0) {
1814 MIMEType = WKGetMIMETypeForExtension(extension);
1818 // If we can't get a known MIME type from the extension, sniff.
1819 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1820 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1821 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1823 if ([data length] != 0) {
1824 MIMEType = [data _webkit_guessedMIMEType];
1826 if ([MIMEType length] == 0) {
1827 MIMEType = @"application/octet-stream";
1834 - (WebDownload *)_downloadURL:(NSURL *)URL
1838 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1839 WebDownload *download = [WebDownload _downloadWithRequest:request
1840 delegate:_private->downloadDelegate
1847 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1849 NSDictionary *features = [[NSDictionary alloc] init];
1850 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1851 createWebViewWithRequest:nil
1852 windowFeatures:features];
1854 if (!newWindowWebView)
1857 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1858 return newWindowWebView;
1861 - (WebInspector *)inspector
1863 if (!_private->inspector)
1864 _private->inspector = [[WebInspector alloc] initWithWebView:self];
1865 return _private->inspector;
1868 #if ENABLE(REMOTE_INSPECTOR)
1869 + (void)_enableRemoteInspector
1871 RemoteInspector::shared().start();
1874 + (void)_disableRemoteInspector
1876 RemoteInspector::shared().stop();
1879 + (void)_disableAutoStartRemoteInspector
1881 RemoteInspector::startDisabled();
1884 + (BOOL)_isRemoteInspectorEnabled
1886 return RemoteInspector::shared().enabled();
1889 + (BOOL)_hasRemoteInspectorSession
1891 return RemoteInspector::shared().hasActiveDebugSession();
1894 - (BOOL)allowsRemoteInspection
1896 return _private->page->remoteInspectionAllowed();
1899 - (void)setAllowsRemoteInspection:(BOOL)allow
1901 _private->page->setRemoteInspectionAllowed(allow);
1904 - (void)setShowingInspectorIndication:(BOOL)showing
1907 ASSERT(WebThreadIsLocked());
1910 if (!_private->indicateLayer) {
1911 _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1912 [_private->indicateLayer setNeedsLayout];
1913 [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1916 [_private->indicateLayer removeFromSuperlayer];
1917 [_private->indicateLayer release];
1918 _private->indicateLayer = nil;
1921 // Implemented in WebCore::InspectorOverlay.
1926 - (void)setHostApplicationBundleId:(NSString *)bundleId name:(NSString *)name
1928 if (![_private->hostApplicationBundleId isEqualToString:bundleId]) {
1929 [_private->hostApplicationBundleId release];
1930 _private->hostApplicationBundleId = [bundleId copy];
1933 if (![_private->hostApplicationName isEqualToString:name]) {
1934 [_private->hostApplicationName release];
1935 _private->hostApplicationName = [name copy];
1938 // FIXME: This has not yet been ported to Inspector::RemoteInspectorServer.
1941 - (NSString *)hostApplicationBundleId
1943 return _private->hostApplicationBundleId;
1946 - (NSString *)hostApplicationName
1948 return _private->hostApplicationName;
1950 #endif // PLATFORM(IOS)
1951 #endif // ENABLE(REMOTE_INSPECTOR)
1953 - (WebCore::Page*)page
1955 return _private->page;
1959 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1961 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1962 NSArray *menuItems = defaultMenuItems;
1964 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1965 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1966 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1967 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1968 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1973 unsigned count = [menuItems count];
1977 NSMenu *menu = [[NSMenu alloc] init];
1978 for (unsigned i = 0; i < count; i++)
1979 [menu addItem:[menuItems objectAtIndex:i]];
1981 return [menu autorelease];
1985 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1987 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1988 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1989 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1992 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1995 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1997 if (!_private->page)
2000 if (!otherView->_private->page)
2003 // It turns out the right combination of behavior is done with the back/forward load
2004 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
2005 // in the back forward list, and go to the current one.
2007 BackForwardClient* backForwardClient = _private->page->backForward().client();
2008 ASSERT(!backForwardClient->currentItem()); // destination list should be empty
2010 BackForwardClient* otherBackForwardClient = otherView->_private->page->backForward().client();
2011 if (!otherBackForwardClient->currentItem())
2012 return; // empty back forward list, bail
2014 HistoryItem* newItemToGoTo = 0;
2016 int lastItemIndex = otherBackForwardClient->forwardListCount();
2017 for (int i = -otherBackForwardClient->backListCount(); i <= lastItemIndex; ++i) {
2019 // If this item is showing , save away its current scroll and form state,
2020 // since that might have changed since loading and it is normally not saved
2021 // until we leave that page.
2022 otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2024 RefPtr<HistoryItem> newItem = otherBackForwardClient->itemAtIndex(i)->copy();
2026 newItemToGoTo = newItem.get();
2027 backForwardClient->addItem(newItem.release());
2030 ASSERT(newItemToGoTo);
2031 _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
2034 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2036 _private->formDelegate = delegate;
2038 [_private->formDelegateForwarder clearTarget];
2039 [_private->formDelegateForwarder release];
2040 _private->formDelegateForwarder = nil;
2044 - (id<WebFormDelegate>)_formDelegate
2046 return _private->formDelegate;
2050 - (id)_formDelegateForwarder
2052 if (_private->closing)
2055 if (!_private->formDelegateForwarder)
2056 _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2057 return _private->formDelegateForwarder;
2060 - (id)_formDelegateForSelector:(SEL)selector
2062 id delegate = self->_private->formDelegate;
2063 if ([delegate respondsToSelector:selector])
2066 delegate = [WebDefaultFormDelegate sharedFormDelegate];
2067 if ([delegate respondsToSelector:selector])
2075 - (BOOL)_needsAdobeFrameReloadingQuirk
2077 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2078 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2079 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2080 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2081 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2082 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2083 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2084 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2085 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2086 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2091 - (BOOL)_needsLinkElementTextCSSQuirk
2093 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2094 && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2098 - (BOOL)_needsIsLoadingInAPISenseQuirk
2100 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2105 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2107 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
2111 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2113 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);
2117 static bool needsSelfRetainWhileLoadingQuirk()
2119 static bool needsQuirk = applicationIsAperture();
2122 #endif // !PLATFORM(IOS)
2124 - (BOOL)_needsPreHTML5ParserQuirks
2127 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2128 // with the new HTML5 parser. If these applications were linked against a
2129 // version of WebKit prior to the introduction of the HTML5 parser, enable
2130 // parser quirks to maintain compatibility. For details, see
2131 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2132 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2133 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2134 && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
2136 // Mail.app must continue to display HTML email that contains quirky markup.
2137 static bool isAppleMail = applicationIsAppleMail();
2139 return isApplicationNeedingParserQuirks
2141 #if ENABLE(DASHBOARD_SUPPORT)
2142 // Pre-HTML5 parser quirks are required to remain compatible with many
2143 // Dashboard widgets. See <rdar://problem/8175982>.
2144 || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2146 || [[self preferences] usePreHTML5ParserQuirks];
2148 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && applicationIsDaijisenDictionary();
2149 return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2153 - (BOOL)_needsUnrestrictedGetMatchedCSSRules
2156 static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
2157 return needsUnrestrictedGetMatchedCSSRules;
2159 // FIXME: <rdar://problem/8963684> Implement linked-on-or-after check for needsUnrestrictedGetMatchedCSSRules
2164 - (void)_preferencesChangedNotification:(NSNotification *)notification
2167 // For WebViews that load synchronously, preference changes need to be propagated
2168 // down to WebCore synchronously so that loads in that WebView have the correct
2169 // up-to-date settings.
2170 if (!WebThreadIsLocked())
2172 if ([[self mainFrame] _loadsSynchronously]) {
2175 WebPreferences *preferences = (WebPreferences *)[notification object];
2176 [self _preferencesChanged:preferences];
2181 // It is possible that the prefs object has already changed before the invocation could be called
2182 // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2183 WebPreferences *preferences = (WebPreferences *)[notification object];
2184 if (preferences != [self preferences])
2186 [self _preferencesChanged:preferences];
2192 - (void)_preferencesChanged:(WebPreferences *)preferences
2194 ASSERT(preferences == [self preferences]);
2195 if (!_private->userAgentOverridden)
2196 _private->userAgent = String();
2198 // Cache this value so we don't have to read NSUserDefaults on each page load
2199 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2201 // Update corresponding WebCore Settings object.
2202 if (!_private->page)
2206 // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2207 // didOneTimeInitialization is true so that we don't initialize databases
2208 // until the first WebView has been created. This is because database
2209 // initialization current requires disk access to populate the origins
2210 // quota map and we want to do this lazily by waiting until WebKit is
2211 // used to display web content in a WebView. The possible cases are:
2212 // - on one time initialize (the first WebView creation) if databases are enabled (default)
2213 // - when databases are dynamically enabled later, and they were disabled at startup (this case)
2214 if (didOneTimeInitialization) {
2215 if ([preferences databasesEnabled])
2216 [WebDatabaseManager sharedWebDatabaseManager];
2218 if ([preferences storageTrackerEnabled])
2219 WebKitInitializeStorageIfNecessary();
2223 Settings& settings = _private->page->settings();
2225 settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2226 settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2227 settings.setDefaultFontSize([preferences defaultFontSize]);
2228 settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2229 settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2230 settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2231 settings.setFixedFontFamily([preferences fixedFontFamily]);
2232 settings.setScreenFontSubstitutionEnabled(
2233 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2234 [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
2236 [preferences screenFontSubstitutionEnabled]
2238 settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2239 settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2240 settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2241 settings.setJavaEnabled([preferences isJavaEnabled]);
2242 settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2243 settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2244 settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2245 settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2246 settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2247 settings.setMinimumFontSize([preferences minimumFontSize]);
2248 settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2249 settings.setPictographFontFamily([preferences pictographFontFamily]);
2250 settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2251 #if ENABLE(SQL_DATABASE)
2252 DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
2254 settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2256 settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2258 _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2259 settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2260 settings.setSerifFontFamily([preferences serifFontFamily]);
2261 settings.setStandardFontFamily([preferences standardFontFamily]);
2262 settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2263 settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2265 settings.setShouldPrintBackgrounds(true);
2267 settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2268 settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2270 settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2271 settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2272 settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2273 settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2274 settings.setUsesPageCache([self usesPageCache]);
2275 settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2276 settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2278 settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2279 settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2281 settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2282 settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
2283 settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2284 settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
2286 if ([preferences userStyleSheetEnabled]) {
2287 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2288 if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2289 location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2290 settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2292 settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2293 settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2294 settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2295 settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2297 // iOS-specific settings
2298 settings.setStandalone([preferences _standalone]);
2299 settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2300 settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
2301 settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2302 settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2303 settings.setMaxParseDuration([preferences _maxParseDuration]);
2304 settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2306 settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2307 settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2308 settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2309 settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2310 settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2311 settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2313 settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2315 settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2317 // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
2318 // Until we fix that, I will comment out the test (CFM)
2319 settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2320 settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2321 settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2322 settings.setShowDebugBorders([preferences showDebugBorders]);
2323 settings.setShowRepaintCounter([preferences showRepaintCounter]);
2324 settings.setWebGLEnabled([preferences webGLEnabled]);
2326 // FIXME: Should we enable this following <rdar://problem/15290404>?
2327 settings.setMultithreadedWebGLEnabled([preferences multithreadedWebGLEnabled]);
2329 settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2330 settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2331 settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2332 settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2333 settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2334 settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2335 settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2336 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2337 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2338 #if ENABLE(WEB_AUDIO)
2339 settings.setWebAudioEnabled([preferences webAudioEnabled]);
2341 settings.setCSSGridLayoutEnabled([preferences cssGridLayoutEnabled]);
2342 #if ENABLE(FULLSCREEN_API)
2343 settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2345 settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2346 settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2347 settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2348 settings.setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
2349 settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2350 settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2351 #if USE(AVFOUNDATION)
2352 settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2355 settings.setQTKitEnabled([preferences isQTKitEnabled]);
2358 settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
2359 settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2360 settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2361 settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2362 settings.setAVKitEnabled([preferences avKitEnabled]);
2364 settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
2365 settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
2366 settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2367 settings.setRegionBasedColumnsEnabled([preferences regionBasedColumnsEnabled]);
2368 settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2369 settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2370 settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2372 #if ENABLE(VIDEO_TRACK)
2373 settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2374 settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2375 settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2378 settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2380 settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2382 settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2383 settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2384 settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2386 settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2388 #if ENABLE(MEDIA_SOURCE)
2389 settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2392 #if ENABLE(SERVICE_CONTROLS)
2393 settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2396 settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2398 settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2400 switch ([preferences storageBlockingPolicy]) {
2401 case WebAllowAllStorage:
2402 settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2404 case WebBlockThirdPartyStorage:
2405 settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2407 case WebBlockAllStorage:
2408 settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2412 settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2414 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2415 settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2417 #if ENABLE(PAGE_VISIBILITY_API)
2418 settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2421 // We have enabled this setting in WebKit2 for the sake of some ScrollingCoordinator work.
2422 // To avoid possible rendering differences, we should enable it for WebKit1 too. We also
2423 // want to keep this setting enabled for iOS. See <rdar://problem/9813262> for more details.
2424 settings.setFixedPositionCreatesStackingContext(true);
2426 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2428 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2430 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2431 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2433 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2434 if (_private->zoomsTextOnly != zoomsTextOnly)
2435 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2437 #if ENABLE(IOS_TEXT_AUTOSIZING)
2438 settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2441 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
2442 DiskImageCache& diskImageCache = WebCore::diskImageCache();
2443 diskImageCache.setEnabled([preferences diskImageCacheEnabled]);
2444 diskImageCache.setMinimumImageSize([preferences diskImageCacheMinimumImageSize]);
2445 diskImageCache.setMaximumCacheSize([preferences diskImageCacheMaximumCacheSize]);
2449 [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2450 [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2451 [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2452 [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2453 settings.setDelegatesPageScaling(true);
2455 settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2456 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2457 ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2460 settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2461 settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2465 static inline IMP getMethod(id o, SEL s)
2467 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2471 - (id)_UIKitDelegateForwarder
2473 if (_private->closing)
2476 if (!_private->UIKitDelegateForwarder)
2477 _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2478 return _private->UIKitDelegateForwarder;
2482 - (void)_cacheResourceLoadDelegateImplementations
2484 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2485 id delegate = _private->resourceProgressDelegate;
2488 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2492 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2493 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2494 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2495 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2496 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2497 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2498 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2502 cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2503 cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2504 cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2505 cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2506 cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2507 cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2508 cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2509 cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2510 cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2513 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2514 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2515 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2516 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2517 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2518 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2519 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2520 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2523 - (void)_cacheFrameLoadDelegateImplementations
2525 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2526 id delegate = _private->frameLoadDelegate;
2529 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2533 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2534 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2535 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2536 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2537 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2538 #if JSC_OBJC_API_ENABLED
2539 cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2541 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2542 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2543 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2544 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2545 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2546 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2547 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2548 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2549 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2550 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2551 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2552 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2553 #if ENABLE(ICONDATABASE)
2554 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2556 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2557 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2558 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2559 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2560 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2561 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2562 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2563 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2564 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2565 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2567 cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2570 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2571 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2572 // for backwards compatibility.
2573 Page* page = core(self);
2575 unsigned milestones = DidFirstLayout;
2577 milestones |= DidFirstVisuallyNonEmptyLayout;
2579 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2580 milestones |= DidFirstVisuallyNonEmptyLayout;
2582 page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2586 - (void)_cacheScriptDebugDelegateImplementations
2588 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2589 id delegate = _private->scriptDebugDelegate;
2592 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2596 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2597 if (cache->didParseSourceFunc)
2598 cache->didParseSourceExpectsBaseLineNumber = YES;
2600 cache->didParseSourceExpectsBaseLineNumber = NO;
2601 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2604 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2606 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2607 if (cache->exceptionWasRaisedFunc)
2608 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2610 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2611 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2615 - (void)_cacheHistoryDelegateImplementations
2617 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2618 id delegate = _private->historyDelegate;
2621 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2625 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2626 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2627 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2628 cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2629 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2630 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2633 - (id)_policyDelegateForwarder
2636 if (_private->closing)
2639 if (!_private->policyDelegateForwarder)
2640 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2641 return _private->policyDelegateForwarder;
2644 - (id)_UIDelegateForwarder
2647 if (_private->closing)
2650 if (!_private->UIDelegateForwarder)
2651 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2652 return _private->UIDelegateForwarder;
2656 - (id)_UIDelegateForSelector:(SEL)selector
2658 id delegate = self->_private->UIDelegate;
2659 if ([delegate respondsToSelector:selector])
2662 delegate = [WebDefaultUIDelegate sharedUIDelegate];
2663 if ([delegate respondsToSelector:selector])
2670 - (id)_editingDelegateForwarder
2673 if (_private->closing)
2676 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2677 // Not sure if that is a bug or not.
2681 if (!_private->editingDelegateForwarder)
2682 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2683 return _private->editingDelegateForwarder;
2686 - (void)_closeWindow
2688 [[self _UIDelegateForwarder] webViewClose:self];
2691 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2693 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2694 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2696 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2697 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2698 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2699 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2702 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2704 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2705 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2707 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2708 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2709 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2710 if ([viewClass class] == [WebHTMLView class])
2711 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2713 // This is used to make _representationExistsForURLScheme faster.
2714 // Without this set, we'd have to create the MIME type each time.
2715 if (schemesWithRepresentationsSet == nil) {
2716 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2718 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2721 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2723 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2726 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2728 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2731 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2733 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2737 if ([NSURLConnection canHandleRequest:request])
2740 NSString *scheme = [[request URL] scheme];
2742 // Representations for URL schemes work at the top level.
2743 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2746 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2750 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2757 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2759 return [self _canHandleRequest:request forMainFrame:YES];
2762 + (NSString *)_decodeData:(NSData *)data
2764 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2765 return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2768 - (void)_pushPerformingProgrammaticFocus
2770 _private->programmaticFocusCount++;
2773 - (void)_popPerformingProgrammaticFocus
2775 _private->programmaticFocusCount--;
2778 - (BOOL)_isPerformingProgrammaticFocus
2780 return _private->programmaticFocusCount != 0;
2784 - (void)_didChangeValueForKey: (NSString *)key
2786 LOG (Bindings, "calling didChangeValueForKey: %@", key);
2787 [self didChangeValueForKey: key];
2790 - (void)_willChangeValueForKey: (NSString *)key
2792 LOG (Bindings, "calling willChangeValueForKey: %@", key);
2793 [self willChangeValueForKey: key];
2796 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2797 static NSSet *manualNotifyKeys = nil;
2798 if (!manualNotifyKeys)
2799 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2800 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2802 if ([manualNotifyKeys containsObject:key])
2807 - (NSArray *)_declaredKeys {
2808 static NSArray *declaredKeys = nil;
2810 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2811 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2812 return declaredKeys;
2815 - (void)setObservationInfo:(void *)info
2817 _private->observationInfo = info;
2820 - (void *)observationInfo
2822 return _private->observationInfo;
2825 - (void)_willChangeBackForwardKeys
2827 [self _willChangeValueForKey: _WebCanGoBackKey];
2828 [self _willChangeValueForKey: _WebCanGoForwardKey];
2831 - (void)_didChangeBackForwardKeys
2833 [self _didChangeValueForKey: _WebCanGoBackKey];
2834 [self _didChangeValueForKey: _WebCanGoForwardKey];
2837 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2839 if (needsSelfRetainWhileLoadingQuirk())
2842 [self _willChangeBackForwardKeys];
2843 if (frame == [self mainFrame]){
2844 // Force an observer update by sending a will/did.
2845 [self _willChangeValueForKey: _WebIsLoadingKey];
2846 [self _didChangeValueForKey: _WebIsLoadingKey];
2848 [self _willChangeValueForKey: _WebMainFrameURLKey];
2851 [NSApp setWindowsNeedUpdate:YES];
2853 #if ENABLE(FULLSCREEN_API)
2854 Document* document = core([frame DOMDocument]);
2855 if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2856 SEL selector = @selector(webView:closeFullScreenWithListener:);
2857 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2858 WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2859 CallUIDelegate(self, selector, listener);
2861 } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2862 [_private->newFullscreenController close];
2868 - (void)_checkDidPerformFirstNavigation
2870 if (_private->_didPerformFirstNavigation)
2873 Page* page = _private->page;
2877 auto& backForwardController = page->backForward();
2879 if (!backForwardController.backItem())
2882 _private->_didPerformFirstNavigation = YES;
2884 if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2885 _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2888 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2890 if (frame == [self mainFrame])
2891 [self _didChangeValueForKey: _WebMainFrameURLKey];
2893 [self _checkDidPerformFirstNavigation];
2895 [NSApp setWindowsNeedUpdate:YES];
2898 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2900 if (needsSelfRetainWhileLoadingQuirk())
2901 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2903 [self _didChangeBackForwardKeys];
2904 if (frame == [self mainFrame]){
2905 // Force an observer update by sending a will/did.
2906 [self _willChangeValueForKey: _WebIsLoadingKey];
2907 [self _didChangeValueForKey: _WebIsLoadingKey];
2909 [NSApp setWindowsNeedUpdate:YES];
2912 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2914 if (needsSelfRetainWhileLoadingQuirk())
2915 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2917 [self _didChangeBackForwardKeys];
2918 if (frame == [self mainFrame]){
2919 // Force an observer update by sending a will/did.
2920 [self _willChangeValueForKey: _WebIsLoadingKey];
2921 [self _didChangeValueForKey: _WebIsLoadingKey];
2923 [NSApp setWindowsNeedUpdate:YES];
2926 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2928 if (needsSelfRetainWhileLoadingQuirk())
2929 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2931 [self _didChangeBackForwardKeys];
2932 if (frame == [self mainFrame]){
2933 // Force an observer update by sending a will/did.
2934 [self _willChangeValueForKey: _WebIsLoadingKey];
2935 [self _didChangeValueForKey: _WebIsLoadingKey];
2937 [self _didChangeValueForKey: _WebMainFrameURLKey];
2939 [NSApp setWindowsNeedUpdate:YES];
2942 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2944 RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2945 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2946 NSCachedURLResponse *cachedResponse;
2948 if (!_private->page)
2951 if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2952 cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2954 cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2956 return cachedResponse;
2959 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2961 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2962 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2963 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2965 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2966 title:[element objectForKey:WebElementImageAltStringKey]
2967 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2972 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2974 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2975 andTitle:[element objectForKey:WebElementLinkLabelKey]
2979 #if ENABLE(DRAG_SUPPORT)
2980 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2982 if (!_private->page)
2984 _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2990 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2992 if (frame == [self mainFrame])
2993 _private->didDrawTiles = 0;
2996 #endif // PLATFORM(IOS)
2998 #if ENABLE(DASHBOARD_SUPPORT)
3000 #define DASHBOARD_CONTROL_LABEL @"control"
3002 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3004 NSRect adjustedBounds = bounds;
3005 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3006 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3007 adjustedBounds.size = bounds.size;
3009 NSRect adjustedClip;
3010 adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3011 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3012 adjustedClip.size = clip.size;
3014 WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds
3015 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3016 NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3017 if (!scrollerRegions) {
3018 scrollerRegions = [[NSMutableArray alloc] init];
3019 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3020 [scrollerRegions release];
3022 [scrollerRegions addObject:region];
3026 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3028 NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3030 for (const auto& widget: frameView->children()) {
3031 if (widget->isFrameView()) {
3032 [self _addScrollerDashboardRegionsForFrameView:toFrameView(widget.get()) dashboardRegions:regions];
3036 if (!widget->isScrollbar())
3039 // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3040 // it's not common to need this to be correct in Dashboard widgets.
3041 NSRect bounds = widget->frameRect();
3042 [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3046 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3048 // Add scroller regions for NSScroller and WebCore scrollbars
3049 NSUInteger count = [views count];
3050 for (NSUInteger i = 0; i < count; i++) {
3051 NSView *view = [views objectAtIndex:i];
3053 if ([view isKindOfClass:[WebHTMLView class]]) {
3054 if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3055 if (FrameView* coreView = coreFrame->view())
3056 [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3058 } else if ([view isKindOfClass:[NSScroller class]]) {
3059 // AppKit places absent scrollers at -100,-100
3060 if ([view frame].origin.y < 0)
3062 [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3064 [self _addScrollerDashboardRegions:regions from:[view subviews]];
3068 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3070 [self _addScrollerDashboardRegions:regions from:[self subviews]];
3073 - (NSDictionary *)_dashboardRegions
3075 // Only return regions from main frame.
3076 Frame* mainFrame = [self _mainCoreFrame];
3080 const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3081 size_t size = regions.size();
3083 NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3084 for (size_t i = 0; i < size; i++) {
3085 const AnnotatedRegionValue& region = regions[i];
3087 if (region.type == StyleDashboardRegion::None)
3090 NSString *label = region.label;
3091 WebDashboardRegionType type = WebDashboardRegionTypeNone;
3092 if (region.type == StyleDashboardRegion::Circle)
3093 type = WebDashboardRegionTypeCircle;
3094 else if (region.type == StyleDashboardRegion::Rectangle)
3095 type = WebDashboardRegionTypeRectangle;
3096 NSMutableArray *regionValues = [webRegions objectForKey:label];
3097 if (!regionValues) {
3098 regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3099 [webRegions setObject:regionValues forKey:label];
3100 [regionValues release];
3103 WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:pixelSnappedIntRect(region.bounds) clip:pixelSnappedIntRect(region.clip) type:type];
3104 [regionValues addObject:webRegion];
3105 [webRegion release];
3108 [self _addScrollerDashboardRegions:webRegions];
3113 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3115 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
3116 // specific support for the backward compatibility mode flag.
3117 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3118 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3121 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3122 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3125 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3126 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3129 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3130 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3133 case WebDashboardBehaviorAllowWheelScrolling: {
3134 _private->dashboardBehaviorAllowWheelScrolling = flag;
3137 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3139 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3140 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3141 RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3147 // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3148 // compatibility mode. See <rdar://problem/8175982>.
3150 _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3153 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3156 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3157 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3159 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3160 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3162 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3163 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3165 case WebDashboardBehaviorAllowWheelScrolling: {
3166 return _private->dashboardBehaviorAllowWheelScrolling;
3168 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3169 return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3175 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3177 + (void)_setShouldUseFontSmoothing:(BOOL)f
3179 Font::setShouldUseSmoothing(f);
3182 + (BOOL)_shouldUseFontSmoothing
3184 return Font::shouldUseSmoothing();
3188 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3190 setUsesTestModeFocusRingColor(f);
3193 + (BOOL)_usesTestModeFocusRingColor
3195 return usesTestModeFocusRingColor();
3200 - (void)_setUIKitDelegate:(id)delegate
3202 _private->UIKitDelegate = delegate;
3203 [_private->UIKitDelegateForwarder clearTarget];
3204 [_private->UIKitDelegateForwarder release];
3205 _private->UIKitDelegateForwarder = nil;
3208 - (id)_UIKitDelegate
3210 return _private->UIKitDelegate;
3213 - (void)setWebMailDelegate:(id)delegate
3215 _private->WebMailDelegate = delegate;
3218 - (id)_webMailDelegate
3220 return _private->WebMailDelegate;
3223 - (id <WebCaretChangeListener>)caretChangeListener
3225 return _private->_caretChangeListener;
3228 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3230 _private->_caretChangeListener = listener;
3233 - (NSSet *)caretChangeListeners
3235 return _private->_caretChangeListeners;
3238 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3240 if (_private->_caretChangeListeners == nil) {
3241 _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3244 [_private->_caretChangeListeners addObject:listener];
3247 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3249 [_private->_caretChangeListeners removeObject:listener];
3252 - (void)removeAllCaretChangeListeners
3254 [_private->_caretChangeListeners removeAllObjects];
3257 - (void)caretChanged
3259 [_private->_caretChangeListener caretChanged];
3260 NSSet *copy = [_private->_caretChangeListeners copy];
3261 for (id <WebCaretChangeListener> listener in copy) {
3262 [listener caretChanged];
3267 - (void)_clearDelegates
3269 ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3271 [self _setFormDelegate:nil];
3272 [self _setUIKitDelegate:nil];
3273 [self setCaretChangeListener:nil];
3274 [self removeAllCaretChangeListeners];
3275 [self setWebMailDelegate:nil];
3277 [self setDownloadDelegate:nil];
3278 [self setEditingDelegate:nil];
3279 [self setFrameLoadDelegate:nil];
3280 [self setPolicyDelegate:nil];
3281 [self setResourceLoadDelegate:nil];
3282 [self setScriptDebugDelegate:nil];
3283 [self setUIDelegate:nil];
3286 - (NSURL *)_displayURL
3289 WebFrame *frame = [self mainFrame];
3290 // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3291 WebDataSource *dataSource = [frame provisionalDataSource];
3293 dataSource = [frame dataSource];
3294 NSURL *unreachableURL = [dataSource unreachableURL];
3295 NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3296 [[URL retain] autorelease];
3299 #endif // PLATFORM(IOS)
3302 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3304 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3306 [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3308 [scrollview setVerticalScrollingModeLocked:NO];
3309 [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3313 - (BOOL)alwaysShowVerticalScroller
3315 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3316 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3319 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3321 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3323 [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3325 [scrollview setHorizontalScrollingModeLocked:NO];
3326 [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3330 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3332 if (Frame* mainFrame = [self _mainCoreFrame])
3333 mainFrame->view()->setProhibitsScrolling(prohibits);
3336 - (BOOL)alwaysShowHorizontalScroller
3338 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3339 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3341 #endif // !PLATFORM(IOS)
3343 - (void)_setUseFastImageScalingMode:(BOOL)flag
3345 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3346 _private->page->setInLowQualityImageInterpolationMode(flag);
3347 [self setNeedsDisplay:YES];
3351 - (BOOL)_inFastImageScalingMode
3354 return _private->page->inLowQualityImageInterpolationMode();
3358 - (BOOL)_cookieEnabled
3361 return _private->page->settings().cookieEnabled();
3365 - (void)_setCookieEnabled:(BOOL)enable
3368 _private->page->settings().setCookieEnabled(enable);
3372 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3374 if (!_private->pluginDatabase)
3375 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3377 [_private->pluginDatabase setPlugInPaths:newPaths];
3378 [_private->pluginDatabase refresh];
3383 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3385 // Ask plug-ins in this frame
3386 id <WebDocumentView> documentView = [[frame frameView] documentView];
3387 if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3388 if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3392 // Ask plug-ins in child frames
3393 NSArray *childFrames = [frame childFrames];
3394 unsigned childCount = [childFrames count];
3395 unsigned childIndex;
3396 for (childIndex = 0; childIndex < childCount; childIndex++) {
3397 if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3404 - (BOOL)_pluginsAreRunning
3407 return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3410 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3412 // Send the message to plug-ins in this frame
3413 id <WebDocumentView> documentView = [[frame frameView] documentView];
3414 if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3415 [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3417 // Send the message to plug-ins in child frames
3418 NSArray *childFrames = [frame childFrames];
3419 unsigned childCount = [childFrames count];
3420 unsigned childIndex;
3421 for (childIndex = 0; childIndex < childCount; childIndex++) {
3422 [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3426 - (void)_destroyAllPlugIns
3429 [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3432 - (void)_clearBackForwardCache
3435 WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3436 BackForwardList* bfList = core([self backForwardList]);
3440 BOOL didClearBFCache = bfList->clearAllPageCaches();
3441 if (WebKit::MemoryMeasure::isLoggingEnabled())
3442 NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3446 - (void)_startAllPlugIns
3449 [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3452 - (void)_stopAllPlugIns
3455 [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3458 - (void)_stopAllPlugInsForPageCache
3461 [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3464 - (void)_restorePlugInsFromCache
3467 [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3470 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3474 Frame* mainCoreFrame = [self _mainCoreFrame];
3475 for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3476 FrameView* coreView = frame ? frame->view() : 0;
3480 // Get the GraphicsLayer for this widget.
3481 GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3482 if (!layerForWidget)
3485 if (layerForWidget->contentsLayerForMedia() != layer) {
3486 layerForWidget->setContentsToMedia(layer);
3487 // We need to make sure the layer hierachy change is applied immediately.
3488 if (mainCoreFrame->view())
3489 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3497 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3500 _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3502 #endif // PLATFORM(IOS)
3504 - (void)_attachScriptDebuggerToAllFrames
3506 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3507 [kit(frame) _attachScriptDebugger];
3510 - (void)_detachScriptDebuggerFromAllFrames
3512 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3513 [kit(frame) _detachScriptDebugger];
3517 - (void)setBackgroundColor:(NSColor *)backgroundColor
3519 if ([_private->backgroundColor isEqual:backgroundColor])
3522 id old = _private->backgroundColor;
3523 _private->backgroundColor = [backgroundColor retain];
3526 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3529 - (NSColor *)backgroundColor
3531 return _private->backgroundColor;
3534 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3536 if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3539 CFTypeRef old = _private->backgroundColor;
3540 CFRetain(backgroundColor);
3541 _private->backgroundColor = backgroundColor;
3544 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3547 - (CGColorRef)backgroundColor
3549 return _private->backgroundColor;
3553 - (BOOL)defersCallbacks
3555 if (!_private->page)
3557 return _private->page->defersLoading();
3560 - (void)setDefersCallbacks:(BOOL)defer
3562 if (!_private->page)
3564 return _private->page->setDefersLoading(defer);
3567 #if TARGET_OS_IPHONE && USE(QUICK_LOOK)
3568 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3570 NSString *uti = qlPreviewConverterUTIForURL(url);
3574 NSString *fileName = qlPreviewConverterFileNameForURL(url);
3578 return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3585 return _private->isStopping;
3590 return _private->closing;
3593 + (NSArray *)_productivityDocumentMIMETypes
3596 return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3602 - (void)_setAllowsMessaging:(BOOL)aFlag
3604 _private->allowsMessaging = aFlag;
3607 - (BOOL)_allowsMessaging
3609 return _private->allowsMessaging;
3612 - (void)_setFixedLayoutSize:(CGSize)size
3614 ASSERT(WebThreadIsLocked());
3615 _private->fixedLayoutSize = size;
3616 if (Frame* mainFrame = core([self mainFrame])) {
3617 IntSize newSize(size);
3618 mainFrame->view()->setFixedLayoutSize(newSize);
3619 mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3620 [self setNeedsDisplay:YES];
3624 - (CGSize)_fixedLayoutSize
3626 return _private->fixedLayoutSize;
3629 - (void)_synchronizeCustomFixedPositionLayoutRect
3631 ASSERT(WebThreadIsLocked());
3635 MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3636 if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3638 newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3639 _private->pendingFixedPositionLayoutRect = CGRectNull;
3642 if (Frame* mainFrame = core([self mainFrame]))
3643 mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
3646 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
3649 MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3650 _private->pendingFixedPositionLayoutRect = rect;
3655 [self _synchronizeCustomFixedPositionLayoutRect];
3659 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
3661 ASSERT(WebThreadIsLocked());
3663 MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3664 _private->pendingFixedPositionLayoutRect = rect;
3666 [self _synchronizeCustomFixedPositionLayoutRect];
3669 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
3671 MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3672 if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3675 *rect = _private->pendingFixedPositionLayoutRect;
3676 _private->pendingFixedPositionLayoutRect = CGRectNull;
3680 - (void)_viewGeometryDidChange
3682 ASSERT(WebThreadIsLocked());
3684 if (Frame* coreFrame = [self _mainCoreFrame])
3685 coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
3688 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
3691 Node* node = core(domNode);
3692 Frame* frame = node->document().frame();
3696 frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
3699 + (void)_doNotStartObservingNetworkReachability
3701 Settings::setShouldOptOutOfNetworkStateObservation(true);
3703 #endif // PLATFORM(IOS)
3705 #if ENABLE(TOUCH_EVENTS)
3706 - (NSArray *)_touchEventRegions
3708 Frame* frame = [self _mainCoreFrame];
3712 Document* document = frame->document();
3716 Vector<IntRect> rects;
3717 document->getTouchRects(rects);
3719 if (rects.size() == 0)
3722 NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
3724 Vector<IntRect>::const_iterator end = rects.end();
3725 for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
3726 const IntRect& rect = *it;
3730 // The event region wants this points in this order:
3735 WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(rect.x(), rect.maxY())
3736 :FloatPoint(rect.x(), rect.y())
3737 :FloatPoint(rect.maxX(), rect.y())
3738 :FloatPoint(rect.maxX(), rect.maxY())];
3740 [eventRegionArray addObject:eventRegion];
3741 [eventRegion release];
3745 return eventRegionArray;
3747 #endif // ENABLE(TOUCH_EVENTS)
3749 // For backwards compatibility with the WebBackForwardList API, we honor both
3750 // a per-WebView and a per-preferences setting for whether to use the page cache.
3752 - (BOOL)usesPageCache
3754 return _private->usesPageCache && [[self preferences] usesPageCache];
3757 - (void)setUsesPageCache:(BOOL)usesPageCache
3759 _private->usesPageCache = usesPageCache;
3761 // Update our own settings and post the public notification only
3762 [self _preferencesChanged:[self preferences]];
3763 [[self preferences] _postPreferencesChangedAPINotification];
3766 - (WebHistoryItem *)_globalHistoryItem
3771 return kit(_private->_globalHistoryItem.get());
3774 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
3776 _private->_globalHistoryItem = historyItem;
3779 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
3781 IntPoint rectStart(rect.origin.x, rect.origin.y);
3782 IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
3784 Frame* coreFrame = [self _mainCoreFrame];
3788 VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
3790 return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
3793 #if ENABLE(DASHBOARD_SUPPORT)
3794 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
3796 NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window];
3797 [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window];
3802 - (void)_clearUndoRedoOperations
3804 if (!_private->page)
3806 _private->page->clearUndoRedoOperations();
3810 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
3812 Frame* coreFrame = [self _mainCoreFrame];
3815 coreFrame->editor().command(name).execute(value);
3818 - (void)_clearMainFrameName
3820 _private->page->mainFrame().tree().clearName();
3823 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
3825 if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
3826 _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);
3827 [self setSmartInsertDeleteEnabled:!flag];
3831 - (BOOL)isSelectTrailingWhitespaceEnabled
3833 return _private->page->settings().selectTrailingWhitespaceEnabled();
3836 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
3838 _private->page->setMemoryCacheClientCallsEnabled(enabled);
3841 - (BOOL)areMemoryCacheDelegateCallsEnabled
3843 return _private->page->areMemoryCacheClientCallsEnabled();
3847 + (NSCursor *)_pointingHandCursor
3849 return handCursor().platformCursor();
3853 - (BOOL)_postsAcceleratedCompositingNotifications
3855 return _private->postsAcceleratedCompositingNotifications;
3857 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
3859 _private->postsAcceleratedCompositingNotifications = flag;
3862 - (BOOL)_isUsingAcceleratedCompositing
3864 Frame* coreFrame = [self _mainCoreFrame];
3865 for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
3866 NSView *documentView = [[kit(frame) frameView] documentView];
3867 if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
3874 - (BOOL)_flushCompositingChanges
3876 Frame* frame = [self _mainCoreFrame];
3877 if (frame && frame->view())
3878 return frame->view()->flushCompositingStateIncludingSubframes();
3883 - (void)_setBaseCTM:(CGAffineTransform)transform forContext:(CGContextRef)context
3885 WKSetBaseCTM(context, transform);
3888 - (BOOL)interactiveFormValidationEnabled
3890 return _private->interactiveFormValidationEnabled;
3893 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
3895 _private->interactiveFormValidationEnabled = enabled;
3898 - (int)validationMessageTimerMagnification
3900 return _private->validationMessageTimerMagnification;
3903 - (void)setValidationMessageTimerMagnification:(int)newValue
3905 _private->validationMessageTimerMagnification = newValue;
3908 - (BOOL)_isSoftwareRenderable
3910 Frame* coreFrame = [self _mainCoreFrame];
3911 for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
3912 if (FrameView* view = frame->view()) {
3913 if (!view->isSoftwareRenderable())
3921 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
3923 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
3926 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
3928 return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
3931 - (void)setTracksRepaints:(BOOL)flag
3933 Frame* coreFrame = [self _mainCoreFrame];
3934 if (FrameView* view = coreFrame->view())
3935 view->setTracksRepaints(flag);
3938 - (BOOL)isTrackingRepaints
3940 Frame* coreFrame = [self _mainCoreFrame];
3941 if (FrameView* view = coreFrame->view())
3942 return view->isTrackingRepaints();
3947 - (void)resetTrackedRepaints
3949 Frame* coreFrame = [self _mainCoreFrame];
3950 if (FrameView* view = coreFrame->view())
3951 view->resetTrackedRepaints();
3954 - (NSArray*)trackedRepaintRects
3956 Frame* coreFrame = [self _mainCoreFrame];
3957 FrameView* view = coreFrame->view();
3958 if (!view || !view->isTrackingRepaints())
3961 const Vector<FloatRect>& repaintRects = view->trackedRepaintRects();
3962 NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
3964 for (unsigned i = 0; i < repaintRects.size(); ++i)
3965 [rectsArray addObject:[NSValue valueWithRect:pixelSnappedIntRect(LayoutRect(repaintRects[i]))]];
3967 return [rectsArray autorelease];
3971 - (NSPasteboard *)_insertionPasteboard
3973 return _private ? _private->insertionPasteboard : nil;
3977 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
3979 SecurityPolicy::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
3982 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
3984 SecurityPolicy::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
3987 + (void)_resetOriginAccessWhitelists
3989 SecurityPolicy::resetOriginAccessWhitelists();
3992 - (BOOL)_isViewVisible
3997 if (![[self window] isVisible])
4000 if ([self isHiddenOrHasHiddenAncestor])
4006 - (void)_updateVisibilityState
4008 if (_private && _private->page)
4009 [self _setIsVisible:[self _isViewVisible]];
4012 - (void)_updateActiveState
4014 if (_private && _private->page)
4016 _private->page->focusController().setActive([[self window] isKeyWindow]);
4018 _private->page->focusController().setActive([[self window] _hasKeyAppearance]);
4022 static Vector<String> toStringVector(NSArray* patterns)
4024 Vector<String> patternsVector;
4026 NSUInteger count = [patterns count];
4028 return patternsVector;
4030 for (NSUInteger i = 0; i < count; ++i) {
4031 id entry = [patterns objectAtIndex:i];
4032 if ([entry isKindOfClass:[NSString class]])
4033 patternsVector.append(String((NSString *)entry));
4035 return patternsVector;
4038 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4039 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4040 injectionTime:(WebUserScriptInjectionTime)injectionTime
4042 [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
4045 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4046 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4047 injectionTime:(WebUserScriptInjectionTime)injectionTime
4048 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4050 String group(groupName);
4051 if (group.isEmpty())
4054 PageGroup* pageGroup = PageGroup::pageGroup(group);
4061 pageGroup->addUserScriptToWorld(*core(world), source, url, toStringVector(whitelist), toStringVector(blacklist),
4062 injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
4063 injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
4066 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4067 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4069 [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
4072 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4073 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4074 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4076 String group(groupName);
4077 if (group.isEmpty())
4080 PageGroup* pageGroup = PageGroup::pageGroup(group);
4087 pageGroup->addUserStyleSheetToWorld(*core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
4090 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4092 String group(groupName);
4093 if (group.isEmpty())
4096 PageGroup* pageGroup = PageGroup::pageGroup(group);
4103 pageGroup->removeUserScriptFromWorld(*core(world), url);
4106 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4108 String group(groupName);
4109 if (group.isEmpty())
4112 PageGroup* pageGroup = PageGroup::pageGroup(group);
4119 pageGroup->removeUserStyleSheetFromWorld(*core(world), url);
4122 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4124 String group(groupName);
4125 if (group.isEmpty())
4128 PageGroup* pageGroup = PageGroup::pageGroup(group);
4135 pageGroup->removeUserScriptsFromWorld(*core(world));
4138 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4140 String group(groupName);
4141 if (group.isEmpty())
4144 PageGroup* pageGroup = PageGroup::pageGroup(group);
4151 pageGroup->removeUserStyleSheetsFromWorld(*core(world));
4154 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
4156 String group(groupName);
4157 if (group.isEmpty())
4160 PageGroup* pageGroup = PageGroup::pageGroup(group);
4164 pageGroup->removeAllUserContent();
4167 - (BOOL)allowsNewCSSAnimationsWhileSuspended
4169 Frame* frame = core([self mainFrame]);
4171 return frame->animation().allowsNewAnimationsWhileSuspended();
4176 - (void)setAllowsNewCSSAnimationsWhileSuspended:(BOOL)allowed
4178 Frame* frame = core([self mainFrame]);
4180 frame->animation().setAllowsNewAnimationsWhileSuspended(allowed);
4183 - (BOOL)cssAnimationsSuspended
4185 // should ask the page!
4186 Frame* frame = core([self mainFrame]);
4188 return frame->animation().isSuspended();
4193 - (void)setCSSAnimationsSuspended:(BOOL)suspended
4195 Frame* frame = core([self mainFrame]);
4196 if (suspended == frame->animation().isSuspended())
4200 frame->animation().suspendAnimations();
4202 frame->animation().resumeAnimations();
4205 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
4207 SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
4210 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
4212 SchemeRegistry::registerURLSchemeAsSecure(scheme);
4215 + (void)_registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing:(NSString *)scheme
4217 SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing(scheme);
4220 + (void)_registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing:(NSString *)scheme
4222 SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing(scheme);
4225 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
4227 _private->page->setPageScaleFactor(scale, IntPoint(origin));
4230 - (float)_viewScaleFactor
4232 return _private->page->pageScaleFactor();
4235 - (void)_setUseFixedLayout:(BOOL)fixed
4237 Frame* coreFrame = [self _mainCoreFrame];
4241 FrameView* view = coreFrame->view();
4245 view->setUseFixedLayout(fixed);
4247 view->setFixedLayoutSize(IntSize());
4251 - (void)_setFixedLayoutSize:(NSSize)size
4253 Frame* coreFrame = [self _mainCoreFrame];
4257 FrameView* view = coreFrame->view();
4261 view->setFixedLayoutSize(IntSize(size));
4262 view->forceLayout();
4266 - (BOOL)_useFixedLayout
4268 Frame* coreFrame = [self _mainCoreFrame];
4272 FrameView* view = coreFrame->view();