2 * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #import "WebViewInternal.h"
31 #import <JavaScriptCore/Assertions.h>
32 #import "WebBackForwardList.h"
33 #import "WebBaseNetscapePluginView.h"
34 #import "WebDOMOperationsPrivate.h"
35 #import "WebDashboardRegion.h"
36 #import "WebDataProtocol.h"
37 #import "WebDataSourceInternal.h"
38 #import "WebDefaultEditingDelegate.h"
39 #import "WebDefaultFrameLoadDelegate.h"
40 #import "WebDefaultPolicyDelegate.h"
41 #import "WebDefaultResourceLoadDelegate.h"
42 #import "WebDefaultScriptDebugDelegate.h"
43 #import "WebDefaultUIDelegate.h"
44 #import "WebDocument.h"
45 #import "WebDocumentInternal.h"
46 #import "WebDownload.h"
47 #import "WebDownloadInternal.h"
48 #import "WebDynamicScrollBarsView.h"
49 #import "WebEditingDelegate.h"
50 #import "WebFormDelegatePrivate.h"
51 #import "WebFrameBridge.h"
52 #import "WebFrameInternal.h"
53 #import "WebFrameLoader.h"
54 #import "WebFrameViewInternal.h"
55 #import "WebHTMLRepresentation.h"
56 #import "WebHTMLViewInternal.h"
57 #import "WebHistoryItemPrivate.h"
58 #import "WebIconDatabase.h"
59 #import "WebInspector.h"
60 #import "WebKitErrors.h"
61 #import "WebKitLogging.h"
62 #import "WebKitNSStringExtras.h"
63 #import "WebKitStatisticsPrivate.h"
64 #import "WebLocalizableStrings.h"
65 #import "WebNSDataExtras.h"
66 #import "WebNSDataExtrasPrivate.h"
67 #import "WebNSDictionaryExtras.h"
68 #import "WebNSEventExtras.h"
69 #import "WebNSObjectExtras.h"
70 #import "WebNSPasteboardExtras.h"
71 #import "WebNSPrintOperationExtras.h"
72 #import "WebNSURLExtras.h"
73 #import "WebNSURLRequestExtras.h"
74 #import "WebNSUserDefaultsExtras.h"
75 #import "WebNSViewExtras.h"
76 #import "WebPageBridge.h"
77 #import "WebPDFView.h"
78 #import "WebPluginDatabase.h"
79 #import "WebPolicyDelegate.h"
80 #import "WebPreferencesPrivate.h"
81 #import "WebResourceLoadDelegate.h"
82 #import "WebScriptDebugDelegatePrivate.h"
83 #import "WebScriptDebugServerPrivate.h"
84 #import "WebUIDelegate.h"
85 #import "WebUIDelegatePrivate.h"
86 #import <CoreFoundation/CFSet.h>
87 #import <Foundation/NSURLConnection.h>
88 #import <WebCore/WebCoreEncodings.h>
89 #import <WebCore/WebCoreFrameBridge.h>
90 #import <WebCore/WebCoreSettings.h>
91 #import <WebCore/WebCoreView.h>
92 #import <WebKit/DOM.h>
93 #import <WebKit/DOMPrivate.h>
94 #import <WebKit/DOMExtensions.h>
95 #import <WebKitSystemInterface.h>
96 #import <objc/objc-runtime.h>
98 #import <WebCore/WebCoreTextRenderer.h>
100 #if defined(__ppc__) || defined(__ppc64__)
101 #define PROCESSOR "PPC"
102 #elif defined(__i386__) || defined(__x86_64__)
103 #define PROCESSOR "Intel"
105 #error Unknown architecture
108 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
110 macro(alignJustified) \
113 macro(capitalizeWord) \
114 macro(centerSelectionInVisibleArea) \
115 macro(changeAttributes) \
117 macro(changeDocumentBackgroundColor) \
119 macro(checkSpelling) \
125 macro(deleteBackward) \
126 macro(deleteBackwardByDecomposingPreviousCharacter) \
127 macro(deleteForward) \
128 macro(deleteToBeginningOfLine) \
129 macro(deleteToBeginningOfParagraph) \
130 macro(deleteToEndOfLine) \
131 macro(deleteToEndOfParagraph) \
132 macro(deleteWordBackward) \
133 macro(deleteWordForward) \
134 macro(ignoreSpelling) \
136 macro(insertBacktab) \
137 macro(insertNewline) \
138 macro(insertNewlineIgnoringFieldEditor) \
139 macro(insertParagraphSeparator) \
141 macro(insertTabIgnoringFieldEditor) \
142 macro(lowercaseWord) \
143 macro(moveBackward) \
144 macro(moveBackwardAndModifySelection) \
146 macro(moveDownAndModifySelection) \
148 macro(moveForwardAndModifySelection) \
150 macro(moveLeftAndModifySelection) \
152 macro(moveRightAndModifySelection) \
153 macro(moveToBeginningOfDocument) \
154 macro(moveToBeginningOfDocumentAndModifySelection) \
155 macro(moveToBeginningOfSentence) \
156 macro(moveToBeginningOfSentenceAndModifySelection) \
157 macro(moveToBeginningOfLine) \
158 macro(moveToBeginningOfLineAndModifySelection) \
159 macro(moveToBeginningOfParagraph) \
160 macro(moveToBeginningOfParagraphAndModifySelection) \
161 macro(moveToEndOfDocument) \
162 macro(moveToEndOfDocumentAndModifySelection) \
163 macro(moveToEndOfLine) \
164 macro(moveToEndOfLineAndModifySelection) \
165 macro(moveToEndOfParagraph) \
166 macro(moveToEndOfParagraphAndModifySelection) \
167 macro(moveToEndOfSentence) \
168 macro(moveToEndOfSentenceAndModifySelection) \
170 macro(moveUpAndModifySelection) \
171 macro(moveWordBackward) \
172 macro(moveWordBackwardAndModifySelection) \
173 macro(moveWordForward) \
174 macro(moveWordForwardAndModifySelection) \
175 macro(moveWordLeft) \
176 macro(moveWordLeftAndModifySelection) \
177 macro(moveWordRight) \
178 macro(moveWordRightAndModifySelection) \
182 macro(pasteAsPlainText) \
183 macro(pasteAsRichText) \
185 macro(performFindPanelAction) \
186 macro(scrollLineDown) \
187 macro(scrollLineUp) \
188 macro(scrollPageDown) \
189 macro(scrollPageUp) \
190 macro(scrollToBeginningOfDocument) \
191 macro(scrollToEndOfDocument) \
194 macro(selectSentence) \
196 macro(selectParagraph) \
197 macro(showGuessPanel) \
198 macro(startSpeaking) \
199 macro(stopSpeaking) \
204 macro(uppercaseWord) \
206 macro(yankAndSelect) \
208 @interface NSSpellChecker (AppKitSecretsIKnow)
209 - (void)_preflightChosenSpellServer;
212 @interface NSView (AppKitSecretsIKnow)
213 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
214 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
215 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
218 @interface WebViewPrivate : NSObject
221 WebPageBridge *_pageBridge;
224 id UIDelegateForwarder;
225 id resourceProgressDelegate;
226 id resourceProgressDelegateForwarder;
229 id policyDelegateForwarder;
230 id frameLoadDelegate;
231 id frameLoadDelegateForwarder;
232 id <WebFormDelegate> formDelegate;
234 id editingDelegateForwarder;
235 id scriptDebugDelegate;
236 id scriptDebugDelegateForwarder;
238 WebBackForwardList *backForwardList;
239 BOOL useBackForwardList;
241 float textSizeMultiplier;
243 NSString *applicationNameForUserAgent;
245 BOOL userAgentOverridden;
247 BOOL defersCallbacks;
249 WebPreferences *preferences;
250 WebCoreSettings *settings;
252 BOOL lastElementWasNonNil;
254 NSWindow *hostWindow;
256 int programmaticFocusCount;
258 WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
260 long long totalPageAndResourceBytesToLoad;
261 long long totalBytesReceived;
262 double progressValue;
263 double lastNotifiedProgressValue;
264 double lastNotifiedProgressTime;
265 double progressNotificationInterval;
266 double progressNotificationTimeInterval;
267 BOOL finalProgressChangedSent;
268 WebFrame *originatingProgressFrame;
270 int numProgressTrackedFrames;
271 NSMutableDictionary *progressItems;
273 void *observationInfo;
276 BOOL shouldCloseWithWindow;
277 BOOL mainFrameDocumentReady;
278 BOOL drawsBackground;
281 BOOL tabKeyCyclesThroughElements;
282 BOOL tabKeyCyclesThroughElementsChanged;
284 NSString *mediaStyle;
286 NSView <WebDocumentDragging> *draggingDocumentView;
287 unsigned int dragDestinationActionMask;
289 BOOL hasSpellCheckerDocumentTag;
290 WebNSInteger spellCheckerDocumentTag;
292 BOOL continuousSpellCheckingEnabled;
293 BOOL smartInsertDeleteEnabled;
295 BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
296 BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
297 BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
298 BOOL dashboardBehaviorAllowWheelScrolling;
300 BOOL selectWordBeforeMenuEvent;
302 WebPluginDatabase *pluginDatabase;
306 @interface WebView (WebFileInternal)
307 - (WebFrame *)_selectedOrMainFrame;
308 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame;
310 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
311 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point;
312 - (WebFrame *)_focusedFrame;
313 + (void)_preflightSpellChecker;
314 - (BOOL)_continuousCheckingAllowed;
315 - (NSResponder *)_responderForResponderOperations;
316 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor;
319 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
320 NSString *WebElementFrameKey = @"WebElementFrame";
321 NSString *WebElementImageKey = @"WebElementImage";
322 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
323 NSString *WebElementImageRectKey = @"WebElementImageRect";
324 NSString *WebElementImageURLKey = @"WebElementImageURL";
325 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
326 NSString *WebElementTitleKey = @"WebElementTitle";
327 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
328 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
329 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
330 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
332 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
333 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
334 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
336 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
337 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
338 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
339 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
340 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
342 enum { WebViewVersion = 2 };
344 #define timedLayoutSize 4096
346 static NSMutableSet *schemesWithRepresentationsSet;
348 NSString *_WebCanGoBackKey = @"canGoBack";
349 NSString *_WebCanGoForwardKey = @"canGoForward";
350 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
351 NSString *_WebIsLoadingKey = @"isLoading";
352 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
353 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
354 NSString *_WebMainFrameURLKey = @"mainFrameURL";
355 NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
357 @interface WebProgressItem : NSObject
360 long long bytesReceived;
361 long long estimatedLength;
365 @implementation WebProgressItem
368 @implementation WebViewPrivate
376 backForwardList = [[WebBackForwardList alloc] init];
377 textSizeMultiplier = 1;
378 progressNotificationInterval = 0.02;
379 progressNotificationTimeInterval = 0.1;
380 settings = [[WebCoreSettings alloc] init];
381 dashboardBehaviorAllowWheelScrolling = YES;
382 tabKeyCyclesThroughElements = YES;
383 shouldCloseWithWindow = objc_collecting_enabled();
390 ASSERT(!_pageBridge);
391 ASSERT(draggingDocumentView == nil);
393 [backForwardList release];
394 [applicationNameForUserAgent release];
397 [preferences release];
399 [hostWindow release];
401 [policyDelegateForwarder release];
402 [resourceProgressDelegateForwarder release];
403 [UIDelegateForwarder release];
404 [frameLoadDelegateForwarder release];
405 [editingDelegateForwarder release];
406 [scriptDebugDelegateForwarder release];
408 [progressItems release];
410 [mediaStyle release];
417 @implementation WebView (AllWebViews)
419 static CFSetCallBacks NonRetainingSetCallbacks = {
428 static CFMutableSetRef allWebViewsSet;
430 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
435 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
438 - (void)_removeFromAllWebViewsSet
441 CFSetRemoveValue(allWebViewsSet, self);
444 - (void)_addToAllWebViewsSet
447 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
449 CFSetSetValue(allWebViewsSet, self);
454 @implementation WebView (WebPrivate)
456 #ifdef DEBUG_WIDGET_DRAWING
457 static bool debugWidget = true;
458 - (void)drawRect:(NSRect)rect
460 [[NSColor blueColor] set];
463 NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
466 while (debugWidget) {
471 NSLog (@"%s: rect: (%0.f,%0.f) %0.f %0.f, htmlViewRect: (%0.f,%0.f) %0.f %0.f\n",
472 __PRETTY_FUNCTION__, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
473 htmlViewRect.origin.x, htmlViewRect.origin.y, htmlViewRect.size.width, htmlViewRect.size.height
476 [super drawRect:rect];
480 + (BOOL)_developerExtrasEnabled
483 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
484 BOOL enableDebugger = [defaults boolForKey:@"WebKitDeveloperExtras"];
486 enableDebugger = [defaults boolForKey:@"IncludeDebugMenu"];
487 return enableDebugger;
489 return YES; // always enable in debug builds
493 + (BOOL)_scriptDebuggerEnabled
496 return [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitScriptDebuggerEnabled"];
498 return YES; // always enable in debug builds
502 + (NSArray *)_supportedMIMETypes
504 // Load the plug-in DB allowing plug-ins to install types.
505 [WebPluginDatabase installedPlugins];
506 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
509 + (NSArray *)_supportedFileExtensions
511 NSMutableSet *extensions = [[NSMutableSet alloc] init];
512 NSArray *MIMETypes = [self _supportedMIMETypes];
513 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
515 while ((MIMEType = [enumerator nextObject]) != nil) {
516 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
517 if (extensionsForType) {
518 [extensions addObjectsFromArray:extensionsForType];
521 NSArray *uniqueExtensions = [extensions allObjects];
522 [extensions release];
523 return uniqueExtensions;
526 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
528 MIMEType = [MIMEType lowercaseString];
529 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
530 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
532 if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
533 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
534 // Load the plug-in DB allowing plug-ins to install types.
535 [WebPluginDatabase installedPlugins];
537 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
538 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
539 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
542 if (viewClass && repClass) {
543 // Special-case WebHTMLView for text types that shouldn't be shown.
544 if (viewClass == [WebHTMLView class] &&
545 repClass == [WebHTMLRepresentation class] &&
546 [[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType]) {
559 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
561 if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType])
564 if (_private->pluginDatabase) {
565 WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
568 *vClass = [WebHTMLView class];
570 *rClass = [WebHTMLRepresentation class];
578 + (void)_setAlwaysUseATSU:(BOOL)f
580 WebCoreSetAlwaysUseATSU(f);
583 + (BOOL)canShowFile:(NSString *)path
585 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
588 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
590 return WKGetPreferredExtensionForMIMEType(type);
595 if (!_private || _private->closed)
597 _private->closed = YES;
599 [self _removeFromAllWebViewsSet];
601 [self setGroupName:nil];
602 [self setHostWindow:nil];
603 [self setDownloadDelegate:nil];
604 [self setEditingDelegate:nil];
605 [self setFrameLoadDelegate:nil];
606 [self setPolicyDelegate:nil];
607 [self setResourceLoadDelegate:nil];
608 [self setScriptDebugDelegate:nil];
609 [self setUIDelegate:nil];
611 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
612 [self removeDragCaret];
614 [[self mainFrame] _detachFromParent];
615 [_private->_pageBridge close];
616 [_private->_pageBridge release];
617 _private->_pageBridge = nil;
619 // Clear the page cache so we call destroy on all the plug-ins in the page cache to break any retain cycles.
620 // See comment in [WebHistoryItem _releaseAllPendingPageCaches] for more information.
621 if (_private->backForwardList) {
622 [_private->backForwardList _close];
623 [_private->backForwardList release];
624 _private->backForwardList = nil;
627 if (_private->hasSpellCheckerDocumentTag) {
628 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
629 _private->hasSpellCheckerDocumentTag = NO;
632 if (_private->pluginDatabase) {
633 [_private->pluginDatabase close];
634 [_private->pluginDatabase release];
635 _private->pluginDatabase = nil;
638 [[NSNotificationCenter defaultCenter] removeObserver:self];
640 [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
643 + (NSString *)_MIMETypeForFile:(NSString *)path
645 NSString *extension = [path pathExtension];
646 NSString *MIMEType = nil;
648 // Get the MIME type from the extension.
649 if ([extension length] != 0) {
650 MIMEType = WKGetMIMETypeForExtension(extension);
653 // If we can't get a known MIME type from the extension, sniff.
654 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
655 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
656 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
658 if ([data length] != 0) {
659 MIMEType = [data _webkit_guessedMIMEType];
661 if ([MIMEType length] == 0) {
662 MIMEType = @"application/octet-stream";
669 - (void)_downloadURL:(NSURL *)URL
673 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
674 [WebDownload _downloadWithRequest:request
675 delegate:_private->downloadDelegate
680 - (BOOL)defersCallbacks
682 return _private->defersCallbacks;
685 - (void)setDefersCallbacks:(BOOL)defers
687 if (defers == _private->defersCallbacks) {
691 _private->defersCallbacks = defers;
692 [[self mainFrame] _defersCallbacksChanged];
695 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
697 id wd = [self UIDelegate];
698 WebView *newWindowWebView = nil;
699 if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
700 newWindowWebView = [wd webView:self createWebViewWithRequest:request];
702 newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
705 [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
707 return newWindowWebView;
710 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
712 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
713 webView:self contextMenuItemsForElement:element defaultMenuItems:items];
714 NSArray *menuItems = defaultMenuItems;
718 DOMNode* node = [element objectForKey:WebElementDOMNodeKey];
719 BOOL elementIsTextField = [node isKindOfClass:[DOMHTMLInputElement class]] && [(DOMHTMLInputElement*)node _isTextField];
720 BOOL elementIsTextArea = [node isKindOfClass:[DOMHTMLTextAreaElement class]];
721 if (_private->UIDelegate && !elementIsTextField && !elementIsTextArea) {
722 id cd = _private->UIDelegate;
724 if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)]) {
725 menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
727 // Versions of Mail compiled with older WebKits will end up without three context menu items, though
728 // with the separators between them. Here we check for that problem and reinsert the three missing
729 // items. This shouldn't affect any clients other than Mail since the tags for the three items
730 // were not public API. We can remove this code when we no longer support previously-built versions
731 // of Mail on Tiger. See 4498606 for more details.
732 if ([menuItems count] && ([[defaultMenuItems objectAtIndex:0] tag] == WebMenuItemTagSearchInSpotlight) && ([[menuItems objectAtIndex:0] isSeparatorItem])) {
733 ASSERT([[menuItems objectAtIndex:1] isSeparatorItem]);
734 ASSERT([[defaultMenuItems objectAtIndex:1] tag] == WebMenuItemTagSearchWeb);
735 ASSERT([[defaultMenuItems objectAtIndex:2] isSeparatorItem]);
736 ASSERT([[defaultMenuItems objectAtIndex:3] tag] == WebMenuItemTagLookUpInDictionary);
737 ASSERT([[defaultMenuItems objectAtIndex:4] isSeparatorItem]);
738 NSMutableArray *mutableMenuItems = [NSMutableArray arrayWithArray:menuItems];
739 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:0] atIndex:0];
740 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:1] atIndex:1];
741 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:3] atIndex:3];
742 menuItems = mutableMenuItems;
747 if (menuItems && [menuItems count] > 0) {
748 menu = [[[NSMenu alloc] init] autorelease];
750 for (i=0; i<[menuItems count]; i++) {
751 [menu addItem:[menuItems objectAtIndex:i]];
755 // optionally add the Inspect Element menu item it if preference is set or in debug builds
756 // and only showing the menu item if we are working with a WebHTMLView
757 WebFrame *webFrame = [element objectForKey:WebElementFrameKey];
758 if ([WebView _developerExtrasEnabled] && [[[webFrame frameView] documentView] isKindOfClass:[WebHTMLView class]]) {
760 menu = [[[NSMenu alloc] init] autorelease];
761 else if ([menu numberOfItems])
762 [menu addItem:[NSMenuItem separatorItem]];
763 NSMenuItem *menuItem = [[[NSMenuItem alloc] init] autorelease];
764 [menuItem setAction:@selector(_inspectElement:)];
765 [menuItem setTitle:UI_STRING("Inspect Element", "Inspect Element context menu item")];
766 [menuItem setRepresentedObject:element];
767 [menu addItem:menuItem];
773 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(WebNSUInteger)modifierFlags
775 // When the mouse isn't over this view at all, we'll get called with a dictionary of nil over
776 // and over again. So it's a good idea to catch that here and not send multiple calls to the delegate
779 if (dictionary && _private->lastElementWasNonNil) {
780 [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
782 _private->lastElementWasNonNil = dictionary != nil;
785 - (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
787 // We never go back/forward on a per-frame basis, so the target must be the main frame
788 //ASSERT([item target] == nil || [self _findFrameNamed:[item target]] == [self mainFrame]);
790 // abort any current load if we're going back/forward
791 [[self mainFrame] stopLoading];
792 [[self mainFrame] _goToItem:item withLoadType:type];
795 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
797 // It turns out the right combination of behavior is done with the back/forward load
798 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
799 // in the back forward list, and go to the current one.
801 WebBackForwardList *bfList = [self backForwardList];
802 ASSERT(![bfList currentItem]); // destination list should be empty
804 WebBackForwardList *otherBFList = [otherView backForwardList];
805 if (![otherBFList currentItem]) {
806 return; // empty back forward list, bail
809 WebHistoryItem *newItemToGoTo = nil;
810 int lastItemIndex = [otherBFList forwardListCount];
812 for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
814 // If this item is showing , save away its current scroll and form state,
815 // since that might have changed since loading and it is normally not saved
816 // until we leave that page.
817 [[otherView mainFrame] _saveDocumentAndScrollState];
819 WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
820 [bfList addItem:newItem];
822 newItemToGoTo = newItem;
826 [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
829 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
831 _private->formDelegate = delegate;
834 - (id<WebFormDelegate>)_formDelegate
836 if (!_private->formDelegate) {
837 // create lazily, to give the client a chance to set one before we bother to alloc the shared one
838 _private->formDelegate = [WebFormDelegate _sharedWebFormDelegate];
840 return _private->formDelegate;
843 - (WebCoreSettings *)_settings
845 return _private->settings;
848 - (void)_updateWebCoreSettingsFromPreferences:(WebPreferences *)preferences
850 [_private->settings setCursiveFontFamily:[preferences cursiveFontFamily]];
851 [_private->settings setDefaultFixedFontSize:[preferences defaultFixedFontSize]];
852 [_private->settings setDefaultFontSize:[preferences defaultFontSize]];
853 [_private->settings setDefaultTextEncoding:[preferences defaultTextEncodingName]];
854 [_private->settings setFantasyFontFamily:[preferences fantasyFontFamily]];
855 [_private->settings setFixedFontFamily:[preferences fixedFontFamily]];
856 [_private->settings setJavaEnabled:[preferences isJavaEnabled]];
857 [_private->settings setJavaScriptEnabled:[preferences isJavaScriptEnabled]];
858 [_private->settings setJavaScriptCanOpenWindowsAutomatically:[preferences javaScriptCanOpenWindowsAutomatically]];
859 [_private->settings setMinimumFontSize:[preferences minimumFontSize]];
860 [_private->settings setMinimumLogicalFontSize:[preferences minimumLogicalFontSize]];
861 [_private->settings setPluginsEnabled:[preferences arePlugInsEnabled]];
862 [_private->settings setPrivateBrowsingEnabled:[preferences privateBrowsingEnabled]];
863 [_private->settings setSansSerifFontFamily:[preferences sansSerifFontFamily]];
864 [_private->settings setSerifFontFamily:[preferences serifFontFamily]];
865 [_private->settings setStandardFontFamily:[preferences standardFontFamily]];
866 [_private->settings setWillLoadImagesAutomatically:[preferences loadsImagesAutomatically]];
868 if ([preferences userStyleSheetEnabled]) {
869 [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
871 [_private->settings setUserStyleSheetLocation:@""];
873 [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
874 [_private->settings setTextAreasAreResizable:[preferences textAreasAreResizable]];
877 - (void)_preferencesChangedNotification: (NSNotification *)notification
879 WebPreferences *preferences = (WebPreferences *)[notification object];
881 ASSERT(preferences == [self preferences]);
882 if (!_private->userAgentOverridden) {
883 [_private->userAgent release];
884 _private->userAgent = nil;
886 [self _updateWebCoreSettingsFromPreferences: preferences];
889 - _frameLoadDelegateForwarder
891 if (!_private->frameLoadDelegateForwarder)
892 _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate] defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
893 return _private->frameLoadDelegateForwarder;
896 - _resourceLoadDelegateForwarder
898 if (!_private->resourceProgressDelegateForwarder)
899 _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
900 return _private->resourceProgressDelegateForwarder;
903 - (void)_cacheResourceLoadDelegateImplementations
905 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
906 id delegate = [self resourceLoadDelegate];
908 cache->delegateImplementsDidCancelAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:)];
909 cache->delegateImplementsDidReceiveAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:)];
910 cache->delegateImplementsDidFinishLoadingFromDataSource = [delegate respondsToSelector:@selector(webView:resource:didFinishLoadingFromDataSource:)];
911 cache->delegateImplementsDidReceiveContentLength = [delegate respondsToSelector:@selector(webView:resource:didReceiveContentLength:fromDataSource:)];
912 cache->delegateImplementsDidReceiveResponse = [delegate respondsToSelector:@selector(webView:resource:didReceiveResponse:fromDataSource:)];
913 cache->delegateImplementsWillSendRequest = [delegate respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)];
914 cache->delegateImplementsIdentifierForRequest = [delegate respondsToSelector:@selector(webView:identifierForInitialRequest:fromDataSource:)];
917 - (WebResourceDelegateImplementationCache)_resourceLoadDelegateImplementations
919 return _private->resourceLoadDelegateImplementations;
922 - _policyDelegateForwarder
924 if (!_private->policyDelegateForwarder)
925 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
926 return _private->policyDelegateForwarder;
929 - _UIDelegateForwarder
931 if (!_private->UIDelegateForwarder)
932 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
933 return _private->UIDelegateForwarder;
936 - _editingDelegateForwarder
938 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
939 // Not sure if that is a bug or not.
942 if (!_private->editingDelegateForwarder)
943 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self editingDelegate] defaultTarget: [WebDefaultEditingDelegate sharedEditingDelegate] templateClass: [WebDefaultEditingDelegate class]];
944 return _private->editingDelegateForwarder;
947 - _scriptDebugDelegateForwarder
949 if (!_private->scriptDebugDelegateForwarder)
950 _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self scriptDebugDelegate] defaultTarget: [WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] templateClass: [WebDefaultScriptDebugDelegate class]];
951 return _private->scriptDebugDelegateForwarder;
956 [[self _UIDelegateForwarder] webViewClose:self];
959 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
961 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
962 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
965 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
967 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
968 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
970 // This is used to make _representationExistsForURLScheme faster.
971 // Without this set, we'd have to create the MIME type each time.
972 if (schemesWithRepresentationsSet == nil) {
973 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
975 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
978 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
980 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
983 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
985 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
988 + (BOOL)_canHandleRequest:(NSURLRequest *)request
990 if ([NSURLConnection canHandleRequest:request]) {
994 // We're always willing to load alternate content for unreachable URLs
995 if ([request _webDataRequestUnreachableURL]) {
999 return [self _representationExistsForURLScheme:[[request URL] scheme]];
1002 + (NSString *)_decodeData:(NSData *)data
1004 return [WebCoreEncodings decodeData:data];
1007 - (void)_pushPerformingProgrammaticFocus
1009 _private->programmaticFocusCount++;
1012 - (void)_popPerformingProgrammaticFocus
1014 _private->programmaticFocusCount--;
1017 - (BOOL)_isPerformingProgrammaticFocus
1019 return _private->programmaticFocusCount != 0;
1022 #define UnknownTotalBytes -1
1023 #define WebProgressItemDefaultEstimatedLength 1024*16
1025 - (void)_didChangeValueForKey: (NSString *)key
1027 LOG (Bindings, "calling didChangeValueForKey: %@", key);
1028 [self didChangeValueForKey: key];
1031 - (void)_willChangeValueForKey: (NSString *)key
1033 LOG (Bindings, "calling willChangeValueForKey: %@", key);
1034 [self willChangeValueForKey: key];
1037 // Always start progress at INITIAL_PROGRESS_VALUE. This helps provide feedback as
1038 // soon as a load starts.
1039 #define INITIAL_PROGRESS_VALUE 0.1
1040 // Similarly, always leave space at the end. This helps show the user that we're not done
1041 // until we're done.
1042 #define FINAL_PROGRESS_VALUE 1.0 - INITIAL_PROGRESS_VALUE
1044 - (void)_resetProgress
1046 [_private->progressItems release];
1047 _private->progressItems = nil;
1048 _private->totalPageAndResourceBytesToLoad = 0;
1049 _private->totalBytesReceived = 0;
1050 _private->progressValue = 0;
1051 _private->lastNotifiedProgressValue = 0;
1052 _private->lastNotifiedProgressTime = 0;
1053 _private->finalProgressChangedSent = NO;
1054 _private->numProgressTrackedFrames = 0;
1055 [_private->originatingProgressFrame release];
1056 _private->originatingProgressFrame = nil;
1058 - (void)_progressStarted:(WebFrame *)frame
1060 LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1061 [self _willChangeValueForKey: @"estimatedProgress"];
1062 if (_private->numProgressTrackedFrames == 0 || _private->originatingProgressFrame == frame){
1063 [self _resetProgress];
1064 _private->progressValue = INITIAL_PROGRESS_VALUE;
1065 _private->originatingProgressFrame = [frame retain];
1066 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressStartedNotification object:self];
1068 _private->numProgressTrackedFrames++;
1069 [self _didChangeValueForKey: @"estimatedProgress"];
1072 - (void)_finalProgressComplete
1076 // Before resetting progress value be sure to send client a least one notification
1077 // with final progress value.
1078 if (!_private->finalProgressChangedSent) {
1079 _private->progressValue = 1;
1080 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1083 [self _resetProgress];
1085 [self setMainFrameDocumentReady:YES]; // make sure this is turned on at this point
1086 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
1089 - (void)_progressCompleted:(WebFrame *)frame
1091 LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1093 if (_private->numProgressTrackedFrames <= 0)
1096 [self _willChangeValueForKey: @"estimatedProgress"];
1098 _private->numProgressTrackedFrames--;
1099 if (_private->numProgressTrackedFrames == 0 ||
1100 (frame == _private->originatingProgressFrame && _private->numProgressTrackedFrames != 0)){
1101 [self _finalProgressComplete];
1103 [self _didChangeValueForKey: @"estimatedProgress"];
1106 - (void)_incrementProgressForIdentifier:(id)identifier response:(NSURLResponse *)response;
1111 LOG (Progress, "_private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1113 if (_private->numProgressTrackedFrames <= 0)
1116 WebProgressItem *item = [[WebProgressItem alloc] init];
1121 long long length = [response expectedContentLength];
1123 length = WebProgressItemDefaultEstimatedLength;
1125 item->estimatedLength = length;
1126 _private->totalPageAndResourceBytesToLoad += length;
1128 if (!_private->progressItems)
1129 _private->progressItems = [[NSMutableDictionary alloc] init];
1131 [_private->progressItems _webkit_setObject:item forUncopiedKey:identifier];
1135 - (void)_incrementProgressForIdentifier:(id)identifier data:(NSData *)data
1140 WebProgressItem *item = [_private->progressItems objectForKey:identifier];
1145 [self _willChangeValueForKey: @"estimatedProgress"];
1147 unsigned bytesReceived = [data length];
1148 double increment, percentOfRemainingBytes;
1149 long long remainingBytes, estimatedBytesForPendingRequests;
1151 item->bytesReceived += bytesReceived;
1152 if (item->bytesReceived > item->estimatedLength){
1153 _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
1154 item->estimatedLength = item->bytesReceived*2;
1157 int numPendingOrLoadingRequests = [_private->originatingProgressFrame _numPendingOrLoadingRequests:YES];
1158 estimatedBytesForPendingRequests = WebProgressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
1159 remainingBytes = ((_private->totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - _private->totalBytesReceived);
1160 percentOfRemainingBytes = (double)bytesReceived / (double)remainingBytes;
1162 // Treat the first layout as the half-way point.
1163 double maxProgressValue = [_private->originatingProgressFrame _firstLayoutDone]
1164 ? FINAL_PROGRESS_VALUE
1166 increment = (maxProgressValue - _private->progressValue) * percentOfRemainingBytes;
1167 _private->progressValue += increment;
1168 if (_private->progressValue > maxProgressValue)
1169 _private->progressValue = maxProgressValue;
1170 ASSERT(_private->progressValue >= INITIAL_PROGRESS_VALUE);
1172 _private->totalBytesReceived += bytesReceived;
1174 double now = CFAbsoluteTimeGetCurrent();
1175 double notifiedProgressTimeDelta = now - _private->lastNotifiedProgressTime;
1177 LOG (Progress, "_private->progressValue %g, _private->numProgressTrackedFrames %d", _private->progressValue, _private->numProgressTrackedFrames);
1178 double notificationProgressDelta = _private->progressValue - _private->lastNotifiedProgressValue;
1179 if ((notificationProgressDelta >= _private->progressNotificationInterval ||
1180 notifiedProgressTimeDelta >= _private->progressNotificationTimeInterval) &&
1181 _private->numProgressTrackedFrames > 0) {
1182 if (!_private->finalProgressChangedSent) {
1183 if (_private->progressValue == 1)
1184 _private->finalProgressChangedSent = YES;
1185 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1186 _private->lastNotifiedProgressValue = _private->progressValue;
1187 _private->lastNotifiedProgressTime = now;
1191 [self _didChangeValueForKey: @"estimatedProgress"];
1194 - (void)_completeProgressForIdentifier:(id)identifier
1196 WebProgressItem *item = [_private->progressItems objectForKey:identifier];
1201 // Adjust the total expected bytes to account for any overage/underage.
1202 long long delta = item->bytesReceived - item->estimatedLength;
1203 _private->totalPageAndResourceBytesToLoad += delta;
1204 item->estimatedLength = item->bytesReceived;
1207 // Required to prevent automatic observer notifications.
1208 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1212 - (NSArray *)_declaredKeys {
1213 static NSArray *declaredKeys = nil;
1215 if (!declaredKeys) {
1216 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1219 return declaredKeys;
1222 - (void)setObservationInfo:(void *)info
1224 _private->observationInfo = info;
1227 - (void *)observationInfo
1229 return _private->observationInfo;
1232 - (void)_willChangeBackForwardKeys
1234 [self _willChangeValueForKey: _WebCanGoBackKey];
1235 [self _willChangeValueForKey: _WebCanGoForwardKey];
1238 - (void)_didChangeBackForwardKeys
1240 [self _didChangeValueForKey: _WebCanGoBackKey];
1241 [self _didChangeValueForKey: _WebCanGoForwardKey];
1244 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1246 [self _willChangeBackForwardKeys];
1247 if (frame == [self mainFrame]){
1248 // Force an observer update by sending a will/did.
1249 [self _willChangeValueForKey: _WebIsLoadingKey];
1250 [self _didChangeValueForKey: _WebIsLoadingKey];
1252 [self _willChangeValueForKey: _WebMainFrameURLKey];
1254 [NSApp setWindowsNeedUpdate:YES];
1257 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1259 if (frame == [self mainFrame]){
1260 [self _didChangeValueForKey: _WebMainFrameURLKey];
1262 [NSApp setWindowsNeedUpdate:YES];
1265 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1267 [self _didChangeBackForwardKeys];
1268 if (frame == [self mainFrame]){
1269 // Force an observer update by sending a will/did.
1270 [self _willChangeValueForKey: _WebIsLoadingKey];
1271 [self _didChangeValueForKey: _WebIsLoadingKey];
1273 [NSApp setWindowsNeedUpdate:YES];
1276 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1278 [self _didChangeBackForwardKeys];
1279 if (frame == [self mainFrame]){
1280 // Force an observer update by sending a will/did.
1281 [self _willChangeValueForKey: _WebIsLoadingKey];
1282 [self _didChangeValueForKey: _WebIsLoadingKey];
1284 [NSApp setWindowsNeedUpdate:YES];
1287 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1289 [self _didChangeBackForwardKeys];
1290 if (frame == [self mainFrame]){
1291 // Force an observer update by sending a will/did.
1292 [self _willChangeValueForKey: _WebIsLoadingKey];
1293 [self _didChangeValueForKey: _WebIsLoadingKey];
1295 [self _didChangeValueForKey: _WebMainFrameURLKey];
1297 [NSApp setWindowsNeedUpdate:YES];
1300 - (void)_reloadForPluginChanges
1302 [[self mainFrame] _reloadForPluginChanges];
1305 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1307 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1308 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1309 NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1311 return cachedResponse;
1314 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1316 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1317 DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1318 [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1320 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1321 title:[element objectForKey:WebElementImageAltStringKey]
1322 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1326 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1328 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1329 andTitle:[element objectForKey:WebElementLinkLabelKey]
1333 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1335 _private->initiatedDrag = initiatedDrag;
1338 #define DASHBOARD_CONTROL_LABEL @"control"
1340 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1342 // Add scroller regions for NSScroller and KWQScrollBar
1343 int i, count = [views count];
1345 for (i = 0; i < count; i++) {
1346 NSView *aView = [views objectAtIndex:i];
1348 if ([aView isKindOfClass:[NSScroller class]] ||
1349 [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1350 NSRect bounds = [aView bounds];
1351 NSRect adjustedBounds;
1352 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1353 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1355 // AppKit has horrible hack of placing absent scrollers at -100,-100
1356 if (adjustedBounds.origin.y == -100)
1358 adjustedBounds.size = bounds.size;
1359 NSRect clip = [aView visibleRect];
1360 NSRect adjustedClip;
1361 adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1362 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1363 adjustedClip.size = clip.size;
1364 WebDashboardRegion *aRegion =
1365 [[[WebDashboardRegion alloc] initWithRect:adjustedBounds
1366 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1367 NSMutableArray *scrollerRegions;
1368 scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1369 if (!scrollerRegions) {
1370 scrollerRegions = [NSMutableArray array];
1371 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1373 [scrollerRegions addObject:aRegion];
1375 [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1379 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1381 [self _addScrollerDashboardRegions:regions from:[self subviews]];
1384 - (NSDictionary *)_dashboardRegions
1386 // Only return regions from main frame.
1387 NSMutableDictionary *regions = [[[self mainFrame] _bridge] dashboardRegions];
1388 [self _addScrollerDashboardRegions:regions];
1392 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag;
1395 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1396 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1399 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1400 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1403 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1404 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1407 case WebDashboardBehaviorAllowWheelScrolling: {
1408 _private->dashboardBehaviorAllowWheelScrolling = flag;
1414 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1417 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1418 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1420 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1421 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1423 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1424 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1426 case WebDashboardBehaviorAllowWheelScrolling: {
1427 return _private->dashboardBehaviorAllowWheelScrolling;
1433 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1435 [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:self resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:dataSource];
1438 + (void)_setShouldUseFontSmoothing:(BOOL)f
1440 WebCoreSetShouldUseFontSmoothing(f);
1443 + (BOOL)_shouldUseFontSmoothing
1445 return WebCoreShouldUseFontSmoothing();
1448 + (NSString *)_minimumRequiredSafariBuildNumber
1453 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1455 WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1457 [scrollview setVerticalScrollingMode:WebCoreScrollBarAlwaysOn];
1458 [scrollview setVerticalScrollingModeLocked:YES];
1460 [scrollview setVerticalScrollingModeLocked:NO];
1461 [scrollview setVerticalScrollingMode:WebCoreScrollBarAuto];
1465 - (BOOL)alwaysShowVerticalScroller
1467 WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1468 return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == WebCoreScrollBarAlwaysOn;
1471 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1473 WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1475 [scrollview setHorizontalScrollingMode:WebCoreScrollBarAlwaysOn];
1476 [scrollview setHorizontalScrollingModeLocked:YES];
1478 [scrollview setHorizontalScrollingModeLocked:NO];
1479 [scrollview setHorizontalScrollingMode:WebCoreScrollBarAuto];
1483 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1485 [[[self mainFrame] _bridge] setProhibitsScrolling:YES];
1488 - (BOOL)alwaysShowHorizontalScroller
1490 WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1491 return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == WebCoreScrollBarAlwaysOn;
1494 - (void)_setInViewSourceMode:(BOOL)flag
1496 [[[self mainFrame] _bridge] setInViewSourceMode:flag];
1499 - (BOOL)_inViewSourceMode
1501 return [[[self mainFrame] _bridge] inViewSourceMode];
1504 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1506 if (!_private->pluginDatabase)
1507 _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1509 [_private->pluginDatabase setPlugInPaths:newPaths];
1510 [_private->pluginDatabase refresh];
1513 - (void)_attachScriptDebuggerToAllFrames
1515 WebFrame *frame = [self mainFrame];
1517 [frame _attachScriptDebugger];
1518 frame = [frame _nextFrameWithWrap:NO];
1522 - (void)_detachScriptDebuggerFromAllFrames
1524 WebFrame *frame = [self mainFrame];
1526 [frame _detachScriptDebugger];
1527 frame = [frame _nextFrameWithWrap:NO];
1534 @implementation _WebSafeForwarder
1536 - initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
1538 self = [super init];
1542 target = t; // Non retained.
1544 templateClass = aClass;
1549 // Used to send messages to delegates that implement informal protocols.
1550 + safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
1552 return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
1556 NSMutableDictionary *countInvocations;
1559 - (void)forwardInvocation:(NSInvocation *)anInvocation
1562 if (!countInvocations){
1563 countInvocations = [[NSMutableDictionary alloc] init];
1565 NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
1567 count = [NSNumber numberWithInt: 1];
1569 count = [NSNumber numberWithInt: [count intValue] + 1];
1570 [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
1572 if ([target respondsToSelector: [anInvocation selector]])
1573 [anInvocation invokeWithTarget: target];
1574 else if ([defaultTarget respondsToSelector: [anInvocation selector]])
1575 [anInvocation invokeWithTarget: defaultTarget];
1576 // Do nothing quietly if method not implemented.
1579 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1581 return [templateClass instanceMethodSignatureForSelector: aSelector];
1586 @implementation WebView
1588 #if REMOVE_SAFARI_DOM_TREE_DEBUG_ITEM
1589 // this prevents open source users from crashing when using the Show DOM Tree menu item in Safari
1590 // FIXME: remove this when it is no longer needed to prevent Safari from crashing
1593 static BOOL tooLate = NO;
1595 if ([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"IncludeDebugMenu"])
1596 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_finishedLaunching) name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1601 +(void)_finishedLaunching
1603 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_removeDOMTreeMenuItem:) name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1604 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1607 +(void)_removeDOMTreeMenuItem:(NSNotification *)notification
1609 NSMenu *debugMenu = [[[[NSApp mainMenu] itemArray] lastObject] submenu];
1610 NSMenuItem *domTree = [debugMenu itemWithTitle:@"Show DOM Tree"];
1612 [debugMenu removeItem:domTree];
1613 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1617 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1619 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1622 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
1624 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase installedPlugins] pluginForMIMEType:MIMEType];
1626 return pluginPackage;
1628 if (_private->pluginDatabase)
1629 return [_private->pluginDatabase pluginForMIMEType:MIMEType];
1634 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
1636 WebBasePluginPackage *pluginPackage = [[WebPluginDatabase installedPlugins] pluginForExtension:extension];
1638 return pluginPackage;
1640 if (_private->pluginDatabase)
1641 return [_private->pluginDatabase pluginForExtension:extension];
1646 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
1648 if ([[WebPluginDatabase installedPlugins] isMIMETypeRegistered:MIMEType])
1651 if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
1657 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1659 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1662 + (NSArray *)MIMETypesShownAsHTML
1664 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1665 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1667 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1669 while ((key = [enumerator nextObject])) {
1670 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1671 [array addObject:key];
1677 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1679 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1680 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1682 while ((key = [enumerator nextObject])) {
1683 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1684 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1687 int i, count = [MIMETypes count];
1688 for (i = 0; i < count; i++) {
1689 [WebView registerViewClass:[WebHTMLView class]
1690 representationClass:[WebHTMLRepresentation class]
1691 forMIMEType:[MIMETypes objectAtIndex:i]];
1695 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1697 return [pasteboard _web_bestURL];
1700 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1702 return [pasteboard stringForType:WebURLNamePboardType];
1705 - (void)_registerDraggedTypes
1707 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1708 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1709 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1710 [types addObjectsFromArray:URLTypes];
1711 [self registerForDraggedTypes:[types allObjects]];
1715 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1717 _private->mainFrameDocumentReady = NO;
1718 _private->drawsBackground = YES;
1719 _private->smartInsertDeleteEnabled = YES;
1721 NSRect f = [self frame];
1722 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1723 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1724 [self addSubview:frameView];
1725 [frameView release];
1727 WebKitInitializeLoggingChannelsIfNecessary();
1728 _private->_pageBridge = [[WebPageBridge alloc] initWithMainFrameName:frameName webView:self frameView:frameView];
1730 [self _addToAllWebViewsSet];
1731 [self setGroupName:groupName];
1733 // If there's already a next key view (e.g., from a nib), wire it up to our
1734 // contained frame view. In any case, wire our next key view up to the our
1735 // contained frame view. This works together with our becomeFirstResponder
1736 // and setNextKeyView overrides.
1737 NSView *nextKeyView = [self nextKeyView];
1738 if (nextKeyView != nil && nextKeyView != frameView) {
1739 [frameView setNextKeyView:nextKeyView];
1741 [super setNextKeyView:frameView];
1745 [self _registerDraggedTypes];
1747 // initialize WebScriptDebugServer here so listeners can register before any pages are loaded.
1748 if ([WebView _scriptDebuggerEnabled])
1749 [WebScriptDebugServer sharedScriptDebugServer];
1751 // Update WebCore with preferences. These values will either come from an archived WebPreferences,
1752 // or from the standard preferences, depending on whether this method was called from initWithCoder:
1753 // or initWithFrame, respectively.
1754 [self _updateWebCoreSettingsFromPreferences: [self preferences]];
1756 // Register to receive notifications whenever preference values change.
1757 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1758 name:WebPreferencesChangedNotification object:[self preferences]];
1761 - (id)initWithFrame:(NSRect)f
1763 return [self initWithFrame:f frameName:nil groupName:nil];
1766 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1768 self = [super initWithFrame:f];
1772 #if ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1773 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1774 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1775 // need for Safari to unset it to prevent it from being passed to applications it launches.
1776 // Unsetting it when a WebView is first created is as good a place as any.
1777 // See <http://bugzilla.opendarwin.org/show_bug.cgi?id=4286> for more details.
1778 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1779 unsetenv("DYLD_FRAMEWORK_PATH");
1780 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1784 _private = [[WebViewPrivate alloc] init];
1785 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1786 [self setMaintainsBackForwardList: YES];
1790 - (id)initWithCoder:(NSCoder *)decoder
1792 WebView *result = nil;
1796 NSString *frameName;
1797 NSString *groupName;
1798 WebPreferences *preferences;
1799 BOOL useBackForwardList;
1801 result = [super initWithCoder:decoder];
1802 result->_private = [[WebViewPrivate alloc] init];
1804 // We don't want any of the archived subviews. The subviews will always
1805 // be created in _commonInitializationFrameName:groupName:.
1806 [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1808 if ([decoder allowsKeyedCoding]) {
1809 frameName = [decoder decodeObjectForKey:@"FrameName"];
1810 groupName = [decoder decodeObjectForKey:@"GroupName"];
1811 preferences = [decoder decodeObjectForKey:@"Preferences"];
1812 useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1815 [decoder decodeValueOfObjCType:@encode(int) at:&version];
1816 frameName = [decoder decodeObject];
1817 groupName = [decoder decodeObject];
1818 preferences = [decoder decodeObject];
1820 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1823 if (![frameName isKindOfClass:[NSString class]])
1825 if (![groupName isKindOfClass:[NSString class]])
1827 if (![preferences isKindOfClass:[WebPreferences class]])
1830 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1833 [result setPreferences:preferences];
1834 result->_private->useBackForwardList = useBackForwardList;
1835 [result _commonInitializationWithFrameName:frameName groupName:groupName];
1847 - (void)encodeWithCoder:(NSCoder *)encoder
1849 [super encodeWithCoder:encoder];
1851 if ([encoder allowsKeyedCoding]) {
1852 [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
1853 [encoder encodeObject:[self groupName] forKey:@"GroupName"];
1854 [encoder encodeObject:[self preferences] forKey:@"Preferences"];
1855 [encoder encodeBool:_private->useBackForwardList forKey:@"UseBackForwardList"];
1857 int version = WebViewVersion;
1858 [encoder encodeValueOfObjCType:@encode(int) at:&version];
1859 [encoder encodeObject:[[self mainFrame] name]];
1860 [encoder encodeObject:[self groupName]];
1861 [encoder encodeObject:[self preferences]];
1862 [encoder encodeValuesOfObjCTypes:"c", &_private->useBackForwardList];
1865 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)_private->useBackForwardList);
1870 // call close to ensure we tear-down completly
1871 // this maintains our old behavior for existing applications
1877 // [super dealloc] can end up dispatching against _private (3466082)
1885 ASSERT(_private->closed);
1897 - (void)setShouldCloseWithWindow:(BOOL)close
1899 _private->shouldCloseWithWindow = close;
1902 - (BOOL)shouldCloseWithWindow
1904 return _private->shouldCloseWithWindow;
1907 - (void)viewWillMoveToWindow:(NSWindow *)window
1909 // Don't do anything if we aren't initialized. This happens
1910 // when decoding a WebView.
1913 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
1915 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
1919 - (void)_windowWillClose:(NSNotification *)notification
1921 if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
1925 - (void)setPreferences:(WebPreferences *)prefs
1927 if (_private->preferences != prefs) {
1928 [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
1929 [WebPreferences _removeReferenceForIdentifier:[_private->preferences identifier]];
1930 [_private->preferences release];
1931 _private->preferences = [prefs retain];
1932 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1933 name:WebPreferencesChangedNotification object:[self preferences]];
1934 [[NSNotificationCenter defaultCenter]
1935 postNotificationName:WebPreferencesChangedNotification object:prefs userInfo:nil];
1939 - (WebPreferences *)preferences
1941 return _private->preferences ? _private->preferences : [WebPreferences standardPreferences];
1944 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
1946 if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
1947 WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
1948 [self setPreferences:prefs];
1953 - (NSString *)preferencesIdentifier
1955 return [[self preferences] identifier];
1959 - (void)setUIDelegate:delegate
1961 _private->UIDelegate = delegate;
1962 [_private->UIDelegateForwarder release];
1963 _private->UIDelegateForwarder = nil;
1968 return _private->UIDelegate;
1971 - (void)setResourceLoadDelegate: delegate
1973 _private->resourceProgressDelegate = delegate;
1974 [_private->resourceProgressDelegateForwarder release];
1975 _private->resourceProgressDelegateForwarder = nil;
1976 [self _cacheResourceLoadDelegateImplementations];
1980 - resourceLoadDelegate
1982 return _private->resourceProgressDelegate;
1986 - (void)setDownloadDelegate: delegate
1988 _private->downloadDelegate = delegate;
1994 return _private->downloadDelegate;
1997 - (void)setPolicyDelegate:delegate
1999 _private->policyDelegate = delegate;
2000 [_private->policyDelegateForwarder release];
2001 _private->policyDelegateForwarder = nil;
2006 return _private->policyDelegate;
2009 - (void)setFrameLoadDelegate:delegate
2011 _private->frameLoadDelegate = delegate;
2012 [_private->frameLoadDelegateForwarder release];
2013 _private->frameLoadDelegateForwarder = nil;
2018 return _private->frameLoadDelegate;
2021 - (WebFrame *)mainFrame
2023 // This can be called in initialization, before _private has been set up (3465613)
2026 return [(WebFrameBridge *)[_private->_pageBridge mainFrame] webFrame];
2029 - (WebFrame *)selectedFrame
2031 // If the first responder is a view in our tree, we get the frame containing the first responder.
2032 // This is faster than searching the frame hierarchy, and will give us a result even in the case
2033 // where the focused frame doesn't actually contain a selection.
2034 WebFrame *focusedFrame = [self _focusedFrame];
2036 return focusedFrame;
2038 // If the first responder is outside of our view tree, we search for a frame containing a selection.
2039 // There should be at most only one of these.
2040 return [[self mainFrame] _findFrameWithSelection];
2045 - (WebBackForwardList *)backForwardList
2047 if (_private->useBackForwardList)
2048 return _private->backForwardList;
2052 - (void)setMaintainsBackForwardList: (BOOL)flag
2054 _private->useBackForwardList = flag;
2059 WebHistoryItem *item = [[self backForwardList] backItem];
2062 [self _goToItem: item withLoadType: WebFrameLoadTypeBack];
2070 WebHistoryItem *item = [[self backForwardList] forwardItem];
2073 [self _goToItem: item withLoadType: WebFrameLoadTypeForward];
2079 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
2081 [self _goToItem: item withLoadType: WebFrameLoadTypeIndexedBackForward];
2085 - (void)setTextSizeMultiplier:(float)m
2087 if (_private->textSizeMultiplier == m) {
2090 _private->textSizeMultiplier = m;
2093 - (float)textSizeMultiplier
2095 return _private->textSizeMultiplier;
2098 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
2100 NSString *name = [applicationName copy];
2101 [_private->applicationNameForUserAgent release];
2102 _private->applicationNameForUserAgent = name;
2103 if (!_private->userAgentOverridden) {
2104 [_private->userAgent release];
2105 _private->userAgent = nil;
2109 - (NSString *)applicationNameForUserAgent
2111 return [[_private->applicationNameForUserAgent retain] autorelease];
2114 - (void)setCustomUserAgent:(NSString *)userAgentString
2116 NSString *override = [userAgentString copy];
2117 [_private->userAgent release];
2118 _private->userAgent = override;
2119 _private->userAgentOverridden = override != nil;
2122 - (NSString *)customUserAgent
2124 return _private->userAgentOverridden ? [[_private->userAgent retain] autorelease] : nil;
2127 - (void)setMediaStyle:(NSString *)mediaStyle
2129 if (_private->mediaStyle != mediaStyle) {
2130 [_private->mediaStyle release];
2131 _private->mediaStyle = [mediaStyle copy];
2135 - (NSString *)mediaStyle
2137 return _private->mediaStyle;
2140 - (BOOL)supportsTextEncoding
2142 id documentView = [[[self mainFrame] frameView] documentView];
2143 return [documentView conformsToProtocol:@protocol(WebDocumentText)]
2144 && [documentView supportsTextEncoding];
2147 - (void)setCustomTextEncodingName:(NSString *)encoding
2149 NSString *oldEncoding = [self customTextEncodingName];
2150 if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding]) {
2153 [[[self mainFrame] _frameLoader] _reloadAllowingStaleDataWithOverrideEncoding:encoding];
2156 - (NSString *)_mainFrameOverrideEncoding
2158 WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
2159 if (dataSource == nil) {
2160 dataSource = [[self mainFrame] dataSource];
2162 if (dataSource == nil) {
2165 return [dataSource _overrideEncoding];
2168 - (NSString *)customTextEncodingName
2170 return [self _mainFrameOverrideEncoding];
2173 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
2175 return [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
2178 - (WebScriptObject *)windowScriptObject
2180 return [[[self mainFrame] _bridge] windowScriptObject];
2183 // Get the appropriate user-agent string for a particular URL.
2184 // Since we no longer automatically spoof, this no longer requires looking at the URL.
2185 - (NSString *)userAgentForURL:(NSURL *)URL
2187 NSString *userAgent = _private->userAgent;
2189 return [[userAgent retain] autorelease];
2192 NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
2193 id sourceVersion = [[NSBundle bundleForClass:[WebView class]]
2194 objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
2195 NSString *applicationName = _private->applicationNameForUserAgent;
2197 if ([applicationName length]) {
2198 userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko) %@",
2199 language, sourceVersion, applicationName];
2201 userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko)",
2202 language, sourceVersion];
2205 _private->userAgent = [userAgent retain];
2209 - (void)setHostWindow:(NSWindow *)hostWindow
2211 if (!_private->closed && hostWindow != _private->hostWindow) {
2212 [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2213 if (_private->hostWindow)
2214 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
2216 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
2217 [_private->hostWindow release];
2218 _private->hostWindow = [hostWindow retain];
2219 [[self mainFrame] _viewDidMoveToHostWindow];
2223 - (NSWindow *)hostWindow
2225 return _private->hostWindow;
2228 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2230 return [[self _frameViewAtWindowPoint:point] documentView];
2233 - (NSView <WebDocumentDragging> *)_draggingDocumentViewAtWindowPoint:(NSPoint)point
2235 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:point];
2236 if ([documentView conformsToProtocol:@protocol(WebDocumentDragging)]) {
2237 return (NSView <WebDocumentDragging> *)documentView;
2242 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2244 WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2247 NSView <WebDocumentView> *documentView = [frameView documentView];
2248 if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2249 NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2250 return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2252 return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2255 - (NSDictionary *)elementAtPoint:(NSPoint)point
2257 return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2260 - (void)_setDraggingDocumentView:(NSView <WebDocumentDragging> *)newDraggingView
2262 if (_private->draggingDocumentView != newDraggingView) {
2263 [_private->draggingDocumentView release];
2264 _private->draggingDocumentView = [newDraggingView retain];
2268 - (NSDragOperation)_loadingDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2270 if (_private->dragDestinationActionMask & WebDragDestinationActionLoad) {
2271 NSPoint windowPoint = [draggingInfo draggingLocation];
2272 NSView *view = [self hitTest:[[self superview] convertPoint:windowPoint toView:nil]];
2273 // Don't accept the drag over a plug-in since plug-ins may want to handle it.
2274 if (![view isKindOfClass:[WebBaseNetscapePluginView class]] && !_private->editable && !_private->initiatedDrag) {
2275 // If not editing or dragging, use _web_dragOperationForDraggingInfo to find a URL to load on the pasteboard.
2276 return [self _web_dragOperationForDraggingInfo:draggingInfo];
2279 return NSDragOperationNone;
2282 - (NSDragOperation)_delegateDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2284 NSPoint windowPoint = [draggingInfo draggingLocation];
2285 NSView <WebDocumentDragging> *newDraggingView = [self _draggingDocumentViewAtWindowPoint:windowPoint];
2286 if (_private->draggingDocumentView != newDraggingView) {
2287 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2288 [self _setDraggingDocumentView:newDraggingView];
2291 _private->dragDestinationActionMask = [[self _UIDelegateForwarder] webView:self dragDestinationActionMaskForDraggingInfo:draggingInfo];
2292 NSDragOperation operation = NSDragOperationNone;
2294 if (_private->dragDestinationActionMask == WebDragDestinationActionNone) {
2295 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2297 operation = [_private->draggingDocumentView draggingUpdatedWithDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask];
2298 if (operation == NSDragOperationNone) {
2299 return [self _loadingDragOperationForDraggingInfo:draggingInfo];
2306 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2307 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination.
2308 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination.
2309 // Forward these calls to the document subview to make its scroll view scroll.
2310 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2312 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2313 [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2316 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2318 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2319 return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2322 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2324 return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2327 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2329 return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2332 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2334 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2335 [self _setDraggingDocumentView:nil];
2338 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2343 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2345 ASSERT(_private->draggingDocumentView == [self _draggingDocumentViewAtWindowPoint:[draggingInfo draggingLocation]]);
2347 if ([_private->draggingDocumentView concludeDragForDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask]) {
2348 [self _setDraggingDocumentView:nil];
2352 [self _setDraggingDocumentView:nil];
2354 if ([self _loadingDragOperationForDraggingInfo:draggingInfo] != NSDragOperationNone) {
2355 NSURL *URL = [[self class] URLFromPasteboard:[draggingInfo draggingPasteboard]];
2357 [[self _UIDelegateForwarder] webView:self willPerformDragDestinationAction:WebDragDestinationActionLoad forDraggingInfo:draggingInfo];
2358 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2359 [[self mainFrame] loadRequest:request];
2368 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2370 NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2371 if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2378 - (BOOL)acceptsFirstResponder
2380 return [[[self mainFrame] frameView] acceptsFirstResponder];
2383 - (BOOL)becomeFirstResponder
2385 // This works together with setNextKeyView to splice the WebView into
2386 // the key loop similar to the way NSScrollView does this. Note that
2387 // WebFrameView has very similar code.
2388 NSWindow *window = [self window];
2389 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2391 if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2392 NSView *previousValidKeyView = [self previousValidKeyView];
2393 if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2394 [window makeFirstResponder:previousValidKeyView];
2401 if ([mainFrameView acceptsFirstResponder]) {
2402 [window makeFirstResponder:mainFrameView];
2409 - (NSView *)_webcore_effectiveFirstResponder
2411 WebFrameView *frameView = [[self mainFrame] frameView];
2412 return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2415 - (void)setNextKeyView:(NSView *)aView
2417 // This works together with becomeFirstResponder to splice the WebView into
2418 // the key loop similar to the way NSScrollView does this. Note that
2419 // WebFrameView has very similar code.
2420 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2421 if (mainFrameView != nil) {
2422 [mainFrameView setNextKeyView:aView];
2424 [super setNextKeyView:aView];
2428 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2430 return forward ? [curr _nextFrameWithWrap:wrapFlag]
2431 : [curr _previousFrameWithWrap:wrapFlag];
2434 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2436 if (_private->closed)
2439 // Get the frame holding the selection, or start with the main frame
2440 WebFrame *startFrame = [self _selectedOrMainFrame];
2442 // Search the first frame, then all the other frames, in order
2443 NSView <WebDocumentSearching> *startSearchView = nil;
2444 BOOL startHasSelection = NO;
2445 WebFrame *frame = startFrame;
2447 id <WebDocumentView> view = [[frame frameView] documentView];
2448 if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2449 NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2451 // first time through
2452 if (frame == startFrame) {
2453 // Remember if start even has a selection, to know if we need to search more later
2454 if ([searchView isKindOfClass:[WebHTMLView class]]) {
2455 // optimization for the common case, to avoid making giant string for selection
2456 startHasSelection = [[startFrame _bridge] selectedDOMRange] != nil;
2457 } else if ([searchView conformsToProtocol:@protocol(WebDocumentText)]) {
2458 startHasSelection = [(id <WebDocumentText>)searchView selectedString] != nil;
2460 startSearchView = searchView;
2463 if ([searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:NO]) {
2464 if (frame != startFrame)
2465 [startFrame _clearSelection];
2466 [[self window] makeFirstResponder:searchView];
2470 frame = incrementFrame(frame, forward, wrapFlag);
2471 } while (frame != nil && frame != startFrame);
2473 // Search contents of startFrame, on the other side of the selection that we did earlier.
2474 // We cheat a bit and just research with wrap on
2475 if (wrapFlag && startHasSelection && startSearchView) {
2476 if ([startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES]) {
2477 [[self window] makeFirstResponder:startSearchView];
2484 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2486 [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2487 [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2490 - (void)setGroupName:(NSString *)groupName
2492 [[self _pageBridge] setGroupName:groupName];
2495 - (NSString *)groupName
2497 return [[self _pageBridge] groupName];
2500 - (double)estimatedProgress
2502 return _private->progressValue;
2505 - (NSArray *)pasteboardTypesForSelection
2507 NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2508 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2509 return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2511 return [NSArray array];
2514 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2516 WebFrameBridge *bridge = [self _bridgeForSelectedOrMainFrame];
2517 if (bridge && [bridge selectionState] != WebSelectionStateRange) {
2518 NSView <WebDocumentView> *documentView = [[[bridge webFrame] frameView] documentView];
2519 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2520 [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2525 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2527 if ([element objectForKey:WebElementImageURLKey] != nil) {
2528 return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2529 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2530 return [NSPasteboard _web_writableTypesForURL];
2531 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2532 return [self pasteboardTypesForSelection];
2534 return [NSArray array];
2537 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2539 if ([element objectForKey:WebElementImageURLKey] != nil) {
2540 [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2541 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2542 [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2543 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2544 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2548 - (void)moveDragCaretToPoint:(NSPoint)point
2550 [[[self mainFrame] _bridge] moveDragCaretToPoint:[self convertPoint:point toView:[[[self mainFrame] frameView] documentView]]];
2553 - (void)removeDragCaret
2555 [[[self mainFrame] _bridge] removeDragCaret];
2558 - (void)setMainFrameURL:(NSString *)URLString
2560 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2563 - (NSString *)mainFrameURL
2566 ds = [[self mainFrame] provisionalDataSource];
2568 ds = [[self mainFrame] dataSource];
2569 return [[[ds request] URL] _web_originalDataAsString];
2574 LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2575 return [self _isLoading];
2578 - (NSString *)mainFrameTitle
2580 NSString *mainFrameTitle = [[[self mainFrame] dataSource] pageTitle];
2581 return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2584 - (NSImage *)mainFrameIcon
2586 return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2589 - (DOMDocument *)mainFrameDocument
2591 // only return the actual value if the state we're in gives NSTreeController
2592 // enough time to release its observers on the old model
2593 if (_private->mainFrameDocumentReady)
2594 return [[self mainFrame] DOMDocument];
2598 - (void)setDrawsBackground:(BOOL)drawsBackground
2600 if (_private->drawsBackground == drawsBackground)
2602 _private->drawsBackground = drawsBackground;
2603 [[self mainFrame] _updateDrawsBackground];
2606 - (BOOL)drawsBackground
2608 return _private->drawsBackground;
2611 - (void)_inspectElement:(id)sender
2613 NSDictionary *element = [sender representedObject];
2614 WebFrame *frame = [element objectForKey:WebElementFrameKey];
2615 DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
2616 if (!node || !frame)
2619 if ([node nodeType] != DOM_ELEMENT_NODE || [node nodeType] != DOM_DOCUMENT_NODE)
2620 node = [node parentNode];
2622 WebInspector *inspector = [WebInspector sharedWebInspector];
2623 [inspector setWebFrame:frame];
2624 [inspector setFocusedDOMNode:node];
2626 node = [node parentNode];
2627 node = [node parentNode];
2628 if (node) // set the root node to something relatively close to the focused node
2629 [inspector setRootDOMNode:node];
2631 [inspector showWindow:nil];
2635 @implementation WebView (WebIBActions)
2637 - (IBAction)takeStringURLFrom: sender
2639 NSString *URLString = [sender stringValue];
2641 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2646 return [[self backForwardList] backItem] != nil;
2649 - (BOOL)canGoForward
2651 return [[self backForwardList] forwardItem] != nil;
2654 - (IBAction)goBack:(id)sender
2659 - (IBAction)goForward:(id)sender
2664 - (IBAction)stopLoading:(id)sender
2666 [[self mainFrame] stopLoading];
2669 - (IBAction)reload:(id)sender
2671 [[self mainFrame] reload];
2674 #define MinimumTextSizeMultiplier 0.5f
2675 #define MaximumTextSizeMultiplier 3.0f
2676 #define TextSizeMultiplierRatio 1.2f
2678 - (BOOL)canMakeTextSmaller
2680 BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2681 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2684 - (BOOL)canMakeTextLarger
2686 BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2687 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2690 - (IBAction)makeTextSmaller:(id)sender
2692 float newScale = _private->textSizeMultiplier / TextSizeMultiplierRatio;
2693 BOOL canShrinkMore = newScale > MinimumTextSizeMultiplier;
2694 [self _performTextSizingSelector:@selector(_makeTextSmaller:) withObject:sender onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:newScale];
2697 - (IBAction)makeTextLarger:(id)sender
2699 float newScale = _private->textSizeMultiplier*TextSizeMultiplierRatio;
2700 BOOL canGrowMore = newScale < MaximumTextSizeMultiplier;
2701 [self _performTextSizingSelector:@selector(_makeTextLarger:) withObject:sender onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:newScale];
2704 - (IBAction)toggleSmartInsertDelete:(id)sender
2706 [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2709 - (IBAction)toggleContinuousSpellChecking:(id)sender
2711 [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2714 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2716 id responder = [self _responderForResponderOperations];
2717 if (responder != self && [responder respondsToSelector:[item action]]) {
2718 if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)]) {
2719 return [responder validateUserInterfaceItem:item];
2726 - (BOOL)canMakeTextStandardSize
2728 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2729 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0.0f];
2732 - (IBAction)makeTextStandardSize:(id)sender
2734 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2735 [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0f];
2738 #define VALIDATE(name) \
2739 else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2741 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2743 SEL action = [item action];
2745 if (action == @selector(goBack:)) {
2746 return [self canGoBack];
2747 } else if (action == @selector(goForward:)) {
2748 return [self canGoForward];
2749 } else if (action == @selector(makeTextLarger:)) {
2750 return [self canMakeTextLarger];
2751 } else if (action == @selector(makeTextSmaller:)) {
2752 return [self canMakeTextSmaller];
2753 } else if (action == @selector(makeTextStandardSize:)) {
2754 return [self canMakeTextStandardSize];
2755 } else if (action == @selector(reload:)) {
2756 return [[self mainFrame] dataSource] != nil;
2757 } else if (action == @selector(stopLoading:)) {
2758 return [self _isLoading];
2759 } else if (action == @selector(toggleContinuousSpellChecking:)) {
2760 BOOL checkMark = NO;
2762 if ([self _continuousCheckingAllowed]) {
2763 checkMark = [self isContinuousSpellCheckingEnabled];
2766 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2767 NSMenuItem *menuItem = (NSMenuItem *)item;
2768 [menuItem setState:checkMark ? NSOnState : NSOffState];
2772 FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2779 @implementation WebView (WebPendingPublic)
2781 - (void)setMainFrameDocumentReady:(BOOL)mainFrameDocumentReady
2783 // by setting this to NO, calls to mainFrameDocument are forced to return nil
2784 // setting this to YES lets it return the actual DOMDocument value
2785 // we use this to tell NSTreeController to reset its observers and clear its state
2786 if (_private->mainFrameDocumentReady == mainFrameDocumentReady)
2788 [self _willChangeValueForKey:_WebMainFrameDocumentKey];
2789 _private->mainFrameDocumentReady = mainFrameDocumentReady;
2790 [self _didChangeValueForKey:_WebMainFrameDocumentKey];
2791 // this will cause observers to call mainFrameDocument where this flag will be checked
2794 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it
2795 // until the day comes when we're no longer supporting Mail on Tiger.
2796 - (WebFrame *)_frameForCurrentSelection
2798 return [self _selectedOrMainFrame];
2801 - (void)setTabKeyCyclesThroughElements:(BOOL)cyclesElements
2803 _private->tabKeyCyclesThroughElementsChanged = YES;
2804 _private->tabKeyCyclesThroughElements = cyclesElements;
2807 - (BOOL)tabKeyCyclesThroughElements
2809 return _private->tabKeyCyclesThroughElements;
2812 - (void)setScriptDebugDelegate:delegate
2814 _private->scriptDebugDelegate = delegate;
2815 [_private->scriptDebugDelegateForwarder release];
2816 _private->scriptDebugDelegateForwarder = nil;
2818 [self _attachScriptDebuggerToAllFrames];
2820 [self _detachScriptDebuggerFromAllFrames];
2823 - scriptDebugDelegate
2825 return _private->scriptDebugDelegate;
2830 WebFrameBridge *bridge = [[self mainFrame] _bridge];
2833 return [bridge shouldClose];
2836 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
2838 return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
2841 - (unsigned)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight
2843 WebFrame *frame = [self mainFrame];
2844 unsigned matchCount = 0;
2846 id <WebDocumentView> view = [[frame frameView] documentView];
2847 // FIXME: introduce a protocol, or otherwise make this work with other types
2848 if ([view isKindOfClass:[WebHTMLView class]])
2849 [(WebHTMLView *)view setMarkedTextMatchesAreHighlighted:highlight];
2850 matchCount += [(WebHTMLView *)view markAllMatchesForText:string caseSensitive:caseFlag];
2852 frame = incrementFrame(frame, YES, NO);
2858 - (void)unmarkAllTextMatches
2860 WebFrame *frame = [self mainFrame];
2862 id <WebDocumentView> view = [[frame frameView] documentView];
2863 // FIXME: introduce a protocol, or otherwise make this work with other types
2864 if ([view isKindOfClass:[WebHTMLView class]])
2865 [(WebHTMLView *)view unmarkAllTextMatches];
2867 frame = incrementFrame(frame, YES, NO);
2871 - (NSArray *)rectsForTextMatches
2873 NSMutableArray *result = [NSMutableArray array];
2874 WebFrame *frame = [self mainFrame];
2876 id <WebDocumentView> view = [[frame frameView] documentView];
2877 // FIXME: introduce a protocol, or otherwise make this work with other types
2878 if ([view isKindOfClass:[WebHTMLView class]]) {
2879 WebHTMLView *htmlView = (WebHTMLView *)view;
2880 NSArray *originalRects = [htmlView rectsForTextMatches];
2881 unsigned rectCount = [originalRects count];
2883 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2884 for (rectIndex = 0; rectIndex < rectCount; ++rectIndex) {
2885 NSRect r = [[originalRects objectAtIndex:rectIndex] rectValue];
2886 if (NSIsEmptyRect(r))
2889 // Convert rect to our coordinate system
2890 r = [htmlView convertRect:r toView:self];
2891 [result addObject:[NSValue valueWithRect:r]];
2892 if (rectIndex % 10 == 0)
2898 frame = incrementFrame(frame, YES, NO);
2906 @implementation WebView (WebViewPrintingPrivate)
2908 - (float)_headerHeight
2910 if ([[self UIDelegate] respondsToSelector:@selector(webViewHeaderHeight:)]) {
2911 return [[self UIDelegate] webViewHeaderHeight:self];
2914 #ifdef DEBUG_HEADER_AND_FOOTER
2921 - (float)_footerHeight
2923 if ([[self UIDelegate] respondsToSelector:@selector(webViewFooterHeight:)]) {
2924 return [[self UIDelegate] webViewFooterHeight:self];
2927 #ifdef DEBUG_HEADER_AND_FOOTER
2934 - (void)_drawHeaderInRect:(NSRect)rect
2936 #ifdef DEBUG_HEADER_AND_FOOTER
2937 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2938 [currentContext saveGraphicsState];
2939 [[NSColor yellowColor] set];
2941 [currentContext restoreGraphicsState];
2944 if ([[self UIDelegate] respondsToSelector:@selector(webView:drawHeaderInRect:)]) {
2945 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2946 [currentContext saveGraphicsState];
2948 [[self UIDelegate] webView:self drawHeaderInRect:rect];
2949 [currentContext restoreGraphicsState];
2953 - (void)_drawFooterInRect:(NSRect)rect
2955 #ifdef DEBUG_HEADER_AND_FOOTER
2956 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2957 [currentContext saveGraphicsState];
2958 [[NSColor cyanColor] set];
2960 [currentContext restoreGraphicsState];
2963 if ([[self UIDelegate] respondsToSelector:@selector(webView:drawFooterInRect:)]) {
2964 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2965 [currentContext saveGraphicsState];
2967 [[self UIDelegate] webView:self drawFooterInRect:rect];
2968 [currentContext restoreGraphicsState];
2972 - (void)_adjustPrintingMarginsForHeaderAndFooter
2974 NSPrintOperation *op = [NSPrintOperation currentOperation];
2975 NSPrintInfo *info = [op printInfo];
2976 float scale = [op _web_pageSetupScaleFactor];
2977 [info setTopMargin:[info topMargin] + [self _headerHeight]*scale];
2978 [info setBottomMargin:[info bottomMargin] + [self _footerHeight]*scale];
2981 - (void)_drawHeaderAndFooter
2983 // The header and footer rect height scales with the page, but the width is always
2984 // all the way across the printed page (inset by printing margins).
2985 NSPrintOperation *op = [NSPrintOperation currentOperation];
2986 float scale = [op _web_pageSetupScaleFactor];
2987 NSPrintInfo *printInfo = [op printInfo];
2988 NSSize paperSize = [printInfo paperSize];
2989 float headerFooterLeft = [printInfo leftMargin]/scale;
2990 float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
2991 NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] ,
2992 headerFooterWidth, [self _footerHeight]);
2993 NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale,
2994 headerFooterWidth, [self _headerHeight]);
2996 [self _drawHeaderInRect:headerRect];
2997 [self _drawFooterInRect:footerRect];
3001 @implementation WebView (WebDebugBinding)
3003 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
3005 LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
3006 [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
3009 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
3011 LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
3012 [super removeObserver:anObserver forKeyPath:keyPath];
3017 //==========================================================================================
3020 @implementation WebView (WebViewCSS)
3022 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
3024 // FIXME: is this the best level for this conversion?
3025 if (pseudoElement == nil) {
3026 pseudoElement = @"";
3028 return [[element ownerDocument] getComputedStyle:element :pseudoElement];
3033 @implementation WebView (WebViewEditing)
3035 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
3037 WebFrameBridge *bridge = [self _bridgeAtPoint:point];
3038 return [bridge editableDOMRangeForPoint:[self convertPoint:point toView:[[[bridge webFrame] frameView] documentView]]];
3041 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
3043 return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
3046 - (BOOL)_shouldBeginEditingInDOMRange:(DOMRange *)range
3048 return [[self _editingDelegateForwarder] webView:self shouldBeginEditingInDOMRange:range];
3051 - (BOOL)_shouldEndEditingInDOMRange:(DOMRange *)range
3053 return [[self _editingDelegateForwarder] webView:self shouldEndEditingInDOMRange:range];
3058 id documentView = [[[self mainFrame] frameView] documentView];
3059 return [documentView respondsToSelector:@selector(_canPaste)] && [documentView _canPaste];
3062 - (BOOL)maintainsInactiveSelection
3067 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
3070 [[self _bridgeForSelectedOrMainFrame] deselectText];
3072 // Derive the bridge to use from the range passed in.
3073 // Using _bridgeForSelectedOrMainFrame could give us a different document than
3074 // the one the range uses.
3075 [[[range startContainer] _bridge] setSelectedDOMRange:range affinity:selectionAffinity closeTyping:YES];
3079 - (DOMRange *)selectedDOMRange
3081 return [[self _bridgeForSelectedOrMainFrame] selectedDOMRange];
3084 - (NSSelectionAffinity)selectionAffinity
3086 return [[self _bridgeForSelectedOrMainFrame] selectionAffinity];
3089 - (void)setEditable:(BOOL)flag
3091 if (_private->editable != flag) {
3092 _private->editable = flag;
3093 if (!_private->tabKeyCyclesThroughElementsChanged)
3094 _private->tabKeyCyclesThroughElements = !flag;
3095 WebFrameBridge *bridge = [[self mainFrame] _bridge];
3097 [bridge applyEditingStyleToBodyElement];
3098 // If the WebView is made editable and the selection is empty, set it to something.
3099 if (![self selectedDOMRange])
3100 [bridge setSelectionFromNone];
3102 [bridge removeEditingStyleFromBodyElement];
3108 return _private->editable;
3111 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
3113 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3114 // change the API to allow this.
3115 [[self _bridgeForSelectedOrMainFrame] setTypingStyle:style withUndoAction:WebUndoActionUnspecified];
3118 - (DOMCSSStyleDeclaration *)typingStyle
3120 return [[self _bridgeForSelectedOrMainFrame] typingStyle];
3123 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
3125 _private->smartInsertDeleteEnabled = flag;
3128 - (BOOL)smartInsertDeleteEnabled
3130 return _private->smartInsertDeleteEnabled;
3133 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
3135 _private->continuousSpellCheckingEnabled = flag;
3136 if ([self isContinuousSpellCheckingEnabled]) {
3137 [[self class] _preflightSpellChecker];
3139 [[self mainFrame] _unmarkAllMisspellings];
3143 - (BOOL)isContinuousSpellCheckingEnabled
3145 return _private->continuousSpellCheckingEnabled && [self _continuousCheckingAllowed];
3148 - (WebNSInteger)spellCheckerDocumentTag
3150 if (!_private->hasSpellCheckerDocumentTag) {
3151 _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3152 _private->hasSpellCheckerDocumentTag = YES;
3154 return _private->spellCheckerDocumentTag;
3157 - (NSUndoManager *)undoManager
3159 NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
3163 return [super undoManager];
3166 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
3168 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3169 if ([_private->editingDelegate respondsToSelector:selector])
3170 [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
3173 - (void)setEditingDelegate:(id)delegate
3175 if (_private->editingDelegate == delegate)
3178 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3180 // remove notifications from current delegate
3181 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
3182 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
3183 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
3184 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
3185 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
3187 _private->editingDelegate = delegate;
3188 [_private->editingDelegateForwarder release];
3189 _private->editingDelegateForwarder = nil;
3191 // add notifications for new delegate
3192 [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
3193 [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
3194 [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
3195 [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
3196 [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
3199 - (id)editingDelegate
3201 return _private->editingDelegate;
3204 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
3206 // FIXME: Should this really be attached to the document with the current selection?
3207 DOMCSSStyleDeclaration *decl = [[[self _bridgeForSelectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
3208 [decl setCssText:text];
3214 @implementation WebView (WebViewUndoableEditing)
3216 - (void)replaceSelectionWithNode:(DOMNode *)node
3218 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:NO];
3221 - (void)replaceSelectionWithText:(NSString *)text
3223 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
3226 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
3228 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
3231 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3233 [[[[self _bridgeForSelectedOrMainFrame] webFrame] dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3236 - (void)deleteSelection
3238 WebFrameBridge *bridge = [self _bridgeForSelectedOrMainFrame];
3239 [bridge deleteSelectionWithSmartDelete:[(WebHTMLView *)[[[bridge webFrame] frameView] documentView] _canSmartCopyOrDelete]];
3242 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3244 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3245 // change the API to allow this.
3246 [[self _bridgeForSelectedOrMainFrame] applyStyle:style withUndoAction:WebUndoActionUnspecified];
3251 @implementation WebView (WebViewEditingActions)
3253 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3255 static BOOL reentered = NO;
3257 [[self nextResponder] tryToPerform:selector with:parameter];
3261 // There are two possibilities here.
3263 // One is that WebView has been called in its role as part of the responder chain.
3264 // In that case, it's fine to call the first responder and end up calling down the
3265 // responder chain again. Later we will return here with reentered = YES and continue
3266 // past the WebView.
3268 // The other is that we are being called directly, in which case we want to pass the
3269 // selector down to the view inside us that can handle it, and continue down the
3270 // responder chain as usual.
3272 // Pass this selector down to the first responder.
3273 NSResponder *responder = [self _responderForResponderOperations];
3275 [responder tryToPerform:selector with:parameter];
3279 #define FORWARD(name) \
3280 - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3282 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3284 - (void)insertText:(NSString *)text
3286 [self _performResponderOperation:_cmd with:text];
3291 @implementation WebView (WebViewEditingInMail)
3293 - (void)_insertNewlineInQuotedContent;
3295 [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3298 - (BOOL)_selectWordBeforeMenuEvent
3300 return _private->selectWordBeforeMenuEvent;
3303 - (void)_setSelectWordBeforeMenuEvent:(BOOL)flag
3305 _private->selectWordBeforeMenuEvent = flag;
3308 - (void)_replaceSelectionWithNode:(DOMNode *)node matchStyle:(BOOL)matchStyle
3310 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:matchStyle];
3315 static WebFrameView *containingFrameView(NSView *view)
3317 while (view && ![view isKindOfClass:[WebFrameView class]])
3318 view = [view superview];
3319 return (WebFrameView *)view;
3322 @implementation WebView (WebFileInternal)
3324 - (WebFrame *)_focusedFrame
3326 NSResponder *resp = [[self window] firstResponder];
3327 if (resp && [resp isKindOfClass:[NSView class]] && [(NSView *)resp isDescendantOf:[[self mainFrame] frameView]]) {
3328 WebFrameView *frameView = containingFrameView((NSView *)resp);
3329 ASSERT(frameView != nil);
3330 return [frameView webFrame];
3336 - (WebFrame *)_selectedOrMainFrame
3338 WebFrame *result = [self selectedFrame];
3340 result = [self mainFrame];
3344 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame
3346 return [[self _selectedOrMainFrame] _bridge];
3351 WebFrame *mainFrame = [self mainFrame];
3352 return [[mainFrame dataSource] isLoading]
3353 || [[mainFrame provisionalDataSource] isLoading];
3356 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point
3358 if (_private->closed)
3360 NSView *view = [self hitTest:[[self superview] convertPoint:point fromView:nil]];
3361 if (![view isDescendantOf:[[self mainFrame] frameView]])
3363 WebFrameView *frameView = containingFrameView(view);
3368 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point
3370 return [[[self _frameViewAtWindowPoint:[self convertPoint:point toView:nil]] webFrame] _bridge];
3373 + (void)_preflightSpellCheckerNow:(id)sender
3375 [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
3378 + (void)_preflightSpellChecker
3380 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3381 if ([NSSpellChecker sharedSpellCheckerExists]) {
3382 [self _preflightSpellCheckerNow:self];
3384 [self performSelector:@selector(_preflightSpellCheckerNow:) withObject:self afterDelay:2.0];
3388 - (BOOL)_continuousCheckingAllowed
3390 static BOOL allowContinuousSpellChecking = YES;
3391 static BOOL readAllowContinuousSpellCheckingDefault = NO;
3392 if (!readAllowContinuousSpellCheckingDefault) {
3393 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NSAllowContinuousSpellChecking"]) {
3394 allowContinuousSpellChecking = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSAllowContinuousSpellChecking"];
3396 readAllowContinuousSpellCheckingDefault = YES;
3398 return allowContinuousSpellChecking;
3401 - (NSResponder *)_responderForResponderOperations
3403 NSResponder *responder = [[self window] firstResponder];
3404 WebFrameView *mainFrameView = [[self mainFrame] frameView];
3406 // If the current responder is outside of the webview, use our main frameView or its
3407 // document view. We also do this for subviews of self that are siblings of the main
3408 // frameView since clients might insert non-webview-related views there (see 4552713).
3409 if (responder != self && ![mainFrameView _web_firstResponderIsSelfOrDescendantView]) {
3410 responder = [mainFrameView documentView];
3412 responder = mainFrameView;
3417 - (void)_searchWithGoogleFromMenu:(id)sender
3419 id documentView = [[[self selectedFrame] frameView] documentView];
3420 if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3424 NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3425 if ([selectedString length] == 0) {
3429 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName];
3430 [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
3431 NSMutableString *s = [selectedString mutableCopy];
3432 const unichar nonBreakingSpaceCharacter = 0xA0;
3433 NSString *nonBreakingSpaceString = [NSString stringWithCharacters:&nonBreakingSpaceCharacter length:1];
3434 [s replaceOccurrencesOfString:nonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
3435 [pasteboard setString:s forType:NSStringPboardType];
3438 // FIXME: seems fragile to use the service by name, but this is what AppKit does
3439 NSPerformService(@"Search With Google", pasteboard);
3442 - (void)_searchWithSpotlightFromMenu:(id)sender
3444 id documentView = [[[self selectedFrame] frameView] documentView];
3445 if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3449 NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3450 if ([selectedString length] == 0) {
3454 (void)HISearchWindowShow((CFStringRef)selectedString, kNilOptions);
3457 // Slightly funky method that lets us have one copy of the logic for finding docViews that can do
3458 // text sizing. It returns whether it found any "suitable" doc views. It sends sel to any suitable
3459 // doc views, or if sel==0 we do nothing to them. For doc views that track our size factor, they are
3460 // suitable if doTrackingViews==YES (which in practice means that our size factor isn't at its max or
3461 // min). For doc views that don't track it, we send them testSel to determine suitablility. If we
3462 // do find any suitable tracking doc views and newScaleFactor!=0, we will set the common scale factor
3463 // to that new factor before we send sel to any of them.
3464 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor
3466 if ([[self mainFrame] dataSource] == nil) {
3470 BOOL foundSome = NO;
3471 NSArray *docViews = [[self mainFrame] _documentViews];
3473 for (i = [docViews count]-1; i >= 0; i--) {
3474 id docView = [docViews objectAtIndex:i];
3475 if ([docView conformsToProtocol:@protocol(_WebDocumentTextSizing)]) {
3476 id <_WebDocumentTextSizing> sizingDocView = (id <_WebDocumentTextSizing>)docView;
3478 if ([sizingDocView _tracksCommonSizeFactor]) {
3479 isSuitable = doTrackingViews;
3480 if (isSuitable && newScaleFactor != 0) {
3481 [self setTextSizeMultiplier:newScaleFactor];
3484 // Incantation to perform a selector returning a BOOL.
3485 isSuitable = ((BOOL(*)(id, SEL))objc_msgSend)(sizingDocView, testSel);
3491 [sizingDocView performSelector:sel withObject:arg];
3493 // if we're just called for the benefit of the return value, we can return at first match
3505 @implementation WebView (WebViewBridge)
3507 - (WebPageBridge *)_pageBridge
3509 return _private->_pageBridge;