2 * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #import "WebViewInternal.h"
32 #import "DOMRangeInternal.h"
33 #import "WebBackForwardList.h"
34 #import "WebBackForwardListInternal.h"
35 #import "WebBaseNetscapePluginView.h"
36 #import "WebChromeClient.h"
37 #import "WebContextMenuClient.h"
38 #import "WebDOMOperationsPrivate.h"
39 #import "WebDatabaseManagerInternal.h"
40 #import "WebDatabaseManagerPrivate.h"
41 #import "WebDataSourceInternal.h"
42 #import "WebDefaultEditingDelegate.h"
43 #import "WebDefaultPolicyDelegate.h"
44 #import "WebDefaultScriptDebugDelegate.h"
45 #import "WebDefaultUIDelegate.h"
46 #import "WebDocument.h"
47 #import "WebDocumentInternal.h"
48 #import "WebDownload.h"
49 #import "WebDownloadInternal.h"
50 #import "WebDragClient.h"
51 #import "WebDynamicScrollBarsView.h"
52 #import "WebEditingDelegate.h"
53 #import "WebEditorClient.h"
54 #import "WebFormDelegatePrivate.h"
55 #import "WebFrameBridge.h"
56 #import "WebFrameInternal.h"
57 #import "WebFrameViewInternal.h"
58 #import "WebHTMLRepresentation.h"
59 #import "WebHTMLViewInternal.h"
60 #import "WebHistoryItemInternal.h"
61 #import "WebIconDatabase.h"
62 #import "WebIconDatabaseInternal.h"
63 #import "WebInspector.h"
64 #import "WebInspectorClient.h"
65 #import "WebKitErrors.h"
66 #import "WebKitLogging.h"
67 #import "WebKitNSStringExtras.h"
68 #import "WebKitStatisticsPrivate.h"
69 #import "WebKitSystemBits.h"
70 #import "WebKitVersionChecks.h"
71 #import "WebLocalizableStrings.h"
72 #import "WebNSDataExtras.h"
73 #import "WebNSDataExtrasPrivate.h"
74 #import "WebNSDictionaryExtras.h"
75 #import "WebNSEventExtras.h"
76 #import "WebNSObjectExtras.h"
77 #import "WebNSPasteboardExtras.h"
78 #import "WebNSPrintOperationExtras.h"
79 #import "WebNSURLExtras.h"
80 #import "WebNSURLRequestExtras.h"
81 #import "WebNSUserDefaultsExtras.h"
82 #import "WebNSViewExtras.h"
83 #import "WebPanelAuthenticationHandler.h"
84 #import "WebPasteboardHelper.h"
85 #import "WebPDFView.h"
86 #import "WebPluginDatabase.h"
87 #import "WebPolicyDelegate.h"
88 #import "WebPreferenceKeysPrivate.h"
89 #import "WebPreferencesPrivate.h"
90 #import "WebScriptDebugDelegatePrivate.h"
91 #import "WebScriptDebugServerPrivate.h"
92 #import "WebUIDelegate.h"
93 #import "WebUIDelegatePrivate.h"
94 #import <CoreFoundation/CFSet.h>
95 #import <Foundation/NSURLConnection.h>
96 #import <JavaScriptCore/Assertions.h>
97 #import <WebCore/Cache.h>
98 #import <WebCore/ColorMac.h>
99 #import <WebCore/Document.h>
100 #import <WebCore/DocumentLoader.h>
101 #import <WebCore/DragController.h>
102 #import <WebCore/DragData.h>
103 #import <WebCore/Editor.h>
104 #import <WebCore/ExceptionHandlers.h>
105 #import <WebCore/Frame.h>
106 #import <WebCore/FrameLoader.h>
107 #import <WebCore/FrameTree.h>
108 #import <WebCore/HTMLNames.h>
109 #import <WebCore/HistoryItem.h>
110 #import <WebCore/Logging.h>
111 #import <WebCore/MIMETypeRegistry.h>
112 #import <WebCore/Page.h>
113 #import <WebCore/PageCache.h>
114 #import <WebCore/PlatformMouseEvent.h>
115 #import <WebCore/ProgressTracker.h>
116 #import <WebCore/SelectionController.h>
117 #import <WebCore/Settings.h>
118 #import <WebCore/TextResourceDecoder.h>
119 #import <WebCore/WebCoreFrameBridge.h>
120 #import <WebCore/WebCoreObjCExtras.h>
121 #import <WebCore/WebCoreTextRenderer.h>
122 #import <WebCore/WebCoreView.h>
123 #import <WebKit/DOM.h>
124 #import <WebKit/DOMExtensions.h>
125 #import <WebKit/DOMPrivate.h>
126 #import <WebKit/WebDashboardRegion.h>
127 #import <WebKitSystemInterface.h>
128 #import <mach-o/dyld.h>
129 #import <objc/objc-auto.h>
130 #import <objc/objc-runtime.h>
131 #import <wtf/RefPtr.h>
132 #import <wtf/HashTraits.h>
134 using namespace WebCore;
136 #if defined(__ppc__) || defined(__ppc64__)
137 #define PROCESSOR "PPC"
138 #elif defined(__i386__) || defined(__x86_64__)
139 #define PROCESSOR "Intel"
141 #error Unknown architecture
144 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
146 macro(alignJustified) \
149 macro(capitalizeWord) \
150 macro(centerSelectionInVisibleArea) \
151 macro(changeAttributes) \
152 macro(changeBaseWritingDirection) \
153 macro(changeBaseWritingDirectionToLTR) \
154 macro(changeBaseWritingDirectionToRTL) \
156 macro(changeDocumentBackgroundColor) \
158 macro(changeSpelling) \
159 macro(checkSpelling) \
165 macro(deleteBackward) \
166 macro(deleteBackwardByDecomposingPreviousCharacter) \
167 macro(deleteForward) \
168 macro(deleteToBeginningOfLine) \
169 macro(deleteToBeginningOfParagraph) \
170 macro(deleteToEndOfLine) \
171 macro(deleteToEndOfParagraph) \
172 macro(deleteToMark) \
173 macro(deleteWordBackward) \
174 macro(deleteWordForward) \
175 macro(ignoreSpelling) \
177 macro(insertBacktab) \
178 macro(insertLineBreak) \
179 macro(insertNewline) \
180 macro(insertNewlineIgnoringFieldEditor) \
181 macro(insertParagraphSeparator) \
183 macro(insertTabIgnoringFieldEditor) \
184 macro(lowercaseWord) \
185 macro(moveBackward) \
186 macro(moveBackwardAndModifySelection) \
188 macro(moveDownAndModifySelection) \
190 macro(moveForwardAndModifySelection) \
192 macro(moveLeftAndModifySelection) \
193 macro(moveParagraphBackwardAndModifySelection) \
194 macro(moveParagraphForwardAndModifySelection) \
196 macro(moveRightAndModifySelection) \
197 macro(moveToBeginningOfDocument) \
198 macro(moveToBeginningOfDocumentAndModifySelection) \
199 macro(moveToBeginningOfLine) \
200 macro(moveToBeginningOfLineAndModifySelection) \
201 macro(moveToBeginningOfParagraph) \
202 macro(moveToBeginningOfParagraphAndModifySelection) \
203 macro(moveToBeginningOfSentence) \
204 macro(moveToBeginningOfSentenceAndModifySelection) \
205 macro(moveToEndOfDocument) \
206 macro(moveToEndOfDocumentAndModifySelection) \
207 macro(moveToEndOfLine) \
208 macro(moveToEndOfLineAndModifySelection) \
209 macro(moveToEndOfParagraph) \
210 macro(moveToEndOfParagraphAndModifySelection) \
211 macro(moveToEndOfSentence) \
212 macro(moveToEndOfSentenceAndModifySelection) \
214 macro(moveUpAndModifySelection) \
215 macro(moveWordBackward) \
216 macro(moveWordBackwardAndModifySelection) \
217 macro(moveWordForward) \
218 macro(moveWordForwardAndModifySelection) \
219 macro(moveWordLeft) \
220 macro(moveWordLeftAndModifySelection) \
221 macro(moveWordRight) \
222 macro(moveWordRightAndModifySelection) \
225 macro(pageDownAndModifySelection) \
227 macro(pageUpAndModifySelection) \
229 macro(pasteAsPlainText) \
230 macro(pasteAsRichText) \
232 macro(performFindPanelAction) \
233 macro(scrollLineDown) \
234 macro(scrollLineUp) \
235 macro(scrollPageDown) \
236 macro(scrollPageUp) \
237 macro(scrollToBeginningOfDocument) \
238 macro(scrollToEndOfDocument) \
241 macro(selectParagraph) \
242 macro(selectSentence) \
243 macro(selectToMark) \
246 macro(showGuessPanel) \
247 macro(startSpeaking) \
248 macro(stopSpeaking) \
251 macro(swapWithMark) \
252 macro(takeFindStringFromSelection) \
253 macro(toggleBaseWritingDirection) \
257 macro(uppercaseWord) \
259 macro(yankAndSelect) \
261 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
262 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
264 static BOOL s_didSetCacheModel;
265 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
267 static BOOL applicationIsTerminating;
268 static int pluginDatabaseClientCount = 0;
270 @interface NSSpellChecker (AppKitSecretsIKnow)
271 - (void)_preflightChosenSpellServer;
274 @interface NSView (AppKitSecretsIKnow)
275 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
276 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
277 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
280 @interface NSWindow (AppKitSecretsIKnow)
281 - (id)_oldFirstResponderBeforeBecoming;
284 @interface NSObject (ValidateWithoutDelegate)
285 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
288 @interface _WebSafeForwarder : NSObject
290 id target; // Non-retained. Don't retain delegates.
292 BOOL catchExceptions;
294 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget catchExceptions:(BOOL)catchExceptions;
297 @interface WebViewPrivate : NSObject
303 id UIDelegateForwarder;
304 id resourceProgressDelegate;
307 id policyDelegateForwarder;
308 id frameLoadDelegate;
309 id frameLoadDelegateForwarder;
310 id <WebFormDelegate> formDelegate;
312 id editingDelegateForwarder;
313 id scriptDebugDelegate;
314 id scriptDebugDelegateForwarder;
316 WebInspector *inspector;
320 float textSizeMultiplier;
322 NSString *applicationNameForUserAgent;
324 BOOL userAgentOverridden;
326 WebPreferences *preferences;
327 BOOL useSiteSpecificSpoofing;
329 NSWindow *hostWindow;
331 int programmaticFocusCount;
333 WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
334 WebFrameLoadDelegateImplementationCache frameLoadDelegateImplementations;
336 void *observationInfo;
339 BOOL shouldCloseWithWindow;
340 BOOL mainFrameDocumentReady;
341 BOOL drawsBackground;
343 BOOL tabKeyCyclesThroughElementsChanged;
344 BOOL becomingFirstResponder;
345 BOOL becomingFirstResponderFromOutside;
346 BOOL hoverFeedbackSuspended;
348 BOOL catchesDelegateExceptions;
350 NSColor *backgroundColor;
352 NSString *mediaStyle;
354 BOOL hasSpellCheckerDocumentTag;
355 NSInteger spellCheckerDocumentTag;
357 BOOL smartInsertDeleteEnabled;
359 BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
360 BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
361 BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
362 BOOL dashboardBehaviorAllowWheelScrolling;
364 // WebKit has both a global plug-in database and a separate, per WebView plug-in database. Dashboard uses the per WebView database.
365 WebPluginDatabase *pluginDatabase;
367 HashMap<unsigned long, RetainPtr<id> >* identifierMap;
371 @interface WebView (WebFileInternal)
372 - (WebFrame *)_selectedOrMainFrame;
373 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame;
375 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
376 - (WebFrame *)_focusedFrame;
377 + (void)_preflightSpellChecker;
378 - (BOOL)_continuousCheckingAllowed;
379 - (NSResponder *)_responderForResponderOperations;
380 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor;
381 - (void)_notifyTextSizeMultiplierChanged;
384 @interface WebView (WebCallDelegateFunctions)
387 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
388 NSString *WebElementFrameKey = @"WebElementFrame";
389 NSString *WebElementImageKey = @"WebElementImage";
390 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
391 NSString *WebElementImageRectKey = @"WebElementImageRect";
392 NSString *WebElementImageURLKey = @"WebElementImageURL";
393 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
394 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
395 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
396 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
397 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
398 NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
399 NSString *WebElementTitleKey = @"WebElementTitle";
400 NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
401 NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
403 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
404 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
405 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
407 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
408 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
409 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
410 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
411 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
413 enum { WebViewVersion = 4 };
415 #define timedLayoutSize 4096
417 static NSMutableSet *schemesWithRepresentationsSet;
419 NSString *_WebCanGoBackKey = @"canGoBack";
420 NSString *_WebCanGoForwardKey = @"canGoForward";
421 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
422 NSString *_WebIsLoadingKey = @"isLoading";
423 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
424 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
425 NSString *_WebMainFrameURLKey = @"mainFrameURL";
426 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
428 @interface WebProgressItem : NSObject
431 long long bytesReceived;
432 long long estimatedLength;
436 @implementation WebProgressItem
439 static BOOL continuousSpellCheckingEnabled;
440 #ifndef BUILDING_ON_TIGER
441 static BOOL grammarCheckingEnabled;
444 @implementation WebViewPrivate
446 #ifndef BUILDING_ON_TIGER
449 WebCoreObjCFinalizeOnMainThread(self);
459 textSizeMultiplier = 1;
460 dashboardBehaviorAllowWheelScrolling = YES;
461 shouldCloseWithWindow = objc_collecting_enabled();
462 continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
464 #ifndef BUILDING_ON_TIGER
465 grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
467 userAgent = new String;
471 identifierMap = new HashMap<unsigned long, RetainPtr<id> >();
472 pluginDatabaseClientCount++;
480 ASSERT(!preferences);
483 delete identifierMap;
485 [applicationNameForUserAgent release];
486 [backgroundColor release];
489 [hostWindow release];
491 [policyDelegateForwarder release];
492 [UIDelegateForwarder release];
493 [frameLoadDelegateForwarder release];
494 [editingDelegateForwarder release];
495 [scriptDebugDelegateForwarder release];
497 [mediaStyle release];
504 ASSERT_MAIN_THREAD();
507 delete identifierMap;
514 @implementation WebView (AllWebViews)
516 static CFSetCallBacks NonRetainingSetCallbacks = {
525 static CFMutableSetRef allWebViewsSet;
527 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
532 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
535 - (void)_removeFromAllWebViewsSet
538 CFSetRemoveValue(allWebViewsSet, self);
541 - (void)_addToAllWebViewsSet
544 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
546 CFSetSetValue(allWebViewsSet, self);
551 @implementation WebView (WebPrivate)
553 #ifdef DEBUG_WIDGET_DRAWING
554 static bool debugWidget = true;
555 - (void)drawRect:(NSRect)rect
557 [[NSColor blueColor] set];
560 NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
563 while (debugWidget) {
568 NSLog (@"%s: rect: (%0.f,%0.f) %0.f %0.f, htmlViewRect: (%0.f,%0.f) %0.f %0.f\n",
569 __PRETTY_FUNCTION__, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
570 htmlViewRect.origin.x, htmlViewRect.origin.y, htmlViewRect.size.width, htmlViewRect.size.height
573 [super drawRect:rect];
577 + (BOOL)_scriptDebuggerEnabled
580 return [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitScriptDebuggerEnabled"];
582 return YES; // always enable in debug builds
586 + (NSArray *)_supportedMIMETypes
588 // Load the plug-in DB allowing plug-ins to install types.
589 [WebPluginDatabase sharedDatabase];
590 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
593 + (NSArray *)_supportedFileExtensions
595 NSMutableSet *extensions = [[NSMutableSet alloc] init];
596 NSArray *MIMETypes = [self _supportedMIMETypes];
597 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
599 while ((MIMEType = [enumerator nextObject]) != nil) {
600 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
601 if (extensionsForType) {
602 [extensions addObjectsFromArray:extensionsForType];
605 NSArray *uniqueExtensions = [extensions allObjects];
606 [extensions release];
607 return uniqueExtensions;
610 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
612 MIMEType = [MIMEType lowercaseString];
613 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
614 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
616 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
617 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
618 // Load the plug-in DB allowing plug-ins to install types.
619 [WebPluginDatabase sharedDatabase];
621 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
622 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
623 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
626 if (viewClass && repClass) {
627 // Special-case WebHTMLView for text types that shouldn't be shown.
628 if (viewClass == [WebHTMLView class] &&
629 repClass == [WebHTMLRepresentation class] &&
630 [[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType]) {
643 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
645 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType])
648 if (_private->pluginDatabase) {
649 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
652 *vClass = [WebHTMLView class];
654 *rClass = [WebHTMLRepresentation class];
662 + (void)_setAlwaysUseATSU:(BOOL)f
664 WebCoreSetAlwaysUseATSU(f);
667 + (BOOL)canShowFile:(NSString *)path
669 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
672 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
674 return WKGetPreferredExtensionForMIMEType(type);
679 if (!_private || _private->closed)
686 if (!_private || _private->closed)
689 FrameLoader* mainFrameLoader = [[self mainFrame] _frameLoader];
691 mainFrameLoader->detachFromParent();
693 [self _removeFromAllWebViewsSet];
694 [self setGroupName:nil];
695 [self setHostWindow:nil];
697 [self setDownloadDelegate:nil];
698 [self setEditingDelegate:nil];
699 [self setFrameLoadDelegate:nil];
700 [self setPolicyDelegate:nil];
701 [self setResourceLoadDelegate:nil];
702 [self setScriptDebugDelegate:nil];
703 [self setUIDelegate:nil];
705 [_private->inspector webViewClosed];
707 // setHostWindow:nil must be called before this value is set (see 5408186)
708 _private->closed = YES;
710 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
711 [self removeDragCaret];
713 // Deleteing the WebCore::Page will clear the page cache so we call destroy on
714 // all the plug-ins in the page cache to break any retain cycles.
715 // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
716 delete _private->page;
719 if (_private->hasSpellCheckerDocumentTag) {
720 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
721 _private->hasSpellCheckerDocumentTag = NO;
724 [[NSNotificationCenter defaultCenter] removeObserver:self];
726 [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
728 WebPreferences *preferences = _private->preferences;
729 _private->preferences = nil;
730 [preferences didRemoveFromWebView];
731 [preferences release];
733 pluginDatabaseClientCount--;
735 // Make sure to close both sets of plug-ins databases because plug-ins need an opportunity to clean up files, etc.
737 // Unload the WebView local plug-in database.
738 if (_private->pluginDatabase) {
739 [_private->pluginDatabase close];
740 [_private->pluginDatabase release];
741 _private->pluginDatabase = nil;
744 // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
745 if (!pluginDatabaseClientCount && applicationIsTerminating)
746 [WebPluginDatabase closeSharedDatabase];
749 + (NSString *)_MIMETypeForFile:(NSString *)path
751 NSString *extension = [path pathExtension];
752 NSString *MIMEType = nil;
754 // Get the MIME type from the extension.
755 if ([extension length] != 0) {
756 MIMEType = WKGetMIMETypeForExtension(extension);
759 // If we can't get a known MIME type from the extension, sniff.
760 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
761 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
762 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
764 if ([data length] != 0) {
765 MIMEType = [data _webkit_guessedMIMEType];
767 if ([MIMEType length] == 0) {
768 MIMEType = @"application/octet-stream";
775 - (WebDownload *)_downloadURL:(NSURL *)URL
779 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
780 WebDownload *download = [WebDownload _downloadWithRequest:request
781 delegate:_private->downloadDelegate
788 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
790 NSDictionary *features = [[NSDictionary alloc] init];
791 WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
792 createWebViewWithRequest:nil
793 windowFeatures:features];
795 if (!newWindowWebView)
798 CallUIDelegate(newWindowWebView, @selector(webViewShow:));
799 return newWindowWebView;
802 - (WebInspector *)inspector
804 if (!_private->inspector)
805 _private->inspector = [[WebInspector alloc] initWithWebView:self];
806 return _private->inspector;
809 - (WebCore::Page*)page
811 return _private->page;
814 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
816 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
818 NSArray *menuItems = CallUIDelegate(self, @selector(webView:contextMenuItemsForElement:defaultMenuItems:), element, defaultMenuItems);
822 unsigned count = [menuItems count];
826 NSMenu *menu = [[NSMenu alloc] init];
827 for (unsigned i = 0; i < count; i++)
828 [menu addItem:[menuItems objectAtIndex:i]];
830 return [menu autorelease];
833 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
835 // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
836 // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
837 // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
840 CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
843 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
848 if (!otherView->_private->page)
851 // It turns out the right combination of behavior is done with the back/forward load
852 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
853 // in the back forward list, and go to the current one.
855 BackForwardList* backForwardList = _private->page->backForwardList();
856 ASSERT(!backForwardList->currentItem()); // destination list should be empty
858 BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
859 if (!otherBackForwardList->currentItem())
860 return; // empty back forward list, bail
862 HistoryItem* newItemToGoTo = 0;
864 int lastItemIndex = otherBackForwardList->forwardListCount();
865 for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
867 // If this item is showing , save away its current scroll and form state,
868 // since that might have changed since loading and it is normally not saved
869 // until we leave that page.
870 otherView->_private->page->mainFrame()->loader()->saveDocumentAndScrollState();
872 RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
874 newItemToGoTo = newItem.get();
875 backForwardList->addItem(newItem.release());
878 ASSERT(newItemToGoTo);
879 _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
882 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
884 _private->formDelegate = delegate;
887 - (id<WebFormDelegate>)_formDelegate
889 return _private->formDelegate;
892 - (BOOL)_needsAdobeFrameReloadingQuirk
894 static BOOL checked = NO;
895 static BOOL needsQuirk = NO;
900 needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
901 || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
902 || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
903 || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
904 || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
905 || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
906 || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
907 || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
908 || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
909 || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
915 - (BOOL)_needsKeyboardEventDisambiguationQuirks
917 static BOOL checked = NO;
918 static BOOL needsQuirks = NO;
923 needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH)
924 && ![[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"];
930 - (BOOL)_needsXcodeVisibilityQuirk
932 static BOOL checked = NO;
933 static BOOL needsQuirk = NO;
938 needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_XCODE_QUIRK)
939 && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Xcode"];
945 - (void)_preferencesChangedNotification:(NSNotification *)notification
947 WebPreferences *preferences = (WebPreferences *)[notification object];
948 ASSERT(preferences == [self preferences]);
950 if (!_private->userAgentOverridden)
951 *_private->userAgent = String();
953 // Cache this value so we don't have to read NSUserDefaults on each page load
954 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
956 // Update corresponding WebCore Settings object.
960 Settings* settings = _private->page->settings();
962 settings->setCursiveFontFamily([preferences cursiveFontFamily]);
963 settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
964 settings->setDefaultFontSize([preferences defaultFontSize]);
965 settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
966 settings->setFantasyFontFamily([preferences fantasyFontFamily]);
967 settings->setFixedFontFamily([preferences fixedFontFamily]);
968 settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
969 settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
970 settings->setJavaEnabled([preferences isJavaEnabled]);
971 settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
972 settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
973 settings->setMinimumFontSize([preferences minimumFontSize]);
974 settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
975 settings->setPluginsEnabled([preferences arePlugInsEnabled]);
976 settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
977 settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
978 settings->setSerifFontFamily([preferences serifFontFamily]);
979 settings->setStandardFontFamily([preferences standardFontFamily]);
980 settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
981 settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
982 settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
983 settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
984 settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
985 settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
986 settings->setUsesPageCache([self usesPageCache]);
987 settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
988 settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
989 settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
990 if ([preferences userStyleSheetEnabled]) {
991 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
992 settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
994 settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
995 settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
996 settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
997 settings->setNeedsXcodeVisibilityQuirk([self _needsXcodeVisibilityQuirk]);
1000 static inline IMP getMethod(id o, SEL s)
1002 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1005 - (void)_cacheResourceLoadDelegateImplementations
1007 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1008 id delegate = _private->resourceProgressDelegate;
1011 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1015 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1016 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1017 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1018 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1019 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1020 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1021 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1022 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1023 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1024 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1025 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1028 WebResourceDelegateImplementationCache* WebViewGetResourceLoadDelegateImplementations(WebView *webView)
1030 static WebResourceDelegateImplementationCache empty;
1033 return &webView->_private->resourceLoadDelegateImplementations;
1036 - (void)_cacheFrameLoadDelegateImplementations
1038 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1039 id delegate = _private->frameLoadDelegate;
1042 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1046 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1047 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1048 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1049 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1050 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1051 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1052 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1053 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1054 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1055 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1056 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1057 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1058 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1059 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1060 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1061 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1062 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1065 WebFrameLoadDelegateImplementationCache* WebViewGetFrameLoadDelegateImplementations(WebView *webView)
1067 static WebFrameLoadDelegateImplementationCache empty;
1070 return &webView->_private->frameLoadDelegateImplementations;
1073 - (id)_policyDelegateForwarder
1075 if (!_private->policyDelegateForwarder)
1076 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1077 return _private->policyDelegateForwarder;
1080 - (id)_UIDelegateForwarder
1082 if (!_private->UIDelegateForwarder)
1083 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1084 return _private->UIDelegateForwarder;
1087 - (id)_editingDelegateForwarder
1089 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1090 // Not sure if that is a bug or not.
1094 if (!_private->editingDelegateForwarder)
1095 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1096 return _private->editingDelegateForwarder;
1099 - (id)_scriptDebugDelegateForwarder
1101 if (!_private->scriptDebugDelegateForwarder)
1102 _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->scriptDebugDelegate defaultTarget:[WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] catchExceptions:_private->catchesDelegateExceptions];
1103 return _private->scriptDebugDelegateForwarder;
1106 - (void)_closeWindow
1108 [[self _UIDelegateForwarder] webViewClose:self];
1111 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
1113 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1114 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1116 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1117 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1118 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1119 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1122 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
1124 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1125 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1127 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1128 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1129 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1130 if ([viewClass class] == [WebHTMLView class])
1131 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1133 // This is used to make _representationExistsForURLScheme faster.
1134 // Without this set, we'd have to create the MIME type each time.
1135 if (schemesWithRepresentationsSet == nil) {
1136 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1138 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1141 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1143 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1146 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1148 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1151 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1153 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed
1157 if ([NSURLConnection canHandleRequest:request])
1160 NSString *scheme = [[request URL] scheme];
1162 if ([self _representationExistsForURLScheme:scheme])
1165 return ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"]);
1168 + (NSString *)_decodeData:(NSData *)data
1170 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1171 RefPtr<TextResourceDecoder> decoder = new TextResourceDecoder("text/html"); // bookmark files are HTML
1172 String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1173 result += decoder->flush();
1177 - (void)_pushPerformingProgrammaticFocus
1179 _private->programmaticFocusCount++;
1182 - (void)_popPerformingProgrammaticFocus
1184 _private->programmaticFocusCount--;
1187 - (BOOL)_isPerformingProgrammaticFocus
1189 return _private->programmaticFocusCount != 0;
1192 - (void)_didChangeValueForKey: (NSString *)key
1194 LOG (Bindings, "calling didChangeValueForKey: %@", key);
1195 [self didChangeValueForKey: key];
1198 - (void)_willChangeValueForKey: (NSString *)key
1200 LOG (Bindings, "calling willChangeValueForKey: %@", key);
1201 [self willChangeValueForKey: key];
1204 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1205 static NSSet *manualNotifyKeys = nil;
1206 if (!manualNotifyKeys)
1207 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1208 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1209 if ([manualNotifyKeys containsObject:key])
1214 - (NSArray *)_declaredKeys {
1215 static NSArray *declaredKeys = nil;
1217 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1218 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1219 return declaredKeys;
1222 - (void)setObservationInfo:(void *)info
1224 _private->observationInfo = info;
1227 - (void *)observationInfo
1229 return _private->observationInfo;
1232 - (void)_willChangeBackForwardKeys
1234 [self _willChangeValueForKey: _WebCanGoBackKey];
1235 [self _willChangeValueForKey: _WebCanGoForwardKey];
1238 - (void)_didChangeBackForwardKeys
1240 [self _didChangeValueForKey: _WebCanGoBackKey];
1241 [self _didChangeValueForKey: _WebCanGoForwardKey];
1244 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1246 [self _willChangeBackForwardKeys];
1247 if (frame == [self mainFrame]){
1248 // Force an observer update by sending a will/did.
1249 [self _willChangeValueForKey: _WebIsLoadingKey];
1250 [self _didChangeValueForKey: _WebIsLoadingKey];
1252 [self _willChangeValueForKey: _WebMainFrameURLKey];
1255 [NSApp setWindowsNeedUpdate:YES];
1258 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1260 if (frame == [self mainFrame])
1261 [self _didChangeValueForKey: _WebMainFrameURLKey];
1262 [NSApp setWindowsNeedUpdate:YES];
1265 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1267 [self _didChangeBackForwardKeys];
1268 if (frame == [self mainFrame]){
1269 // Force an observer update by sending a will/did.
1270 [self _willChangeValueForKey: _WebIsLoadingKey];
1271 [self _didChangeValueForKey: _WebIsLoadingKey];
1273 [NSApp setWindowsNeedUpdate:YES];
1276 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1278 [self _didChangeBackForwardKeys];
1279 if (frame == [self mainFrame]){
1280 // Force an observer update by sending a will/did.
1281 [self _willChangeValueForKey: _WebIsLoadingKey];
1282 [self _didChangeValueForKey: _WebIsLoadingKey];
1284 [NSApp setWindowsNeedUpdate:YES];
1287 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1289 [self _didChangeBackForwardKeys];
1290 if (frame == [self mainFrame]){
1291 // Force an observer update by sending a will/did.
1292 [self _willChangeValueForKey: _WebIsLoadingKey];
1293 [self _didChangeValueForKey: _WebIsLoadingKey];
1295 [self _didChangeValueForKey: _WebMainFrameURLKey];
1297 [NSApp setWindowsNeedUpdate:YES];
1300 - (void)_reloadForPluginChanges
1302 [[self mainFrame] _reloadForPluginChanges];
1305 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1307 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1308 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1309 NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1311 return cachedResponse;
1314 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1316 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1317 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1318 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1320 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1321 title:[element objectForKey:WebElementImageAltStringKey]
1322 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1327 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1329 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1330 andTitle:[element objectForKey:WebElementLinkLabelKey]
1334 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1336 if (!_private->page)
1338 _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
1341 #define DASHBOARD_CONTROL_LABEL @"control"
1343 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1345 // Add scroller regions for NSScroller and KWQScrollBar
1346 int i, count = [views count];
1348 for (i = 0; i < count; i++) {
1349 NSView *aView = [views objectAtIndex:i];
1351 if ([aView isKindOfClass:[NSScroller class]] ||
1352 [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1353 NSRect bounds = [aView bounds];
1354 NSRect adjustedBounds;
1355 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1356 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1358 // AppKit has horrible hack of placing absent scrollers at -100,-100
1359 if (adjustedBounds.origin.y == -100)
1361 adjustedBounds.size = bounds.size;
1362 NSRect clip = [aView visibleRect];
1363 NSRect adjustedClip;
1364 adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1365 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1366 adjustedClip.size = clip.size;
1367 WebDashboardRegion *aRegion =
1368 [[[WebDashboardRegion alloc] initWithRect:adjustedBounds
1369 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1370 NSMutableArray *scrollerRegions;
1371 scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1372 if (!scrollerRegions) {
1373 scrollerRegions = [NSMutableArray array];
1374 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1376 [scrollerRegions addObject:aRegion];
1378 [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1382 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1384 [self _addScrollerDashboardRegions:regions from:[self subviews]];
1387 - (NSDictionary *)_dashboardRegions
1389 // Only return regions from main frame.
1390 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1393 NSMutableDictionary *regions = mainFrame->dashboardRegionsDictionary();
1394 [self _addScrollerDashboardRegions:regions];
1398 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
1400 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
1401 // specific support for the backward compatibility mode flag.
1402 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
1403 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
1406 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1407 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1410 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1411 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1414 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1415 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1418 case WebDashboardBehaviorAllowWheelScrolling: {
1419 _private->dashboardBehaviorAllowWheelScrolling = flag;
1422 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1424 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
1430 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1433 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1434 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1436 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1437 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1439 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1440 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1442 case WebDashboardBehaviorAllowWheelScrolling: {
1443 return _private->dashboardBehaviorAllowWheelScrolling;
1445 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1446 return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
1452 + (void)_setShouldUseFontSmoothing:(BOOL)f
1454 WebCoreSetShouldUseFontSmoothing(f);
1457 + (BOOL)_shouldUseFontSmoothing
1459 return WebCoreShouldUseFontSmoothing();
1462 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
1464 setUsesTestModeFocusRingColor(f);
1467 + (BOOL)_usesTestModeFocusRingColor
1469 return usesTestModeFocusRingColor();
1472 // This is only used by older versions of Safari and should be removed in a future release.
1473 + (NSString *)_minimumRequiredSafariBuildNumber
1478 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1480 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1482 [scrollview setVerticalScrollingMode:WebCoreScrollbarAlwaysOn andLock:YES];
1484 [scrollview setVerticalScrollingModeLocked:NO];
1485 [scrollview setVerticalScrollingMode:WebCoreScrollbarAuto];
1489 - (BOOL)alwaysShowVerticalScroller
1491 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1492 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == WebCoreScrollbarAlwaysOn;
1495 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1497 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1499 [scrollview setHorizontalScrollingMode:WebCoreScrollbarAlwaysOn andLock:YES];
1501 [scrollview setHorizontalScrollingModeLocked:NO];
1502 [scrollview setHorizontalScrollingMode:WebCoreScrollbarAuto];
1506 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1508 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1510 mainFrame->setProhibitsScrolling(prohibits);
1513 - (BOOL)alwaysShowHorizontalScroller
1515 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1516 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == WebCoreScrollbarAlwaysOn;
1519 - (void)_setInViewSourceMode:(BOOL)flag
1521 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1523 mainFrame->setInViewSourceMode(flag);
1526 - (BOOL)_inViewSourceMode
1528 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1529 return mainFrame && mainFrame->inViewSourceMode();
1532 - (void)_setUseFastImageScalingMode:(BOOL)flag
1534 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
1535 _private->page->setInLowQualityImageInterpolationMode(flag);
1536 [self setNeedsDisplay:YES];
1540 - (BOOL)_inFastImageScalingMode
1543 return _private->page->inLowQualityImageInterpolationMode();
1547 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1549 if (!_private->pluginDatabase)
1550 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1552 [_private->pluginDatabase setPlugInPaths:newPaths];
1553 [_private->pluginDatabase refresh];
1556 - (void)_attachScriptDebuggerToAllFrames
1558 for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1559 [kit(frame) _attachScriptDebugger];
1562 - (void)_detachScriptDebuggerFromAllFrames
1564 for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1565 [kit(frame) _detachScriptDebugger];
1568 - (void)setBackgroundColor:(NSColor *)backgroundColor
1570 if ([_private->backgroundColor isEqual:backgroundColor])
1573 id old = _private->backgroundColor;
1574 _private->backgroundColor = [backgroundColor retain];
1577 [[self mainFrame] _updateBackground];
1580 - (NSColor *)backgroundColor
1582 return _private->backgroundColor;
1585 - (BOOL)defersCallbacks
1587 if (!_private->page)
1589 return _private->page->defersLoading();
1592 - (void)setDefersCallbacks:(BOOL)defer
1594 if (!_private->page)
1596 return _private->page->setDefersLoading(defer);
1599 // For backwards compatibility with the WebBackForwardList API, we honor both
1600 // a per-WebView and a per-preferences setting for whether to use the page cache.
1602 - (BOOL)usesPageCache
1604 return _private->usesPageCache && [[self preferences] usesPageCache];
1607 - (void)setUsesPageCache:(BOOL)usesPageCache
1609 _private->usesPageCache = usesPageCache;
1611 // Post a notification so the WebCore settings update.
1612 [[self preferences] _postPreferencesChangesNotification];
1615 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1617 NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window];
1618 [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window];
1621 - (void)_clearUndoRedoOperations
1623 if (!_private->page)
1625 _private->page->clearUndoRedoOperations();
1628 - (void)_setCatchesDelegateExceptions:(BOOL)f
1630 _private->catchesDelegateExceptions = f;
1633 - (BOOL)_catchesDelegateExceptions
1635 return _private->catchesDelegateExceptions;
1638 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
1640 Frame* coreFrame = [[[self mainFrame] _bridge] _frame];
1643 coreFrame->editor()->command(name).execute(value);
1648 @implementation _WebSafeForwarder
1650 // Used to send messages to delegates that implement informal protocols.
1652 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
1654 self = [super init];
1657 target = t; // Non retained.
1659 catchExceptions = c;
1663 - (void)forwardInvocation:(NSInvocation *)invocation
1665 if ([target respondsToSelector:[invocation selector]]) {
1666 if (catchExceptions) {
1668 [invocation invokeWithTarget:target];
1669 } @catch(id exception) {
1670 ReportDiscardedDelegateException([invocation selector], exception);
1673 [invocation invokeWithTarget:target];
1677 if ([defaultTarget respondsToSelector:[invocation selector]])
1678 [invocation invokeWithTarget:defaultTarget];
1680 // Do nothing quietly if method not implemented.
1683 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1685 return [defaultTarget methodSignatureForSelector:aSelector];
1690 @implementation WebView
1694 static BOOL initialized = NO;
1699 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
1700 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedNotification object:nil];
1701 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];
1704 + (void)_applicationWillTerminate
1706 applicationIsTerminating = YES;
1707 if (!pluginDatabaseClientCount)
1708 [WebPluginDatabase closeSharedDatabase];
1711 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1713 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1716 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
1718 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
1720 return pluginPackage;
1722 if (_private->pluginDatabase)
1723 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
1728 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
1730 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
1732 return pluginPackage;
1734 if (_private->pluginDatabase)
1735 return [_private->pluginDatabase pluginForExtension:extension];
1740 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
1742 if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
1745 if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
1751 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1753 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1756 + (NSArray *)MIMETypesShownAsHTML
1758 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1759 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1761 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1763 while ((key = [enumerator nextObject])) {
1764 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1765 [array addObject:key];
1771 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1773 NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
1774 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1776 while ((key = [enumerator nextObject])) {
1777 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1778 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1781 int i, count = [MIMETypes count];
1782 for (i = 0; i < count; i++) {
1783 [WebView registerViewClass:[WebHTMLView class]
1784 representationClass:[WebHTMLRepresentation class]
1785 forMIMEType:[MIMETypes objectAtIndex:i]];
1787 [viewTypes release];
1790 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1792 return [pasteboard _web_bestURL];
1795 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1797 return [pasteboard stringForType:WebURLNamePboardType];
1800 + (void)registerURLSchemeAsLocal:(NSString *)protocol
1802 FrameLoader::registerURLSchemeAsLocal(protocol);
1805 - (void)_registerDraggedTypes
1807 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1808 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1809 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1810 [types addObjectsFromArray:URLTypes];
1811 [self registerForDraggedTypes:[types allObjects]];
1815 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1817 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1818 [standardPreferences willAddToWebView];
1820 _private->preferences = [standardPreferences retain];
1821 _private->catchesDelegateExceptions = YES;
1822 _private->mainFrameDocumentReady = NO;
1823 _private->drawsBackground = YES;
1824 _private->smartInsertDeleteEnabled = YES;
1825 _private->backgroundColor = [[NSColor whiteColor] retain];
1827 NSRect f = [self frame];
1828 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1829 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1830 [self addSubview:frameView];
1831 [frameView release];
1833 WebKitInitializeLoggingChannelsIfNecessary();
1834 WebCore::InitializeLoggingChannelsIfNecessary();
1835 [WebHistoryItem initWindowWatcherIfNecessary];
1836 WebKitInitializeDatabasesIfNecessary();
1838 _private->page = new Page(new WebChromeClient(self), new WebContextMenuClient(self), new WebEditorClient(self), new WebDragClient(self), new WebInspectorClient(self));
1839 [[[WebFrameBridge alloc] initMainFrameWithPage:_private->page frameName:frameName frameView:frameView] release];
1841 [self _addToAllWebViewsSet];
1842 [self setGroupName:groupName];
1844 // If there's already a next key view (e.g., from a nib), wire it up to our
1845 // contained frame view. In any case, wire our next key view up to the our
1846 // contained frame view. This works together with our becomeFirstResponder
1847 // and setNextKeyView overrides.
1848 NSView *nextKeyView = [self nextKeyView];
1849 if (nextKeyView != nil && nextKeyView != frameView) {
1850 [frameView setNextKeyView:nextKeyView];
1852 [super setNextKeyView:frameView];
1856 [self _registerDraggedTypes];
1858 // initialize WebScriptDebugServer here so listeners can register before any pages are loaded.
1859 if ([WebView _scriptDebuggerEnabled])
1860 [WebScriptDebugServer sharedScriptDebugServer];
1862 WebPreferences *prefs = [self preferences];
1863 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1864 name:WebPreferencesChangedNotification object:prefs];
1866 // Post a notification so the WebCore settings update.
1867 [[self preferences] _postPreferencesChangesNotification];
1869 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION))
1870 FrameLoader::setRestrictAccessToLocal(false);
1873 - (id)initWithFrame:(NSRect)f
1875 return [self initWithFrame:f frameName:nil groupName:nil];
1878 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1880 self = [super initWithFrame:f];
1884 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1885 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1886 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1887 // need for Safari to unset it to prevent it from being passed to applications it launches.
1888 // Unsetting it when a WebView is first created is as good a place as any.
1889 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1890 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1891 unsetenv("DYLD_FRAMEWORK_PATH");
1892 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1896 _private = [[WebViewPrivate alloc] init];
1897 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1898 [self setMaintainsBackForwardList: YES];
1902 - (id)initWithCoder:(NSCoder *)decoder
1904 WebView *result = nil;
1907 NSString *frameName;
1908 NSString *groupName;
1909 WebPreferences *preferences;
1910 BOOL useBackForwardList = NO;
1911 BOOL allowsUndo = YES;
1913 result = [super initWithCoder:decoder];
1914 result->_private = [[WebViewPrivate alloc] init];
1916 // We don't want any of the archived subviews. The subviews will always
1917 // be created in _commonInitializationFrameName:groupName:.
1918 [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1920 if ([decoder allowsKeyedCoding]) {
1921 frameName = [decoder decodeObjectForKey:@"FrameName"];
1922 groupName = [decoder decodeObjectForKey:@"GroupName"];
1923 preferences = [decoder decodeObjectForKey:@"Preferences"];
1924 useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1925 if ([decoder containsValueForKey:@"AllowsUndo"])
1926 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
1929 [decoder decodeValueOfObjCType:@encode(int) at:&version];
1930 frameName = [decoder decodeObject];
1931 groupName = [decoder decodeObject];
1932 preferences = [decoder decodeObject];
1934 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1935 // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
1936 // version 3 NIBs that have this field encoded, we still need to read it in.
1938 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
1941 if (![frameName isKindOfClass:[NSString class]])
1943 if (![groupName isKindOfClass:[NSString class]])
1945 if (![preferences isKindOfClass:[WebPreferences class]])
1948 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1949 [result _commonInitializationWithFrameName:frameName groupName:groupName];
1950 [result page]->backForwardList()->setEnabled(useBackForwardList);
1951 result->_private->allowsUndo = allowsUndo;
1953 [result setPreferences:preferences];
1954 } @catch (NSException *localException) {
1962 - (void)encodeWithCoder:(NSCoder *)encoder
1964 // Set asside the subviews before we archive. We don't want to archive any subviews.
1965 // The subviews will always be created in _commonInitializationFrameName:groupName:.
1966 id originalSubviews = _subviews;
1969 [super encodeWithCoder:encoder];
1971 // Restore the subviews we set aside.
1972 _subviews = originalSubviews;
1974 BOOL useBackForwardList = _private->page && _private->page->backForwardList()->enabled();
1975 if ([encoder allowsKeyedCoding]) {
1976 [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
1977 [encoder encodeObject:[self groupName] forKey:@"GroupName"];
1978 [encoder encodeObject:[self preferences] forKey:@"Preferences"];
1979 [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
1980 [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
1982 int version = WebViewVersion;
1983 [encoder encodeValueOfObjCType:@encode(int) at:&version];
1984 [encoder encodeObject:[[self mainFrame] name]];
1985 [encoder encodeObject:[self groupName]];
1986 [encoder encodeObject:[self preferences]];
1987 [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
1988 // DO NOT encode any new fields here, doing so will break older WebKit releases.
1991 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
1996 // call close to ensure we tear-down completely
1997 // this maintains our old behavior for existing applications
2003 // [super dealloc] can end up dispatching against _private (3466082)
2011 ASSERT(_private->closed);
2023 - (void)setShouldCloseWithWindow:(BOOL)close
2025 _private->shouldCloseWithWindow = close;
2028 - (BOOL)shouldCloseWithWindow
2030 return _private->shouldCloseWithWindow;
2033 - (void)viewWillMoveToWindow:(NSWindow *)window
2035 // Don't do anything if we aren't initialized. This happens when decoding a WebView.
2040 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
2043 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
2045 // Ensure that we will receive the events that WebHTMLView (at least) needs. It's expensive enough
2046 // that we don't want to call it over and over.
2047 [window setAcceptsMouseMovedEvents:YES];
2048 WKSetNSWindowShouldPostEventNotifications(window, YES);
2052 - (void)_windowWillClose:(NSNotification *)notification
2054 if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
2058 - (void)setPreferences:(WebPreferences *)prefs
2061 prefs = [WebPreferences standardPreferences];
2063 if (_private->preferences == prefs)
2066 [prefs willAddToWebView];
2068 WebPreferences *oldPrefs = _private->preferences;
2070 [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
2071 [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
2073 _private->preferences = [prefs retain];
2075 // After registering for the notification, post it so the WebCore settings update.
2076 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
2077 name:WebPreferencesChangedNotification object:[self preferences]];
2078 [[self preferences] _postPreferencesChangesNotification];
2080 [oldPrefs didRemoveFromWebView];
2084 - (WebPreferences *)preferences
2086 return _private->preferences;
2089 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
2091 if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
2092 WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
2093 [self setPreferences:prefs];
2098 - (NSString *)preferencesIdentifier
2100 return [[self preferences] identifier];
2104 - (void)setUIDelegate:delegate
2106 _private->UIDelegate = delegate;
2107 [_private->UIDelegateForwarder release];
2108 _private->UIDelegateForwarder = nil;
2113 return _private->UIDelegate;
2116 - (void)setResourceLoadDelegate: delegate
2118 _private->resourceProgressDelegate = delegate;
2119 [self _cacheResourceLoadDelegateImplementations];
2122 - resourceLoadDelegate
2124 return _private->resourceProgressDelegate;
2127 - (void)setDownloadDelegate: delegate
2129 _private->downloadDelegate = delegate;
2135 return _private->downloadDelegate;
2138 - (void)setPolicyDelegate:delegate
2140 _private->policyDelegate = delegate;
2141 [_private->policyDelegateForwarder release];
2142 _private->policyDelegateForwarder = nil;
2147 return _private->policyDelegate;
2150 - (void)setFrameLoadDelegate:delegate
2152 _private->frameLoadDelegate = delegate;
2153 [self _cacheFrameLoadDelegateImplementations];
2155 // If this delegate wants callbacks for icons, fire up the icon database.
2156 if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
2157 [WebIconDatabase sharedIconDatabase];
2162 return _private->frameLoadDelegate;
2165 - (WebFrame *)mainFrame
2167 // This can be called in initialization, before _private has been set up (3465613)
2170 if (!_private->page)
2172 return kit(_private->page->mainFrame());
2175 - (WebFrame *)selectedFrame
2177 // If the first responder is a view in our tree, we get the frame containing the first responder.
2178 // This is faster than searching the frame hierarchy, and will give us a result even in the case
2179 // where the focused frame doesn't actually contain a selection.
2180 WebFrame *focusedFrame = [self _focusedFrame];
2182 return focusedFrame;
2184 // If the first responder is outside of our view tree, we search for a frame containing a selection.
2185 // There should be at most only one of these.
2186 return [[self mainFrame] _findFrameWithSelection];
2189 - (WebBackForwardList *)backForwardList
2191 if (!_private->page)
2193 if (!_private->page->backForwardList()->enabled())
2195 return kit(_private->page->backForwardList());
2198 - (void)setMaintainsBackForwardList: (BOOL)flag
2200 if (!_private->page)
2202 _private->page->backForwardList()->setEnabled(flag);
2207 if (!_private->page)
2210 return _private->page->goBack();
2215 if (!_private->page)
2218 return _private->page->goForward();
2221 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
2223 if (!_private->page)
2226 _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
2230 - (void)setTextSizeMultiplier:(float)m
2232 // NOTE: This has no visible effect when viewing a PDF (see <rdar://problem/4737380>)
2233 if (_private->textSizeMultiplier == m)
2236 _private->textSizeMultiplier = m;
2237 [self _notifyTextSizeMultiplierChanged];
2240 - (float)textSizeMultiplier
2242 return _private->textSizeMultiplier;
2245 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
2247 NSString *name = [applicationName copy];
2248 [_private->applicationNameForUserAgent release];
2249 _private->applicationNameForUserAgent = name;
2250 if (!_private->userAgentOverridden)
2251 *_private->userAgent = String();
2254 - (NSString *)applicationNameForUserAgent
2256 return [[_private->applicationNameForUserAgent retain] autorelease];
2259 - (void)setCustomUserAgent:(NSString *)userAgentString
2261 *_private->userAgent = userAgentString;
2262 _private->userAgentOverridden = userAgentString != nil;
2265 - (NSString *)customUserAgent
2267 if (!_private->userAgentOverridden)
2269 return *_private->userAgent;
2272 - (void)setMediaStyle:(NSString *)mediaStyle
2274 if (_private->mediaStyle != mediaStyle) {
2275 [_private->mediaStyle release];
2276 _private->mediaStyle = [mediaStyle copy];
2280 - (NSString *)mediaStyle
2282 return _private->mediaStyle;
2285 - (BOOL)supportsTextEncoding
2287 id documentView = [[[self mainFrame] frameView] documentView];
2288 return [documentView conformsToProtocol:@protocol(WebDocumentText)]
2289 && [documentView supportsTextEncoding];
2292 - (void)setCustomTextEncodingName:(NSString *)encoding
2294 NSString *oldEncoding = [self customTextEncodingName];
2295 if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding])
2297 FrameLoader* mainFrameLoader = [[self mainFrame] _frameLoader];
2298 if (mainFrameLoader)
2299 mainFrameLoader->reloadAllowingStaleData(encoding);
2302 - (NSString *)_mainFrameOverrideEncoding
2304 WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
2305 if (dataSource == nil)
2306 dataSource = [[self mainFrame] _dataSource];
2307 if (dataSource == nil)
2309 return nsStringNilIfEmpty([dataSource _documentLoader]->overrideEncoding());
2312 - (NSString *)customTextEncodingName
2314 return [self _mainFrameOverrideEncoding];
2317 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
2319 // Return statements are only valid in a function but some applications pass in scripts
2320 // prefixed with return (<rdar://problems/5103720&4616860>) since older WebKit versions
2321 // silently ignored the return. If the application is linked against an earlier version
2322 // of WebKit we will strip the return so the script wont fail.
2323 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_JAVASCRIPT_RETURN_QUIRK)) {
2324 NSRange returnStringRange = [script rangeOfString:@"return "];
2325 if (returnStringRange.length && !returnStringRange.location)
2326 script = [script substringFromIndex:returnStringRange.location + returnStringRange.length];
2329 NSString *result = [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
2330 // The only way stringByEvaluatingJavaScriptFromString can return nil is if the frame was removed by the script
2331 // Since there's no way to get rid of the main frame, result will never ever be nil here.
2337 - (WebScriptObject *)windowScriptObject
2339 Frame* coreFrame = core([self mainFrame]);
2342 return coreFrame->windowScriptObject();
2345 // Get the appropriate user-agent string for a particular URL.
2346 - (NSString *)userAgentForURL:(NSURL *)url
2348 return [self _userAgentForURL:KURL([url absoluteURL])];
2351 - (void)setHostWindow:(NSWindow *)hostWindow
2353 if (!_private->closed && hostWindow != _private->hostWindow) {
2354 [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2355 if (_private->hostWindow)
2356 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
2358 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
2359 [_private->hostWindow release];
2360 _private->hostWindow = [hostWindow retain];
2361 [[self mainFrame] _viewDidMoveToHostWindow];
2365 - (NSWindow *)hostWindow
2367 return _private->hostWindow;
2370 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2372 return [[self _frameViewAtWindowPoint:point] documentView];
2375 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2377 WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2380 NSView <WebDocumentView> *documentView = [frameView documentView];
2381 if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2382 NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2383 return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2385 return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2388 - (NSDictionary *)elementAtPoint:(NSPoint)point
2390 return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2393 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2394 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination.
2395 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination.
2396 // Forward these calls to the document subview to make its scroll view scroll.
2397 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2399 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2400 [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2403 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2405 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2406 return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2409 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2411 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2412 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2413 IntPoint client([draggingInfo draggingLocation]);
2414 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2415 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2416 return core(self)->dragController()->dragEntered(&dragData);
2419 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2421 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2422 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2423 IntPoint client([draggingInfo draggingLocation]);
2424 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2425 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2426 return core(self)->dragController()->dragUpdated(&dragData);
2429 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2431 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2432 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2433 IntPoint client([draggingInfo draggingLocation]);
2434 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2435 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2436 core(self)->dragController()->dragExited(&dragData);
2439 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2444 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2446 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2447 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]]? (WebHTMLView*)view : nil);
2448 IntPoint client([draggingInfo draggingLocation]);
2449 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2450 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2451 return core(self)->dragController()->performDrag(&dragData);
2454 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2456 NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2457 if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2464 - (BOOL)acceptsFirstResponder
2466 return [[[self mainFrame] frameView] acceptsFirstResponder];
2469 - (BOOL)becomeFirstResponder
2471 if (_private->becomingFirstResponder) {
2472 // Fix for unrepro infinite recursion reported in radar 4448181. If we hit this assert on
2473 // a debug build, we should figure out what causes the problem and do a better fix.
2474 ASSERT_NOT_REACHED();
2478 // This works together with setNextKeyView to splice the WebView into
2479 // the key loop similar to the way NSScrollView does this. Note that
2480 // WebFrameView has very similar code.
2481 NSWindow *window = [self window];
2482 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2484 NSResponder *previousFirstResponder = [[self window] _oldFirstResponderBeforeBecoming];
2485 BOOL fromOutside = ![previousFirstResponder isKindOfClass:[NSView class]] || (![(NSView *)previousFirstResponder isDescendantOf:self] && previousFirstResponder != self);
2487 if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2488 NSView *previousValidKeyView = [self previousValidKeyView];
2489 if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2490 _private->becomingFirstResponder = YES;
2491 _private->becomingFirstResponderFromOutside = fromOutside;
2492 [window makeFirstResponder:previousValidKeyView];
2493 _private->becomingFirstResponderFromOutside = NO;
2494 _private->becomingFirstResponder = NO;
2501 if ([mainFrameView acceptsFirstResponder]) {
2502 _private->becomingFirstResponder = YES;
2503 _private->becomingFirstResponderFromOutside = fromOutside;
2504 [window makeFirstResponder:mainFrameView];
2505 _private->becomingFirstResponderFromOutside = NO;
2506 _private->becomingFirstResponder = NO;
2513 - (NSView *)_webcore_effectiveFirstResponder
2515 WebFrameView *frameView = [[self mainFrame] frameView];
2516 return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2519 - (void)setNextKeyView:(NSView *)aView
2521 // This works together with becomeFirstResponder to splice the WebView into
2522 // the key loop similar to the way NSScrollView does this. Note that
2523 // WebFrameView has very similar code.
2524 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2525 if (mainFrameView != nil) {
2526 [mainFrameView setNextKeyView:aView];
2528 [super setNextKeyView:aView];
2532 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2534 Frame* coreFrame = core(curr);
2536 ? coreFrame->tree()->traverseNextWithWrap(wrapFlag)
2537 : coreFrame->tree()->traversePreviousWithWrap(wrapFlag));
2540 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2542 return [self searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag startInSelection:NO];
2545 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2547 [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2548 [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2550 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2551 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2552 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2553 if ([viewClass class] == [WebHTMLView class])
2554 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2557 - (void)setGroupName:(NSString *)groupName
2559 if (!_private->page)
2561 _private->page->setGroupName(groupName);
2564 - (NSString *)groupName
2566 if (!_private->page)
2568 return _private->page->groupName();
2571 - (double)estimatedProgress
2573 if (!_private->page)
2576 return _private->page->progress()->estimatedProgress();
2579 - (NSArray *)pasteboardTypesForSelection
2581 NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2582 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2583 return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2585 return [NSArray array];
2588 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2590 WebFrame *frame = [self _selectedOrMainFrame];
2591 if (frame && [frame _hasSelection]) {
2592 NSView <WebDocumentView> *documentView = [[frame frameView] documentView];
2593 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)])
2594 [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2598 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2600 if ([element objectForKey:WebElementImageURLKey] != nil) {
2601 return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2602 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2603 return [NSPasteboard _web_writableTypesForURL];
2604 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2605 return [self pasteboardTypesForSelection];
2607 return [NSArray array];
2610 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2612 if ([element objectForKey:WebElementImageURLKey] != nil) {
2613 [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2614 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2615 [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2616 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2617 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2621 - (void)moveDragCaretToPoint:(NSPoint)point
2623 if (Page* page = core(self))
2624 page->dragController()->placeDragCaret(IntPoint([self convertPoint:point toView:nil]));
2627 - (void)removeDragCaret
2629 if (Page* page = core(self))
2630 page->dragController()->dragEnded();
2633 - (void)setMainFrameURL:(NSString *)URLString
2635 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2638 - (NSString *)mainFrameURL
2641 ds = [[self mainFrame] provisionalDataSource];
2643 ds = [[self mainFrame] _dataSource];
2644 return [[[ds request] URL] _web_originalDataAsString];
2649 LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2650 return [self _isLoading];
2653 - (NSString *)mainFrameTitle
2655 NSString *mainFrameTitle = [[[self mainFrame] _dataSource] pageTitle];
2656 return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2659 - (NSImage *)mainFrameIcon
2661 return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] _dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2664 - (DOMDocument *)mainFrameDocument
2666 // only return the actual value if the state we're in gives NSTreeController
2667 // enough time to release its observers on the old model
2668 if (_private->mainFrameDocumentReady)
2669 return [[self mainFrame] DOMDocument];
2673 - (void)setDrawsBackground:(BOOL)drawsBackground
2675 if (_private->drawsBackground == drawsBackground)
2677 _private->drawsBackground = drawsBackground;
2678 [[self mainFrame] _updateBackground];
2681 - (BOOL)drawsBackground
2683 return _private->drawsBackground;
2688 @implementation WebView (WebIBActions)
2690 - (IBAction)takeStringURLFrom: sender
2692 NSString *URLString = [sender stringValue];
2694 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2699 if (!_private->page)
2702 return !!_private->page->backForwardList()->backItem();
2705 - (BOOL)canGoForward
2707 if (!_private->page)
2710 return !!_private->page->backForwardList()->forwardItem();
2713 - (IBAction)goBack:(id)sender
2718 - (IBAction)goForward:(id)sender
2723 - (IBAction)stopLoading:(id)sender
2725 [[self mainFrame] stopLoading];
2728 - (IBAction)reload:(id)sender
2730 [[self mainFrame] reload];
2733 #define MinimumTextSizeMultiplier 0.5f
2734 #define MaximumTextSizeMultiplier 3.0f
2735 #define TextSizeMultiplierRatio 1.2f
2737 - (BOOL)canMakeTextSmaller
2739 BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2740 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2743 - (BOOL)canMakeTextLarger
2745 BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2746 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2749 - (IBAction)makeTextSmaller:(id)sender
2751 float newScale = _private->textSizeMultiplier / TextSizeMultiplierRatio;
2752 BOOL canShrinkMore = newScale > MinimumTextSizeMultiplier;
2753 [self _performTextSizingSelector:@selector(_makeTextSmaller:) withObject:sender onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:newScale];
2756 - (IBAction)makeTextLarger:(id)sender
2758 float newScale = _private->textSizeMultiplier*TextSizeMultiplierRatio;
2759 BOOL canGrowMore = newScale < MaximumTextSizeMultiplier;
2760 [self _performTextSizingSelector:@selector(_makeTextLarger:) withObject:sender onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:newScale];
2763 - (IBAction)toggleSmartInsertDelete:(id)sender
2765 [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2768 - (IBAction)toggleContinuousSpellChecking:(id)sender
2770 [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2773 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2775 id responder = [self _responderForResponderOperations];
2776 if (responder != self && [responder respondsToSelector:[item action]]) {
2777 if ([responder respondsToSelector:@selector(validateUserInterfaceItemWithoutDelegate:)])
2778 return [responder validateUserInterfaceItemWithoutDelegate:item];
2779 if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)])
2780 return [responder validateUserInterfaceItem:item];
2786 - (BOOL)canMakeTextStandardSize
2788 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2789 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0.0f];
2792 - (IBAction)makeTextStandardSize:(id)sender
2794 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2795 [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0f];
2798 #define VALIDATE(name) \
2799 else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2801 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item
2803 SEL action = [item action];
2805 if (action == @selector(goBack:)) {
2806 return [self canGoBack];
2807 } else if (action == @selector(goForward:)) {
2808 return [self canGoForward];
2809 } else if (action == @selector(makeTextLarger:)) {
2810 return [self canMakeTextLarger];
2811 } else if (action == @selector(makeTextSmaller:)) {
2812 return [self canMakeTextSmaller];
2813 } else if (action == @selector(makeTextStandardSize:)) {
2814 return [self canMakeTextStandardSize];
2815 } else if (action == @selector(reload:)) {
2816 return [[self mainFrame] _dataSource] != nil;
2817 } else if (action == @selector(stopLoading:)) {
2818 return [self _isLoading];
2819 } else if (action == @selector(toggleContinuousSpellChecking:)) {
2820 BOOL checkMark = NO;
2822 if ([self _continuousCheckingAllowed]) {
2823 checkMark = [self isContinuousSpellCheckingEnabled];
2826 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2827 NSMenuItem *menuItem = (NSMenuItem *)item;
2828 [menuItem setState:checkMark ? NSOnState : NSOffState];
2831 #ifndef BUILDING_ON_TIGER
2832 } else if (action == @selector(toggleGrammarChecking:)) {
2833 BOOL checkMark = [self isGrammarCheckingEnabled];
2834 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2835 NSMenuItem *menuItem = (NSMenuItem *)item;
2836 [menuItem setState:checkMark ? NSOnState : NSOffState];
2841 FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2846 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2848 BOOL result = [self validateUserInterfaceItemWithoutDelegate:item];
2849 return CallUIDelegateReturningBoolean(result, self, @selector(webView:validateUserInterfaceItem:defaultValidation:), item, result);
2854 @implementation WebView (WebPendingPublic)
2856 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
2858 if (_private->closed)
2861 // Get the frame holding the selection, or start with the main frame
2862 WebFrame *startFrame = [self _selectedOrMainFrame];
2864 // Search the first frame, then all the other frames, in order
2865 NSView <WebDocumentSearching> *startSearchView = nil;
2866 WebFrame *frame = startFrame;
2868 WebFrame *nextFrame = incrementFrame(frame, forward, wrapFlag);
2870 BOOL onlyOneFrame = (frame == nextFrame);
2871 ASSERT(!onlyOneFrame || frame == startFrame);
2873 id <WebDocumentView> view = [[frame frameView] documentView];
2874 if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2875 NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2877 if (frame == startFrame)
2878 startSearchView = searchView;
2881 // In some cases we have to search some content twice; see comment later in this method.
2882 // We can avoid ever doing this in the common one-frame case by passing YES for wrapFlag
2883 // here, and then bailing out before we get to the code that would search again in the
2885 BOOL wrapOnThisPass = wrapFlag && onlyOneFrame;
2886 if ([searchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
2887 foundString = [(NSView <WebDocumentIncrementalSearching> *)searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass startInSelection:startInSelection];
2889 foundString = [searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass];
2892 if (frame != startFrame)
2893 [startFrame _clearSelection];
2894 [[self window] makeFirstResponder:searchView];
2902 } while (frame && frame != startFrame);
2904 // If there are multiple frames and wrapFlag is true and we've visited each one without finding a result, we still need to search in the
2905 // first-searched frame up to the selection. However, the API doesn't provide a way to search only up to a particular point. The only
2906 // way to make sure the entire frame is searched is to pass YES for the wrapFlag. When there are no matches, this will search again
2907 // some content that we already searched on the first pass. In the worst case, we could search the entire contents of this frame twice.
2908 // To fix this, we'd need to add a mechanism to specify a range in which to search.
2909 if (wrapFlag && startSearchView) {
2911 if ([startSearchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
2912 foundString = [(NSView <WebDocumentIncrementalSearching> *)startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES startInSelection:startInSelection];
2914 foundString = [startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES];
2916 [[self window] makeFirstResponder:startSearchView];
2923 - (void)setHoverFeedbackSuspended:(BOOL)newValue
2925 if (_private->hoverFeedbackSuspended == newValue)
2928 _private->hoverFeedbackSuspended = newValue;
2929 id <WebDocumentView> documentView = [[[self mainFrame] frameView] documentView];
2930 // FIXME: in a perfect world we'd do this in a general way that worked with any document view,
2931 // such as by calling a protocol method or using respondsToSelector or sending a notification.
2932 // But until there is any need for these more general solutions, we'll just hardwire it to work
2933 // with WebHTMLView.
2934 // Note that _hoverFeedbackSuspendedChanged needs to be called only on the main WebHTMLView, not
2935 // on each subframe separately.
2936 if ([documentView isKindOfClass:[WebHTMLView class]])
2937 [(WebHTMLView *)documentView _hoverFeedbackSuspendedChanged];
2940 - (BOOL)isHoverFeedbackSuspended
2942 return _private->hoverFeedbackSuspended;
2945 - (void)setMainFrameDocumentReady:(BOOL)mainFrameDocumentReady
2947 // by setting this to NO, calls to mainFrameDocument are forced to return nil
2948 // setting this to YES lets it return the actual DOMDocument value
2949 // we use this to tell NSTreeController to reset its observers and clear its state
2950 if (_private->mainFrameDocumentReady == mainFrameDocumentReady)
2952 [self _willChangeValueForKey:_WebMainFrameDocumentKey];
2953 _private->mainFrameDocumentReady = mainFrameDocumentReady;
2954 [self _didChangeValueForKey:_WebMainFrameDocumentKey];
2955 // this will cause observers to call mainFrameDocument where this flag will be checked
2958 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it
2959 // until the day comes when we're no longer supporting Mail on Tiger.
2960 - (WebFrame *)_frameForCurrentSelection
2962 return [self _selectedOrMainFrame];
2965 - (void)setTabKeyCyclesThroughElements:(BOOL)cyclesElements
2967 _private->tabKeyCyclesThroughElementsChanged = YES;
2969 _private->page->setTabKeyCyclesThroughElements(cyclesElements);
2972 - (BOOL)tabKeyCyclesThroughElements
2974 return _private->page && _private->page->tabKeyCyclesThroughElements();
2977 - (void)setScriptDebugDelegate:(id)delegate
2979 _private->scriptDebugDelegate = delegate;
2980 [_private->scriptDebugDelegateForwarder release];
2981 _private->scriptDebugDelegateForwarder = nil;
2983 [self _attachScriptDebuggerToAllFrames];
2985 [self _detachScriptDebuggerFromAllFrames];
2988 - (id)scriptDebugDelegate
2990 return _private->scriptDebugDelegate;
2995 Frame* coreFrame = core([self mainFrame]);
2998 return coreFrame->shouldClose();
3001 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
3003 return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
3006 - (BOOL)canMarkAllTextMatches
3008 WebFrame *frame = [self mainFrame];
3010 id <WebDocumentView> view = [[frame frameView] documentView];
3011 if (view && ![view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3014 frame = incrementFrame(frame, YES, NO);
3020 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
3022 WebFrame *frame = [self mainFrame];
3023 unsigned matchCount = 0;
3025 id <WebDocumentView> view = [[frame frameView] documentView];
3026 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3027 [(NSView <WebMultipleTextMatches>*)view setMarkedTextMatchesAreHighlighted:highlight];
3029 ASSERT(limit == 0 || matchCount < limit);
3030 matchCount += [(NSView <WebMultipleTextMatches>*)view markAllMatchesForText:string caseSensitive:caseFlag limit:limit == 0 ? 0 : limit - matchCount];
3032 // Stop looking if we've reached the limit. A limit of 0 means no limit.
3033 if (limit > 0 && matchCount >= limit)
3037 frame = incrementFrame(frame, YES, NO);
3043 - (void)unmarkAllTextMatches
3045 WebFrame *frame = [self mainFrame];
3047 id <WebDocumentView> view = [[frame frameView] documentView];
3048 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3049 [(NSView <WebMultipleTextMatches>*)view unmarkAllTextMatches];
3051 frame = incrementFrame(frame, YES, NO);
3055 - (NSArray *)rectsForTextMatches
3057 NSMutableArray *result = [NSMutableArray array];
3058 WebFrame *frame = [self mainFrame];
3060 id <WebDocumentView> view = [[frame frameView] documentView];
3061 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3062 NSView <WebMultipleTextMatches> *documentView = (NSView <WebMultipleTextMatches> *)view;
3063 NSRect documentViewVisibleRect = [documentView visibleRect];
3064 NSArray *originalRects = [documentView rectsForTextMatches];
3065 unsigned rectCount = [originalRects count];
3067 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3068 for (rectIndex = 0; rectIndex < rectCount; ++rectIndex) {
3069 NSRect r = [[originalRects objectAtIndex:rectIndex] rectValue];
3070 // Clip rect to document view's visible rect so rect is confined to subframe
3071 r = NSIntersectionRect(r, documentViewVisibleRect);
3072 if (NSIsEmptyRect(r))
3075 // Convert rect to our coordinate system
3076 r = [documentView convertRect:r toView:self];
3077 [result addObject:[NSValue valueWithRect:r]];
3078 if (rectIndex % 10 == 0) {
3080 pool = [[NSAutoreleasePool alloc] init];
3086 frame = incrementFrame(frame, YES, NO);
3092 - (void)scrollDOMRangeToVisible:(DOMRange *)range
3094 [[[range startContainer] _bridge] scrollDOMRangeToVisible:range];
3099 return _private->allowsUndo;
3102 - (void)setAllowsUndo:(BOOL)flag
3104 _private->allowsUndo = flag;
3109 @implementation WebView (WebViewPrintingPrivate)
3111 - (float)_headerHeight
3113 return CallUIDelegateReturningFloat(self, @selector(webViewHeaderHeight:));
3116 - (float)_footerHeight
3118 return CallUIDelegateReturningFloat(self, @selector(webViewFooterHeight:));
3121 - (void)_drawHeaderInRect:(NSRect)rect
3123 #ifdef DEBUG_HEADER_AND_FOOTER
3124 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3125 [currentContext saveGraphicsState];
3126 [[NSColor yellowColor] set];
3128 [currentContext restoreGraphicsState];
3131 SEL selector = @selector(webView:drawHeaderInRect:);
3132 if (![_private->UIDelegate respondsToSelector:selector])
3135 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3136 [currentContext saveGraphicsState];
3139 CallUIDelegate(self, selector, rect);
3141 [currentContext restoreGraphicsState];
3144 - (void)_drawFooterInRect:(NSRect)rect
3146 #ifdef DEBUG_HEADER_AND_FOOTER
3147 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3148 [currentContext saveGraphicsState];
3149 [[NSColor cyanColor] set];
3151 [currentContext restoreGraphicsState];
3154 SEL selector = @selector(webView:drawFooterInRect:);
3155 if (![_private->UIDelegate respondsToSelector:selector])
3158 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3159 [currentContext saveGraphicsState];
3162 CallUIDelegate(self, selector, rect);
3164 [currentContext restoreGraphicsState];
3167 - (void)_adjustPrintingMarginsForHeaderAndFooter
3169 NSPrintOperation *op = [NSPrintOperation currentOperation];
3170 NSPrintInfo *info = [op printInfo];
3171 NSMutableDictionary *infoDictionary = [info dictionary];
3173 // We need to modify the top and bottom margins in the NSPrintInfo to account for the space needed by the
3174 // header and footer. Because this method can be called more than once on the same NSPrintInfo (see 5038087),
3175 // we stash away the unmodified top and bottom margins the first time this method is called, and we read from
3176 // those stashed-away values on subsequent calls.
3177 float originalTopMargin;
3178 float originalBottomMargin;
3179 NSNumber *originalTopMarginNumber = [infoDictionary objectForKey:WebKitOriginalTopPrintingMarginKey];
3180 if (!originalTopMarginNumber) {
3181 ASSERT(![infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey]);
3182 originalTopMargin = [info topMargin];
3183 originalBottomMargin = [info bottomMargin];
3184 [infoDictionary setObject:[NSNumber numberWithFloat:originalTopMargin] forKey:WebKitOriginalTopPrintingMarginKey];
3185 [infoDictionary setObject:[NSNumber numberWithFloat:originalBottomMargin] forKey:WebKitOriginalBottomPrintingMarginKey];
3187 ASSERT([originalTopMarginNumber isKindOfClass:[NSNumber class]]);
3188 ASSERT([[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] isKindOfClass:[NSNumber class]]);
3189 originalTopMargin = [originalTopMarginNumber floatValue];
3190 originalBottomMargin = [[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] floatValue];
3193 float scale = [op _web_pageSetupScaleFactor];
3194 [info setTopMargin:originalTopMargin + [self _headerHeight] * scale];
3195 [info setBottomMargin:originalBottomMargin + [self _footerHeight] * scale];
3198 - (void)_drawHeaderAndFooter
3200 // The header and footer rect height scales with the page, but the width is always
3201 // all the way across the printed page (inset by printing margins).
3202 NSPrintOperation *op = [NSPrintOperation currentOperation];
3203 float scale = [op _web_pageSetupScaleFactor];
3204 NSPrintInfo *printInfo = [op printInfo];
3205 NSSize paperSize = [printInfo paperSize];
3206 float headerFooterLeft = [printInfo leftMargin]/scale;
3207 float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
3208 NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] ,
3209 headerFooterWidth, [self _footerHeight]);
3210 NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale,
3211 headerFooterWidth, [self _headerHeight]);
3213 [self _drawHeaderInRect:headerRect];
3214 [self _drawFooterInRect:footerRect];
3218 @implementation WebView (WebDebugBinding)
3220 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
3222 LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
3223 [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
3226 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
3228 LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
3229 [super removeObserver:anObserver forKeyPath:keyPath];
3234 //==========================================================================================
3237 @implementation WebView (WebViewCSS)
3239 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
3241 // FIXME: is this the best level for this conversion?
3242 if (pseudoElement == nil)
3243 pseudoElement = @"";
3245 return [[element ownerDocument] getComputedStyle:element pseudoElement:pseudoElement];
3250 @implementation WebView (WebViewEditing)
3252 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
3254 Page* page = core(self);
3257 return kit(page->mainFrame()->editor()->rangeForPoint(IntPoint([self convertPoint:point toView:nil])).get());
3260 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
3262 // FIXME: This quirk is needed due to <rdar://problem/4985321> - We can phase it out once Aperture can adopt the new behavior on their end
3263 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_APERTURE_QUIRK) && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Aperture"])
3265 return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
3268 - (BOOL)maintainsInactiveSelection
3273 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
3275 Frame* coreFrame = core([self _selectedOrMainFrame]);
3280 coreFrame->selectionController()->clear();
3282 // Derive the frame to use from the range passed in.
3283 // Using _bridgeForSelectedOrMainFrame could give us a different document than
3284 // the one the range uses.
3285 coreFrame = core([range startContainer])->document()->frame();
3289 coreFrame->selectionController()->setSelectedRange([range _range], core(selectionAffinity), true);
3293 - (DOMRange *)selectedDOMRange
3295 Frame* coreFrame = core([self _selectedOrMainFrame]);
3298 return kit(coreFrame->selectionController()->toRange().get());
3301 - (NSSelectionAffinity)selectionAffinity
3303 Frame* coreFrame = core([self _selectedOrMainFrame]);
3305 return NSSelectionAffinityDownstream;
3306 return kit(coreFrame->selectionController()->affinity());
3309 - (void)setEditable:(BOOL)flag
3311 if (_private->editable != flag) {
3312 _private->editable = flag;
3313 if (!_private->tabKeyCyclesThroughElementsChanged && _private->page)
3314 _private->page->setTabKeyCyclesThroughElements(!flag);
3315 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
3318 mainFrame->applyEditingStyleToBodyElement();
3319 // If the WebView is made editable and the selection is empty, set it to something.
3320 if (![self selectedDOMRange])
3321 mainFrame->setSelectionFromNone();
3323 mainFrame->removeEditingStyleFromBodyElement();
3330 return _private->editable;
3333 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
3335 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3336 // change the API to allow this.
3337 [[self _bridgeForSelectedOrMainFrame] setTypingStyle:style withUndoAction:EditActionUnspecified];
3340 - (DOMCSSStyleDeclaration *)typingStyle
3342 return [[self _bridgeForSelectedOrMainFrame] typingStyle];
3345 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
3347 _private->smartInsertDeleteEnabled = flag;
3350 - (BOOL)smartInsertDeleteEnabled
3352 return _private->smartInsertDeleteEnabled;
3355 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
3357 if (continuousSpellCheckingEnabled != flag) {
3358 continuousSpellCheckingEnabled = flag;
3359 [[NSUserDefaults standardUserDefaults] setBool:continuousSpellCheckingEnabled forKey:WebContinuousSpellCheckingEnabled];
3362 if ([self isContinuousSpellCheckingEnabled]) {
3363 [[self class] _preflightSpellChecker];
3365 [[self mainFrame] _unmarkAllMisspellings];
3369 - (BOOL)isContinuousSpellCheckingEnabled
3371 return (continuousSpellCheckingEnabled && [self _continuousCheckingAllowed]);
3374 - (NSInteger)spellCheckerDocumentTag
3376 if (!_private->hasSpellCheckerDocumentTag) {
3377 _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3378 _private->hasSpellCheckerDocumentTag = YES;
3380 return _private->spellCheckerDocumentTag;
3383 - (NSUndoManager *)undoManager
3385 if (!_private->allowsUndo)
3388 NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
3392 return [super undoManager];
3395 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
3397 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3398 if ([_private->editingDelegate respondsToSelector:selector])
3399 [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
3402 - (void)setEditingDelegate:(id)delegate
3404 if (_private->editingDelegate == delegate)
3407 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3409 // remove notifications from current delegate
3410 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
3411 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
3412 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
3413 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
3414 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
3416 _private->editingDelegate = delegate;
3417 [_private->editingDelegateForwarder release];
3418 _private->editingDelegateForwarder = nil;
3420 // add notifications for new delegate
3421 [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
3422 [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
3423 [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
3424 [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
3425 [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
3428 - (id)editingDelegate
3430 return _private->editingDelegate;
3433 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
3435 // FIXME: Should this really be attached to the document with the current selection?
3436 DOMCSSStyleDeclaration *decl = [[[self _selectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
3437 [decl setCssText:text];
3443 @implementation WebView (WebViewGrammarChecking)
3445 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3446 - (BOOL)isGrammarCheckingEnabled
3448 #ifdef BUILDING_ON_TIGER
3451 return grammarCheckingEnabled;
3455 #ifndef BUILDING_ON_TIGER
3456 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3457 - (void)setGrammarCheckingEnabled:(BOOL)flag
3459 if (grammarCheckingEnabled == flag)
3462 grammarCheckingEnabled = flag;
3463 [[NSUserDefaults standardUserDefaults] setBool:grammarCheckingEnabled forKey:WebGrammarCheckingEnabled];
3465 // FIXME 4811447: workaround for lack of API
3466 NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
3467 if ([spellChecker respondsToSelector:@selector(_updateGrammar)])
3468 [spellChecker performSelector:@selector(_updateGrammar)];
3470 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3471 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3473 if (![self isGrammarCheckingEnabled])
3474 [[self mainFrame] _unmarkAllBadGrammar];
3477 // FIXME: This method should be merged into WebIBActions when we're not in API freeze
3478 - (void)toggleGrammarChecking:(id)sender
3480 [self setGrammarCheckingEnabled:![self isGrammarCheckingEnabled]];
3486 @implementation WebView (WebViewUndoableEditing)
3488 - (void)replaceSelectionWithNode:(DOMNode *)node
3490 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:NO];
3493 - (void)replaceSelectionWithText:(NSString *)text
3495 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
3498 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
3500 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
3503 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3505 [[[[self _bridgeForSelectedOrMainFrame] webFrame] _dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3508 - (void)deleteSelection
3510 WebFrame *webFrame = [self _selectedOrMainFrame];
3511 Frame* coreFrame = core(webFrame);
3513 coreFrame->editor()->deleteSelectionWithSmartDelete([(WebHTMLView *)[[webFrame frameView] documentView] _canSmartCopyOrDelete]);
3516 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3518 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3519 // change the API to allow this.
3520 WebFrame *webFrame = [self _selectedOrMainFrame];
3521 Frame* coreFrame = core(webFrame);
3523 coreFrame->editor()->applyStyle(core(style));
3528 @implementation WebView (WebViewEditingActions)
3530 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3532 static BOOL reentered = NO;
3534 [[self nextResponder] tryToPerform:selector with:parameter];
3538 // There are two possibilities here.
3540 // One is that WebView has been called in its role as part of the responder chain.
3541 // In that case, it's fine to call the first responder and end up calling down the
3542 // responder chain again. Later we will return here with reentered = YES and continue
3543 // past the WebView.
3545 // The other is that we are being called directly, in which case we want to pass the
3546 // selector down to the view inside us that can handle it, and continue down the
3547 // responder chain as usual.
3549 // Pass this selector down to the first responder.
3550 NSResponder *responder = [self _responderForResponderOperations];
3552 [responder tryToPerform:selector with:parameter];
3556 #define FORWARD(name) \
3557 - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3559 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3561 - (void)insertText:(NSString *)text
3563 [self _performResponderOperation:_cmd with:text];
3568 @implementation WebView (WebViewEditingInMail)
3570 - (void)_insertNewlineInQuotedContent;
3572 [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3575 - (void)_replaceSelectionWithNode:(DOMNode *)node matchStyle:(BOOL)matchStyle
3577 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:matchStyle];
3582 static WebFrameView *containingFrameView(NSView *view)
3584 while (view && ![view isKindOfClass:[WebFrameView class]])
3585 view = [view superview];
3586 return (WebFrameView *)view;
3589 @implementation WebView (WebFileInternal)
3591 + (void)_setCacheModel:(WebCacheModel)cacheModel
3593 if (s_didSetCacheModel && cacheModel == s_cacheModel)
3596 NSString *nsurlCacheDirectory = [(NSString *)WKCopyFoundationCacheDirectory() autorelease];
3597 if (!nsurlCacheDirectory)
3598 nsurlCacheDirectory = NSHomeDirectory();
3600 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
3601 // count doesn't align exactly to a megabyte boundary.
3602 vm_size_t memSize = WebMemorySize() / 1024 / 1000;
3603 unsigned long long diskFreeSize = WebVolumeFreeSize(nsurlCacheDirectory) / 1024 / 1000;
3604 NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
3606 unsigned cacheTotalCapacity = 0;
3607 unsigned cacheMinDeadCapacity = 0;
3608 unsigned cacheMaxDeadCapacity = 0;
3610 unsigned pageCacheCapacity = 0;
3612 NSUInteger nsurlCacheMemoryCapacity = 0;
3613 NSUInteger nsurlCacheDiskCapacity = 0;
3615 switch (cacheModel) {
3616 case WebCacheModelDocumentViewer: {
3617 // Page cache capacity (in pages)
3618 pageCacheCapacity = 0;
3620 // Object cache capacities (in bytes)
3621 if (memSize >= 4096)
3622 cacheTotalCapacity = 256 * 1024 * 1024;
3623 else if (memSize >= 3072)
3624 cacheTotalCapacity = 192 * 1024 * 1024;
3625 else if (memSize >= 2048)
3626 cacheTotalCapacity = 128 * 1024 * 1024;
3627 else if (memSize >= 1536)
3628 cacheTotalCapacity = 86 * 1024 * 1024;
3629 else if (memSize >= 1024)
3630 cacheTotalCapacity = 64 * 1024 * 1024;
3631 else if (memSize >= 512)
3632 cacheTotalCapacity = 32 * 1024 * 1024;
3633 else if (memSize >= 256)
3634 cacheTotalCapacity = 16 * 1024 * 1024;
3636 cacheMinDeadCapacity = 0;
3637 cacheMaxDeadCapacity = 0;
3639 // Foundation memory cache capacity (in bytes)
3640 nsurlCacheMemoryCapacity = 0;
3642 // Foundation disk cache capacity (in bytes)
3643 nsurlCacheDiskCapacity = [nsurlCache diskCapacity];
3647 case WebCacheModelDocumentBrowser: {
3648 // Page cache capacity (in pages)
3649 if (memSize >= 1024)
3650 pageCacheCapacity = 3;
3651 else if (memSize >= 512)
3652 pageCacheCapacity = 2;
3653 else if (memSize >= 256)
3654 pageCacheCapacity = 1;
3656 pageCacheCapacity = 0;
3658 // Object cache capacities (in bytes)
3659 if (memSize >= 4096)
3660 cacheTotalCapacity = 256 * 1024 * 1024;
3661 else if (memSize >= 3072)
3662 cacheTotalCapacity = 192 * 1024 * 1024;
3663 else if (memSize >= 2048)
3664 cacheTotalCapacity = 128 * 1024 * 1024;
3665 else if (memSize >= 1536)
3666 cacheTotalCapacity = 86 * 1024 * 1024;
3667 else if (memSize >= 1024)
3668 cacheTotalCapacity = 64 * 1024 * 1024;
3669 else if (memSize >= 512)
3670 cacheTotalCapacity = 32 * 1024 * 1024;
3671 else if (memSize >= 256)
3672 cacheTotalCapacity = 16 * 1024 * 1024;
3674 cacheMinDeadCapacity = cacheTotalCapacity / 8;
3675 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
3677 // Foundation memory cache capacity (in bytes)
3678 if (memSize >= 2048)
3679 nsurlCacheMemoryCapacity = 4 * 1024 * 1024;
3680 else if (memSize >= 1024)
3681 nsurlCacheMemoryCapacity = 2 * 1024 * 1024;
3682 else if (memSize >= 512)
3683 nsurlCacheMemoryCapacity = 1 * 1024 * 1024;