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