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 - (void)_preferencesChangedNotification:(NSNotification *)notification
932 WebPreferences *preferences = (WebPreferences *)[notification object];
933 ASSERT(preferences == [self preferences]);
935 if (!_private->userAgentOverridden)
936 *_private->userAgent = String();
938 // Cache this value so we don't have to read NSUserDefaults on each page load
939 _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
941 // Update corresponding WebCore Settings object.
945 Settings* settings = _private->page->settings();
947 settings->setCursiveFontFamily([preferences cursiveFontFamily]);
948 settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
949 settings->setDefaultFontSize([preferences defaultFontSize]);
950 settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
951 settings->setFantasyFontFamily([preferences fantasyFontFamily]);
952 settings->setFixedFontFamily([preferences fixedFontFamily]);
953 settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
954 settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
955 settings->setJavaEnabled([preferences isJavaEnabled]);
956 settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
957 settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
958 settings->setMinimumFontSize([preferences minimumFontSize]);
959 settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
960 settings->setPluginsEnabled([preferences arePlugInsEnabled]);
961 settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
962 settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
963 settings->setSerifFontFamily([preferences serifFontFamily]);
964 settings->setStandardFontFamily([preferences standardFontFamily]);
965 settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
966 settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
967 settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
968 settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
969 settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
970 settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
971 settings->setUsesPageCache([self usesPageCache]);
972 settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
973 settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
974 settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
975 if ([preferences userStyleSheetEnabled]) {
976 NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
977 settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
979 settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
980 settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
981 settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
982 settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
985 static inline IMP getMethod(id o, SEL s)
987 return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
990 - (void)_cacheResourceLoadDelegateImplementations
992 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
993 id delegate = _private->resourceProgressDelegate;
996 bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1000 cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1001 cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1002 cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1003 cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1004 cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1005 cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1006 cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1007 cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1008 cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1009 cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1010 cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1013 WebResourceDelegateImplementationCache* WebViewGetResourceLoadDelegateImplementations(WebView *webView)
1015 static WebResourceDelegateImplementationCache empty;
1018 return &webView->_private->resourceLoadDelegateImplementations;
1021 - (void)_cacheFrameLoadDelegateImplementations
1023 WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1024 id delegate = _private->frameLoadDelegate;
1027 bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1031 cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1032 cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1033 cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1034 cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1035 cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1036 cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1037 cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1038 cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1039 cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1040 cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1041 cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1042 cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1043 cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1044 cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1045 cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1046 cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1047 cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1050 WebFrameLoadDelegateImplementationCache* WebViewGetFrameLoadDelegateImplementations(WebView *webView)
1052 static WebFrameLoadDelegateImplementationCache empty;
1055 return &webView->_private->frameLoadDelegateImplementations;
1058 - (id)_policyDelegateForwarder
1060 if (!_private->policyDelegateForwarder)
1061 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1062 return _private->policyDelegateForwarder;
1065 - (id)_UIDelegateForwarder
1067 if (!_private->UIDelegateForwarder)
1068 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1069 return _private->UIDelegateForwarder;
1072 - (id)_editingDelegateForwarder
1074 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1075 // Not sure if that is a bug or not.
1079 if (!_private->editingDelegateForwarder)
1080 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1081 return _private->editingDelegateForwarder;
1084 - (id)_scriptDebugDelegateForwarder
1086 if (!_private->scriptDebugDelegateForwarder)
1087 _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->scriptDebugDelegate defaultTarget:[WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] catchExceptions:_private->catchesDelegateExceptions];
1088 return _private->scriptDebugDelegateForwarder;
1091 - (void)_closeWindow
1093 [[self _UIDelegateForwarder] webViewClose:self];
1096 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
1098 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1099 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1101 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1102 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1103 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1104 MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1107 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
1109 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1110 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1112 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1113 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
1114 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1115 if ([viewClass class] == [WebHTMLView class])
1116 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1118 // This is used to make _representationExistsForURLScheme faster.
1119 // Without this set, we'd have to create the MIME type each time.
1120 if (schemesWithRepresentationsSet == nil) {
1121 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1123 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1126 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1128 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1131 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1133 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1136 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1138 // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed
1142 if ([NSURLConnection canHandleRequest:request])
1145 NSString *scheme = [[request URL] scheme];
1147 if ([self _representationExistsForURLScheme:scheme])
1150 return ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"]);
1153 + (NSString *)_decodeData:(NSData *)data
1155 HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1156 RefPtr<TextResourceDecoder> decoder = new TextResourceDecoder("text/html"); // bookmark files are HTML
1157 String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1158 result += decoder->flush();
1162 - (void)_pushPerformingProgrammaticFocus
1164 _private->programmaticFocusCount++;
1167 - (void)_popPerformingProgrammaticFocus
1169 _private->programmaticFocusCount--;
1172 - (BOOL)_isPerformingProgrammaticFocus
1174 return _private->programmaticFocusCount != 0;
1177 - (void)_didChangeValueForKey: (NSString *)key
1179 LOG (Bindings, "calling didChangeValueForKey: %@", key);
1180 [self didChangeValueForKey: key];
1183 - (void)_willChangeValueForKey: (NSString *)key
1185 LOG (Bindings, "calling willChangeValueForKey: %@", key);
1186 [self willChangeValueForKey: key];
1189 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1190 static NSSet *manualNotifyKeys = nil;
1191 if (!manualNotifyKeys)
1192 manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1193 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1194 if ([manualNotifyKeys containsObject:key])
1199 - (NSArray *)_declaredKeys {
1200 static NSArray *declaredKeys = nil;
1202 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1203 _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1204 return declaredKeys;
1207 - (void)setObservationInfo:(void *)info
1209 _private->observationInfo = info;
1212 - (void *)observationInfo
1214 return _private->observationInfo;
1217 - (void)_willChangeBackForwardKeys
1219 [self _willChangeValueForKey: _WebCanGoBackKey];
1220 [self _willChangeValueForKey: _WebCanGoForwardKey];
1223 - (void)_didChangeBackForwardKeys
1225 [self _didChangeValueForKey: _WebCanGoBackKey];
1226 [self _didChangeValueForKey: _WebCanGoForwardKey];
1229 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1231 [self _willChangeBackForwardKeys];
1232 if (frame == [self mainFrame]){
1233 // Force an observer update by sending a will/did.
1234 [self _willChangeValueForKey: _WebIsLoadingKey];
1235 [self _didChangeValueForKey: _WebIsLoadingKey];
1237 [self _willChangeValueForKey: _WebMainFrameURLKey];
1240 [NSApp setWindowsNeedUpdate:YES];
1243 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1245 if (frame == [self mainFrame])
1246 [self _didChangeValueForKey: _WebMainFrameURLKey];
1247 [NSApp setWindowsNeedUpdate:YES];
1250 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1252 [self _didChangeBackForwardKeys];
1253 if (frame == [self mainFrame]){
1254 // Force an observer update by sending a will/did.
1255 [self _willChangeValueForKey: _WebIsLoadingKey];
1256 [self _didChangeValueForKey: _WebIsLoadingKey];
1258 [NSApp setWindowsNeedUpdate:YES];
1261 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1263 [self _didChangeBackForwardKeys];
1264 if (frame == [self mainFrame]){
1265 // Force an observer update by sending a will/did.
1266 [self _willChangeValueForKey: _WebIsLoadingKey];
1267 [self _didChangeValueForKey: _WebIsLoadingKey];
1269 [NSApp setWindowsNeedUpdate:YES];
1272 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1274 [self _didChangeBackForwardKeys];
1275 if (frame == [self mainFrame]){
1276 // Force an observer update by sending a will/did.
1277 [self _willChangeValueForKey: _WebIsLoadingKey];
1278 [self _didChangeValueForKey: _WebIsLoadingKey];
1280 [self _didChangeValueForKey: _WebMainFrameURLKey];
1282 [NSApp setWindowsNeedUpdate:YES];
1285 - (void)_reloadForPluginChanges
1287 [[self mainFrame] _reloadForPluginChanges];
1290 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1292 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1293 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1294 NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1296 return cachedResponse;
1299 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1301 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1302 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1303 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1305 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1306 title:[element objectForKey:WebElementImageAltStringKey]
1307 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1312 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1314 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1315 andTitle:[element objectForKey:WebElementLinkLabelKey]
1319 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1321 if (!_private->page)
1323 _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
1326 #define DASHBOARD_CONTROL_LABEL @"control"
1328 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1330 // Add scroller regions for NSScroller and KWQScrollBar
1331 int i, count = [views count];
1333 for (i = 0; i < count; i++) {
1334 NSView *aView = [views objectAtIndex:i];
1336 if ([aView isKindOfClass:[NSScroller class]] ||
1337 [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1338 NSRect bounds = [aView bounds];
1339 NSRect adjustedBounds;
1340 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1341 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1343 // AppKit has horrible hack of placing absent scrollers at -100,-100
1344 if (adjustedBounds.origin.y == -100)
1346 adjustedBounds.size = bounds.size;
1347 NSRect clip = [aView visibleRect];
1348 NSRect adjustedClip;
1349 adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1350 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1351 adjustedClip.size = clip.size;
1352 WebDashboardRegion *aRegion =
1353 [[[WebDashboardRegion alloc] initWithRect:adjustedBounds
1354 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1355 NSMutableArray *scrollerRegions;
1356 scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1357 if (!scrollerRegions) {
1358 scrollerRegions = [NSMutableArray array];
1359 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1361 [scrollerRegions addObject:aRegion];
1363 [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1367 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1369 [self _addScrollerDashboardRegions:regions from:[self subviews]];
1372 - (NSDictionary *)_dashboardRegions
1374 // Only return regions from main frame.
1375 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1378 NSMutableDictionary *regions = mainFrame->dashboardRegionsDictionary();
1379 [self _addScrollerDashboardRegions:regions];
1383 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
1385 // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement
1386 // specific support for the backward compatibility mode flag.
1387 if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
1388 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
1391 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1392 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1395 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1396 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1399 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1400 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1403 case WebDashboardBehaviorAllowWheelScrolling: {
1404 _private->dashboardBehaviorAllowWheelScrolling = flag;
1407 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1409 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
1415 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1418 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1419 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1421 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1422 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1424 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1425 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1427 case WebDashboardBehaviorAllowWheelScrolling: {
1428 return _private->dashboardBehaviorAllowWheelScrolling;
1430 case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1431 return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
1437 + (void)_setShouldUseFontSmoothing:(BOOL)f
1439 WebCoreSetShouldUseFontSmoothing(f);
1442 + (BOOL)_shouldUseFontSmoothing
1444 return WebCoreShouldUseFontSmoothing();
1447 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
1449 setUsesTestModeFocusRingColor(f);
1452 + (BOOL)_usesTestModeFocusRingColor
1454 return usesTestModeFocusRingColor();
1457 // This is only used by versions of Safari up to and including 3.0 and should be removed in a future release.
1458 + (NSString *)_minimumRequiredSafariBuildNumber
1463 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1465 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1467 [scrollview setVerticalScrollingMode:WebCoreScrollbarAlwaysOn andLock:YES];
1469 [scrollview setVerticalScrollingModeLocked:NO];
1470 [scrollview setVerticalScrollingMode:WebCoreScrollbarAuto];
1474 - (BOOL)alwaysShowVerticalScroller
1476 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1477 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == WebCoreScrollbarAlwaysOn;
1480 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1482 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1484 [scrollview setHorizontalScrollingMode:WebCoreScrollbarAlwaysOn andLock:YES];
1486 [scrollview setHorizontalScrollingModeLocked:NO];
1487 [scrollview setHorizontalScrollingMode:WebCoreScrollbarAuto];
1491 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1493 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1495 mainFrame->setProhibitsScrolling(prohibits);
1498 - (BOOL)alwaysShowHorizontalScroller
1500 WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1501 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == WebCoreScrollbarAlwaysOn;
1504 - (void)_setInViewSourceMode:(BOOL)flag
1506 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1508 mainFrame->setInViewSourceMode(flag);
1511 - (BOOL)_inViewSourceMode
1513 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
1514 return mainFrame && mainFrame->inViewSourceMode();
1517 - (void)_setUseFastImageScalingMode:(BOOL)flag
1519 if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
1520 _private->page->setInLowQualityImageInterpolationMode(flag);
1521 [self setNeedsDisplay:YES];
1525 - (BOOL)_inFastImageScalingMode
1528 return _private->page->inLowQualityImageInterpolationMode();
1532 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1534 if (!_private->pluginDatabase)
1535 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1537 [_private->pluginDatabase setPlugInPaths:newPaths];
1538 [_private->pluginDatabase refresh];
1541 - (void)_attachScriptDebuggerToAllFrames
1543 for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1544 [kit(frame) _attachScriptDebugger];
1547 - (void)_detachScriptDebuggerFromAllFrames
1549 for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1550 [kit(frame) _detachScriptDebugger];
1553 - (void)setBackgroundColor:(NSColor *)backgroundColor
1555 if ([_private->backgroundColor isEqual:backgroundColor])
1558 id old = _private->backgroundColor;
1559 _private->backgroundColor = [backgroundColor retain];
1562 [[self mainFrame] _updateBackground];
1565 - (NSColor *)backgroundColor
1567 return _private->backgroundColor;
1570 - (BOOL)defersCallbacks
1572 if (!_private->page)
1574 return _private->page->defersLoading();
1577 - (void)setDefersCallbacks:(BOOL)defer
1579 if (!_private->page)
1581 return _private->page->setDefersLoading(defer);
1584 // For backwards compatibility with the WebBackForwardList API, we honor both
1585 // a per-WebView and a per-preferences setting for whether to use the page cache.
1587 - (BOOL)usesPageCache
1589 return _private->usesPageCache && [[self preferences] usesPageCache];
1592 - (void)setUsesPageCache:(BOOL)usesPageCache
1594 _private->usesPageCache = usesPageCache;
1596 // Post a notification so the WebCore settings update.
1597 [[self preferences] _postPreferencesChangesNotification];
1600 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1602 NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window];
1603 [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window];
1606 - (void)_clearUndoRedoOperations
1608 if (!_private->page)
1610 _private->page->clearUndoRedoOperations();
1613 - (void)_setCatchesDelegateExceptions:(BOOL)f
1615 _private->catchesDelegateExceptions = f;
1618 - (BOOL)_catchesDelegateExceptions
1620 return _private->catchesDelegateExceptions;
1623 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
1625 Frame* coreFrame = [[[self mainFrame] _bridge] _frame];
1628 coreFrame->editor()->command(name).execute(value);
1633 @implementation _WebSafeForwarder
1635 // Used to send messages to delegates that implement informal protocols.
1637 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
1639 self = [super init];
1642 target = t; // Non retained.
1644 catchExceptions = c;
1648 - (void)forwardInvocation:(NSInvocation *)invocation
1650 if ([target respondsToSelector:[invocation selector]]) {
1651 if (catchExceptions) {
1653 [invocation invokeWithTarget:target];
1654 } @catch(id exception) {
1655 ReportDiscardedDelegateException([invocation selector], exception);
1658 [invocation invokeWithTarget:target];
1662 if ([defaultTarget respondsToSelector:[invocation selector]])
1663 [invocation invokeWithTarget:defaultTarget];
1665 // Do nothing quietly if method not implemented.
1668 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1670 return [defaultTarget methodSignatureForSelector:aSelector];
1675 @implementation WebView
1679 static BOOL initialized = NO;
1684 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
1685 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedNotification object:nil];
1686 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];
1689 + (void)_applicationWillTerminate
1691 applicationIsTerminating = YES;
1692 if (!pluginDatabaseClientCount)
1693 [WebPluginDatabase closeSharedDatabase];
1696 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1698 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1701 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
1703 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
1705 return pluginPackage;
1707 if (_private->pluginDatabase)
1708 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
1713 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
1715 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
1717 return pluginPackage;
1719 if (_private->pluginDatabase)
1720 return [_private->pluginDatabase pluginForExtension:extension];
1725 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
1727 if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
1730 if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
1736 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1738 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1741 + (NSArray *)MIMETypesShownAsHTML
1743 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1744 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1746 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1748 while ((key = [enumerator nextObject])) {
1749 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1750 [array addObject:key];
1756 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1758 NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
1759 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1761 while ((key = [enumerator nextObject])) {
1762 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1763 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1766 int i, count = [MIMETypes count];
1767 for (i = 0; i < count; i++) {
1768 [WebView registerViewClass:[WebHTMLView class]
1769 representationClass:[WebHTMLRepresentation class]
1770 forMIMEType:[MIMETypes objectAtIndex:i]];
1772 [viewTypes release];
1775 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1777 return [pasteboard _web_bestURL];
1780 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1782 return [pasteboard stringForType:WebURLNamePboardType];
1785 + (void)registerURLSchemeAsLocal:(NSString *)protocol
1787 FrameLoader::registerURLSchemeAsLocal(protocol);
1790 - (void)_registerDraggedTypes
1792 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1793 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1794 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1795 [types addObjectsFromArray:URLTypes];
1796 [self registerForDraggedTypes:[types allObjects]];
1800 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1802 WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1803 [standardPreferences willAddToWebView];
1805 _private->preferences = [standardPreferences retain];
1806 _private->catchesDelegateExceptions = YES;
1807 _private->mainFrameDocumentReady = NO;
1808 _private->drawsBackground = YES;
1809 _private->smartInsertDeleteEnabled = YES;
1810 _private->backgroundColor = [[NSColor whiteColor] retain];
1812 NSRect f = [self frame];
1813 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1814 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1815 [self addSubview:frameView];
1816 [frameView release];
1818 WebKitInitializeLoggingChannelsIfNecessary();
1819 WebCore::InitializeLoggingChannelsIfNecessary();
1820 [WebHistoryItem initWindowWatcherIfNecessary];
1821 WebKitInitializeDatabasesIfNecessary();
1823 _private->page = new Page(new WebChromeClient(self), new WebContextMenuClient(self), new WebEditorClient(self), new WebDragClient(self), new WebInspectorClient(self));
1824 [[[WebFrameBridge alloc] initMainFrameWithPage:_private->page frameName:frameName frameView:frameView] release];
1826 #ifndef BUILDING_ON_TIGER
1827 if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1828 [self scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
1830 [self scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
1833 [self _addToAllWebViewsSet];
1834 [self setGroupName:groupName];
1836 // If there's already a next key view (e.g., from a nib), wire it up to our
1837 // contained frame view. In any case, wire our next key view up to the our
1838 // contained frame view. This works together with our becomeFirstResponder
1839 // and setNextKeyView overrides.
1840 NSView *nextKeyView = [self nextKeyView];
1841 if (nextKeyView && nextKeyView != frameView)
1842 [frameView setNextKeyView:nextKeyView];
1843 [super setNextKeyView:frameView];
1847 [self _registerDraggedTypes];
1849 // initialize WebScriptDebugServer here so listeners can register before any pages are loaded.
1850 if ([WebView _scriptDebuggerEnabled])
1851 [WebScriptDebugServer sharedScriptDebugServer];
1853 WebPreferences *prefs = [self preferences];
1854 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1855 name:WebPreferencesChangedNotification object:prefs];
1857 // Post a notification so the WebCore settings update.
1858 [[self preferences] _postPreferencesChangesNotification];
1860 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION))
1861 FrameLoader::setRestrictAccessToLocal(false);
1864 - (id)initWithFrame:(NSRect)f
1866 return [self initWithFrame:f frameName:nil groupName:nil];
1869 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1871 self = [super initWithFrame:f];
1875 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1876 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1877 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1878 // need for Safari to unset it to prevent it from being passed to applications it launches.
1879 // Unsetting it when a WebView is first created is as good a place as any.
1880 // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1881 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1882 unsetenv("DYLD_FRAMEWORK_PATH");
1883 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1887 _private = [[WebViewPrivate alloc] init];
1888 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1889 [self setMaintainsBackForwardList: YES];
1893 - (id)initWithCoder:(NSCoder *)decoder
1895 WebView *result = nil;
1898 NSString *frameName;
1899 NSString *groupName;
1900 WebPreferences *preferences;
1901 BOOL useBackForwardList = NO;
1902 BOOL allowsUndo = YES;
1904 result = [super initWithCoder:decoder];
1905 result->_private = [[WebViewPrivate alloc] init];
1907 // We don't want any of the archived subviews. The subviews will always
1908 // be created in _commonInitializationFrameName:groupName:.
1909 [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1911 if ([decoder allowsKeyedCoding]) {
1912 frameName = [decoder decodeObjectForKey:@"FrameName"];
1913 groupName = [decoder decodeObjectForKey:@"GroupName"];
1914 preferences = [decoder decodeObjectForKey:@"Preferences"];
1915 useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1916 if ([decoder containsValueForKey:@"AllowsUndo"])
1917 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
1920 [decoder decodeValueOfObjCType:@encode(int) at:&version];
1921 frameName = [decoder decodeObject];
1922 groupName = [decoder decodeObject];
1923 preferences = [decoder decodeObject];
1925 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1926 // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
1927 // version 3 NIBs that have this field encoded, we still need to read it in.
1929 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
1932 if (![frameName isKindOfClass:[NSString class]])
1934 if (![groupName isKindOfClass:[NSString class]])
1936 if (![preferences isKindOfClass:[WebPreferences class]])
1939 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1940 [result _commonInitializationWithFrameName:frameName groupName:groupName];
1941 [result page]->backForwardList()->setEnabled(useBackForwardList);
1942 result->_private->allowsUndo = allowsUndo;
1944 [result setPreferences:preferences];
1945 } @catch (NSException *localException) {
1953 - (void)encodeWithCoder:(NSCoder *)encoder
1955 // Set asside the subviews before we archive. We don't want to archive any subviews.
1956 // The subviews will always be created in _commonInitializationFrameName:groupName:.
1957 id originalSubviews = _subviews;
1960 [super encodeWithCoder:encoder];
1962 // Restore the subviews we set aside.
1963 _subviews = originalSubviews;
1965 BOOL useBackForwardList = _private->page && _private->page->backForwardList()->enabled();
1966 if ([encoder allowsKeyedCoding]) {
1967 [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
1968 [encoder encodeObject:[self groupName] forKey:@"GroupName"];
1969 [encoder encodeObject:[self preferences] forKey:@"Preferences"];
1970 [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
1971 [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
1973 int version = WebViewVersion;
1974 [encoder encodeValueOfObjCType:@encode(int) at:&version];
1975 [encoder encodeObject:[[self mainFrame] name]];
1976 [encoder encodeObject:[self groupName]];
1977 [encoder encodeObject:[self preferences]];
1978 [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
1979 // DO NOT encode any new fields here, doing so will break older WebKit releases.
1982 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
1987 // call close to ensure we tear-down completely
1988 // this maintains our old behavior for existing applications
1994 // [super dealloc] can end up dispatching against _private (3466082)
2002 ASSERT(_private->closed);
2014 - (void)setShouldCloseWithWindow:(BOOL)close
2016 _private->shouldCloseWithWindow = close;
2019 - (BOOL)shouldCloseWithWindow
2021 return _private->shouldCloseWithWindow;
2024 - (void)viewWillMoveToWindow:(NSWindow *)window
2026 // Don't do anything if we aren't initialized. This happens when decoding a WebView.
2031 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
2034 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
2036 // Ensure that we will receive the events that WebHTMLView (at least) needs. It's expensive enough
2037 // that we don't want to call it over and over.
2038 [window setAcceptsMouseMovedEvents:YES];
2039 WKSetNSWindowShouldPostEventNotifications(window, YES);
2043 - (void)_windowWillClose:(NSNotification *)notification
2045 if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
2049 - (void)setPreferences:(WebPreferences *)prefs
2052 prefs = [WebPreferences standardPreferences];
2054 if (_private->preferences == prefs)
2057 [prefs willAddToWebView];
2059 WebPreferences *oldPrefs = _private->preferences;
2061 [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
2062 [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
2064 _private->preferences = [prefs retain];
2066 // After registering for the notification, post it so the WebCore settings update.
2067 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
2068 name:WebPreferencesChangedNotification object:[self preferences]];
2069 [[self preferences] _postPreferencesChangesNotification];
2071 [oldPrefs didRemoveFromWebView];
2075 - (WebPreferences *)preferences
2077 return _private->preferences;
2080 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
2082 if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
2083 WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
2084 [self setPreferences:prefs];
2089 - (NSString *)preferencesIdentifier
2091 return [[self preferences] identifier];
2095 - (void)setUIDelegate:delegate
2097 _private->UIDelegate = delegate;
2098 [_private->UIDelegateForwarder release];
2099 _private->UIDelegateForwarder = nil;
2104 return _private->UIDelegate;
2107 - (void)setResourceLoadDelegate: delegate
2109 _private->resourceProgressDelegate = delegate;
2110 [self _cacheResourceLoadDelegateImplementations];
2113 - resourceLoadDelegate
2115 return _private->resourceProgressDelegate;
2118 - (void)setDownloadDelegate: delegate
2120 _private->downloadDelegate = delegate;
2126 return _private->downloadDelegate;
2129 - (void)setPolicyDelegate:delegate
2131 _private->policyDelegate = delegate;
2132 [_private->policyDelegateForwarder release];
2133 _private->policyDelegateForwarder = nil;
2138 return _private->policyDelegate;
2141 - (void)setFrameLoadDelegate:delegate
2143 _private->frameLoadDelegate = delegate;
2144 [self _cacheFrameLoadDelegateImplementations];
2146 // If this delegate wants callbacks for icons, fire up the icon database.
2147 if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
2148 [WebIconDatabase sharedIconDatabase];
2153 return _private->frameLoadDelegate;
2156 - (WebFrame *)mainFrame
2158 // This can be called in initialization, before _private has been set up (3465613)
2161 if (!_private->page)
2163 return kit(_private->page->mainFrame());
2166 - (WebFrame *)selectedFrame
2168 // If the first responder is a view in our tree, we get the frame containing the first responder.
2169 // This is faster than searching the frame hierarchy, and will give us a result even in the case
2170 // where the focused frame doesn't actually contain a selection.
2171 WebFrame *focusedFrame = [self _focusedFrame];
2173 return focusedFrame;
2175 // If the first responder is outside of our view tree, we search for a frame containing a selection.
2176 // There should be at most only one of these.
2177 return [[self mainFrame] _findFrameWithSelection];
2180 - (WebBackForwardList *)backForwardList
2182 if (!_private->page)
2184 if (!_private->page->backForwardList()->enabled())
2186 return kit(_private->page->backForwardList());
2189 - (void)setMaintainsBackForwardList: (BOOL)flag
2191 if (!_private->page)
2193 _private->page->backForwardList()->setEnabled(flag);
2198 if (!_private->page)
2201 return _private->page->goBack();
2206 if (!_private->page)
2209 return _private->page->goForward();
2212 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
2214 if (!_private->page)
2217 _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
2221 - (void)setTextSizeMultiplier:(float)m
2223 // NOTE: This has no visible effect when viewing a PDF (see <rdar://problem/4737380>)
2224 if (_private->textSizeMultiplier == m)
2227 _private->textSizeMultiplier = m;
2228 [self _notifyTextSizeMultiplierChanged];
2231 - (float)textSizeMultiplier
2233 return _private->textSizeMultiplier;
2236 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
2238 NSString *name = [applicationName copy];
2239 [_private->applicationNameForUserAgent release];
2240 _private->applicationNameForUserAgent = name;
2241 if (!_private->userAgentOverridden)
2242 *_private->userAgent = String();
2245 - (NSString *)applicationNameForUserAgent
2247 return [[_private->applicationNameForUserAgent retain] autorelease];
2250 - (void)setCustomUserAgent:(NSString *)userAgentString
2252 *_private->userAgent = userAgentString;
2253 _private->userAgentOverridden = userAgentString != nil;
2256 - (NSString *)customUserAgent
2258 if (!_private->userAgentOverridden)
2260 return *_private->userAgent;
2263 - (void)setMediaStyle:(NSString *)mediaStyle
2265 if (_private->mediaStyle != mediaStyle) {
2266 [_private->mediaStyle release];
2267 _private->mediaStyle = [mediaStyle copy];
2271 - (NSString *)mediaStyle
2273 return _private->mediaStyle;
2276 - (BOOL)supportsTextEncoding
2278 id documentView = [[[self mainFrame] frameView] documentView];
2279 return [documentView conformsToProtocol:@protocol(WebDocumentText)]
2280 && [documentView supportsTextEncoding];
2283 - (void)setCustomTextEncodingName:(NSString *)encoding
2285 NSString *oldEncoding = [self customTextEncodingName];
2286 if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding])
2288 FrameLoader* mainFrameLoader = [[self mainFrame] _frameLoader];
2289 if (mainFrameLoader)
2290 mainFrameLoader->reloadAllowingStaleData(encoding);
2293 - (NSString *)_mainFrameOverrideEncoding
2295 WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
2296 if (dataSource == nil)
2297 dataSource = [[self mainFrame] _dataSource];
2298 if (dataSource == nil)
2300 return nsStringNilIfEmpty([dataSource _documentLoader]->overrideEncoding());
2303 - (NSString *)customTextEncodingName
2305 return [self _mainFrameOverrideEncoding];
2308 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
2310 // Return statements are only valid in a function but some applications pass in scripts
2311 // prefixed with return (<rdar://problems/5103720&4616860>) since older WebKit versions
2312 // silently ignored the return. If the application is linked against an earlier version
2313 // of WebKit we will strip the return so the script wont fail.
2314 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_JAVASCRIPT_RETURN_QUIRK)) {
2315 NSRange returnStringRange = [script rangeOfString:@"return "];
2316 if (returnStringRange.length && !returnStringRange.location)
2317 script = [script substringFromIndex:returnStringRange.location + returnStringRange.length];
2320 NSString *result = [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
2321 // The only way stringByEvaluatingJavaScriptFromString can return nil is if the frame was removed by the script
2322 // Since there's no way to get rid of the main frame, result will never ever be nil here.
2328 - (WebScriptObject *)windowScriptObject
2330 Frame* coreFrame = core([self mainFrame]);
2333 return coreFrame->windowScriptObject();
2336 // Get the appropriate user-agent string for a particular URL.
2337 - (NSString *)userAgentForURL:(NSURL *)url
2339 return [self _userAgentForURL:KURL([url absoluteURL])];
2342 - (void)setHostWindow:(NSWindow *)hostWindow
2344 if (!_private->closed && hostWindow != _private->hostWindow) {
2345 [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2346 if (_private->hostWindow)
2347 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
2349 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
2350 [_private->hostWindow release];
2351 _private->hostWindow = [hostWindow retain];
2352 [[self mainFrame] _viewDidMoveToHostWindow];
2356 - (NSWindow *)hostWindow
2358 return _private->hostWindow;
2361 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2363 return [[self _frameViewAtWindowPoint:point] documentView];
2366 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2368 WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2371 NSView <WebDocumentView> *documentView = [frameView documentView];
2372 if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2373 NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2374 return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2376 return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2379 - (NSDictionary *)elementAtPoint:(NSPoint)point
2381 return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2384 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2385 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination.
2386 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination.
2387 // Forward these calls to the document subview to make its scroll view scroll.
2388 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2390 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2391 [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2394 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2396 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2397 return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2400 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2402 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2403 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2404 IntPoint client([draggingInfo draggingLocation]);
2405 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2406 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2407 return core(self)->dragController()->dragEntered(&dragData);
2410 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2412 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2413 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2414 IntPoint client([draggingInfo draggingLocation]);
2415 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2416 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2417 return core(self)->dragController()->dragUpdated(&dragData);
2420 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2422 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2423 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2424 IntPoint client([draggingInfo draggingLocation]);
2425 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2426 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2427 core(self)->dragController()->dragExited(&dragData);
2430 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2435 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2437 NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2438 WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]]? (WebHTMLView*)view : nil);
2439 IntPoint client([draggingInfo draggingLocation]);
2440 IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2441 DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2442 return core(self)->dragController()->performDrag(&dragData);
2445 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2447 NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2448 if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2455 - (BOOL)acceptsFirstResponder
2457 return [[[self mainFrame] frameView] acceptsFirstResponder];
2460 - (BOOL)becomeFirstResponder
2462 if (_private->becomingFirstResponder) {
2463 // Fix for unrepro infinite recursion reported in radar 4448181. If we hit this assert on
2464 // a debug build, we should figure out what causes the problem and do a better fix.
2465 ASSERT_NOT_REACHED();
2469 // This works together with setNextKeyView to splice the WebView into
2470 // the key loop similar to the way NSScrollView does this. Note that
2471 // WebFrameView has very similar code.
2472 NSWindow *window = [self window];
2473 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2475 NSResponder *previousFirstResponder = [[self window] _oldFirstResponderBeforeBecoming];
2476 BOOL fromOutside = ![previousFirstResponder isKindOfClass:[NSView class]] || (![(NSView *)previousFirstResponder isDescendantOf:self] && previousFirstResponder != self);
2478 if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2479 NSView *previousValidKeyView = [self previousValidKeyView];
2480 if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2481 _private->becomingFirstResponder = YES;
2482 _private->becomingFirstResponderFromOutside = fromOutside;
2483 [window makeFirstResponder:previousValidKeyView];
2484 _private->becomingFirstResponderFromOutside = NO;
2485 _private->becomingFirstResponder = NO;
2492 if ([mainFrameView acceptsFirstResponder]) {
2493 _private->becomingFirstResponder = YES;
2494 _private->becomingFirstResponderFromOutside = fromOutside;
2495 [window makeFirstResponder:mainFrameView];
2496 _private->becomingFirstResponderFromOutside = NO;
2497 _private->becomingFirstResponder = NO;
2504 - (NSView *)_webcore_effectiveFirstResponder
2506 WebFrameView *frameView = [[self mainFrame] frameView];
2507 return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2510 - (void)setNextKeyView:(NSView *)aView
2512 // This works together with becomeFirstResponder to splice the WebView into
2513 // the key loop similar to the way NSScrollView does this. Note that
2514 // WebFrameView has very similar code.
2515 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2516 if (mainFrameView != nil) {
2517 [mainFrameView setNextKeyView:aView];
2519 [super setNextKeyView:aView];
2523 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2525 Frame* coreFrame = core(curr);
2527 ? coreFrame->tree()->traverseNextWithWrap(wrapFlag)
2528 : coreFrame->tree()->traversePreviousWithWrap(wrapFlag));
2531 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2533 return [self searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag startInSelection:NO];
2536 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2538 [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2539 [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2541 // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2542 // in the WebCore MIMEType registry. For now we're doing this in a safe, limited manner
2543 // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2544 if ([viewClass class] == [WebHTMLView class])
2545 MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2548 - (void)setGroupName:(NSString *)groupName
2550 if (!_private->page)
2552 _private->page->setGroupName(groupName);
2555 - (NSString *)groupName
2557 if (!_private->page)
2559 return _private->page->groupName();
2562 - (double)estimatedProgress
2564 if (!_private->page)
2567 return _private->page->progress()->estimatedProgress();
2570 - (NSArray *)pasteboardTypesForSelection
2572 NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2573 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2574 return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2576 return [NSArray array];
2579 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2581 WebFrame *frame = [self _selectedOrMainFrame];
2582 if (frame && [frame _hasSelection]) {
2583 NSView <WebDocumentView> *documentView = [[frame frameView] documentView];
2584 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)])
2585 [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2589 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2591 if ([element objectForKey:WebElementImageURLKey] != nil) {
2592 return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2593 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2594 return [NSPasteboard _web_writableTypesForURL];
2595 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2596 return [self pasteboardTypesForSelection];
2598 return [NSArray array];
2601 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2603 if ([element objectForKey:WebElementImageURLKey] != nil) {
2604 [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2605 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2606 [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2607 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2608 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2612 - (void)moveDragCaretToPoint:(NSPoint)point
2614 if (Page* page = core(self))
2615 page->dragController()->placeDragCaret(IntPoint([self convertPoint:point toView:nil]));
2618 - (void)removeDragCaret
2620 if (Page* page = core(self))
2621 page->dragController()->dragEnded();
2624 - (void)setMainFrameURL:(NSString *)URLString
2626 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2629 - (NSString *)mainFrameURL
2632 ds = [[self mainFrame] provisionalDataSource];
2634 ds = [[self mainFrame] _dataSource];
2635 return [[[ds request] URL] _web_originalDataAsString];
2640 LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2641 return [self _isLoading];
2644 - (NSString *)mainFrameTitle
2646 NSString *mainFrameTitle = [[[self mainFrame] _dataSource] pageTitle];
2647 return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2650 - (NSImage *)mainFrameIcon
2652 return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] _dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2655 - (DOMDocument *)mainFrameDocument
2657 // only return the actual value if the state we're in gives NSTreeController
2658 // enough time to release its observers on the old model
2659 if (_private->mainFrameDocumentReady)
2660 return [[self mainFrame] DOMDocument];
2664 - (void)setDrawsBackground:(BOOL)drawsBackground
2666 if (_private->drawsBackground == drawsBackground)
2668 _private->drawsBackground = drawsBackground;
2669 [[self mainFrame] _updateBackground];
2672 - (BOOL)drawsBackground
2674 return _private->drawsBackground;
2679 @implementation WebView (WebIBActions)
2681 - (IBAction)takeStringURLFrom: sender
2683 NSString *URLString = [sender stringValue];
2685 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2690 if (!_private->page)
2693 return !!_private->page->backForwardList()->backItem();
2696 - (BOOL)canGoForward
2698 if (!_private->page)
2701 return !!_private->page->backForwardList()->forwardItem();
2704 - (IBAction)goBack:(id)sender
2709 - (IBAction)goForward:(id)sender
2714 - (IBAction)stopLoading:(id)sender
2716 [[self mainFrame] stopLoading];
2719 - (IBAction)reload:(id)sender
2721 [[self mainFrame] reload];
2724 #define MinimumTextSizeMultiplier 0.5f
2725 #define MaximumTextSizeMultiplier 3.0f
2726 #define TextSizeMultiplierRatio 1.2f
2728 - (BOOL)canMakeTextSmaller
2730 BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2731 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2734 - (BOOL)canMakeTextLarger
2736 BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2737 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2740 - (IBAction)makeTextSmaller:(id)sender
2742 float newScale = _private->textSizeMultiplier / TextSizeMultiplierRatio;
2743 BOOL canShrinkMore = newScale > MinimumTextSizeMultiplier;
2744 [self _performTextSizingSelector:@selector(_makeTextSmaller:) withObject:sender onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:newScale];
2747 - (IBAction)makeTextLarger:(id)sender
2749 float newScale = _private->textSizeMultiplier*TextSizeMultiplierRatio;
2750 BOOL canGrowMore = newScale < MaximumTextSizeMultiplier;
2751 [self _performTextSizingSelector:@selector(_makeTextLarger:) withObject:sender onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:newScale];
2754 - (IBAction)toggleSmartInsertDelete:(id)sender
2756 [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2759 - (IBAction)toggleContinuousSpellChecking:(id)sender
2761 [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2764 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2766 id responder = [self _responderForResponderOperations];
2767 if (responder != self && [responder respondsToSelector:[item action]]) {
2768 if ([responder respondsToSelector:@selector(validateUserInterfaceItemWithoutDelegate:)])
2769 return [responder validateUserInterfaceItemWithoutDelegate:item];
2770 if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)])
2771 return [responder validateUserInterfaceItem:item];
2777 - (BOOL)canMakeTextStandardSize
2779 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2780 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0.0f];
2783 - (IBAction)makeTextStandardSize:(id)sender
2785 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2786 [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0f];
2789 #define VALIDATE(name) \
2790 else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2792 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item
2794 SEL action = [item action];
2796 if (action == @selector(goBack:)) {
2797 return [self canGoBack];
2798 } else if (action == @selector(goForward:)) {
2799 return [self canGoForward];
2800 } else if (action == @selector(makeTextLarger:)) {
2801 return [self canMakeTextLarger];
2802 } else if (action == @selector(makeTextSmaller:)) {
2803 return [self canMakeTextSmaller];
2804 } else if (action == @selector(makeTextStandardSize:)) {
2805 return [self canMakeTextStandardSize];
2806 } else if (action == @selector(reload:)) {
2807 return [[self mainFrame] _dataSource] != nil;
2808 } else if (action == @selector(stopLoading:)) {
2809 return [self _isLoading];
2810 } else if (action == @selector(toggleContinuousSpellChecking:)) {
2811 BOOL checkMark = NO;
2813 if ([self _continuousCheckingAllowed]) {
2814 checkMark = [self isContinuousSpellCheckingEnabled];
2817 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2818 NSMenuItem *menuItem = (NSMenuItem *)item;
2819 [menuItem setState:checkMark ? NSOnState : NSOffState];
2822 #ifndef BUILDING_ON_TIGER
2823 } else if (action == @selector(toggleGrammarChecking:)) {
2824 BOOL checkMark = [self isGrammarCheckingEnabled];
2825 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2826 NSMenuItem *menuItem = (NSMenuItem *)item;
2827 [menuItem setState:checkMark ? NSOnState : NSOffState];
2832 FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2837 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2839 BOOL result = [self validateUserInterfaceItemWithoutDelegate:item];
2840 return CallUIDelegateReturningBoolean(result, self, @selector(webView:validateUserInterfaceItem:defaultValidation:), item, result);
2845 @implementation WebView (WebPendingPublic)
2847 - (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode
2849 #ifndef BUILDING_ON_TIGER
2850 if (runLoop && mode)
2851 core(self)->addSchedulePair(SchedulePair::create(runLoop, (CFStringRef)mode));
2855 - (void)unscheduleFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode
2857 #ifndef BUILDING_ON_TIGER
2858 if (runLoop && mode)
2859 core(self)->removeSchedulePair(SchedulePair::create(runLoop, (CFStringRef)mode));
2863 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
2865 if (_private->closed)
2868 // Get the frame holding the selection, or start with the main frame
2869 WebFrame *startFrame = [self _selectedOrMainFrame];
2871 // Search the first frame, then all the other frames, in order
2872 NSView <WebDocumentSearching> *startSearchView = nil;
2873 WebFrame *frame = startFrame;
2875 WebFrame *nextFrame = incrementFrame(frame, forward, wrapFlag);
2877 BOOL onlyOneFrame = (frame == nextFrame);
2878 ASSERT(!onlyOneFrame || frame == startFrame);
2880 id <WebDocumentView> view = [[frame frameView] documentView];
2881 if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2882 NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2884 if (frame == startFrame)
2885 startSearchView = searchView;
2888 // In some cases we have to search some content twice; see comment later in this method.
2889 // We can avoid ever doing this in the common one-frame case by passing YES for wrapFlag
2890 // here, and then bailing out before we get to the code that would search again in the
2892 BOOL wrapOnThisPass = wrapFlag && onlyOneFrame;
2893 if ([searchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
2894 foundString = [(NSView <WebDocumentIncrementalSearching> *)searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass startInSelection:startInSelection];
2896 foundString = [searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass];
2899 if (frame != startFrame)
2900 [startFrame _clearSelection];
2901 [[self window] makeFirstResponder:searchView];
2909 } while (frame && frame != startFrame);
2911 // 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
2912 // 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
2913 // 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
2914 // some content that we already searched on the first pass. In the worst case, we could search the entire contents of this frame twice.
2915 // To fix this, we'd need to add a mechanism to specify a range in which to search.
2916 if (wrapFlag && startSearchView) {
2918 if ([startSearchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
2919 foundString = [(NSView <WebDocumentIncrementalSearching> *)startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES startInSelection:startInSelection];
2921 foundString = [startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES];
2923 [[self window] makeFirstResponder:startSearchView];
2930 - (void)setHoverFeedbackSuspended:(BOOL)newValue
2932 if (_private->hoverFeedbackSuspended == newValue)
2935 _private->hoverFeedbackSuspended = newValue;
2936 id <WebDocumentView> documentView = [[[self mainFrame] frameView] documentView];
2937 // FIXME: in a perfect world we'd do this in a general way that worked with any document view,
2938 // such as by calling a protocol method or using respondsToSelector or sending a notification.
2939 // But until there is any need for these more general solutions, we'll just hardwire it to work
2940 // with WebHTMLView.
2941 // Note that _hoverFeedbackSuspendedChanged needs to be called only on the main WebHTMLView, not
2942 // on each subframe separately.
2943 if ([documentView isKindOfClass:[WebHTMLView class]])
2944 [(WebHTMLView *)documentView _hoverFeedbackSuspendedChanged];
2947 - (BOOL)isHoverFeedbackSuspended
2949 return _private->hoverFeedbackSuspended;
2952 - (void)setMainFrameDocumentReady:(BOOL)mainFrameDocumentReady
2954 // by setting this to NO, calls to mainFrameDocument are forced to return nil
2955 // setting this to YES lets it return the actual DOMDocument value
2956 // we use this to tell NSTreeController to reset its observers and clear its state
2957 if (_private->mainFrameDocumentReady == mainFrameDocumentReady)
2959 [self _willChangeValueForKey:_WebMainFrameDocumentKey];
2960 _private->mainFrameDocumentReady = mainFrameDocumentReady;
2961 [self _didChangeValueForKey:_WebMainFrameDocumentKey];
2962 // this will cause observers to call mainFrameDocument where this flag will be checked
2965 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it
2966 // until the day comes when we're no longer supporting Mail on Tiger.
2967 - (WebFrame *)_frameForCurrentSelection
2969 return [self _selectedOrMainFrame];
2972 - (void)setTabKeyCyclesThroughElements:(BOOL)cyclesElements
2974 _private->tabKeyCyclesThroughElementsChanged = YES;
2976 _private->page->setTabKeyCyclesThroughElements(cyclesElements);
2979 - (BOOL)tabKeyCyclesThroughElements
2981 return _private->page && _private->page->tabKeyCyclesThroughElements();
2984 - (void)setScriptDebugDelegate:(id)delegate
2986 _private->scriptDebugDelegate = delegate;
2987 [_private->scriptDebugDelegateForwarder release];
2988 _private->scriptDebugDelegateForwarder = nil;
2990 [self _attachScriptDebuggerToAllFrames];
2992 [self _detachScriptDebuggerFromAllFrames];
2995 - (id)scriptDebugDelegate
2997 return _private->scriptDebugDelegate;
3002 Frame* coreFrame = core([self mainFrame]);
3005 return coreFrame->shouldClose();
3008 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
3010 return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
3013 - (BOOL)canMarkAllTextMatches
3015 WebFrame *frame = [self mainFrame];
3017 id <WebDocumentView> view = [[frame frameView] documentView];
3018 if (view && ![view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3021 frame = incrementFrame(frame, YES, NO);
3027 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
3029 WebFrame *frame = [self mainFrame];
3030 unsigned matchCount = 0;
3032 id <WebDocumentView> view = [[frame frameView] documentView];
3033 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3034 [(NSView <WebMultipleTextMatches>*)view setMarkedTextMatchesAreHighlighted:highlight];
3036 ASSERT(limit == 0 || matchCount < limit);
3037 matchCount += [(NSView <WebMultipleTextMatches>*)view markAllMatchesForText:string caseSensitive:caseFlag limit:limit == 0 ? 0 : limit - matchCount];
3039 // Stop looking if we've reached the limit. A limit of 0 means no limit.
3040 if (limit > 0 && matchCount >= limit)
3044 frame = incrementFrame(frame, YES, NO);
3050 - (void)unmarkAllTextMatches
3052 WebFrame *frame = [self mainFrame];
3054 id <WebDocumentView> view = [[frame frameView] documentView];
3055 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3056 [(NSView <WebMultipleTextMatches>*)view unmarkAllTextMatches];
3058 frame = incrementFrame(frame, YES, NO);
3062 - (NSArray *)rectsForTextMatches
3064 NSMutableArray *result = [NSMutableArray array];
3065 WebFrame *frame = [self mainFrame];
3067 id <WebDocumentView> view = [[frame frameView] documentView];
3068 if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3069 NSView <WebMultipleTextMatches> *documentView = (NSView <WebMultipleTextMatches> *)view;
3070 NSRect documentViewVisibleRect = [documentView visibleRect];
3071 NSArray *originalRects = [documentView rectsForTextMatches];
3072 unsigned rectCount = [originalRects count];
3074 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3075 for (rectIndex = 0; rectIndex < rectCount; ++rectIndex) {
3076 NSRect r = [[originalRects objectAtIndex:rectIndex] rectValue];
3077 // Clip rect to document view's visible rect so rect is confined to subframe
3078 r = NSIntersectionRect(r, documentViewVisibleRect);
3079 if (NSIsEmptyRect(r))
3082 // Convert rect to our coordinate system
3083 r = [documentView convertRect:r toView:self];
3084 [result addObject:[NSValue valueWithRect:r]];
3085 if (rectIndex % 10 == 0) {
3087 pool = [[NSAutoreleasePool alloc] init];
3093 frame = incrementFrame(frame, YES, NO);
3099 - (void)scrollDOMRangeToVisible:(DOMRange *)range
3101 [[[range startContainer] _bridge] scrollDOMRangeToVisible:range];
3106 return _private->allowsUndo;
3109 - (void)setAllowsUndo:(BOOL)flag
3111 _private->allowsUndo = flag;
3116 @implementation WebView (WebViewPrintingPrivate)
3118 - (float)_headerHeight
3120 return CallUIDelegateReturningFloat(self, @selector(webViewHeaderHeight:));
3123 - (float)_footerHeight
3125 return CallUIDelegateReturningFloat(self, @selector(webViewFooterHeight:));
3128 - (void)_drawHeaderInRect:(NSRect)rect
3130 #ifdef DEBUG_HEADER_AND_FOOTER
3131 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3132 [currentContext saveGraphicsState];
3133 [[NSColor yellowColor] set];
3135 [currentContext restoreGraphicsState];
3138 SEL selector = @selector(webView:drawHeaderInRect:);
3139 if (![_private->UIDelegate respondsToSelector:selector])
3142 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3143 [currentContext saveGraphicsState];
3146 CallUIDelegate(self, selector, rect);
3148 [currentContext restoreGraphicsState];
3151 - (void)_drawFooterInRect:(NSRect)rect
3153 #ifdef DEBUG_HEADER_AND_FOOTER
3154 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3155 [currentContext saveGraphicsState];
3156 [[NSColor cyanColor] set];
3158 [currentContext restoreGraphicsState];
3161 SEL selector = @selector(webView:drawFooterInRect:);
3162 if (![_private->UIDelegate respondsToSelector:selector])
3165 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3166 [currentContext saveGraphicsState];
3169 CallUIDelegate(self, selector, rect);
3171 [currentContext restoreGraphicsState];
3174 - (void)_adjustPrintingMarginsForHeaderAndFooter
3176 NSPrintOperation *op = [NSPrintOperation currentOperation];
3177 NSPrintInfo *info = [op printInfo];
3178 NSMutableDictionary *infoDictionary = [info dictionary];
3180 // We need to modify the top and bottom margins in the NSPrintInfo to account for the space needed by the
3181 // header and footer. Because this method can be called more than once on the same NSPrintInfo (see 5038087),
3182 // we stash away the unmodified top and bottom margins the first time this method is called, and we read from
3183 // those stashed-away values on subsequent calls.
3184 float originalTopMargin;
3185 float originalBottomMargin;
3186 NSNumber *originalTopMarginNumber = [infoDictionary objectForKey:WebKitOriginalTopPrintingMarginKey];
3187 if (!originalTopMarginNumber) {
3188 ASSERT(![infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey]);
3189 originalTopMargin = [info topMargin];
3190 originalBottomMargin = [info bottomMargin];
3191 [infoDictionary setObject:[NSNumber numberWithFloat:originalTopMargin] forKey:WebKitOriginalTopPrintingMarginKey];
3192 [infoDictionary setObject:[NSNumber numberWithFloat:originalBottomMargin] forKey:WebKitOriginalBottomPrintingMarginKey];
3194 ASSERT([originalTopMarginNumber isKindOfClass:[NSNumber class]]);
3195 ASSERT([[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] isKindOfClass:[NSNumber class]]);
3196 originalTopMargin = [originalTopMarginNumber floatValue];
3197 originalBottomMargin = [[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] floatValue];
3200 float scale = [op _web_pageSetupScaleFactor];
3201 [info setTopMargin:originalTopMargin + [self _headerHeight] * scale];
3202 [info setBottomMargin:originalBottomMargin + [self _footerHeight] * scale];
3205 - (void)_drawHeaderAndFooter
3207 // The header and footer rect height scales with the page, but the width is always
3208 // all the way across the printed page (inset by printing margins).
3209 NSPrintOperation *op = [NSPrintOperation currentOperation];
3210 float scale = [op _web_pageSetupScaleFactor];
3211 NSPrintInfo *printInfo = [op printInfo];
3212 NSSize paperSize = [printInfo paperSize];
3213 float headerFooterLeft = [printInfo leftMargin]/scale;
3214 float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
3215 NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] ,
3216 headerFooterWidth, [self _footerHeight]);
3217 NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale,
3218 headerFooterWidth, [self _headerHeight]);
3220 [self _drawHeaderInRect:headerRect];
3221 [self _drawFooterInRect:footerRect];
3225 @implementation WebView (WebDebugBinding)
3227 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
3229 LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
3230 [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
3233 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
3235 LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
3236 [super removeObserver:anObserver forKeyPath:keyPath];
3241 //==========================================================================================
3244 @implementation WebView (WebViewCSS)
3246 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
3248 // FIXME: is this the best level for this conversion?
3249 if (pseudoElement == nil)
3250 pseudoElement = @"";
3252 return [[element ownerDocument] getComputedStyle:element pseudoElement:pseudoElement];
3257 @implementation WebView (WebViewEditing)
3259 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
3261 Page* page = core(self);
3264 return kit(page->mainFrame()->editor()->rangeForPoint(IntPoint([self convertPoint:point toView:nil])).get());
3267 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
3269 // 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
3270 if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_APERTURE_QUIRK) && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Aperture"])
3272 return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
3275 - (BOOL)maintainsInactiveSelection
3280 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
3282 Frame* coreFrame = core([self _selectedOrMainFrame]);
3287 coreFrame->selectionController()->clear();
3289 // Derive the frame to use from the range passed in.
3290 // Using _bridgeForSelectedOrMainFrame could give us a different document than
3291 // the one the range uses.
3292 coreFrame = core([range startContainer])->document()->frame();
3296 coreFrame->selectionController()->setSelectedRange([range _range], core(selectionAffinity), true);
3300 - (DOMRange *)selectedDOMRange
3302 Frame* coreFrame = core([self _selectedOrMainFrame]);
3305 return kit(coreFrame->selectionController()->toRange().get());
3308 - (NSSelectionAffinity)selectionAffinity
3310 Frame* coreFrame = core([self _selectedOrMainFrame]);
3312 return NSSelectionAffinityDownstream;
3313 return kit(coreFrame->selectionController()->affinity());
3316 - (void)setEditable:(BOOL)flag
3318 if (_private->editable != flag) {
3319 _private->editable = flag;
3320 if (!_private->tabKeyCyclesThroughElementsChanged && _private->page)
3321 _private->page->setTabKeyCyclesThroughElements(!flag);
3322 Frame* mainFrame = [[[self mainFrame] _bridge] _frame];
3325 mainFrame->applyEditingStyleToBodyElement();
3326 // If the WebView is made editable and the selection is empty, set it to something.
3327 if (![self selectedDOMRange])
3328 mainFrame->setSelectionFromNone();
3330 mainFrame->removeEditingStyleFromBodyElement();
3337 return _private->editable;
3340 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
3342 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3343 // change the API to allow this.
3344 [[self _bridgeForSelectedOrMainFrame] setTypingStyle:style withUndoAction:EditActionUnspecified];
3347 - (DOMCSSStyleDeclaration *)typingStyle
3349 return [[self _bridgeForSelectedOrMainFrame] typingStyle];
3352 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
3354 _private->smartInsertDeleteEnabled = flag;
3357 - (BOOL)smartInsertDeleteEnabled
3359 return _private->smartInsertDeleteEnabled;
3362 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
3364 if (continuousSpellCheckingEnabled != flag) {
3365 continuousSpellCheckingEnabled = flag;
3366 [[NSUserDefaults standardUserDefaults] setBool:continuousSpellCheckingEnabled forKey:WebContinuousSpellCheckingEnabled];
3369 if ([self isContinuousSpellCheckingEnabled]) {
3370 [[self class] _preflightSpellChecker];
3372 [[self mainFrame] _unmarkAllMisspellings];
3376 - (BOOL)isContinuousSpellCheckingEnabled
3378 return (continuousSpellCheckingEnabled && [self _continuousCheckingAllowed]);
3381 - (NSInteger)spellCheckerDocumentTag
3383 if (!_private->hasSpellCheckerDocumentTag) {
3384 _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3385 _private->hasSpellCheckerDocumentTag = YES;
3387 return _private->spellCheckerDocumentTag;
3390 - (NSUndoManager *)undoManager
3392 if (!_private->allowsUndo)
3395 NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
3399 return [super undoManager];
3402 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
3404 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3405 if ([_private->editingDelegate respondsToSelector:selector])
3406 [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
3409 - (void)setEditingDelegate:(id)delegate
3411 if (_private->editingDelegate == delegate)
3414 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3416 // remove notifications from current delegate
3417 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
3418 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
3419 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
3420 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
3421 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
3423 _private->editingDelegate = delegate;
3424 [_private->editingDelegateForwarder release];
3425 _private->editingDelegateForwarder = nil;
3427 // add notifications for new delegate
3428 [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
3429 [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
3430 [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
3431 [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
3432 [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
3435 - (id)editingDelegate
3437 return _private->editingDelegate;
3440 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
3442 // FIXME: Should this really be attached to the document with the current selection?
3443 DOMCSSStyleDeclaration *decl = [[[self _selectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
3444 [decl setCssText:text];
3450 @implementation WebView (WebViewGrammarChecking)
3452 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3453 - (BOOL)isGrammarCheckingEnabled
3455 #ifdef BUILDING_ON_TIGER
3458 return grammarCheckingEnabled;
3462 #ifndef BUILDING_ON_TIGER
3463 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3464 - (void)setGrammarCheckingEnabled:(BOOL)flag
3466 if (grammarCheckingEnabled == flag)
3469 grammarCheckingEnabled = flag;
3470 [[NSUserDefaults standardUserDefaults] setBool:grammarCheckingEnabled forKey:WebGrammarCheckingEnabled];
3472 // FIXME 4811447: workaround for lack of API
3473 NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
3474 if ([spellChecker respondsToSelector:@selector(_updateGrammar)])
3475 [spellChecker performSelector:@selector(_updateGrammar)];
3477 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3478 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3480 if (![self isGrammarCheckingEnabled])
3481 [[self mainFrame] _unmarkAllBadGrammar];
3484 // FIXME: This method should be merged into WebIBActions when we're not in API freeze
3485 - (void)toggleGrammarChecking:(id)sender
3487 [self setGrammarCheckingEnabled:![self isGrammarCheckingEnabled]];
3493 @implementation WebView (WebViewUndoableEditing)
3495 - (void)replaceSelectionWithNode:(DOMNode *)node
3497 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:NO];
3500 - (void)replaceSelectionWithText:(NSString *)text
3502 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
3505 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
3507 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
3510 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3512 [[[[self _bridgeForSelectedOrMainFrame] webFrame] _dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3515 - (void)deleteSelection
3517 WebFrame *webFrame = [self _selectedOrMainFrame];
3518 Frame* coreFrame = core(webFrame);
3520 coreFrame->editor()->deleteSelectionWithSmartDelete([(WebHTMLView *)[[webFrame frameView] documentView] _canSmartCopyOrDelete]);
3523 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3525 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3526 // change the API to allow this.
3527 WebFrame *webFrame = [self _selectedOrMainFrame];
3528 Frame* coreFrame = core(webFrame);
3530 coreFrame->editor()->applyStyle(core(style));
3535 @implementation WebView (WebViewEditingActions)
3537 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3539 static BOOL reentered = NO;
3541 [[self nextResponder] tryToPerform:selector with:parameter];
3545 // There are two possibilities here.
3547 // One is that WebView has been called in its role as part of the responder chain.
3548 // In that case, it's fine to call the first responder and end up calling down the
3549 // responder chain again. Later we will return here with reentered = YES and continue
3550 // past the WebView.
3552 // The other is that we are being called directly, in which case we want to pass the
3553 // selector down to the view inside us that can handle it, and continue down the
3554 // responder chain as usual.
3556 // Pass this selector down to the first responder.
3557 NSResponder *responder = [self _responderForResponderOperations];
3559 [responder tryToPerform:selector with:parameter];
3563 #define FORWARD(name) \
3564 - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3566 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3568 - (void)insertText:(NSString *)text
3570 [self _performResponderOperation:_cmd with:text];
3575 @implementation WebView (WebViewEditingInMail)
3577 - (void)_insertNewlineInQuotedContent;
3579 [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3582 - (void)_replaceSelectionWithNode:(DOMNode *)node matchStyle:(BOOL)matchStyle
3584 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:matchStyle];
3589 static WebFrameView *containingFrameView(NSView *view)
3591 while (view && ![view isKindOfClass:[WebFrameView class]])
3592 view = [view superview];
3593 return (WebFrameView *)view;
3596 @implementation WebView (WebFileInternal)
3598 + (void)_setCacheModel:(WebCacheModel)cacheModel
3600 if (s_didSetCacheModel && cacheModel == s_cacheModel)
3603 NSString *nsurlCacheDirectory = [(NSString *)WKCopyFoundationCacheDirectory() autorelease];
3604 if (!nsurlCacheDirectory)
3605 nsurlCacheDirectory = NSHomeDirectory();
3607 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
3608 // count doesn't align exactly to a megabyte boundary.
3609 vm_size_t memSize = WebMemorySize() / 1024 / 1000;
3610 unsigned long long diskFreeSize = WebVolumeFreeSize(nsurlCacheDirectory) / 1024 / 1000;
3611 NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
3613 unsigned cacheTotalCapacity = 0;
3614 unsigned cacheMinDeadCapacity = 0;
3615 unsigned cacheMaxDeadCapacity = 0;
3617 unsigned pageCacheCapacity = 0;
3619 NSUInteger nsurlCacheMemoryCapacity = 0;
3620 NSUInteger nsurlCacheDiskCapacity = 0;
3622 switch (cacheModel) {
3623 case WebCacheModelDocumentViewer: {
3624 // Page cache capacity (in pages)
3625 pageCacheCapacity = 0;
3627 // Object cache capacities (in bytes)
3628 if (memSize >= 4096)
3629 cacheTotalCapacity = 256 * 1024 * 1024;
3630 else if (memSize >= 3072)
3631 cacheTotalCapacity = 192 * 1024 * 1024;
3632 else if (memSize >= 2048)
3633 cacheTotalCapacity = 128 * 1024 * 1024;
3634 else if (memSize >= 1536)
3635 cacheTotalCapacity = 86 * 1024 * 1024;
3636 else if (memSize >= 1024)
3637 cacheTotalCapacity = 64 * 1024 * 1024;
3638 else if (memSize >= 512)
3639 cacheTotalCapacity = 32 * 1024 * 1024;
3640 else if (memSize >= 256)
3641 cacheTotalCapacity = 16 * 1024 * 1024;
3643 cacheMinDeadCapacity = 0;
3644 cacheMaxDeadCapacity = 0;
3646 // Foundation memory cache capacity (in bytes)
3647 nsurlCacheMemoryCapacity = 0;
3649 // Foundation disk cache capacity (in bytes)
3650 nsurlCacheDiskCapacity = [nsurlCache diskCapacity];
3654 case WebCacheModelDocumentBrowser: {
3655 // Page cache capacity (in pages)
3656 if (memSize >= 1024)
3657 pageCacheCapacity = 3;
3658 else if (memSize >= 512)
3659 pageCacheCapacity = 2;
3660 else if (memSize >= 256)
3661 pageCacheCapacity = 1;
3663 pageCacheCapacity = 0;
3665 // Object cache capacities (in bytes)
3666 if (memSize >= 4096)
3667 cacheTotalCapacity = 256 * 1024 * 1024;
3668 else if (memSize >= 3072)
3669 cacheTotalCapacity = 192 * 1024 * 1024;
3670 else if (memSize >= 2048)
3671 cacheTotalCapacity = 128 * 1024 * 1024;
3672 else if (memSize >= 1536)
3673 cacheTotalCapacity = 86 * 1024 * 1024;
3674 else if (memSize >= 1024)
3675 cacheTotalCapacity = 64 * 1024 * 1024;
3676 else if (memSize >= 512)
3677 cacheTotalCapacity = 32 * 1024 * 1024;
3678 else if (memSize >= 256)
3679 cacheTotalCapacity = 16 * 1024 * 1024;
3681 cacheMinDeadCapacity = cacheTotalCapacity / 8;
3682 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
3684 // Foundation memory cache capacity (in bytes)