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