WebCore:
[WebKit-https.git] / WebKit / WebView / WebView.m
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
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. 
16  *
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.
27  */
28
29 #import "WebViewInternal.h"
30
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>
95
96 #if __ppc__
97 #define PROCESSOR "PPC"
98 #elif __i386__
99 #define PROCESSOR "Intel"
100 #else
101 #error Unknown architecture
102 #endif
103
104 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
105 macro(alignCenter) \
106 macro(alignJustified) \
107 macro(alignLeft) \
108 macro(alignRight) \
109 macro(capitalizeWord) \
110 macro(centerSelectionInVisibleArea) \
111 macro(changeAttributes) \
112 macro(changeColor) \
113 macro(changeDocumentBackgroundColor) \
114 macro(changeFont) \
115 macro(checkSpelling) \
116 macro(complete) \
117 macro(copy) \
118 macro(copyFont) \
119 macro(cut) \
120 macro(delete) \
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) \
131 macro(indent) \
132 macro(insertBacktab) \
133 macro(insertNewline) \
134 macro(insertNewlineIgnoringFieldEditor) \
135 macro(insertParagraphSeparator) \
136 macro(insertTab) \
137 macro(insertTabIgnoringFieldEditor) \
138 macro(lowercaseWord) \
139 macro(moveBackward) \
140 macro(moveBackwardAndModifySelection) \
141 macro(moveDown) \
142 macro(moveDownAndModifySelection) \
143 macro(moveForward) \
144 macro(moveForwardAndModifySelection) \
145 macro(moveLeft) \
146 macro(moveLeftAndModifySelection) \
147 macro(moveRight) \
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) \
161 macro(moveUp) \
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) \
171 macro(pageDown) \
172 macro(pageUp) \
173 macro(paste) \
174 macro(pasteAsPlainText) \
175 macro(pasteAsRichText) \
176 macro(pasteFont) \
177 macro(performFindPanelAction) \
178 macro(scrollLineDown) \
179 macro(scrollLineUp) \
180 macro(scrollPageDown) \
181 macro(scrollPageUp) \
182 macro(scrollToBeginningOfDocument) \
183 macro(scrollToEndOfDocument) \
184 macro(selectAll) \
185 macro(selectLine) \
186 macro(selectParagraph) \
187 macro(selectWord) \
188 macro(showGuessPanel) \
189 macro(startSpeaking) \
190 macro(stopSpeaking) \
191 macro(subscript) \
192 macro(superscript) \
193 macro(underline) \
194 macro(unscript) \
195 macro(uppercaseWord) \
196 macro(yank) \
197 macro(yankAndSelect) \
198
199 @interface NSSpellChecker (AppKitSecretsIKnow)
200 - (void)_preflightChosenSpellServer;
201 @end
202
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;
207 @end
208
209 @interface WebViewPrivate : NSObject
210 {
211 @public
212     WebPageBridge *_pageBridge;
213     
214     id UIDelegate;
215     id UIDelegateForwarder;
216     id resourceProgressDelegate;
217     id resourceProgressDelegateForwarder;
218     id downloadDelegate;
219     id policyDelegate;
220     id policyDelegateForwarder;
221     id frameLoadDelegate;
222     id frameLoadDelegateForwarder;
223     id <WebFormDelegate> formDelegate;
224     id editingDelegate;
225     id editingDelegateForwarder;
226     id scriptDebugDelegate;
227     id scriptDebugDelegateForwarder;
228     
229     WebBackForwardList *backForwardList;
230     BOOL useBackForwardList;
231     
232     float textSizeMultiplier;
233
234     NSString *applicationNameForUserAgent;
235     NSString *userAgent;
236     BOOL userAgentOverridden;
237     
238     BOOL defersCallbacks;
239
240     WebPreferences *preferences;
241     WebCoreSettings *settings;
242         
243     BOOL lastElementWasNonNil;
244
245     NSWindow *hostWindow;
246
247     int programmaticFocusCount;
248     
249     WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
250
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;
260     
261     int numProgressTrackedFrames;
262     NSMutableDictionary *progressItems;
263     
264     void *observationInfo;
265     
266     BOOL drawsBackground;
267     BOOL editable;
268     BOOL initiatedDrag;
269         
270     NSString *mediaStyle;
271     
272     NSView <WebDocumentDragging> *draggingDocumentView;
273     unsigned int dragDestinationActionMask;
274     WebFrameBridge *dragCaretBridge;
275     
276     BOOL hasSpellCheckerDocumentTag;
277     WebNSInt spellCheckerDocumentTag;
278
279     BOOL continuousSpellCheckingEnabled;
280     BOOL smartInsertDeleteEnabled;
281     
282     BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
283     BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
284     BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
285     BOOL dashboardBehaviorAllowWheelScrolling;
286     
287     BOOL shouldUseFontSmoothing;
288     BOOL selectWordBeforeMenuEvent;
289 }
290 @end
291
292 @interface WebView (WebFileInternal)
293 - (WebFrame *)_selectedOrMainFrame;
294 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame;
295 - (BOOL)_isLoading;
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;
303 @end
304
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";
316
317 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
318 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
319 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
320
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";
326
327 enum { WebViewVersion = 2 };
328
329 #define timedLayoutSize 4096
330
331 static NSMutableSet *schemesWithRepresentationsSet;
332
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";
340
341 @interface WebProgressItem : NSObject
342 {
343 @public
344     long long bytesReceived;
345     long long estimatedLength;
346 }
347 @end
348
349 @implementation WebProgressItem
350 @end
351
352 static BOOL shouldUseFontSmoothing = YES;
353
354 @implementation WebViewPrivate
355
356 - init 
357 {
358     self = [super init];
359     if (!self)
360         return nil;
361     
362     backForwardList = [[WebBackForwardList alloc] init];
363     textSizeMultiplier = 1;
364     progressNotificationInterval = 0.02;
365     progressNotificationTimeInterval = 0.1;
366     settings = [[WebCoreSettings alloc] init];
367     dashboardBehaviorAllowWheelScrolling = YES;
368
369     return self;
370 }
371
372 - (void)dealloc
373 {
374     ASSERT(!_pageBridge);
375     ASSERT(draggingDocumentView == nil);
376     ASSERT(dragCaretBridge == nil);
377     
378     [backForwardList release];
379     [applicationNameForUserAgent release];
380     [userAgent release];
381     
382     [preferences release];
383     [settings release];
384     [hostWindow release];
385     
386     [policyDelegateForwarder release];
387     [resourceProgressDelegateForwarder release];
388     [UIDelegateForwarder release];
389     [frameLoadDelegateForwarder release];
390     [editingDelegateForwarder release];
391     [scriptDebugDelegateForwarder release];
392     
393     [progressItems release];
394         
395     [mediaStyle release];
396     
397     [super dealloc];
398 }
399
400 @end
401
402 @implementation WebView (AllWebViews)
403
404 static CFSetCallBacks NonRetainingSetCallbacks = {
405     0,
406     NULL,
407     NULL,
408     CFCopyDescription,
409     CFEqual,
410     CFHash
411 };
412
413 static CFMutableSetRef allWebViewsSet;
414
415 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
416 {
417     if (!allWebViewsSet)
418         return;
419
420     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
421 }
422
423 - (void)_removeFromAllWebViewsSet
424 {
425     if (allWebViewsSet)
426         CFSetRemoveValue(allWebViewsSet, self);
427 }
428
429 - (void)_addToAllWebViewsSet
430 {
431     if (!allWebViewsSet)
432         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
433
434     CFSetSetValue(allWebViewsSet, self);
435 }
436
437 @end
438
439 @implementation WebView (WebPrivate)
440
441 #ifdef DEBUG_WIDGET_DRAWING
442 static bool debugWidget = true;
443 - (void)drawRect:(NSRect)rect
444 {
445     [[NSColor blueColor] set];
446     NSRectFill (rect);
447     
448     NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
449
450     if (debugWidget) {
451         while (debugWidget) {
452             sleep (1);
453         }
454     }
455
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
459         );
460
461     [super drawRect:rect];
462 }
463 #endif
464
465 + (NSArray *)_supportedMIMETypes
466 {
467     // Load the plug-in DB allowing plug-ins to install types.
468     [WebPluginDatabase installedPlugins];
469     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
470 }
471
472 + (NSArray *)_supportedFileExtensions
473 {
474     NSMutableSet *extensions = [[NSMutableSet alloc] init];
475     NSArray *MIMETypes = [self _supportedMIMETypes];
476     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
477     NSString *MIMEType;
478     while ((MIMEType = [enumerator nextObject]) != nil) {
479         NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
480         if (extensionsForType) {
481             [extensions addObjectsFromArray:extensionsForType];
482         }
483     }
484     NSArray *uniqueExtensions = [extensions allObjects];
485     [extensions release];
486     return uniqueExtensions;
487 }
488
489 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
490 {
491     MIMEType = [MIMEType lowercaseString];
492     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
493     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
494     
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];
499             
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];
503     }
504     
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]) {
510             return NO;
511         }
512         if (vClass)
513             *vClass = viewClass;
514         if (rClass)
515             *rClass = repClass;
516         return YES;
517     }
518     
519     return NO;
520 }
521
522 + (void)_setAlwaysUseATSU:(BOOL)f
523 {
524     [WebTextRenderer setAlwaysUseATSU:f];
525 }
526
527 + (BOOL)canShowFile:(NSString *)path
528 {
529     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
530 }
531
532 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
533 {
534     return WKGetPreferredExtensionForMIMEType(type);
535 }
536
537 - (void)_close
538 {
539     [self _removeFromAllWebViewsSet];
540     [self setGroupName:nil];
541
542     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
543     [self removeDragCaret];
544     
545     [[self mainFrame] _detachFromParent];
546     [_private->_pageBridge release];
547     _private->_pageBridge = nil;
548     
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];
552     
553     if (_private->hasSpellCheckerDocumentTag) {
554         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
555         _private->hasSpellCheckerDocumentTag = NO;
556     }
557 }
558
559 - (void)_finishedLoadingResourceFromDataSource:(WebDataSource *)dataSource
560 {
561     WebFrame *frame = [dataSource webFrame];
562     
563     ASSERT(dataSource != nil);
564     
565     // This resource has completed, so check if the load is complete for all frames.
566     if (frame != nil)
567         [frame _checkLoadComplete];
568 }
569
570 - (void)_mainReceivedBytesSoFar:(unsigned)bytesSoFar fromDataSource:(WebDataSource *)dataSource complete: (BOOL)isComplete
571 {
572     WebFrame *frame = [dataSource webFrame];
573     
574     ASSERT(dataSource != nil);
575
576     // The frame may be nil if a previously cancelled load is still making progress callbacks.
577     if (frame == nil)
578         return;
579         
580     // This resource has completed, so check if the load is complete for this frame and its ancestors
581     if (isComplete){
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];
586     }
587 }
588
589 - (void)_receivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource
590 {
591     WebFrame *frame = [dataSource webFrame];
592
593     [frame _checkLoadComplete];
594 }
595
596 - (void)_mainReceivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource complete:(BOOL)isComplete
597 {
598     ASSERT(dataSource);
599     ASSERT([dataSource webFrame]);
600     
601     [dataSource _setMainDocumentError: error];
602
603     if (isComplete) {
604         [dataSource _setPrimaryLoadComplete:YES];
605         [[dataSource webFrame] _checkLoadComplete];
606     }
607 }
608
609 + (NSString *)_MIMETypeForFile:(NSString *)path
610 {
611     NSString *extension = [path pathExtension];
612     NSString *MIMEType = nil;
613
614     // Get the MIME type from the extension.
615     if ([extension length] != 0) {
616         MIMEType = WKGetMIMETypeForExtension(extension);
617     }
618
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];
623         [handle closeFile];
624         if ([data length] != 0) {
625             MIMEType = [data _webkit_guessedMIMEType];
626         }
627         if ([MIMEType length] == 0) {
628             MIMEType = @"application/octet-stream";
629         }
630     }
631
632     return MIMEType;
633 }
634
635 - (void)_downloadURL:(NSURL *)URL
636 {
637     [self _downloadURL:URL toDirectory:nil];
638 }
639
640 - (void)_downloadURL:(NSURL *)URL toDirectory:(NSString *)directory
641 {
642     ASSERT(URL);
643     
644     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
645     [WebDownload _downloadWithRequest:request
646                              delegate:_private->downloadDelegate
647                             directory:[directory isAbsolutePath] ? directory : nil];
648     [request release];
649 }
650
651 - (BOOL)defersCallbacks
652 {
653     return _private->defersCallbacks;
654 }
655
656 - (void)setDefersCallbacks:(BOOL)defers
657 {
658     if (defers == _private->defersCallbacks) {
659         return;
660     }
661
662     _private->defersCallbacks = defers;
663     [[self mainFrame] _defersCallbacksChanged];
664 }
665
666 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
667 {
668     id wd = [self UIDelegate];
669     WebView *newWindowWebView = nil;
670     if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
671         newWindowWebView = [wd webView:self createWebViewWithRequest:request];
672     else {
673         newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
674     }
675
676     [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
677
678     return newWindowWebView;
679 }
680
681 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
682 {
683     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
684           webView:self contextMenuItemsForElement:element defaultMenuItems:items];
685     NSArray *menuItems = defaultMenuItems;
686     NSMenu *menu = nil;
687     unsigned i;
688
689     if (_private->UIDelegate) {
690         id cd = _private->UIDelegate;
691         
692         if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)])
693             menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
694     } 
695
696     if (menuItems && [menuItems count] > 0) {
697         menu = [[[NSMenu alloc] init] autorelease];
698
699         for (i=0; i<[menuItems count]; i++) {
700             [menu addItem:[menuItems objectAtIndex:i]];
701         }
702     }
703
704 #ifdef NDEBUG
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"];
709 #else
710     BOOL enableInspectElement = YES; // always enable in debug builds
711 #endif
712
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]]) {
717         if (!menu)
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];
726     }
727
728     return menu;
729 }
730
731 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(WebNSUInt)modifierFlags
732 {
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
735     // for that case.
736     
737     if (dictionary && _private->lastElementWasNonNil) {
738         [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
739     }
740     _private->lastElementWasNonNil = dictionary != nil;
741 }
742
743 - (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
744 {
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]);
747
748     // abort any current load if we're going back/forward
749     [[self mainFrame] stopLoading];
750     [[self mainFrame] _goToItem:item withLoadType:type];
751 }
752
753 // Not used now, but could be if we ever store frames in bookmarks or history
754 - (void)_loadItem:(WebHistoryItem *)item
755 {
756     WebHistoryItem *newItem = [item copy];      // Makes a deep copy, happily
757     [[self backForwardList] addItem:newItem];
758     [self _goToItem:newItem withLoadType:WebFrameLoadTypeIndexedBackForward];
759 }
760
761 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
762 {
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.
766
767     WebBackForwardList *bfList = [self backForwardList];
768     ASSERT(![bfList currentItem]);      // destination list should be empty
769
770     WebBackForwardList *otherBFList = [otherView backForwardList];
771     if (![otherBFList currentItem]) {
772         return;         // empty back forward list, bail
773     }
774
775     WebHistoryItem *newItemToGoTo = nil;
776     int lastItemIndex = [otherBFList forwardListCount];
777     int i;
778     for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
779         if (i == 0) {
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];
784         }
785         WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
786         [bfList addItem:newItem];
787         if (i == 0) {
788             newItemToGoTo = newItem;
789         }
790     }
791     
792     [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
793 }
794
795 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
796 {
797     _private->formDelegate = delegate;
798 }
799
800 - (id<WebFormDelegate>)_formDelegate
801 {
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];
805     }
806     return _private->formDelegate;
807 }
808
809 - (WebCoreSettings *)_settings
810 {
811     return _private->settings;
812 }
813
814 - (void)_updateWebCoreSettingsFromPreferences:(WebPreferences *)preferences
815 {
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]];
832
833     if ([preferences userStyleSheetEnabled]) {
834         [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
835     } else {
836         [_private->settings setUserStyleSheetLocation:@""];
837     }
838     [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
839     [_private->settings setTextAreasAreResizable:[preferences textAreasAreResizable]];
840 }
841
842 - (void)_preferencesChangedNotification: (NSNotification *)notification
843 {
844     WebPreferences *preferences = (WebPreferences *)[notification object];
845     
846     ASSERT(preferences == [self preferences]);
847     if (!_private->userAgentOverridden) {
848         [_private->userAgent release];
849         _private->userAgent = nil;
850     }
851     [self _updateWebCoreSettingsFromPreferences: preferences];
852 }
853
854 - _frameLoadDelegateForwarder
855 {
856     if (!_private->frameLoadDelegateForwarder)
857         _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate]  defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
858     return _private->frameLoadDelegateForwarder;
859 }
860
861 - _resourceLoadDelegateForwarder
862 {
863     if (!_private->resourceProgressDelegateForwarder)
864         _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
865     return _private->resourceProgressDelegateForwarder;
866 }
867
868 - (void)_cacheResourceLoadDelegateImplementations
869 {
870     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
871     id delegate = [self resourceLoadDelegate];
872
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:)];
880 }
881
882 - (WebResourceDelegateImplementationCache)_resourceLoadDelegateImplementations
883 {
884     return _private->resourceLoadDelegateImplementations;
885 }
886
887 - _policyDelegateForwarder
888 {
889     if (!_private->policyDelegateForwarder)
890         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
891     return _private->policyDelegateForwarder;
892 }
893
894 - _UIDelegateForwarder
895 {
896     if (!_private->UIDelegateForwarder)
897         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
898     return _private->UIDelegateForwarder;
899 }
900
901 - _editingDelegateForwarder
902 {
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.
905     if (!_private)
906         return nil;
907     if (!_private->editingDelegateForwarder)
908         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self editingDelegate] defaultTarget: [WebDefaultEditingDelegate sharedEditingDelegate] templateClass: [WebDefaultEditingDelegate class]];
909     return _private->editingDelegateForwarder;
910 }
911
912 - _scriptDebugDelegateForwarder
913 {
914     if (!_private->scriptDebugDelegateForwarder)
915         _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self scriptDebugDelegate] defaultTarget: [WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] templateClass: [WebDefaultScriptDebugDelegate class]];
916     return _private->scriptDebugDelegateForwarder;
917 }
918
919 - (void)_closeWindow
920 {
921     [[self _UIDelegateForwarder] webViewClose:self];
922 }
923
924 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
925 {
926     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
927     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
928 }
929
930 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
931 {
932     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
933     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
934
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];
939     }
940     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
941 }
942
943 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
944 {
945     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
946 }
947
948 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
949 {
950     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
951 }
952
953 + (BOOL)_canHandleRequest:(NSURLRequest *)request
954 {
955     if ([NSURLConnection canHandleRequest:request]) {
956         return YES;
957     }
958     
959     // We're always willing to load alternate content for unreachable URLs
960     if ([request _webDataRequestUnreachableURL]) {
961         return YES;
962     }
963
964     return [self _representationExistsForURLScheme:[[request URL] scheme]];
965 }
966
967 + (NSString *)_decodeData:(NSData *)data
968 {
969     return [WebCoreEncodings decodeData:data];
970 }
971
972 - (void)_pushPerformingProgrammaticFocus
973 {
974     _private->programmaticFocusCount++;
975 }
976
977 - (void)_popPerformingProgrammaticFocus
978 {
979     _private->programmaticFocusCount--;
980 }
981
982 - (BOOL)_isPerformingProgrammaticFocus
983 {
984     return _private->programmaticFocusCount != 0;
985 }
986
987 #define UnknownTotalBytes -1
988 #define WebProgressItemDefaultEstimatedLength 1024*16
989
990 - (void)_didChangeValueForKey: (NSString *)key
991 {
992     LOG (Bindings, "calling didChangeValueForKey: %@", key);
993     [self didChangeValueForKey: key];
994 }
995
996 - (void)_willChangeValueForKey: (NSString *)key
997 {
998     LOG (Bindings, "calling willChangeValueForKey: %@", key);
999     [self willChangeValueForKey: key];
1000 }
1001
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
1004 // starts.
1005 #define INITIAL_PROGRESS_VALUE 0.1
1006
1007 - (void)_resetProgress
1008 {
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;
1020 }
1021 - (void)_progressStarted:(WebFrame *)frame
1022 {
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];
1030     }
1031     _private->numProgressTrackedFrames++;
1032     [self _didChangeValueForKey: @"estimatedProgress"];
1033 }
1034
1035 - (void)_finalProgressComplete
1036 {
1037     LOG (Progress, "");
1038
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];
1044     }
1045     
1046     [self _resetProgress];
1047     
1048     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
1049 }
1050
1051 - (void)_progressCompleted:(WebFrame *)frame
1052 {    
1053     LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->orginatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->orginatingProgressFrame);
1054
1055     if (_private->numProgressTrackedFrames <= 0)
1056         return;
1057
1058     [self _willChangeValueForKey: @"estimatedProgress"];
1059
1060     _private->numProgressTrackedFrames--;
1061     if (_private->numProgressTrackedFrames == 0 ||
1062         (frame == _private->orginatingProgressFrame && _private->numProgressTrackedFrames != 0)){
1063         [self _finalProgressComplete];
1064     }
1065     [self _didChangeValueForKey: @"estimatedProgress"];
1066 }
1067
1068 - (void)_incrementProgressForConnectionDelegate:(id)connectionDelegate response:(NSURLResponse *)response;
1069 {
1070     if (!connectionDelegate)
1071         return;
1072
1073     LOG (Progress, "_private->numProgressTrackedFrames %d, _private->orginatingProgressFrame %p", _private->numProgressTrackedFrames, _private->orginatingProgressFrame);
1074     
1075     if (_private->numProgressTrackedFrames <= 0)
1076         return;
1077         
1078     WebProgressItem *item = [[WebProgressItem alloc] init];
1079
1080     if (!item)
1081         return;
1082
1083     long long length = [response expectedContentLength];
1084     if (length < 0){
1085         length = WebProgressItemDefaultEstimatedLength;
1086     }
1087     item->estimatedLength = length;
1088     _private->totalPageAndResourceBytesToLoad += length;
1089     
1090     if (!_private->progressItems)
1091         _private->progressItems = [[NSMutableDictionary alloc] init];
1092         
1093     [_private->progressItems _webkit_setObject:item forUncopiedKey:connectionDelegate];
1094     [item release];
1095 }
1096
1097 - (void)_incrementProgressForConnectionDelegate:(id)connectionDelegate data:(NSData *)data
1098 {
1099     if (!connectionDelegate)
1100         return;
1101
1102     WebProgressItem *item = [_private->progressItems objectForKey:connectionDelegate];
1103
1104     if (!item)
1105         return;
1106
1107     [self _willChangeValueForKey: @"estimatedProgress"];
1108
1109     unsigned bytesReceived = [data length];
1110     double increment = 0, percentOfRemainingBytes;
1111     long long remainingBytes, estimatedBytesForPendingRequests;
1112
1113     item->bytesReceived += bytesReceived;
1114     if (item->bytesReceived > item->estimatedLength){
1115         _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
1116         item->estimatedLength = item->bytesReceived*2;
1117     }
1118     
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;
1124     
1125     _private->totalBytesReceived += bytesReceived;
1126     
1127     _private->progressValue += increment;
1128
1129     if (_private->progressValue < 0.0)
1130         _private->progressValue = 0.0;
1131
1132     if (_private->progressValue > 1.0)
1133         _private->progressValue = 1.0;
1134
1135     double now = CFAbsoluteTimeGetCurrent();
1136     double notifiedProgressTimeDelta = CFAbsoluteTimeGetCurrent() - _private->lastNotifiedProgressTime;
1137     _private->lastNotifiedProgressTime = now;
1138     
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;
1149         }
1150     }
1151
1152     [self _didChangeValueForKey: @"estimatedProgress"];
1153 }
1154
1155 - (void)_completeProgressForConnectionDelegate:(id)connectionDelegate
1156 {
1157     WebProgressItem *item = [_private->progressItems objectForKey:connectionDelegate];
1158
1159     if (!item)
1160         return;
1161         
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;
1166 }
1167
1168 // Required to prevent automatic observer notifications.
1169 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1170     return NO;
1171 }
1172
1173 - (NSArray *)_declaredKeys {
1174     static NSArray *declaredKeys = nil;
1175     
1176     if (!declaredKeys) {
1177         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, nil];
1178     }
1179
1180     return declaredKeys;
1181 }
1182
1183 - (void)setObservationInfo:(void *)info
1184 {
1185     _private->observationInfo = info;
1186 }
1187
1188 - (void *)observationInfo
1189 {
1190     return _private->observationInfo;
1191 }
1192
1193 - (void)_willChangeBackForwardKeys
1194 {
1195     [self _willChangeValueForKey: _WebCanGoBackKey];
1196     [self _willChangeValueForKey: _WebCanGoForwardKey];
1197 }
1198
1199 - (void)_didChangeBackForwardKeys
1200 {
1201     [self _didChangeValueForKey: _WebCanGoBackKey];
1202     [self _didChangeValueForKey: _WebCanGoForwardKey];
1203 }
1204
1205 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1206 {
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];
1212
1213         [self _willChangeValueForKey: _WebMainFrameURLKey];
1214     }
1215     [NSApp setWindowsNeedUpdate:YES];
1216 }
1217
1218 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1219 {
1220     if (frame == [self mainFrame]){
1221         [self _didChangeValueForKey: _WebMainFrameURLKey];
1222     }
1223     [NSApp setWindowsNeedUpdate:YES];
1224 }
1225
1226 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1227 {
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];
1233     }
1234     [NSApp setWindowsNeedUpdate:YES];
1235 }
1236
1237 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1238 {
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];
1244     }
1245     [NSApp setWindowsNeedUpdate:YES];
1246 }
1247
1248 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1249 {
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];
1255         
1256         [self _didChangeValueForKey: _WebMainFrameURLKey];
1257     }
1258     [NSApp setWindowsNeedUpdate:YES];
1259 }
1260
1261 - (void)_reloadForPluginChanges
1262 {
1263     [[self mainFrame] _reloadForPluginChanges];
1264 }
1265
1266 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1267 {
1268     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1269     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1270     NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1271     [request release];
1272     return cachedResponse;
1273 }
1274
1275 - (void)_writeImageElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1276 {
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]
1283                           types:types];
1284 }
1285
1286 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1287 {
1288     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1289                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1290                         types:types];
1291 }
1292
1293 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1294 {
1295     _private->initiatedDrag = initiatedDrag;
1296 }
1297
1298 #define DASHBOARD_CONTROL_LABEL @"control"
1299
1300 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1301 {
1302     // Add scroller regions for NSScroller and KWQScrollBar
1303     int i, count = [views count];
1304     
1305     for (i = 0; i < count; i++) {
1306         NSView *aView = [views objectAtIndex:i];
1307         
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;
1314             
1315             // AppKit has horrible hack of placing absent scrollers at -100,-100
1316             if (adjustedBounds.origin.y == -100)
1317                 continue;
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];
1332             }
1333             [scrollerRegions addObject:aRegion];
1334         }
1335         [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1336     }
1337 }
1338
1339 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1340 {
1341     [self _addScrollerDashboardRegions:regions from:[self subviews]];
1342 }
1343
1344 - (NSDictionary *)_dashboardRegions
1345 {
1346     // Only return regions from main frame.
1347     NSMutableDictionary *regions = [[[self mainFrame] _bridge] dashboardRegions];
1348     [self _addScrollerDashboardRegions:regions];
1349     return regions;
1350 }
1351
1352 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag;
1353 {
1354     switch (behavior) {
1355         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1356             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1357             break;
1358         }
1359         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1360             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1361             break;
1362         }
1363         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1364             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1365             break;
1366         }
1367         case WebDashboardBehaviorAllowWheelScrolling: {
1368             _private->dashboardBehaviorAllowWheelScrolling = flag;
1369             break;
1370         }
1371     }
1372 }
1373
1374 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1375 {
1376     switch (behavior) {
1377         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1378             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1379         }
1380         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1381             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1382         }
1383         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1384             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1385         }
1386         case WebDashboardBehaviorAllowWheelScrolling: {
1387             return _private->dashboardBehaviorAllowWheelScrolling;
1388         }
1389     }
1390     return NO;
1391 }
1392
1393 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1394 {
1395     [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:self resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:dataSource];
1396 }
1397
1398 + (void)_setShouldUseFontSmoothing:(BOOL)f
1399 {
1400     shouldUseFontSmoothing = f;
1401 }
1402
1403 + (BOOL)_shouldUseFontSmoothing
1404 {
1405     return shouldUseFontSmoothing;
1406 }
1407
1408 + (NSString *)_minimumRequiredSafariBuildNumber
1409 {
1410     return @"420+";
1411 }
1412
1413 @end
1414
1415
1416 @implementation _WebSafeForwarder
1417
1418 - initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
1419 {
1420     self = [super init];
1421     if (!self)
1422         return nil;
1423     
1424     target = t;         // Non retained.
1425     defaultTarget = dt;
1426     templateClass = aClass;
1427     return self;
1428 }
1429
1430
1431 // Used to send messages to delegates that implement informal protocols.
1432 + safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
1433 {
1434     return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
1435 }
1436
1437 #ifndef NDEBUG
1438 NSMutableDictionary *countInvocations;
1439 #endif
1440
1441 - (void)forwardInvocation:(NSInvocation *)anInvocation
1442 {
1443 #ifndef NDEBUG
1444     if (!countInvocations){
1445         countInvocations = [[NSMutableDictionary alloc] init];
1446     }
1447     NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
1448     if (!count)
1449         count = [NSNumber numberWithInt: 1];
1450     else
1451         count = [NSNumber numberWithInt: [count intValue] + 1];
1452     [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
1453 #endif
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.
1459 }
1460
1461 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1462 {
1463     return [templateClass instanceMethodSignatureForSelector: aSelector];
1464 }
1465
1466 @end
1467
1468 @implementation WebView
1469
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
1473 +(void)initialize
1474 {
1475     static BOOL tooLate = NO;
1476     if (!tooLate) {
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];
1479         tooLate = YES;
1480     }
1481 }
1482
1483 +(void)_finishedLaunching
1484 {
1485     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_removeDOMTreeMenuItem:) name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1486     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1487 }
1488
1489 +(void)_removeDOMTreeMenuItem:(NSNotification *)notification
1490 {
1491     NSMenu *debugMenu = [[[[NSApp mainMenu] itemArray] lastObject] submenu];
1492     NSMenuItem *domTree = [debugMenu itemWithTitle:@"Show DOM Tree"];
1493     if (domTree)
1494         [debugMenu removeItem:domTree];
1495     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1496 }
1497 #endif
1498
1499 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1500 {
1501     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1502 }
1503
1504 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1505 {
1506     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1507 }
1508
1509 + (NSArray *)MIMETypesShownAsHTML
1510 {
1511     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1512     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1513     id key;
1514     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1515     
1516     while ((key = [enumerator nextObject])) {
1517         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1518             [array addObject:key];
1519     }
1520     
1521     return array;
1522 }
1523
1524 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1525 {
1526     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1527     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1528     id key;
1529     while ((key = [enumerator nextObject])) {
1530         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1531             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1532     }
1533     
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]];
1539     }
1540 }
1541
1542 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1543 {
1544     return [pasteboard _web_bestURL];
1545 }
1546
1547 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1548 {
1549     return [pasteboard stringForType:WebURLNamePboardType];
1550 }
1551
1552 - (void)_registerDraggedTypes
1553 {
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]];
1559     [types release];
1560 }
1561
1562 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1563 {
1564     static bool CGContextInitialized = false;
1565     if (!CGContextInitialized) {
1566         WKDisableCGDeferredUpdates();
1567         CGContextInitialized = true;
1568     }
1569
1570     _private->drawsBackground = YES;
1571     _private->smartInsertDeleteEnabled = YES;
1572
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];
1578
1579     _private->_pageBridge = [[WebPageBridge alloc] initWithMainFrameName:frameName webView:self frameView:frameView];
1580
1581     [self _addToAllWebViewsSet];
1582     [self setGroupName:groupName];
1583     
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];
1591     }
1592     [super setNextKeyView:frameView];
1593
1594     ++WebViewCount;
1595
1596     [self _registerDraggedTypes];
1597
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]];
1602     
1603     // Register to receive notifications whenever preference values change.
1604     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1605                                                  name:WebPreferencesChangedNotification object:[self preferences]];
1606 }
1607
1608 - initWithFrame:(NSRect)f
1609 {
1610     return [self initWithFrame:f frameName:nil groupName:nil];
1611 }
1612
1613 - initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1614 {
1615     self = [super initWithFrame:f];
1616     if (!self)
1617         return nil;
1618
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");
1628     }
1629 #endif
1630
1631     _private = [[WebViewPrivate alloc] init];
1632     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1633     [self setMaintainsBackForwardList: YES];
1634     return self;
1635 }
1636
1637 - (id)initWithCoder:(NSCoder *)decoder
1638 {
1639     WebView *result = nil;
1640
1641 NS_DURING
1642
1643     NSString *frameName;
1644     NSString *groupName;
1645     WebPreferences *preferences;
1646     BOOL useBackForwardList;
1647
1648     result = [super initWithCoder:decoder];
1649     result->_private = [[WebViewPrivate alloc] init];
1650
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)];
1654
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"];
1660     } else {
1661         int version;
1662         [decoder decodeValueOfObjCType:@encode(int) at:&version];
1663         frameName = [decoder decodeObject];
1664         groupName = [decoder decodeObject];
1665         preferences = [decoder decodeObject];
1666         if (version > 1)
1667             [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1668     }
1669
1670     if (![frameName isKindOfClass:[NSString class]])
1671         frameName = nil;
1672     if (![groupName isKindOfClass:[NSString class]])
1673         groupName = nil;
1674     if (![preferences isKindOfClass:[WebPreferences class]])
1675         preferences = nil;
1676
1677     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1678
1679     if (preferences)
1680         [result setPreferences:preferences];
1681     result->_private->useBackForwardList = useBackForwardList;
1682     [result _commonInitializationWithFrameName:frameName groupName:groupName];
1683
1684 NS_HANDLER
1685
1686     result = nil;
1687     [self release];
1688
1689 NS_ENDHANDLER
1690
1691     return result;
1692 }
1693
1694 - (void)encodeWithCoder:(NSCoder *)encoder
1695 {
1696     [super encodeWithCoder:encoder];
1697
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"];
1703     } else {
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];
1710     }
1711
1712     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)_private->useBackForwardList);
1713 }
1714
1715 - (void)dealloc
1716 {
1717     [self _close];
1718     
1719     --WebViewCount;
1720     
1721     [[NSNotificationCenter defaultCenter] removeObserver:self];
1722     
1723     [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
1724     
1725     [_private release];
1726     // [super dealloc] can end up dispatching against _private (3466082)
1727     _private = nil;
1728
1729     [super dealloc];
1730 }
1731
1732 - (void)finalize
1733 {
1734     [self _close];
1735
1736     --WebViewCount;
1737
1738     [[NSNotificationCenter defaultCenter] removeObserver:self];
1739
1740     [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
1741
1742     [super finalize];
1743 }
1744
1745 - (void)setPreferences:(WebPreferences *)prefs
1746 {
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];
1756     }
1757 }
1758
1759 - (WebPreferences *)preferences
1760 {
1761     return _private->preferences ? _private->preferences : [WebPreferences standardPreferences];
1762 }
1763
1764 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
1765 {
1766     if (![anIdentifier isEqual:[[self preferences] identifier]]) {
1767         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
1768         [self setPreferences:prefs];
1769         [prefs release];
1770     }
1771 }
1772
1773 - (NSString *)preferencesIdentifier
1774 {
1775     return [[self preferences] identifier];
1776 }
1777
1778
1779 - (void)setUIDelegate:delegate
1780 {
1781     _private->UIDelegate = delegate;
1782     [_private->UIDelegateForwarder release];
1783     _private->UIDelegateForwarder = nil;
1784 }
1785
1786 - UIDelegate
1787 {
1788     return _private->UIDelegate;
1789 }
1790
1791 - (void)setResourceLoadDelegate: delegate
1792 {
1793     _private->resourceProgressDelegate = delegate;
1794     [_private->resourceProgressDelegateForwarder release];
1795     _private->resourceProgressDelegateForwarder = nil;
1796     [self _cacheResourceLoadDelegateImplementations];
1797 }
1798
1799
1800 - resourceLoadDelegate
1801 {
1802     return _private->resourceProgressDelegate;
1803 }
1804
1805
1806 - (void)setDownloadDelegate: delegate
1807 {
1808     _private->downloadDelegate = delegate;
1809 }
1810
1811
1812 - downloadDelegate
1813 {
1814     return _private->downloadDelegate;
1815 }
1816
1817 - (void)setPolicyDelegate:delegate
1818 {
1819     _private->policyDelegate = delegate;
1820     [_private->policyDelegateForwarder release];
1821     _private->policyDelegateForwarder = nil;
1822 }
1823
1824 - policyDelegate
1825 {
1826     return _private->policyDelegate;
1827 }
1828
1829 - (void)setFrameLoadDelegate:delegate
1830 {
1831     _private->frameLoadDelegate = delegate;
1832     [_private->frameLoadDelegateForwarder release];
1833     _private->frameLoadDelegateForwarder = nil;
1834 }
1835
1836 - frameLoadDelegate
1837 {
1838     return _private->frameLoadDelegate;
1839 }
1840
1841 - (WebFrame *)mainFrame
1842 {
1843     // This can be called in initialization, before _private has been set up (3465613)
1844     if (!_private)
1845         return nil;
1846
1847     return [(WebFrameBridge *)[_private->_pageBridge mainFrame] webFrame];
1848 }
1849
1850 - (WebBackForwardList *)backForwardList
1851 {
1852     if (_private->useBackForwardList)
1853         return _private->backForwardList;
1854     return nil;
1855 }
1856
1857 - (void)setMaintainsBackForwardList: (BOOL)flag
1858 {
1859     _private->useBackForwardList = flag;
1860 }
1861
1862 - (BOOL)goBack
1863 {
1864     WebHistoryItem *item = [[self backForwardList] backItem];
1865     
1866     if (item){
1867         [self _goToItem: item withLoadType: WebFrameLoadTypeBack];
1868         return YES;
1869     }
1870     return NO;
1871 }
1872
1873 - (BOOL)goForward
1874 {
1875     WebHistoryItem *item = [[self backForwardList] forwardItem];
1876     
1877     if (item){
1878         [self _goToItem: item withLoadType: WebFrameLoadTypeForward];
1879         return YES;
1880     }
1881     return NO;
1882 }
1883
1884 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
1885 {
1886     [self _goToItem: item withLoadType: WebFrameLoadTypeIndexedBackForward];
1887     return YES;
1888 }
1889
1890 - (void)setTextSizeMultiplier:(float)m
1891 {
1892     if (_private->textSizeMultiplier == m) {
1893         return;
1894     }
1895     _private->textSizeMultiplier = m;
1896 }
1897
1898 - (float)textSizeMultiplier
1899 {
1900     return _private->textSizeMultiplier;
1901 }
1902
1903 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
1904 {
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;
1911     }
1912 }
1913
1914 - (NSString *)applicationNameForUserAgent
1915 {
1916     return [[_private->applicationNameForUserAgent retain] autorelease];
1917 }
1918
1919 - (void)setCustomUserAgent:(NSString *)userAgentString
1920 {
1921     NSString *override = [userAgentString copy];
1922     [_private->userAgent release];
1923     _private->userAgent = override;
1924     _private->userAgentOverridden = override != nil;
1925 }
1926
1927 - (NSString *)customUserAgent
1928 {
1929     return _private->userAgentOverridden ? [[_private->userAgent retain] autorelease] : nil;
1930 }
1931
1932 - (void)setMediaStyle:(NSString *)mediaStyle
1933 {
1934     if (_private->mediaStyle != mediaStyle) {
1935         [_private->mediaStyle release];
1936         _private->mediaStyle = [mediaStyle copy];
1937     }
1938 }
1939
1940 - (NSString *)mediaStyle
1941 {
1942     return _private->mediaStyle;
1943 }
1944
1945 - (BOOL)supportsTextEncoding
1946 {
1947     id documentView = [[[self mainFrame] frameView] documentView];
1948     return [documentView conformsToProtocol:@protocol(WebDocumentText)]
1949         && [documentView supportsTextEncoding];
1950 }
1951
1952 - (void)setCustomTextEncodingName:(NSString *)encoding
1953 {
1954     NSString *oldEncoding = [self customTextEncodingName];
1955     if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding]) {
1956         return;
1957     }
1958     [[self mainFrame] _reloadAllowingStaleDataWithOverrideEncoding:encoding];
1959 }
1960
1961 - (NSString *)_mainFrameOverrideEncoding
1962 {
1963     WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
1964     if (dataSource == nil) {
1965         dataSource = [[self mainFrame] dataSource];
1966     }
1967     if (dataSource == nil) {
1968         return nil;
1969     }
1970     return [dataSource _overrideEncoding];
1971 }
1972
1973 - (NSString *)customTextEncodingName
1974 {
1975     return [self _mainFrameOverrideEncoding];
1976 }
1977
1978 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
1979 {
1980     return [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
1981 }
1982
1983 - (WebScriptObject *)windowScriptObject
1984 {
1985     return [[[self mainFrame] _bridge] windowScriptObject];
1986 }
1987
1988         
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
1992 {
1993     NSString *userAgent = _private->userAgent;
1994     if (userAgent) {
1995         return [[userAgent retain] autorelease];
1996     }
1997     
1998     NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
1999     id sourceVersion = [[NSBundle bundleForClass:[WebView class]]
2000         objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
2001     NSString *applicationName = _private->applicationNameForUserAgent;
2002
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];
2006     } else {
2007         userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko)",
2008             language, sourceVersion];
2009     }
2010
2011     _private->userAgent = [userAgent retain];
2012     return userAgent;
2013 }
2014
2015 - (void)setHostWindow:(NSWindow *)hostWindow
2016 {
2017     if (hostWindow != _private->hostWindow) {
2018         [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2019         [_private->hostWindow release];
2020         _private->hostWindow = [hostWindow retain];
2021         [[self mainFrame] _viewDidMoveToHostWindow];
2022     }
2023 }
2024
2025 - (NSWindow *)hostWindow
2026 {
2027     return _private->hostWindow;
2028 }
2029
2030 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2031 {
2032     return [[self _frameViewAtWindowPoint:point] documentView];
2033 }
2034
2035 - (NSView <WebDocumentDragging> *)_draggingDocumentViewAtWindowPoint:(NSPoint)point
2036 {
2037     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:point];
2038     if ([documentView conformsToProtocol:@protocol(WebDocumentDragging)]) {
2039         return (NSView <WebDocumentDragging> *)documentView;
2040     }
2041     return nil;
2042 }
2043
2044 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2045 {
2046     WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2047     if (!frameView)
2048         return nil;
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];
2053     }
2054     return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2055 }
2056
2057 - (NSDictionary *)elementAtPoint:(NSPoint)point
2058 {
2059     return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2060 }
2061
2062 - (void)_setDraggingDocumentView:(NSView <WebDocumentDragging> *)newDraggingView
2063 {
2064     if (_private->draggingDocumentView != newDraggingView) {
2065         [_private->draggingDocumentView release];
2066         _private->draggingDocumentView = [newDraggingView retain];
2067     }
2068 }
2069
2070 - (NSDragOperation)_loadingDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2071 {
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];
2079         }
2080     }
2081     return NSDragOperationNone;
2082 }
2083
2084 - (NSDragOperation)_delegateDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2085 {
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];
2091     }
2092     
2093     _private->dragDestinationActionMask = [[self _UIDelegateForwarder] webView:self dragDestinationActionMaskForDraggingInfo:draggingInfo];
2094     NSDragOperation operation = NSDragOperationNone;
2095     
2096     if (_private->dragDestinationActionMask == WebDragDestinationActionNone) {
2097         [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2098     } else {
2099         operation = [_private->draggingDocumentView draggingUpdatedWithDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask];
2100         if (operation == NSDragOperationNone) {
2101             return [self _loadingDragOperationForDraggingInfo:draggingInfo];
2102         }
2103     }
2104     
2105     return operation;
2106 }
2107
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
2113 {
2114     if (![self isEditable])
2115         return;
2116     
2117     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2118     [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2119 }
2120
2121 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2122 {
2123     if (![self isEditable])
2124         return NO;
2125     
2126     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2127     return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2128 }
2129
2130 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2131 {
2132     return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2133 }
2134
2135 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2136 {
2137     return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2138 }
2139
2140 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2141 {
2142     [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2143     [self _setDraggingDocumentView:nil];
2144 }
2145
2146 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2147 {
2148     return YES;
2149 }
2150
2151 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2152 {
2153     ASSERT(_private->draggingDocumentView == [self _draggingDocumentViewAtWindowPoint:[draggingInfo draggingLocation]]);
2154     
2155     if ([_private->draggingDocumentView concludeDragForDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask]) {
2156         [self _setDraggingDocumentView:nil];
2157         return YES;
2158     }
2159     
2160     [self _setDraggingDocumentView:nil];
2161         
2162     if ([self _loadingDragOperationForDraggingInfo:draggingInfo] != NSDragOperationNone) {    
2163         NSURL *URL = [[self class] URLFromPasteboard:[draggingInfo draggingPasteboard]];
2164         if (URL != nil) {
2165             [[self _UIDelegateForwarder] webView:self willPerformDragDestinationAction:WebDragDestinationActionLoad forDraggingInfo:draggingInfo];
2166             NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2167             [[self mainFrame] loadRequest:request];
2168             [request release];
2169             return YES;
2170         }
2171     }
2172     
2173     return NO;
2174 }
2175
2176 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2177 {
2178     NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2179     if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2180         return self;
2181     } else {
2182         return hitView;
2183     }
2184 }
2185
2186 - (BOOL)acceptsFirstResponder
2187 {
2188     return [[[self mainFrame] frameView] acceptsFirstResponder];
2189 }
2190
2191 - (BOOL)becomeFirstResponder
2192 {
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];
2198     
2199     if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2200         NSView *previousValidKeyView = [self previousValidKeyView];
2201         if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2202             [window makeFirstResponder:previousValidKeyView];
2203             return YES;
2204         } else {
2205             return NO;
2206         }
2207     }
2208     
2209     if ([mainFrameView acceptsFirstResponder]) {
2210         [window makeFirstResponder:mainFrameView];
2211         return YES;
2212     } 
2213     
2214     return NO;
2215 }
2216
2217 - (NSView *)_webcore_effectiveFirstResponder
2218 {
2219     WebFrameView *frameView = [[self mainFrame] frameView];
2220     return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2221 }
2222
2223 - (void)setNextKeyView:(NSView *)aView
2224 {
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];
2231     } else {
2232         [super setNextKeyView:aView];
2233     }
2234 }
2235
2236 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2237 {
2238     return forward ? [curr _nextFrameWithWrap:wrapFlag]
2239                    : [curr _previousFrameWithWrap:wrapFlag];
2240 }
2241
2242 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2243 {
2244     // Get the frame holding the selection, or start with the main frame
2245     WebFrame *startFrame = [self _selectedOrMainFrame];
2246
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;
2251     do {
2252         id <WebDocumentView> view = [[frame frameView] documentView];
2253         if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2254             NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2255
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;
2264                 }
2265                 startSearchView = searchView;
2266             }
2267             
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];
2273                 return YES;
2274             }
2275         }
2276         frame = incrementFrame(frame, forward, wrapFlag);
2277     } while (frame != nil && frame != startFrame);
2278
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];
2284             return YES;
2285         }
2286     }
2287     return NO;
2288 }
2289
2290 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2291 {
2292     [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2293     [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2294 }
2295
2296 - (void)setGroupName:(NSString *)groupName
2297 {
2298     [[self mainFrame] _setFrameNamespace:groupName];
2299 }
2300
2301 - (NSString *)groupName
2302 {
2303     return [[self mainFrame] _frameNamespace];
2304 }
2305
2306 - (double)estimatedProgress
2307 {
2308     return _private->progressValue;
2309 }
2310
2311 - (NSArray *)pasteboardTypesForSelection
2312 {
2313     NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2314     if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2315         return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2316     }
2317     return [NSArray array];
2318 }
2319
2320 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2321 {
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];
2327         }
2328     }
2329 }
2330
2331 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2332 {
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];
2339     }
2340     return [NSArray array];
2341 }
2342
2343 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2344 {
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];
2351     }
2352 }
2353
2354 - (void)moveDragCaretToPoint:(NSPoint)point
2355 {
2356     WebFrameBridge *bridge = [self _bridgeAtPoint:point];
2357     if (bridge != _private->dragCaretBridge) {
2358         [_private->dragCaretBridge removeDragCaret];
2359         _private->dragCaretBridge = [bridge retain];
2360     }
2361     [_private->dragCaretBridge moveDragCaretToPoint:[self convertPoint:point toView:[[[_private->dragCaretBridge webFrame] frameView] documentView]]];
2362 }
2363
2364 - (void)removeDragCaret
2365 {
2366     [_private->dragCaretBridge removeDragCaret];
2367     [_private->dragCaretBridge release];
2368     _private->dragCaretBridge = nil;
2369 }
2370
2371 - (void)_inspectElement:(id)sender
2372 {
2373     NSDictionary *element = [sender representedObject];
2374     WebFrame *frame = [element objectForKey:WebElementFrameKey];
2375     DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
2376     if (!node || !frame)
2377         return;
2378
2379     if ([node nodeType] != DOM_ELEMENT_NODE || [node nodeType] != DOM_DOCUMENT_NODE)
2380         node = [node parentNode];
2381
2382     WebInspector *inspector = [WebInspector sharedWebInspector];
2383     [inspector setWebFrame:frame];
2384     [inspector setFocusedDOMNode:node];
2385
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];
2390
2391     [inspector showWindow:nil];
2392 }
2393 @end
2394
2395 @implementation WebView (WebIBActions)
2396
2397 - (IBAction)takeStringURLFrom: sender
2398 {
2399     NSString *URLString = [sender stringValue];
2400     
2401     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2402 }
2403
2404 - (BOOL)canGoBack
2405 {
2406     return [[self backForwardList] backItem] != nil;
2407 }
2408
2409 - (BOOL)canGoForward
2410 {
2411     return [[self backForwardList] forwardItem] != nil;
2412 }
2413
2414 - (IBAction)goBack:(id)sender
2415 {
2416     [self goBack];
2417 }
2418
2419 - (IBAction)goForward:(id)sender
2420 {
2421     [self goForward];
2422 }
2423
2424 - (IBAction)stopLoading:(id)sender
2425 {
2426     [[self mainFrame] stopLoading];
2427 }
2428
2429 - (IBAction)reload:(id)sender
2430 {
2431     [[self mainFrame] reload];
2432 }
2433
2434 #define MinimumTextSizeMultiplier       0.5
2435 #define MaximumTextSizeMultiplier       3.0
2436 #define TextSizeMultiplierRatio         1.2
2437
2438 - (BOOL)canMakeTextSmaller
2439 {
2440     BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2441     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2442 }
2443
2444 - (BOOL)canMakeTextLarger
2445 {
2446     BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2447     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2448 }
2449
2450 - (IBAction)makeTextSmaller:(id)sender
2451 {
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];
2455 }
2456
2457 - (IBAction)makeTextLarger:(id)sender
2458 {
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];
2462 }
2463
2464 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2465 {
2466     id responder = [self _responderForResponderOperations];
2467     if (responder != self && [responder respondsToSelector:[item action]]) {
2468         if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)]) {
2469             return [responder validateUserInterfaceItem:item];
2470         }
2471         return YES;
2472     }
2473     return NO;
2474 }
2475
2476 #define VALIDATE(name) \
2477     else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2478
2479 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2480 {
2481     SEL action = [item action];
2482
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;
2499         BOOL retVal = NO;
2500         if ([self isEditable] && [self _continuousCheckingAllowed]) {
2501             checkMark = [self isContinuousSpellCheckingEnabled];
2502             retVal = YES;
2503         }
2504         if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2505             NSMenuItem *menuItem = (NSMenuItem *)item;
2506             [menuItem setState:checkMark ? NSOnState : NSOffState];
2507         }
2508         return retVal;
2509     }
2510     FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2511
2512     return YES;
2513 }
2514
2515 @end
2516
2517 @implementation WebView (WebPendingPublic)
2518
2519 - (void)setMainFrameURL:(NSString *)URLString
2520 {
2521     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2522 }
2523
2524 - (NSString *)mainFrameURL
2525 {
2526     WebDataSource *ds;
2527     ds = [[self mainFrame] provisionalDataSource];
2528     if (!ds)
2529         ds = [[self mainFrame] dataSource];
2530     return [[[ds request] URL] _web_originalDataAsString];
2531 }
2532
2533 - (BOOL)isLoading
2534 {
2535     LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2536     return [self _isLoading];
2537 }
2538
2539 - (NSString *)mainFrameTitle
2540 {
2541     NSString *mainFrameTitle = [[[self mainFrame] dataSource] pageTitle];
2542     return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2543 }
2544
2545 - (NSImage *)mainFrameIcon
2546 {
2547     return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2548 }
2549
2550 - (void)setDrawsBackground:(BOOL)drawsBackground
2551 {
2552     if (_private->drawsBackground == drawsBackground)
2553         return;
2554     _private->drawsBackground = drawsBackground;
2555     [[self mainFrame] _updateDrawsBackground];
2556 }
2557
2558 - (BOOL)drawsBackground
2559 {
2560     return _private->drawsBackground;
2561 }
2562
2563 - (void)toggleSmartInsertDelete:(id)sender
2564 {
2565     if ([self isEditable]) {
2566         [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2567     }
2568 }
2569
2570 - (IBAction)toggleContinuousSpellChecking:(id)sender
2571 {
2572     if ([self isEditable]) {
2573         [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2574     }
2575 }
2576
2577 - (BOOL)maintainsInactiveSelection
2578 {
2579     return [self isEditable];
2580 }
2581
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
2585 {
2586     return [self _selectedOrMainFrame];
2587 }
2588
2589 - (WebFrame *)selectedFrame
2590 {
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];
2595     if (focusedFrame) {
2596 #ifndef NDEBUG
2597         WebFrame *frameWithSelection = [[self mainFrame] _findFrameWithSelection];
2598 #endif
2599         ASSERT(frameWithSelection == nil || frameWithSelection == focusedFrame);
2600         return focusedFrame;
2601     }
2602     
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];
2606     
2607     return nil;
2608 }
2609
2610 - (BOOL)canMakeTextStandardSize
2611 {
2612     BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0;
2613     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0];
2614 }
2615
2616 - (IBAction)makeTextStandardSize:(id)sender
2617 {
2618     BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0;
2619     [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0];
2620 }
2621
2622 - (void)setScriptDebugDelegate:delegate
2623 {
2624     _private->scriptDebugDelegate = delegate;
2625     [_private->scriptDebugDelegateForwarder release];
2626     _private->scriptDebugDelegateForwarder = nil;
2627 }
2628
2629 - scriptDebugDelegate
2630 {
2631     return _private->scriptDebugDelegate;
2632 }
2633
2634 - (BOOL)shouldClose
2635 {
2636     WebFrameBridge *bridge = [[self mainFrame] _bridge];
2637     if (!bridge)
2638         return YES;
2639     return [bridge shouldClose];
2640 }
2641
2642 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
2643 {
2644     return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
2645 }
2646
2647 - (unsigned)highlightAllMatchesForString:(NSString *)string caseSensitive:(BOOL)caseFlag
2648 {
2649     WebFrame *frame = [self mainFrame];
2650     unsigned matchCount = 0;
2651     do {
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];
2656
2657         frame = incrementFrame(frame, YES, NO);
2658     } while (frame);
2659     
2660     return matchCount;
2661 }
2662
2663 - (void)clearHighlightedMatches
2664 {
2665     WebFrame *frame = [self mainFrame];
2666     do {
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];
2671
2672         frame = incrementFrame(frame, YES, NO);
2673     } while (frame);
2674 }
2675
2676 @end
2677
2678 @implementation WebView (WebViewPrintingPrivate)
2679
2680 - (float)_headerHeight
2681 {
2682     if ([[self UIDelegate] respondsToSelector:@selector(webViewHeaderHeight:)]) {
2683         return [[self UIDelegate] webViewHeaderHeight:self];
2684     }
2685     
2686 #ifdef DEBUG_HEADER_AND_FOOTER
2687     return 25;
2688 #else
2689     return 0;
2690 #endif
2691 }
2692
2693 - (float)_footerHeight
2694 {
2695     if ([[self UIDelegate] respondsToSelector:@selector(webViewFooterHeight:)]) {
2696         return [[self UIDelegate] webViewFooterHeight:self];
2697     }
2698     
2699 #ifdef DEBUG_HEADER_AND_FOOTER
2700     return 50;
2701 #else
2702     return 0;
2703 #endif
2704 }
2705
2706 - (void)_drawHeaderInRect:(NSRect)rect
2707 {
2708 #ifdef DEBUG_HEADER_AND_FOOTER
2709     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2710     [currentContext saveGraphicsState];
2711     [[NSColor yellowColor] set];
2712     NSRectFill(rect);
2713     [currentContext restoreGraphicsState];
2714 #endif
2715     
2716     if ([[self UIDelegate] respondsToSelector:@selector(webView:drawHeaderInRect:)]) {
2717         NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2718         [currentContext saveGraphicsState];
2719         NSRectClip(rect);
2720         [[self UIDelegate] webView:self drawHeaderInRect:rect]; 
2721         [currentContext restoreGraphicsState];
2722     }
2723 }
2724
2725 - (void)_drawFooterInRect:(NSRect)rect
2726 {
2727 #ifdef DEBUG_HEADER_AND_FOOTER
2728     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2729     [currentContext saveGraphicsState];
2730     [[NSColor cyanColor] set];
2731     NSRectFill(rect);
2732     [currentContext restoreGraphicsState];
2733 #endif
2734     
2735     if ([[self UIDelegate] respondsToSelector:@selector(webView:drawFooterInRect:)]) {
2736         NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
2737         [currentContext saveGraphicsState];
2738         NSRectClip(rect);
2739         [[self UIDelegate] webView:self drawFooterInRect:rect];
2740         [currentContext restoreGraphicsState];
2741     }
2742 }
2743
2744 - (void)_adjustPrintingMarginsForHeaderAndFooter
2745 {
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];
2751 }
2752
2753 - (void)_drawHeaderAndFooter
2754 {
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]);
2767     
2768     [self _drawHeaderInRect:headerRect];
2769     [self _drawFooterInRect:footerRect];
2770 }
2771 @end
2772
2773 @implementation WebView (WebDebugBinding)
2774
2775 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
2776 {
2777     LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
2778     [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
2779 }
2780
2781 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
2782 {
2783     LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
2784     [super removeObserver:anObserver forKeyPath:keyPath];
2785 }
2786
2787 @end
2788
2789 //==========================================================================================
2790 // Editing
2791
2792 @implementation WebView (WebViewCSS)
2793
2794 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
2795 {
2796     // FIXME: is this the best level for this conversion?
2797     if (pseudoElement == nil) {
2798         pseudoElement = @"";
2799     }
2800     return [[element ownerDocument] getComputedStyle:element :pseudoElement];
2801 }
2802
2803 @end
2804
2805 @implementation WebView (WebViewEditing)
2806
2807 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
2808 {
2809     WebFrameBridge *bridge = [self _bridgeAtPoint:point];
2810     return [bridge editableDOMRangeForPoint:[self convertPoint:point toView:[[[bridge webFrame] frameView] documentView]]];
2811 }
2812
2813 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
2814 {
2815     return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
2816 }
2817
2818 - (BOOL)_shouldBeginEditingInDOMRange:(DOMRange *)range
2819 {
2820     return [[self _editingDelegateForwarder] webView:self shouldBeginEditingInDOMRange:range];
2821 }
2822
2823 - (BOOL)_shouldEndEditingInDOMRange:(DOMRange *)range
2824 {
2825     return [[self _editingDelegateForwarder] webView:self shouldEndEditingInDOMRange:range];
2826 }
2827
2828 - (BOOL)_canPaste
2829 {
2830     id documentView = [[[self mainFrame] frameView] documentView];
2831     return [documentView respondsToSelector:@selector(_canPaste)] && [documentView _canPaste];
2832 }
2833
2834 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
2835 {
2836     if (range == nil) {
2837         [[self _bridgeForSelectedOrMainFrame] deselectText];
2838     } else {
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];
2843     }
2844 }
2845
2846 - (DOMRange *)selectedDOMRange
2847 {
2848     return [[self _bridgeForSelectedOrMainFrame] selectedDOMRange];
2849 }
2850
2851 - (NSSelectionAffinity)selectionAffinity
2852 {
2853     return [[self _bridgeForSelectedOrMainFrame] selectionAffinity];
2854 }
2855
2856 - (void)setEditable:(BOOL)flag
2857 {
2858     if (_private->editable != flag) {
2859         _private->editable = flag;
2860         WebFrameBridge *bridge = [[self mainFrame] _bridge];
2861         if (flag) {
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];
2866         }
2867         else {
2868             [bridge removeEditingStyleFromBodyElement];
2869         }
2870     }
2871 }
2872
2873 - (BOOL)isEditable
2874 {
2875     return _private->editable;
2876 }
2877
2878 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
2879 {
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];
2883 }
2884
2885 - (DOMCSSStyleDeclaration *)typingStyle
2886 {
2887     return [[self _bridgeForSelectedOrMainFrame] typingStyle];
2888 }
2889
2890 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
2891 {
2892     _private->smartInsertDeleteEnabled = flag;
2893 }
2894
2895 - (BOOL)smartInsertDeleteEnabled
2896 {
2897     return _private->smartInsertDeleteEnabled;
2898 }
2899
2900 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
2901 {
2902     _private->continuousSpellCheckingEnabled = flag;
2903     if ([self isContinuousSpellCheckingEnabled]) {
2904         [[self class] _preflightSpellChecker];
2905     } else {
2906         [[self mainFrame] _unmarkAllMisspellings];
2907     }
2908 }
2909
2910 - (BOOL)isContinuousSpellCheckingEnabled
2911 {
2912     return _private->continuousSpellCheckingEnabled && [self _continuousCheckingAllowed];
2913 }
2914
2915 - (WebNSInt)spellCheckerDocumentTag
2916 {
2917     if (!_private->hasSpellCheckerDocumentTag) {
2918         _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
2919         _private->hasSpellCheckerDocumentTag = YES;
2920     }
2921     return _private->spellCheckerDocumentTag;
2922 }
2923
2924 - (NSUndoManager *)undoManager
2925 {
2926     NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
2927     if (undoManager) {
2928         return undoManager;
2929     }
2930     return [super undoManager];
2931 }
2932
2933 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
2934 {
2935     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
2936     if ([_private->editingDelegate respondsToSelector:selector])
2937         [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
2938 }
2939
2940 - (void)setEditingDelegate:(id)delegate
2941 {
2942     if (_private->editingDelegate == delegate)
2943         return;
2944
2945     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
2946
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];
2953     
2954     _private->editingDelegate = delegate;
2955     [_private->editingDelegateForwarder release];
2956     _private->editingDelegateForwarder = nil;
2957     
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:)];
2964 }
2965
2966 - (id)editingDelegate
2967 {
2968     return _private->editingDelegate;
2969 }
2970
2971 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
2972 {
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];
2976     return decl;
2977 }
2978
2979 @end
2980
2981 @implementation WebView (WebViewUndoableEditing)
2982
2983 - (void)replaceSelectionWithNode:(DOMNode *)node
2984 {
2985     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO];
2986 }    
2987
2988 - (void)replaceSelectionWithText:(NSString *)text
2989 {
2990     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
2991 }
2992
2993 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
2994 {
2995     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
2996 }
2997
2998 - (void)replaceSelectionWithArchive:(WebArchive *)archive
2999 {
3000     [[[[self _bridgeForSelectedOrMainFrame] webFrame] dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3001 }
3002
3003 - (void)deleteSelection
3004 {
3005     WebFrameBridge *bridge = [self _bridgeForSelectedOrMainFrame];
3006     [bridge deleteSelectionWithSmartDelete:[(WebHTMLView *)[[[bridge webFrame] frameView] documentView] _canSmartCopyOrDelete]];
3007 }
3008     
3009 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3010 {
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];
3014 }
3015
3016 @end
3017
3018 @implementation WebView (WebViewEditingActions)
3019
3020 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3021 {
3022     static BOOL reentered = NO;
3023     if (reentered) {
3024         [[self nextResponder] tryToPerform:selector with:parameter];
3025         return;
3026     }
3027
3028     // There are two possibilities here.
3029     //
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.
3034     //
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.
3038
3039     // Pass this selector down to the first responder.
3040     NSResponder *responder = [self _responderForResponderOperations];
3041     reentered = YES;
3042     [responder tryToPerform:selector with:parameter];
3043     reentered = NO;
3044 }
3045
3046 #define FORWARD(name) \
3047     - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3048
3049 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3050
3051 - (void)insertText:(NSString *)text
3052 {
3053     [self _performResponderOperation:_cmd with:text];
3054 }
3055
3056 @end
3057
3058 @implementation WebView (WebViewEditingInMail)
3059
3060 - (void)_insertNewlineInQuotedContent;
3061 {
3062     [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3063 }
3064
3065 - (BOOL)_selectWordBeforeMenuEvent
3066 {
3067     return _private->selectWordBeforeMenuEvent;
3068 }
3069
3070 - (void)_setSelectWordBeforeMenuEvent:(BOOL)flag
3071 {
3072     _private->selectWordBeforeMenuEvent = flag;
3073 }
3074
3075 @end
3076
3077 @implementation WebView (WebFileInternal)
3078
3079 - (WebFrame *)_focusedFrame
3080 {
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];
3088     }
3089     
3090     return nil;
3091 }
3092
3093 - (WebFrame *)_selectedOrMainFrame
3094 {
3095     WebFrame *result = [self selectedFrame];
3096     if (result == nil)
3097         result = [self mainFrame];
3098     return result;
3099 }
3100
3101 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame
3102 {
3103     return [[self _selectedOrMainFrame] _bridge];
3104 }
3105
3106 - (BOOL)_isLoading
3107 {
3108     WebFrame *mainFrame = [self mainFrame];
3109     return [[mainFrame dataSource] isLoading]
3110         || [[mainFrame provisionalDataSource] isLoading];
3111 }
3112
3113 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point
3114 {
3115     NSView *view = [self hitTest:[[self superview] convertPoint:point fromView:nil]];
3116     return (WebFrameView *)[view _web_superviewOfClass:[WebFrameView class] stoppingAtClass:[self class]];
3117 }
3118
3119 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point
3120 {
3121     return [[[self _frameViewAtWindowPoint:[self convertPoint:point toView:nil]] webFrame] _bridge];
3122 }
3123
3124 + (void)_preflightSpellCheckerNow:(id)sender
3125 {
3126     [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
3127 }
3128
3129 + (void)_preflightSpellChecker
3130 {
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];
3134     } else {
3135         [self performSelector:@selector(_preflightSpellCheckerNow:) withObject:self afterDelay:2.0];
3136     }
3137 }
3138
3139 - (BOOL)_continuousCheckingAllowed
3140 {
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"];
3146         }
3147         readAllowContinuousSpellCheckingDefault = YES;
3148     }
3149     return allowContinuousSpellChecking;
3150 }
3151
3152 - (NSResponder *)_responderForResponderOperations
3153 {
3154     NSResponder *responder = [[self window] firstResponder];
3155     if (![self _web_firstResponderIsSelfOrDescendantView]) {
3156         responder = [[[self mainFrame] frameView] documentView];
3157         if (!responder) {
3158             responder = [[self mainFrame] frameView];
3159         }
3160     }
3161     return responder;
3162 }
3163
3164 - (void)_searchWithGoogleFromMenu:(id)sender
3165 {
3166     id documentView = [[[self mainFrame] frameView] documentView];
3167     if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3168         return;
3169     }
3170     
3171     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3172     if ([selectedString length] == 0) {
3173         return;
3174     }
3175     
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];
3183     [s release];
3184     
3185     // FIXME: seems fragile to use the service by name, but this is what AppKit does
3186     NSPerformService(@"Search With Google", pasteboard);
3187 }
3188
3189 - (void)_searchWithSpotlightFromMenu:(id)sender
3190 {
3191     id documentView = [[[self mainFrame] frameView] documentView];
3192     if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3193         return;
3194     }
3195     
3196     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3197     if ([selectedString length] == 0) {
3198         return;
3199     }
3200
3201     (void)HISearchWindowShow((CFStringRef)selectedString, kNilOptions);
3202 }
3203
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
3212 {
3213     if ([[self mainFrame] dataSource] == nil) {
3214         return NO;
3215     }
3216     
3217     BOOL foundSome = NO;
3218     NSArray *docViews = [[self mainFrame] _documentViews];
3219     int i;
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;
3224             BOOL isSuitable;
3225             if ([sizingDocView _tracksCommonSizeFactor]) {
3226                 isSuitable = doTrackingViews;
3227                 if (isSuitable && newScaleFactor != 0) {
3228                     [self setTextSizeMultiplier:newScaleFactor];
3229                 }
3230             } else {
3231                 // Incantation to perform a selector returning a BOOL.
3232                 isSuitable = ((BOOL(*)(id, SEL))objc_msgSend)(sizingDocView, testSel);
3233             }
3234             
3235             if (isSuitable) {
3236                 if (sel != 0) {
3237                     foundSome = YES;
3238                     [sizingDocView performSelector:sel withObject:arg];
3239                 } else {
3240                     // if we're just called for the benefit of the return value, we can return at first match
3241                     return YES;
3242                 }
3243             }
3244         }
3245     }
3246     
3247     return foundSome;
3248 }
3249
3250 @end
3251
3252 @implementation WebView (WebViewBridge)
3253
3254 - (WebPageBridge *)_pageBridge
3255 {
3256     return _private->_pageBridge;
3257 }
3258
3259 @end