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 "WebAssertions.h"
32 #import "WebBackForwardList.h"
33 #import "WebBaseNetscapePluginView.h"
34 #import "WebDOMOperationsPrivate.h"
35 #import "WebDashboardRegion.h"
36 #import "WebDataProtocol.h"
37 #import "WebDataSourcePrivate.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 "WebFrameViewInternal.h"
54 #import "WebHTMLRepresentation.h"
55 #import "WebHTMLViewInternal.h"
56 #import "WebHistoryItemPrivate.h"
57 #import "WebIconDatabase.h"
58 #import "WebInspector.h"
59 #import "WebKitErrors.h"
60 #import "WebKitLogging.h"
61 #import "WebKitNSStringExtras.h"
62 #import "WebKitStatisticsPrivate.h"
63 #import "WebLocalizableStrings.h"
64 #import "WebNSDataExtras.h"
65 #import "WebNSDataExtrasPrivate.h"
66 #import "WebNSDictionaryExtras.h"
67 #import "WebNSEventExtras.h"
68 #import "WebNSObjectExtras.h"
69 #import "WebNSPasteboardExtras.h"
70 #import "WebNSPrintOperationExtras.h"
71 #import "WebNSURLExtras.h"
72 #import "WebNSURLRequestExtras.h"
73 #import "WebNSUserDefaultsExtras.h"
74 #import "WebNSViewExtras.h"
75 #import "WebPageBridge.h"
76 #import "WebPluginDatabase.h"
77 #import "WebPolicyDelegate.h"
78 #import "WebPreferencesPrivate.h"
79 #import "WebResourceLoadDelegate.h"
80 #import "WebScriptDebugDelegatePrivate.h"
81 #import "WebTextRenderer.h"
82 #import "WebTextRepresentation.h"
83 #import "WebTextView.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/WebCoreSettings.h>
90 #import <WebCore/WebCoreView.h>
91 #import <WebKit/DOM.h>
92 #import <WebKit/DOMExtensions.h>
93 #import <WebKitSystemInterface.h>
94 #import <objc/objc-runtime.h>
97 #define PROCESSOR "PPC"
99 #define PROCESSOR "Intel"
101 #error Unknown architecture
104 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
106 macro(alignJustified) \
109 macro(capitalizeWord) \
110 macro(centerSelectionInVisibleArea) \
111 macro(changeAttributes) \
113 macro(changeDocumentBackgroundColor) \
115 macro(checkSpelling) \
121 macro(deleteBackward) \
122 macro(deleteBackwardByDecomposingPreviousCharacter) \
123 macro(deleteForward) \
124 macro(deleteToBeginningOfLine) \
125 macro(deleteToBeginningOfParagraph) \
126 macro(deleteToEndOfLine) \
127 macro(deleteToEndOfParagraph) \
128 macro(deleteWordBackward) \
129 macro(deleteWordForward) \
130 macro(ignoreSpelling) \
132 macro(insertBacktab) \
133 macro(insertNewline) \
134 macro(insertNewlineIgnoringFieldEditor) \
135 macro(insertParagraphSeparator) \
137 macro(insertTabIgnoringFieldEditor) \
138 macro(lowercaseWord) \
139 macro(moveBackward) \
140 macro(moveBackwardAndModifySelection) \
142 macro(moveDownAndModifySelection) \
144 macro(moveForwardAndModifySelection) \
146 macro(moveLeftAndModifySelection) \
148 macro(moveRightAndModifySelection) \
149 macro(moveToBeginningOfDocument) \
150 macro(moveToBeginningOfDocumentAndModifySelection) \
151 macro(moveToBeginningOfLine) \
152 macro(moveToBeginningOfLineAndModifySelection) \
153 macro(moveToBeginningOfParagraph) \
154 macro(moveToBeginningOfParagraphAndModifySelection) \
155 macro(moveToEndOfDocument) \
156 macro(moveToEndOfDocumentAndModifySelection) \
157 macro(moveToEndOfLine) \
158 macro(moveToEndOfLineAndModifySelection) \
159 macro(moveToEndOfParagraph) \
160 macro(moveToEndOfParagraphAndModifySelection) \
162 macro(moveUpAndModifySelection) \
163 macro(moveWordBackward) \
164 macro(moveWordBackwardAndModifySelection) \
165 macro(moveWordForward) \
166 macro(moveWordForwardAndModifySelection) \
167 macro(moveWordLeft) \
168 macro(moveWordLeftAndModifySelection) \
169 macro(moveWordRight) \
170 macro(moveWordRightAndModifySelection) \
174 macro(pasteAsPlainText) \
175 macro(pasteAsRichText) \
177 macro(performFindPanelAction) \
178 macro(scrollLineDown) \
179 macro(scrollLineUp) \
180 macro(scrollPageDown) \
181 macro(scrollPageUp) \
182 macro(scrollToBeginningOfDocument) \
183 macro(scrollToEndOfDocument) \
186 macro(selectParagraph) \
188 macro(showGuessPanel) \
189 macro(startSpeaking) \
190 macro(stopSpeaking) \
195 macro(uppercaseWord) \
197 macro(yankAndSelect) \
199 @interface NSSpellChecker (AppKitSecretsIKnow)
200 - (void)_preflightChosenSpellServer;
203 @interface NSView (AppKitSecretsIKnow)
204 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
205 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
206 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
209 @interface WebViewPrivate : NSObject
212 WebPageBridge *_pageBridge;
215 id UIDelegateForwarder;
216 id resourceProgressDelegate;
217 id resourceProgressDelegateForwarder;
220 id policyDelegateForwarder;
221 id frameLoadDelegate;
222 id frameLoadDelegateForwarder;
223 id <WebFormDelegate> formDelegate;
225 id editingDelegateForwarder;
226 id scriptDebugDelegate;
227 id scriptDebugDelegateForwarder;
229 WebBackForwardList *backForwardList;
230 BOOL useBackForwardList;
232 float textSizeMultiplier;
234 NSString *applicationNameForUserAgent;
236 BOOL userAgentOverridden;
238 BOOL defersCallbacks;
240 WebPreferences *preferences;
241 WebCoreSettings *settings;
243 BOOL lastElementWasNonNil;
245 NSWindow *hostWindow;
247 int programmaticFocusCount;
249 WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
251 long long totalPageAndResourceBytesToLoad;
252 long long totalBytesReceived;
253 double progressValue;
254 double lastNotifiedProgressValue;
255 double lastNotifiedProgressTime;
256 double progressNotificationInterval;
257 double progressNotificationTimeInterval;
258 BOOL finalProgressChangedSent;
259 WebFrame *orginatingProgressFrame;
261 int numProgressTrackedFrames;
262 NSMutableDictionary *progressItems;
264 void *observationInfo;
266 BOOL drawsBackground;
270 NSString *mediaStyle;
272 NSView <WebDocumentDragging> *draggingDocumentView;
273 unsigned int dragDestinationActionMask;
274 WebFrameBridge *dragCaretBridge;
276 BOOL hasSpellCheckerDocumentTag;
277 WebNSInt spellCheckerDocumentTag;
279 BOOL continuousSpellCheckingEnabled;
280 BOOL smartInsertDeleteEnabled;
282 BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
283 BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
284 BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
285 BOOL dashboardBehaviorAllowWheelScrolling;
287 BOOL shouldUseFontSmoothing;
288 BOOL selectWordBeforeMenuEvent;
292 @interface WebView (WebFileInternal)
293 - (WebFrame *)_selectedOrMainFrame;
294 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame;
296 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
297 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point;
298 - (WebFrame *)_focusedFrame;
299 + (void)_preflightSpellChecker;
300 - (BOOL)_continuousCheckingAllowed;
301 - (NSResponder *)_responderForResponderOperations;
302 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor;
305 NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
306 NSString *WebElementFrameKey = @"WebElementFrame";
307 NSString *WebElementImageKey = @"WebElementImage";
308 NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
309 NSString *WebElementImageRectKey = @"WebElementImageRect";
310 NSString *WebElementImageURLKey = @"WebElementImageURL";
311 NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
312 NSString *WebElementLinkURLKey = @"WebElementLinkURL";
313 NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
314 NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
315 NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
317 NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
318 NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
319 NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
321 NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
322 NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
323 NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
324 NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
325 NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
327 enum { WebViewVersion = 2 };
329 #define timedLayoutSize 4096
331 static NSMutableSet *schemesWithRepresentationsSet;
333 NSString *_WebCanGoBackKey = @"canGoBack";
334 NSString *_WebCanGoForwardKey = @"canGoForward";
335 NSString *_WebEstimatedProgressKey = @"estimatedProgress";
336 NSString *_WebIsLoadingKey = @"isLoading";
337 NSString *_WebMainFrameIconKey = @"mainFrameIcon";
338 NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
339 NSString *_WebMainFrameURLKey = @"mainFrameURL";
341 @interface WebProgressItem : NSObject
344 long long bytesReceived;
345 long long estimatedLength;
349 @implementation WebProgressItem
352 static BOOL shouldUseFontSmoothing = YES;
354 @implementation WebViewPrivate
362 backForwardList = [[WebBackForwardList alloc] init];
363 textSizeMultiplier = 1;
364 progressNotificationInterval = 0.02;
365 progressNotificationTimeInterval = 0.1;
366 settings = [[WebCoreSettings alloc] init];
367 dashboardBehaviorAllowWheelScrolling = YES;
374 ASSERT(!_pageBridge);
375 ASSERT(draggingDocumentView == nil);
376 ASSERT(dragCaretBridge == nil);
378 [backForwardList release];
379 [applicationNameForUserAgent release];
382 [preferences release];
384 [hostWindow release];
386 [policyDelegateForwarder release];
387 [resourceProgressDelegateForwarder release];
388 [UIDelegateForwarder release];
389 [frameLoadDelegateForwarder release];
390 [editingDelegateForwarder release];
391 [scriptDebugDelegateForwarder release];
393 [progressItems release];
395 [mediaStyle release];
402 @implementation WebView (AllWebViews)
404 static CFSetCallBacks NonRetainingSetCallbacks = {
413 static CFMutableSetRef allWebViewsSet;
415 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
420 [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
423 - (void)_removeFromAllWebViewsSet
426 CFSetRemoveValue(allWebViewsSet, self);
429 - (void)_addToAllWebViewsSet
432 allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
434 CFSetSetValue(allWebViewsSet, self);
439 @implementation WebView (WebPrivate)
441 #ifdef DEBUG_WIDGET_DRAWING
442 static bool debugWidget = true;
443 - (void)drawRect:(NSRect)rect
445 [[NSColor blueColor] set];
448 NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
451 while (debugWidget) {
456 NSLog (@"%s: rect: (%0.f,%0.f) %0.f %0.f, htmlViewRect: (%0.f,%0.f) %0.f %0.f\n",
457 __PRETTY_FUNCTION__, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
458 htmlViewRect.origin.x, htmlViewRect.origin.y, htmlViewRect.size.width, htmlViewRect.size.height
461 [super drawRect:rect];
465 + (NSArray *)_supportedMIMETypes
467 // Load the plug-in DB allowing plug-ins to install types.
468 [WebPluginDatabase installedPlugins];
469 return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
472 + (NSArray *)_supportedFileExtensions
474 NSMutableSet *extensions = [[NSMutableSet alloc] init];
475 NSArray *MIMETypes = [self _supportedMIMETypes];
476 NSEnumerator *enumerator = [MIMETypes objectEnumerator];
478 while ((MIMEType = [enumerator nextObject]) != nil) {
479 NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
480 if (extensionsForType) {
481 [extensions addObjectsFromArray:extensionsForType];
484 NSArray *uniqueExtensions = [extensions allObjects];
485 [extensions release];
486 return uniqueExtensions;
489 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
491 MIMEType = [MIMEType lowercaseString];
492 Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
493 Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
495 if (!viewClass || !repClass) {
496 // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
497 // Load the plug-in DB allowing plug-ins to install types.
498 [WebPluginDatabase installedPlugins];
500 // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
501 viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
502 repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
505 if (viewClass && repClass) {
506 // Special-case WebTextView for text types that shouldn't be shown.
507 if (viewClass == [WebTextView class] &&
508 repClass == [WebTextRepresentation class] &&
509 [[WebTextView unsupportedTextMIMETypes] containsObject:MIMEType]) {
522 + (void)_setAlwaysUseATSU:(BOOL)f
524 [WebTextRenderer setAlwaysUseATSU:f];
527 + (BOOL)canShowFile:(NSString *)path
529 return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
532 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
534 return WKGetPreferredExtensionForMIMEType(type);
539 [self _removeFromAllWebViewsSet];
540 [self setGroupName:nil];
542 // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
543 [self removeDragCaret];
545 [[self mainFrame] _detachFromParent];
546 [_private->_pageBridge release];
547 _private->_pageBridge = nil;
549 // Clear the page cache so we call destroy on all the plug-ins in the page cache to break any retain cycles.
550 // See comment in [WebHistoryItem _releaseAllPendingPageCaches] for more information.
551 [_private->backForwardList _clearPageCache];
553 if (_private->hasSpellCheckerDocumentTag) {
554 [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
555 _private->hasSpellCheckerDocumentTag = NO;
559 - (void)_finishedLoadingResourceFromDataSource:(WebDataSource *)dataSource
561 WebFrame *frame = [dataSource webFrame];
563 ASSERT(dataSource != nil);
565 // This resource has completed, so check if the load is complete for all frames.
567 [frame _checkLoadComplete];
570 - (void)_mainReceivedBytesSoFar:(unsigned)bytesSoFar fromDataSource:(WebDataSource *)dataSource complete: (BOOL)isComplete
572 WebFrame *frame = [dataSource webFrame];
574 ASSERT(dataSource != nil);
576 // The frame may be nil if a previously cancelled load is still making progress callbacks.
580 // This resource has completed, so check if the load is complete for this frame and its ancestors
582 // If the load is complete, mark the primary load as done. The primary load is the load
583 // of the main document. Other resources may still be arriving.
584 [dataSource _setPrimaryLoadComplete:YES];
585 [frame _checkLoadComplete];
589 - (void)_receivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource
591 WebFrame *frame = [dataSource webFrame];
593 [frame _checkLoadComplete];
596 - (void)_mainReceivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource complete:(BOOL)isComplete
599 ASSERT([dataSource webFrame]);
601 [dataSource _setMainDocumentError: error];
604 [dataSource _setPrimaryLoadComplete:YES];
605 [[dataSource webFrame] _checkLoadComplete];
609 + (NSString *)_MIMETypeForFile:(NSString *)path
611 NSString *extension = [path pathExtension];
612 NSString *MIMEType = nil;
614 // Get the MIME type from the extension.
615 if ([extension length] != 0) {
616 MIMEType = WKGetMIMETypeForExtension(extension);
619 // If we can't get a known MIME type from the extension, sniff.
620 if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
621 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
622 NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
624 if ([data length] != 0) {
625 MIMEType = [data _webkit_guessedMIMEType];
627 if ([MIMEType length] == 0) {
628 MIMEType = @"application/octet-stream";
635 - (void)_downloadURL:(NSURL *)URL
637 [self _downloadURL:URL toDirectory:nil];
640 - (void)_downloadURL:(NSURL *)URL toDirectory:(NSString *)directory
644 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
645 [WebDownload _downloadWithRequest:request
646 delegate:_private->downloadDelegate
647 directory:[directory isAbsolutePath] ? directory : nil];
651 - (BOOL)defersCallbacks
653 return _private->defersCallbacks;
656 - (void)setDefersCallbacks:(BOOL)defers
658 if (defers == _private->defersCallbacks) {
662 _private->defersCallbacks = defers;
663 [[self mainFrame] _defersCallbacksChanged];
666 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
668 id wd = [self UIDelegate];
669 WebView *newWindowWebView = nil;
670 if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
671 newWindowWebView = [wd webView:self createWebViewWithRequest:request];
673 newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
676 [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
678 return newWindowWebView;
681 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
683 NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
684 webView:self contextMenuItemsForElement:element defaultMenuItems:items];
685 NSArray *menuItems = defaultMenuItems;
689 if (_private->UIDelegate) {
690 id cd = _private->UIDelegate;
692 if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)])
693 menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
696 if (menuItems && [menuItems count] > 0) {
697 menu = [[[NSMenu alloc] init] autorelease];
699 for (i=0; i<[menuItems count]; i++) {
700 [menu addItem:[menuItems objectAtIndex:i]];
705 BOOL enableInspectElement = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitDeveloperExtras"];
706 enableInspectElement |= [[NSUserDefaults standardUserDefaults] boolForKey:@"IncludeDebugMenu"];
707 // FIXME: remove the following check later, once everyone switches to the new generic default name
708 enableInspectElement |= [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitEnableInspectElementContextMenuItem"];
710 BOOL enableInspectElement = YES; // always enable in debug builds
713 // optionally add the Inspect Element menu item it if preference is set or in debug builds
714 // and only showing the menu item if we are working with a WebHTMLView
715 WebFrame *webFrame = [element objectForKey:WebElementFrameKey];
716 if (enableInspectElement && [[[webFrame frameView] documentView] isKindOfClass:[WebHTMLView class]]) {
718 menu = [[[NSMenu alloc] init] autorelease];
719 else if ([menu numberOfItems])
720 [menu addItem:[NSMenuItem separatorItem]];
721 NSMenuItem *menuItem = [[[NSMenuItem alloc] init] autorelease];
722 [menuItem setAction:@selector(_inspectElement:)];
723 [menuItem setTitle:UI_STRING("Inspect Element", "Inspect Element context menu item")];
724 [menuItem setRepresentedObject:element];
725 [menu addItem:menuItem];
731 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(WebNSUInt)modifierFlags
733 // When the mouse isn't over this view at all, we'll get called with a dictionary of nil over
734 // and over again. So it's a good idea to catch that here and not send multiple calls to the delegate
737 if (dictionary && _private->lastElementWasNonNil) {
738 [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
740 _private->lastElementWasNonNil = dictionary != nil;
743 - (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
745 // We never go back/forward on a per-frame basis, so the target must be the main frame
746 //ASSERT([item target] == nil || [self _findFrameNamed:[item target]] == [self mainFrame]);
748 // abort any current load if we're going back/forward
749 [[self mainFrame] stopLoading];
750 [[self mainFrame] _goToItem:item withLoadType:type];
753 // Not used now, but could be if we ever store frames in bookmarks or history
754 - (void)_loadItem:(WebHistoryItem *)item
756 WebHistoryItem *newItem = [item copy]; // Makes a deep copy, happily
757 [[self backForwardList] addItem:newItem];
758 [self _goToItem:newItem withLoadType:WebFrameLoadTypeIndexedBackForward];
761 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
763 // It turns out the right combination of behavior is done with the back/forward load
764 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
765 // in the back forward list, and go to the current one.
767 WebBackForwardList *bfList = [self backForwardList];
768 ASSERT(![bfList currentItem]); // destination list should be empty
770 WebBackForwardList *otherBFList = [otherView backForwardList];
771 if (![otherBFList currentItem]) {
772 return; // empty back forward list, bail
775 WebHistoryItem *newItemToGoTo = nil;
776 int lastItemIndex = [otherBFList forwardListCount];
778 for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
780 // If this item is showing , save away its current scroll and form state,
781 // since that might have changed since loading and it is normally not saved
782 // until we leave that page.
783 [[otherView mainFrame] _saveDocumentAndScrollState];
785 WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
786 [bfList addItem:newItem];
788 newItemToGoTo = newItem;
792 [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
795 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
797 _private->formDelegate = delegate;
800 - (id<WebFormDelegate>)_formDelegate
802 if (!_private->formDelegate) {
803 // create lazily, to give the client a chance to set one before we bother to alloc the shared one
804 _private->formDelegate = [WebFormDelegate _sharedWebFormDelegate];
806 return _private->formDelegate;
809 - (WebCoreSettings *)_settings
811 return _private->settings;
814 - (void)_updateWebCoreSettingsFromPreferences:(WebPreferences *)preferences
816 [_private->settings setCursiveFontFamily:[preferences cursiveFontFamily]];
817 [_private->settings setDefaultFixedFontSize:[preferences defaultFixedFontSize]];
818 [_private->settings setDefaultFontSize:[preferences defaultFontSize]];
819 [_private->settings setDefaultTextEncoding:[preferences defaultTextEncodingName]];
820 [_private->settings setFantasyFontFamily:[preferences fantasyFontFamily]];
821 [_private->settings setFixedFontFamily:[preferences fixedFontFamily]];
822 [_private->settings setJavaEnabled:[preferences isJavaEnabled]];
823 [_private->settings setJavaScriptEnabled:[preferences isJavaScriptEnabled]];
824 [_private->settings setJavaScriptCanOpenWindowsAutomatically:[preferences javaScriptCanOpenWindowsAutomatically]];
825 [_private->settings setMinimumFontSize:[preferences minimumFontSize]];
826 [_private->settings setMinimumLogicalFontSize:[preferences minimumLogicalFontSize]];
827 [_private->settings setPluginsEnabled:[preferences arePlugInsEnabled]];
828 [_private->settings setSansSerifFontFamily:[preferences sansSerifFontFamily]];
829 [_private->settings setSerifFontFamily:[preferences serifFontFamily]];
830 [_private->settings setStandardFontFamily:[preferences standardFontFamily]];
831 [_private->settings setWillLoadImagesAutomatically:[preferences loadsImagesAutomatically]];
833 if ([preferences userStyleSheetEnabled]) {
834 [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
836 [_private->settings setUserStyleSheetLocation:@""];
838 [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
839 [_private->settings setTextAreasAreResizable:[preferences textAreasAreResizable]];
842 - (void)_preferencesChangedNotification: (NSNotification *)notification
844 WebPreferences *preferences = (WebPreferences *)[notification object];
846 ASSERT(preferences == [self preferences]);
847 if (!_private->userAgentOverridden) {
848 [_private->userAgent release];
849 _private->userAgent = nil;
851 [self _updateWebCoreSettingsFromPreferences: preferences];
854 - _frameLoadDelegateForwarder
856 if (!_private->frameLoadDelegateForwarder)
857 _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate] defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
858 return _private->frameLoadDelegateForwarder;
861 - _resourceLoadDelegateForwarder
863 if (!_private->resourceProgressDelegateForwarder)
864 _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
865 return _private->resourceProgressDelegateForwarder;
868 - (void)_cacheResourceLoadDelegateImplementations
870 WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
871 id delegate = [self resourceLoadDelegate];
873 cache->delegateImplementsDidCancelAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:)];
874 cache->delegateImplementsDidReceiveAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:)];
875 cache->delegateImplementsDidFinishLoadingFromDataSource = [delegate respondsToSelector:@selector(webView:resource:didFinishLoadingFromDataSource:)];
876 cache->delegateImplementsDidReceiveContentLength = [delegate respondsToSelector:@selector(webView:resource:didReceiveContentLength:fromDataSource:)];
877 cache->delegateImplementsDidReceiveResponse = [delegate respondsToSelector:@selector(webView:resource:didReceiveResponse:fromDataSource:)];
878 cache->delegateImplementsWillSendRequest = [delegate respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)];
879 cache->delegateImplementsIdentifierForRequest = [delegate respondsToSelector:@selector(webView:identifierForInitialRequest:fromDataSource:)];
882 - (WebResourceDelegateImplementationCache)_resourceLoadDelegateImplementations
884 return _private->resourceLoadDelegateImplementations;
887 - _policyDelegateForwarder
889 if (!_private->policyDelegateForwarder)
890 _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
891 return _private->policyDelegateForwarder;
894 - _UIDelegateForwarder
896 if (!_private->UIDelegateForwarder)
897 _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
898 return _private->UIDelegateForwarder;
901 - _editingDelegateForwarder
903 // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
904 // Not sure if that is a bug or not.
907 if (!_private->editingDelegateForwarder)
908 _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self editingDelegate] defaultTarget: [WebDefaultEditingDelegate sharedEditingDelegate] templateClass: [WebDefaultEditingDelegate class]];
909 return _private->editingDelegateForwarder;
912 - _scriptDebugDelegateForwarder
914 if (!_private->scriptDebugDelegateForwarder)
915 _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self scriptDebugDelegate] defaultTarget: [WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] templateClass: [WebDefaultScriptDebugDelegate class]];
916 return _private->scriptDebugDelegateForwarder;
921 [[self _UIDelegateForwarder] webViewClose:self];
924 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
926 [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
927 [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
930 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
932 NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
933 [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
935 // This is used to make _representationExistsForURLScheme faster.
936 // Without this set, we'd have to create the MIME type each time.
937 if (schemesWithRepresentationsSet == nil) {
938 schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
940 [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
943 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
945 return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
948 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
950 return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
953 + (BOOL)_canHandleRequest:(NSURLRequest *)request
955 if ([NSURLConnection canHandleRequest:request]) {
959 // We're always willing to load alternate content for unreachable URLs
960 if ([request _webDataRequestUnreachableURL]) {
964 return [self _representationExistsForURLScheme:[[request URL] scheme]];
967 + (NSString *)_decodeData:(NSData *)data
969 return [WebCoreEncodings decodeData:data];
972 - (void)_pushPerformingProgrammaticFocus
974 _private->programmaticFocusCount++;
977 - (void)_popPerformingProgrammaticFocus
979 _private->programmaticFocusCount--;
982 - (BOOL)_isPerformingProgrammaticFocus
984 return _private->programmaticFocusCount != 0;
987 #define UnknownTotalBytes -1
988 #define WebProgressItemDefaultEstimatedLength 1024*16
990 - (void)_didChangeValueForKey: (NSString *)key
992 LOG (Bindings, "calling didChangeValueForKey: %@", key);
993 [self didChangeValueForKey: key];
996 - (void)_willChangeValueForKey: (NSString *)key
998 LOG (Bindings, "calling willChangeValueForKey: %@", key);
999 [self willChangeValueForKey: key];
1002 // Always start progress at INITIAL_PROGRESS_VALUE so it appears progress indicators
1003 // will immediately show some progress. This helps provide feedback as soon as a load
1005 #define INITIAL_PROGRESS_VALUE 0.1
1007 - (void)_resetProgress
1009 [_private->progressItems release];
1010 _private->progressItems = nil;
1011 _private->totalPageAndResourceBytesToLoad = 0;
1012 _private->totalBytesReceived = 0;
1013 _private->progressValue = 0;
1014 _private->lastNotifiedProgressValue = 0;
1015 _private->lastNotifiedProgressTime = 0;
1016 _private->finalProgressChangedSent = NO;
1017 _private->numProgressTrackedFrames = 0;
1018 [_private->orginatingProgressFrame release];
1019 _private->orginatingProgressFrame = nil;
1021 - (void)_progressStarted:(WebFrame *)frame
1023 LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->orginatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->orginatingProgressFrame);
1024 [self _willChangeValueForKey: @"estimatedProgress"];
1025 if (_private->numProgressTrackedFrames == 0 || _private->orginatingProgressFrame == frame){
1026 [self _resetProgress];
1027 _private->progressValue = INITIAL_PROGRESS_VALUE;
1028 _private->orginatingProgressFrame = [frame retain];
1029 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressStartedNotification object:self];
1031 _private->numProgressTrackedFrames++;
1032 [self _didChangeValueForKey: @"estimatedProgress"];
1035 - (void)_finalProgressComplete
1039 // Before resetting progress value be sure to send client a least one notification
1040 // with final progress value.
1041 if (!_private->finalProgressChangedSent) {
1042 _private->progressValue = 1;
1043 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1046 [self _resetProgress];
1048 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
1051 - (void)_progressCompleted:(WebFrame *)frame
1053 LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->orginatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->orginatingProgressFrame);
1055 if (_private->numProgressTrackedFrames <= 0)
1058 [self _willChangeValueForKey: @"estimatedProgress"];
1060 _private->numProgressTrackedFrames--;
1061 if (_private->numProgressTrackedFrames == 0 ||
1062 (frame == _private->orginatingProgressFrame && _private->numProgressTrackedFrames != 0)){
1063 [self _finalProgressComplete];
1065 [self _didChangeValueForKey: @"estimatedProgress"];
1068 - (void)_incrementProgressForConnectionDelegate:(id)connectionDelegate response:(NSURLResponse *)response;
1070 if (!connectionDelegate)
1073 LOG (Progress, "_private->numProgressTrackedFrames %d, _private->orginatingProgressFrame %p", _private->numProgressTrackedFrames, _private->orginatingProgressFrame);
1075 if (_private->numProgressTrackedFrames <= 0)
1078 WebProgressItem *item = [[WebProgressItem alloc] init];
1083 long long length = [response expectedContentLength];
1085 length = WebProgressItemDefaultEstimatedLength;
1087 item->estimatedLength = length;
1088 _private->totalPageAndResourceBytesToLoad += length;
1090 if (!_private->progressItems)
1091 _private->progressItems = [[NSMutableDictionary alloc] init];
1093 [_private->progressItems _webkit_setObject:item forUncopiedKey:connectionDelegate];
1097 - (void)_incrementProgressForConnectionDelegate:(id)connectionDelegate data:(NSData *)data
1099 if (!connectionDelegate)
1102 WebProgressItem *item = [_private->progressItems objectForKey:connectionDelegate];
1107 [self _willChangeValueForKey: @"estimatedProgress"];
1109 unsigned bytesReceived = [data length];
1110 double increment = 0, percentOfRemainingBytes;
1111 long long remainingBytes, estimatedBytesForPendingRequests;
1113 item->bytesReceived += bytesReceived;
1114 if (item->bytesReceived > item->estimatedLength){
1115 _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
1116 item->estimatedLength = item->bytesReceived*2;
1119 int numPendingOrLoadingRequests = [[self mainFrame] _numPendingOrLoadingRequests:YES];
1120 estimatedBytesForPendingRequests = WebProgressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
1121 remainingBytes = ((_private->totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - _private->totalBytesReceived);
1122 percentOfRemainingBytes = (double)bytesReceived / (double)remainingBytes;
1123 increment = (1.0 - _private->progressValue) * percentOfRemainingBytes;
1125 _private->totalBytesReceived += bytesReceived;
1127 _private->progressValue += increment;
1129 if (_private->progressValue < 0.0)
1130 _private->progressValue = 0.0;
1132 if (_private->progressValue > 1.0)
1133 _private->progressValue = 1.0;
1135 double now = CFAbsoluteTimeGetCurrent();
1136 double notifiedProgressTimeDelta = CFAbsoluteTimeGetCurrent() - _private->lastNotifiedProgressTime;
1137 _private->lastNotifiedProgressTime = now;
1139 LOG (Progress, "_private->progressValue %g, _private->numProgressTrackedFrames %d", _private->progressValue, _private->numProgressTrackedFrames);
1140 double notificationProgressDelta = _private->progressValue - _private->lastNotifiedProgressValue;
1141 if ((notificationProgressDelta >= _private->progressNotificationInterval ||
1142 notifiedProgressTimeDelta >= _private->progressNotificationTimeInterval) &&
1143 _private->numProgressTrackedFrames > 0) {
1144 if (!_private->finalProgressChangedSent) {
1145 if (_private->progressValue == 1)
1146 _private->finalProgressChangedSent = YES;
1147 [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1148 _private->lastNotifiedProgressValue = _private->progressValue;
1152 [self _didChangeValueForKey: @"estimatedProgress"];
1155 - (void)_completeProgressForConnectionDelegate:(id)connectionDelegate
1157 WebProgressItem *item = [_private->progressItems objectForKey:connectionDelegate];
1162 // Adjust the total expected bytes to account for any overage/underage.
1163 long long delta = item->bytesReceived - item->estimatedLength;
1164 _private->totalPageAndResourceBytesToLoad += delta;
1165 item->estimatedLength = item->bytesReceived;
1168 // Required to prevent automatic observer notifications.
1169 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1173 - (NSArray *)_declaredKeys {
1174 static NSArray *declaredKeys = nil;
1176 if (!declaredKeys) {
1177 declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, nil];
1180 return declaredKeys;
1183 - (void)setObservationInfo:(void *)info
1185 _private->observationInfo = info;
1188 - (void *)observationInfo
1190 return _private->observationInfo;
1193 - (void)_willChangeBackForwardKeys
1195 [self _willChangeValueForKey: _WebCanGoBackKey];
1196 [self _willChangeValueForKey: _WebCanGoForwardKey];
1199 - (void)_didChangeBackForwardKeys
1201 [self _didChangeValueForKey: _WebCanGoBackKey];
1202 [self _didChangeValueForKey: _WebCanGoForwardKey];
1205 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1207 [self _willChangeBackForwardKeys];
1208 if (frame == [self mainFrame]){
1209 // Force an observer update by sending a will/did.
1210 [self _willChangeValueForKey: _WebIsLoadingKey];
1211 [self _didChangeValueForKey: _WebIsLoadingKey];
1213 [self _willChangeValueForKey: _WebMainFrameURLKey];
1215 [NSApp setWindowsNeedUpdate:YES];
1218 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1220 if (frame == [self mainFrame]){
1221 [self _didChangeValueForKey: _WebMainFrameURLKey];
1223 [NSApp setWindowsNeedUpdate:YES];
1226 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1228 [self _didChangeBackForwardKeys];
1229 if (frame == [self mainFrame]){
1230 // Force an observer update by sending a will/did.
1231 [self _willChangeValueForKey: _WebIsLoadingKey];
1232 [self _didChangeValueForKey: _WebIsLoadingKey];
1234 [NSApp setWindowsNeedUpdate:YES];
1237 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1239 [self _didChangeBackForwardKeys];
1240 if (frame == [self mainFrame]){
1241 // Force an observer update by sending a will/did.
1242 [self _willChangeValueForKey: _WebIsLoadingKey];
1243 [self _didChangeValueForKey: _WebIsLoadingKey];
1245 [NSApp setWindowsNeedUpdate:YES];
1248 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1250 [self _didChangeBackForwardKeys];
1251 if (frame == [self mainFrame]){
1252 // Force an observer update by sending a will/did.
1253 [self _willChangeValueForKey: _WebIsLoadingKey];
1254 [self _didChangeValueForKey: _WebIsLoadingKey];
1256 [self _didChangeValueForKey: _WebMainFrameURLKey];
1258 [NSApp setWindowsNeedUpdate:YES];
1261 - (void)_reloadForPluginChanges
1263 [[self mainFrame] _reloadForPluginChanges];
1266 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1268 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1269 [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1270 NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1272 return cachedResponse;
1275 - (void)_writeImageElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1277 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1278 [pasteboard _web_writeImage:nil
1279 element:[element objectForKey:WebElementDOMNodeKey]
1280 URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1281 title:[element objectForKey:WebElementImageAltStringKey]
1282 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1286 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1288 [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1289 andTitle:[element objectForKey:WebElementLinkLabelKey]
1293 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1295 _private->initiatedDrag = initiatedDrag;
1298 #define DASHBOARD_CONTROL_LABEL @"control"
1300 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1302 // Add scroller regions for NSScroller and KWQScrollBar
1303 int i, count = [views count];
1305 for (i = 0; i < count; i++) {
1306 NSView *aView = [views objectAtIndex:i];
1308 if ([aView isKindOfClass:[NSScroller class]] ||
1309 [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1310 NSRect bounds = [aView bounds];
1311 NSRect adjustedBounds;
1312 adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1313 adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1315 // AppKit has horrible hack of placing absent scrollers at -100,-100
1316 if (adjustedBounds.origin.y == -100)
1318 adjustedBounds.size = bounds.size;
1319 NSRect clip = [aView visibleRect];
1320 NSRect adjustedClip;
1321 adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1322 adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1323 adjustedClip.size = clip.size;
1324 WebDashboardRegion *aRegion =
1325 [[[WebDashboardRegion alloc] initWithRect:adjustedBounds
1326 clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1327 NSMutableArray *scrollerRegions;
1328 scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1329 if (!scrollerRegions) {
1330 scrollerRegions = [NSMutableArray array];
1331 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1333 [scrollerRegions addObject:aRegion];
1335 [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1339 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1341 [self _addScrollerDashboardRegions:regions from:[self subviews]];
1344 - (NSDictionary *)_dashboardRegions
1346 // Only return regions from main frame.
1347 NSMutableDictionary *regions = [[[self mainFrame] _bridge] dashboardRegions];
1348 [self _addScrollerDashboardRegions:regions];
1352 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag;
1355 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1356 _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1359 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1360 _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1363 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1364 _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1367 case WebDashboardBehaviorAllowWheelScrolling: {
1368 _private->dashboardBehaviorAllowWheelScrolling = flag;
1374 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1377 case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1378 return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1380 case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1381 return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1383 case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1384 return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1386 case WebDashboardBehaviorAllowWheelScrolling: {
1387 return _private->dashboardBehaviorAllowWheelScrolling;
1393 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1395 [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:self resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:dataSource];
1398 + (void)_setShouldUseFontSmoothing:(BOOL)f
1400 shouldUseFontSmoothing = f;
1403 + (BOOL)_shouldUseFontSmoothing
1405 return shouldUseFontSmoothing;
1408 + (NSString *)_minimumRequiredSafariBuildNumber
1416 @implementation _WebSafeForwarder
1418 - initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
1420 self = [super init];
1424 target = t; // Non retained.
1426 templateClass = aClass;
1431 // Used to send messages to delegates that implement informal protocols.
1432 + safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
1434 return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
1438 NSMutableDictionary *countInvocations;
1441 - (void)forwardInvocation:(NSInvocation *)anInvocation
1444 if (!countInvocations){
1445 countInvocations = [[NSMutableDictionary alloc] init];
1447 NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
1449 count = [NSNumber numberWithInt: 1];
1451 count = [NSNumber numberWithInt: [count intValue] + 1];
1452 [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
1454 if ([target respondsToSelector: [anInvocation selector]])
1455 [anInvocation invokeWithTarget: target];
1456 else if ([defaultTarget respondsToSelector: [anInvocation selector]])
1457 [anInvocation invokeWithTarget: defaultTarget];
1458 // Do nothing quietly if method not implemented.
1461 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1463 return [templateClass instanceMethodSignatureForSelector: aSelector];
1468 @implementation WebView
1470 #if REMOVE_SAFARI_DOM_TREE_DEBUG_ITEM
1471 // this prevents open source users from crashing when using the Show DOM Tree menu item in Safari
1472 // FIXME: remove this when it is no longer needed to prevent Safari from crashing
1475 static BOOL tooLate = NO;
1477 if ([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"IncludeDebugMenu"])
1478 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_finishedLaunching) name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1483 +(void)_finishedLaunching
1485 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_removeDOMTreeMenuItem:) name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1486 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1489 +(void)_removeDOMTreeMenuItem:(NSNotification *)notification
1491 NSMenu *debugMenu = [[[[NSApp mainMenu] itemArray] lastObject] submenu];
1492 NSMenuItem *domTree = [debugMenu itemWithTitle:@"Show DOM Tree"];
1494 [debugMenu removeItem:domTree];
1495 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1499 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1501 return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1504 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1506 return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1509 + (NSArray *)MIMETypesShownAsHTML
1511 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1512 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1514 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1516 while ((key = [enumerator nextObject])) {
1517 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1518 [array addObject:key];
1524 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1526 NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1527 NSEnumerator *enumerator = [viewTypes keyEnumerator];
1529 while ((key = [enumerator nextObject])) {
1530 if ([viewTypes objectForKey:key] == [WebHTMLView class])
1531 [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1534 int i, count = [MIMETypes count];
1535 for (i = 0; i < count; i++) {
1536 [WebView registerViewClass:[WebHTMLView class]
1537 representationClass:[WebHTMLRepresentation class]
1538 forMIMEType:[MIMETypes objectAtIndex:i]];
1542 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1544 return [pasteboard _web_bestURL];
1547 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1549 return [pasteboard stringForType:WebURLNamePboardType];
1552 - (void)_registerDraggedTypes
1554 NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1555 NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1556 NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1557 [types addObjectsFromArray:URLTypes];
1558 [self registerForDraggedTypes:[types allObjects]];
1562 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1564 static bool CGContextInitialized = false;
1565 if (!CGContextInitialized) {
1566 WKDisableCGDeferredUpdates();
1567 CGContextInitialized = true;
1570 _private->drawsBackground = YES;
1571 _private->smartInsertDeleteEnabled = YES;
1573 NSRect f = [self frame];
1574 WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1575 [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1576 [self addSubview:frameView];
1577 [frameView release];
1579 _private->_pageBridge = [[WebPageBridge alloc] initWithMainFrameName:frameName webView:self frameView:frameView];
1581 [self _addToAllWebViewsSet];
1582 [self setGroupName:groupName];
1584 // If there's already a next key view (e.g., from a nib), wire it up to our
1585 // contained frame view. In any case, wire our next key view up to the our
1586 // contained frame view. This works together with our becomeFirstResponder
1587 // and setNextKeyView overrides.
1588 NSView *nextKeyView = [self nextKeyView];
1589 if (nextKeyView != nil && nextKeyView != frameView) {
1590 [frameView setNextKeyView:nextKeyView];
1592 [super setNextKeyView:frameView];
1596 [self _registerDraggedTypes];
1598 // Update WebCore with preferences. These values will either come from an archived WebPreferences,
1599 // or from the standard preferences, depending on whether this method was called from initWithCoder:
1600 // or initWithFrame, respectively.
1601 [self _updateWebCoreSettingsFromPreferences: [self preferences]];
1603 // Register to receive notifications whenever preference values change.
1604 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1605 name:WebPreferencesChangedNotification object:[self preferences]];
1608 - initWithFrame:(NSRect)f
1610 return [self initWithFrame:f frameName:nil groupName:nil];
1613 - initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1615 self = [super initWithFrame:f];
1619 #if ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1620 // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1621 // may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
1622 // need for Safari to unset it to prevent it from being passed to applications it launches.
1623 // Unsetting it when a WebView is first created is as good a place as any.
1624 // See <http://bugzilla.opendarwin.org/show_bug.cgi?id=4286> for more details.
1625 if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1626 unsetenv("DYLD_FRAMEWORK_PATH");
1627 unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1631 _private = [[WebViewPrivate alloc] init];
1632 [self _commonInitializationWithFrameName:frameName groupName:groupName];
1633 [self setMaintainsBackForwardList: YES];
1637 - (id)initWithCoder:(NSCoder *)decoder
1639 WebView *result = nil;
1643 NSString *frameName;
1644 NSString *groupName;
1645 WebPreferences *preferences;
1646 BOOL useBackForwardList;
1648 result = [super initWithCoder:decoder];
1649 result->_private = [[WebViewPrivate alloc] init];
1651 // We don't want any of the archived subviews. The subviews will always
1652 // be created in _commonInitializationFrameName:groupName:.
1653 [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1655 if ([decoder allowsKeyedCoding]) {
1656 frameName = [decoder decodeObjectForKey:@"FrameName"];
1657 groupName = [decoder decodeObjectForKey:@"GroupName"];
1658 preferences = [decoder decodeObjectForKey:@"Preferences"];
1659 result->_private->useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1662 [decoder decodeValueOfObjCType:@encode(int) at:&version];
1663 frameName = [decoder decodeObject];
1664 groupName = [decoder decodeObject];
1665 preferences = [decoder decodeObject];
1667 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1670 if (![frameName isKindOfClass:[NSString class]])
1672 if (![groupName isKindOfClass:[NSString class]])
1674 if (![preferences isKindOfClass:[WebPreferences class]])
1677 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1680 [result setPreferences:preferences];
1681 result->_private->useBackForwardList = useBackForwardList;
1682 [result _commonInitializationWithFrameName:frameName groupName:groupName];
1694 - (void)encodeWithCoder:(NSCoder *)encoder
1696 [super encodeWithCoder:encoder];
1698 if ([encoder allowsKeyedCoding]) {
1699 [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
1700 [encoder encodeObject:[self groupName] forKey:@"GroupName"];
1701 [encoder encodeObject:[self preferences] forKey:@"Preferences"];
1702 [encoder encodeBool:_private->useBackForwardList forKey:@"UseBackForwardList"];
1704 int version = WebViewVersion;
1705 [encoder encodeValueOfObjCType:@encode(int) at:&version];
1706 [encoder encodeObject:[[self mainFrame] name]];
1707 [encoder encodeObject:[self groupName]];
1708 [encoder encodeObject:[self preferences]];
1709 [encoder encodeValuesOfObjCTypes:"c", &_private->useBackForwardList];
1712 LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)_private->useBackForwardList);
1721 [[NSNotificationCenter defaultCenter] removeObserver:self];
1723 [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
1726 // [super dealloc] can end up dispatching against _private (3466082)
1738 [[NSNotificationCenter defaultCenter] removeObserver:self];
1740 [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
1745 - (void)setPreferences:(WebPreferences *)prefs
1747 if (_private->preferences != prefs) {
1748 [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
1749 [WebPreferences _removeReferenceForIdentifier:[_private->preferences identifier]];
1750 [_private->preferences release];
1751 _private->preferences = [prefs retain];
1752 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1753 name:WebPreferencesChangedNotification object:[self preferences]];
1754 [[NSNotificationCenter defaultCenter]
1755 postNotificationName:WebPreferencesChangedNotification object:prefs userInfo:nil];
1759 - (WebPreferences *)preferences
1761 return _private->preferences ? _private->preferences : [WebPreferences standardPreferences];
1764 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
1766 if (![anIdentifier isEqual:[[self preferences] identifier]]) {
1767 WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
1768 [self setPreferences:prefs];
1773 - (NSString *)preferencesIdentifier
1775 return [[self preferences] identifier];
1779 - (void)setUIDelegate:delegate
1781 _private->UIDelegate = delegate;
1782 [_private->UIDelegateForwarder release];
1783 _private->UIDelegateForwarder = nil;
1788 return _private->UIDelegate;
1791 - (void)setResourceLoadDelegate: delegate
1793 _private->resourceProgressDelegate = delegate;
1794 [_private->resourceProgressDelegateForwarder release];
1795 _private->resourceProgressDelegateForwarder = nil;
1796 [self _cacheResourceLoadDelegateImplementations];
1800 - resourceLoadDelegate
1802 return _private->resourceProgressDelegate;
1806 - (void)setDownloadDelegate: delegate
1808 _private->downloadDelegate = delegate;
1814 return _private->downloadDelegate;
1817 - (void)setPolicyDelegate:delegate
1819 _private->policyDelegate = delegate;
1820 [_private->policyDelegateForwarder release];
1821 _private->policyDelegateForwarder = nil;
1826 return _private->policyDelegate;
1829 - (void)setFrameLoadDelegate:delegate
1831 _private->frameLoadDelegate = delegate;
1832 [_private->frameLoadDelegateForwarder release];
1833 _private->frameLoadDelegateForwarder = nil;
1838 return _private->frameLoadDelegate;
1841 - (WebFrame *)mainFrame
1843 // This can be called in initialization, before _private has been set up (3465613)
1847 return [(WebFrameBridge *)[_private->_pageBridge mainFrame] webFrame];
1850 - (WebBackForwardList *)backForwardList
1852 if (_private->useBackForwardList)
1853 return _private->backForwardList;
1857 - (void)setMaintainsBackForwardList: (BOOL)flag
1859 _private->useBackForwardList = flag;
1864 WebHistoryItem *item = [[self backForwardList] backItem];
1867 [self _goToItem: item withLoadType: WebFrameLoadTypeBack];
1875 WebHistoryItem *item = [[self backForwardList] forwardItem];
1878 [self _goToItem: item withLoadType: WebFrameLoadTypeForward];
1884 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
1886 [self _goToItem: item withLoadType: WebFrameLoadTypeIndexedBackForward];
1890 - (void)setTextSizeMultiplier:(float)m
1892 if (_private->textSizeMultiplier == m) {
1895 _private->textSizeMultiplier = m;
1898 - (float)textSizeMultiplier
1900 return _private->textSizeMultiplier;
1903 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
1905 NSString *name = [applicationName copy];
1906 [_private->applicationNameForUserAgent release];
1907 _private->applicationNameForUserAgent = name;
1908 if (!_private->userAgentOverridden) {
1909 [_private->userAgent release];
1910 _private->userAgent = nil;
1914 - (NSString *)applicationNameForUserAgent
1916 return [[_private->applicationNameForUserAgent retain] autorelease];
1919 - (void)setCustomUserAgent:(NSString *)userAgentString
1921 NSString *override = [userAgentString copy];
1922 [_private->userAgent release];
1923 _private->userAgent = override;
1924 _private->userAgentOverridden = override != nil;
1927 - (NSString *)customUserAgent
1929 return _private->userAgentOverridden ? [[_private->userAgent retain] autorelease] : nil;
1932 - (void)setMediaStyle:(NSString *)mediaStyle
1934 if (_private->mediaStyle != mediaStyle) {
1935 [_private->mediaStyle release];
1936 _private->mediaStyle = [mediaStyle copy];
1940 - (NSString *)mediaStyle
1942 return _private->mediaStyle;
1945 - (BOOL)supportsTextEncoding
1947 id documentView = [[[self mainFrame] frameView] documentView];
1948 return [documentView conformsToProtocol:@protocol(WebDocumentText)]
1949 && [documentView supportsTextEncoding];
1952 - (void)setCustomTextEncodingName:(NSString *)encoding
1954 NSString *oldEncoding = [self customTextEncodingName];
1955 if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding]) {
1958 [[self mainFrame] _reloadAllowingStaleDataWithOverrideEncoding:encoding];
1961 - (NSString *)_mainFrameOverrideEncoding
1963 WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
1964 if (dataSource == nil) {
1965 dataSource = [[self mainFrame] dataSource];
1967 if (dataSource == nil) {
1970 return [dataSource _overrideEncoding];
1973 - (NSString *)customTextEncodingName
1975 return [self _mainFrameOverrideEncoding];
1978 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
1980 return [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
1983 - (WebScriptObject *)windowScriptObject
1985 return [[[self mainFrame] _bridge] windowScriptObject];
1989 // Get the appropriate user-agent string for a particular URL.
1990 // Since we no longer automatically spoof, this no longer requires looking at the URL.
1991 - (NSString *)userAgentForURL:(NSURL *)URL
1993 NSString *userAgent = _private->userAgent;
1995 return [[userAgent retain] autorelease];
1998 NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
1999 id sourceVersion = [[NSBundle bundleForClass:[WebView class]]
2000 objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
2001 NSString *applicationName = _private->applicationNameForUserAgent;
2003 if ([applicationName length]) {
2004 userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko) %@",
2005 language, sourceVersion, applicationName];
2007 userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko)",
2008 language, sourceVersion];
2011 _private->userAgent = [userAgent retain];
2015 - (void)setHostWindow:(NSWindow *)hostWindow
2017 if (hostWindow != _private->hostWindow) {
2018 [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2019 [_private->hostWindow release];
2020 _private->hostWindow = [hostWindow retain];
2021 [[self mainFrame] _viewDidMoveToHostWindow];
2025 - (NSWindow *)hostWindow
2027 return _private->hostWindow;
2030 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2032 return [[self _frameViewAtWindowPoint:point] documentView];
2035 - (NSView <WebDocumentDragging> *)_draggingDocumentViewAtWindowPoint:(NSPoint)point
2037 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:point];
2038 if ([documentView conformsToProtocol:@protocol(WebDocumentDragging)]) {
2039 return (NSView <WebDocumentDragging> *)documentView;
2044 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2046 WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2049 NSView <WebDocumentView> *documentView = [frameView documentView];
2050 if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2051 NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2052 return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2054 return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2057 - (NSDictionary *)elementAtPoint:(NSPoint)point
2059 return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2062 - (void)_setDraggingDocumentView:(NSView <WebDocumentDragging> *)newDraggingView
2064 if (_private->draggingDocumentView != newDraggingView) {
2065 [_private->draggingDocumentView release];
2066 _private->draggingDocumentView = [newDraggingView retain];
2070 - (NSDragOperation)_loadingDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2072 if (_private->dragDestinationActionMask & WebDragDestinationActionLoad) {
2073 NSPoint windowPoint = [draggingInfo draggingLocation];
2074 NSView *view = [self hitTest:[[self superview] convertPoint:windowPoint toView:nil]];
2075 // Don't accept the drag over a plug-in since plug-ins may want to handle it.
2076 if (![view isKindOfClass:[WebBaseNetscapePluginView class]] && !_private->editable && !_private->initiatedDrag) {
2077 // If not editing or dragging, use _web_dragOperationForDraggingInfo to find a URL to load on the pasteboard.
2078 return [self _web_dragOperationForDraggingInfo:draggingInfo];
2081 return NSDragOperationNone;
2084 - (NSDragOperation)_delegateDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2086 NSPoint windowPoint = [draggingInfo draggingLocation];
2087 NSView <WebDocumentDragging> *newDraggingView = [self _draggingDocumentViewAtWindowPoint:windowPoint];
2088 if (_private->draggingDocumentView != newDraggingView) {
2089 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2090 [self _setDraggingDocumentView:newDraggingView];
2093 _private->dragDestinationActionMask = [[self _UIDelegateForwarder] webView:self dragDestinationActionMaskForDraggingInfo:draggingInfo];
2094 NSDragOperation operation = NSDragOperationNone;
2096 if (_private->dragDestinationActionMask == WebDragDestinationActionNone) {
2097 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2099 operation = [_private->draggingDocumentView draggingUpdatedWithDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask];
2100 if (operation == NSDragOperationNone) {
2101 return [self _loadingDragOperationForDraggingInfo:draggingInfo];
2108 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2109 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination.
2110 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination.
2111 // Forward these calls to the document subview to make its scroll view scroll.
2112 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2114 if (![self isEditable])
2117 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2118 [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2121 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2123 if (![self isEditable])
2126 NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2127 return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2130 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2132 return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2135 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2137 return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2140 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2142 [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2143 [self _setDraggingDocumentView:nil];
2146 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2151 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2153 ASSERT(_private->draggingDocumentView == [self _draggingDocumentViewAtWindowPoint:[draggingInfo draggingLocation]]);
2155 if ([_private->draggingDocumentView concludeDragForDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask]) {
2156 [self _setDraggingDocumentView:nil];
2160 [self _setDraggingDocumentView:nil];
2162 if ([self _loadingDragOperationForDraggingInfo:draggingInfo] != NSDragOperationNone) {
2163 NSURL *URL = [[self class] URLFromPasteboard:[draggingInfo draggingPasteboard]];
2165 [[self _UIDelegateForwarder] webView:self willPerformDragDestinationAction:WebDragDestinationActionLoad forDraggingInfo:draggingInfo];
2166 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2167 [[self mainFrame] loadRequest:request];
2176 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2178 NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2179 if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2186 - (BOOL)acceptsFirstResponder
2188 return [[[self mainFrame] frameView] acceptsFirstResponder];
2191 - (BOOL)becomeFirstResponder
2193 // This works together with setNextKeyView to splice the WebView into
2194 // the key loop similar to the way NSScrollView does this. Note that
2195 // WebFrameView has very similar code.
2196 NSWindow *window = [self window];
2197 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2199 if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2200 NSView *previousValidKeyView = [self previousValidKeyView];
2201 if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2202 [window makeFirstResponder:previousValidKeyView];
2209 if ([mainFrameView acceptsFirstResponder]) {
2210 [window makeFirstResponder:mainFrameView];
2217 - (NSView *)_webcore_effectiveFirstResponder
2219 WebFrameView *frameView = [[self mainFrame] frameView];
2220 return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2223 - (void)setNextKeyView:(NSView *)aView
2225 // This works together with becomeFirstResponder to splice the WebView into
2226 // the key loop similar to the way NSScrollView does this. Note that
2227 // WebFrameView has very similar code.
2228 WebFrameView *mainFrameView = [[self mainFrame] frameView];
2229 if (mainFrameView != nil) {
2230 [mainFrameView setNextKeyView:aView];
2232 [super setNextKeyView:aView];
2236 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2238 return forward ? [curr _nextFrameWithWrap:wrapFlag]
2239 : [curr _previousFrameWithWrap:wrapFlag];
2242 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2244 // Get the frame holding the selection, or start with the main frame
2245 WebFrame *startFrame = [self _selectedOrMainFrame];
2247 // Search the first frame, then all the other frames, in order
2248 NSView <WebDocumentSearching> *startSearchView = nil;
2249 BOOL startHasSelection = NO;
2250 WebFrame *frame = startFrame;
2252 id <WebDocumentView> view = [[frame frameView] documentView];
2253 if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2254 NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2256 // first time through
2257 if (frame == startFrame) {
2258 // Remember if start even has a selection, to know if we need to search more later
2259 if ([searchView isKindOfClass:[WebHTMLView class]]) {
2260 // optimization for the common case, to avoid making giant string for selection
2261 startHasSelection = [[startFrame _bridge] selectedDOMRange] != nil;
2262 } else if ([searchView conformsToProtocol:@protocol(WebDocumentText)]) {
2263 startHasSelection = [(id <WebDocumentText>)searchView selectedString] != nil;
2265 startSearchView = searchView;
2268 if ([searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:NO]) {
2269 WebFrame *newSelectedFrame = [(WebFrameView *)[searchView _web_superviewOfClass:[WebFrameView class]] webFrame];
2270 if (newSelectedFrame != startFrame)
2271 [startFrame _clearSelection];
2272 [[self window] makeFirstResponder:searchView];
2276 frame = incrementFrame(frame, forward, wrapFlag);
2277 } while (frame != nil && frame != startFrame);
2279 // Search contents of startFrame, on the other side of the selection that we did earlier.
2280 // We cheat a bit and just research with wrap on
2281 if (wrapFlag && startHasSelection && startSearchView) {
2282 if ([startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES]) {
2283 [[self window] makeFirstResponder:startSearchView];
2290 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2292 [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2293 [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2296 - (void)setGroupName:(NSString *)groupName
2298 [[self mainFrame] _setFrameNamespace:groupName];
2301 - (NSString *)groupName
2303 return [[self mainFrame] _frameNamespace];
2306 - (double)estimatedProgress
2308 return _private->progressValue;
2311 - (NSArray *)pasteboardTypesForSelection
2313 NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2314 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2315 return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2317 return [NSArray array];
2320 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2322 WebFrameBridge *bridge = [self _bridgeForSelectedOrMainFrame];
2323 if ([bridge selectionState] != WebSelectionStateRange) {
2324 NSView <WebDocumentView> *documentView = [[[bridge webFrame] frameView] documentView];
2325 if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2326 [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2331 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2333 if ([element objectForKey:WebElementImageURLKey] != nil) {
2334 return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2335 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2336 return [NSPasteboard _web_writableTypesForURL];
2337 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2338 return [self pasteboardTypesForSelection];
2340 return [NSArray array];
2343 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2345 if ([element objectForKey:WebElementImageURLKey] != nil) {
2346 [self _writeImageElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2347 } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2348 [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2349 } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2350 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2354 - (void)moveDragCaretToPoint:(NSPoint)point
2356 WebFrameBridge *bridge = [self _bridgeAtPoint:point];
2357 if (bridge != _private->dragCaretBridge) {
2358 [_private->dragCaretBridge removeDragCaret];
2359 _private->dragCaretBridge = [bridge retain];
2361 [_private->dragCaretBridge moveDragCaretToPoint:[self convertPoint:point toView:[[[_private->dragCaretBridge webFrame] frameView] documentView]]];
2364 - (void)removeDragCaret
2366 [_private->dragCaretBridge removeDragCaret];
2367 [_private->dragCaretBridge release];
2368 _private->dragCaretBridge = nil;
2371 - (void)_inspectElement:(id)sender
2373 NSDictionary *element = [sender representedObject];
2374 WebFrame *frame = [element objectForKey:WebElementFrameKey];
2375 DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
2376 if (!node || !frame)
2379 if ([node nodeType] != DOM_ELEMENT_NODE || [node nodeType] != DOM_DOCUMENT_NODE)
2380 node = [node parentNode];
2382 WebInspector *inspector = [WebInspector sharedWebInspector];
2383 [inspector setWebFrame:frame];
2384 [inspector setFocusedDOMNode:node];
2386 node = [node parentNode];
2387 node = [node parentNode];
2388 if (node) // set the root node to something retivally close to the focused node
2389 [inspector setRootDOMNode:node];
2391 [inspector showWindow:nil];
2395 @implementation WebView (WebIBActions)
2397 - (IBAction)takeStringURLFrom: sender
2399 NSString *URLString = [sender stringValue];
2401 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2406 return [[self backForwardList] backItem] != nil;
2409 - (BOOL)canGoForward
2411 return [[self backForwardList] forwardItem] != nil;
2414 - (IBAction)goBack:(id)sender
2419 - (IBAction)goForward:(id)sender
2424 - (IBAction)stopLoading:(id)sender
2426 [[self mainFrame] stopLoading];
2429 - (IBAction)reload:(id)sender
2431 [[self mainFrame] reload];
2434 #define MinimumTextSizeMultiplier 0.5
2435 #define MaximumTextSizeMultiplier 3.0
2436 #define TextSizeMultiplierRatio 1.2
2438 - (BOOL)canMakeTextSmaller
2440 BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2441 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2444 - (BOOL)canMakeTextLarger
2446 BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2447 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2450 - (IBAction)makeTextSmaller:(id)sender
2452 float newScale = _private->textSizeMultiplier/TextSizeMultiplierRatio;
2453 BOOL canShrinkMore = newScale > MinimumTextSizeMultiplier;
2454 [self _performTextSizingSelector:@selector(_makeTextSmaller:) withObject:sender onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:newScale];
2457 - (IBAction)makeTextLarger:(id)sender
2459 float newScale = _private->textSizeMultiplier*TextSizeMultiplierRatio;
2460 BOOL canGrowMore = newScale < MaximumTextSizeMultiplier;
2461 [self _performTextSizingSelector:@selector(_makeTextLarger:) withObject:sender onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:newScale];
2464 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2466 id responder = [self _responderForResponderOperations];
2467 if (responder != self && [responder respondsToSelector:[item action]]) {
2468 if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)]) {
2469 return [responder validateUserInterfaceItem:item];
2476 #define VALIDATE(name) \
2477 else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2479 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2481 SEL action = [item action];
2483 if (action == @selector(goBack:)) {
2484 return [self canGoBack];
2485 } else if (action == @selector(goForward:)) {
2486 return [self canGoForward];
2487 } else if (action == @selector(makeTextLarger:)) {
2488 return [self canMakeTextLarger];
2489 } else if (action == @selector(makeTextSmaller:)) {
2490 return [self canMakeTextSmaller];
2491 } else if (action == @selector(makeTextStandardSize:)) {
2492 return [self canMakeTextStandardSize];
2493 } else if (action == @selector(reload:)) {
2494 return [[self mainFrame] dataSource] != nil;
2495 } else if (action == @selector(stopLoading:)) {
2496 return [self _isLoading];
2497 } else if (action == @selector(toggleContinuousSpellChecking:)) {
2498 BOOL checkMark = NO;
2500 if ([self isEditable] && [self _continuousCheckingAllowed]) {
2501 checkMark = [self isContinuousSpellCheckingEnabled];
2504 if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2505 NSMenuItem *menuItem = (NSMenuItem *)item;
2506 [menuItem setState:checkMark ? NSOnState : NSOffState];
2510 FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2517 @implementation WebView (WebPendingPublic)
2519 - (void)setMainFrameURL:(NSString *)URLString
2521 [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2524 - (NSString *)mainFrameURL
2527 ds = [[self mainFrame] provisionalDataSource];
2529 ds = [[self mainFrame] dataSource];
2530 return [[[ds request] URL] _web_originalDataAsString];
2535 LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2536 return [self _isLoading];
2539 - (NSString *)mainFrameTitle
2541 NSString *mainFrameTitle = [[[self mainFrame] dataSource] pageTitle];
2542 return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2545 - (NSImage *)mainFrameIcon
2547 return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2550 - (void)setDrawsBackground:(BOOL)drawsBackground
2552 if (_private->drawsBackground == drawsBackground)
2554 _private->drawsBackground = drawsBackground;
2555 [[self mainFrame] _updateDrawsBackground];
2558 - (BOOL)drawsBackground
2560 return _private->drawsBackground;
2563 - (void)toggleSmartInsertDelete:(id)sender
2565 if ([self isEditable]) {
2566 [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2570 - (IBAction)toggleContinuousSpellChecking:(id)sender
2572 if ([self isEditable]) {
2573 [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2577 - (BOOL)maintainsInactiveSelection
2579 return [self isEditable];
2582 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it
2583 // until the day comes when we're no longer supporting Mail on Tiger.
2584 - (WebFrame *)_frameForCurrentSelection
2586 return [self _selectedOrMainFrame];
2589 - (WebFrame *)selectedFrame
2591 // If the first responder is a view in our tree, we get the frame containing the first responder.
2592 // This is faster than searching the frame hierarchy, and will give us a result even in the case
2593 // where the focused frame doesn't actually contain a selection.
2594 WebFrame *focusedFrame = [self _focusedFrame];
2597 WebFrame *frameWithSelection = [[self mainFrame] _findFrameWithSelection];
2599 ASSERT(frameWithSelection == nil || frameWithSelection == focusedFrame);
2600 return focusedFrame;
2603 // If the first responder is outside of our view tree, we search for a frame containing a selection.
2604 // There should be at most only one of these.
2605 return [[self mainFrame] _findFrameWithSelection];
2610 - (BOOL)canMakeTextStandardSize
2612 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0;
2613 return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0];
2616 - (IBAction)makeTextStandardSize:(id)sender
2618 BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0;
2619 [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0];
2622 - (void)setScriptDebugDelegate:delegate
2624 _private->scriptDebugDelegate = delegate;
2625 [_private->scriptDebugDelegateForwarder release];
2626 _private->scriptDebugDelegateForwarder = nil;
2629 - scriptDebugDelegate
2631 return _private->scriptDebugDelegate;
2636 WebFrameBridge *bridge = [[self mainFrame] _bridge];
2639 return [bridge shouldClose];
2642 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
2644 return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
2647 - (unsigned)highlightAllMatchesForString:(NSString *)string caseSensitive:(BOOL)caseFlag
2649 WebFrame *frame = [self mainFrame];
2650 unsigned matchCount = 0;
2652 id <WebDocumentView> view = [[frame frameView] documentView];
2653 // FIXME: introduce a protocol, or otherwise make this work with other types
2654 if ([view isKindOfClass:[WebHTMLView class]])
2655 matchCount += [(WebHTMLView *)view highlightAllMatchesForString:string caseSensitive:caseFlag];
2657 frame = incrementFrame(frame, YES, NO);
2663 - (void)clearHighlightedMatches
2665 WebFrame *frame = [self mainFrame];
2667 id <WebDocumentView> view = [[frame frameView] documentView];
2668 // FIXME: introduce a protocol, or otherwise make this work with other types
2669 if ([view isKindOfClass:[WebHTMLView class]])
2670 [(WebHTMLView *)view clearHighlightedMatches];
2672 frame = incrementFrame(frame, YES, NO);
2678 @implementation WebView (WebViewPrintingPrivate)
2680 - (float)_headerHeight
2682 if ([[self UIDelegate] respondsToSelector:@selector(webViewHeaderHeight:)]) {
2683 return [[self UIDelegate] webViewHeaderHeight:self];
2686 #ifdef DEBUG_HEADER_AND_FOOTER
2693 - (float)_footerHeight
2695 if ([[self UIDelegate] respondsToSelector:@selector(webViewFooterHeight:)]) {
2696 return [[self UIDelegate] webViewFooterHeight:self];
2699 #ifdef DEBUG_HEADER_AND_FOOTER
2706 - (void)_drawHeaderInRect:(NSRect)rect
2708 #ifdef DEBUG_HEADER_AND_FOOTER
2709 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2710 [currentContext saveGraphicsState];
2711 [[NSColor yellowColor] set];
2713 [currentContext restoreGraphicsState];
2716 if ([[self UIDelegate] respondsToSelector:@selector(webView:drawHeaderInRect:)]) {
2717 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2718 [currentContext saveGraphicsState];
2720 [[self UIDelegate] webView:self drawHeaderInRect:rect];
2721 [currentContext restoreGraphicsState];
2725 - (void)_drawFooterInRect:(NSRect)rect
2727 #ifdef DEBUG_HEADER_AND_FOOTER
2728 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2729 [currentContext saveGraphicsState];
2730 [[NSColor cyanColor] set];
2732 [currentContext restoreGraphicsState];
2735 if ([[self UIDelegate] respondsToSelector:@selector(webView:drawFooterInRect:)]) {
2736 NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2737 [currentContext saveGraphicsState];
2739 [[self UIDelegate] webView:self drawFooterInRect:rect];
2740 [currentContext restoreGraphicsState];
2744 - (void)_adjustPrintingMarginsForHeaderAndFooter
2746 NSPrintOperation *op = [NSPrintOperation currentOperation];
2747 NSPrintInfo *info = [op printInfo];
2748 float scale = [op _web_pageSetupScaleFactor];
2749 [info setTopMargin:[info topMargin] + [self _headerHeight]*scale];
2750 [info setBottomMargin:[info bottomMargin] + [self _footerHeight]*scale];
2753 - (void)_drawHeaderAndFooter
2755 // The header and footer rect height scales with the page, but the width is always
2756 // all the way across the printed page (inset by printing margins).
2757 NSPrintOperation *op = [NSPrintOperation currentOperation];
2758 float scale = [op _web_pageSetupScaleFactor];
2759 NSPrintInfo *printInfo = [op printInfo];
2760 NSSize paperSize = [printInfo paperSize];
2761 float headerFooterLeft = [printInfo leftMargin]/scale;
2762 float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
2763 NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] ,
2764 headerFooterWidth, [self _footerHeight]);
2765 NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale,
2766 headerFooterWidth, [self _headerHeight]);
2768 [self _drawHeaderInRect:headerRect];
2769 [self _drawFooterInRect:footerRect];
2773 @implementation WebView (WebDebugBinding)
2775 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
2777 LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
2778 [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
2781 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
2783 LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
2784 [super removeObserver:anObserver forKeyPath:keyPath];
2789 //==========================================================================================
2792 @implementation WebView (WebViewCSS)
2794 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
2796 // FIXME: is this the best level for this conversion?
2797 if (pseudoElement == nil) {
2798 pseudoElement = @"";
2800 return [[element ownerDocument] getComputedStyle:element :pseudoElement];
2805 @implementation WebView (WebViewEditing)
2807 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
2809 WebFrameBridge *bridge = [self _bridgeAtPoint:point];
2810 return [bridge editableDOMRangeForPoint:[self convertPoint:point toView:[[[bridge webFrame] frameView] documentView]]];
2813 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
2815 return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
2818 - (BOOL)_shouldBeginEditingInDOMRange:(DOMRange *)range
2820 return [[self _editingDelegateForwarder] webView:self shouldBeginEditingInDOMRange:range];
2823 - (BOOL)_shouldEndEditingInDOMRange:(DOMRange *)range
2825 return [[self _editingDelegateForwarder] webView:self shouldEndEditingInDOMRange:range];
2830 id documentView = [[[self mainFrame] frameView] documentView];
2831 return [documentView respondsToSelector:@selector(_canPaste)] && [documentView _canPaste];
2834 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
2837 [[self _bridgeForSelectedOrMainFrame] deselectText];
2839 // Derive the bridge to use from the range passed in.
2840 // Using _bridgeForSelectedOrMainFrame could give us a different document than
2841 // the one the range uses.
2842 [[[range startContainer] _bridge] setSelectedDOMRange:range affinity:selectionAffinity closeTyping:YES];
2846 - (DOMRange *)selectedDOMRange
2848 return [[self _bridgeForSelectedOrMainFrame] selectedDOMRange];
2851 - (NSSelectionAffinity)selectionAffinity
2853 return [[self _bridgeForSelectedOrMainFrame] selectionAffinity];
2856 - (void)setEditable:(BOOL)flag
2858 if (_private->editable != flag) {
2859 _private->editable = flag;
2860 WebFrameBridge *bridge = [[self mainFrame] _bridge];
2862 [bridge applyEditingStyleToBodyElement];
2863 // If the WebView is made editable and the selection is empty, set it to something.
2864 if ([self selectedDOMRange] == nil)
2865 [bridge setSelectionFromNone];
2868 [bridge removeEditingStyleFromBodyElement];
2875 return _private->editable;
2878 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
2880 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
2881 // change the API to allow this.
2882 [[self _bridgeForSelectedOrMainFrame] setTypingStyle:style withUndoAction:WebUndoActionUnspecified];
2885 - (DOMCSSStyleDeclaration *)typingStyle
2887 return [[self _bridgeForSelectedOrMainFrame] typingStyle];
2890 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
2892 _private->smartInsertDeleteEnabled = flag;
2895 - (BOOL)smartInsertDeleteEnabled
2897 return _private->smartInsertDeleteEnabled;
2900 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
2902 _private->continuousSpellCheckingEnabled = flag;
2903 if ([self isContinuousSpellCheckingEnabled]) {
2904 [[self class] _preflightSpellChecker];
2906 [[self mainFrame] _unmarkAllMisspellings];
2910 - (BOOL)isContinuousSpellCheckingEnabled
2912 return _private->continuousSpellCheckingEnabled && [self _continuousCheckingAllowed];
2915 - (WebNSInt)spellCheckerDocumentTag
2917 if (!_private->hasSpellCheckerDocumentTag) {
2918 _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
2919 _private->hasSpellCheckerDocumentTag = YES;
2921 return _private->spellCheckerDocumentTag;
2924 - (NSUndoManager *)undoManager
2926 NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
2930 return [super undoManager];
2933 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
2935 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
2936 if ([_private->editingDelegate respondsToSelector:selector])
2937 [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
2940 - (void)setEditingDelegate:(id)delegate
2942 if (_private->editingDelegate == delegate)
2945 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
2947 // remove notifications from current delegate
2948 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
2949 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
2950 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
2951 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
2952 [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
2954 _private->editingDelegate = delegate;
2955 [_private->editingDelegateForwarder release];
2956 _private->editingDelegateForwarder = nil;
2958 // add notifications for new delegate
2959 [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
2960 [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
2961 [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
2962 [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
2963 [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
2966 - (id)editingDelegate
2968 return _private->editingDelegate;
2971 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
2973 // FIXME: Should this really be attached to the document with the current selection?
2974 DOMCSSStyleDeclaration *decl = [[[self _bridgeForSelectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
2975 [decl setCssText:text];
2981 @implementation WebView (WebViewUndoableEditing)
2983 - (void)replaceSelectionWithNode:(DOMNode *)node
2985 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO];
2988 - (void)replaceSelectionWithText:(NSString *)text
2990 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
2993 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
2995 [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
2998 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3000 [[[[self _bridgeForSelectedOrMainFrame] webFrame] dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3003 - (void)deleteSelection
3005 WebFrameBridge *bridge = [self _bridgeForSelectedOrMainFrame];
3006 [bridge deleteSelectionWithSmartDelete:[(WebHTMLView *)[[[bridge webFrame] frameView] documentView] _canSmartCopyOrDelete]];
3009 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3011 // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3012 // change the API to allow this.
3013 [[self _bridgeForSelectedOrMainFrame] applyStyle:style withUndoAction:WebUndoActionUnspecified];
3018 @implementation WebView (WebViewEditingActions)
3020 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3022 static BOOL reentered = NO;
3024 [[self nextResponder] tryToPerform:selector with:parameter];
3028 // There are two possibilities here.
3030 // One is that WebView has been called in its role as part of the responder chain.
3031 // In that case, it's fine to call the first responder and end up calling down the
3032 // responder chain again. Later we will return here with reentered = YES and continue
3033 // past the WebView.
3035 // The other is that we are being called directly, in which case we want to pass the
3036 // selector down to the view inside us that can handle it, and continue down the
3037 // responder chain as usual.
3039 // Pass this selector down to the first responder.
3040 NSResponder *responder = [self _responderForResponderOperations];
3042 [responder tryToPerform:selector with:parameter];
3046 #define FORWARD(name) \
3047 - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3049 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3051 - (void)insertText:(NSString *)text
3053 [self _performResponderOperation:_cmd with:text];
3058 @implementation WebView (WebViewEditingInMail)
3060 - (void)_insertNewlineInQuotedContent;
3062 [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3065 - (BOOL)_selectWordBeforeMenuEvent
3067 return _private->selectWordBeforeMenuEvent;
3070 - (void)_setSelectWordBeforeMenuEvent:(BOOL)flag
3072 _private->selectWordBeforeMenuEvent = flag;
3077 @implementation WebView (WebFileInternal)
3079 - (WebFrame *)_focusedFrame
3081 NSResponder *resp = [[self window] firstResponder];
3082 if (resp && [resp isKindOfClass:[NSView class]] && [(NSView *)resp isDescendantOf:self]) {
3083 WebFrameView *frameView = [resp isKindOfClass:[WebFrameView class]]
3084 ? (WebFrameView *)resp
3085 : (WebFrameView *)[(NSView *)resp _web_superviewOfClass:[WebFrameView class]];
3086 ASSERT(frameView != nil);
3087 return [frameView webFrame];
3093 - (WebFrame *)_selectedOrMainFrame
3095 WebFrame *result = [self selectedFrame];
3097 result = [self mainFrame];
3101 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame
3103 return [[self _selectedOrMainFrame] _bridge];
3108 WebFrame *mainFrame = [self mainFrame];
3109 return [[mainFrame dataSource] isLoading]
3110 || [[mainFrame provisionalDataSource] isLoading];
3113 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point
3115 NSView *view = [self hitTest:[[self superview] convertPoint:point fromView:nil]];
3116 return (WebFrameView *)[view _web_superviewOfClass:[WebFrameView class] stoppingAtClass:[self class]];
3119 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point
3121 return [[[self _frameViewAtWindowPoint:[self convertPoint:point toView:nil]] webFrame] _bridge];
3124 + (void)_preflightSpellCheckerNow:(id)sender
3126 [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
3129 + (void)_preflightSpellChecker
3131 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3132 if ([NSSpellChecker sharedSpellCheckerExists]) {
3133 [self _preflightSpellCheckerNow:self];
3135 [self performSelector:@selector(_preflightSpellCheckerNow:) withObject:self afterDelay:2.0];
3139 - (BOOL)_continuousCheckingAllowed
3141 static BOOL allowContinuousSpellChecking = YES;
3142 static BOOL readAllowContinuousSpellCheckingDefault = NO;
3143 if (!readAllowContinuousSpellCheckingDefault) {
3144 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NSAllowContinuousSpellChecking"]) {
3145 allowContinuousSpellChecking = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSAllowContinuousSpellChecking"];
3147 readAllowContinuousSpellCheckingDefault = YES;
3149 return allowContinuousSpellChecking;
3152 - (NSResponder *)_responderForResponderOperations
3154 NSResponder *responder = [[self window] firstResponder];
3155 if (![self _web_firstResponderIsSelfOrDescendantView]) {
3156 responder = [[[self mainFrame] frameView] documentView];
3158 responder = [[self mainFrame] frameView];
3164 - (void)_searchWithGoogleFromMenu:(id)sender
3166 id documentView = [[[self mainFrame] frameView] documentView];
3167 if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3171 NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3172 if ([selectedString length] == 0) {
3176 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName];
3177 [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
3178 NSMutableString *s = [selectedString mutableCopy];
3179 const unichar nonBreakingSpaceCharacter = 0xA0;
3180 NSString *nonBreakingSpaceString = [NSString stringWithCharacters:&nonBreakingSpaceCharacter length:1];
3181 [s replaceOccurrencesOfString:nonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
3182 [pasteboard setString:s forType:NSStringPboardType];
3185 // FIXME: seems fragile to use the service by name, but this is what AppKit does
3186 NSPerformService(@"Search With Google", pasteboard);
3189 - (void)_searchWithSpotlightFromMenu:(id)sender
3191 id documentView = [[[self mainFrame] frameView] documentView];
3192 if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3196 NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3197 if ([selectedString length] == 0) {
3201 (void)HISearchWindowShow((CFStringRef)selectedString, kNilOptions);
3204 // Slightly funky method that lets us have one copy of the logic for finding docViews that can do
3205 // text sizing. It returns whether it found any "suitable" doc views. It sends sel to any suitable
3206 // doc views, or if sel==0 we do nothing to them. For doc views that track our size factor, they are
3207 // suitable if doTrackingViews==YES (which in practice means that our size factor isn't at its max or
3208 // min). For doc views that don't track it, we send them testSel to determine suitablility. If we
3209 // do find any suitable tracking doc views and newScaleFactor!=0, we will set the common scale factor
3210 // to that new factor before we send sel to any of them.
3211 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor
3213 if ([[self mainFrame] dataSource] == nil) {
3217 BOOL foundSome = NO;
3218 NSArray *docViews = [[self mainFrame] _documentViews];
3220 for (i = [docViews count]-1; i >= 0; i--) {
3221 id docView = [docViews objectAtIndex:i];
3222 if ([docView conformsToProtocol:@protocol(_WebDocumentTextSizing)]) {
3223 id <_WebDocumentTextSizing> sizingDocView = (id <_WebDocumentTextSizing>)docView;
3225 if ([sizingDocView _tracksCommonSizeFactor]) {
3226 isSuitable = doTrackingViews;
3227 if (isSuitable && newScaleFactor != 0) {
3228 [self setTextSizeMultiplier:newScaleFactor];
3231 // Incantation to perform a selector returning a BOOL.
3232 isSuitable = ((BOOL(*)(id, SEL))objc_msgSend)(sizingDocView, testSel);
3238 [sizingDocView performSelector:sel withObject:arg];
3240 // if we're just called for the benefit of the return value, we can return at first match
3252 @implementation WebView (WebViewBridge)
3254 - (WebPageBridge *)_pageBridge
3256 return _private->_pageBridge;