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 Computer, 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 "WebContextMenuClient.h"
45 #import "WebDOMOperationsPrivate.h"
46 #import "WebDataSourceInternal.h"
47 #import "WebDatabaseManagerPrivate.h"
48 #import "WebDefaultEditingDelegate.h"
49 #import "WebDefaultPolicyDelegate.h"
50 #import "WebDefaultUIDelegate.h"
51 #import "WebDelegateImplementationCaching.h"
52 #import "WebDeviceOrientationClient.h"
53 #import "WebDeviceOrientationProvider.h"
54 #import "WebDocument.h"
55 #import "WebDocumentInternal.h"
56 #import "WebDownload.h"
57 #import "WebDownloadInternal.h"
58 #import "WebDragClient.h"
59 #import "WebDynamicScrollBarsViewInternal.h"
60 #import "WebEditingDelegate.h"
61 #import "WebEditorClient.h"
62 #import "WebFormDelegatePrivate.h"
63 #import "WebFrameInternal.h"
64 #import "WebFrameLoaderClient.h"
65 #import "WebFrameNetworkingContext.h"
66 #import "WebFrameViewInternal.h"
67 #import "WebFullScreenController.h"
68 #import "WebGeolocationClient.h"
69 #import "WebGeolocationPositionInternal.h"
70 #import "WebHTMLRepresentation.h"
71 #import "WebHTMLViewInternal.h"
72 #import "WebHistoryItemInternal.h"
73 #import "WebIconDatabaseInternal.h"
74 #import "WebInspector.h"
75 #import "WebInspectorClient.h"
76 #import "WebKitErrors.h"
77 #import "WebKitFullScreenListener.h"
78 #import "WebKitLogging.h"
79 #import "WebKitNSStringExtras.h"
80 #import "WebKitStatisticsPrivate.h"
81 #import "WebKitSystemBits.h"
82 #import "WebKitVersionChecks.h"
83 #import "WebLocalizableStrings.h"
84 #import "WebNSDataExtras.h"
85 #import "WebNSDataExtrasPrivate.h"
86 #import "WebNSDictionaryExtras.h"
87 #import "WebNSEventExtras.h"
88 #import "WebNSObjectExtras.h"
89 #import "WebNSPasteboardExtras.h"
90 #import "WebNSPrintOperationExtras.h"
91 #import "WebNSURLExtras.h"
92 #import "WebNSURLRequestExtras.h"
93 #import "WebNSViewExtras.h"
94 #import "WebNodeHighlight.h"
95 #import "WebNotificationClient.h"
96 #import "WebPDFView.h"
97 #import "WebPanelAuthenticationHandler.h"
98 #import "WebPlatformStrategies.h"
99 #import "WebPluginDatabase.h"
100 #import "WebPolicyDelegate.h"
101 #import "WebPreferenceKeysPrivate.h"
102 #import "WebPreferencesPrivate.h"
103 #import "WebScriptDebugDelegate.h"
104 #import "WebScriptWorldInternal.h"
105 #import "WebStorageManagerInternal.h"
106 #import "WebSystemInterface.h"
107 #import "WebTextCompletionController.h"
108 #import "WebTextIterator.h"
109 #import "WebUIDelegate.h"
110 #import "WebUIDelegatePrivate.h"
111 #import "WebUserMediaClient.h"
112 #import <CoreFoundation/CFSet.h>
113 #import <Foundation/NSURLConnection.h>
114 #import <JavaScriptCore/APICast.h>
115 #import <JavaScriptCore/JSValueRef.h>
116 #import <WebCore/AlternativeTextUIController.h>
117 #import <WebCore/AnimationController.h>
118 #import <WebCore/ApplicationCacheStorage.h>
119 #import <WebCore/BackForwardList.h>
120 #import <WebCore/MemoryCache.h>
121 #import <WebCore/Chrome.h>
122 #import <WebCore/ColorMac.h>
123 #import <WebCore/Cursor.h>
124 #import <WebCore/DatabaseManager.h>
125 #import <WebCore/Document.h>
126 #import <WebCore/DocumentLoader.h>
127 #import <WebCore/DragController.h>
128 #import <WebCore/DragData.h>
129 #import <WebCore/DragSession.h>
130 #import <WebCore/Editor.h>
131 #import <WebCore/EventHandler.h>
132 #import <WebCore/ExceptionHandlers.h>
133 #import <WebCore/FocusController.h>
134 #import <WebCore/FrameLoader.h>
135 #import <WebCore/FrameSelection.h>
136 #import <WebCore/FrameTree.h>
137 #import <WebCore/FrameView.h>
138 #import <WebCore/GCController.h>
139 #import <WebCore/GeolocationController.h>
140 #import <WebCore/GeolocationError.h>
141 #import <WebCore/HTMLMediaElement.h>
142 #import <WebCore/HTMLNames.h>
143 #import <WebCore/HistoryController.h>
144 #import <WebCore/HistoryItem.h>
145 #import <WebCore/IconDatabase.h>
146 #import <WebCore/JSCSSStyleDeclaration.h>
147 #import <WebCore/JSDocument.h>
148 #import <WebCore/JSElement.h>
149 #import <WebCore/JSNodeList.h>
150 #import <WebCore/JSNotification.h>
151 #import <WebCore/Logging.h>
152 #import <WebCore/MIMETypeRegistry.h>
153 #import <WebCore/MainFrame.h>
154 #import <WebCore/MemoryPressureHandler.h>
155 #import <WebCore/NodeList.h>
156 #import <WebCore/Notification.h>
157 #import <WebCore/NotificationController.h>
158 #import <WebCore/Page.h>
159 #import <WebCore/PageCache.h>
160 #import <WebCore/PageGroup.h>
161 #import <WebCore/PlatformEventFactoryMac.h>
162 #import <WebCore/ProgressTracker.h>
163 #import <WebCore/RenderView.h>
164 #import <WebCore/RenderWidget.h>
165 #import <WebCore/ResourceHandle.h>
166 #import <WebCore/ResourceLoadScheduler.h>
167 #import <WebCore/ResourceRequest.h>
168 #import <WebCore/RuntimeApplicationChecks.h>
169 #import <WebCore/RuntimeEnabledFeatures.h>
170 #import <WebCore/SchemeRegistry.h>
171 #import <WebCore/ScriptController.h>
172 #import <WebCore/ScriptValue.h>
173 #import <WebCore/SecurityOrigin.h>
174 #import <WebCore/SecurityPolicy.h>
175 #import <WebCore/Settings.h>
176 #import <WebCore/StyleProperties.h>
177 #import <WebCore/SystemVersionMac.h>
178 #import <WebCore/TextResourceDecoder.h>
179 #import <WebCore/ThreadCheck.h>
180 #import <WebCore/WebCoreObjCExtras.h>
181 #import <WebCore/WebCoreView.h>
182 #import <WebCore/WebVideoFullscreenController.h>
183 #import <WebCore/Widget.h>
184 #import <WebKit/DOM.h>
185 #import <WebKit/DOMExtensions.h>
186 #import <WebKit/DOMPrivate.h>
187 #import <WebKitSystemInterface.h>
188 #import <mach-o/dyld.h>
189 #import <objc/objc-auto.h>
190 #import <objc/runtime.h>
191 #import <runtime/ArrayPrototype.h>
192 #import <runtime/DateInstance.h>
193 #import <runtime/InitializeThreading.h>
194 #import <runtime/JSLock.h>
195 #import <runtime/JSCJSValue.h>
196 #import <wtf/Assertions.h>
197 #import <wtf/HashTraits.h>
198 #import <wtf/MainThread.h>
199 #import <wtf/ObjcRuntimeExtras.h>
200 #import <wtf/RefCountedLeakCounter.h>
201 #import <wtf/RefPtr.h>
202 #import <wtf/RunLoop.h>
203 #import <wtf/StdLibExtras.h>
205 #if ENABLE(DASHBOARD_SUPPORT)
206 #import <WebKit/WebDashboardRegion.h>
209 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
210 #import "WebDiskImageCacheClientIOS.h"
211 #import <WebCore/DiskImageCacheIOS.h>
214 #if ENABLE(REMOTE_INSPECTOR)
216 #import "WebIndicateLayer.h"
224 @interface NSSpellChecker (WebNSSpellCheckerDetails)
225 - (void)_preflightChosenSpellServer;
228 @interface NSView (WebNSViewDetails)
229 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
230 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
231 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
234 @interface NSWindow (WebNSWindowDetails)
235 - (id)_oldFirstResponderBeforeBecoming;
236 - (void)_enableScreenUpdatesIfNeeded;
237 - (BOOL)_wrapsCarbonWindow;
238 - (BOOL)_hasKeyAppearance;
241 using namespace WebCore;
244 #if defined(__ppc__) || defined(__ppc64__)
245 #define PROCESSOR "PPC"
246 #elif defined(__i386__) || defined(__x86_64__)
247 #define PROCESSOR "Intel"
249 #error Unknown architecture
252 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
254 macro(alignJustified) \
257 macro(capitalizeWord) \
258 macro(centerSelectionInVisibleArea) \
259 macro(changeAttributes) \
260 macro(changeBaseWritingDirection) \
261 macro(changeBaseWritingDirectionToLTR) \
262 macro(changeBaseWritingDirectionToRTL) \
264 macro(changeDocumentBackgroundColor) \
266 macro(changeSpelling) \
267 macro(checkSpelling) \
273 macro(deleteBackward) \
274 macro(deleteBackwardByDecomposingPreviousCharacter) \
275 macro(deleteForward) \
276 macro(deleteToBeginningOfLine) \
277 macro(deleteToBeginningOfParagraph) \
278 macro(deleteToEndOfLine) \
279 macro(deleteToEndOfParagraph) \
280 macro(deleteToMark) \
281 macro(deleteWordBackward) \
282 macro(deleteWordForward) \
283 macro(ignoreSpelling) \
285 macro(insertBacktab) \
286 macro(insertLineBreak) \
287 macro(insertNewline) \
288 macro(insertNewlineIgnoringFieldEditor) \
289 macro(insertParagraphSeparator) \
291 macro(insertTabIgnoringFieldEditor) \
292 macro(lowercaseWord) \
293 macro(makeBaseWritingDirectionLeftToRight) \
294 macro(makeBaseWritingDirectionRightToLeft) \
295 macro(makeTextWritingDirectionLeftToRight) \
296 macro(makeTextWritingDirectionNatural) \
297 macro(makeTextWritingDirectionRightToLeft) \
298 macro(moveBackward) \
299 macro(moveBackwardAndModifySelection) \
301 macro(moveDownAndModifySelection) \
303 macro(moveForwardAndModifySelection) \
305 macro(moveLeftAndModifySelection) \
306 macro(moveParagraphBackwardAndModifySelection) \
307 macro(moveParagraphForwardAndModifySelection) \
309 macro(moveRightAndModifySelection) \
310 macro(moveToBeginningOfDocument) \
311 macro(moveToBeginningOfDocumentAndModifySelection) \
312 macro(moveToBeginningOfLine) \
313 macro(moveToBeginningOfLineAndModifySelection) \
314 macro(moveToBeginningOfParagraph) \
315 macro(moveToBeginningOfParagraphAndModifySelection) \
316 macro(moveToBeginningOfSentence) \
317 macro(moveToBeginningOfSentenceAndModifySelection) \
318 macro(moveToEndOfDocument) \
319 macro(moveToEndOfDocumentAndModifySelection) \
320 macro(moveToEndOfLine) \
321 macro(moveToEndOfLineAndModifySelection) \
322 macro(moveToEndOfParagraph) \
323 macro(moveToEndOfParagraphAndModifySelection) \
324 macro(moveToEndOfSentence) \
325 macro(moveToEndOfSentenceAndModifySelection) \
326 macro(moveToLeftEndOfLine) \
327 macro(moveToLeftEndOfLineAndModifySelection) \
328 macro(moveToRightEndOfLine) \
329 macro(moveToRightEndOfLineAndModifySelection) \
331 macro(moveUpAndModifySelection) \
332 macro(moveWordBackward) \
333 macro(moveWordBackwardAndModifySelection) \
334 macro(moveWordForward) \
335 macro(moveWordForwardAndModifySelection) \
336 macro(moveWordLeft) \
337 macro(moveWordLeftAndModifySelection) \
338 macro(moveWordRight) \
339 macro(moveWordRightAndModifySelection) \
340 macro(orderFrontSubstitutionsPanel) \
344 macro(pageDownAndModifySelection) \
346 macro(pageUpAndModifySelection) \
348 macro(pasteAsPlainText) \
349 macro(pasteAsRichText) \
351 macro(performFindPanelAction) \
352 macro(scrollLineDown) \
353 macro(scrollLineUp) \
354 macro(scrollPageDown) \
355 macro(scrollPageUp) \
356 macro(scrollToBeginningOfDocument) \
357 macro(scrollToEndOfDocument) \
360 macro(selectParagraph) \
361 macro(selectSentence) \
362 macro(selectToMark) \
365 macro(showGuessPanel) \
366 macro(startSpeaking) \
367 macro(stopSpeaking) \
370 macro(swapWithMark) \
371 macro(takeFindStringFromSelection) \
372 macro(toggleBaseWritingDirection) \
376 macro(uppercaseWord) \
378 macro(yankAndSelect) \
380 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
381 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
383 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
384 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
386 static BOOL s_didSetCacheModel;
387 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
390 static const char webViewIsOpen[] = "At least one WebView is still open.";
393 @interface NSObject (WebValidateWithoutDelegate)
394 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
397 @interface _WebSafeForwarder : NSObject
399 id target; // Non-retained. Don't retain delegates.
402 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
405 FindOptions coreOptions(WebFindOptions options)
407 return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
408 | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
409 | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
410 | (options & WebFindOptionsBackwards ? Backwards : 0)
411 | (options & WebFindOptionsWrapAround ? WrapAround : 0)
412 | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
415 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
417 return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
418 | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
419 | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
422 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
424 return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
425 | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
426 | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
429 static PageVisibilityState core(WebPageVisibilityState visibilityState)
431 switch (visibilityState) {
432 case WebPageVisibilityStateVisible:
433 return PageVisibilityStateVisible;
434 case WebPageVisibilityStateHidden:
435 return PageVisibilityStateHidden;
436 case WebPageVisibilityStatePrerender:
437 return PageVisibilityStatePrerender;
438 case WebPageVisibilityStateUnloaded:
439 return PageVisibilityStateUnloaded;
442 ASSERT_NOT_REACHED();
443 return PageVisibilityStateVisible;
446 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
448 switch (visibilityState) {
449 case PageVisibilityStateVisible:
450 return WebPageVisibilityStateVisible;
451 case PageVisibilityStateHidden:
452 return WebPageVisibilityStateHidden;
453 case PageVisibilityStatePrerender:
454 return WebPageVisibilityStatePrerender;
455 case PageVisibilityStateUnloaded:
456 return WebPageVisibilityStateUnloaded;
459 ASSERT_NOT_REACHED();
460 return WebPageVisibilityStateVisible;
463 @interface WebView (WebFileInternal)
464 - (float)_deviceScaleFactor;
466 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
467 - (WebFrame *)_focusedFrame;
468 + (void)_preflightSpellChecker;
469 - (BOOL)_continuousCheckingAllowed;
470 - (NSResponder *)_responderForResponderOperations;
472 - (void)_clearGlibLoopObserver;
476 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
477 NSString *WebElementFrameKey = @"WebElementFrame";
478 NSString *WebElementImageKey = @"WebElementImage";
479 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
480 NSString *WebElementImageRectKey = @"WebElementImageRect";
481 NSString *WebElementImageURLKey = @"WebElementImageURL";
482 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
483 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
484 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
485 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
486 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
487 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
488 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
489 NSString *WebElementTitleKey = @"WebElementTitle";
490 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
491 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
492 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
494 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
495 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
496 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
498 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
499 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
500 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
501 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
502 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
504 enum { WebViewVersion = 4 };
506 #define timedLayoutSize 4096
508 static NSMutableSet *schemesWithRepresentationsSet;
510 NSString *_WebCanGoBackKey = @"canGoBack";
511 NSString *_WebCanGoForwardKey = @"canGoForward";
512 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
513 NSString *_WebIsLoadingKey = @"isLoading";
514 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
515 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
516 NSString *_WebMainFrameURLKey = @"mainFrameURL";
517 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
519 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
520 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
522 #if ENABLE(REMOTE_INSPECTOR)
523 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
524 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
527 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
529 @interface WebProgressItem : NSObject
532 long long bytesReceived;
533 long long estimatedLength;
537 @implementation WebProgressItem
540 static BOOL continuousSpellCheckingEnabled;
541 static BOOL grammarCheckingEnabled;
542 static BOOL automaticQuoteSubstitutionEnabled;
543 static BOOL automaticLinkDetectionEnabled;
544 static BOOL automaticDashSubstitutionEnabled;
545 static BOOL automaticTextReplacementEnabled;
546 static BOOL automaticSpellingCorrectionEnabled;
548 @implementation WebView (AllWebViews)
550 static CFSetCallBacks NonRetainingSetCallbacks = {
559 static CFMutableSetRef allWebViewsSet;
561 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
566 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
569 - (void)_removeFromAllWebViewsSet
572 CFSetRemoveValue(allWebViewsSet, self);
575 - (void)_addToAllWebViewsSet
578 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
580 CFSetSetValue(allWebViewsSet, self);
585 @implementation WebView (WebPrivate)
587 static NSString *systemMarketingVersionForUserAgentString()
589 // Use underscores instead of dots because when we first added the Mac OS X version to the user agent string
590 // we were concerned about old DHTML libraries interpreting "4." as Netscape 4. That's no longer a concern for us
591 // but we're sticking with the underscores for compatibility with the format used by older versions of Safari.
592 return [systemMarketingVersion() stringByReplacingOccurrencesOfString:@"." withString:@"_"];
595 static NSString *createUserVisibleWebKitVersionString()
597 // If the version is 4 digits long or longer, then the first digit represents
598 // the version of the OS. Our user agent string should not include this first digit,
599 // so strip it off and report the rest as the version. <rdar://problem/4997547>
600 NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
601 NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
602 if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
603 return [[fullVersion substringFromIndex:1] copy];
604 if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
605 return [[fullVersion substringFromIndex:1] copy];
606 return [fullVersion copy];
609 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
611 // Note: Do *not* move the initialization of osVersion nor webKitVersion into the declaration.
612 // Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
613 static NSString *osVersion;
614 static NSString *webKitVersion;
616 osVersion = [systemMarketingVersionForUserAgentString() retain];
618 webKitVersion = createUserVisibleWebKitVersionString();
619 if ([applicationName length])
620 return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko) %@", osVersion, webKitVersion, applicationName];
621 return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko)", osVersion, webKitVersion];
624 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
626 if (!exception || !context)
629 JSC::ExecState* execState = toJS(context);
630 JSLockHolder lock(execState);
632 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
633 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
636 reportException(execState, toJS(execState, exception));
639 static void WebKitInitializeApplicationCachePathIfNecessary()
641 static BOOL initialized = NO;
645 NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
647 appName = [[NSProcessInfo processInfo] processName];
651 NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
653 cacheStorage().setCacheDirectory(cacheDir);
657 static bool shouldEnableLoadDeferring()
659 return !applicationIsAdobeInstaller();
662 static bool shouldRestrictWindowFocus()
664 return !applicationIsHRBlock();
667 - (void)_dispatchPendingLoadRequests
669 resourceLoadScheduler()->servePendingRequests();
672 - (void)_registerDraggedTypes
674 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
675 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
676 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
677 [types addObjectsFromArray:URLTypes];
678 [self registerForDraggedTypes:[types allObjects]];
682 static bool needsOutlookQuirksScript()
684 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
685 && applicationIsMicrosoftOutlook();
686 return isOutlookNeedingQuirksScript;
689 static NSString *leakOutlookQuirksUserScriptContents()
691 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
692 NSStringEncoding encoding;
693 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
696 -(void)_injectOutlookQuirksScript
698 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
699 core(self)->group().addUserScriptToWorld(*core([WebScriptWorld world]),
700 outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames);
703 static bool shouldRespectPriorityInCSSAttributeSetters()
705 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
706 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
707 return isIAdProducerNeedingAttributeSetterQuirk;
710 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
712 static bool shouldUseLegacyBackgroundSizeShorthandBehavior = applicationIsVersions()
713 && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
714 return shouldUseLegacyBackgroundSizeShorthandBehavior;
717 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
719 WebCoreThreadViolationCheckRoundTwo();
722 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
725 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
726 [standardPreferences willAddToWebView];
728 _private->preferences = [standardPreferences retain];
729 _private->mainFrameDocumentReady = NO;
730 _private->drawsBackground = YES;
731 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
732 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
734 NSRect f = [self frame];
735 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
736 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
737 [self addSubview:frameView];
740 static bool didOneTimeInitialization = false;
741 if (!didOneTimeInitialization) {
743 WebKitInitializeLoggingChannelsIfNecessary();
744 WebCore::initializeLoggingChannelsIfNecessary();
745 #endif // !LOG_DISABLED
747 // Initialize our platform strategies first before invoking the rest
748 // of the initialization code which may depend on the strategies.
749 WebPlatformStrategies::initializeIfNecessary();
751 #if ENABLE(SQL_DATABASE)
752 [WebDatabaseManager sharedWebDatabaseManager];
755 WebKitInitializeStorageIfNecessary();
756 WebKitInitializeApplicationCachePathIfNecessary();
757 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
758 WebKitInitializeWebDiskImageCache();
761 Settings::setDefaultMinDOMTimerInterval(0.004);
763 Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
765 didOneTimeInitialization = true;
768 Page::PageClients pageClients;
769 pageClients.chromeClient = new WebChromeClient(self);
770 pageClients.contextMenuClient = new WebContextMenuClient(self);
771 pageClients.editorClient = new WebEditorClient(self);
772 #if ENABLE(DRAG_SUPPORT)
773 pageClients.dragClient = new WebDragClient(self);
775 pageClients.inspectorClient = new WebInspectorClient(self);
776 pageClients.alternativeTextClient = new WebAlternativeTextClient(self);
777 pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
778 _private->page = new Page(pageClients);
779 #if ENABLE(GEOLOCATION)
780 WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
782 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
783 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
785 #if ENABLE(DEVICE_ORIENTATION)
786 WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
788 #if ENABLE(MEDIA_STREAM)
789 WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
792 #if ENABLE(REMOTE_INSPECTOR)
793 _private->page->setRemoteInspectionAllowed(true);
796 _private->page->setCanStartMedia([self window]);
797 _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
798 _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
800 if (needsOutlookQuirksScript()) {
801 _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
802 [self _injectOutlookQuirksScript];
805 if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
806 [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
808 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
810 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
812 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
813 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
815 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
817 [self _addToAllWebViewsSet];
818 [self setGroupName:groupName];
820 // If there's already a next key view (e.g., from a nib), wire it up to our
821 // contained frame view. In any case, wire our next key view up to the our
822 // contained frame view. This works together with our becomeFirstResponder
823 // and setNextKeyView overrides.
824 NSView *nextKeyView = [self nextKeyView];
825 if (nextKeyView && nextKeyView != frameView)
826 [frameView setNextKeyView:nextKeyView];
827 [super setNextKeyView:frameView];
829 if ([[self class] shouldIncludeInWebKitStatistics])
832 [self _registerDraggedTypes];
834 [self _setVisibilityState:([self _isViewVisible] ? WebPageVisibilityStateVisible : WebPageVisibilityStateHidden) isInitialState:YES];
836 WebPreferences *prefs = [self preferences];
837 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
838 name:WebPreferencesChangedInternalNotification object:prefs];
840 [self _preferencesChanged:[self preferences]];
841 [[self preferences] _postPreferencesChangedAPINotification];
843 memoryPressureHandler().install();
845 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
846 // Originally, we allowed all local loads.
847 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
848 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
849 // Later, we allowed local loads for local URLs and documents loaded
850 // with substitute data.
851 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
854 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
855 ResourceHandle::forceContentSniffing();
858 [self _scheduleGlibContextIterations];
862 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
864 // FIXME: Remove the usesDocumentViews parameter; it's only here for compatibility with WebKit nightly builds
865 // running against Safari 5 on Leopard.
866 ASSERT(usesDocumentViews);
868 self = [super initWithFrame:f];
872 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
873 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
874 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
875 // need for Safari to unset it to prevent it from being passed to applications it launches.
876 // Unsetting it when a WebView is first created is as good a place as any.
877 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
878 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
879 unsetenv("DYLD_FRAMEWORK_PATH");
880 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
884 _private = [[WebViewPrivate alloc] init];
885 [self _commonInitializationWithFrameName:frameName groupName:groupName];
886 [self setMaintainsBackForwardList: YES];
887 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
891 - (void)_viewWillDrawInternal
893 Frame* frame = [self _mainCoreFrame];
894 if (frame && frame->view())
895 frame->view()->updateLayoutAndStyleIfNeededRecursive();
898 + (NSArray *)_supportedMIMETypes
900 // Load the plug-in DB allowing plug-ins to install types.
901 [WebPluginDatabase sharedDatabase];
902 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
905 + (NSArray *)_supportedFileExtensions
907 NSMutableSet *extensions = [[NSMutableSet alloc] init];
908 NSArray *MIMETypes = [self _supportedMIMETypes];
909 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
911 while ((MIMEType = [enumerator nextObject]) != nil) {
912 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
913 if (extensionsForType) {
914 [extensions addObjectsFromArray:extensionsForType];
917 NSArray *uniqueExtensions = [extensions allObjects];
918 [extensions release];
919 return uniqueExtensions;
922 static NSMutableSet *knownPluginMIMETypes()
924 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
929 + (void)_registerPluginMIMEType:(NSString *)MIMEType
931 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
932 [knownPluginMIMETypes() addObject:MIMEType];
935 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
937 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
938 [knownPluginMIMETypes() removeObject:MIMEType];
941 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
943 MIMEType = [MIMEType lowercaseString];
944 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
945 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
947 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
948 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
951 // Load the plug-in DB allowing plug-ins to install types.
952 [WebPluginDatabase sharedDatabase];
955 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
956 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
957 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
960 if (viewClass && repClass) {
961 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
962 // Special-case WebHTMLView for text types that shouldn't be shown.
963 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
966 // If the MIME type is a known plug-in we might not want to load it.
967 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
968 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
969 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
971 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
972 if (!isSupportedByWebKit)
986 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
988 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
991 if (_private->pluginDatabase) {
992 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
995 *vClass = [WebHTMLView class];
997 *rClass = [WebHTMLRepresentation class];
1005 + (void)_setAlwaysUseATSU:(BOOL)f
1007 [self _setAlwaysUsesComplexTextCodePath:f];
1010 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1012 Font::setCodePath(f ? Font::Complex : Font::Auto);
1015 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1017 TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1020 + (BOOL)_allowsRoundingHacks
1022 return TextRun::allowsRoundingHacks();
1025 + (BOOL)canCloseAllWebViews
1027 return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1030 + (void)closeAllWebViews
1032 DOMWindow::dispatchAllPendingUnloadEvents();
1034 // This will close the WebViews in a random order. Change this if close order is important.
1035 // Make a new set to avoid mutating the set we are enumerating.
1036 NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet];
1037 NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1038 while (WebView *webView = [enumerator nextObject])
1042 + (BOOL)canShowFile:(NSString *)path
1044 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1047 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1049 return WKGetPreferredExtensionForMIMEType(type);
1054 return !_private || _private->closed;
1057 - (void)_closePluginDatabases
1059 pluginDatabaseClientCount--;
1061 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1063 // Unload the WebView local plug-in database.
1064 if (_private->pluginDatabase) {
1065 [_private->pluginDatabase destroyAllPluginInstanceViews];
1066 [_private->pluginDatabase close];
1067 [_private->pluginDatabase release];
1068 _private->pluginDatabase = nil;
1071 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1072 if (!pluginDatabaseClientCount && applicationIsTerminating)
1073 [WebPluginDatabase closeSharedDatabase];
1076 - (void)_closeWithFastTeardown
1079 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1082 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1083 [[NSNotificationCenter defaultCenter] removeObserver:self];
1085 [self _closePluginDatabases];
1088 static bool fastDocumentTeardownEnabled()
1091 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1093 static bool initialized = false;
1094 static bool enabled = false;
1096 // This allows debug builds to default to not have fast teardown, so leak checking still works.
1097 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1098 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1100 enabled = ![setting boolValue];
1107 // _close is here only for backward compatibility; clients and subclasses should use
1108 // public method -close instead.
1111 if (!_private || _private->closed)
1114 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1116 _private->closed = YES;
1117 [self _removeFromAllWebViewsSet];
1120 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1123 // To quit the apps fast we skip document teardown, except plugins
1124 // need to be destroyed and unloaded.
1125 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1126 [self _closeWithFastTeardown];
1131 [self _exitFullscreen];
1134 if (Frame* mainFrame = [self _mainCoreFrame])
1135 mainFrame->loader().detachFromParent();
1137 [self setHostWindow:nil];
1139 [self setDownloadDelegate:nil];
1140 [self setEditingDelegate:nil];
1141 [self setFrameLoadDelegate:nil];
1142 [self setPolicyDelegate:nil];
1143 [self setResourceLoadDelegate:nil];
1144 [self setScriptDebugDelegate:nil];
1145 [self setUIDelegate:nil];
1147 [_private->inspector webViewClosed];
1149 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1150 [self removeDragCaret];
1152 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1153 // all the plug-ins in the page cache to break any retain cycles.
1154 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1155 Page* page = _private->page;
1159 if (_private->hasSpellCheckerDocumentTag) {
1160 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1161 _private->hasSpellCheckerDocumentTag = NO;
1164 #if USE(ACCELERATED_COMPOSITING)
1165 if (_private->layerFlushController) {
1166 _private->layerFlushController->invalidate();
1167 _private->layerFlushController = nullptr;
1172 [self _clearGlibLoopObserver];
1175 [[self _notificationProvider] unregisterWebView:self];
1177 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1178 [[NSNotificationCenter defaultCenter] removeObserver:self];
1180 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1182 WebPreferences *preferences = _private->preferences;
1183 _private->preferences = nil;
1184 [preferences didRemoveFromWebView];
1185 [preferences release];
1187 [self _closePluginDatabases];
1190 // Need this to make leak messages accurate.
1191 if (applicationIsTerminating) {
1192 gcController().garbageCollectNow();
1193 [WebCache setDisabled:YES];
1198 // Indicates if the WebView is in the midst of a user gesture.
1199 - (BOOL)_isProcessingUserGesture
1201 return ScriptController::processingUserGesture();
1204 + (NSString *)_MIMETypeForFile:(NSString *)path
1206 NSString *extension = [path pathExtension];
1207 NSString *MIMEType = nil;
1209 // Get the MIME type from the extension.
1210 if ([extension length] != 0) {
1211 MIMEType = WKGetMIMETypeForExtension(extension);
1214 // If we can't get a known MIME type from the extension, sniff.
1215 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1216 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1217 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1219 if ([data length] != 0) {
1220 MIMEType = [data _webkit_guessedMIMEType];
1222 if ([MIMEType length] == 0) {
1223 MIMEType = @"application/octet-stream";
1230 - (WebDownload *)_downloadURL:(NSURL *)URL
1234 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1235 WebDownload *download = [WebDownload _downloadWithRequest:request
1236 delegate:_private->downloadDelegate
1243 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1245 NSDictionary *features = [[NSDictionary alloc] init];
1246 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1247 createWebViewWithRequest:nil
1248 windowFeatures:features];
1250 if (!newWindowWebView)
1253 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1254 return newWindowWebView;
1257 - (WebInspector *)inspector
1259 if (!_private->inspector)
1260 _private->inspector = [[WebInspector alloc] initWithWebView:self];
1261 return _private->inspector;
1264 #if ENABLE(REMOTE_INSPECTOR)
1265 + (void)_enableRemoteInspector
1267 // FIXME: Move this to a new Inspector::RemoteInspectorServer interface or remove it.
1270 + (void)_disableRemoteInspector
1272 // FIXME: Move this to a new Inspector::RemoteInspectorServer interface or remove it.
1275 + (void)_disableAutoStartRemoteInspector
1277 // FIXME: Move this to a new Inspector::RemoteInspectorServer interface or remove it.
1280 + (BOOL)_isRemoteInspectorEnabled
1282 // FIXME: Move this to a new Inspector::RemoteInspectorServer interface or remove it.
1286 + (BOOL)_hasRemoteInspectorSession
1288 // FIXME: Move this to a new Inspector::RemoteInspectorServer interface or remove it.
1292 - (BOOL)allowsRemoteInspection
1294 // FIXME: Move this to a new API.
1298 - (void)setAllowsRemoteInspection:(BOOL)allow
1300 // FIXME: Move this to a new API.
1303 - (void)setIndicatingForRemoteInspector:(BOOL)enabled
1306 ASSERT(WebThreadIsLocked());
1309 if (!_private->indicateLayer) {
1310 _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1311 [_private->indicateLayer setNeedsLayout];
1312 [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1315 [_private->indicateLayer removeFromSuperlayer];
1316 [_private->indicateLayer release];
1317 _private->indicateLayer = nil;
1320 // FIXME: Needs implementation or put an implementation in WebCore::InspectorOverlay.
1325 - (void)setHostApplicationBundleId:(NSString *)bundleId name:(NSString *)name
1327 // FIXME: This has not yet been ported to Inspector::RemoteInspectorServer.
1329 if (![_private->hostApplicationBundleId isEqualToString:bundleId]) {
1330 [_private->hostApplicationBundleId release];
1331 _private->hostApplicationBundleId = [bundleId copy];
1334 if (![_private->hostApplicationName isEqualToString:name]) {
1335 [_private->hostApplicationName release];
1336 _private->hostApplicationName = [name copy];
1339 [[WebView sharedWebInspectorServer] pushListing];
1342 - (NSString *)hostApplicationBundleId
1344 return _private->hostApplicationBundleId;
1347 - (NSString *)hostApplicationName
1349 return _private->hostApplicationName;
1351 #endif // PLATFORM(IOS)
1352 #endif // ENABLE(REMOTE_INSPECTOR)
1354 - (WebCore::Page*)page
1356 return _private->page;
1359 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1361 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1362 NSArray *menuItems = defaultMenuItems;
1364 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1365 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1366 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1367 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1368 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1373 unsigned count = [menuItems count];
1377 NSMenu *menu = [[NSMenu alloc] init];
1378 for (unsigned i = 0; i < count; i++)
1379 [menu addItem:[menuItems objectAtIndex:i]];
1381 return [menu autorelease];
1384 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1386 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1387 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1388 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1391 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1394 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1396 if (!_private->page)
1399 if (!otherView->_private->page)
1402 // It turns out the right combination of behavior is done with the back/forward load
1403 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
1404 // in the back forward list, and go to the current one.
1406 BackForwardClient* backForwardClient = _private->page->backForwardClient();
1407 ASSERT(!backForwardClient->currentItem()); // destination list should be empty
1409 BackForwardClient* otherBackForwardClient = otherView->_private->page->backForwardClient();
1410 if (!otherBackForwardClient->currentItem())
1411 return; // empty back forward list, bail
1413 HistoryItem* newItemToGoTo = 0;
1415 int lastItemIndex = otherBackForwardClient->forwardListCount();
1416 for (int i = -otherBackForwardClient->backListCount(); i <= lastItemIndex; ++i) {
1418 // If this item is showing , save away its current scroll and form state,
1419 // since that might have changed since loading and it is normally not saved
1420 // until we leave that page.
1421 otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
1423 RefPtr<HistoryItem> newItem = otherBackForwardClient->itemAtIndex(i)->copy();
1425 newItemToGoTo = newItem.get();
1426 backForwardClient->addItem(newItem.release());
1429 ASSERT(newItemToGoTo);
1430 _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
1433 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
1435 _private->formDelegate = delegate;
1438 - (id<WebFormDelegate>)_formDelegate
1440 return _private->formDelegate;
1443 - (BOOL)_needsAdobeFrameReloadingQuirk
1445 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
1446 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
1447 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
1448 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
1449 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
1450 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
1451 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
1452 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
1453 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
1454 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
1459 - (BOOL)_needsLinkElementTextCSSQuirk
1461 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
1462 && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
1466 - (BOOL)_needsIsLoadingInAPISenseQuirk
1468 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
1473 - (BOOL)_needsKeyboardEventDisambiguationQuirks
1475 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
1479 - (BOOL)_needsFrameLoadDelegateRetainQuirk
1481 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);
1485 static bool needsSelfRetainWhileLoadingQuirk()
1487 static bool needsQuirk = applicationIsAperture();
1491 - (BOOL)_needsPreHTML5ParserQuirks
1493 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
1494 // with the new HTML5 parser. If these applications were linked against a
1495 // version of WebKit prior to the introduction of the HTML5 parser, enable
1496 // parser quirks to maintain compatibility. For details, see
1497 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
1498 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
1499 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1500 && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
1502 // Mail.app must continue to display HTML email that contains quirky markup.
1503 static bool isAppleMail = applicationIsAppleMail();
1505 return isApplicationNeedingParserQuirks
1507 #if ENABLE(DASHBOARD_SUPPORT)
1508 // Pre-HTML5 parser quirks are required to remain compatible with many
1509 // Dashboard widgets. See <rdar://problem/8175982>.
1510 || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
1512 || [[self preferences] usePreHTML5ParserQuirks];
1515 - (BOOL)_needsUnrestrictedGetMatchedCSSRules
1517 static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
1518 return needsUnrestrictedGetMatchedCSSRules;
1521 - (void)_preferencesChangedNotification:(NSNotification *)notification
1523 WebPreferences *preferences = (WebPreferences *)[notification object];
1524 [self _preferencesChanged:preferences];
1527 - (void)_preferencesChanged:(WebPreferences *)preferences
1529 ASSERT(preferences == [self preferences]);
1530 if (!_private->userAgentOverridden)
1531 _private->userAgent = String();
1533 // Cache this value so we don't have to read NSUserDefaults on each page load
1534 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
1536 // Update corresponding WebCore Settings object.
1537 if (!_private->page)
1540 Settings& settings = _private->page->settings();
1542 settings.setCursiveFontFamily([preferences cursiveFontFamily]);
1543 settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
1544 settings.setDefaultFontSize([preferences defaultFontSize]);
1545 settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
1546 settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
1547 settings.setFantasyFontFamily([preferences fantasyFontFamily]);
1548 settings.setFixedFontFamily([preferences fixedFontFamily]);
1549 settings.setScreenFontSubstitutionEnabled(
1550 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1551 [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
1553 [preferences screenFontSubstitutionEnabled]
1555 settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
1556 settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
1557 settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
1558 settings.setJavaEnabled([preferences isJavaEnabled]);
1559 settings.setScriptEnabled([preferences isJavaScriptEnabled]);
1560 settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
1561 settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
1562 settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
1563 settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
1564 settings.setMinimumFontSize([preferences minimumFontSize]);
1565 settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
1566 settings.setPictographFontFamily([preferences pictographFontFamily]);
1567 settings.setPluginsEnabled([preferences arePlugInsEnabled]);
1568 #if ENABLE(SQL_DATABASE)
1569 DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
1571 settings.setLocalStorageEnabled([preferences localStorageEnabled]);
1572 settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
1574 bool privateBrowsingEnabled = [preferences privateBrowsingEnabled];
1575 #if PLATFORM(MAC) || USE(CFNETWORK)
1576 if (privateBrowsingEnabled)
1577 WebFrameNetworkingContext::ensurePrivateBrowsingSession();
1579 WebFrameNetworkingContext::destroyPrivateBrowsingSession();
1581 settings.setPrivateBrowsingEnabled(privateBrowsingEnabled);
1583 settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
1584 settings.setSerifFontFamily([preferences serifFontFamily]);
1585 settings.setStandardFontFamily([preferences standardFontFamily]);
1586 settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
1587 settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
1588 settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
1589 settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
1590 settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
1591 settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
1592 settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
1593 settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
1594 settings.setUsesPageCache([self usesPageCache]);
1595 settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
1596 settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
1597 settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
1598 settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
1599 settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
1600 settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
1601 settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
1602 settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
1603 if ([preferences userStyleSheetEnabled]) {
1604 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
1605 if ([location isEqualToString:@"apple-dashboard://stylesheet"])
1606 location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
1607 settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
1609 settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
1610 settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
1611 settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
1612 settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
1613 settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
1614 settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
1615 settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
1616 settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
1617 settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
1618 settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
1619 settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
1620 settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
1622 // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
1623 // Until we fix that, I will comment out the test (CFM)
1624 settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
1625 settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1626 settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
1627 settings.setShowDebugBorders([preferences showDebugBorders]);
1628 settings.setShowRepaintCounter([preferences showRepaintCounter]);
1629 settings.setWebGLEnabled([preferences webGLEnabled]);
1630 settings.setMultithreadedWebGLEnabled([preferences multithreadedWebGLEnabled]);
1631 settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
1632 settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
1633 settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
1634 settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
1635 settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
1636 settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
1637 settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
1638 #if ENABLE(CSS_SHADERS)
1639 settings.setCSSCustomFilterEnabled([preferences cssCustomFilterEnabled]);
1641 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
1642 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
1643 #if ENABLE(WEB_AUDIO)
1644 settings.setWebAudioEnabled([preferences webAudioEnabled]);
1646 #if ENABLE(IFRAME_SEAMLESS)
1647 RuntimeEnabledFeatures::sharedFeatures().setSeamlessIFramesEnabled([preferences seamlessIFramesEnabled]);
1649 settings.setCSSGridLayoutEnabled([preferences cssGridLayoutEnabled]);
1650 #if ENABLE(FULLSCREEN_API)
1651 settings.setFullScreenEnabled([preferences fullScreenEnabled]);
1653 settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
1654 settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
1655 settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
1656 settings.setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
1657 settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
1658 settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
1659 #if USE(AVFOUNDATION)
1660 settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
1663 settings.setQTKitEnabled([preferences isQTKitEnabled]);
1665 settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
1666 settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
1667 settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
1668 settings.setRegionBasedColumnsEnabled([preferences regionBasedColumnsEnabled]);
1669 settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
1670 settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
1671 settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
1673 #if ENABLE(VIDEO_TRACK)
1674 settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
1675 settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
1676 settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
1679 settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
1680 settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
1681 settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
1682 settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
1683 settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
1685 settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
1687 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1688 settings->setVideoPluginProxyEnabled([preferences isVideoPluginProxyEnabled]);
1691 switch ([preferences storageBlockingPolicy]) {
1692 case WebAllowAllStorage:
1693 settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
1695 case WebBlockThirdPartyStorage:
1696 settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
1698 case WebBlockAllStorage:
1699 settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
1703 settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
1705 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
1706 settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
1708 #if ENABLE(PAGE_VISIBILITY_API)
1709 settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
1712 // We have enabled this setting in WebKit2 for the sake of some ScrollingCoordinator work.
1713 // To avoid possible rendering differences, we should enable it for WebKit1 too.
1714 settings.setFixedPositionCreatesStackingContext(true);
1716 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
1718 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
1720 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
1721 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
1723 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
1724 if (_private->zoomsTextOnly != zoomsTextOnly)
1725 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
1727 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
1728 DiskImageCache& diskImageCache = WebCore::diskImageCache();
1729 diskImageCache.setEnabled([preferences diskImageCacheEnabled]);
1730 diskImageCache.setMinimumImageSize([preferences diskImageCacheMinimumImageSize]);
1731 diskImageCache.setMaximumCacheSize([preferences diskImageCacheMaximumCacheSize]);
1735 static inline IMP getMethod(id o, SEL s)
1737 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1740 - (void)_cacheResourceLoadDelegateImplementations
1742 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1743 id delegate = _private->resourceProgressDelegate;
1746 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1750 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
1751 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1752 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1753 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1754 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1755 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1756 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
1758 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1759 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1760 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1761 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1762 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1763 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1764 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
1765 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
1768 - (void)_cacheFrameLoadDelegateImplementations
1770 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1771 id delegate = _private->frameLoadDelegate;
1774 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1778 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1779 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1780 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
1781 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
1782 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
1783 #if JSC_OBJC_API_ENABLED
1784 cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
1786 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1787 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
1788 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
1789 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1790 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1791 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1792 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1793 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1794 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1795 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
1796 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
1797 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1798 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1799 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1800 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1801 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1802 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1803 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1804 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1805 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
1806 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
1807 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
1808 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
1810 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
1811 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
1812 // for backwards compatibility.
1813 Page* page = core(self);
1815 unsigned milestones = DidFirstLayout;
1816 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
1817 milestones |= DidFirstVisuallyNonEmptyLayout;
1818 page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1822 - (void)_cacheScriptDebugDelegateImplementations
1824 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
1825 id delegate = _private->scriptDebugDelegate;
1828 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
1832 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
1833 if (cache->didParseSourceFunc)
1834 cache->didParseSourceExpectsBaseLineNumber = YES;
1836 cache->didParseSourceExpectsBaseLineNumber = NO;
1837 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
1840 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
1842 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
1843 if (cache->exceptionWasRaisedFunc)
1844 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
1846 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
1847 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
1851 - (void)_cacheHistoryDelegateImplementations
1853 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
1854 id delegate = _private->historyDelegate;
1857 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
1861 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
1862 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
1863 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
1864 cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
1865 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
1866 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
1869 - (id)_policyDelegateForwarder
1871 if (!_private->policyDelegateForwarder)
1872 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
1873 return _private->policyDelegateForwarder;
1876 - (id)_UIDelegateForwarder
1878 if (!_private->UIDelegateForwarder)
1879 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
1880 return _private->UIDelegateForwarder;
1883 - (id)_editingDelegateForwarder
1885 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1886 // Not sure if that is a bug or not.
1890 if (!_private->editingDelegateForwarder)
1891 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
1892 return _private->editingDelegateForwarder;
1895 - (void)_closeWindow
1897 [[self _UIDelegateForwarder] webViewClose:self];
1900 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
1902 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1903 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1905 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1906 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1907 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1908 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1911 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
1913 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1914 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1916 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1917 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1918 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1919 if ([viewClass class] == [WebHTMLView class])
1920 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1922 // This is used to make _representationExistsForURLScheme faster.
1923 // Without this set, we'd have to create the MIME type each time.
1924 if (schemesWithRepresentationsSet == nil) {
1925 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1927 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1930 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1932 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1935 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1937 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1940 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
1942 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
1946 if ([NSURLConnection canHandleRequest:request])
1949 NSString *scheme = [[request URL] scheme];
1951 // Representations for URL schemes work at the top level.
1952 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
1955 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
1959 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
1966 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1968 return [self _canHandleRequest:request forMainFrame:YES];
1971 + (NSString *)_decodeData:(NSData *)data
1973 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1974 RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
1975 String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1976 result.append(decoder->flush());
1980 - (void)_pushPerformingProgrammaticFocus
1982 _private->programmaticFocusCount++;
1985 - (void)_popPerformingProgrammaticFocus
1987 _private->programmaticFocusCount--;
1990 - (BOOL)_isPerformingProgrammaticFocus
1992 return _private->programmaticFocusCount != 0;
1995 - (void)_didChangeValueForKey: (NSString *)key
1997 LOG (Bindings, "calling didChangeValueForKey: %@", key);
1998 [self didChangeValueForKey: key];
2001 - (void)_willChangeValueForKey: (NSString *)key
2003 LOG (Bindings, "calling willChangeValueForKey: %@", key);
2004 [self willChangeValueForKey: key];
2007 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2008 static NSSet *manualNotifyKeys = nil;
2009 if (!manualNotifyKeys)
2010 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2011 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2013 if ([manualNotifyKeys containsObject:key])
2018 - (NSArray *)_declaredKeys {
2019 static NSArray *declaredKeys = nil;
2021 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2022 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2023 return declaredKeys;
2026 - (void)setObservationInfo:(void *)info
2028 _private->observationInfo = info;
2031 - (void *)observationInfo
2033 return _private->observationInfo;
2036 - (void)_willChangeBackForwardKeys
2038 [self _willChangeValueForKey: _WebCanGoBackKey];
2039 [self _willChangeValueForKey: _WebCanGoForwardKey];
2042 - (void)_didChangeBackForwardKeys
2044 [self _didChangeValueForKey: _WebCanGoBackKey];
2045 [self _didChangeValueForKey: _WebCanGoForwardKey];
2048 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2050 if (needsSelfRetainWhileLoadingQuirk())
2053 [self _willChangeBackForwardKeys];
2054 if (frame == [self mainFrame]){
2055 // Force an observer update by sending a will/did.
2056 [self _willChangeValueForKey: _WebIsLoadingKey];
2057 [self _didChangeValueForKey: _WebIsLoadingKey];
2059 [self _willChangeValueForKey: _WebMainFrameURLKey];
2062 [NSApp setWindowsNeedUpdate:YES];
2064 #if ENABLE(FULLSCREEN_API)
2065 Document* document = core([frame DOMDocument]);
2066 if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2067 SEL selector = @selector(webView:closeFullScreenWithListener:);
2068 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2069 WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2070 CallUIDelegate(self, selector, listener);
2072 } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2073 [_private->newFullscreenController close];
2079 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2081 if (frame == [self mainFrame])
2082 [self _didChangeValueForKey: _WebMainFrameURLKey];
2083 [NSApp setWindowsNeedUpdate:YES];
2086 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2088 if (needsSelfRetainWhileLoadingQuirk())
2089 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2091 [self _didChangeBackForwardKeys];
2092 if (frame == [self mainFrame]){
2093 // Force an observer update by sending a will/did.
2094 [self _willChangeValueForKey: _WebIsLoadingKey];
2095 [self _didChangeValueForKey: _WebIsLoadingKey];
2097 [NSApp setWindowsNeedUpdate:YES];
2100 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2102 if (needsSelfRetainWhileLoadingQuirk())
2103 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2105 [self _didChangeBackForwardKeys];
2106 if (frame == [self mainFrame]){
2107 // Force an observer update by sending a will/did.
2108 [self _willChangeValueForKey: _WebIsLoadingKey];
2109 [self _didChangeValueForKey: _WebIsLoadingKey];
2111 [NSApp setWindowsNeedUpdate:YES];
2114 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2116 if (needsSelfRetainWhileLoadingQuirk())
2117 [self performSelector:@selector(release) withObject:nil afterDelay:0];
2119 [self _didChangeBackForwardKeys];
2120 if (frame == [self mainFrame]){
2121 // Force an observer update by sending a will/did.
2122 [self _willChangeValueForKey: _WebIsLoadingKey];
2123 [self _didChangeValueForKey: _WebIsLoadingKey];
2125 [self _didChangeValueForKey: _WebMainFrameURLKey];
2127 [NSApp setWindowsNeedUpdate:YES];
2130 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2132 RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2133 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2134 NSCachedURLResponse *cachedResponse;
2136 if (!_private->page)
2139 if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2140 cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2142 cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2144 return cachedResponse;
2147 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2149 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2150 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2151 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2153 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2154 title:[element objectForKey:WebElementImageAltStringKey]
2155 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2160 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2162 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2163 andTitle:[element objectForKey:WebElementLinkLabelKey]
2167 #if ENABLE(DRAG_SUPPORT)
2168 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2170 if (!_private->page)
2172 _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2176 #if ENABLE(DASHBOARD_SUPPORT)
2178 #define DASHBOARD_CONTROL_LABEL @"control"
2180 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2182 NSRect adjustedBounds = bounds;
2183 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2184 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2185 adjustedBounds.size = bounds.size;
2187 NSRect adjustedClip;
2188 adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2189 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2190 adjustedClip.size = clip.size;
2192 WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds
2193 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2194 NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2195 if (!scrollerRegions) {
2196 scrollerRegions = [[NSMutableArray alloc] init];
2197 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2198 [scrollerRegions release];
2200 [scrollerRegions addObject:region];
2204 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2206 NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
2208 for (const auto& widget: frameView->children()) {
2209 if (widget->isFrameView()) {
2210 [self _addScrollerDashboardRegionsForFrameView:toFrameView(widget.get()) dashboardRegions:regions];
2214 if (!widget->isScrollbar())
2217 // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
2218 // it's not common to need this to be correct in Dashboard widgets.
2219 NSRect bounds = widget->frameRect();
2220 [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
2224 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
2226 // Add scroller regions for NSScroller and WebCore scrollbars
2227 NSUInteger count = [views count];
2228 for (NSUInteger i = 0; i < count; i++) {
2229 NSView *view = [views objectAtIndex:i];
2231 if ([view isKindOfClass:[WebHTMLView class]]) {
2232 if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
2233 if (FrameView* coreView = coreFrame->view())
2234 [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
2236 } else if ([view isKindOfClass:[NSScroller class]]) {
2237 // AppKit places absent scrollers at -100,-100
2238 if ([view frame].origin.y < 0)
2240 [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
2242 [self _addScrollerDashboardRegions:regions from:[view subviews]];
2246 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
2248 [self _addScrollerDashboardRegions:regions from:[self subviews]];
2251 - (NSDictionary *)_dashboardRegions
2253 // Only return regions from main frame.
2254 Frame* mainFrame = [self _mainCoreFrame];
2258 const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
2259 size_t size = regions.size();
2261 NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
2262 for (size_t i = 0; i < size; i++) {
2263 const AnnotatedRegionValue& region = regions[i];
2265 if (region.type == StyleDashboardRegion::None)
2268 NSString *label = region.label;
2269 WebDashboardRegionType type = WebDashboardRegionTypeNone;
2270 if (region.type == StyleDashboardRegion::Circle)
2271 type = WebDashboardRegionTypeCircle;
2272 else if (region.type == StyleDashboardRegion::Rectangle)
2273 type = WebDashboardRegionTypeRectangle;
2274 NSMutableArray *regionValues = [webRegions objectForKey:label];
2275 if (!regionValues) {
2276 regionValues = [[NSMutableArray alloc] initWithCapacity:1];
2277 [webRegions setObject:regionValues forKey:label];
2278 [regionValues release];
2281 WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:pixelSnappedIntRect(region.bounds) clip:pixelSnappedIntRect(region.clip) type:type];
2282 [regionValues addObject:webRegion];
2283 [webRegion release];
2286 [self _addScrollerDashboardRegions:webRegions];
2291 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
2293 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
2294 // specific support for the backward compatibility mode flag.
2295 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
2296 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
2299 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2300 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
2303 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2304 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
2307 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2308 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
2311 case WebDashboardBehaviorAllowWheelScrolling: {
2312 _private->dashboardBehaviorAllowWheelScrolling = flag;
2315 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2317 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
2318 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
2319 RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
2325 // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
2326 // compatibility mode. See <rdar://problem/8175982>.
2328 _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2331 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
2334 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2335 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
2337 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2338 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
2340 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2341 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
2343 case WebDashboardBehaviorAllowWheelScrolling: {
2344 return _private->dashboardBehaviorAllowWheelScrolling;
2346 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2347 return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
2353 #endif /* ENABLE(DASHBOARD_SUPPORT) */
2355 + (void)_setShouldUseFontSmoothing:(BOOL)f
2357 Font::setShouldUseSmoothing(f);
2360 + (BOOL)_shouldUseFontSmoothing
2362 return Font::shouldUseSmoothing();
2365 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
2367 setUsesTestModeFocusRingColor(f);
2370 + (BOOL)_usesTestModeFocusRingColor
2372 return usesTestModeFocusRingColor();
2375 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
2377 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2379 [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2381 [scrollview setVerticalScrollingModeLocked:NO];
2382 [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
2386 - (BOOL)alwaysShowVerticalScroller
2388 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2389 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
2392 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
2394 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2396 [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2398 [scrollview setHorizontalScrollingModeLocked:NO];
2399 [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
2403 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
2405 if (Frame* mainFrame = [self _mainCoreFrame])
2406 mainFrame->view()->setProhibitsScrolling(prohibits);
2409 - (BOOL)alwaysShowHorizontalScroller
2411 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2412 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
2415 - (void)_setInViewSourceMode:(BOOL)flag
2417 if (Frame* mainFrame = [self _mainCoreFrame])
2418 mainFrame->setInViewSourceMode(flag);
2421 - (BOOL)_inViewSourceMode
2423 Frame* mainFrame = [self _mainCoreFrame];
2424 return mainFrame && mainFrame->inViewSourceMode();
2427 - (void)_setUseFastImageScalingMode:(BOOL)flag
2429 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
2430 _private->page->setInLowQualityImageInterpolationMode(flag);
2431 [self setNeedsDisplay:YES];
2435 - (BOOL)_inFastImageScalingMode
2438 return _private->page->inLowQualityImageInterpolationMode();
2442 - (BOOL)_cookieEnabled
2445 return _private->page->settings().cookieEnabled();
2449 - (void)_setCookieEnabled:(BOOL)enable
2452 _private->page->settings().setCookieEnabled(enable);
2455 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
2457 if (!_private->pluginDatabase)
2458 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
2460 [_private->pluginDatabase setPlugInPaths:newPaths];
2461 [_private->pluginDatabase refresh];
2464 - (void)_attachScriptDebuggerToAllFrames
2466 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
2467 [kit(frame) _attachScriptDebugger];
2470 - (void)_detachScriptDebuggerFromAllFrames
2472 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
2473 [kit(frame) _detachScriptDebugger];
2476 - (void)setBackgroundColor:(NSColor *)backgroundColor
2478 if ([_private->backgroundColor isEqual:backgroundColor])
2481 id old = _private->backgroundColor;
2482 _private->backgroundColor = [backgroundColor retain];
2485 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
2488 - (NSColor *)backgroundColor
2490 return _private->backgroundColor;
2493 - (BOOL)defersCallbacks
2495 if (!_private->page)
2497 return _private->page->defersLoading();
2500 - (void)setDefersCallbacks:(BOOL)defer
2502 if (!_private->page)
2504 return _private->page->setDefersLoading(defer);
2507 // For backwards compatibility with the WebBackForwardList API, we honor both
2508 // a per-WebView and a per-preferences setting for whether to use the page cache.
2510 - (BOOL)usesPageCache
2512 return _private->usesPageCache && [[self preferences] usesPageCache];
2515 - (void)setUsesPageCache:(BOOL)usesPageCache
2517 _private->usesPageCache = usesPageCache;
2519 // Update our own settings and post the public notification only
2520 [self _preferencesChanged:[self preferences]];
2521 [[self preferences] _postPreferencesChangedAPINotification];
2524 - (WebHistoryItem *)_globalHistoryItem
2529 return kit(_private->_globalHistoryItem.get());
2532 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
2534 _private->_globalHistoryItem = historyItem;
2537 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
2539 IntPoint rectStart(rect.origin.x, rect.origin.y);
2540 IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
2542 Frame* coreFrame = [self _mainCoreFrame];
2546 VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
2548 return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
2551 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
2553 NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window];
2554 [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window];
2557 - (void)_clearUndoRedoOperations
2559 if (!_private->page)
2561 _private->page->clearUndoRedoOperations();
2564 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
2566 Frame* coreFrame = [self _mainCoreFrame];
2569 coreFrame->editor().command(name).execute(value);
2572 - (void)_setCustomHTMLTokenizerTimeDelay:(double)timeDelay
2574 if (!_private->page)
2576 return _private->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
2579 - (void)_setCustomHTMLTokenizerChunkSize:(int)chunkSize
2581 if (!_private->page)
2583 return _private->page->setCustomHTMLTokenizerChunkSize(chunkSize);
2586 - (void)_clearMainFrameName
2588 _private->page->mainFrame().tree().clearName();
2591 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
2593 if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
2594 _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);
2595 [self setSmartInsertDeleteEnabled:!flag];
2599 - (BOOL)isSelectTrailingWhitespaceEnabled
2601 return _private->page->settings().selectTrailingWhitespaceEnabled();
2604 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
2606 _private->page->setMemoryCacheClientCallsEnabled(enabled);
2609 - (BOOL)areMemoryCacheDelegateCallsEnabled
2611 return _private->page->areMemoryCacheClientCallsEnabled();
2614 + (NSCursor *)_pointingHandCursor
2616 return handCursor().platformCursor();
2619 - (BOOL)_postsAcceleratedCompositingNotifications
2621 #if USE(ACCELERATED_COMPOSITING)
2622 return _private->postsAcceleratedCompositingNotifications;
2628 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
2630 #if USE(ACCELERATED_COMPOSITING)
2631 _private->postsAcceleratedCompositingNotifications = flag;
2635 - (BOOL)_isUsingAcceleratedCompositing
2637 #if USE(ACCELERATED_COMPOSITING)
2638 Frame* coreFrame = [self _mainCoreFrame];
2639 for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
2640 NSView *documentView = [[kit(frame) frameView] documentView];
2641 if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
2648 - (void)_setBaseCTM:(CGAffineTransform)transform forContext:(CGContextRef)context
2650 WKSetBaseCTM(context, transform);
2653 - (BOOL)interactiveFormValidationEnabled
2655 return _private->interactiveFormValidationEnabled;
2658 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
2660 _private->interactiveFormValidationEnabled = enabled;
2663 - (int)validationMessageTimerMagnification
2665 return _private->validationMessageTimerMagnification;
2668 - (void)setValidationMessageTimerMagnification:(int)newValue
2670 _private->validationMessageTimerMagnification = newValue;
2673 - (BOOL)_isSoftwareRenderable
2675 #if USE(ACCELERATED_COMPOSITING)
2676 Frame* coreFrame = [self _mainCoreFrame];
2677 for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
2678 if (FrameView* view = frame->view()) {
2679 if (!view->isSoftwareRenderable())
2687 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
2689 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
2692 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
2694 return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
2697 - (void)setTracksRepaints:(BOOL)flag
2699 Frame* coreFrame = [self _mainCoreFrame];
2700 if (FrameView* view = coreFrame->view())
2701 view->setTracksRepaints(flag);
2704 - (BOOL)isTrackingRepaints
2706 Frame* coreFrame = [self _mainCoreFrame];
2707 if (FrameView* view = coreFrame->view())
2708 return view->isTrackingRepaints();
2713 - (void)resetTrackedRepaints
2715 Frame* coreFrame = [self _mainCoreFrame];
2716 if (FrameView* view = coreFrame->view())
2717 view->resetTrackedRepaints();
2720 - (NSArray*)trackedRepaintRects
2722 Frame* coreFrame = [self _mainCoreFrame];
2723 FrameView* view = coreFrame->view();
2724 if (!view || !view->isTrackingRepaints())
2727 const Vector<IntRect>& repaintRects = view->trackedRepaintRects();
2728 NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
2730 for (unsigned i = 0; i < repaintRects.size(); ++i)
2731 [rectsArray addObject:[NSValue valueWithRect:pixelSnappedIntRect(repaintRects[i])]];
2733 return [rectsArray autorelease];
2736 - (NSPasteboard *)_insertionPasteboard
2738 return _private ? _private->insertionPasteboard : nil;
2741 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2743 SecurityPolicy::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2746 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2748 SecurityPolicy::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2751 + (void)_resetOriginAccessWhitelists
2753 SecurityPolicy::resetOriginAccessWhitelists();
2756 - (BOOL)_isViewVisible
2761 if (![[self window] isVisible])
2764 if ([self isHiddenOrHasHiddenAncestor])
2770 - (void)_updateVisibilityState
2772 if (_private && _private->page)
2773 [self _setVisibilityState:([self _isViewVisible] ? WebPageVisibilityStateVisible : WebPageVisibilityStateHidden) isInitialState:NO];
2776 - (void)_updateActiveState
2778 if (_private && _private->page)
2779 _private->page->focusController().setActive([[self window] _hasKeyAppearance]);
2782 static Vector<String> toStringVector(NSArray* patterns)
2784 Vector<String> patternsVector;
2786 NSUInteger count = [patterns count];
2788 return patternsVector;
2790 for (NSUInteger i = 0; i < count; ++i) {
2791 id entry = [patterns objectAtIndex:i];
2792 if ([entry isKindOfClass:[NSString class]])
2793 patternsVector.append(String((NSString *)entry));
2795 return patternsVector;
2798 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2799 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2800 injectionTime:(WebUserScriptInjectionTime)injectionTime
2802 [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
2805 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2806 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2807 injectionTime:(WebUserScriptInjectionTime)injectionTime
2808 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2810 String group(groupName);
2811 if (group.isEmpty())
2814 PageGroup* pageGroup = PageGroup::pageGroup(group);
2821 pageGroup->addUserScriptToWorld(*core(world), source, url, toStringVector(whitelist), toStringVector(blacklist),
2822 injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
2823 injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2826 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2827 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2829 [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
2832 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2833 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2834 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2836 String group(groupName);
2837 if (group.isEmpty())
2840 PageGroup* pageGroup = PageGroup::pageGroup(group);
2847 pageGroup->addUserStyleSheetToWorld(*core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2850 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2852 String group(groupName);
2853 if (group.isEmpty())
2856 PageGroup* pageGroup = PageGroup::pageGroup(group);
2863 pageGroup->removeUserScriptFromWorld(*core(world), url);
2866 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2868 String group(groupName);
2869 if (group.isEmpty())
2872 PageGroup* pageGroup = PageGroup::pageGroup(group);
2879 pageGroup->removeUserStyleSheetFromWorld(*core(world), url);
2882 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2884 String group(groupName);
2885 if (group.isEmpty())
2888 PageGroup* pageGroup = PageGroup::pageGroup(group);
2895 pageGroup->removeUserScriptsFromWorld(*core(world));
2898 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2900 String group(groupName);
2901 if (group.isEmpty())
2904 PageGroup* pageGroup = PageGroup::pageGroup(group);
2911 pageGroup->removeUserStyleSheetsFromWorld(*core(world));
2914 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
2916 String group(groupName);
2917 if (group.isEmpty())
2920 PageGroup* pageGroup = PageGroup::pageGroup(group);
2924 pageGroup->removeAllUserContent();
2927 - (BOOL)allowsNewCSSAnimationsWhileSuspended
2929 Frame* frame = core([self mainFrame]);
2931 return frame->animation().allowsNewAnimationsWhileSuspended();
2936 - (void)setAllowsNewCSSAnimationsWhileSuspended:(BOOL)allowed
2938 Frame* frame = core([self mainFrame]);
2940 frame->animation().setAllowsNewAnimationsWhileSuspended(allowed);
2943 - (BOOL)cssAnimationsSuspended
2945 // should ask the page!
2946 Frame* frame = core([self mainFrame]);
2948 return frame->animation().isSuspended();
2953 - (void)setCSSAnimationsSuspended:(BOOL)suspended
2955 Frame* frame = core([self mainFrame]);
2956 if (suspended == frame->animation().isSuspended())
2960 frame->animation().suspendAnimations();
2962 frame->animation().resumeAnimations();
2965 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
2967 SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
2970 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
2972 SchemeRegistry::registerURLSchemeAsSecure(scheme);
2975 + (void)_registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing:(NSString *)scheme
2977 SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing(scheme);
2980 + (void)_registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing:(NSString *)scheme
2982 SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing(scheme);
2985 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
2987 _private->page->setPageScaleFactor(scale, IntPoint(origin));
2990 - (float)_viewScaleFactor
2992 return _private->page->pageScaleFactor();
2995 - (void)_setUseFixedLayout:(BOOL)fixed
2997 Frame* coreFrame = [self _mainCoreFrame];
3001 FrameView* view = coreFrame->view();
3005 view->setUseFixedLayout(fixed);
3007 view->setFixedLayoutSize(IntSize());
3010 - (void)_setFixedLayoutSize:(NSSize)size
3012 Frame* coreFrame = [self _mainCoreFrame];
3016 FrameView* view = coreFrame->view();
3020 view->setFixedLayoutSize(IntSize(size));
3021 view->forceLayout();
3024 - (BOOL)_useFixedLayout
3026 Frame* coreFrame = [self _mainCoreFrame];
3030 FrameView* view = coreFrame->view();
3034 return view->useFixedLayout();
3037 - (NSSize)_fixedLayoutSize
3039 Frame* coreFrame = [self _mainCoreFrame];
3043 FrameView* view = coreFrame->view();
3047 return view->fixedLayoutSize();
3050 - (void)_setPaginationMode:(WebPaginationMode)paginationMode
3052 Page* page = core(self);
3056 Pagination pagination = page->pagination();
3057 switch (paginationMode) {
3058 case WebPaginationModeUnpaginated:
3059 pagination.mode = Pagination::Unpaginated;
3061 case WebPaginationModeLeftToRight:
3062 pagination.mode = Pagination::LeftToRightPaginated;
3064 case WebPaginationModeRightToLeft:
3065 pagination.mode = Pagination::RightToLeftPaginated;
3067 case WebPaginationModeTopToBottom:
3068 pagination.mode = Pagination::TopToBottomPaginated;
3070 case WebPaginationModeBottomToTop:
3071 pagination.mode = Pagination::BottomToTopPaginated;
3077 page->setPagination(pagination);
3080 - (WebPaginationMode)_paginationMode
3082 Page* page = core(self);
3084 return WebPaginationModeUnpaginated;
3086 switch (page->pagination().mode) {
3087 case Pagination::Unpaginated:
3088 return WebPaginationModeUnpaginated;
3089 case Pagination::LeftToRightPaginated:
3090 return WebPaginationModeLeftToRight;
3091 case Pagination::RightToLeftPaginated:
3092 return WebPaginationModeRightToLeft;
3093 case Pagination::TopToBottomPaginated:
3094 return WebPaginationModeTopToBottom;
3095 case Pagination::BottomToTopPaginated:
3096 return WebPaginationModeBottomToTop;
3099 ASSERT_NOT_REACHED();
3100 return WebPaginationModeUnpaginated;
3103 - (void)_listenForLayoutMilestones:(WebLayoutMilestones)layoutMilestones
3105 Page* page = core(self);
3109 page->addLayoutMilestones(coreLayoutMilestones(layoutMilestones));
3112 - (WebLayoutMilestones)_layoutMilestones
3114 Page* page = core(self);
3118 return kitLayoutMilestones(page->requestedLayoutMilestones());
3121 - (WebPageVisibilityState)_visibilityState
3123 #if ENABLE(PAGE_VISIBILITY_API) || ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
3125 return kit(_private->page->visibilityState());
3127 return WebPageVisibilityStateVisible;
3130 - (void)_setVisibilityState:(WebPageVisibilityState)visibilityState isInitialState:(BOOL)isInitialState
3132 #if ENABLE(PAGE_VISIBILITY_API) || ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
3134 _private->page->setVisibilityState(core(visibilityState), isInitialState);
3138 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
3140 Page* page = core(self);
3144 Pagination pagination = page->pagination();
3145 pagination.behavesLikeColumns = behavesLikeColumns;
3147 page->setPagination(pagination);
3150 - (BOOL)_paginationBehavesLikeColumns
3152 Page* page = core(self);
3156 return page->pagination().behavesLikeColumns;
3159 - (void)_setPageLength:(CGFloat)pageLength
3161 Page* page = core(self);
3165 Pagination pagination = page->pagination();
3166 pagination.pageLength = pageLength;
3168 page->setPagination(pagination);
3171 - (CGFloat)_pageLength
3173 Page* page = core(self);
3177 return page->pagination().pageLength;
3180 - (void)_setGapBetweenPages:(CGFloat)pageGap
3182 Page* page = core(self);
3186 Pagination pagination = page->pagination();
3187 pagination.gap = pageGap;
3188 page->setPagination(pagination);
3191 - (CGFloat)_gapBetweenPages
3193 Page* page = core(self);
3197 return page->pagination().gap;
3200 - (NSUInteger)_pageCount
3202 Page* page = core(self);
3206 return page->pageCount();
3209 - (CGFloat)_backingScaleFactor
3211 return [self _deviceScaleFactor];
3214 - (void)_setCustomBackingScaleFactor:(CGFloat)customScaleFactor
3216 float oldScaleFactor = [self _deviceScaleFactor];
3218 _private->customDeviceScaleFactor = customScaleFactor;
3220 if (oldScaleFactor != [self _deviceScaleFactor])
3221 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
3224 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
3226 return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:YES];
3229 - (NSUInteger)countMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit markMatches:(BOOL)markMatches
3231 return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:markMatches];
3234 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
3236 return [self findString:string options:((forward ? 0 : WebFindOptionsBackwards) | (caseFlag ? 0 : WebFindOptionsCaseInsensitive) | (wrapFlag ? WebFindOptionsWrapAround : 0) | (startInSelection ? WebFindOptionsStartInSelection : 0))];
3239 + (void)_setLoadResourcesSerially:(BOOL)serialize
3241 WebPlatformStrategies::initializeIfNecessary();
3242 resourceLoadScheduler()->setSerialLoadingEnabled(serialize);
3245 + (BOOL)_HTTPPipeliningEnabled
3247 return ResourceRequest::httpPipeliningEnabled();
3250 + (void)_setHTTPPipeliningEnabled:(BOOL)enabled
3252 ResourceRequest::setHTTPPipeliningEnabled(enabled);
3255 - (void)_setSourceApplicationAuditData:(NSData *)sourceApplicationAuditData
3257 if (_private->sourceApplicationAuditData == sourceApplicationAuditData)
3260 _private->sourceApplicationAuditData = adoptNS([sourceApplicationAuditData copy]);
3263 - (NSData *)_sourceApplicationAuditData
3265 return _private->sourceApplicationAuditData.get();
3268 - (void)_setFontFallbackPrefersPictographs:(BOOL)flag
3271 _private->page->settings().setFontFallbackPrefersPictographs(flag);
3276 @implementation _WebSafeForwarder
3278 // Used to send messages to delegates that implement informal protocols.
3280 - (id)initWithTarget:(id)t defaultTarget:(id)dt
3282 self = [super init];
3285 target = t; // Non retained.
3290 - (void)forwardInvocation:(NSInvocation *)invocation
3292 if ([target respondsToSelector:[invocation selector]]) {
3294 [invocation invokeWithTarget:target];
3295 } @catch(id exception) {
3296 ReportDiscardedDelegateException([invocation selector], exception);
3301 if ([defaultTarget respondsToSelector:[invocation selector]])
3302 [invocation invokeWithTarget:defaultTarget];
3304 // Do nothing quietly if method not implemented.
3307 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
3309 return [defaultTarget methodSignatureForSelector:aSelector];
3314 @implementation WebView
3318 static BOOL initialized = NO;
3323 InitWebCoreSystemInterface();
3324 JSC::initializeThreading();
3325 WTF::initializeMainThreadToProcessMainThread();
3326 RunLoop::initializeMainRunLoop();
3328 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
3329 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_cacheModelChangedNotification:) name:WebPreferencesCacheModelChangedInternalNotification object:nil];
3330 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];
3332 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3334 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3335 [defaults registerDefaults:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]];
3338 continuousSpellCheckingEnabled = [defaults boolForKey:WebContinuousSpellCheckingEnabled];
3339 grammarCheckingEnabled = [defaults boolForKey:WebGrammarCheckingEnabled];
3341 Font::setDefaultTypesettingFeatures([defaults boolForKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey] ? Kerning | Ligatures : 0);
3343 automaticQuoteSubstitutionEnabled = [self _shouldAutomaticQuoteSubstitutionBeEnabled];
3344 automaticLinkDetectionEnabled = [defaults boolForKey:WebAutomaticLinkDetectionEnabled];
3345 automaticDashSubstitutionEnabled = [self _shouldAutomaticDashSubstitutionBeEnabled];
3346 automaticTextReplacementEnabled = [self _shouldAutomaticTextReplacementBeEnabled];
3347 automaticSpellingCorrectionEnabled = [self _shouldAutomaticSpellingCorrectionBeEnabled];
3349 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didChangeAutomaticTextReplacementEnabled:)
3350 name:NSSpellCheckerDidChangeAutomaticTextReplacementNotification object:nil];
3351 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didChangeAutomaticSpellingCorrectionEnabled:)
3352 name:NSSpellCheckerDidChangeAutomaticSpellingCorrectionNotification object:nil];
3354 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3355 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didChangeAutomaticQuoteSubstitutionEnabled:)
3356 name:NSSpellCheckerDidChangeAutomaticQuoteSubstitutionNotification object:nil];
3357 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didChangeAutomaticDashSubstitutionEnabled:)
3358 name:NSSpellCheckerDidChangeAutomaticDashSubstitutionNotification object:nil];
3362 + (BOOL)_shouldAutomaticTextReplacementBeEnabled
3364 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3365 if (![defaults objectForKey:WebAutomaticTextReplacementEnabled])
3366 return [NSSpellChecker isAutomaticTextReplacementEnabled];
3367 return [defaults boolForKey:WebAutomaticTextReplacementEnabled];
3370 + (void)_didChangeAutomaticTextReplacementEnabled:(NSNotification *)notification
3372 automaticTextReplacementEnabled = [self _shouldAutomaticTextReplacementBeEnabled];
3373 [[NSSpellChecker sharedSpellChecker] updatePanels];
3376 + (BOOL)_shouldAutomaticSpellingCorrectionBeEnabled
3378 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3379 if (![defaults objectForKey:WebAutomaticSpellingCorrectionEnabled])
3380 return [NSSpellChecker isAutomaticTextReplacementEnabled];
3381 return [defaults boolForKey:WebAutomaticSpellingCorrectionEnabled];
3384 + (void)_didChangeAutomaticSpellingCorrectionEnabled:(NSNotification *)notification
3386 automaticSpellingCorrectionEnabled = [self _shouldAutomaticSpellingCorrectionBeEnabled];
3387 [[NSSpellChecker sharedSpellChecker] updatePanels];
3390 + (BOOL)_shouldAutomaticQuoteSubstitutionBeEnabled
3392 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3393 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3394 if (![defaults objectForKey:WebAutomaticQuoteSubstitutionEnabled])
3395 return [NSSpellChecker isAutomaticQuoteSubstitutionEnabled];
3397 return [defaults boolForKey:WebAutomaticQuoteSubstitutionEnabled];
3400 + (BOOL)_shouldAutomaticDashSubstitutionBeEnabled
3402 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3403 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3404 if (![defaults objectForKey:WebAutomaticDashSubstitutionEnabled])
3405 return [NSSpellChecker isAutomaticDashSubstitutionEnabled];
3407 return [defaults boolForKey:WebAutomaticDashSubstitutionEnabled];
3410 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3411 + (void)_didChangeAutomaticQuoteSubstitutionEnabled:(NSNotification *)notification
3413 automaticQuoteSubstitutionEnabled = [self _shouldAutomaticQuoteSubstitutionBeEnabled];
3414 [[NSSpellChecker sharedSpellChecker] updatePanels];
3417 + (void)_didChangeAutomaticDashSubstitutionEnabled:(NSNotification *)notification
3419 automaticDashSubstitutionEnabled = [self _shouldAutomaticDashSubstitutionBeEnabled];
3420 [[NSSpellChecker sharedSpellChecker] updatePanels];
3424 + (void)_applicationWillTerminate
3426 applicationIsTerminating = YES;
3428 if (fastDocumentTeardownEnabled())
3429 [self closeAllWebViews];
3431 if (!pluginDatabaseClientCount)
3432 [WebPluginDatabase closeSharedDatabase];
3434 PageGroup::closeLocalStorage();
3437 + (BOOL)_canShowMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
3439 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType allowingPlugins:allowPlugins];
3442 + (BOOL)canShowMIMEType:(NSString *)MIMEType
3444 return [self _canShowMIMEType:MIMEType allowingPlugins:YES];
3447 - (BOOL)_canShowMIMEType:(NSString *)MIMEType
3449 return [[self class] _canShowMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]];
3452 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
3454 if (![_private->preferences arePlugInsEnabled])
3457 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3459 return pluginPackage;
3461 if (_private->pluginDatabase)
3462 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3467 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
3468 - (WebBasePluginPackage *)_videoProxyPluginForMIMEType:(NSString *)MIMEType
3470 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3472 return pluginPackage;
3474 if (_private->pluginDatabase)
3475 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3481 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
3483 if (![_private->preferences arePlugInsEnabled])
3486 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
3488 return pluginPackage;
3490 if (_private->pluginDatabase)
3491 return [_private->pluginDatabase pluginForExtension:extension];
3496 - (void)addPluginInstanceView:(NSView *)view
3498 if (!_private->pluginDatabase)
3499 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3500 [_private->pluginDatabase addPluginInstanceView:view];
3503 - (void)removePluginInstanceView:(NSView *)view
3505 if (_private->pluginDatabase)
3506 [_private->pluginDatabase removePluginInstanceView:view];
3509 - (void)removePluginInstanceViewsFor:(WebFrame*)webFrame
3511 if (_private->pluginDatabase)
3512 [_private->pluginDatabase removePluginInstanceViewsFor:webFrame];
3515 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
3517 if (![_private->preferences arePlugInsEnabled])
3520 if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
3523 if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
3529 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
3531 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
3534 + (NSArray *)MIMETypesShownAsHTML
3536 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
3537 NSEnumerator *enumerator = [viewTypes keyEnumerator];
3539 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
3541 while ((key = [enumerator nextObject])) {
3542 if ([viewTypes objectForKey:key] == [WebHTMLView class])
3543 [array addObject:key];
3549 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
3551 NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
3552 NSEnumerator *enumerator = [viewTypes keyEnumerator];
3554 while ((key = [enumerator nextObject])) {
3555 if ([viewTypes objectForKey:key] == [WebHTMLView class])
3556 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
3559 int i, count = [MIMETypes count];
3560 for (i = 0; i < count; i++) {
3561 [WebView registerViewClass:[WebHTMLView class]
3562 representationClass:[WebHTMLRepresentation class]
3563 forMIMEType:[MIMETypes objectAtIndex:i]];
3565 [viewTypes release];
3568 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
3570 return [pasteboard _web_bestURL];
3573 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
3575 return [pasteboard stringForType:WebURLNamePboardType];
3578 + (void)registerURLSchemeAsLocal:(NSString *)protocol
3580 SchemeRegistry::registerURLSchemeAsLocal(protocol);
3583 - (id)_initWithArguments:(NSDictionary *) arguments
3585 NSCoder *decoder = [arguments objectForKey:@"decoder"];
3587 self = [self initWithCoder:decoder];
3589 ASSERT([arguments objectForKey:@"frame"]);
3590 NSValue *frameValue = [arguments objectForKey:@"frame"];
3591 NSRect frame = (frameValue ? [frameValue rectValue] : NSZeroRect);
3592 NSString *frameName = [arguments objectForKey:@"frameName"];
3593 NSString *groupName = [arguments objectForKey:@"groupName"];
3594 self = [self initWithFrame:frame frameName:frameName groupName:groupName];
3600 static bool clientNeedsWebViewInitThreadWorkaround()
3602 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_WEBVIEW_INIT_THREAD_WORKAROUND))
3605 NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
3608 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.installer"])
3612 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Automator"])
3615 // Automator Runner.
3616 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.AutomatorRunner"])
3619 // Automator workflows.
3620 if ([bundleIdentifier _webkit_hasCaseInsensitivePrefix:@"com.apple.Automator."])
3626 static bool needsWebViewInitThreadWorkaround()
3628 static bool isOldClient = clientNeedsWebViewInitThreadWorkaround();
3629 return isOldClient && !pthread_main_np();