38eeeedfce515589f27899bac56d792ae51ca8e5
[WebKit-https.git] / WebKit / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #import "WebViewInternal.h"
31
32 #import "DOMRangeInternal.h"
33 #import "WebBackForwardList.h"
34 #import "WebBaseNetscapePluginView.h"
35 #import "WebDOMOperationsPrivate.h"
36 #import "WebDashboardRegion.h"
37 #import "WebDataSourceInternal.h"
38 #import "WebDefaultEditingDelegate.h"
39 #import "WebDefaultFrameLoadDelegate.h"
40 #import "WebDefaultPolicyDelegate.h"
41 #import "WebDefaultResourceLoadDelegate.h"
42 #import "WebDefaultScriptDebugDelegate.h"
43 #import "WebDefaultUIDelegate.h"
44 #import "WebDocument.h"
45 #import "WebDocumentInternal.h"
46 #import "WebDownload.h"
47 #import "WebDownloadInternal.h"
48 #import "WebDynamicScrollBarsView.h"
49 #import "WebEditingDelegate.h"
50 #import "WebFormDelegatePrivate.h"
51 #import "WebFrameBridge.h"
52 #import "WebFrameInternal.h"
53 #import "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 "WebPDFView.h"
76 #import "WebPageBridge.h"
77 #import "WebPluginDatabase.h"
78 #import "WebPolicyDelegate.h"
79 #import "WebPreferenceKeysPrivate.h"
80 #import "WebPreferencesPrivate.h"
81 #import "WebResourceLoadDelegate.h"
82 #import "WebScriptDebugDelegatePrivate.h"
83 #import "WebScriptDebugServerPrivate.h"
84 #import "WebUIDelegate.h"
85 #import "WebUIDelegatePrivate.h"
86 #import <CoreFoundation/CFSet.h>
87 #import <Foundation/NSURLConnection.h>
88 #import <JavaScriptCore/Assertions.h>
89 #import <WebCore/Document.h>
90 #import <WebCore/Editor.h>
91 #import <WebCore/ExceptionHandlers.h>
92 #import <WebCore/FrameLoader.h>
93 #import <WebCore/FrameMac.h>
94 #import <WebCore/FrameTree.h>
95 #import <WebCore/Page.h>
96 #import <WebCore/WebCoreEncodings.h>
97 #import <WebCore/WebCoreFrameBridge.h>
98 #import <WebCore/WebCoreSettings.h>
99 #import <WebCore/WebCoreTextRenderer.h>
100 #import <WebCore/WebCoreView.h>
101 #import <WebCore/WebDataProtocol.h>
102 #import <WebCore/DocumentLoader.h>
103 #import <WebKit/DOM.h>
104 #import <WebKit/DOMExtensions.h>
105 #import <WebKit/DOMPrivate.h>
106 #import <WebKitSystemInterface.h>
107 #import <objc/objc-runtime.h>
108
109 using namespace WebCore;
110
111 #if defined(__ppc__) || defined(__ppc64__)
112 #define PROCESSOR "PPC"
113 #elif defined(__i386__) || defined(__x86_64__)
114 #define PROCESSOR "Intel"
115 #else
116 #error Unknown architecture
117 #endif
118
119 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
120 macro(alignCenter) \
121 macro(alignJustified) \
122 macro(alignLeft) \
123 macro(alignRight) \
124 macro(capitalizeWord) \
125 macro(centerSelectionInVisibleArea) \
126 macro(changeAttributes) \
127 macro(changeColor) \
128 macro(changeDocumentBackgroundColor) \
129 macro(changeFont) \
130 macro(checkSpelling) \
131 macro(complete) \
132 macro(copy) \
133 macro(copyFont) \
134 macro(cut) \
135 macro(delete) \
136 macro(deleteBackward) \
137 macro(deleteBackwardByDecomposingPreviousCharacter) \
138 macro(deleteForward) \
139 macro(deleteToBeginningOfLine) \
140 macro(deleteToBeginningOfParagraph) \
141 macro(deleteToEndOfLine) \
142 macro(deleteToEndOfParagraph) \
143 macro(deleteWordBackward) \
144 macro(deleteWordForward) \
145 macro(ignoreSpelling) \
146 macro(indent) \
147 macro(insertBacktab) \
148 macro(insertNewline) \
149 macro(insertNewlineIgnoringFieldEditor) \
150 macro(insertParagraphSeparator) \
151 macro(insertTab) \
152 macro(insertTabIgnoringFieldEditor) \
153 macro(lowercaseWord) \
154 macro(moveBackward) \
155 macro(moveBackwardAndModifySelection) \
156 macro(moveDown) \
157 macro(moveDownAndModifySelection) \
158 macro(moveForward) \
159 macro(moveForwardAndModifySelection) \
160 macro(moveLeft) \
161 macro(moveLeftAndModifySelection) \
162 macro(moveRight) \
163 macro(moveRightAndModifySelection) \
164 macro(moveToBeginningOfDocument) \
165 macro(moveToBeginningOfDocumentAndModifySelection) \
166 macro(moveToBeginningOfSentence) \
167 macro(moveToBeginningOfSentenceAndModifySelection) \
168 macro(moveToBeginningOfLine) \
169 macro(moveToBeginningOfLineAndModifySelection) \
170 macro(moveToBeginningOfParagraph) \
171 macro(moveToBeginningOfParagraphAndModifySelection) \
172 macro(moveToEndOfDocument) \
173 macro(moveToEndOfDocumentAndModifySelection) \
174 macro(moveToEndOfLine) \
175 macro(moveToEndOfLineAndModifySelection) \
176 macro(moveToEndOfParagraph) \
177 macro(moveToEndOfParagraphAndModifySelection) \
178 macro(moveToEndOfSentence) \
179 macro(moveToEndOfSentenceAndModifySelection) \
180 macro(moveUp) \
181 macro(moveUpAndModifySelection) \
182 macro(moveWordBackward) \
183 macro(moveWordBackwardAndModifySelection) \
184 macro(moveWordForward) \
185 macro(moveWordForwardAndModifySelection) \
186 macro(moveWordLeft) \
187 macro(moveWordLeftAndModifySelection) \
188 macro(moveWordRight) \
189 macro(moveWordRightAndModifySelection) \
190 macro(pageDown) \
191 macro(pageUp) \
192 macro(paste) \
193 macro(pasteAsPlainText) \
194 macro(pasteAsRichText) \
195 macro(pasteFont) \
196 macro(performFindPanelAction) \
197 macro(scrollLineDown) \
198 macro(scrollLineUp) \
199 macro(scrollPageDown) \
200 macro(scrollPageUp) \
201 macro(scrollToBeginningOfDocument) \
202 macro(scrollToEndOfDocument) \
203 macro(selectAll) \
204 macro(selectWord) \
205 macro(selectSentence) \
206 macro(selectLine) \
207 macro(selectParagraph) \
208 macro(showGuessPanel) \
209 macro(startSpeaking) \
210 macro(stopSpeaking) \
211 macro(subscript) \
212 macro(superscript) \
213 macro(underline) \
214 macro(unscript) \
215 macro(uppercaseWord) \
216 macro(yank) \
217 macro(yankAndSelect) \
218
219 @interface NSSpellChecker (AppKitSecretsIKnow)
220 - (void)_preflightChosenSpellServer;
221 @end
222
223 @interface NSView (AppKitSecretsIKnow)
224 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
225 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
226 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
227 @end
228
229 @interface WebViewPrivate : NSObject
230 {
231 @public
232     WebPageBridge *_pageBridge;
233     
234     id UIDelegate;
235     id UIDelegateForwarder;
236     id resourceProgressDelegate;
237     id resourceProgressDelegateForwarder;
238     id downloadDelegate;
239     id policyDelegate;
240     id policyDelegateForwarder;
241     id frameLoadDelegate;
242     id frameLoadDelegateForwarder;
243     id <WebFormDelegate> formDelegate;
244     id editingDelegate;
245     id editingDelegateForwarder;
246     id scriptDebugDelegate;
247     id scriptDebugDelegateForwarder;
248     
249     WebBackForwardList *backForwardList;
250     BOOL useBackForwardList;
251     
252     float textSizeMultiplier;
253
254     NSString *applicationNameForUserAgent;
255     NSString *userAgent;
256     BOOL userAgentOverridden;
257     
258     WebPreferences *preferences;
259     WebCoreSettings *settings;
260         
261     BOOL lastElementWasNonNil;
262
263     NSWindow *hostWindow;
264
265     int programmaticFocusCount;
266     
267     WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
268
269     long long totalPageAndResourceBytesToLoad;
270     long long totalBytesReceived;
271     double progressValue;
272     double lastNotifiedProgressValue;
273     double lastNotifiedProgressTime;
274     double progressNotificationInterval;
275     double progressNotificationTimeInterval;
276     BOOL finalProgressChangedSent;
277     WebFrame *originatingProgressFrame;
278     
279     int numProgressTrackedFrames;
280     NSMutableDictionary *progressItems;
281     
282     void *observationInfo;
283     
284     BOOL closed;
285     BOOL shouldCloseWithWindow;
286     BOOL mainFrameDocumentReady;
287     BOOL drawsBackground;
288     BOOL editable;
289     BOOL initiatedDrag;
290     BOOL tabKeyCyclesThroughElements;
291     BOOL tabKeyCyclesThroughElementsChanged;
292
293     NSColor *backgroundColor;
294
295     NSString *mediaStyle;
296     
297     NSView <WebDocumentDragging> *draggingDocumentView;
298     unsigned int dragDestinationActionMask;
299     
300     BOOL hasSpellCheckerDocumentTag;
301     WebNSInteger spellCheckerDocumentTag;
302
303     BOOL smartInsertDeleteEnabled;
304         
305     BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
306     BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
307     BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
308     BOOL dashboardBehaviorAllowWheelScrolling;
309     
310     BOOL selectWordBeforeMenuEvent;
311     
312     WebPluginDatabase *pluginDatabase;
313 }
314 @end
315
316 @interface WebView (WebFileInternal)
317 - (WebFrame *)_selectedOrMainFrame;
318 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame;
319 - (BOOL)_isLoading;
320 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
321 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point;
322 - (WebFrame *)_focusedFrame;
323 + (void)_preflightSpellChecker;
324 - (BOOL)_continuousCheckingAllowed;
325 - (NSResponder *)_responderForResponderOperations;
326 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor;
327 - (void)_notifyTextSizeMultiplierChanged;
328 @end
329
330 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
331 NSString *WebElementFrameKey =              @"WebElementFrame";
332 NSString *WebElementImageKey =              @"WebElementImage";
333 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
334 NSString *WebElementImageRectKey =          @"WebElementImageRect";
335 NSString *WebElementImageURLKey =           @"WebElementImageURL";
336 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
337 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
338 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
339 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
340 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
341 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
342 NSString *WebElementTitleKey =              @"WebElementTitle";
343
344 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
345 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
346 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
347
348 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
349 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
350 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
351 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
352 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
353
354 enum { WebViewVersion = 2 };
355
356 #define timedLayoutSize 4096
357
358 static NSMutableSet *schemesWithRepresentationsSet;
359
360 NSString *_WebCanGoBackKey =            @"canGoBack";
361 NSString *_WebCanGoForwardKey =         @"canGoForward";
362 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
363 NSString *_WebIsLoadingKey =            @"isLoading";
364 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
365 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
366 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
367 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
368
369 @interface WebProgressItem : NSObject
370 {
371 @public
372     long long bytesReceived;
373     long long estimatedLength;
374 }
375 @end
376
377 @implementation WebProgressItem
378 @end
379
380
381 static BOOL continuousSpellCheckingEnabled;
382 #if !BUILDING_ON_TIGER
383 static BOOL grammarCheckingEnabled;
384 #endif
385
386 @implementation WebViewPrivate
387
388 - init 
389 {
390     self = [super init];
391     if (!self)
392         return nil;
393     
394     backForwardList = [[WebBackForwardList alloc] init];
395     textSizeMultiplier = 1;
396     progressNotificationInterval = 0.02;
397     progressNotificationTimeInterval = 0.1;
398     settings = [[WebCoreSettings alloc] init];
399     dashboardBehaviorAllowWheelScrolling = YES;
400     tabKeyCyclesThroughElements = YES;
401     shouldCloseWithWindow = objc_collecting_enabled();
402     continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
403 #if !BUILDING_ON_TIGER
404     grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
405 #endif
406     
407     return self;
408 }
409
410 - (void)dealloc
411 {
412     ASSERT(!_pageBridge);
413     ASSERT(draggingDocumentView == nil);
414     
415     [backForwardList release];
416     [applicationNameForUserAgent release];
417     [userAgent release];
418     [backgroundColor release];
419     
420     [preferences release];
421     [settings release];
422     [hostWindow release];
423     
424     [policyDelegateForwarder release];
425     [resourceProgressDelegateForwarder release];
426     [UIDelegateForwarder release];
427     [frameLoadDelegateForwarder release];
428     [editingDelegateForwarder release];
429     [scriptDebugDelegateForwarder release];
430     
431     [progressItems release];
432         
433     [mediaStyle release];
434     
435     [super dealloc];
436 }
437
438 @end
439
440 @implementation WebView (AllWebViews)
441
442 static CFSetCallBacks NonRetainingSetCallbacks = {
443     0,
444     NULL,
445     NULL,
446     CFCopyDescription,
447     CFEqual,
448     CFHash
449 };
450
451 static CFMutableSetRef allWebViewsSet;
452
453 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
454 {
455     if (!allWebViewsSet)
456         return;
457
458     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
459 }
460
461 - (void)_removeFromAllWebViewsSet
462 {
463     if (allWebViewsSet)
464         CFSetRemoveValue(allWebViewsSet, self);
465 }
466
467 - (void)_addToAllWebViewsSet
468 {
469     if (!allWebViewsSet)
470         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
471
472     CFSetSetValue(allWebViewsSet, self);
473 }
474
475 @end
476
477 @implementation WebView (WebPrivate)
478
479 #ifdef DEBUG_WIDGET_DRAWING
480 static bool debugWidget = true;
481 - (void)drawRect:(NSRect)rect
482 {
483     [[NSColor blueColor] set];
484     NSRectFill (rect);
485     
486     NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
487
488     if (debugWidget) {
489         while (debugWidget) {
490             sleep (1);
491         }
492     }
493
494     NSLog (@"%s:   rect:  (%0.f,%0.f) %0.f %0.f, htmlViewRect:  (%0.f,%0.f) %0.f %0.f\n", 
495         __PRETTY_FUNCTION__, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
496         htmlViewRect.origin.x, htmlViewRect.origin.y, htmlViewRect.size.width, htmlViewRect.size.height
497     );
498
499     [super drawRect:rect];
500 }
501 #endif
502
503 + (BOOL)_developerExtrasEnabled
504 {
505 #ifdef NDEBUG
506     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
507     BOOL enableDebugger = [defaults boolForKey:@"WebKitDeveloperExtras"];
508     if (!enableDebugger)
509         enableDebugger = [defaults boolForKey:@"IncludeDebugMenu"];
510     return enableDebugger;
511 #else
512     return YES; // always enable in debug builds
513 #endif
514 }
515
516 + (BOOL)_scriptDebuggerEnabled
517 {
518 #ifdef NDEBUG
519     return [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitScriptDebuggerEnabled"];
520 #else
521     return YES; // always enable in debug builds
522 #endif
523 }
524
525 + (NSArray *)_supportedMIMETypes
526 {
527     // Load the plug-in DB allowing plug-ins to install types.
528     [WebPluginDatabase installedPlugins];
529     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
530 }
531
532 + (NSArray *)_supportedFileExtensions
533 {
534     NSMutableSet *extensions = [[NSMutableSet alloc] init];
535     NSArray *MIMETypes = [self _supportedMIMETypes];
536     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
537     NSString *MIMEType;
538     while ((MIMEType = [enumerator nextObject]) != nil) {
539         NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
540         if (extensionsForType) {
541             [extensions addObjectsFromArray:extensionsForType];
542         }
543     }
544     NSArray *uniqueExtensions = [extensions allObjects];
545     [extensions release];
546     return uniqueExtensions;
547 }
548
549 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
550 {
551     MIMEType = [MIMEType lowercaseString];
552     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
553     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
554     
555     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
556         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
557         // Load the plug-in DB allowing plug-ins to install types.
558         [WebPluginDatabase installedPlugins];
559             
560         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
561         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
562         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
563     }
564     
565     if (viewClass && repClass) {
566         // Special-case WebHTMLView for text types that shouldn't be shown.
567         if (viewClass == [WebHTMLView class] &&
568             repClass == [WebHTMLRepresentation class] &&
569             [[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType]) {
570             return NO;
571         }
572         if (vClass)
573             *vClass = viewClass;
574         if (rClass)
575             *rClass = repClass;
576         return YES;
577     }
578     
579     return NO;
580 }
581
582 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
583 {
584     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType])
585         return YES;
586
587     if (_private->pluginDatabase) {
588         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
589         if (pluginPackage) {
590             if (vClass)
591                 *vClass = [WebHTMLView class];
592             if (rClass)
593                 *rClass = [WebHTMLRepresentation class];
594             return YES;
595         }
596     }
597     
598     return NO;
599 }
600
601 + (void)_setAlwaysUseATSU:(BOOL)f
602 {
603     WebCoreSetAlwaysUseATSU(f);
604 }
605
606 + (BOOL)canShowFile:(NSString *)path
607 {
608     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
609 }
610
611 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
612 {
613     return WKGetPreferredExtensionForMIMEType(type);
614 }
615
616 - (void)_close
617 {
618     if (!_private || _private->closed)
619         return;
620     _private->closed = YES;
621
622     [self _removeFromAllWebViewsSet];
623
624     [self setGroupName:nil];
625     [self setHostWindow:nil];
626     [self setDownloadDelegate:nil];
627     [self setEditingDelegate:nil];
628     [self setFrameLoadDelegate:nil];
629     [self setPolicyDelegate:nil];
630     [self setResourceLoadDelegate:nil];
631     [self setScriptDebugDelegate:nil];
632     [self setUIDelegate:nil];
633
634     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
635     [self removeDragCaret];
636
637     FrameLoader* mainFrameLoader = [[self mainFrame] _frameLoader];
638     if (mainFrameLoader)
639         mainFrameLoader->detachFromParent();
640     [_private->_pageBridge close];
641     [_private->_pageBridge release];
642     _private->_pageBridge = nil;
643
644     // Clear the page cache so we call destroy on all the plug-ins in the page cache to break any retain cycles.
645     // See comment in [WebHistoryItem _releaseAllPendingPageCaches] for more information.
646     if (_private->backForwardList) {
647         [_private->backForwardList _close];
648         [_private->backForwardList release];
649         _private->backForwardList = nil;
650     }
651
652     if (_private->hasSpellCheckerDocumentTag) {
653         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
654         _private->hasSpellCheckerDocumentTag = NO;
655     }
656
657     if (_private->pluginDatabase) {
658         [_private->pluginDatabase close];
659         [_private->pluginDatabase release];
660         _private->pluginDatabase = nil;
661     }
662
663     [[NSNotificationCenter defaultCenter] removeObserver:self];
664
665     [WebPreferences _removeReferenceForIdentifier: [self preferencesIdentifier]];
666 }
667
668 + (NSString *)_MIMETypeForFile:(NSString *)path
669 {
670     NSString *extension = [path pathExtension];
671     NSString *MIMEType = nil;
672
673     // Get the MIME type from the extension.
674     if ([extension length] != 0) {
675         MIMEType = WKGetMIMETypeForExtension(extension);
676     }
677
678     // If we can't get a known MIME type from the extension, sniff.
679     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
680         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
681         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
682         [handle closeFile];
683         if ([data length] != 0) {
684             MIMEType = [data _webkit_guessedMIMEType];
685         }
686         if ([MIMEType length] == 0) {
687             MIMEType = @"application/octet-stream";
688         }
689     }
690
691     return MIMEType;
692 }
693
694 - (void)_downloadURL:(NSURL *)URL
695 {
696     ASSERT(URL);
697     
698     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
699     [WebDownload _downloadWithRequest:request
700                              delegate:_private->downloadDelegate
701                             directory:nil];
702     [request release];
703 }
704
705 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
706 {
707     id wd = [self UIDelegate];
708     WebView *newWindowWebView = nil;
709     if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
710         newWindowWebView = [wd webView:self createWebViewWithRequest:request];
711     else {
712         newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
713     }
714
715     [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
716
717     return newWindowWebView;
718 }
719
720 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
721 {
722     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
723           webView:self contextMenuItemsForElement:element defaultMenuItems:items];
724     NSArray *menuItems = defaultMenuItems;
725     NSMenu *menu = nil;
726     unsigned i;
727
728     DOMNode* node = [element objectForKey:WebElementDOMNodeKey];
729     BOOL elementIsTextField = [node isKindOfClass:[DOMHTMLInputElement class]] && [(DOMHTMLInputElement*)node _isTextField];
730     BOOL elementIsTextArea = [node isKindOfClass:[DOMHTMLTextAreaElement class]];
731     if (_private->UIDelegate && !elementIsTextField && !elementIsTextArea) {
732         id cd = _private->UIDelegate;
733         
734         if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)]) {
735             menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
736
737             // Versions of Mail compiled with older WebKits will end up without three context menu items, though
738             // with the separators between them. Here we check for that problem and reinsert the three missing
739             // items. This shouldn't affect any clients other than Mail since the tags for the three items
740             // were not public API. We can remove this code when we no longer support previously-built versions
741             // of Mail on Tiger. See 4498606 for more details.
742             if ([menuItems count] && ([[defaultMenuItems objectAtIndex:0] tag] == WebMenuItemTagSearchInSpotlight) && ([[menuItems objectAtIndex:0] isSeparatorItem])) {
743                 ASSERT([[menuItems objectAtIndex:1] isSeparatorItem]);
744                 ASSERT([[defaultMenuItems objectAtIndex:1] tag] == WebMenuItemTagSearchWeb);
745                 ASSERT([[defaultMenuItems objectAtIndex:2] isSeparatorItem]);
746                 ASSERT([[defaultMenuItems objectAtIndex:3] tag] == WebMenuItemTagLookUpInDictionary);
747                 ASSERT([[defaultMenuItems objectAtIndex:4] isSeparatorItem]);
748                 NSMutableArray *mutableMenuItems = [NSMutableArray arrayWithArray:menuItems];
749                 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:0] atIndex:0];
750                 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:1] atIndex:1];
751                 [mutableMenuItems insertObject:[defaultMenuItems objectAtIndex:3] atIndex:3];
752                 menuItems = mutableMenuItems;
753             }
754         }
755     } 
756
757     if (menuItems && [menuItems count] > 0) {
758         menu = [[[NSMenu alloc] init] autorelease];
759
760         for (i=0; i<[menuItems count]; i++) {
761             [menu addItem:[menuItems objectAtIndex:i]];
762         }
763     }
764
765     // optionally add the Inspect Element menu item it if preference is set or in debug builds
766     // and only showing the menu item if we are working with a WebHTMLView
767     WebFrame *webFrame = [element objectForKey:WebElementFrameKey];
768     if ([WebView _developerExtrasEnabled] && [[[webFrame frameView] documentView] isKindOfClass:[WebHTMLView class]]) {
769         if (!menu)
770             menu = [[[NSMenu alloc] init] autorelease];
771         else if ([menu numberOfItems])
772             [menu addItem:[NSMenuItem separatorItem]];
773         NSMenuItem *menuItem = [[[NSMenuItem alloc] init] autorelease];
774         [menuItem setAction:@selector(_inspectElement:)];
775         [menuItem setTitle:UI_STRING("Inspect Element", "Inspect Element context menu item")];
776         [menuItem setRepresentedObject:element];
777         [menu addItem:menuItem];
778     }
779
780     return menu;
781 }
782
783 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(WebNSUInteger)modifierFlags
784 {
785     // When the mouse isn't over this view at all, we'll get called with a dictionary of nil over
786     // and over again. So it's a good idea to catch that here and not send multiple calls to the delegate
787     // for that case.
788     
789     if (dictionary && _private->lastElementWasNonNil) {
790         [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
791     }
792     _private->lastElementWasNonNil = dictionary != nil;
793 }
794
795 - (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
796 {
797     // We never go back/forward on a per-frame basis, so the target must be the main frame
798     //ASSERT([item target] == nil || [self _findFrameNamed:[item target]] == [self mainFrame]);
799
800     // abort any current load if we're going back/forward
801     [[self mainFrame] stopLoading];
802     [[self mainFrame] _goToItem:item withLoadType:(FrameLoadType)type];
803 }
804
805 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
806 {
807     // It turns out the right combination of behavior is done with the back/forward load
808     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
809     // in the back forward list, and go to the current one.
810
811     WebBackForwardList *bfList = [self backForwardList];
812     ASSERT(![bfList currentItem]); // destination list should be empty
813
814     WebBackForwardList *otherBFList = [otherView backForwardList];
815     if (![otherBFList currentItem]) {
816         return; // empty back forward list, bail
817     }
818
819     WebHistoryItem *newItemToGoTo = nil;
820     int lastItemIndex = [otherBFList forwardListCount];
821     int i;
822     for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
823         if (i == 0) {
824             // If this item is showing , save away its current scroll and form state,
825             // since that might have changed since loading and it is normally not saved
826             // until we leave that page.
827             [[otherView mainFrame] _saveDocumentAndScrollState];
828         }
829         WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
830         [bfList addItem:newItem];
831         if (i == 0) {
832             newItemToGoTo = newItem;
833         }
834     }
835     
836     [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
837 }
838
839 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
840 {
841     _private->formDelegate = delegate;
842 }
843
844 - (id<WebFormDelegate>)_formDelegate
845 {
846     return _private->formDelegate;
847 }
848
849 - (WebCoreSettings *)_settings
850 {
851     return _private->settings;
852 }
853
854 - (void)_updateWebCoreSettingsFromPreferences:(WebPreferences *)preferences
855 {
856     [_private->settings setCursiveFontFamily:[preferences cursiveFontFamily]];
857     [_private->settings setDefaultFixedFontSize:[preferences defaultFixedFontSize]];
858     [_private->settings setDefaultFontSize:[preferences defaultFontSize]];
859     [_private->settings setDefaultTextEncoding:[preferences defaultTextEncodingName]];
860     [_private->settings setFantasyFontFamily:[preferences fantasyFontFamily]];
861     [_private->settings setFixedFontFamily:[preferences fixedFontFamily]];
862     [_private->settings setJavaEnabled:[preferences isJavaEnabled]];
863     [_private->settings setJavaScriptEnabled:[preferences isJavaScriptEnabled]];
864     [_private->settings setJavaScriptCanOpenWindowsAutomatically:[preferences javaScriptCanOpenWindowsAutomatically]];
865     [_private->settings setMinimumFontSize:[preferences minimumFontSize]];
866     [_private->settings setMinimumLogicalFontSize:[preferences minimumLogicalFontSize]];
867     [_private->settings setPluginsEnabled:[preferences arePlugInsEnabled]];
868     [_private->settings setPrivateBrowsingEnabled:[preferences privateBrowsingEnabled]];
869     [_private->settings setSansSerifFontFamily:[preferences sansSerifFontFamily]];
870     [_private->settings setSerifFontFamily:[preferences serifFontFamily]];
871     [_private->settings setStandardFontFamily:[preferences standardFontFamily]];
872     [_private->settings setWillLoadImagesAutomatically:[preferences loadsImagesAutomatically]];
873
874     if ([preferences userStyleSheetEnabled]) {
875         [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
876     } else {
877         [_private->settings setUserStyleSheetLocation:@""];
878     }
879     [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
880     [_private->settings setTextAreasAreResizable:[preferences textAreasAreResizable]];
881     [_private->settings setEditableLinkBehavior:[preferences editableLinkBehavior]];
882 }
883
884 - (void)_preferencesChangedNotification: (NSNotification *)notification
885 {
886     WebPreferences *preferences = (WebPreferences *)[notification object];
887     
888     ASSERT(preferences == [self preferences]);
889     if (!_private->userAgentOverridden) {
890         [_private->userAgent release];
891         _private->userAgent = nil;
892     }
893     [self _updateWebCoreSettingsFromPreferences: preferences];
894 }
895
896 - _frameLoadDelegateForwarder
897 {
898     if (!_private->frameLoadDelegateForwarder)
899         _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate]  defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
900     return _private->frameLoadDelegateForwarder;
901 }
902
903 - _resourceLoadDelegateForwarder
904 {
905     if (!_private->resourceProgressDelegateForwarder)
906         _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
907     return _private->resourceProgressDelegateForwarder;
908 }
909
910 - (void)_cacheResourceLoadDelegateImplementations
911 {
912     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
913     id delegate = [self resourceLoadDelegate];
914     Class delegateClass = [delegate class];
915
916     cache->delegateImplementsDidCancelAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:)];
917     cache->delegateImplementsDidReceiveAuthenticationChallenge = [delegate respondsToSelector:@selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:)];
918     cache->delegateImplementsDidFinishLoadingFromDataSource = [delegate respondsToSelector:@selector(webView:resource:didFinishLoadingFromDataSource:)];
919     cache->delegateImplementsDidReceiveContentLength = [delegate respondsToSelector:@selector(webView:resource:didReceiveContentLength:fromDataSource:)];
920     cache->delegateImplementsDidReceiveResponse = [delegate respondsToSelector:@selector(webView:resource:didReceiveResponse:fromDataSource:)];
921     cache->delegateImplementsWillSendRequest = [delegate respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)];
922     cache->delegateImplementsIdentifierForRequest = [delegate respondsToSelector:@selector(webView:identifierForInitialRequest:fromDataSource:)];
923     cache->delegateImplementsDidLoadResourceFromMemoryCache = [delegate respondsToSelector:@selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:)];
924
925     if (cache->delegateImplementsDidCancelAuthenticationChallenge)
926         cache->didCancelAuthenticationChallengeFunc = (WebDidCancelAuthenticationChallengeFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:))->method_imp;
927     if (cache->delegateImplementsDidReceiveAuthenticationChallenge)
928         cache->didReceiveAuthenticationChallengeFunc = (WebDidReceiveAuthenticationChallengeFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:))->method_imp;
929     if (cache->delegateImplementsDidFinishLoadingFromDataSource)
930         cache->didFinishLoadingFromDataSourceFunc = (WebDidFinishLoadingFromDataSourceFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:didFinishLoadingFromDataSource:))->method_imp;
931     if (cache->delegateImplementsDidReceiveContentLength)
932         cache->didReceiveContentLengthFunc = (WebDidReceiveContentLengthFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:didReceiveContentLength:fromDataSource:))->method_imp;
933     if (cache->delegateImplementsDidReceiveResponse)
934         cache->didReceiveResponseFunc = (WebDidReceiveResponseFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:didReceiveResponse:fromDataSource:))->method_imp;
935     if (cache->delegateImplementsWillSendRequest)
936         cache->willSendRequestFunc = (WebWillSendRequestFunc)class_getInstanceMethod(delegateClass, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:))->method_imp;
937     if (cache->delegateImplementsIdentifierForRequest)
938         cache->identifierForRequestFunc = (WebIdentifierForRequestFunc)class_getInstanceMethod(delegateClass, @selector(webView:identifierForInitialRequest:fromDataSource:))->method_imp;
939     if (cache->delegateImplementsDidLoadResourceFromMemoryCache)
940         cache->didLoadResourceFromMemoryCacheFunc = (WebDidLoadResourceFromMemoryCacheFunc)class_getInstanceMethod(delegateClass, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:))->method_imp;
941 }
942
943 id WebViewGetResourceLoadDelegate(WebView *webView)
944 {
945     return webView->_private->resourceProgressDelegate;
946 }
947
948 WebResourceDelegateImplementationCache WebViewGetResourceLoadDelegateImplementations(WebView *webView)
949 {
950     return webView->_private->resourceLoadDelegateImplementations;
951 }
952
953 - _policyDelegateForwarder
954 {
955     if (!_private->policyDelegateForwarder)
956         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
957     return _private->policyDelegateForwarder;
958 }
959
960 - _UIDelegateForwarder
961 {
962     if (!_private->UIDelegateForwarder)
963         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
964     return _private->UIDelegateForwarder;
965 }
966
967 - _editingDelegateForwarder
968 {
969     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
970     // Not sure if that is a bug or not.
971     if (!_private)
972         return nil;
973     if (!_private->editingDelegateForwarder)
974         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self editingDelegate] defaultTarget: [WebDefaultEditingDelegate sharedEditingDelegate] templateClass: [WebDefaultEditingDelegate class]];
975     return _private->editingDelegateForwarder;
976 }
977
978 - _scriptDebugDelegateForwarder
979 {
980     if (!_private->scriptDebugDelegateForwarder)
981         _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self scriptDebugDelegate] defaultTarget: [WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] templateClass: [WebDefaultScriptDebugDelegate class]];
982     return _private->scriptDebugDelegateForwarder;
983 }
984
985 - (void)_closeWindow
986 {
987     [[self _UIDelegateForwarder] webViewClose:self];
988 }
989
990 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
991 {
992     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
993     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
994 }
995
996 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
997 {
998     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
999     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1000
1001     // This is used to make _representationExistsForURLScheme faster.
1002     // Without this set, we'd have to create the MIME type each time.
1003     if (schemesWithRepresentationsSet == nil) {
1004         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1005     }
1006     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1007 }
1008
1009 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1010 {
1011     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1012 }
1013
1014 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1015 {
1016     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1017 }
1018
1019 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1020 {
1021     if ([NSURLConnection canHandleRequest:request]) {
1022         return YES;
1023     }
1024     
1025     // We're always willing to load alternate content for unreachable URLs
1026     if ([request _webDataRequestUnreachableURL]) {
1027         return YES;
1028     }
1029
1030     return [self _representationExistsForURLScheme:[[request URL] scheme]];
1031 }
1032
1033 + (NSString *)_decodeData:(NSData *)data
1034 {
1035     return [WebCoreEncodings decodeData:data];
1036 }
1037
1038 - (void)_pushPerformingProgrammaticFocus
1039 {
1040     _private->programmaticFocusCount++;
1041 }
1042
1043 - (void)_popPerformingProgrammaticFocus
1044 {
1045     _private->programmaticFocusCount--;
1046 }
1047
1048 - (BOOL)_isPerformingProgrammaticFocus
1049 {
1050     return _private->programmaticFocusCount != 0;
1051 }
1052
1053 #define UnknownTotalBytes -1
1054 #define WebProgressItemDefaultEstimatedLength 1024*16
1055
1056 - (void)_didChangeValueForKey: (NSString *)key
1057 {
1058     LOG (Bindings, "calling didChangeValueForKey: %@", key);
1059     [self didChangeValueForKey: key];
1060 }
1061
1062 - (void)_willChangeValueForKey: (NSString *)key
1063 {
1064     LOG (Bindings, "calling willChangeValueForKey: %@", key);
1065     [self willChangeValueForKey: key];
1066 }
1067
1068 // Always start progress at INITIAL_PROGRESS_VALUE. This helps provide feedback as 
1069 // soon as a load starts.
1070 #define INITIAL_PROGRESS_VALUE 0.1
1071 // Similarly, always leave space at the end. This helps show the user that we're not done
1072 // until we're done.
1073 #define FINAL_PROGRESS_VALUE 1.0 - INITIAL_PROGRESS_VALUE
1074
1075 - (void)_resetProgress
1076 {
1077     [_private->progressItems release];
1078     _private->progressItems = nil;
1079     _private->totalPageAndResourceBytesToLoad = 0;
1080     _private->totalBytesReceived = 0;
1081     _private->progressValue = 0;
1082     _private->lastNotifiedProgressValue = 0;
1083     _private->lastNotifiedProgressTime = 0;
1084     _private->finalProgressChangedSent = NO;
1085     _private->numProgressTrackedFrames = 0;
1086     [_private->originatingProgressFrame release];
1087     _private->originatingProgressFrame = nil;
1088 }
1089 - (void)_progressStarted:(WebFrame *)frame
1090 {
1091     LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1092     [self _willChangeValueForKey: @"estimatedProgress"];
1093     if (_private->numProgressTrackedFrames == 0 || _private->originatingProgressFrame == frame){
1094         [self _resetProgress];
1095         _private->progressValue = INITIAL_PROGRESS_VALUE;
1096         _private->originatingProgressFrame = [frame retain];
1097         [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressStartedNotification object:self];
1098     }
1099     _private->numProgressTrackedFrames++;
1100     [self _didChangeValueForKey: @"estimatedProgress"];
1101 }
1102
1103 - (void)_finalProgressComplete
1104 {
1105     LOG (Progress, "");
1106
1107     // Before resetting progress value be sure to send client a least one notification
1108     // with final progress value.
1109     if (!_private->finalProgressChangedSent) {
1110         _private->progressValue = 1;
1111         [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1112     }
1113     
1114     [self _resetProgress];
1115     
1116     [self setMainFrameDocumentReady:YES];   // make sure this is turned on at this point
1117     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
1118 }
1119
1120 - (void)_progressCompleted:(WebFrame *)frame
1121 {    
1122     LOG (Progress, "frame %p(%@), _private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", frame, [frame name], _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1123
1124     if (_private->numProgressTrackedFrames <= 0)
1125         return;
1126
1127     [self _willChangeValueForKey: @"estimatedProgress"];
1128
1129     _private->numProgressTrackedFrames--;
1130     if (_private->numProgressTrackedFrames == 0 ||
1131         (frame == _private->originatingProgressFrame && _private->numProgressTrackedFrames != 0)){
1132         [self _finalProgressComplete];
1133     }
1134     [self _didChangeValueForKey: @"estimatedProgress"];
1135 }
1136
1137 - (void)_incrementProgressForIdentifier:(id)identifier response:(NSURLResponse *)response;
1138 {
1139     if (!identifier)
1140         return;
1141
1142     LOG (Progress, "_private->numProgressTrackedFrames %d, _private->originatingProgressFrame %p", _private->numProgressTrackedFrames, _private->originatingProgressFrame);
1143     
1144     if (_private->numProgressTrackedFrames <= 0)
1145         return;
1146         
1147     WebProgressItem *item = [[WebProgressItem alloc] init];
1148
1149     if (!item)
1150         return;
1151
1152     long long length = [response expectedContentLength];
1153     if (length < 0){
1154         length = WebProgressItemDefaultEstimatedLength;
1155     }
1156     item->estimatedLength = length;
1157     _private->totalPageAndResourceBytesToLoad += length;
1158     
1159     if (!_private->progressItems)
1160         _private->progressItems = [[NSMutableDictionary alloc] init];
1161         
1162     [_private->progressItems _webkit_setObject:item forUncopiedKey:identifier];
1163     [item release];
1164 }
1165
1166 - (void)_incrementProgressForIdentifier:(id)identifier data:(NSData *)data
1167 {
1168     if (!identifier)
1169         return;
1170
1171     WebProgressItem *item = [_private->progressItems objectForKey:identifier];
1172
1173     if (!item)
1174         return;
1175
1176     [self _willChangeValueForKey: @"estimatedProgress"];
1177
1178     unsigned bytesReceived = [data length];
1179     double increment, percentOfRemainingBytes;
1180     long long remainingBytes, estimatedBytesForPendingRequests;
1181
1182     item->bytesReceived += bytesReceived;
1183     if (item->bytesReceived > item->estimatedLength){
1184         _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
1185         item->estimatedLength = item->bytesReceived*2;
1186     }
1187     
1188     int numPendingOrLoadingRequests = [_private->originatingProgressFrame _numPendingOrLoadingRequests:YES];
1189     estimatedBytesForPendingRequests = WebProgressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
1190     remainingBytes = ((_private->totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - _private->totalBytesReceived);
1191     percentOfRemainingBytes = (double)bytesReceived / (double)remainingBytes;
1192
1193     // Treat the first layout as the half-way point.
1194     double maxProgressValue = [_private->originatingProgressFrame _firstLayoutDone]
1195         ? FINAL_PROGRESS_VALUE
1196         : .5;
1197     increment = (maxProgressValue - _private->progressValue) * percentOfRemainingBytes;
1198     _private->progressValue += increment;
1199     if (_private->progressValue > maxProgressValue)
1200         _private->progressValue = maxProgressValue;
1201     ASSERT(_private->progressValue >= INITIAL_PROGRESS_VALUE);
1202
1203     _private->totalBytesReceived += bytesReceived;
1204
1205     double now = CFAbsoluteTimeGetCurrent();
1206     double notifiedProgressTimeDelta = now - _private->lastNotifiedProgressTime;
1207     
1208     LOG (Progress, "_private->progressValue %g, _private->numProgressTrackedFrames %d", _private->progressValue, _private->numProgressTrackedFrames);
1209     double notificationProgressDelta = _private->progressValue - _private->lastNotifiedProgressValue;
1210     if ((notificationProgressDelta >= _private->progressNotificationInterval ||
1211             notifiedProgressTimeDelta >= _private->progressNotificationTimeInterval) &&
1212             _private->numProgressTrackedFrames > 0) {
1213         if (!_private->finalProgressChangedSent) {
1214             if (_private->progressValue == 1)
1215                 _private->finalProgressChangedSent = YES;
1216             [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
1217             _private->lastNotifiedProgressValue = _private->progressValue;
1218             _private->lastNotifiedProgressTime = now;
1219         }
1220     }
1221
1222     [self _didChangeValueForKey: @"estimatedProgress"];
1223 }
1224
1225 - (void)_completeProgressForIdentifier:(id)identifier
1226 {
1227     WebProgressItem *item = [_private->progressItems objectForKey:identifier];
1228
1229     if (!item)
1230         return;
1231         
1232     // Adjust the total expected bytes to account for any overage/underage.
1233     long long delta = item->bytesReceived - item->estimatedLength;
1234     _private->totalPageAndResourceBytesToLoad += delta;
1235     item->estimatedLength = item->bytesReceived;
1236 }
1237
1238 // Required to prevent automatic observer notifications.
1239 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1240     return NO;
1241 }
1242
1243 - (NSArray *)_declaredKeys {
1244     static NSArray *declaredKeys = nil;
1245     
1246     if (!declaredKeys) {
1247         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1248     }
1249
1250     return declaredKeys;
1251 }
1252
1253 - (void)setObservationInfo:(void *)info
1254 {
1255     _private->observationInfo = info;
1256 }
1257
1258 - (void *)observationInfo
1259 {
1260     return _private->observationInfo;
1261 }
1262
1263 - (void)_willChangeBackForwardKeys
1264 {
1265     [self _willChangeValueForKey: _WebCanGoBackKey];
1266     [self _willChangeValueForKey: _WebCanGoForwardKey];
1267 }
1268
1269 - (void)_didChangeBackForwardKeys
1270 {
1271     [self _didChangeValueForKey: _WebCanGoBackKey];
1272     [self _didChangeValueForKey: _WebCanGoForwardKey];
1273 }
1274
1275 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1276 {
1277     [self _willChangeBackForwardKeys];
1278     if (frame == [self mainFrame]){
1279         // Force an observer update by sending a will/did.
1280         [self _willChangeValueForKey: _WebIsLoadingKey];
1281         [self _didChangeValueForKey: _WebIsLoadingKey];
1282
1283         [self _willChangeValueForKey: _WebMainFrameURLKey];
1284     }
1285     [NSApp setWindowsNeedUpdate:YES];
1286 }
1287
1288 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1289 {
1290     if (frame == [self mainFrame]){
1291         [self _didChangeValueForKey: _WebMainFrameURLKey];
1292     }
1293     [NSApp setWindowsNeedUpdate:YES];
1294 }
1295
1296 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1297 {
1298     [self _didChangeBackForwardKeys];
1299     if (frame == [self mainFrame]){
1300         // Force an observer update by sending a will/did.
1301         [self _willChangeValueForKey: _WebIsLoadingKey];
1302         [self _didChangeValueForKey: _WebIsLoadingKey];
1303     }
1304     [NSApp setWindowsNeedUpdate:YES];
1305 }
1306
1307 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1308 {
1309     [self _didChangeBackForwardKeys];
1310     if (frame == [self mainFrame]){
1311         // Force an observer update by sending a will/did.
1312         [self _willChangeValueForKey: _WebIsLoadingKey];
1313         [self _didChangeValueForKey: _WebIsLoadingKey];
1314     }
1315     [NSApp setWindowsNeedUpdate:YES];
1316 }
1317
1318 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1319 {
1320     [self _didChangeBackForwardKeys];
1321     if (frame == [self mainFrame]){
1322         // Force an observer update by sending a will/did.
1323         [self _willChangeValueForKey: _WebIsLoadingKey];
1324         [self _didChangeValueForKey: _WebIsLoadingKey];
1325         
1326         [self _didChangeValueForKey: _WebMainFrameURLKey];
1327     }
1328     [NSApp setWindowsNeedUpdate:YES];
1329 }
1330
1331 - (void)_reloadForPluginChanges
1332 {
1333     [[self mainFrame] _reloadForPluginChanges];
1334 }
1335
1336 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1337 {
1338     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1339     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1340     NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1341     [request release];
1342     return cachedResponse;
1343 }
1344
1345 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1346 {
1347     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1348     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1349     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1350                         element:domElement
1351                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1352                           title:[element objectForKey:WebElementImageAltStringKey] 
1353                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1354                           types:types];
1355 }
1356
1357 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1358 {
1359     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1360                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1361                         types:types];
1362 }
1363
1364 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1365 {
1366     _private->initiatedDrag = initiatedDrag;
1367 }
1368
1369 #define DASHBOARD_CONTROL_LABEL @"control"
1370
1371 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1372 {
1373     // Add scroller regions for NSScroller and KWQScrollBar
1374     int i, count = [views count];
1375     
1376     for (i = 0; i < count; i++) {
1377         NSView *aView = [views objectAtIndex:i];
1378         
1379         if ([aView isKindOfClass:[NSScroller class]] ||
1380             [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1381             NSRect bounds = [aView bounds];
1382             NSRect adjustedBounds;
1383             adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1384             adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1385             
1386             // AppKit has horrible hack of placing absent scrollers at -100,-100
1387             if (adjustedBounds.origin.y == -100)
1388                 continue;
1389             adjustedBounds.size = bounds.size;
1390             NSRect clip = [aView visibleRect];
1391             NSRect adjustedClip;
1392             adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1393             adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1394             adjustedClip.size = clip.size;
1395             WebDashboardRegion *aRegion = 
1396                         [[[WebDashboardRegion alloc] initWithRect:adjustedBounds 
1397                                     clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1398             NSMutableArray *scrollerRegions;
1399             scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1400             if (!scrollerRegions) {
1401                 scrollerRegions = [NSMutableArray array];
1402                 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1403             }
1404             [scrollerRegions addObject:aRegion];
1405         }
1406         [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1407     }
1408 }
1409
1410 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1411 {
1412     [self _addScrollerDashboardRegions:regions from:[self subviews]];
1413 }
1414
1415 - (NSDictionary *)_dashboardRegions
1416 {
1417     // Only return regions from main frame.
1418     FrameMac* mainFrame = [[[self mainFrame] _bridge] _frame];
1419     if (!mainFrame)
1420         return nil;
1421     NSMutableDictionary *regions = mainFrame->dashboardRegionsDictionary();
1422     [self _addScrollerDashboardRegions:regions];
1423     return regions;
1424 }
1425
1426 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag;
1427 {
1428     switch (behavior) {
1429         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1430             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1431             break;
1432         }
1433         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1434             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1435             break;
1436         }
1437         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1438             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1439             break;
1440         }
1441         case WebDashboardBehaviorAllowWheelScrolling: {
1442             _private->dashboardBehaviorAllowWheelScrolling = flag;
1443             break;
1444         }
1445     }
1446 }
1447
1448 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1449 {
1450     switch (behavior) {
1451         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1452             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1453         }
1454         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1455             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1456         }
1457         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1458             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1459         }
1460         case WebDashboardBehaviorAllowWheelScrolling: {
1461             return _private->dashboardBehaviorAllowWheelScrolling;
1462         }
1463     }
1464     return NO;
1465 }
1466
1467 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource
1468 {
1469     [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:self resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:dataSource];
1470 }
1471
1472 + (void)_setShouldUseFontSmoothing:(BOOL)f
1473 {
1474     WebCoreSetShouldUseFontSmoothing(f);
1475 }
1476
1477 + (BOOL)_shouldUseFontSmoothing
1478 {
1479     return WebCoreShouldUseFontSmoothing();
1480 }
1481
1482 + (NSString *)_minimumRequiredSafariBuildNumber
1483 {
1484     return @"420+";
1485 }
1486
1487 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1488 {
1489     WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1490     if (flag) {
1491         [scrollview setVerticalScrollingMode:WebCoreScrollbarAlwaysOn];
1492         [scrollview setVerticalScrollingModeLocked:YES];
1493     } else {
1494         [scrollview setVerticalScrollingModeLocked:NO];
1495         [scrollview setVerticalScrollingMode:WebCoreScrollbarAuto];
1496     }
1497 }
1498
1499 - (BOOL)alwaysShowVerticalScroller
1500 {
1501     WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1502     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == WebCoreScrollbarAlwaysOn;
1503 }
1504
1505 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1506 {
1507     WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1508     if (flag) {
1509         [scrollview setHorizontalScrollingMode:WebCoreScrollbarAlwaysOn];
1510         [scrollview setHorizontalScrollingModeLocked:YES];
1511     } else {
1512         [scrollview setHorizontalScrollingModeLocked:NO];
1513         [scrollview setHorizontalScrollingMode:WebCoreScrollbarAuto];
1514     }
1515 }
1516
1517 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1518 {
1519     FrameMac* mainFrame = [[[self mainFrame] _bridge] _frame];
1520     if (mainFrame)
1521         mainFrame->setProhibitsScrolling(prohibits);
1522 }
1523
1524 - (BOOL)alwaysShowHorizontalScroller
1525 {
1526     WebDynamicScrollBarsView *scrollview = (WebDynamicScrollBarsView *)[[[self mainFrame] frameView] _scrollView];
1527     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == WebCoreScrollbarAlwaysOn;
1528 }
1529
1530 - (void)_setInViewSourceMode:(BOOL)flag
1531 {
1532     FrameMac* mainFrame = [[[self mainFrame] _bridge] _frame];
1533     if (mainFrame)
1534         mainFrame->setInViewSourceMode(flag);
1535 }
1536
1537 - (BOOL)_inViewSourceMode
1538 {
1539     FrameMac* mainFrame = [[[self mainFrame] _bridge] _frame];
1540     return mainFrame && mainFrame->inViewSourceMode();
1541 }
1542
1543 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1544 {
1545     if (!_private->pluginDatabase)
1546         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1547         
1548     [_private->pluginDatabase setPlugInPaths:newPaths];
1549     [_private->pluginDatabase refresh];
1550 }
1551
1552 - (void)_attachScriptDebuggerToAllFrames
1553 {
1554     for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1555         [kit(frame) _attachScriptDebugger];
1556 }
1557
1558 - (void)_detachScriptDebuggerFromAllFrames
1559 {
1560     for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1561         [kit(frame) _detachScriptDebugger];
1562 }
1563
1564 - (void)setBackgroundColor:(NSColor *)backgroundColor
1565 {
1566     if ([_private->backgroundColor isEqual:backgroundColor])
1567         return;
1568
1569     id old = _private->backgroundColor;
1570     _private->backgroundColor = [backgroundColor retain];
1571     [old release];
1572
1573     [[self mainFrame] _updateBackground];
1574 }
1575
1576 - (NSColor *)backgroundColor
1577 {
1578     return _private->backgroundColor;
1579 }
1580
1581 - (BOOL)defersCallbacks
1582 {
1583     return [_private->_pageBridge impl]->defersLoading();
1584 }
1585
1586 - (void)setDefersCallbacks:(BOOL)defer
1587 {
1588     return [_private->_pageBridge impl]->setDefersLoading(defer);
1589 }
1590
1591 @end
1592
1593 @implementation _WebSafeForwarder
1594
1595 - initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
1596 {
1597     self = [super init];
1598     if (!self)
1599         return nil;
1600     
1601     target = t; // Non retained.
1602     defaultTarget = dt;
1603     templateClass = aClass;
1604     return self;
1605 }
1606
1607 // Used to send messages to delegates that implement informal protocols.
1608 + safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
1609 {
1610     return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
1611 }
1612
1613 #ifndef NDEBUG
1614 NSMutableDictionary *countInvocations;
1615 #endif
1616
1617 - (void)forwardInvocation:(NSInvocation *)anInvocation
1618 {
1619 #ifndef NDEBUG
1620     if (!countInvocations){
1621         countInvocations = [[NSMutableDictionary alloc] init];
1622     }
1623     NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
1624     if (!count)
1625         count = [NSNumber numberWithInt: 1];
1626     else
1627         count = [NSNumber numberWithInt: [count intValue] + 1];
1628     [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
1629 #endif
1630     if ([target respondsToSelector: [anInvocation selector]])
1631         [anInvocation invokeWithTarget: target];
1632     else if ([defaultTarget respondsToSelector: [anInvocation selector]])
1633         [anInvocation invokeWithTarget: defaultTarget];
1634     // Do nothing quietly if method not implemented.
1635 }
1636
1637 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1638 {
1639     return [templateClass instanceMethodSignatureForSelector: aSelector];
1640 }
1641
1642 @end
1643
1644 @implementation WebView
1645
1646 #if REMOVE_SAFARI_DOM_TREE_DEBUG_ITEM
1647 // this prevents open source users from crashing when using the Show DOM Tree menu item in Safari
1648 // FIXME: remove this when it is no longer needed to prevent Safari from crashing
1649 +(void)initialize
1650 {
1651     static BOOL tooLate = NO;
1652     if (!tooLate) {
1653         if ([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"IncludeDebugMenu"])
1654             [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_finishedLaunching) name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1655         tooLate = YES;
1656     }
1657 }
1658
1659 +(void)_finishedLaunching
1660 {
1661     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_removeDOMTreeMenuItem:) name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1662     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidFinishLaunchingNotification object:NSApp];
1663 }
1664
1665 +(void)_removeDOMTreeMenuItem:(NSNotification *)notification
1666 {
1667     NSMenu *debugMenu = [[[[NSApp mainMenu] itemArray] lastObject] submenu];
1668     NSMenuItem *domTree = [debugMenu itemWithTitle:@"Show DOM Tree"];
1669     if (domTree)
1670         [debugMenu removeItem:domTree];
1671     [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMenuDidAddItemNotification object:[NSApp mainMenu]];
1672 }
1673 #endif
1674
1675 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1676 {
1677     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1678 }
1679
1680 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
1681 {
1682     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase installedPlugins] pluginForMIMEType:MIMEType];
1683     if (pluginPackage)
1684         return pluginPackage;
1685     
1686     if (_private->pluginDatabase)
1687         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
1688     
1689     return nil;
1690 }
1691
1692 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
1693 {
1694     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase installedPlugins] pluginForExtension:extension];
1695     if (pluginPackage)
1696         return pluginPackage;
1697     
1698     if (_private->pluginDatabase)
1699         return [_private->pluginDatabase pluginForExtension:extension];
1700     
1701     return nil;
1702 }
1703
1704 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
1705 {
1706     if ([[WebPluginDatabase installedPlugins] isMIMETypeRegistered:MIMEType])
1707         return YES;
1708         
1709     if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
1710         return YES;
1711     
1712     return NO;
1713 }
1714
1715 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1716 {
1717     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1718 }
1719
1720 + (NSArray *)MIMETypesShownAsHTML
1721 {
1722     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1723     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1724     id key;
1725     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1726     
1727     while ((key = [enumerator nextObject])) {
1728         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1729             [array addObject:key];
1730     }
1731     
1732     return array;
1733 }
1734
1735 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1736 {
1737     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1738     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1739     id key;
1740     while ((key = [enumerator nextObject])) {
1741         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1742             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1743     }
1744     
1745     int i, count = [MIMETypes count];
1746     for (i = 0; i < count; i++) {
1747         [WebView registerViewClass:[WebHTMLView class] 
1748                 representationClass:[WebHTMLRepresentation class] 
1749                 forMIMEType:[MIMETypes objectAtIndex:i]];
1750     }
1751 }
1752
1753 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1754 {
1755     return [pasteboard _web_bestURL];
1756 }
1757
1758 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1759 {
1760     return [pasteboard stringForType:WebURLNamePboardType];
1761 }
1762
1763 - (void)_registerDraggedTypes
1764 {
1765     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1766     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1767     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1768     [types addObjectsFromArray:URLTypes];
1769     [self registerForDraggedTypes:[types allObjects]];
1770     [types release];
1771 }
1772
1773 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1774 {
1775     _private->mainFrameDocumentReady = NO;
1776     _private->drawsBackground = YES;
1777     _private->smartInsertDeleteEnabled = YES;
1778     _private->backgroundColor = [[NSColor whiteColor] retain];
1779
1780     NSRect f = [self frame];
1781     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1782     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1783     [self addSubview:frameView];
1784     [frameView release];
1785
1786     WebKitInitializeLoggingChannelsIfNecessary();
1787     _private->_pageBridge = [[WebPageBridge alloc] initWithMainFrameName:frameName webView:self frameView:frameView];
1788
1789     [self _addToAllWebViewsSet];
1790     [self setGroupName:groupName];
1791     
1792     // If there's already a next key view (e.g., from a nib), wire it up to our
1793     // contained frame view. In any case, wire our next key view up to the our
1794     // contained frame view. This works together with our becomeFirstResponder 
1795     // and setNextKeyView overrides.
1796     NSView *nextKeyView = [self nextKeyView];
1797     if (nextKeyView != nil && nextKeyView != frameView) {
1798         [frameView setNextKeyView:nextKeyView];
1799     }
1800     [super setNextKeyView:frameView];
1801
1802     ++WebViewCount;
1803
1804     [self _registerDraggedTypes];
1805
1806     // initialize WebScriptDebugServer here so listeners can register before any pages are loaded.
1807     if ([WebView _scriptDebuggerEnabled])
1808         [WebScriptDebugServer sharedScriptDebugServer];
1809
1810     // Update WebCore with preferences.  These values will either come from an archived WebPreferences,
1811     // or from the standard preferences, depending on whether this method was called from initWithCoder:
1812     // or initWithFrame, respectively.
1813     [self _updateWebCoreSettingsFromPreferences: [self preferences]];
1814     
1815     // Register to receive notifications whenever preference values change.
1816     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1817                                                  name:WebPreferencesChangedNotification object:[self preferences]];
1818 }
1819
1820 - (id)initWithFrame:(NSRect)f
1821 {
1822     return [self initWithFrame:f frameName:nil groupName:nil];
1823 }
1824
1825 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1826 {
1827     self = [super initWithFrame:f];
1828     if (!self)
1829         return nil;
1830
1831 #if ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1832     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1833     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1834     // need for Safari to unset it to prevent it from being passed to applications it launches.
1835     // Unsetting it when a WebView is first created is as good a place as any.
1836     // See <http://bugzilla.opendarwin.org/show_bug.cgi?id=4286> for more details.
1837     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1838         unsetenv("DYLD_FRAMEWORK_PATH");
1839         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1840     }
1841 #endif
1842
1843     _private = [[WebViewPrivate alloc] init];
1844     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1845     [self setMaintainsBackForwardList: YES];
1846     return self;
1847 }
1848
1849 - (id)initWithCoder:(NSCoder *)decoder
1850 {
1851     WebView *result = nil;
1852
1853 NS_DURING
1854
1855     NSString *frameName;
1856     NSString *groupName;
1857     WebPreferences *preferences;
1858     BOOL useBackForwardList;
1859
1860     result = [super initWithCoder:decoder];
1861     result->_private = [[WebViewPrivate alloc] init];
1862
1863     // We don't want any of the archived subviews. The subviews will always
1864     // be created in _commonInitializationFrameName:groupName:.
1865     [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1866
1867     if ([decoder allowsKeyedCoding]) {
1868         frameName = [decoder decodeObjectForKey:@"FrameName"];
1869         groupName = [decoder decodeObjectForKey:@"GroupName"];
1870         preferences = [decoder decodeObjectForKey:@"Preferences"];
1871         useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1872     } else {
1873         int version;
1874         [decoder decodeValueOfObjCType:@encode(int) at:&version];
1875         frameName = [decoder decodeObject];
1876         groupName = [decoder decodeObject];
1877         preferences = [decoder decodeObject];
1878         if (version > 1)
1879             [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1880     }
1881
1882     if (![frameName isKindOfClass:[NSString class]])
1883         frameName = nil;
1884     if (![groupName isKindOfClass:[NSString class]])
1885         groupName = nil;
1886     if (![preferences isKindOfClass:[WebPreferences class]])
1887         preferences = nil;
1888
1889     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1890
1891     if (preferences)
1892         [result setPreferences:preferences];
1893     result->_private->useBackForwardList = useBackForwardList;
1894     [result _commonInitializationWithFrameName:frameName groupName:groupName];
1895
1896 NS_HANDLER
1897
1898     result = nil;
1899     [self release];
1900
1901 NS_ENDHANDLER
1902
1903     return result;
1904 }
1905
1906 - (void)encodeWithCoder:(NSCoder *)encoder
1907 {
1908     [super encodeWithCoder:encoder];
1909
1910     if ([encoder allowsKeyedCoding]) {
1911         [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
1912         [encoder encodeObject:[self groupName] forKey:@"GroupName"];
1913         [encoder encodeObject:[self preferences] forKey:@"Preferences"];
1914         [encoder encodeBool:_private->useBackForwardList forKey:@"UseBackForwardList"];
1915     } else {
1916         int version = WebViewVersion;
1917         [encoder encodeValueOfObjCType:@encode(int) at:&version];
1918         [encoder encodeObject:[[self mainFrame] name]];
1919         [encoder encodeObject:[self groupName]];
1920         [encoder encodeObject:[self preferences]];
1921         [encoder encodeValuesOfObjCTypes:"c", &_private->useBackForwardList];
1922     }
1923
1924     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)_private->useBackForwardList);
1925 }
1926
1927 - (void)dealloc
1928 {
1929     // call close to ensure we tear-down completly
1930     // this maintains our old behavior for existing applications
1931     [self _close];
1932
1933     --WebViewCount;
1934     
1935     [_private release];
1936     // [super dealloc] can end up dispatching against _private (3466082)
1937     _private = nil;
1938
1939     [super dealloc];
1940 }
1941
1942 - (void)finalize
1943 {
1944     ASSERT(_private->closed);
1945
1946     --WebViewCount;
1947
1948     [super finalize];
1949 }
1950
1951 - (void)close
1952 {
1953     [self _close];
1954 }
1955
1956 - (void)setShouldCloseWithWindow:(BOOL)close
1957 {
1958     _private->shouldCloseWithWindow = close;
1959 }
1960
1961 - (BOOL)shouldCloseWithWindow
1962 {
1963     return _private->shouldCloseWithWindow;
1964 }
1965
1966 - (void)viewWillMoveToWindow:(NSWindow *)window
1967 {
1968     // Don't do anything if we aren't initialized.  This happens when decoding a WebView.
1969     if (!_private)
1970         return;
1971     
1972     if ([self window])
1973         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
1974
1975     if (window) {
1976         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
1977
1978         // Ensure that we will receive the events that WebHTMLView (at least) needs. It's expensive enough
1979         // that we don't want to call it over and over.
1980         [window setAcceptsMouseMovedEvents:YES];
1981         WKSetNSWindowShouldPostEventNotifications(window, YES);
1982     }
1983 }
1984
1985 - (void)_windowWillClose:(NSNotification *)notification
1986 {
1987     if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
1988         [self _close];
1989 }
1990
1991 - (void)setPreferences:(WebPreferences *)prefs
1992 {
1993     if (_private->preferences != prefs) {
1994         [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
1995         [WebPreferences _removeReferenceForIdentifier:[_private->preferences identifier]];
1996         [_private->preferences release];
1997         _private->preferences = [prefs retain];
1998         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1999             name:WebPreferencesChangedNotification object:[self preferences]];
2000         [[NSNotificationCenter defaultCenter]
2001             postNotificationName:WebPreferencesChangedNotification object:prefs userInfo:nil];
2002     }
2003 }
2004
2005 - (WebPreferences *)preferences
2006 {
2007     return _private->preferences ? _private->preferences : [WebPreferences standardPreferences];
2008 }
2009
2010 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
2011 {
2012     if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
2013         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
2014         [self setPreferences:prefs];
2015         [prefs release];
2016     }
2017 }
2018
2019 - (NSString *)preferencesIdentifier
2020 {
2021     return [[self preferences] identifier];
2022 }
2023
2024
2025 - (void)setUIDelegate:delegate
2026 {
2027     _private->UIDelegate = delegate;
2028     [_private->UIDelegateForwarder release];
2029     _private->UIDelegateForwarder = nil;
2030 }
2031
2032 - UIDelegate
2033 {
2034     return _private->UIDelegate;
2035 }
2036
2037 - (void)setResourceLoadDelegate: delegate
2038 {
2039     _private->resourceProgressDelegate = delegate;
2040     [_private->resourceProgressDelegateForwarder release];
2041     _private->resourceProgressDelegateForwarder = nil;
2042     [self _cacheResourceLoadDelegateImplementations];
2043 }
2044
2045
2046 - resourceLoadDelegate
2047 {
2048     return _private->resourceProgressDelegate;
2049 }
2050
2051 - (void)setDownloadDelegate: delegate
2052 {
2053     _private->downloadDelegate = delegate;
2054 }
2055
2056
2057 - downloadDelegate
2058 {
2059     return _private->downloadDelegate;
2060 }
2061
2062 - (void)setPolicyDelegate:delegate
2063 {
2064     _private->policyDelegate = delegate;
2065     [_private->policyDelegateForwarder release];
2066     _private->policyDelegateForwarder = nil;
2067 }
2068
2069 - policyDelegate
2070 {
2071     return _private->policyDelegate;
2072 }
2073
2074 - (void)setFrameLoadDelegate:delegate
2075 {
2076     _private->frameLoadDelegate = delegate;
2077     [_private->frameLoadDelegateForwarder release];
2078     _private->frameLoadDelegateForwarder = nil;
2079 }
2080
2081 - frameLoadDelegate
2082 {
2083     return _private->frameLoadDelegate;
2084 }
2085
2086 - (WebFrame *)mainFrame
2087 {
2088     // This can be called in initialization, before _private has been set up (3465613)
2089     if (!_private)
2090         return nil;
2091     return [(WebFrameBridge *)[_private->_pageBridge mainFrame] webFrame];
2092 }
2093
2094 - (WebFrame *)selectedFrame
2095 {
2096     // If the first responder is a view in our tree, we get the frame containing the first responder.
2097     // This is faster than searching the frame hierarchy, and will give us a result even in the case
2098     // where the focused frame doesn't actually contain a selection.
2099     WebFrame *focusedFrame = [self _focusedFrame];
2100     if (focusedFrame)
2101         return focusedFrame;
2102     
2103     // If the first responder is outside of our view tree, we search for a frame containing a selection.
2104     // There should be at most only one of these.
2105     return [[self mainFrame] _findFrameWithSelection];
2106     
2107     return nil;
2108 }
2109
2110 - (WebBackForwardList *)backForwardList
2111 {
2112     if (_private->useBackForwardList)
2113         return _private->backForwardList;
2114     return nil;
2115 }
2116
2117 - (void)setMaintainsBackForwardList: (BOOL)flag
2118 {
2119     _private->useBackForwardList = flag;
2120 }
2121
2122 - (BOOL)goBack
2123 {
2124     WebHistoryItem *item = [[self backForwardList] backItem];
2125     
2126     if (item){
2127         [self _goToItem: item withLoadType: WebFrameLoadTypeBack];
2128         return YES;
2129     }
2130     return NO;
2131 }
2132
2133 - (BOOL)goForward
2134 {
2135     WebHistoryItem *item = [[self backForwardList] forwardItem];
2136     
2137     if (item){
2138         [self _goToItem: item withLoadType: WebFrameLoadTypeForward];
2139         return YES;
2140     }
2141     return NO;
2142 }
2143
2144 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
2145 {
2146     [self _goToItem: item withLoadType: WebFrameLoadTypeIndexedBackForward];
2147     return YES;
2148 }
2149
2150 - (void)setTextSizeMultiplier:(float)m
2151 {
2152     // NOTE: This has no visible effect when viewing a PDF (see <rdar://problem/4737380>)
2153     if (_private->textSizeMultiplier == m)
2154         return;
2155
2156     _private->textSizeMultiplier = m;
2157     [self _notifyTextSizeMultiplierChanged];
2158 }
2159
2160 - (float)textSizeMultiplier
2161 {
2162     return _private->textSizeMultiplier;
2163 }
2164
2165 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
2166 {
2167     NSString *name = [applicationName copy];
2168     [_private->applicationNameForUserAgent release];
2169     _private->applicationNameForUserAgent = name;
2170     if (!_private->userAgentOverridden) {
2171         [_private->userAgent release];
2172         _private->userAgent = nil;
2173     }
2174 }
2175
2176 - (NSString *)applicationNameForUserAgent
2177 {
2178     return [[_private->applicationNameForUserAgent retain] autorelease];
2179 }
2180
2181 - (void)setCustomUserAgent:(NSString *)userAgentString
2182 {
2183     NSString *override = [userAgentString copy];
2184     [_private->userAgent release];
2185     _private->userAgent = override;
2186     _private->userAgentOverridden = override != nil;
2187 }
2188
2189 - (NSString *)customUserAgent
2190 {
2191     return _private->userAgentOverridden ? [[_private->userAgent retain] autorelease] : nil;
2192 }
2193
2194 - (void)setMediaStyle:(NSString *)mediaStyle
2195 {
2196     if (_private->mediaStyle != mediaStyle) {
2197         [_private->mediaStyle release];
2198         _private->mediaStyle = [mediaStyle copy];
2199     }
2200 }
2201
2202 - (NSString *)mediaStyle
2203 {
2204     return _private->mediaStyle;
2205 }
2206
2207 - (BOOL)supportsTextEncoding
2208 {
2209     id documentView = [[[self mainFrame] frameView] documentView];
2210     return [documentView conformsToProtocol:@protocol(WebDocumentText)]
2211         && [documentView supportsTextEncoding];
2212 }
2213
2214 - (void)setCustomTextEncodingName:(NSString *)encoding
2215 {
2216     NSString *oldEncoding = [self customTextEncodingName];
2217     if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding])
2218         return;
2219     FrameLoader* mainFrameLoader = [[self mainFrame] _frameLoader];
2220     if (mainFrameLoader)
2221         mainFrameLoader->reloadAllowingStaleData(encoding);
2222 }
2223
2224 - (NSString *)_mainFrameOverrideEncoding
2225 {
2226     WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
2227     if (dataSource == nil)
2228         dataSource = [[self mainFrame] dataSource];
2229     if (dataSource == nil)
2230         return nil;
2231     return [dataSource _documentLoader]->overrideEncoding();
2232 }
2233
2234 - (NSString *)customTextEncodingName
2235 {
2236     return [self _mainFrameOverrideEncoding];
2237 }
2238
2239 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
2240 {
2241     return [[[self mainFrame] _bridge] stringByEvaluatingJavaScriptFromString:script];
2242 }
2243
2244 - (WebScriptObject *)windowScriptObject
2245 {
2246     return core([self mainFrame])->windowScriptObject();
2247 }
2248
2249 // Get the appropriate user-agent string for a particular URL.
2250 // Since we no longer automatically spoof, this no longer requires looking at the URL.
2251 - (NSString *)userAgentForURL:(NSURL *)URL
2252 {
2253     NSString *userAgent = _private->userAgent;
2254     if (userAgent) {
2255         return [[userAgent retain] autorelease];
2256     }
2257     
2258     NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
2259     id sourceVersion = [[NSBundle bundleForClass:[WebView class]]
2260         objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
2261     NSString *applicationName = _private->applicationNameForUserAgent;
2262
2263     if ([applicationName length]) {
2264         userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko) %@",
2265             language, sourceVersion, applicationName];
2266     } else {
2267         userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X; %@) AppleWebKit/%@ (KHTML, like Gecko)",
2268             language, sourceVersion];
2269     }
2270
2271     _private->userAgent = [userAgent retain];
2272     return userAgent;
2273 }
2274
2275 - (void)setHostWindow:(NSWindow *)hostWindow
2276 {
2277     if (!_private->closed && hostWindow != _private->hostWindow) {
2278         [[self mainFrame] _viewWillMoveToHostWindow:hostWindow];
2279         if (_private->hostWindow)
2280             [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
2281         if (hostWindow)
2282             [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
2283         [_private->hostWindow release];
2284         _private->hostWindow = [hostWindow retain];
2285         [[self mainFrame] _viewDidMoveToHostWindow];
2286     }
2287 }
2288
2289 - (NSWindow *)hostWindow
2290 {
2291     return _private->hostWindow;
2292 }
2293
2294 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2295 {
2296     return [[self _frameViewAtWindowPoint:point] documentView];
2297 }
2298
2299 - (NSView <WebDocumentDragging> *)_draggingDocumentViewAtWindowPoint:(NSPoint)point
2300 {
2301     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:point];
2302     if ([documentView conformsToProtocol:@protocol(WebDocumentDragging)]) {
2303         return (NSView <WebDocumentDragging> *)documentView;
2304     }
2305     return nil;
2306 }
2307
2308 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2309 {
2310     WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2311     if (!frameView)
2312         return nil;
2313     NSView <WebDocumentView> *documentView = [frameView documentView];
2314     if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2315         NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2316         return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2317     }
2318     return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2319 }
2320
2321 - (NSDictionary *)elementAtPoint:(NSPoint)point
2322 {
2323     return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2324 }
2325
2326 - (void)_setDraggingDocumentView:(NSView <WebDocumentDragging> *)newDraggingView
2327 {
2328     if (_private->draggingDocumentView != newDraggingView) {
2329         [_private->draggingDocumentView release];
2330         _private->draggingDocumentView = [newDraggingView retain];
2331     }
2332 }
2333
2334 - (NSDragOperation)_loadingDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2335 {
2336     if (_private->dragDestinationActionMask & WebDragDestinationActionLoad) {
2337         NSPoint windowPoint = [draggingInfo draggingLocation];
2338         NSView *view = [self hitTest:[[self superview] convertPoint:windowPoint toView:nil]];
2339         // Don't accept the drag over a plug-in since plug-ins may want to handle it.
2340         if (![view isKindOfClass:[WebBaseNetscapePluginView class]] && !_private->editable && !_private->initiatedDrag) {
2341             // If not editing or dragging, use _web_dragOperationForDraggingInfo to find a URL to load on the pasteboard.
2342             return [self _web_dragOperationForDraggingInfo:draggingInfo];
2343         }
2344     }
2345     return NSDragOperationNone;
2346 }
2347
2348 - (NSDragOperation)_delegateDragOperationForDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2349 {
2350     NSPoint windowPoint = [draggingInfo draggingLocation];
2351     NSView <WebDocumentDragging> *newDraggingView = [self _draggingDocumentViewAtWindowPoint:windowPoint];
2352     if (_private->draggingDocumentView != newDraggingView) {
2353         [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2354         [self _setDraggingDocumentView:newDraggingView];
2355     }
2356     
2357     _private->dragDestinationActionMask = [[self _UIDelegateForwarder] webView:self dragDestinationActionMaskForDraggingInfo:draggingInfo];
2358     NSDragOperation operation = NSDragOperationNone;
2359     
2360     if (_private->dragDestinationActionMask == WebDragDestinationActionNone) {
2361         [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2362     } else {
2363         operation = [_private->draggingDocumentView draggingUpdatedWithDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask];
2364         if (operation == NSDragOperationNone) {
2365             return [self _loadingDragOperationForDraggingInfo:draggingInfo];
2366         }
2367     }
2368     
2369     return operation;
2370 }
2371
2372 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2373 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination. 
2374 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination. 
2375 // Forward these calls to the document subview to make its scroll view scroll.
2376 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2377 {
2378     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2379     [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2380 }
2381
2382 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2383 {
2384     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2385     return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2386 }
2387
2388 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2389 {
2390     return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2391 }
2392
2393 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2394 {
2395     return [self _delegateDragOperationForDraggingInfo:draggingInfo];
2396 }
2397
2398 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2399 {
2400     [_private->draggingDocumentView draggingCancelledWithDraggingInfo:draggingInfo];
2401     [self _setDraggingDocumentView:nil];
2402 }
2403
2404 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2405 {
2406     return YES;
2407 }
2408
2409 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2410 {
2411     ASSERT(_private->draggingDocumentView == [self _draggingDocumentViewAtWindowPoint:[draggingInfo draggingLocation]]);
2412     
2413     if ([_private->draggingDocumentView concludeDragForDraggingInfo:draggingInfo actionMask:_private->dragDestinationActionMask]) {
2414         [self _setDraggingDocumentView:nil];
2415         return YES;
2416     }
2417     
2418     [self _setDraggingDocumentView:nil];
2419         
2420     if ([self _loadingDragOperationForDraggingInfo:draggingInfo] != NSDragOperationNone) {    
2421         NSURL *URL = [[self class] URLFromPasteboard:[draggingInfo draggingPasteboard]];
2422         if (URL != nil) {
2423             [[self _UIDelegateForwarder] webView:self willPerformDragDestinationAction:WebDragDestinationActionLoad forDraggingInfo:draggingInfo];
2424             NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2425             [[self mainFrame] loadRequest:request];
2426             [request release];
2427             return YES;
2428         }
2429     }
2430     
2431     return NO;
2432 }
2433
2434 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2435 {
2436     NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2437     if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2438         return self;
2439     } else {
2440         return hitView;
2441     }
2442 }
2443
2444 - (BOOL)acceptsFirstResponder
2445 {
2446     return [[[self mainFrame] frameView] acceptsFirstResponder];
2447 }
2448
2449 - (BOOL)becomeFirstResponder
2450 {
2451     // This works together with setNextKeyView to splice the WebView into
2452     // the key loop similar to the way NSScrollView does this. Note that
2453     // WebFrameView has very similar code.
2454     NSWindow *window = [self window];
2455     WebFrameView *mainFrameView = [[self mainFrame] frameView];
2456     
2457     if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2458         NSView *previousValidKeyView = [self previousValidKeyView];
2459         if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2460             [window makeFirstResponder:previousValidKeyView];
2461             return YES;
2462         } else {
2463             return NO;
2464         }
2465     }
2466     
2467     if ([mainFrameView acceptsFirstResponder]) {
2468         [window makeFirstResponder:mainFrameView];
2469         return YES;
2470     } 
2471     
2472     return NO;
2473 }
2474
2475 - (NSView *)_webcore_effectiveFirstResponder
2476 {
2477     WebFrameView *frameView = [[self mainFrame] frameView];
2478     return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2479 }
2480
2481 - (void)setNextKeyView:(NSView *)aView
2482 {
2483     // This works together with becomeFirstResponder to splice the WebView into
2484     // the key loop similar to the way NSScrollView does this. Note that
2485     // WebFrameView has very similar code.
2486     WebFrameView *mainFrameView = [[self mainFrame] frameView];
2487     if (mainFrameView != nil) {
2488         [mainFrameView setNextKeyView:aView];
2489     } else {
2490         [super setNextKeyView:aView];
2491     }
2492 }
2493
2494 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2495 {
2496     Frame* coreFrame = core(curr);
2497     return kit(forward
2498         ? coreFrame->tree()->traverseNextWithWrap(wrapFlag)
2499         : coreFrame->tree()->traversePreviousWithWrap(wrapFlag));
2500 }
2501
2502 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2503 {
2504     if (_private->closed)
2505         return NO;
2506
2507     // Get the frame holding the selection, or start with the main frame
2508     WebFrame *startFrame = [self _selectedOrMainFrame];
2509
2510     // Search the first frame, then all the other frames, in order
2511     NSView <WebDocumentSearching> *startSearchView = nil;
2512     BOOL startHasSelection = NO;
2513     WebFrame *frame = startFrame;
2514     do {
2515         id <WebDocumentView> view = [[frame frameView] documentView];
2516         if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
2517             NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
2518
2519             // first time through
2520             if (frame == startFrame) {
2521                 // Remember if start even has a selection, to know if we need to search more later
2522                 if ([searchView isKindOfClass:[WebHTMLView class]])
2523                     // optimization for the common case, to avoid making giant string for selection
2524                     startHasSelection = [startFrame _hasSelection];
2525                 else if ([searchView conformsToProtocol:@protocol(WebDocumentText)])
2526                     startHasSelection = [(id <WebDocumentText>)searchView selectedString] != nil;
2527                 startSearchView = searchView;
2528             }
2529             
2530             if ([searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:NO]) {
2531                 if (frame != startFrame)
2532                     [startFrame _clearSelection];
2533                 [[self window] makeFirstResponder:searchView];
2534                 return YES;
2535             }
2536         }
2537         frame = incrementFrame(frame, forward, wrapFlag);
2538     } while (frame != nil && frame != startFrame);
2539
2540     // Search contents of startFrame, on the other side of the selection that we did earlier.
2541     // We cheat a bit and just research with wrap on
2542     if (wrapFlag && startHasSelection && startSearchView) {
2543         if ([startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES]) {
2544             [[self window] makeFirstResponder:startSearchView];
2545             return YES;
2546         }
2547     }
2548     return NO;
2549 }
2550
2551 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2552 {
2553     [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2554     [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2555 }
2556
2557 - (void)setGroupName:(NSString *)groupName
2558 {
2559     [[self _pageBridge] setGroupName:groupName];
2560 }
2561
2562 - (NSString *)groupName
2563 {
2564     return [[self _pageBridge] groupName];
2565 }
2566
2567 - (double)estimatedProgress
2568 {
2569     return _private->progressValue;
2570 }
2571
2572 - (NSArray *)pasteboardTypesForSelection
2573 {
2574     NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2575     if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2576         return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2577     }
2578     return [NSArray array];
2579 }
2580
2581 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2582 {
2583     WebFrame *frame = [self _selectedOrMainFrame];
2584     if (frame && [frame _hasSelection]) {
2585         NSView <WebDocumentView> *documentView = [[frame frameView] documentView];
2586         if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)])
2587             [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2588     }
2589 }
2590
2591 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2592 {
2593     if ([element objectForKey:WebElementImageURLKey] != nil) {
2594         return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2595     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2596         return [NSPasteboard _web_writableTypesForURL];
2597     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2598         return [self pasteboardTypesForSelection];
2599     }
2600     return [NSArray array];
2601 }
2602
2603 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2604 {
2605     if ([element objectForKey:WebElementImageURLKey] != nil) {
2606         [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2607     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2608         [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2609     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2610         [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2611     }
2612 }
2613
2614 - (void)moveDragCaretToPoint:(NSPoint)point
2615 {
2616     [[[self mainFrame] _bridge] moveDragCaretToPoint:[self convertPoint:point toView:[[[self mainFrame] frameView] documentView]]];
2617 }
2618
2619 - (void)removeDragCaret
2620 {
2621     [_private->_pageBridge impl]->dragCaretController()->clear();
2622 }
2623
2624 - (void)setMainFrameURL:(NSString *)URLString
2625 {
2626     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2627 }
2628
2629 - (NSString *)mainFrameURL
2630 {
2631     WebDataSource *ds;
2632     ds = [[self mainFrame] provisionalDataSource];
2633     if (!ds)
2634         ds = [[self mainFrame] dataSource];
2635     return [[[ds request] URL] _web_originalDataAsString];
2636 }
2637
2638 - (BOOL)isLoading
2639 {
2640     LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2641     return [self _isLoading];
2642 }
2643
2644 - (NSString *)mainFrameTitle
2645 {
2646     NSString *mainFrameTitle = [[[self mainFrame] dataSource] pageTitle];
2647     return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2648 }
2649
2650 - (NSImage *)mainFrameIcon
2651 {
2652     return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2653 }
2654
2655 - (DOMDocument *)mainFrameDocument
2656 {
2657     // only return the actual value if the state we're in gives NSTreeController
2658     // enough time to release its observers on the old model
2659     if (_private->mainFrameDocumentReady)
2660         return [[self mainFrame] DOMDocument];
2661     return nil;
2662 }
2663
2664 - (void)setDrawsBackground:(BOOL)drawsBackground
2665 {
2666     if (_private->drawsBackground == drawsBackground)
2667         return;
2668     _private->drawsBackground = drawsBackground;
2669     [[self mainFrame] _updateBackground];
2670 }
2671
2672 - (BOOL)drawsBackground
2673 {
2674     return _private->drawsBackground;
2675 }
2676
2677 - (void)_inspectElement:(id)sender
2678 {
2679     NSDictionary *element = [sender representedObject];
2680     WebFrame *frame = [element objectForKey:WebElementFrameKey];
2681     DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
2682     if (!node || !frame)
2683         return;
2684
2685     if ([node nodeType] != DOM_ELEMENT_NODE || [node nodeType] != DOM_DOCUMENT_NODE)
2686         node = [node parentNode];
2687
2688     WebInspector *inspector = [WebInspector sharedWebInspector];
2689     [inspector setWebFrame:frame];
2690     [inspector setFocusedDOMNode:node];
2691
2692     node = [node parentNode];
2693     node = [node parentNode];
2694     if (node) // set the root node to something relatively close to the focused node
2695         [inspector setRootDOMNode:node];
2696
2697     [inspector showWindow:nil];
2698 }
2699 @end
2700
2701 @implementation WebView (WebIBActions)
2702
2703 - (IBAction)takeStringURLFrom: sender
2704 {
2705     NSString *URLString = [sender stringValue];
2706     
2707     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2708 }
2709
2710 - (BOOL)canGoBack
2711 {
2712     return [[self backForwardList] backItem] != nil;
2713 }
2714
2715 - (BOOL)canGoForward
2716 {
2717     return [[self backForwardList] forwardItem] != nil;
2718 }
2719
2720 - (IBAction)goBack:(id)sender
2721 {
2722     [self goBack];
2723 }
2724
2725 - (IBAction)goForward:(id)sender
2726 {
2727     [self goForward];
2728 }
2729
2730 - (IBAction)stopLoading:(id)sender
2731 {
2732     [[self mainFrame] stopLoading];
2733 }
2734
2735 - (IBAction)reload:(id)sender
2736 {
2737     [[self mainFrame] reload];
2738 }
2739
2740 #define MinimumTextSizeMultiplier       0.5f
2741 #define MaximumTextSizeMultiplier       3.0f
2742 #define TextSizeMultiplierRatio         1.2f
2743
2744 - (BOOL)canMakeTextSmaller
2745 {
2746     BOOL canShrinkMore = _private->textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
2747     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:0];
2748 }
2749
2750 - (BOOL)canMakeTextLarger
2751 {
2752     BOOL canGrowMore = _private->textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
2753     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:0];
2754 }
2755
2756 - (IBAction)makeTextSmaller:(id)sender
2757 {
2758     float newScale = _private->textSizeMultiplier / TextSizeMultiplierRatio;
2759     BOOL canShrinkMore = newScale > MinimumTextSizeMultiplier;
2760     [self _performTextSizingSelector:@selector(_makeTextSmaller:) withObject:sender onTrackingDocs:canShrinkMore selForNonTrackingDocs:@selector(_canMakeTextSmaller) newScaleFactor:newScale];
2761 }
2762
2763 - (IBAction)makeTextLarger:(id)sender
2764 {
2765     float newScale = _private->textSizeMultiplier*TextSizeMultiplierRatio;
2766     BOOL canGrowMore = newScale < MaximumTextSizeMultiplier;
2767     [self _performTextSizingSelector:@selector(_makeTextLarger:) withObject:sender onTrackingDocs:canGrowMore selForNonTrackingDocs:@selector(_canMakeTextLarger) newScaleFactor:newScale];
2768 }
2769
2770 - (IBAction)toggleSmartInsertDelete:(id)sender
2771 {
2772     [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2773 }
2774
2775 - (IBAction)toggleContinuousSpellChecking:(id)sender
2776 {
2777     [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2778 }
2779
2780 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2781 {
2782     id responder = [self _responderForResponderOperations];
2783     if (responder != self && [responder respondsToSelector:[item action]]) {
2784         if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)]) {
2785             return [responder validateUserInterfaceItem:item];
2786         }
2787         return YES;
2788     }
2789     return NO;
2790 }
2791
2792 - (BOOL)canMakeTextStandardSize
2793 {
2794     BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2795     return [self _performTextSizingSelector:(SEL)0 withObject:nil onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:0.0f];
2796 }
2797
2798 - (IBAction)makeTextStandardSize:(id)sender
2799 {
2800     BOOL notAlreadyStandard = _private->textSizeMultiplier != 1.0f;
2801     [self _performTextSizingSelector:@selector(_makeTextStandardSize:) withObject:sender onTrackingDocs:notAlreadyStandard selForNonTrackingDocs:@selector(_canMakeTextStandardSize) newScaleFactor:1.0f];
2802 }
2803
2804 #define VALIDATE(name) \
2805     else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2806
2807 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2808 {
2809     SEL action = [item action];
2810
2811     if (action == @selector(goBack:)) {
2812         return [self canGoBack];
2813     } else if (action == @selector(goForward:)) {
2814         return [self canGoForward];
2815     } else if (action == @selector(makeTextLarger:)) {
2816         return [self canMakeTextLarger];
2817     } else if (action == @selector(makeTextSmaller:)) {
2818         return [self canMakeTextSmaller];
2819     } else if (action == @selector(makeTextStandardSize:)) {
2820         return [self canMakeTextStandardSize];
2821     } else if (action == @selector(reload:)) {
2822         return [[self mainFrame] dataSource] != nil;
2823     } else if (action == @selector(stopLoading:)) {
2824         return [self _isLoading];
2825     } else if (action == @selector(toggleContinuousSpellChecking:)) {
2826         BOOL checkMark = NO;
2827         BOOL retVal = NO;
2828         if ([self _continuousCheckingAllowed]) {
2829             checkMark = [self isContinuousSpellCheckingEnabled];
2830             retVal = YES;
2831         }
2832         if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2833             NSMenuItem *menuItem = (NSMenuItem *)item;
2834             [menuItem setState:checkMark ? NSOnState : NSOffState];
2835         }
2836         return retVal;
2837 #if !BUILDING_ON_TIGER
2838     } else if (action == @selector(toggleGrammarChecking:)) {
2839         BOOL checkMark = [self isGrammarCheckingEnabled];
2840         if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2841             NSMenuItem *menuItem = (NSMenuItem *)item;
2842             [menuItem setState:checkMark ? NSOnState : NSOffState];
2843         }
2844         return YES;
2845 #endif
2846     }
2847     FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2848
2849     return YES;
2850 }
2851
2852 @end
2853
2854 @implementation WebView (WebPendingPublic)
2855
2856 - (void)setMainFrameDocumentReady:(BOOL)mainFrameDocumentReady
2857 {
2858     // by setting this to NO, calls to mainFrameDocument are forced to return nil
2859     // setting this to YES lets it return the actual DOMDocument value
2860     // we use this to tell NSTreeController to reset its observers and clear its state
2861     if (_private->mainFrameDocumentReady == mainFrameDocumentReady)
2862         return;
2863     [self _willChangeValueForKey:_WebMainFrameDocumentKey];
2864     _private->mainFrameDocumentReady = mainFrameDocumentReady;
2865     [self _didChangeValueForKey:_WebMainFrameDocumentKey];
2866     // this will cause observers to call mainFrameDocument where this flag will be checked
2867 }
2868
2869 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it 
2870 // until the day comes when we're no longer supporting Mail on Tiger.
2871 - (WebFrame *)_frameForCurrentSelection
2872 {
2873     return [self _selectedOrMainFrame];
2874 }
2875
2876 - (void)setTabKeyCyclesThroughElements:(BOOL)cyclesElements
2877 {
2878     _private->tabKeyCyclesThroughElementsChanged = YES;
2879     _private->tabKeyCyclesThroughElements = cyclesElements;
2880 }
2881
2882 - (BOOL)tabKeyCyclesThroughElements
2883 {
2884     return _private->tabKeyCyclesThroughElements;
2885 }
2886
2887 - (void)setScriptDebugDelegate:(id)delegate
2888 {
2889     _private->scriptDebugDelegate = delegate;
2890     [_private->scriptDebugDelegateForwarder release];
2891     _private->scriptDebugDelegateForwarder = nil;
2892     if (delegate)
2893         [self _attachScriptDebuggerToAllFrames];
2894     else
2895         [self _detachScriptDebuggerFromAllFrames];
2896 }
2897
2898 - (id)scriptDebugDelegate
2899 {
2900     return _private->scriptDebugDelegate;
2901 }
2902
2903 - (BOOL)shouldClose
2904 {
2905     FrameMac* coreFrame = core([self mainFrame]);
2906     if (!coreFrame)
2907         return YES;
2908     return coreFrame->shouldClose();
2909 }
2910
2911 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
2912 {
2913     return [[[self mainFrame] _bridge] aeDescByEvaluatingJavaScriptFromString:script];
2914 }
2915
2916 - (unsigned)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(unsigned)limit
2917 {
2918     WebFrame *frame = [self mainFrame];
2919     unsigned matchCount = 0;
2920     do {
2921         id <WebDocumentView> view = [[frame frameView] documentView];
2922         // FIXME: introduce a protocol, or otherwise make this work with other types
2923         if ([view isKindOfClass:[WebHTMLView class]])
2924             [(WebHTMLView *)view setMarkedTextMatchesAreHighlighted:highlight];
2925         
2926         ASSERT(limit == 0 || matchCount < limit);
2927         matchCount += [(WebHTMLView *)view markAllMatchesForText:string caseSensitive:caseFlag limit:limit == 0 ? 0 : limit - matchCount];
2928
2929         // Stop looking if we've reached the limit. A limit of 0 means no limit.
2930         if (limit > 0 && matchCount >= limit)
2931             break;
2932         
2933         frame = incrementFrame(frame, YES, NO);
2934     } while (frame);
2935     
2936     return matchCount;
2937 }
2938
2939 - (void)unmarkAllTextMatches
2940 {
2941     WebFrame *frame = [self mainFrame];
2942     do {
2943         id <WebDocumentView> view = [[frame frameView] documentView];
2944         // FIXME: introduce a protocol, or otherwise make this work with other types
2945         if ([view isKindOfClass:[WebHTMLView class]])
2946             [(WebHTMLView *)view unmarkAllTextMatches];
2947         
2948         frame = incrementFrame(frame, YES, NO);
2949     } while (frame);
2950 }
2951
2952 - (NSArray *)rectsForTextMatches
2953 {
2954     NSMutableArray *result = [NSMutableArray array];
2955     WebFrame *frame = [self mainFrame];
2956     do {
2957         id <WebDocumentView> view = [[frame frameView] documentView];
2958         // FIXME: introduce a protocol, or otherwise make this work with other types
2959         if ([view isKindOfClass:[WebHTMLView class]]) {
2960             WebHTMLView *htmlView = (WebHTMLView *)view;
2961             NSArray *originalRects = [htmlView rectsForTextMatches];
2962             unsigned rectCount = [originalRects count];
2963             unsigned rectIndex;
2964             NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2965             for (rectIndex = 0; rectIndex < rectCount; ++rectIndex) {
2966                 NSRect r = [[originalRects objectAtIndex:rectIndex] rectValue];
2967                 if (NSIsEmptyRect(r))
2968                     continue;
2969                 
2970                 // Convert rect to our coordinate system
2971                 r = [htmlView convertRect:r toView:self];
2972                 [result addObject:[NSValue valueWithRect:r]];
2973                 if (rectIndex % 10 == 0)
2974                     [pool drain];
2975             }
2976             [pool release];
2977         }
2978         
2979         frame = incrementFrame(frame, YES, NO);
2980     } while (frame);
2981     
2982     return result;
2983 }
2984
2985 - (void)scrollDOMRangeToVisible:(DOMRange *)range
2986 {
2987     [[[range startContainer] _bridge] scrollDOMRangeToVisible:range];
2988 }
2989
2990 @end
2991
2992 @implementation WebView (WebViewPrintingPrivate)
2993
2994 - (float)_headerHeight
2995 {
2996     if ([[self UIDelegate] respondsToSelector:@selector(webViewHeaderHeight:)]) {
2997         return [[self UIDelegate] webViewHeaderHeight:self];
2998     }
2999     
3000 #ifdef DEBUG_HEADER_AND_FOOTER
3001     return 25;
3002 #else
3003     return 0;
3004 #endif
3005 }
3006
3007 - (float)_footerHeight
3008 {
3009     if ([[self UIDelegate] respondsToSelector:@selector(webViewFooterHeight:)]) {
3010         return [[self UIDelegate] webViewFooterHeight:self];
3011     }
3012     
3013 #ifdef DEBUG_HEADER_AND_FOOTER
3014     return 50;
3015 #else
3016     return 0;
3017 #endif
3018 }
3019
3020 - (void)_drawHeaderInRect:(NSRect)rect
3021 {
3022 #ifdef DEBUG_HEADER_AND_FOOTER
3023     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3024     [currentContext saveGraphicsState];
3025     [[NSColor yellowColor] set];
3026     NSRectFill(rect);
3027     [currentContext restoreGraphicsState];
3028 #endif
3029     
3030     if ([[self UIDelegate] respondsToSelector:@selector(webView:drawHeaderInRect:)]) {
3031         NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3032         [currentContext saveGraphicsState];
3033         NSRectClip(rect);
3034         [[self UIDelegate] webView:self drawHeaderInRect:rect]; 
3035         [currentContext restoreGraphicsState];
3036     }
3037 }
3038
3039 - (void)_drawFooterInRect:(NSRect)rect
3040 {
3041 #ifdef DEBUG_HEADER_AND_FOOTER
3042     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3043     [currentContext saveGraphicsState];
3044     [[NSColor cyanColor] set];
3045     NSRectFill(rect);
3046     [currentContext restoreGraphicsState];
3047 #endif
3048     
3049     if ([[self UIDelegate] respondsToSelector:@selector(webView:drawFooterInRect:)]) {
3050         NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3051         [currentContext saveGraphicsState];
3052         NSRectClip(rect);
3053         [[self UIDelegate] webView:self drawFooterInRect:rect];
3054         [currentContext restoreGraphicsState];
3055     }
3056 }
3057
3058 - (void)_adjustPrintingMarginsForHeaderAndFooter
3059 {
3060     NSPrintOperation *op = [NSPrintOperation currentOperation];
3061     NSPrintInfo *info = [op printInfo];
3062     float scale = [op _web_pageSetupScaleFactor];
3063     [info setTopMargin:[info topMargin] + [self _headerHeight]*scale];
3064     [info setBottomMargin:[info bottomMargin] + [self _footerHeight]*scale];
3065 }
3066
3067 - (void)_drawHeaderAndFooter
3068 {
3069     // The header and footer rect height scales with the page, but the width is always
3070     // all the way across the printed page (inset by printing margins).
3071     NSPrintOperation *op = [NSPrintOperation currentOperation];
3072     float scale = [op _web_pageSetupScaleFactor];
3073     NSPrintInfo *printInfo = [op printInfo];
3074     NSSize paperSize = [printInfo paperSize];
3075     float headerFooterLeft = [printInfo leftMargin]/scale;
3076     float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
3077     NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] , 
3078                                    headerFooterWidth, [self _footerHeight]);
3079     NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale, 
3080                                    headerFooterWidth, [self _headerHeight]);
3081     
3082     [self _drawHeaderInRect:headerRect];
3083     [self _drawFooterInRect:footerRect];
3084 }
3085 @end
3086
3087 @implementation WebView (WebDebugBinding)
3088
3089 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
3090 {
3091     LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
3092     [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
3093 }
3094
3095 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
3096 {
3097     LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
3098     [super removeObserver:anObserver forKeyPath:keyPath];
3099 }
3100
3101 @end
3102
3103 //==========================================================================================
3104 // Editing
3105
3106 @implementation WebView (WebViewCSS)
3107
3108 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
3109 {
3110     // FIXME: is this the best level for this conversion?
3111     if (pseudoElement == nil) {
3112         pseudoElement = @"";
3113     }
3114     return [[element ownerDocument] getComputedStyle:element pseudoElement:pseudoElement];
3115 }
3116
3117 @end
3118
3119 @implementation WebView (WebViewEditing)
3120
3121 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
3122 {
3123     WebFrameBridge *bridge = [self _bridgeAtPoint:point];
3124     return [bridge editableDOMRangeForPoint:[self convertPoint:point toView:[[[bridge webFrame] frameView] documentView]]];
3125 }
3126
3127 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
3128 {
3129     return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
3130 }
3131
3132 - (BOOL)_shouldBeginEditingInDOMRange:(DOMRange *)range
3133 {
3134     return [[self _editingDelegateForwarder] webView:self shouldBeginEditingInDOMRange:range];
3135 }
3136
3137 - (BOOL)_shouldEndEditingInDOMRange:(DOMRange *)range
3138 {
3139     return [[self _editingDelegateForwarder] webView:self shouldEndEditingInDOMRange:range];
3140 }
3141
3142 - (BOOL)maintainsInactiveSelection
3143 {
3144     return NO;
3145 }
3146
3147 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
3148 {
3149     Frame* coreFrame = core([self _selectedOrMainFrame]);
3150     if (!coreFrame)
3151         return;
3152
3153     if (range == nil)
3154         coreFrame->selectionController()->clear();
3155     else {
3156         // Derive the frame to use from the range passed in.
3157         // Using _bridgeForSelectedOrMainFrame could give us a different document than
3158         // the one the range uses.
3159         coreFrame = core([range startContainer])->document()->frame();
3160         if (!coreFrame)
3161             return;
3162
3163         selectRange(coreFrame->selectionController(), [range _range], core(selectionAffinity), true);
3164     }
3165 }
3166
3167 - (DOMRange *)selectedDOMRange
3168 {
3169     Frame* coreFrame = core([self _selectedOrMainFrame]);
3170     if (!coreFrame)
3171         return nil;
3172     return kit(coreFrame->selectionController()->toRange().get());
3173 }
3174
3175 - (NSSelectionAffinity)selectionAffinity
3176 {
3177     Frame* coreFrame = core([self _selectedOrMainFrame]);
3178     if (!coreFrame)
3179         return NSSelectionAffinityDownstream;
3180     return kit(coreFrame->selectionController()->affinity());
3181 }
3182
3183 - (void)setEditable:(BOOL)flag
3184 {
3185     if (_private->editable != flag) {
3186         _private->editable = flag;
3187         if (!_private->tabKeyCyclesThroughElementsChanged)
3188             _private->tabKeyCyclesThroughElements = !flag;
3189         FrameMac* mainFrame = [[[self mainFrame] _bridge] _frame];
3190         if (mainFrame) {
3191             if (flag) {
3192                 mainFrame->applyEditingStyleToBodyElement();
3193                 // If the WebView is made editable and the selection is empty, set it to something.
3194                 if (![self selectedDOMRange])
3195                     mainFrame->setSelectionFromNone();
3196             } else
3197                 mainFrame->removeEditingStyleFromBodyElement();
3198         }
3199     }
3200 }
3201
3202 - (BOOL)isEditable
3203 {
3204     return _private->editable;
3205 }
3206
3207 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
3208 {
3209     // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3210     // change the API to allow this.
3211     [[self _bridgeForSelectedOrMainFrame] setTypingStyle:style withUndoAction:WebUndoActionUnspecified];
3212 }
3213
3214 - (DOMCSSStyleDeclaration *)typingStyle
3215 {
3216     return [[self _bridgeForSelectedOrMainFrame] typingStyle];
3217 }
3218
3219 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
3220 {
3221     _private->smartInsertDeleteEnabled = flag;
3222 }
3223
3224 - (BOOL)smartInsertDeleteEnabled
3225 {
3226     return _private->smartInsertDeleteEnabled;
3227 }
3228
3229 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
3230 {
3231     if (continuousSpellCheckingEnabled != flag) {
3232         continuousSpellCheckingEnabled = flag;
3233         [[NSUserDefaults standardUserDefaults] setBool:continuousSpellCheckingEnabled forKey:WebContinuousSpellCheckingEnabled];
3234     }
3235     
3236     if ([self isContinuousSpellCheckingEnabled]) {
3237         [[self class] _preflightSpellChecker];
3238     } else {
3239         [[self mainFrame] _unmarkAllMisspellings];
3240     }
3241 }
3242
3243 - (BOOL)isContinuousSpellCheckingEnabled
3244 {
3245     return (continuousSpellCheckingEnabled && [self _continuousCheckingAllowed]);
3246 }
3247
3248 - (WebNSInteger)spellCheckerDocumentTag
3249 {
3250     if (!_private->hasSpellCheckerDocumentTag) {
3251         _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3252         _private->hasSpellCheckerDocumentTag = YES;
3253     }
3254     return _private->spellCheckerDocumentTag;
3255 }
3256
3257 - (NSUndoManager *)undoManager
3258 {
3259     NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
3260     if (undoManager) {
3261         return undoManager;
3262     }
3263     return [super undoManager];
3264 }
3265
3266 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
3267 {
3268     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3269     if ([_private->editingDelegate respondsToSelector:selector])
3270         [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
3271 }
3272
3273 - (void)setEditingDelegate:(id)delegate
3274 {
3275     if (_private->editingDelegate == delegate)
3276         return;
3277
3278     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3279
3280     // remove notifications from current delegate
3281     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
3282     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
3283     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
3284     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
3285     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
3286     
3287     _private->editingDelegate = delegate;
3288     [_private->editingDelegateForwarder release];
3289     _private->editingDelegateForwarder = nil;
3290     
3291     // add notifications for new delegate
3292     [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
3293     [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
3294     [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
3295     [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
3296     [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
3297 }
3298
3299 - (id)editingDelegate
3300 {
3301     return _private->editingDelegate;
3302 }
3303
3304 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
3305 {
3306     // FIXME: Should this really be attached to the document with the current selection?
3307     DOMCSSStyleDeclaration *decl = [[[self _selectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
3308     [decl setCssText:text];
3309     return decl;
3310 }
3311
3312 @end
3313
3314 #if !BUILDING_ON_TIGER
3315 @implementation WebView (WebViewGrammarChecking)
3316
3317 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3318 - (BOOL)isGrammarCheckingEnabled
3319 {
3320     return grammarCheckingEnabled;
3321 }
3322
3323 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3324 - (void)setGrammarCheckingEnabled:(BOOL)flag
3325 {
3326     if (grammarCheckingEnabled != flag) {
3327         grammarCheckingEnabled = flag;
3328         [[NSUserDefaults standardUserDefaults] setBool:grammarCheckingEnabled forKey:WebGrammarCheckingEnabled];
3329     }
3330     
3331     // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3332     // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3333     
3334     if (![self isGrammarCheckingEnabled])
3335         [[self mainFrame] _unmarkAllBadGrammar];
3336 }
3337
3338 // FIXME: This method should be merged into WebIBActions when we're not in API freeze
3339 - (void)toggleGrammarChecking:(id)sender
3340 {
3341     [self setGrammarCheckingEnabled:![self isGrammarCheckingEnabled]];
3342 }
3343
3344 @end
3345 #endif
3346
3347 @implementation WebView (WebViewUndoableEditing)
3348
3349 - (void)replaceSelectionWithNode:(DOMNode *)node
3350 {
3351     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:NO];
3352 }    
3353
3354 - (void)replaceSelectionWithText:(NSString *)text
3355 {
3356     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
3357 }
3358
3359 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
3360 {
3361     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
3362 }
3363
3364 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3365 {
3366     [[[[self _bridgeForSelectedOrMainFrame] webFrame] dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3367 }
3368
3369 - (void)deleteSelection
3370 {
3371     WebFrame *webFrame = [self _selectedOrMainFrame];
3372     Frame* coreFrame = core(webFrame);
3373     if (coreFrame)
3374         coreFrame->editor()->deleteSelectionWithSmartDelete([(WebHTMLView *)[[webFrame frameView] documentView] _canSmartCopyOrDelete]);
3375 }
3376     
3377 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3378 {
3379     // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3380     // change the API to allow this.
3381     [[self _bridgeForSelectedOrMainFrame] applyStyle:style withUndoAction:WebUndoActionUnspecified];
3382 }
3383
3384 @end
3385
3386 @implementation WebView (WebViewEditingActions)
3387
3388 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3389 {
3390     static BOOL reentered = NO;
3391     if (reentered) {
3392         [[self nextResponder] tryToPerform:selector with:parameter];
3393         return;
3394     }
3395
3396     // There are two possibilities here.
3397     //
3398     // One is that WebView has been called in its role as part of the responder chain.
3399     // In that case, it's fine to call the first responder and end up calling down the
3400     // responder chain again. Later we will return here with reentered = YES and continue
3401     // past the WebView.
3402     //
3403     // The other is that we are being called directly, in which case we want to pass the
3404     // selector down to the view inside us that can handle it, and continue down the
3405     // responder chain as usual.
3406
3407     // Pass this selector down to the first responder.
3408     NSResponder *responder = [self _responderForResponderOperations];
3409     reentered = YES;
3410     [responder tryToPerform:selector with:parameter];
3411     reentered = NO;
3412 }
3413
3414 #define FORWARD(name) \
3415     - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3416
3417 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3418
3419 - (void)insertText:(NSString *)text
3420 {
3421     [self _performResponderOperation:_cmd with:text];
3422 }
3423
3424 @end
3425
3426 @implementation WebView (WebViewEditingInMail)
3427
3428 - (void)_insertNewlineInQuotedContent;
3429 {
3430     [[self _bridgeForSelectedOrMainFrame] insertParagraphSeparatorInQuotedContent];
3431 }
3432
3433 - (BOOL)_selectWordBeforeMenuEvent
3434 {
3435     return _private->selectWordBeforeMenuEvent;
3436 }
3437
3438 - (void)_setSelectWordBeforeMenuEvent:(BOOL)flag
3439 {
3440     _private->selectWordBeforeMenuEvent = flag;
3441 }
3442
3443 - (void)_replaceSelectionWithNode:(DOMNode *)node matchStyle:(BOOL)matchStyle
3444 {
3445     [[self _bridgeForSelectedOrMainFrame] replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:matchStyle];
3446 }
3447
3448 @end
3449
3450 static WebFrameView *containingFrameView(NSView *view)
3451 {
3452     while (view && ![view isKindOfClass:[WebFrameView class]])
3453         view = [view superview];
3454     return (WebFrameView *)view;    
3455 }
3456
3457 @implementation WebView (WebFileInternal)
3458
3459 - (WebFrame *)_focusedFrame
3460 {
3461     NSResponder *resp = [[self window] firstResponder];
3462     if (resp && [resp isKindOfClass:[NSView class]] && [(NSView *)resp isDescendantOf:[[self mainFrame] frameView]]) {
3463         WebFrameView *frameView = containingFrameView((NSView *)resp);
3464         ASSERT(frameView != nil);
3465         return [frameView webFrame];
3466     }
3467     
3468     return nil;
3469 }
3470
3471 - (WebFrame *)_selectedOrMainFrame
3472 {
3473     WebFrame *result = [self selectedFrame];
3474     if (result == nil)
3475         result = [self mainFrame];
3476     return result;
3477 }
3478
3479 - (WebFrameBridge *)_bridgeForSelectedOrMainFrame
3480 {
3481     return [[self _selectedOrMainFrame] _bridge];
3482 }
3483
3484 - (BOOL)_isLoading
3485 {
3486     WebFrame *mainFrame = [self mainFrame];
3487     return [[mainFrame dataSource] isLoading]
3488         || [[mainFrame provisionalDataSource] isLoading];
3489 }
3490
3491 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point
3492 {
3493     if (_private->closed)
3494         return nil;
3495     NSView *view = [self hitTest:[[self superview] convertPoint:point fromView:nil]];
3496     if (![view isDescendantOf:[[self mainFrame] frameView]])
3497         return nil;
3498     WebFrameView *frameView = containingFrameView(view);
3499     ASSERT(frameView);
3500     return frameView;
3501 }
3502
3503 - (WebFrameBridge *)_bridgeAtPoint:(NSPoint)point
3504 {
3505     return [[[self _frameViewAtWindowPoint:[self convertPoint:point toView:nil]] webFrame] _bridge];
3506 }
3507
3508 + (void)_preflightSpellCheckerNow:(id)sender
3509 {
3510     [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
3511 }
3512
3513 + (void)_preflightSpellChecker
3514 {
3515     // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3516     if ([NSSpellChecker sharedSpellCheckerExists]) {
3517         [self _preflightSpellCheckerNow:self];
3518     } else {
3519         [self performSelector:@selector(_preflightSpellCheckerNow:) withObject:self afterDelay:2.0];
3520     }
3521 }
3522
3523 - (BOOL)_continuousCheckingAllowed
3524 {
3525     static BOOL allowContinuousSpellChecking = YES;
3526     static BOOL readAllowContinuousSpellCheckingDefault = NO;
3527     if (!readAllowContinuousSpellCheckingDefault) {
3528         if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NSAllowContinuousSpellChecking"]) {
3529             allowContinuousSpellChecking = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSAllowContinuousSpellChecking"];
3530         }
3531         readAllowContinuousSpellCheckingDefault = YES;
3532     }
3533     return allowContinuousSpellChecking;
3534 }
3535
3536 - (NSResponder *)_responderForResponderOperations
3537 {
3538     NSResponder *responder = [[self window] firstResponder];
3539     WebFrameView *mainFrameView = [[self mainFrame] frameView];
3540     
3541     // If the current responder is outside of the webview, use our main frameView or its
3542     // document view. We also do this for subviews of self that are siblings of the main
3543     // frameView since clients might insert non-webview-related views there (see 4552713).
3544     if (responder != self && ![mainFrameView _web_firstResponderIsSelfOrDescendantView]) {
3545         responder = [mainFrameView documentView];
3546         if (!responder)
3547             responder = mainFrameView;
3548     }
3549     return responder;
3550 }
3551
3552 - (void)_searchWithGoogleFromMenu:(id)sender
3553 {
3554     id documentView = [[[self selectedFrame] frameView] documentView];
3555     if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3556         return;
3557     }
3558     
3559     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3560     if ([selectedString length] == 0) {
3561         return;
3562     }
3563     
3564     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName];
3565     [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
3566     NSMutableString *s = [selectedString mutableCopy];
3567     const unichar nonBreakingSpaceCharacter = 0xA0;
3568     NSString *nonBreakingSpaceString = [NSString stringWithCharacters:&nonBreakingSpaceCharacter length:1];
3569     [s replaceOccurrencesOfString:nonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
3570     [pasteboard setString:s forType:NSStringPboardType];
3571     [s release];
3572     
3573     // FIXME: seems fragile to use the service by name, but this is what AppKit does
3574     NSPerformService(@"Search With Google", pasteboard);
3575 }
3576
3577 - (void)_searchWithSpotlightFromMenu:(id)sender
3578 {
3579     id documentView = [[[self selectedFrame] frameView] documentView];
3580     if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
3581         return;
3582     }
3583     
3584     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
3585     if ([selectedString length] == 0) {
3586         return;
3587     }
3588
3589     (void)HISearchWindowShow((CFStringRef)selectedString, kNilOptions);
3590 }
3591
3592 // Slightly funky method that lets us have one copy of the logic for finding docViews that can do
3593 // text sizing.  It returns whether it found any "suitable" doc views.  It sends sel to any suitable
3594 // doc views, or if sel==0 we do nothing to them.  For doc views that track our size factor, they are
3595 // suitable if doTrackingViews==YES (which in practice means that our size factor isn't at its max or
3596 // min).  For doc views that don't track it, we send them testSel to determine suitablility.  If we
3597 // do find any suitable tracking doc views and newScaleFactor!=0, we will set the common scale factor
3598 // to that new factor before we send sel to any of them. 
3599 - (BOOL)_performTextSizingSelector:(SEL)sel withObject:(id)arg onTrackingDocs:(BOOL)doTrackingViews selForNonTrackingDocs:(SEL)testSel newScaleFactor:(float)newScaleFactor
3600 {
3601     if ([[self mainFrame] dataSource] == nil)
3602         return NO;
3603     
3604     BOOL foundSome = NO;
3605     NSArray *docViews = [[self mainFrame] _documentViews];
3606     for (int i = [docViews count]-1; i >= 0; i--) {
3607         id docView = [docViews objectAtIndex:i];
3608         if ([docView conformsToProtocol:@protocol(_WebDocumentTextSizing)]) {
3609             id <_WebDocumentTextSizing> sizingDocView = (id <_WebDocumentTextSizing>)docView;
3610             BOOL isSuitable;
3611             if ([sizingDocView _tracksCommonSizeFactor]) {
3612                 isSuitable = doTrackingViews;
3613                 if (isSuitable && newScaleFactor != 0)
3614                     _private->textSizeMultiplier = newScaleFactor;
3615             } else {
3616                 // Incantation to perform a selector returning a BOOL.
3617                 isSuitable = ((BOOL(*)(id, SEL))objc_msgSend)(sizingDocView, testSel);
3618             }
3619             
3620             if (isSuitable) {
3621                 if (sel != 0) {
3622                     foundSome = YES;
3623                     [sizingDocView performSelector:sel withObject:arg];
3624                 } else {
3625                     // if we're just called for the benefit of the return value, we can return at first match
3626                     return YES;
3627                 }
3628             }
3629         }
3630     }
3631     
3632     return foundSome;
3633 }
3634
3635 - (void)_notifyTextSizeMultiplierChanged
3636 {
3637     if ([[self mainFrame] dataSource] == nil)
3638         return;
3639
3640     NSArray *docViews = [[self mainFrame] _documentViews];
3641     for (int i = [docViews count]-1; i >= 0; i--) {
3642         id docView = [docViews objectAtIndex:i];
3643         if ([docView conformsToProtocol:@protocol(_WebDocumentTextSizing)] == NO)
3644             continue;
3645
3646         id <_WebDocumentTextSizing> sizingDocView = (id <_WebDocumentTextSizing>)docView;
3647         if ([sizingDocView _tracksCommonSizeFactor])
3648             [sizingDocView _textSizeMultiplierChanged];
3649     }
3650
3651 }
3652
3653 @end
3654
3655 @implementation WebView (WebViewBridge)
3656
3657 - (WebPageBridge *)_pageBridge
3658 {
3659     return _private->_pageBridge;
3660 }
3661
3662 @end