2 * Copyright (C) 2005-2012 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 "WebDatabaseManagerInternal.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 "WebFrameNetworkingContext.h"
65 #import "WebFrameViewInternal.h"
66 #import "WebFullScreenController.h"
67 #import "WebGeolocationClient.h"
68 #import "WebGeolocationPositionInternal.h"
69 #import "WebHTMLRepresentation.h"
70 #import "WebHTMLViewInternal.h"
71 #import "WebHistoryItemInternal.h"
72 #import "WebIconDatabaseInternal.h"
73 #import "WebInspector.h"
74 #import "WebInspectorClient.h"
75 #import "WebKitErrors.h"
76 #import "WebKitFullScreenListener.h"
77 #import "WebKitLogging.h"
78 #import "WebKitNSStringExtras.h"
79 #import "WebKitStatisticsPrivate.h"
80 #import "WebKitSystemBits.h"
81 #import "WebKitVersionChecks.h"
82 #import "WebLocalizableStrings.h"
83 #import "WebNSDataExtras.h"
84 #import "WebNSDataExtrasPrivate.h"
85 #import "WebNSDictionaryExtras.h"
86 #import "WebNSEventExtras.h"
87 #import "WebNSObjectExtras.h"
88 #import "WebNSPasteboardExtras.h"
89 #import "WebNSPrintOperationExtras.h"
90 #import "WebNSURLExtras.h"
91 #import "WebNSURLRequestExtras.h"
92 #import "WebNSViewExtras.h"
93 #import "WebNodeHighlight.h"
94 #import "WebNotificationClient.h"
95 #import "WebPDFView.h"
96 #import "WebPanelAuthenticationHandler.h"
97 #import "WebPlatformStrategies.h"
98 #import "WebPluginDatabase.h"
99 #import "WebPolicyDelegate.h"
100 #import "WebPreferenceKeysPrivate.h"
101 #import "WebPreferencesPrivate.h"
102 #import "WebScriptDebugDelegate.h"
103 #import "WebScriptWorldInternal.h"
104 #import "WebStorageManagerInternal.h"
105 #import "WebSystemInterface.h"
106 #import "WebTextCompletionController.h"
107 #import "WebTextIterator.h"
108 #import "WebUIDelegate.h"
109 #import "WebUIDelegatePrivate.h"
110 #import <CoreFoundation/CFSet.h>
111 #import <Foundation/NSURLConnection.h>
112 #import <JavaScriptCore/APICast.h>
113 #import <JavaScriptCore/JSValueRef.h>
114 #import <WebCore/AlternativeTextUIController.h>
115 #import <WebCore/ApplicationCacheStorage.h>
116 #import <WebCore/BackForwardListImpl.h>
117 #import <WebCore/MemoryCache.h>
118 #import <WebCore/ColorMac.h>
119 #import <WebCore/CSSComputedStyleDeclaration.h>
120 #import <WebCore/Cursor.h>
121 #import <WebCore/DatabaseManager.h>
122 #import <WebCore/Document.h>
123 #import <WebCore/DocumentLoader.h>
124 #import <WebCore/DragController.h>
125 #import <WebCore/DragData.h>
126 #import <WebCore/DragSession.h>
127 #import <WebCore/Editor.h>
128 #import <WebCore/EventHandler.h>
129 #import <WebCore/ExceptionHandlers.h>
130 #import <WebCore/FocusController.h>
131 #import <WebCore/Frame.h>
132 #import <WebCore/FrameLoader.h>
133 #import <WebCore/FrameSelection.h>
134 #import <WebCore/FrameTree.h>
135 #import <WebCore/FrameView.h>
136 #import <WebCore/GCController.h>
137 #import <WebCore/GeolocationController.h>
138 #import <WebCore/GeolocationError.h>
139 #import <WebCore/HTMLMediaElement.h>
140 #import <WebCore/HTMLNames.h>
141 #import <WebCore/HistoryItem.h>
142 #import <WebCore/IconDatabase.h>
143 #import <WebCore/InitializeLogging.h>
144 #import <WebCore/JSCSSStyleDeclaration.h>
145 #import <WebCore/JSDocument.h>
146 #import <WebCore/JSElement.h>
147 #import <WebCore/JSNodeList.h>
148 #import <WebCore/JSNotification.h>
149 #import <WebCore/MemoryPressureHandler.h>
150 #import <WebCore/MIMETypeRegistry.h>
151 #import <WebCore/NodeList.h>
152 #import <WebCore/Notification.h>
153 #import <WebCore/NotificationController.h>
154 #import <WebCore/Page.h>
155 #import <WebCore/PageCache.h>
156 #import <WebCore/PageGroup.h>
157 #import <WebCore/PlatformEventFactoryMac.h>
158 #import <WebCore/ProgressTracker.h>
159 #import <WebCore/RenderView.h>
160 #import <WebCore/RenderWidget.h>
161 #import <WebCore/ResourceHandle.h>
162 #import <WebCore/ResourceLoadScheduler.h>
163 #import <WebCore/ResourceRequest.h>
164 #import <WebCore/RunLoop.h>
165 #import <WebCore/RuntimeApplicationChecks.h>
166 #import <WebCore/RuntimeEnabledFeatures.h>
167 #import <WebCore/SchemeRegistry.h>
168 #import <WebCore/ScriptController.h>
169 #import <WebCore/ScriptValue.h>
170 #import <WebCore/SecurityOrigin.h>
171 #import <WebCore/SecurityPolicy.h>
172 #import <WebCore/Settings.h>
173 #import <WebCore/SystemVersionMac.h>
174 #import <WebCore/TextResourceDecoder.h>
175 #import <WebCore/ThreadCheck.h>
176 #import <WebCore/WebCoreObjCExtras.h>
177 #import <WebCore/WebCoreView.h>
178 #import <WebCore/WebVideoFullscreenController.h>
179 #import <WebCore/Widget.h>
180 #import <WebKit/DOM.h>
181 #import <WebKit/DOMExtensions.h>
182 #import <WebKit/DOMPrivate.h>
183 #import <WebKitSystemInterface.h>
184 #import <mach-o/dyld.h>
185 #import <objc/objc-auto.h>
186 #import <objc/runtime.h>
187 #import <runtime/ArrayPrototype.h>
188 #import <runtime/DateInstance.h>
189 #import <runtime/InitializeThreading.h>
190 #import <runtime/JSLock.h>
191 #import <runtime/JSValue.h>
192 #import <wtf/Assertions.h>
193 #import <wtf/HashTraits.h>
194 #import <wtf/MainThread.h>
195 #import <wtf/RefCountedLeakCounter.h>
196 #import <wtf/RefPtr.h>
197 #import <wtf/StdLibExtras.h>
199 #if ENABLE(DASHBOARD_SUPPORT)
200 #import <WebKit/WebDashboardRegion.h>
203 #if ENABLE(GLIB_SUPPORT)
207 @interface NSSpellChecker (WebNSSpellCheckerDetails)
208 - (void)_preflightChosenSpellServer;
211 @interface NSView (WebNSViewDetails)
212 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
213 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
214 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
217 @interface NSWindow (WebNSWindowDetails)
218 - (id)_oldFirstResponderBeforeBecoming;
219 - (void)_enableScreenUpdatesIfNeeded;
220 - (BOOL)_wrapsCarbonWindow;
221 - (BOOL)_hasKeyAppearance;
224 using namespace WebCore;
227 #if defined(__ppc__) || defined(__ppc64__)
228 #define PROCESSOR "PPC"
229 #elif defined(__i386__) || defined(__x86_64__)
230 #define PROCESSOR "Intel"
232 #error Unknown architecture
235 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
237 macro(alignJustified) \
240 macro(capitalizeWord) \
241 macro(centerSelectionInVisibleArea) \
242 macro(changeAttributes) \
243 macro(changeBaseWritingDirection) \
244 macro(changeBaseWritingDirectionToLTR) \
245 macro(changeBaseWritingDirectionToRTL) \
247 macro(changeDocumentBackgroundColor) \
249 macro(changeSpelling) \
250 macro(checkSpelling) \
256 macro(deleteBackward) \
257 macro(deleteBackwardByDecomposingPreviousCharacter) \
258 macro(deleteForward) \
259 macro(deleteToBeginningOfLine) \
260 macro(deleteToBeginningOfParagraph) \
261 macro(deleteToEndOfLine) \
262 macro(deleteToEndOfParagraph) \
263 macro(deleteToMark) \
264 macro(deleteWordBackward) \
265 macro(deleteWordForward) \
266 macro(ignoreSpelling) \
268 macro(insertBacktab) \
269 macro(insertLineBreak) \
270 macro(insertNewline) \
271 macro(insertNewlineIgnoringFieldEditor) \
272 macro(insertParagraphSeparator) \
274 macro(insertTabIgnoringFieldEditor) \
275 macro(lowercaseWord) \
276 macro(makeBaseWritingDirectionLeftToRight) \
277 macro(makeBaseWritingDirectionRightToLeft) \
278 macro(makeTextWritingDirectionLeftToRight) \
279 macro(makeTextWritingDirectionNatural) \
280 macro(makeTextWritingDirectionRightToLeft) \
281 macro(moveBackward) \
282 macro(moveBackwardAndModifySelection) \
284 macro(moveDownAndModifySelection) \
286 macro(moveForwardAndModifySelection) \
288 macro(moveLeftAndModifySelection) \
289 macro(moveParagraphBackwardAndModifySelection) \
290 macro(moveParagraphForwardAndModifySelection) \
292 macro(moveRightAndModifySelection) \
293 macro(moveToBeginningOfDocument) \
294 macro(moveToBeginningOfDocumentAndModifySelection) \
295 macro(moveToBeginningOfLine) \
296 macro(moveToBeginningOfLineAndModifySelection) \
297 macro(moveToBeginningOfParagraph) \
298 macro(moveToBeginningOfParagraphAndModifySelection) \
299 macro(moveToBeginningOfSentence) \
300 macro(moveToBeginningOfSentenceAndModifySelection) \
301 macro(moveToEndOfDocument) \
302 macro(moveToEndOfDocumentAndModifySelection) \
303 macro(moveToEndOfLine) \
304 macro(moveToEndOfLineAndModifySelection) \
305 macro(moveToEndOfParagraph) \
306 macro(moveToEndOfParagraphAndModifySelection) \
307 macro(moveToEndOfSentence) \
308 macro(moveToEndOfSentenceAndModifySelection) \
309 macro(moveToLeftEndOfLine) \
310 macro(moveToLeftEndOfLineAndModifySelection) \
311 macro(moveToRightEndOfLine) \
312 macro(moveToRightEndOfLineAndModifySelection) \
314 macro(moveUpAndModifySelection) \
315 macro(moveWordBackward) \
316 macro(moveWordBackwardAndModifySelection) \
317 macro(moveWordForward) \
318 macro(moveWordForwardAndModifySelection) \
319 macro(moveWordLeft) \
320 macro(moveWordLeftAndModifySelection) \
321 macro(moveWordRight) \
322 macro(moveWordRightAndModifySelection) \
324 macro(orderFrontSubstitutionsPanel) \
326 macro(pageDownAndModifySelection) \
328 macro(pageUpAndModifySelection) \
330 macro(pasteAsPlainText) \
331 macro(pasteAsRichText) \
333 macro(performFindPanelAction) \
334 macro(scrollLineDown) \
335 macro(scrollLineUp) \
336 macro(scrollPageDown) \
337 macro(scrollPageUp) \
338 macro(scrollToBeginningOfDocument) \
339 macro(scrollToEndOfDocument) \
342 macro(selectParagraph) \
343 macro(selectSentence) \
344 macro(selectToMark) \
347 macro(showGuessPanel) \
348 macro(startSpeaking) \
349 macro(stopSpeaking) \
352 macro(swapWithMark) \
353 macro(takeFindStringFromSelection) \
354 macro(toggleBaseWritingDirection) \
358 macro(uppercaseWord) \
360 macro(yankAndSelect) \
362 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
363 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
365 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
366 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
367 #define UniversalAccessDomain CFSTR("com.apple.universalaccess")
369 static BOOL s_didSetCacheModel;
370 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
373 static const char webViewIsOpen[] = "At least one WebView is still open.";
376 @interface NSObject (WebValidateWithoutDelegate)
377 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
380 @interface _WebSafeForwarder : NSObject
382 id target; // Non-retained. Don't retain delegates.
385 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
388 FindOptions coreOptions(WebFindOptions options)
390 return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
391 | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
392 | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
393 | (options & WebFindOptionsBackwards ? Backwards : 0)
394 | (options & WebFindOptionsWrapAround ? WrapAround : 0)
395 | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
398 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
400 return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
401 | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
402 | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
405 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
407 return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
408 | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
409 | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
412 @interface WebView (WebFileInternal)
413 - (float)_deviceScaleFactor;
415 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
416 - (WebFrame *)_focusedFrame;
417 + (void)_preflightSpellChecker;
418 - (BOOL)_continuousCheckingAllowed;
419 - (NSResponder *)_responderForResponderOperations;
420 #if ENABLE(GLIB_SUPPORT)
421 - (void)_clearGlibLoopObserver;
425 static void patchMailRemoveAttributesMethod();
427 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
428 NSString *WebElementFrameKey = @"WebElementFrame";
429 NSString *WebElementImageKey = @"WebElementImage";
430 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
431 NSString *WebElementImageRectKey = @"WebElementImageRect";
432 NSString *WebElementImageURLKey = @"WebElementImageURL";
433 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
434 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
435 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
436 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
437 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
438 NSString *WebElementMediaURLKey = @"WebElementMediaURL";
439 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
440 NSString *WebElementTitleKey = @"WebElementTitle";
441 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
442 NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
443 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
445 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
446 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
447 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
449 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
450 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
451 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
452 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
453 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
455 enum { WebViewVersion = 4 };
457 #define timedLayoutSize 4096
459 static NSMutableSet *schemesWithRepresentationsSet;
461 NSString *_WebCanGoBackKey = @"canGoBack";
462 NSString *_WebCanGoForwardKey = @"canGoForward";
463 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
464 NSString *_WebIsLoadingKey = @"isLoading";
465 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
466 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
467 NSString *_WebMainFrameURLKey = @"mainFrameURL";
468 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
470 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
472 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
474 @interface WebProgressItem : NSObject
477 long long bytesReceived;
478 long long estimatedLength;
482 @implementation WebProgressItem
485 static BOOL continuousSpellCheckingEnabled;
486 static BOOL grammarCheckingEnabled;
487 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
488 static BOOL automaticQuoteSubstitutionEnabled;
489 static BOOL automaticLinkDetectionEnabled;
490 static BOOL automaticDashSubstitutionEnabled;
491 static BOOL automaticTextReplacementEnabled;
492 static BOOL automaticSpellingCorrectionEnabled;
495 @implementation WebView (AllWebViews)
497 static CFSetCallBacks NonRetainingSetCallbacks = {
506 static CFMutableSetRef allWebViewsSet;
508 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
513 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
516 - (void)_removeFromAllWebViewsSet
519 CFSetRemoveValue(allWebViewsSet, self);
522 - (void)_addToAllWebViewsSet
525 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
527 CFSetSetValue(allWebViewsSet, self);
532 @implementation WebView (WebPrivate)
534 static NSString *systemMarketingVersionForUserAgentString()
536 // Use underscores instead of dots because when we first added the Mac OS X version to the user agent string
537 // we were concerned about old DHTML libraries interpreting "4." as Netscape 4. That's no longer a concern for us
538 // but we're sticking with the underscores for compatibility with the format used by older versions of Safari.
539 return [systemMarketingVersion() stringByReplacingOccurrencesOfString:@"." withString:@"_"];
542 static NSString *createUserVisibleWebKitVersionString()
544 // If the version is 4 digits long or longer, then the first digit represents
545 // the version of the OS. Our user agent string should not include this first digit,
546 // so strip it off and report the rest as the version. <rdar://problem/4997547>
547 NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
548 NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
549 if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
550 return [[fullVersion substringFromIndex:1] copy];
551 if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
552 return [[fullVersion substringFromIndex:1] copy];
553 return [fullVersion copy];
556 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
558 // Note: Do *not* move the initialization of osVersion nor webKitVersion into the declaration.
559 // Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
560 static NSString *osVersion;
561 static NSString *webKitVersion;
563 osVersion = [systemMarketingVersionForUserAgentString() retain];
565 webKitVersion = createUserVisibleWebKitVersionString();
566 if ([applicationName length])
567 return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko) %@", osVersion, webKitVersion, applicationName];
568 return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko)", osVersion, webKitVersion];
571 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
573 if (!exception || !context)
576 JSC::ExecState* execState = toJS(context);
577 JSLockHolder lock(execState);
579 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
580 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
583 reportException(execState, toJS(execState, exception));
586 static void WebKitInitializeApplicationCachePathIfNecessary()
588 static BOOL initialized = NO;
592 NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
594 appName = [[NSProcessInfo processInfo] processName];
598 NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
600 cacheStorage().setCacheDirectory(cacheDir);
604 static bool runningLeopardMail()
606 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
607 return applicationIsAppleMail();
612 static bool coreVideoHas7228836Fix()
614 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
615 NSBundle* coreVideoFrameworkBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/CoreVideo.framework"];
616 double version = [[coreVideoFrameworkBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] doubleValue];
617 return (version >= 48);
622 static bool shouldEnableLoadDeferring()
624 return !applicationIsAdobeInstaller();
627 - (void)_dispatchPendingLoadRequests
629 resourceLoadScheduler()->servePendingRequests();
632 - (void)_registerDraggedTypes
634 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
635 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
636 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
637 [types addObjectsFromArray:URLTypes];
638 [self registerForDraggedTypes:[types allObjects]];
642 #if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1060
643 // This method should be removed once we no longer want to keep Safari 5.0.x working with nightly builds.
644 - (BOOL)_usesDocumentViews
650 static NSString *leakMailQuirksUserScriptContents()
652 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"MailQuirksUserScript" ofType:@"js"];
653 NSStringEncoding encoding;
654 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
657 - (void)_injectMailQuirksScript
659 static NSString *mailQuirksScriptContents = leakMailQuirksUserScriptContents();
660 core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
661 mailQuirksScriptContents, KURL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames);
664 static bool needsOutlookQuirksScript()
666 static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
667 && applicationIsMicrosoftOutlook();
668 return isOutlookNeedingQuirksScript;
671 static NSString *leakOutlookQuirksUserScriptContents()
673 NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
674 NSStringEncoding encoding;
675 return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
678 -(void)_injectOutlookQuirksScript
680 static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
681 core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
682 outlookQuirksScriptContents, KURL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames);
685 static bool shouldRespectPriorityInCSSAttributeSetters()
687 static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
688 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
689 return isIAdProducerNeedingAttributeSetterQuirk;
692 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
694 WebCoreThreadViolationCheckRoundTwo();
697 WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
700 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
701 [standardPreferences willAddToWebView];
703 _private->preferences = [standardPreferences retain];
704 _private->mainFrameDocumentReady = NO;
705 _private->drawsBackground = YES;
706 _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
707 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
709 NSRect f = [self frame];
710 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
711 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
712 [self addSubview:frameView];
715 static bool didOneTimeInitialization = false;
716 if (!didOneTimeInitialization) {
718 WebKitInitializeLoggingChannelsIfNecessary();
719 WebCore::initializeLoggingChannelsIfNecessary();
720 #endif // !LOG_DISABLED
722 // Initialize our platform strategies first before invoking the rest
723 // of the initialization code which may depend on the strategies.
724 WebPlatformStrategies::initialize();
726 [WebHistoryItem initWindowWatcherIfNecessary];
727 #if ENABLE(SQL_DATABASE)
728 WebKitInitializeDatabasesIfNecessary();
731 WebKitInitializeStorageIfNecessary();
732 WebKitInitializeApplicationCachePathIfNecessary();
733 patchMailRemoveAttributesMethod();
735 Settings::setDefaultMinDOMTimerInterval(0.004);
737 Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
739 didOneTimeInitialization = true;
742 Page::PageClients pageClients;
743 pageClients.chromeClient = new WebChromeClient(self);
744 pageClients.contextMenuClient = new WebContextMenuClient(self);
745 pageClients.editorClient = new WebEditorClient(self);
746 #if ENABLE(DRAG_SUPPORT)
747 pageClients.dragClient = new WebDragClient(self);
749 pageClients.inspectorClient = new WebInspectorClient(self);
750 pageClients.alternativeTextClient = new WebAlternativeTextClient(self);
751 _private->page = new Page(pageClients);
752 #if ENABLE(GEOLOCATION)
753 WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
755 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
756 WebCore::provideNotification(_private->page, new WebNotificationClient(self));
758 #if ENABLE(DEVICE_ORIENTATION)
759 WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
762 _private->page->setCanStartMedia([self window]);
763 _private->page->settings()->setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
765 if (needsOutlookQuirksScript()) {
766 _private->page->settings()->setShouldInjectUserScriptsInInitialEmptyDocument(true);
767 [self _injectOutlookQuirksScript];
770 [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
772 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
774 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
775 [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
777 [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
779 [self _addToAllWebViewsSet];
780 [self setGroupName:groupName];
782 // If there's already a next key view (e.g., from a nib), wire it up to our
783 // contained frame view. In any case, wire our next key view up to the our
784 // contained frame view. This works together with our becomeFirstResponder
785 // and setNextKeyView overrides.
786 NSView *nextKeyView = [self nextKeyView];
787 if (nextKeyView && nextKeyView != frameView)
788 [frameView setNextKeyView:nextKeyView];
789 [super setNextKeyView:frameView];
791 if ([[self class] shouldIncludeInWebKitStatistics])
794 [self _registerDraggedTypes];
796 WebPreferences *prefs = [self preferences];
797 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
798 name:WebPreferencesChangedInternalNotification object:prefs];
800 [self _preferencesChanged:[self preferences]];
801 [[self preferences] _postPreferencesChangedAPINotification];
803 memoryPressureHandler().install();
805 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
806 // Originally, we allowed all local loads.
807 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
808 } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
809 // Later, we allowed local loads for local URLs and documents loaded
810 // with substitute data.
811 SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
814 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
815 ResourceHandle::forceContentSniffing();
817 #if ENABLE(GLIB_SUPPORT)
818 [self _scheduleGlibContextIterations];
821 if (runningLeopardMail())
822 [self _injectMailQuirksScript];
825 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
827 // FIXME: Remove the usesDocumentViews parameter; it's only here for compatibility with WebKit nightly builds
828 // running against Safari 5 on Leopard.
829 ASSERT(usesDocumentViews);
831 self = [super initWithFrame:f];
835 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
836 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
837 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
838 // need for Safari to unset it to prevent it from being passed to applications it launches.
839 // Unsetting it when a WebView is first created is as good a place as any.
840 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
841 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
842 unsetenv("DYLD_FRAMEWORK_PATH");
843 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
847 _private = [[WebViewPrivate alloc] init];
848 [self _commonInitializationWithFrameName:frameName groupName:groupName];
849 [self setMaintainsBackForwardList: YES];
850 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
854 - (void)_viewWillDrawInternal
856 Frame* frame = [self _mainCoreFrame];
857 if (frame && frame->view())
858 frame->view()->updateLayoutAndStyleIfNeededRecursive();
861 + (NSArray *)_supportedMIMETypes
863 // Load the plug-in DB allowing plug-ins to install types.
864 [WebPluginDatabase sharedDatabase];
865 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
868 + (NSArray *)_supportedFileExtensions
870 NSMutableSet *extensions = [[NSMutableSet alloc] init];
871 NSArray *MIMETypes = [self _supportedMIMETypes];
872 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
874 while ((MIMEType = [enumerator nextObject]) != nil) {
875 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
876 if (extensionsForType) {
877 [extensions addObjectsFromArray:extensionsForType];
880 NSArray *uniqueExtensions = [extensions allObjects];
881 [extensions release];
882 return uniqueExtensions;
885 static NSMutableSet *knownPluginMIMETypes()
887 static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
892 + (void)_registerPluginMIMEType:(NSString *)MIMEType
894 [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
895 [knownPluginMIMETypes() addObject:MIMEType];
898 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
900 [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
901 [knownPluginMIMETypes() removeObject:MIMEType];
904 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
906 MIMEType = [MIMEType lowercaseString];
907 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
908 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
910 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
911 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
914 // Load the plug-in DB allowing plug-ins to install types.
915 [WebPluginDatabase sharedDatabase];
918 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
919 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
920 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
923 if (viewClass && repClass) {
924 if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
925 // Special-case WebHTMLView for text types that shouldn't be shown.
926 if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
929 // If the MIME type is a known plug-in we might not want to load it.
930 if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
931 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
932 [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
934 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
935 if (!isSupportedByWebKit)
949 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
951 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
954 if (_private->pluginDatabase) {
955 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
958 *vClass = [WebHTMLView class];
960 *rClass = [WebHTMLRepresentation class];
968 + (void)_setAlwaysUseATSU:(BOOL)f
970 [self _setAlwaysUsesComplexTextCodePath:f];
973 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
975 Font::setCodePath(f ? Font::Complex : Font::Auto);
978 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
980 TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
983 + (BOOL)_allowsRoundingHacks
985 return TextRun::allowsRoundingHacks();
988 + (BOOL)canCloseAllWebViews
990 return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
993 + (void)closeAllWebViews
995 DOMWindow::dispatchAllPendingUnloadEvents();
997 // This will close the WebViews in a random order. Change this if close order is important.
998 // Make a new set to avoid mutating the set we are enumerating.
999 NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet];
1000 NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1001 while (WebView *webView = [enumerator nextObject])
1005 + (BOOL)canShowFile:(NSString *)path
1007 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1010 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1012 return WKGetPreferredExtensionForMIMEType(type);
1017 return !_private || _private->closed;
1020 - (void)_closePluginDatabases
1022 pluginDatabaseClientCount--;
1024 // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1026 // Unload the WebView local plug-in database.
1027 if (_private->pluginDatabase) {
1028 [_private->pluginDatabase destroyAllPluginInstanceViews];
1029 [_private->pluginDatabase close];
1030 [_private->pluginDatabase release];
1031 _private->pluginDatabase = nil;
1034 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1035 if (!pluginDatabaseClientCount && applicationIsTerminating)
1036 [WebPluginDatabase closeSharedDatabase];
1039 - (void)_closeWithFastTeardown
1042 WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1045 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1046 [[NSNotificationCenter defaultCenter] removeObserver:self];
1048 [self _closePluginDatabases];
1051 static bool fastDocumentTeardownEnabled()
1054 static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1056 static bool initialized = false;
1057 static bool enabled = false;
1059 // This allows debug builds to default to not have fast teardown, so leak checking still works.
1060 // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1061 NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1063 enabled = ![setting boolValue];
1070 // _close is here only for backward compatibility; clients and subclasses should use
1071 // public method -close instead.
1074 if (!_private || _private->closed)
1077 _private->closed = YES;
1078 [self _removeFromAllWebViewsSet];
1081 WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1084 // To quit the apps fast we skip document teardown, except plugins
1085 // need to be destroyed and unloaded.
1086 if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1087 [self _closeWithFastTeardown];
1092 [self _exitFullscreen];
1095 if (Frame* mainFrame = [self _mainCoreFrame])
1096 mainFrame->loader()->detachFromParent();
1098 [self setHostWindow:nil];
1100 [self setDownloadDelegate:nil];
1101 [self setEditingDelegate:nil];
1102 [self setFrameLoadDelegate:nil];
1103 [self setPolicyDelegate:nil];
1104 [self setResourceLoadDelegate:nil];
1105 [self setScriptDebugDelegate:nil];
1106 [self setUIDelegate:nil];
1108 [_private->inspector webViewClosed];
1110 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1111 [self removeDragCaret];
1113 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1114 // all the plug-ins in the page cache to break any retain cycles.
1115 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1116 Page* page = _private->page;
1120 if (_private->hasSpellCheckerDocumentTag) {
1121 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1122 _private->hasSpellCheckerDocumentTag = NO;
1125 #if USE(ACCELERATED_COMPOSITING)
1126 if (_private->layerFlushController) {
1127 _private->layerFlushController->invalidateObserver();
1128 _private->layerFlushController = nullptr;
1132 #if ENABLE(GLIB_SUPPORT)
1133 [self _clearGlibLoopObserver];
1136 [[self _notificationProvider] unregisterWebView:self];
1138 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1139 [[NSNotificationCenter defaultCenter] removeObserver:self];
1141 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1143 WebPreferences *preferences = _private->preferences;
1144 _private->preferences = nil;
1145 [preferences didRemoveFromWebView];
1146 [preferences release];
1148 [self _closePluginDatabases];
1151 // Need this to make leak messages accurate.
1152 if (applicationIsTerminating) {
1153 gcController().garbageCollectNow();
1154 [WebCache setDisabled:YES];
1159 // Indicates if the WebView is in the midst of a user gesture.
1160 - (BOOL)_isProcessingUserGesture
1162 return ScriptController::processingUserGesture();
1165 + (NSString *)_MIMETypeForFile:(NSString *)path
1167 NSString *extension = [path pathExtension];
1168 NSString *MIMEType = nil;
1170 // Get the MIME type from the extension.
1171 if ([extension length] != 0) {
1172 MIMEType = WKGetMIMETypeForExtension(extension);
1175 // If we can't get a known MIME type from the extension, sniff.
1176 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1177 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1178 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1180 if ([data length] != 0) {
1181 MIMEType = [data _webkit_guessedMIMEType];
1183 if ([MIMEType length] == 0) {
1184 MIMEType = @"application/octet-stream";
1191 - (WebDownload *)_downloadURL:(NSURL *)URL
1195 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1196 WebDownload *download = [WebDownload _downloadWithRequest:request
1197 delegate:_private->downloadDelegate
1204 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1206 NSDictionary *features = [[NSDictionary alloc] init];
1207 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1208 createWebViewWithRequest:nil
1209 windowFeatures:features];
1211 if (!newWindowWebView)
1214 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1215 return newWindowWebView;
1218 - (WebInspector *)inspector
1220 if (!_private->inspector)
1221 _private->inspector = [[WebInspector alloc] initWithWebView:self];
1222 return _private->inspector;
1225 - (WebCore::Page*)page
1227 return _private->page;
1230 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1232 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1233 NSArray *menuItems = defaultMenuItems;
1235 // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1236 // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1237 SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1238 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1239 menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1244 unsigned count = [menuItems count];
1248 NSMenu *menu = [[NSMenu alloc] init];
1249 for (unsigned i = 0; i < count; i++)
1250 [menu addItem:[menuItems objectAtIndex:i]];
1252 return [menu autorelease];
1255 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1257 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1258 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1259 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1262 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1265 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1267 if (!_private->page)
1270 if (!otherView->_private->page)
1273 // It turns out the right combination of behavior is done with the back/forward load
1274 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
1275 // in the back forward list, and go to the current one.
1277 BackForwardList* backForwardList = _private->page->backForwardList();
1278 ASSERT(!backForwardList->currentItem()); // destination list should be empty
1280 BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
1281 if (!otherBackForwardList->currentItem())
1282 return; // empty back forward list, bail
1284 HistoryItem* newItemToGoTo = 0;
1286 int lastItemIndex = otherBackForwardList->forwardListCount();
1287 for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
1289 // If this item is showing , save away its current scroll and form state,
1290 // since that might have changed since loading and it is normally not saved
1291 // until we leave that page.
1292 otherView->_private->page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
1294 RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
1296 newItemToGoTo = newItem.get();
1297 backForwardList->addItem(newItem.release());
1300 ASSERT(newItemToGoTo);
1301 _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
1304 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
1306 _private->formDelegate = delegate;
1309 - (id<WebFormDelegate>)_formDelegate
1311 return _private->formDelegate;
1314 - (BOOL)_needsAdobeFrameReloadingQuirk
1316 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
1317 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
1318 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
1319 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
1320 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
1321 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
1322 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
1323 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
1324 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
1325 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
1330 - (BOOL)_needsLinkElementTextCSSQuirk
1332 static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
1333 && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
1337 - (BOOL)_needsIsLoadingInAPISenseQuirk
1339 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
1344 - (BOOL)_needsKeyboardEventDisambiguationQuirks
1346 static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
1350 - (BOOL)_needsFrameLoadDelegateRetainQuirk
1352 static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);
1356 static bool needsDidFinishLoadOrderQuirk()
1358 static bool needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CORRECT_DID_FINISH_LOAD_ORDER) && applicationIsAppleMail();
1362 static bool needsSelfRetainWhileLoadingQuirk()
1364 static bool needsQuirk = applicationIsAperture();
1368 - (BOOL)_needsPreHTML5ParserQuirks
1370 // AOL Instant Messenger and Microsoft My Day contain markup incompatible
1371 // with the new HTML5 parser. If these applications were linked against a
1372 // version of WebKit prior to the introduction of the HTML5 parser, enable
1373 // parser quirks to maintain compatibility. For details, see
1374 // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
1375 // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
1376 static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1377 && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
1379 // Mail.app must continue to display HTML email that contains quirky markup.
1380 static bool isAppleMail = applicationIsAppleMail();
1382 return isApplicationNeedingParserQuirks
1384 #if ENABLE(DASHBOARD_SUPPORT)
1385 // Pre-HTML5 parser quirks are required to remain compatible with many
1386 // Dashboard widgets. See <rdar://problem/8175982>.
1387 || (_private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode())
1389 || [[self preferences] usePreHTML5ParserQuirks];
1392 - (BOOL)_needsUnrestrictedGetMatchedCSSRules
1394 static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
1395 return needsUnrestrictedGetMatchedCSSRules;
1398 - (void)_preferencesChangedNotification:(NSNotification *)notification
1400 WebPreferences *preferences = (WebPreferences *)[notification object];
1401 [self _preferencesChanged:preferences];
1404 - (void)_preferencesChanged:(WebPreferences *)preferences
1406 ASSERT(preferences == [self preferences]);
1407 if (!_private->userAgentOverridden)
1408 _private->userAgent = String();
1410 // Cache this value so we don't have to read NSUserDefaults on each page load
1411 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
1413 // Update corresponding WebCore Settings object.
1414 if (!_private->page)
1417 Settings* settings = _private->page->settings();
1419 settings->setCursiveFontFamily([preferences cursiveFontFamily]);
1420 settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
1421 settings->setDefaultFontSize([preferences defaultFontSize]);
1422 settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
1423 settings->setUsesEncodingDetector([preferences usesEncodingDetector]);
1424 settings->setFantasyFontFamily([preferences fantasyFontFamily]);
1425 settings->setFixedFontFamily([preferences fixedFontFamily]);
1426 settings->setScreenFontSubstitutionEnabled(
1427 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1428 [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
1430 [preferences screenFontSubstitutionEnabled]
1432 settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
1433 settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
1434 settings->setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
1435 settings->setJavaEnabled([preferences isJavaEnabled]);
1436 settings->setScriptEnabled([preferences isJavaScriptEnabled]);
1437 settings->setWebSecurityEnabled([preferences isWebSecurityEnabled]);
1438 settings->setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
1439 settings->setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
1440 settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
1441 settings->setMinimumFontSize([preferences minimumFontSize]);
1442 settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
1443 settings->setPictographFontFamily([preferences pictographFontFamily]);
1444 settings->setPluginsEnabled([preferences arePlugInsEnabled]);
1445 #if ENABLE(SQL_DATABASE)
1446 DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
1448 settings->setLocalStorageEnabled([preferences localStorageEnabled]);
1449 settings->setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
1451 bool privateBrowsingEnabled = [preferences privateBrowsingEnabled];
1452 #if PLATFORM(MAC) || USE(CFNETWORK)
1453 if (privateBrowsingEnabled)
1454 WebFrameNetworkingContext::ensurePrivateBrowsingSession();
1456 WebFrameNetworkingContext::destroyPrivateBrowsingSession();
1458 settings->setPrivateBrowsingEnabled(privateBrowsingEnabled);
1460 settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
1461 settings->setSerifFontFamily([preferences serifFontFamily]);
1462 settings->setStandardFontFamily([preferences standardFontFamily]);
1463 settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
1464 settings->setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
1465 settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
1466 settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
1467 settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
1468 settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
1469 settings->setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
1470 settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
1471 settings->setUsesPageCache([self usesPageCache]);
1472 settings->setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
1473 settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
1474 settings->setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
1475 settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
1476 settings->setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
1477 settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
1478 settings->setApplicationChromeMode([preferences applicationChromeModeEnabled]);
1479 if ([preferences userStyleSheetEnabled]) {
1480 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
1481 if ([location isEqualToString:@"apple-dashboard://stylesheet"])
1482 location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
1483 settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
1485 settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
1486 settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
1487 settings->setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
1488 settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
1489 settings->setNeedsLeopardMailQuirks(runningLeopardMail());
1490 settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
1491 settings->setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
1492 settings->setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
1493 settings->setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
1494 settings->setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
1495 settings->setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
1496 settings->setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
1497 settings->setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
1499 // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
1500 // Until we fix that, I will comment out the test (CFM)
1501 settings->setAcceleratedCompositingEnabled((coreVideoHas7228836Fix() || [preferences webGLEnabled] ||
1502 [preferences accelerated2dCanvasEnabled]) && [preferences acceleratedCompositingEnabled]);
1503 settings->setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1504 settings->setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
1505 settings->setShowDebugBorders([preferences showDebugBorders]);
1506 settings->setShowRepaintCounter([preferences showRepaintCounter]);
1507 settings->setWebAudioEnabled([preferences webAudioEnabled]);
1508 settings->setWebGLEnabled([preferences webGLEnabled]);
1509 settings->setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
1510 settings->setLoadDeferringEnabled(shouldEnableLoadDeferring());
1511 settings->setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
1512 settings->setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
1513 settings->setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
1514 #if ENABLE(CSS_SHADERS)
1515 settings->setCSSCustomFilterEnabled([preferences cssCustomFilterEnabled]);
1517 RuntimeEnabledFeatures::setCSSRegionsEnabled([preferences cssRegionsEnabled]);
1518 #if ENABLE(IFRAME_SEAMLESS)
1519 RuntimeEnabledFeatures::setSeamlessIFramesEnabled([preferences seamlessIFramesEnabled]);
1521 settings->setCSSGridLayoutEnabled([preferences cssGridLayoutEnabled]);
1522 #if ENABLE(FULLSCREEN_API)
1523 settings->setFullScreenEnabled([preferences fullScreenEnabled]);
1525 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
1526 // Asynchronous spell checking API is available for 10.6 or later.
1527 settings->setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
1529 settings->setMemoryInfoEnabled([preferences memoryInfoEnabled]);
1530 settings->setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
1531 settings->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
1532 settings->setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
1533 settings->setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
1534 settings->setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
1535 #if USE(AVFOUNDATION)
1536 #if ENABLE(FULLSCREEN_API)
1537 settings->setAVFoundationEnabled([preferences isAVFoundationEnabled] && [preferences fullScreenEnabled]);
1539 settings->setAVFoundationEnabled(false);
1542 settings->setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
1543 settings->setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
1544 settings->setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
1545 settings->setRegionBasedColumnsEnabled([preferences regionBasedColumnsEnabled]);
1546 settings->setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
1547 settings->setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
1548 settings->setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
1550 #if ENABLE(VIDEO_TRACK)
1551 settings->setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
1552 settings->setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
1553 settings->setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
1556 settings->setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
1557 settings->setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
1558 settings->setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
1559 settings->setNeedsDidFinishLoadOrderQuirk(needsDidFinishLoadOrderQuirk());
1560 settings->setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
1562 switch ([preferences storageBlockingPolicy]) {
1563 case WebAllowAllStorage:
1564 settings->setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
1566 case WebBlockThirdPartyStorage:
1567 settings->setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
1569 case WebBlockAllStorage:
1570 settings->setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
1574 settings->setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
1576 // We have enabled this setting in WebKit2 for the sake of some ScrollingCoordinator work.
1577 // To avoid possible rendering differences, we should enable it for WebKit1 too.
1578 settings->setFixedPositionCreatesStackingContext(true);
1580 NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
1582 settings->setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
1584 // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
1585 [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
1587 BOOL zoomsTextOnly = [preferences zoomsTextOnly];
1588 if (_private->zoomsTextOnly != zoomsTextOnly)
1589 [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
1592 static inline IMP getMethod(id o, SEL s)
1594 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1597 - (void)_cacheResourceLoadDelegateImplementations
1599 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1600 id delegate = _private->resourceProgressDelegate;
1603 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1607 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
1608 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1609 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1610 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1611 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1612 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1613 cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
1615 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1616 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1617 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1618 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1619 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1620 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1621 cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
1622 cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
1625 - (void)_cacheFrameLoadDelegateImplementations
1627 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1628 id delegate = _private->frameLoadDelegate;
1631 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1635 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1636 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1637 cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
1638 cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
1639 cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
1640 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1641 cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
1642 cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
1643 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1644 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1645 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1646 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1647 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1648 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1649 cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
1650 cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
1651 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1652 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1653 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1654 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1655 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1656 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1657 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1658 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1659 cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
1660 cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
1661 cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
1662 cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
1664 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
1665 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
1666 // for backwards compatibility.
1667 Page* page = core(self);
1669 unsigned milestones = DidFirstLayout;
1670 if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
1671 milestones |= DidFirstVisuallyNonEmptyLayout;
1672 page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1676 - (void)_cacheScriptDebugDelegateImplementations
1678 WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
1679 id delegate = _private->scriptDebugDelegate;
1682 bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
1686 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
1687 if (cache->didParseSourceFunc)
1688 cache->didParseSourceExpectsBaseLineNumber = YES;
1690 cache->didParseSourceExpectsBaseLineNumber = NO;
1691 cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
1694 cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
1695 cache->didEnterCallFrameFunc = getMethod(delegate, @selector(webView:didEnterCallFrame:sourceId:line:forWebFrame:));
1696 cache->willExecuteStatementFunc = getMethod(delegate, @selector(webView:willExecuteStatement:sourceId:line:forWebFrame:));
1697 cache->willLeaveCallFrameFunc = getMethod(delegate, @selector(webView:willLeaveCallFrame:sourceId:line:forWebFrame:));
1699 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
1700 if (cache->exceptionWasRaisedFunc)
1701 cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
1703 cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
1704 cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
1708 - (void)_cacheHistoryDelegateImplementations
1710 WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
1711 id delegate = _private->historyDelegate;
1714 bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
1718 cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
1719 cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
1720 cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
1721 cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
1722 cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
1725 - (id)_policyDelegateForwarder
1727 if (!_private->policyDelegateForwarder)
1728 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
1729 return _private->policyDelegateForwarder;
1732 - (id)_UIDelegateForwarder
1734 if (!_private->UIDelegateForwarder)
1735 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
1736 return _private->UIDelegateForwarder;
1739 - (id)_editingDelegateForwarder
1741 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1742 // Not sure if that is a bug or not.
1746 if (!_private->editingDelegateForwarder)
1747 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
1748 return _private->editingDelegateForwarder;
1751 - (void)_closeWindow
1753 [[self _UIDelegateForwarder] webViewClose:self];
1756 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
1758 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1759 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1761 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1762 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1763 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1764 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1767 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
1769 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1770 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1772 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1773 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1774 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1775 if ([viewClass class] == [WebHTMLView class])
1776 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1778 // This is used to make _representationExistsForURLScheme faster.
1779 // Without this set, we'd have to create the MIME type each time.
1780 if (schemesWithRepresentationsSet == nil) {
1781 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1783 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1786 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1788 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1791 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1793 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1796 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
1798 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
1802 if ([NSURLConnection canHandleRequest:request])
1805 NSString *scheme = [[request URL] scheme];
1807 // Representations for URL schemes work at the top level.
1808 if (forMainFrame && [self _representationExistsForURLScheme:scheme])
1811 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
1815 if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
1822 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1824 return [self _canHandleRequest:request forMainFrame:YES];
1827 + (NSString *)_decodeData:(NSData *)data
1829 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1830 RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
1831 String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1832 result.append(decoder->flush());
1836 - (void)_pushPerformingProgrammaticFocus
1838 _private->programmaticFocusCount++;
1841 - (void)_popPerformingProgrammaticFocus
1843 _private->programmaticFocusCount--;
1846 - (BOOL)_isPerformingProgrammaticFocus
1848 return _private->programmaticFocusCount != 0;
1851 - (void)_didChangeValueForKey: (NSString *)key
1853 LOG (Bindings, "calling didChangeValueForKey: %@", key);
1854 [self didChangeValueForKey: key];
1857 - (void)_willChangeValueForKey: (NSString *)key
1859 LOG (Bindings, "calling willChangeValueForKey: %@", key);
1860 [self willChangeValueForKey: key];
1863 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1864 static NSSet *manualNotifyKeys = nil;
1865 if (!manualNotifyKeys)
1866 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1867 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
1869 if ([manualNotifyKeys containsObject:key])
1874 - (NSArray *)_declaredKeys {
1875 static NSArray *declaredKeys = nil;
1877 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1878 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1879 return declaredKeys;
1882 - (void)setObservationInfo:(void *)info
1884 _private->observationInfo = info;
1887 - (void *)observationInfo
1889 return _private->observationInfo;
1892 - (void)_willChangeBackForwardKeys
1894 [self _willChangeValueForKey: _WebCanGoBackKey];
1895 [self _willChangeValueForKey: _WebCanGoForwardKey];
1898 - (void)_didChangeBackForwardKeys
1900 [self _didChangeValueForKey: _WebCanGoBackKey];
1901 [self _didChangeValueForKey: _WebCanGoForwardKey];
1904 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1906 if (needsSelfRetainWhileLoadingQuirk())
1909 [self _willChangeBackForwardKeys];
1910 if (frame == [self mainFrame]){
1911 // Force an observer update by sending a will/did.
1912 [self _willChangeValueForKey: _WebIsLoadingKey];
1913 [self _didChangeValueForKey: _WebIsLoadingKey];
1915 [self _willChangeValueForKey: _WebMainFrameURLKey];
1918 [NSApp setWindowsNeedUpdate:YES];
1920 #if ENABLE(FULLSCREEN_API)
1921 Document* document = core([frame DOMDocument]);
1922 if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
1923 SEL selector = @selector(webView:closeFullScreenWithListener:);
1924 if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1925 WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
1926 CallUIDelegate(self, selector, listener);
1928 } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
1929 [_private->newFullscreenController close];
1935 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1937 if (frame == [self mainFrame])
1938 [self _didChangeValueForKey: _WebMainFrameURLKey];
1939 [NSApp setWindowsNeedUpdate:YES];
1942 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1944 if (needsSelfRetainWhileLoadingQuirk())
1945 [self performSelector:@selector(release) withObject:nil afterDelay:0];
1947 [self _didChangeBackForwardKeys];
1948 if (frame == [self mainFrame]){
1949 // Force an observer update by sending a will/did.
1950 [self _willChangeValueForKey: _WebIsLoadingKey];
1951 [self _didChangeValueForKey: _WebIsLoadingKey];
1953 [NSApp setWindowsNeedUpdate:YES];
1956 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1958 if (needsSelfRetainWhileLoadingQuirk())
1959 [self performSelector:@selector(release) withObject:nil afterDelay:0];
1961 [self _didChangeBackForwardKeys];
1962 if (frame == [self mainFrame]){
1963 // Force an observer update by sending a will/did.
1964 [self _willChangeValueForKey: _WebIsLoadingKey];
1965 [self _didChangeValueForKey: _WebIsLoadingKey];
1967 [NSApp setWindowsNeedUpdate:YES];
1970 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1972 if (needsSelfRetainWhileLoadingQuirk())
1973 [self performSelector:@selector(release) withObject:nil afterDelay:0];
1975 [self _didChangeBackForwardKeys];
1976 if (frame == [self mainFrame]){
1977 // Force an observer update by sending a will/did.
1978 [self _willChangeValueForKey: _WebIsLoadingKey];
1979 [self _didChangeValueForKey: _WebIsLoadingKey];
1981 [self _didChangeValueForKey: _WebMainFrameURLKey];
1983 [NSApp setWindowsNeedUpdate:YES];
1986 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1988 RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
1989 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1990 NSCachedURLResponse *cachedResponse;
1992 if (!_private->page)
1995 if (CFURLStorageSessionRef storageSession = _private->page->mainFrame()->loader()->networkingContext()->storageSession().platformSession())
1996 cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
1998 cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2000 return cachedResponse;
2003 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2005 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2006 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2007 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2009 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2010 title:[element objectForKey:WebElementImageAltStringKey]
2011 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2016 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2018 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2019 andTitle:[element objectForKey:WebElementLinkLabelKey]
2023 #if ENABLE(DRAG_SUPPORT)
2024 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2026 if (!_private->page)
2028 _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
2032 #if ENABLE(DASHBOARD_SUPPORT)
2034 #define DASHBOARD_CONTROL_LABEL @"control"
2036 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2038 NSRect adjustedBounds = bounds;
2039 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2040 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2041 adjustedBounds.size = bounds.size;
2043 NSRect adjustedClip;
2044 adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2045 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2046 adjustedClip.size = clip.size;
2048 WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds
2049 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2050 NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2051 if (!scrollerRegions) {
2052 scrollerRegions = [[NSMutableArray alloc] init];
2053 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2054 [scrollerRegions release];
2056 [scrollerRegions addObject:region];
2060 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2062 NSView *documentView = [[kit(frameView->frame()) frameView] documentView];
2064 const HashSet<RefPtr<Widget> >* children = frameView->children();
2065 HashSet<RefPtr<Widget> >::const_iterator end = children->end();
2066 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != end; ++it) {
2067 Widget* widget = (*it).get();
2068 if (widget->isFrameView()) {
2069 [self _addScrollerDashboardRegionsForFrameView:static_cast<FrameView*>(widget) dashboardRegions:regions];
2073 if (!widget->isScrollbar())
2076 // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
2077 // it's not common to need this to be correct in Dashboard widgets.
2078 NSRect bounds = widget->frameRect();
2079 [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
2083 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
2085 // Add scroller regions for NSScroller and WebCore scrollbars
2086 NSUInteger count = [views count];
2087 for (NSUInteger i = 0; i < count; i++) {
2088 NSView *view = [views objectAtIndex:i];
2090 if ([view isKindOfClass:[WebHTMLView class]]) {
2091 if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
2092 if (FrameView* coreView = coreFrame->view())
2093 [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
2095 } else if ([view isKindOfClass:[NSScroller class]]) {
2096 // AppKit places absent scrollers at -100,-100
2097 if ([view frame].origin.y < 0)
2099 [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
2101 [self _addScrollerDashboardRegions:regions from:[view subviews]];
2105 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
2107 [self _addScrollerDashboardRegions:regions from:[self subviews]];
2110 - (NSDictionary *)_dashboardRegions
2112 // Only return regions from main frame.
2113 Frame* mainFrame = [self _mainCoreFrame];
2117 const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
2118 size_t size = regions.size();
2120 NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
2121 for (size_t i = 0; i < size; i++) {
2122 const AnnotatedRegionValue& region = regions[i];
2124 if (region.type == StyleDashboardRegion::None)
2127 NSString *label = region.label;
2128 WebDashboardRegionType type = WebDashboardRegionTypeNone;
2129 if (region.type == StyleDashboardRegion::Circle)
2130 type = WebDashboardRegionTypeCircle;
2131 else if (region.type == StyleDashboardRegion::Rectangle)
2132 type = WebDashboardRegionTypeRectangle;
2133 NSMutableArray *regionValues = [webRegions objectForKey:label];
2134 if (!regionValues) {
2135 regionValues = [[NSMutableArray alloc] initWithCapacity:1];
2136 [webRegions setObject:regionValues forKey:label];
2137 [regionValues release];
2140 WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:pixelSnappedIntRect(region.bounds) clip:pixelSnappedIntRect(region.clip) type:type];
2141 [regionValues addObject:webRegion];
2142 [webRegion release];
2145 [self _addScrollerDashboardRegions:webRegions];
2150 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
2152 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
2153 // specific support for the backward compatibility mode flag.
2154 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
2155 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
2158 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2159 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
2162 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2163 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
2166 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2167 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
2170 case WebDashboardBehaviorAllowWheelScrolling: {
2171 _private->dashboardBehaviorAllowWheelScrolling = flag;
2174 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2176 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
2181 // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
2182 // compatibility mode. See <rdar://problem/8175982>.
2184 _private->page->settings()->setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2187 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
2190 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
2191 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
2193 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
2194 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
2196 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
2197 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
2199 case WebDashboardBehaviorAllowWheelScrolling: {
2200 return _private->dashboardBehaviorAllowWheelScrolling;
2202 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
2203 return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
2209 #endif /* ENABLE(DASHBOARD_SUPPORT) */
2211 + (void)_setShouldUseFontSmoothing:(BOOL)f
2213 Font::setShouldUseSmoothing(f);
2216 + (BOOL)_shouldUseFontSmoothing
2218 return Font::shouldUseSmoothing();
2221 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
2223 setUsesTestModeFocusRingColor(f);
2226 + (BOOL)_usesTestModeFocusRingColor
2228 return usesTestModeFocusRingColor();
2231 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
2233 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2235 [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2237 [scrollview setVerticalScrollingModeLocked:NO];
2238 [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
2242 - (BOOL)alwaysShowVerticalScroller
2244 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2245 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
2248 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
2250 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2252 [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
2254 [scrollview setHorizontalScrollingModeLocked:NO];
2255 [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
2259 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
2261 if (Frame* mainFrame = [self _mainCoreFrame])
2262 mainFrame->view()->setProhibitsScrolling(prohibits);
2265 - (BOOL)alwaysShowHorizontalScroller
2267 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
2268 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
2271 - (void)_setInViewSourceMode:(BOOL)flag
2273 if (Frame* mainFrame = [self _mainCoreFrame])
2274 mainFrame->setInViewSourceMode(flag);
2277 - (BOOL)_inViewSourceMode
2279 Frame* mainFrame = [self _mainCoreFrame];
2280 return mainFrame && mainFrame->inViewSourceMode();
2283 - (void)_setUseFastImageScalingMode:(BOOL)flag
2285 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
2286 _private->page->setInLowQualityImageInterpolationMode(flag);
2287 [self setNeedsDisplay:YES];
2291 - (BOOL)_inFastImageScalingMode
2294 return _private->page->inLowQualityImageInterpolationMode();
2298 - (BOOL)_cookieEnabled
2301 return _private->page->settings()->cookieEnabled();
2305 - (void)_setCookieEnabled:(BOOL)enable
2308 _private->page->settings()->setCookieEnabled(enable);
2311 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
2313 if (!_private->pluginDatabase)
2314 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
2316 [_private->pluginDatabase setPlugInPaths:newPaths];
2317 [_private->pluginDatabase refresh];
2320 - (void)_attachScriptDebuggerToAllFrames
2322 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2323 [kit(frame) _attachScriptDebugger];
2326 - (void)_detachScriptDebuggerFromAllFrames
2328 for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
2329 [kit(frame) _detachScriptDebugger];
2332 - (void)setBackgroundColor:(NSColor *)backgroundColor
2334 if ([_private->backgroundColor isEqual:backgroundColor])
2337 id old = _private->backgroundColor;
2338 _private->backgroundColor = [backgroundColor retain];
2341 [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
2344 - (NSColor *)backgroundColor
2346 return _private->backgroundColor;
2349 - (BOOL)defersCallbacks
2351 if (!_private->page)
2353 return _private->page->defersLoading();
2356 - (void)setDefersCallbacks:(BOOL)defer
2358 if (!_private->page)
2360 return _private->page->setDefersLoading(defer);
2363 // For backwards compatibility with the WebBackForwardList API, we honor both
2364 // a per-WebView and a per-preferences setting for whether to use the page cache.
2366 - (BOOL)usesPageCache
2368 return _private->usesPageCache && [[self preferences] usesPageCache];
2371 - (void)setUsesPageCache:(BOOL)usesPageCache
2373 _private->usesPageCache = usesPageCache;
2375 // Update our own settings and post the public notification only
2376 [self _preferencesChanged:[self preferences]];
2377 [[self preferences] _postPreferencesChangedAPINotification];
2380 - (WebHistoryItem *)_globalHistoryItem
2385 return kit(_private->_globalHistoryItem.get());
2388 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
2390 _private->_globalHistoryItem = historyItem;
2393 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
2395 IntPoint rectStart(rect.origin.x, rect.origin.y);
2396 IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
2398 Frame* coreFrame = [self _mainCoreFrame];
2402 VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
2404 return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
2407 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
2409 NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window];
2410 [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window];
2413 - (void)_clearUndoRedoOperations
2415 if (!_private->page)
2417 _private->page->clearUndoRedoOperations();
2420 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
2422 Frame* coreFrame = [self _mainCoreFrame];
2425 coreFrame->editor()->command(name).execute(value);
2428 - (void)_setCustomHTMLTokenizerTimeDelay:(double)timeDelay
2430 if (!_private->page)
2432 return _private->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
2435 - (void)_setCustomHTMLTokenizerChunkSize:(int)chunkSize
2437 if (!_private->page)
2439 return _private->page->setCustomHTMLTokenizerChunkSize(chunkSize);
2442 - (void)_clearMainFrameName
2444 _private->page->mainFrame()->tree()->clearName();
2447 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
2449 _private->selectTrailingWhitespaceEnabled = flag;
2451 [self setSmartInsertDeleteEnabled:false];
2454 - (BOOL)isSelectTrailingWhitespaceEnabled
2456 return _private->selectTrailingWhitespaceEnabled;
2459 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
2461 _private->page->setMemoryCacheClientCallsEnabled(enabled);
2464 - (BOOL)areMemoryCacheDelegateCallsEnabled
2466 return _private->page->areMemoryCacheClientCallsEnabled();
2469 + (NSCursor *)_pointingHandCursor
2471 return handCursor().platformCursor();
2474 - (BOOL)_postsAcceleratedCompositingNotifications
2476 #if USE(ACCELERATED_COMPOSITING)
2477 return _private->postsAcceleratedCompositingNotifications;
2483 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
2485 #if USE(ACCELERATED_COMPOSITING)
2486 _private->postsAcceleratedCompositingNotifications = flag;
2490 - (BOOL)_isUsingAcceleratedCompositing
2492 #if USE(ACCELERATED_COMPOSITING)
2493 Frame* coreFrame = [self _mainCoreFrame];
2494 for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2495 NSView *documentView = [[kit(frame) frameView] documentView];
2496 if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
2503 - (void)_setBaseCTM:(CGAffineTransform)transform forContext:(CGContextRef)context
2505 WKSetBaseCTM(context, transform);
2508 - (BOOL)interactiveFormValidationEnabled
2510 return _private->interactiveFormValidationEnabled;
2513 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
2515 _private->interactiveFormValidationEnabled = enabled;
2518 - (int)validationMessageTimerMagnification
2520 return _private->validationMessageTimerMagnification;
2523 - (void)setValidationMessageTimerMagnification:(int)newValue
2525 _private->validationMessageTimerMagnification = newValue;
2528 - (BOOL)_isSoftwareRenderable
2530 #if USE(ACCELERATED_COMPOSITING)
2531 Frame* coreFrame = [self _mainCoreFrame];
2532 for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2533 if (FrameView* view = frame->view()) {
2534 if (!view->isSoftwareRenderable())
2542 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
2544 _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
2547 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
2549 return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
2552 - (void)setTracksRepaints:(BOOL)flag
2554 Frame* coreFrame = [self _mainCoreFrame];
2555 if (FrameView* view = coreFrame->view())
2556 view->setTracksRepaints(flag);
2559 - (BOOL)isTrackingRepaints
2561 Frame* coreFrame = [self _mainCoreFrame];
2562 if (FrameView* view = coreFrame->view())
2563 return view->isTrackingRepaints();
2568 - (void)resetTrackedRepaints
2570 Frame* coreFrame = [self _mainCoreFrame];
2571 if (FrameView* view = coreFrame->view())
2572 view->resetTrackedRepaints();
2575 - (NSArray*)trackedRepaintRects
2577 Frame* coreFrame = [self _mainCoreFrame];
2578 FrameView* view = coreFrame->view();
2579 if (!view || !view->isTrackingRepaints())
2582 const Vector<IntRect>& repaintRects = view->trackedRepaintRects();
2583 NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
2585 for (unsigned i = 0; i < repaintRects.size(); ++i)
2586 [rectsArray addObject:[NSValue valueWithRect:pixelSnappedIntRect(repaintRects[i])]];
2588 return [rectsArray autorelease];
2591 - (NSPasteboard *)_insertionPasteboard
2593 return _private ? _private->insertionPasteboard : nil;
2596 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2598 SecurityPolicy::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2601 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2603 SecurityPolicy::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2606 +(void)_resetOriginAccessWhitelists
2608 SecurityPolicy::resetOriginAccessWhitelists();
2611 - (void)_updateActiveState
2613 if (_private && _private->page)
2614 _private->page->focusController()->setActive([[self window] _hasKeyAppearance]);
2617 static Vector<String> toStringVector(NSArray* patterns)
2619 Vector<String> patternsVector;
2621 NSUInteger count = [patterns count];
2623 return patternsVector;
2625 for (NSUInteger i = 0; i < count; ++i) {
2626 id entry = [patterns objectAtIndex:i];
2627 if ([entry isKindOfClass:[NSString class]])
2628 patternsVector.append(String((NSString *)entry));
2630 return patternsVector;
2633 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2634 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2635 injectionTime:(WebUserScriptInjectionTime)injectionTime
2637 [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
2640 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2641 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2642 injectionTime:(WebUserScriptInjectionTime)injectionTime
2643 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2645 String group(groupName);
2646 if (group.isEmpty())
2649 PageGroup* pageGroup = PageGroup::pageGroup(group);
2653 pageGroup->addUserScriptToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist),
2654 injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
2655 injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2658 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2659 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2661 [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
2664 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2665 whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2666 injectedFrames:(WebUserContentInjectedFrames)injectedFrames
2668 String group(groupName);
2669 if (group.isEmpty())
2672 PageGroup* pageGroup = PageGroup::pageGroup(group);
2676 pageGroup->addUserStyleSheetToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
2679 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2681 String group(groupName);
2682 if (group.isEmpty())
2685 PageGroup* pageGroup = PageGroup::pageGroup(group);
2689 pageGroup->removeUserScriptFromWorld(core(world), url);
2692 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2694 String group(groupName);
2695 if (group.isEmpty())
2698 PageGroup* pageGroup = PageGroup::pageGroup(group);
2702 pageGroup->removeUserStyleSheetFromWorld(core(world), url);
2705 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2707 String group(groupName);
2708 if (group.isEmpty())
2711 PageGroup* pageGroup = PageGroup::pageGroup(group);
2715 pageGroup->removeUserScriptsFromWorld(core(world));
2718 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2720 String group(groupName);
2721 if (group.isEmpty())
2724 PageGroup* pageGroup = PageGroup::pageGroup(group);
2728 pageGroup->removeUserStyleSheetsFromWorld(core(world));
2731 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
2733 String group(groupName);
2734 if (group.isEmpty())
2737 PageGroup* pageGroup = PageGroup::pageGroup(group);
2741 pageGroup->removeAllUserContent();
2744 - (BOOL)cssAnimationsSuspended
2746 return _private->cssAnimationsSuspended;
2749 - (void)setCSSAnimationsSuspended:(BOOL)suspended
2751 if (suspended == _private->cssAnimationsSuspended)
2754 _private->cssAnimationsSuspended = suspended;
2756 Frame* frame = core([self mainFrame]);
2758 frame->animation()->suspendAnimations();
2760 frame->animation()->resumeAnimations();
2763 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
2765 SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
2768 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
2770 SchemeRegistry::registerURLSchemeAsSecure(scheme);
2773 + (void)_registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing:(NSString *)scheme
2775 SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing(scheme);
2778 + (void)_registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing:(NSString *)scheme
2780 SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing(scheme);
2783 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
2785 _private->page->setPageScaleFactor(scale, IntPoint(origin));
2788 - (float)_viewScaleFactor
2790 return _private->page->pageScaleFactor();
2793 - (void)_setUseFixedLayout:(BOOL)fixed
2795 Frame* coreFrame = [self _mainCoreFrame];
2799 FrameView* view = coreFrame->view();
2803 view->setUseFixedLayout(fixed);
2805 view->setFixedLayoutSize(IntSize());
2808 - (void)_setFixedLayoutSize:(NSSize)size
2810 Frame* coreFrame = [self _mainCoreFrame];
2814 FrameView* view = coreFrame->view();
2818 view->setFixedLayoutSize(IntSize(size));
2819 view->forceLayout();
2822 - (BOOL)_useFixedLayout
2824 Frame* coreFrame = [self _mainCoreFrame];
2828 FrameView* view = coreFrame->view();
2832 return view->useFixedLayout();
2835 - (NSSize)_fixedLayoutSize
2837 Frame* coreFrame = [self _mainCoreFrame];
2841 FrameView* view = coreFrame->view();
2845 return view->fixedLayoutSize();
2848 - (void)_setPaginationMode:(WebPaginationMode)paginationMode
2850 Page* page = core(self);
2854 Pagination pagination = page->pagination();
2855 switch (paginationMode) {
2856 case WebPaginationModeUnpaginated:
2857 pagination.mode = Pagination::Unpaginated;
2859 case WebPaginationModeLeftToRight:
2860 pagination.mode = Pagination::LeftToRightPaginated;
2862 case WebPaginationModeRightToLeft:
2863 pagination.mode = Pagination::RightToLeftPaginated;
2865 case WebPaginationModeTopToBottom:
2866 pagination.mode = Pagination::TopToBottomPaginated;
2868 case WebPaginationModeBottomToTop:
2869 pagination.mode = Pagination::BottomToTopPaginated;
2875 page->setPagination(pagination);
2878 - (WebPaginationMode)_paginationMode
2880 Page* page = core(self);
2882 return WebPaginationModeUnpaginated;
2884 switch (page->pagination().mode) {
2885 case Pagination::Unpaginated:
2886 return WebPaginationModeUnpaginated;
2887 case Pagination::LeftToRightPaginated:
2888 return WebPaginationModeLeftToRight;
2889 case Pagination::RightToLeftPaginated:
2890 return WebPaginationModeRightToLeft;
2891 case Pagination::TopToBottomPaginated:
2892 return WebPaginationModeTopToBottom;
2893 case Pagination::BottomToTopPaginated:
2894 return WebPaginationModeBottomToTop;
2897 ASSERT_NOT_REACHED();
2898 return WebPaginationModeUnpaginated;
2901 - (void)_listenForLayoutMilestones:(WebLayoutMilestones)layoutMilestones
2903 Page* page = core(self);
2907 page->addLayoutMilestones(coreLayoutMilestones(layoutMilestones));
2910 - (WebLayoutMilestones)_layoutMilestones
2912 Page* page = core(self);
2916 return kitLayoutMilestones(page->layoutMilestones());
2919 - (void)_setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns
2921 Page* page = core(self);
2925 Pagination pagination = page->pagination();
2926 pagination.behavesLikeColumns = behavesLikeColumns;
2928 page->setPagination(pagination);
2931 - (BOOL)_paginationBehavesLikeColumns
2933 Page* page = core(self);
2937 return page->pagination().behavesLikeColumns;
2940 - (void)_setPageLength:(CGFloat)pageLength
2942 Page* page = core(self);
2946 Pagination pagination = page->pagination();
2947 pagination.pageLength = pageLength;
2949 page->setPagination(pagination);
2952 - (CGFloat)_pageLength
2954 Page* page = core(self);
2958 return page->pagination().pageLength;
2961 - (void)_setGapBetweenPages:(CGFloat)pageGap
2963 Page* page = core(self);
2967 Pagination pagination = page->pagination();
2968 pagination.gap = pageGap;
2969 page->setPagination(pagination);
2972 - (CGFloat)_gapBetweenPages
2974 Page* page = core(self);
2978 return page->pagination().gap;
2981 - (NSUInteger)_pageCount
2983 Page* page = core(self);
2987 return page->pageCount();
2990 - (CGFloat)_backingScaleFactor
2992 return [self _deviceScaleFactor];
2995 - (void)_setCustomBackingScaleFactor:(CGFloat)customScaleFactor
2997 float oldScaleFactor = [self _deviceScaleFactor];
2999 _private->customDeviceScaleFactor = customScaleFactor;
3001 if (oldScaleFactor != [self _deviceScaleFactor])
3002 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
3005 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
3007 return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:YES];
3010 - (NSUInteger)countMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit markMatches:(BOOL)markMatches
3012 return [self countMatchesForText:string options:(caseFlag ? 0 : WebFindOptionsCaseInsensitive) highlight:highlight limit:limit markMatches:markMatches];
3015 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
3017 return [self findString:string options:((forward ? 0 : WebFindOptionsBackwards) | (caseFlag ? 0 : WebFindOptionsCaseInsensitive) | (wrapFlag ? WebFindOptionsWrapAround : 0) | (startInSelection ? WebFindOptionsStartInSelection : 0))];
3020 + (void)_setLoadResourcesSerially:(BOOL)serialize
3022 WebPlatformStrategies::initialize();
3023 resourceLoadScheduler()->setSerialLoadingEnabled(serialize);
3026 + (double)_defaultMinimumTimerInterval
3028 return Settings::defaultMinDOMTimerInterval();
3031 - (void)_setMinimumTimerInterval:(double)intervalInSeconds
3034 _private->page->settings()->setMinDOMTimerInterval(intervalInSeconds);
3037 + (BOOL)_HTTPPipeliningEnabled
3039 return ResourceRequest::httpPipeliningEnabled();
3042 + (void)_setHTTPPipeliningEnabled:(BOOL)enabled
3044 ResourceRequest::setHTTPPipeliningEnabled(enabled);
3047 - (void)_setVisibilityState:(int)visibilityState isInitialState:(BOOL)isInitialState
3049 #if ENABLE(PAGE_VISIBILITY_API) || ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
3050 if (_private->page) {
3051 _private->page->setVisibilityState(static_cast<PageVisibilityState>(visibilityState), isInitialState);
3058 @implementation _WebSafeForwarder
3060 // Used to send messages to delegates that implement informal protocols.
3062 - (id)initWithTarget:(id)t defaultTarget:(id)dt
3064 self = [super init];
3067 target = t; // Non retained.
3072 - (void)forwardInvocation:(NSInvocation *)invocation
3074 if ([target respondsToSelector:[invocation selector]]) {
3076 [invocation invokeWithTarget:target];
3077 } @catch(id exception) {
3078 ReportDiscardedDelegateException([invocation selector], exception);
3083 if ([defaultTarget respondsToSelector:[invocation selector]])
3084 [invocation invokeWithTarget:defaultTarget];
3086 // Do nothing quietly if method not implemented.
3089 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
3091 return [defaultTarget methodSignatureForSelector:aSelector];
3096 @implementation WebView
3100 static BOOL initialized = NO;
3105 InitWebCoreSystemInterface();
3106 JSC::initializeThreading();
3107 WTF::initializeMainThreadToProcessMainThread();
3108 WebCore::RunLoop::initializeMainRunLoop();
3110 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
3111 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_cacheModelChangedNotification:) name:WebPreferencesCacheModelChangedInternalNotification object:nil];
3112 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];
3114 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
3116 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
3117 [defaults registerDefaults:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]];
3120 continuousSpellCheckingEnabled = [defaults boolForKey:WebContinuousSpellCheckingEnabled];
3121 grammarCheckingEnabled = [defaults boolForKey:WebGrammarCheckingEnabled];
3123 Font::setDefaultTypesettingFeatures([defaults boolForKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey] ? Kerning | Ligatures : 0);
3125 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
3126 automaticQuoteSubstitutionEnabled = [defaults boolForKey:WebAutomaticQuoteSubstitutionEnabled];
3127 automaticLinkDetectionEnabled = [defaults boolForKey:WebAutomaticLinkDetectionEnabled];
3128 automaticDashSubstitutionEnabled = [defaults boolForKey:WebAutomaticDashSubstitutionEnabled];
3129 automaticTextReplacementEnabled = [defaults boolForKey:WebAutomaticTextReplacementEnabled];
3130 automaticSpellingCorrectionEnabled = [defaults boolForKey:WebAutomaticSpellingCorrectionEnabled];
3133 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
3134 if (![defaults objectForKey:WebAutomaticTextReplacementEnabled])
3135 automaticTextReplacementEnabled = [NSSpellChecker isAutomaticTextReplacementEnabled];
3136 if (![defaults objectForKey:WebAutomaticSpellingCorrectionEnabled])
3137 automaticSpellingCorrectionEnabled = [NSSpellChecker isAutomaticSpellingCorrectionEnabled];
3141 + (void)_applicationWillTerminate
3143 applicationIsTerminating = YES;
3145 if (fastDocumentTeardownEnabled())
3146 [self closeAllWebViews];
3148 if (!pluginDatabaseClientCount)
3149 [WebPluginDatabase closeSharedDatabase];
3151 PageGroup::closeLocalStorage();
3154 + (BOOL)_canShowMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
3156 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType allowingPlugins:allowPlugins];
3159 + (BOOL)canShowMIMEType:(NSString *)MIMEType
3161 return [self _canShowMIMEType:MIMEType allowingPlugins:YES];
3164 - (BOOL)_canShowMIMEType:(NSString *)MIMEType
3166 return [[self class] _canShowMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]];
3169 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
3171 if (![_private->preferences arePlugInsEnabled])
3174 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3176 return pluginPackage;
3178 if (_private->pluginDatabase)
3179 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3184 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
3185 - (WebBasePluginPackage *)_videoProxyPluginForMIMEType:(NSString *)MIMEType
3187 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
3189 return pluginPackage;
3191 if (_private->pluginDatabase)
3192 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
3198 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
3200 if (![_private->preferences arePlugInsEnabled])
3203 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
3205 return pluginPackage;
3207 if (_private->pluginDatabase)
3208 return [_private->pluginDatabase pluginForExtension:extension];
3213 - (void)addPluginInstanceView:(NSView *)view
3215 if (!_private->pluginDatabase)
3216 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3217 [_private->pluginDatabase addPluginInstanceView:view];
3220 - (void)removePluginInstanceView:(NSView *)view
3222 if (_private->pluginDatabase)
3223 [_private->pluginDatabase removePluginInstanceView:view];
3226 - (void)removePluginInstanceViewsFor:(WebFrame*)webFrame
3228 if (_private->pluginDatabase)
3229 [_private->pluginDatabase removePluginInstanceViewsFor:webFrame];
3232 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
3234 if (![_private->preferences arePlugInsEnabled])
3237 if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
3240 if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
3246 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
3248 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
3251 + (NSArray *)MIMETypesShownAsHTML
3253 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
3254 NSEnumerator *enumerator = [viewTypes keyEnumerator];
3256 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
3258 while ((key = [enumerator nextObject])) {
3259 if ([viewTypes objectForKey:key] == [WebHTMLView class])
3260 [array addObject:key];
3266 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
3268 NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
3269 NSEnumerator *enumerator = [viewTypes keyEnumerator];
3271 while ((key = [enumerator nextObject])) {
3272 if ([viewTypes objectForKey:key] == [WebHTMLView class])
3273 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
3276 int i, count = [MIMETypes count];
3277 for (i = 0; i < count; i++) {
3278 [WebView registerViewClass:[WebHTMLView class]
3279 representationClass:[WebHTMLRepresentation class]
3280 forMIMEType:[MIMETypes objectAtIndex:i]];
3282 [viewTypes release];
3285 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
3287 return [pasteboard _web_bestURL];
3290 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
3292 return [pasteboard stringForType:WebURLNamePboardType];
3295 + (void)registerURLSchemeAsLocal:(NSString *)protocol
3297 SchemeRegistry::registerURLSchemeAsLocal(protocol);
3300 - (id)_initWithArguments:(NSDictionary *) arguments
3302 NSCoder *decoder = [arguments objectForKey:@"decoder"];
3304 self = [self initWithCoder:decoder];
3306 ASSERT([arguments objectForKey:@"frame"]);
3307 NSValue *frameValue = [arguments objectForKey:@"frame"];
3308 NSRect frame = (frameValue ? [frameValue rectValue] : NSZeroRect);
3309 NSString *frameName = [arguments objectForKey:@"frameName"];
3310 NSString *groupName = [arguments objectForKey:@"groupName"];
3311 self = [self initWithFrame:frame frameName:frameName groupName:groupName];
3317 static bool clientNeedsWebViewInitThreadWorkaround()
3319 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_WEBVIEW_INIT_THREAD_WORKAROUND))
3322 NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
3325 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.installer"])
3329 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Automator"])
3332 // Automator Runner.
3333 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.AutomatorRunner"])
3336 // Automator workflows.
3337 if ([bundleIdentifier _webkit_hasCaseInsensitivePrefix:@"com.apple.Automator."])
3340 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
3342 if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Mail"])
3349 static bool needsWebViewInitThreadWorkaround()
3351 static bool isOldClient = clientNeedsWebViewInitThreadWorkaround();
3352 return isOldClient && !pthread_main_np();
3355 - (id)initWithFrame:(NSRect)f
3357 return [self initWithFrame:f frameName:nil groupName:nil];
3360 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
3362 if (needsWebViewInitThreadWorkaround())
3363 return [[self _webkit_invokeOnMainThread] initWithFrame:f frameName:frameName groupName:groupName];
3365 WebCoreThreadViolationCheckRoundTwo();
3366 return [self _initWithFrame:f frameName:frameName groupName:groupName usesDocumentViews:YES];
3369 - (id)initWithCoder:(NSCoder *)decoder
3371 if (needsWebViewInitThreadWorkaround())
3372 return [[self _webkit_invokeOnMainThread] initWithCoder:decoder];
3374 WebCoreThreadViolationCheckRoundTwo();
3375 WebView *result = nil;
3378 NSString *frameName;
3379 NSString *groupName;
3380 WebPreferences *preferences;
3381 BOOL useBackForwardList = NO;
3382 BOOL allowsUndo = YES;
3384 result = [super initWithCoder:decoder];
3385 result->_private = [[WebViewPrivate alloc] init];
3387 // We don't want any of the archived subviews. The subviews will always
3388 // be created in _commonInitializationFrameName:groupName:.
3389 [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
3391 if ([decoder allowsKeyedCoding]) {
3392 frameName = [decoder decodeObjectForKey:@"FrameName"];
3393 groupName = [decoder decodeObjectForKey:@"GroupName"];
3394 preferences = [decoder decodeObjectForKey:@"Preferences"];
3395 useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
3396 if ([decoder containsValueForKey:@"AllowsUndo"])
3397 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
3400 [decoder decodeValueOfObjCType:@encode(int) at:&version];
3401 frameName = [decoder decodeObject];
3402 groupName = [decoder decodeObject];
3403 preferences = [decoder decodeObject];
3405 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
3406 // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
3407 // version 3 NIBs that have this field encoded, we still need to read it in.
3409 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
3412 if (![frameName isKindOfClass:[NSString class]])
3414 if (![groupName isKindOfClass:[NSString class]])
3416 if (![preferences isKindOfClass:[WebPreferences class]])
3419 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
3420 [result _commonInitializationWithFrameName:frameName groupName:groupName];
3421 static_cast<BackForwardListImpl*>([result page]->backForwardList())->setEnabled(useBackForwardList);
3422 result->_private->allowsUndo = allowsUndo;
3424 [result setPreferences:preferences];
3425 } @catch (NSException *localException) {
3433 - (void)encodeWithCoder:(NSCoder *)encoder
3435 // Set asside the subviews before we archive. We don't want to archive any subviews.
3436 // The subviews will always be created in _commonInitializationFrameName:groupName:.
3437 id originalSubviews = _subviews;
3440 [super encodeWithCoder:encoder];
3442 // Restore the subviews we set aside.
3443 _subviews = originalSubviews;
3445 BOOL useBackForwardList = _private->page && static_cast<BackForwardListImpl*>(_private->page->backForwardList())->enabled();
3446 if ([encoder allowsKeyedCoding]) {
3447 [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
3448 [encoder encodeObject:[self groupName] forKey:@"GroupName"];
3449 [encoder encodeObject:[self preferences] forKey:@"Preferences"];
3450 [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
3451 [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
3453 int version = WebViewVersion;
3454 [encoder encodeValueOfObjCType:@encode(int) at:&version];
3455 [encoder encodeObject:[[self mainFrame] name]];
3456 [encoder encodeObject:[self groupName]];
3457 [encoder encodeObject:[self preferences]];
3458 [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
3459 // DO NOT encode any new fields here, doing so will break older WebKit releases.
3462 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
3467 if (WebCoreObjCScheduleDeallocateOnMainThread([WebView class], self))
3470 // call close to ensure we tear-down completely
3471 // this maintains our old behavior for existing applications
3474 if ([[self class] shouldIncludeInWebKitStatistics])
3477 if ([self _needsFrameLoadDelegateRetainQuirk])
3478 [_private->frameLoadDelegate release];
3481 // [super dealloc] can end up dispatching against _private (3466082)
3489 ASSERT(_private->closed);
3498 // _close existed first, and some clients might be calling or overriding it, so call through.
3502 - (void)setShouldCloseWithWindow:(BOOL)close
3504 _private->shouldCloseWithWindow = close;
3507 - (BOOL)shouldCloseWithWindow
3509 return _private->shouldCloseWithWindow;
3512 // FIXME: Use AppKit constants for these when they are available.
3513 static NSString * const windowDidChangeBackingPropertiesNotification = @"NSWindowDidChangeBackingPropertiesNotification";
3514 static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOldScaleFactorKey";
3516 - (void)addWindowObserversForWindow:(NSWindow *)window
3519 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOnScreen:)
3520 name:WKWindowWillOrderOnScreenNotification() object:window];
3521 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOffScreen:)
3522 name:WKWindowWillOrderOffScreenNotification() object:window];
3523 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:)
3524 name:windowDidChangeBackingPropertiesNotification object:window];
3525 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:)
3526 name:NSWindowDidChangeScreenNotification object:window];
3530 - (void)removeWindowObservers
3532 NSWindow *window = [self window];
3534 [[NSNotificationCenter defaultCenter] removeObserver:self
3535 name:WKWindowWillOrderOnScreenNotification() object:window];
3536 [[NSNotificationCenter defaultCenter] removeObserver:self
3537 name:WKWindowWillOrderOffScreenNotification() object:window];
3538 [[NSNotificationCenter defaultCenter] removeObserver:self
3539 name:windowDidChangeBackingPropertiesNotification object:window];
3540 [[NSNotificationCenter defaultCenter] removeObserver:self
3541 name:NSWindowDidChangeScreenNotification object:window];
3545 - (void)viewWillMoveToWindow:(NSWindow *)window
3547 // Don't do anything if the WebView isn't initialized.
3548 // This happens when decoding a WebView in a nib.
3549 // FIXME: What sets up the observer of NSWindowWillCloseNotification in this case?
3550 if (!_private || _private->closed)
3553 if ([self window] && [self window] != [self hostWindow])
3554 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
3557 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
3559 // Ensure that we will receive the events that WebHTMLView (at least) needs.
3560 // The following are expensive enough that we don't want to call them over
3561 // and over, so do them when we move into a window.
3562 [window setAcceptsMouseMovedEvents:YES];
3563 WKSetNSWindowShouldPostEventNotifications(window, YES);
3565 _private->page->setCanStartMedia(false);
3566 _private->page->willMoveOffscreen();
3569 if (window != [self window]) {
3570 [self removeWindowObservers];
3571 [self addWindowObserversForWindow:window];
3575 - (void)viewDidMoveToWindow
3577 // Don't do anything if we aren't initialized. This happens
3578 // when decoding a WebView. When WebViews are decoded their subviews
3579 // are created by initWithCoder: and so won't be normally
3580 // initialized. The stub views are discarded by WebView.
3581 if (!_private || _private->closed)
3584 if ([self window]) {
3585 _private->page->setCanStartMedia(true);
3586 _private->page->didMoveOnscreen();
3589 _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
3591 [self _updateActiveState];
3594 - (void)doWindowDidChangeScreen
3596 if (_private && _private->page)
3597 _private->page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]);
3600 - (void)_windowChangedKeyState
3602 [self _updateActiveState];