2c2575197e2a15c0d0c0fc9e3c2b7e5bb49a2d59
[WebKit-https.git] / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008 Apple 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 "WebBackForwardListInternal.h"
34 #import "WebBaseNetscapePluginView.h"
35 #import "WebChromeClient.h"
36 #import "WebContextMenuClient.h"
37 #import "WebDOMOperationsPrivate.h"
38 #import "WebDataSourceInternal.h"
39 #import "WebDatabaseManagerInternal.h"
40 #import "WebDefaultEditingDelegate.h"
41 #import "WebDefaultPolicyDelegate.h"
42 #import "WebDefaultScriptDebugDelegate.h"
43 #import "WebDefaultUIDelegate.h"
44 #import "WebDocument.h"
45 #import "WebDocumentInternal.h"
46 #import "WebDownload.h"
47 #import "WebDownloadInternal.h"
48 #import "WebDragClient.h"
49 #import "WebDynamicScrollBarsViewInternal.h"
50 #import "WebEditingDelegate.h"
51 #import "WebEditorClient.h"
52 #import "WebFormDelegatePrivate.h"
53 #import "WebFrameInternal.h"
54 #import "WebFrameViewInternal.h"
55 #import "WebHTMLRepresentation.h"
56 #import "WebHTMLViewInternal.h"
57 #import "WebHistoryItemInternal.h"
58 #import "WebIconDatabaseInternal.h"
59 #import "WebInspector.h"
60 #import "WebInspectorClient.h"
61 #import "WebKitErrors.h"
62 #import "WebKitLogging.h"
63 #import "WebKitNSStringExtras.h"
64 #import "WebKitStatisticsPrivate.h"
65 #import "WebKitSystemBits.h"
66 #import "WebKitVersionChecks.h"
67 #import "WebLocalizableStrings.h"
68 #import "WebNSDataExtras.h"
69 #import "WebNSDataExtrasPrivate.h"
70 #import "WebNSDictionaryExtras.h"
71 #import "WebNSEventExtras.h"
72 #import "WebNSObjectExtras.h"
73 #import "WebNSPasteboardExtras.h"
74 #import "WebNSPrintOperationExtras.h"
75 #import "WebNSURLExtras.h"
76 #import "WebNSURLRequestExtras.h"
77 #import "WebNSUserDefaultsExtras.h"
78 #import "WebNSViewExtras.h"
79 #import "WebPDFView.h"
80 #import "WebPanelAuthenticationHandler.h"
81 #import "WebPasteboardHelper.h"
82 #import "WebPluginDatabase.h"
83 #import "WebPolicyDelegate.h"
84 #import "WebPreferenceKeysPrivate.h"
85 #import "WebPreferencesPrivate.h"
86 #import "WebScriptDebugServerPrivate.h"
87 #import "WebUIDelegate.h"
88 #import "WebUIDelegatePrivate.h"
89 #import <CoreFoundation/CFSet.h>
90 #import <Foundation/NSURLConnection.h>
91 #import <JavaScriptCore/Assertions.h>
92 #import <JavaScriptCore/HashTraits.h>
93 #import <JavaScriptCore/RefPtr.h>
94 #import <JavaScriptCore/array_object.h>
95 #import <JavaScriptCore/date_object.h>
96 #import <WebCore/ApplicationCacheStorage.h>
97 #import <WebCore/Cache.h>
98 #import <WebCore/ColorMac.h>
99 #import <WebCore/Document.h>
100 #import <WebCore/DocumentLoader.h>
101 #import <WebCore/DragController.h>
102 #import <WebCore/DragData.h>
103 #import <WebCore/Editor.h>
104 #import <WebCore/ExceptionHandlers.h>
105 #import <WebCore/Frame.h>
106 #import <WebCore/FrameLoader.h>
107 #import <WebCore/FrameTree.h>
108 #import <WebCore/HTMLNames.h>
109 #import <WebCore/HistoryItem.h>
110 #import <WebCore/Logging.h>
111 #import <WebCore/MIMETypeRegistry.h>
112 #import <WebCore/Page.h>
113 #import <WebCore/PageCache.h>
114 #import <WebCore/PlatformMouseEvent.h>
115 #import <WebCore/ProgressTracker.h>
116 #import <WebCore/SelectionController.h>
117 #import <WebCore/Settings.h>
118 #import <WebCore/TextResourceDecoder.h>
119 #import <WebCore/WebCoreObjCExtras.h>
120 #import <WebCore/WebCoreTextRenderer.h>
121 #import <WebCore/WebCoreView.h>
122 #import <WebCore/kjs_proxy.h>
123 #import <WebKit/DOM.h>
124 #import <WebKit/DOMExtensions.h>
125 #import <WebKit/DOMPrivate.h>
126 #import <WebKitSystemInterface.h>
127 #import <kjs/InitializeThreading.h>
128 #import <mach-o/dyld.h>
129 #import <objc/objc-auto.h>
130 #import <objc/objc-runtime.h>
131 #import <sys/param.h>
132
133 #if ENABLE(DASHBOARD_SUPPORT)
134 #import <WebKit/WebDashboardRegion.h>
135 #endif
136
137 using namespace WebCore;
138 using namespace KJS;
139
140 #if defined(__ppc__) || defined(__ppc64__)
141 #define PROCESSOR "PPC"
142 #elif defined(__i386__) || defined(__x86_64__)
143 #define PROCESSOR "Intel"
144 #else
145 #error Unknown architecture
146 #endif
147
148 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
149 macro(alignCenter) \
150 macro(alignJustified) \
151 macro(alignLeft) \
152 macro(alignRight) \
153 macro(capitalizeWord) \
154 macro(centerSelectionInVisibleArea) \
155 macro(changeAttributes) \
156 macro(changeBaseWritingDirection) \
157 macro(changeBaseWritingDirectionToLTR) \
158 macro(changeBaseWritingDirectionToRTL) \
159 macro(changeColor) \
160 macro(changeDocumentBackgroundColor) \
161 macro(changeFont) \
162 macro(changeSpelling) \
163 macro(checkSpelling) \
164 macro(complete) \
165 macro(copy) \
166 macro(copyFont) \
167 macro(cut) \
168 macro(delete) \
169 macro(deleteBackward) \
170 macro(deleteBackwardByDecomposingPreviousCharacter) \
171 macro(deleteForward) \
172 macro(deleteToBeginningOfLine) \
173 macro(deleteToBeginningOfParagraph) \
174 macro(deleteToEndOfLine) \
175 macro(deleteToEndOfParagraph) \
176 macro(deleteToMark) \
177 macro(deleteWordBackward) \
178 macro(deleteWordForward) \
179 macro(ignoreSpelling) \
180 macro(indent) \
181 macro(insertBacktab) \
182 macro(insertLineBreak) \
183 macro(insertNewline) \
184 macro(insertNewlineIgnoringFieldEditor) \
185 macro(insertParagraphSeparator) \
186 macro(insertTab) \
187 macro(insertTabIgnoringFieldEditor) \
188 macro(lowercaseWord) \
189 macro(moveBackward) \
190 macro(moveBackwardAndModifySelection) \
191 macro(moveDown) \
192 macro(moveDownAndModifySelection) \
193 macro(moveForward) \
194 macro(moveForwardAndModifySelection) \
195 macro(moveLeft) \
196 macro(moveLeftAndModifySelection) \
197 macro(moveParagraphBackwardAndModifySelection) \
198 macro(moveParagraphForwardAndModifySelection) \
199 macro(moveRight) \
200 macro(moveRightAndModifySelection) \
201 macro(moveToBeginningOfDocument) \
202 macro(moveToBeginningOfDocumentAndModifySelection) \
203 macro(moveToBeginningOfLine) \
204 macro(moveToBeginningOfLineAndModifySelection) \
205 macro(moveToBeginningOfParagraph) \
206 macro(moveToBeginningOfParagraphAndModifySelection) \
207 macro(moveToBeginningOfSentence) \
208 macro(moveToBeginningOfSentenceAndModifySelection) \
209 macro(moveToEndOfDocument) \
210 macro(moveToEndOfDocumentAndModifySelection) \
211 macro(moveToEndOfLine) \
212 macro(moveToEndOfLineAndModifySelection) \
213 macro(moveToEndOfParagraph) \
214 macro(moveToEndOfParagraphAndModifySelection) \
215 macro(moveToEndOfSentence) \
216 macro(moveToEndOfSentenceAndModifySelection) \
217 macro(moveUp) \
218 macro(moveUpAndModifySelection) \
219 macro(moveWordBackward) \
220 macro(moveWordBackwardAndModifySelection) \
221 macro(moveWordForward) \
222 macro(moveWordForwardAndModifySelection) \
223 macro(moveWordLeft) \
224 macro(moveWordLeftAndModifySelection) \
225 macro(moveWordRight) \
226 macro(moveWordRightAndModifySelection) \
227 macro(outdent) \
228 macro(pageDown) \
229 macro(pageDownAndModifySelection) \
230 macro(pageUp) \
231 macro(pageUpAndModifySelection) \
232 macro(paste) \
233 macro(pasteAsPlainText) \
234 macro(pasteAsRichText) \
235 macro(pasteFont) \
236 macro(performFindPanelAction) \
237 macro(scrollLineDown) \
238 macro(scrollLineUp) \
239 macro(scrollPageDown) \
240 macro(scrollPageUp) \
241 macro(scrollToBeginningOfDocument) \
242 macro(scrollToEndOfDocument) \
243 macro(selectAll) \
244 macro(selectLine) \
245 macro(selectParagraph) \
246 macro(selectSentence) \
247 macro(selectToMark) \
248 macro(selectWord) \
249 macro(setMark) \
250 macro(showGuessPanel) \
251 macro(startSpeaking) \
252 macro(stopSpeaking) \
253 macro(subscript) \
254 macro(superscript) \
255 macro(swapWithMark) \
256 macro(takeFindStringFromSelection) \
257 macro(toggleBaseWritingDirection) \
258 macro(transpose) \
259 macro(underline) \
260 macro(unscript) \
261 macro(uppercaseWord) \
262 macro(yank) \
263 macro(yankAndSelect) \
264
265 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
266 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
267
268 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
269 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
270 #define UniversalAccessDomain CFSTR("com.apple.universalaccess")
271
272 static BOOL s_didSetCacheModel;
273 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
274
275 static BOOL applicationIsTerminating;
276 static int pluginDatabaseClientCount = 0;
277
278 @interface NSSpellChecker (AppKitSecretsIKnow)
279 - (void)_preflightChosenSpellServer;
280 @end
281
282 @interface NSView (AppKitSecretsIKnow)
283 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
284 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
285 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
286 @end
287
288 @interface NSWindow (AppKitSecretsIKnow) 
289 - (id)_oldFirstResponderBeforeBecoming;
290 @end
291
292 @interface NSObject (ValidateWithoutDelegate)
293 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
294 @end
295
296 @interface _WebSafeForwarder : NSObject
297 {
298     id target; // Non-retained. Don't retain delegates.
299     id defaultTarget;
300     BOOL catchExceptions;
301 }
302 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget catchExceptions:(BOOL)catchExceptions;
303 @end
304
305 @interface WebViewPrivate : NSObject {
306 @public
307     Page* page;
308     
309     id UIDelegate;
310     id UIDelegateForwarder;
311     id resourceProgressDelegate;
312     id downloadDelegate;
313     id policyDelegate;
314     id policyDelegateForwarder;
315     id frameLoadDelegate;
316     id frameLoadDelegateForwarder;
317     id <WebFormDelegate> formDelegate;
318     id editingDelegate;
319     id editingDelegateForwarder;
320     id scriptDebugDelegate;
321     id scriptDebugDelegateForwarder;
322
323     WebInspector *inspector;
324
325     BOOL allowsUndo;
326         
327     float zoomMultiplier;
328     BOOL zoomMultiplierIsTextOnly;
329
330     NSString *applicationNameForUserAgent;
331     String* userAgent;
332     BOOL userAgentOverridden;
333     
334     WebPreferences *preferences;
335     BOOL useSiteSpecificSpoofing;
336
337     NSWindow *hostWindow;
338
339     int programmaticFocusCount;
340     
341     WebResourceDelegateImplementationCache resourceLoadDelegateImplementations;
342     WebFrameLoadDelegateImplementationCache frameLoadDelegateImplementations;
343
344     void *observationInfo;
345     
346     BOOL closed;
347     BOOL shouldCloseWithWindow;
348     BOOL mainFrameDocumentReady;
349     BOOL drawsBackground;
350     BOOL editable;
351     BOOL tabKeyCyclesThroughElementsChanged;
352     BOOL becomingFirstResponder;
353     BOOL becomingFirstResponderFromOutside;
354     BOOL hoverFeedbackSuspended;
355     BOOL usesPageCache;
356     BOOL catchesDelegateExceptions;
357
358     NSColor *backgroundColor;
359
360     NSString *mediaStyle;
361     
362     BOOL hasSpellCheckerDocumentTag;
363     NSInteger spellCheckerDocumentTag;
364
365     BOOL smartInsertDeleteEnabled;
366         
367 #if ENABLE(DASHBOARD_SUPPORT)
368     BOOL dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
369     BOOL dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
370     BOOL dashboardBehaviorAlwaysAcceptsFirstMouse;
371     BOOL dashboardBehaviorAllowWheelScrolling;
372 #endif
373     
374     // WebKit has both a global plug-in database and a separate, per WebView plug-in database. Dashboard uses the per WebView database.
375     WebPluginDatabase *pluginDatabase;
376     
377     HashMap<unsigned long, RetainPtr<id> >* identifierMap;
378
379     BOOL _keyboardUIModeAccessed;
380     KeyboardUIMode _keyboardUIMode;
381 }
382 @end
383
384 @interface WebView (WebFileInternal)
385 - (WebFrame *)_selectedOrMainFrame;
386 - (BOOL)_isLoading;
387 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
388 - (WebFrame *)_focusedFrame;
389 + (void)_preflightSpellChecker;
390 - (BOOL)_continuousCheckingAllowed;
391 - (NSResponder *)_responderForResponderOperations;
392 @end
393
394 @interface WebView (WebCallDelegateFunctions)
395 @end
396
397 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
398 NSString *WebElementFrameKey =              @"WebElementFrame";
399 NSString *WebElementImageKey =              @"WebElementImage";
400 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
401 NSString *WebElementImageRectKey =          @"WebElementImageRect";
402 NSString *WebElementImageURLKey =           @"WebElementImageURL";
403 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
404 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
405 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
406 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
407 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
408 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
409 NSString *WebElementTitleKey =              @"WebElementTitle";
410 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
411 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
412
413 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
414 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
415 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
416
417 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
418 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
419 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
420 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
421 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
422
423 enum { WebViewVersion = 4 };
424
425 #define timedLayoutSize 4096
426
427 static NSMutableSet *schemesWithRepresentationsSet;
428
429 NSString *_WebCanGoBackKey =            @"canGoBack";
430 NSString *_WebCanGoForwardKey =         @"canGoForward";
431 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
432 NSString *_WebIsLoadingKey =            @"isLoading";
433 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
434 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
435 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
436 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
437
438 @interface WebProgressItem : NSObject
439 {
440 @public
441     long long bytesReceived;
442     long long estimatedLength;
443 }
444 @end
445
446 @implementation WebProgressItem
447 @end
448
449 static BOOL continuousSpellCheckingEnabled;
450 #ifndef BUILDING_ON_TIGER
451 static BOOL grammarCheckingEnabled;
452 #endif
453
454 @implementation WebViewPrivate
455
456 #ifndef BUILDING_ON_TIGER
457 + (void)initialize
458 {
459     WebCoreObjCFinalizeOnMainThread(self);
460 }
461 #endif
462
463 - init 
464 {
465     self = [super init];
466     if (!self)
467         return nil;
468     KJS::initializeThreading();
469     allowsUndo = YES;
470     zoomMultiplier = 1;
471     zoomMultiplierIsTextOnly = YES;
472 #if ENABLE(DASHBOARD_SUPPORT)
473     dashboardBehaviorAllowWheelScrolling = YES;
474 #endif
475     shouldCloseWithWindow = objc_collecting_enabled();
476     continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
477
478 #ifndef BUILDING_ON_TIGER
479     grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
480 #endif
481     userAgent = new String;
482     
483     usesPageCache = YES;
484     
485     identifierMap = new HashMap<unsigned long, RetainPtr<id> >();
486     pluginDatabaseClientCount++;
487
488     return self;
489 }
490
491 - (void)dealloc
492 {
493     ASSERT(!page);
494     ASSERT(!preferences);
495
496     delete userAgent;
497     delete identifierMap;
498     
499     [applicationNameForUserAgent release];
500     [backgroundColor release];
501     
502     [inspector release];
503     [hostWindow release];
504
505     [policyDelegateForwarder release];
506     [UIDelegateForwarder release];
507     [frameLoadDelegateForwarder release];
508     [editingDelegateForwarder release];
509     [scriptDebugDelegateForwarder release];
510     
511     [mediaStyle release];
512     
513     [super dealloc];
514 }
515
516 - (void)finalize
517 {
518     ASSERT_MAIN_THREAD();
519
520     delete userAgent;
521     delete identifierMap;
522
523     [super finalize];
524 }
525
526 @end
527
528 @implementation WebView (AllWebViews)
529
530 static CFSetCallBacks NonRetainingSetCallbacks = {
531     0,
532     NULL,
533     NULL,
534     CFCopyDescription,
535     CFEqual,
536     CFHash
537 };
538
539 static CFMutableSetRef allWebViewsSet;
540
541 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
542 {
543     if (!allWebViewsSet)
544         return;
545
546     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
547 }
548
549 - (void)_removeFromAllWebViewsSet
550 {
551     if (allWebViewsSet)
552         CFSetRemoveValue(allWebViewsSet, self);
553 }
554
555 - (void)_addToAllWebViewsSet
556 {
557     if (!allWebViewsSet)
558         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
559
560     CFSetSetValue(allWebViewsSet, self);
561 }
562
563 @end
564
565 @implementation WebView (WebPrivate)
566
567 #ifdef DEBUG_WIDGET_DRAWING
568 static bool debugWidget = true;
569 - (void)drawRect:(NSRect)rect
570 {
571     [[NSColor blueColor] set];
572     NSRectFill (rect);
573     
574     NSRect htmlViewRect = [[[[self mainFrame] frameView] documentView] frame];
575
576     if (debugWidget) {
577         while (debugWidget) {
578             sleep (1);
579         }
580     }
581
582     NSLog (@"%s:   rect:  (%0.f,%0.f) %0.f %0.f, htmlViewRect:  (%0.f,%0.f) %0.f %0.f\n", 
583         __PRETTY_FUNCTION__, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
584         htmlViewRect.origin.x, htmlViewRect.origin.y, htmlViewRect.size.width, htmlViewRect.size.height
585     );
586
587     [super drawRect:rect];
588 }
589 #endif
590
591 + (BOOL)_scriptDebuggerEnabled
592 {
593 #ifdef NDEBUG
594     return [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitScriptDebuggerEnabled"];
595 #else
596     return YES; // always enable in debug builds
597 #endif
598 }
599
600 + (NSArray *)_supportedMIMETypes
601 {
602     // Load the plug-in DB allowing plug-ins to install types.
603     [WebPluginDatabase sharedDatabase];
604     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
605 }
606
607 + (NSArray *)_supportedFileExtensions
608 {
609     NSMutableSet *extensions = [[NSMutableSet alloc] init];
610     NSArray *MIMETypes = [self _supportedMIMETypes];
611     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
612     NSString *MIMEType;
613     while ((MIMEType = [enumerator nextObject]) != nil) {
614         NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
615         if (extensionsForType) {
616             [extensions addObjectsFromArray:extensionsForType];
617         }
618     }
619     NSArray *uniqueExtensions = [extensions allObjects];
620     [extensions release];
621     return uniqueExtensions;
622 }
623
624 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
625 {
626     MIMEType = [MIMEType lowercaseString];
627     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
628     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
629     
630     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
631         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
632         // Load the plug-in DB allowing plug-ins to install types.
633         [WebPluginDatabase sharedDatabase];
634             
635         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
636         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
637         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
638     }
639     
640     if (viewClass && repClass) {
641         // Special-case WebHTMLView for text types that shouldn't be shown.
642         if (viewClass == [WebHTMLView class] &&
643             repClass == [WebHTMLRepresentation class] &&
644             [[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType]) {
645             return NO;
646         }
647         if (vClass)
648             *vClass = viewClass;
649         if (rClass)
650             *rClass = repClass;
651         return YES;
652     }
653     
654     return NO;
655 }
656
657 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType;
658 {
659     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType])
660         return YES;
661
662     if (_private->pluginDatabase) {
663         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
664         if (pluginPackage) {
665             if (vClass)
666                 *vClass = [WebHTMLView class];
667             if (rClass)
668                 *rClass = [WebHTMLRepresentation class];
669             return YES;
670         }
671     }
672     
673     return NO;
674 }
675
676 + (void)_setAlwaysUseATSU:(BOOL)f
677 {
678     WebCoreSetAlwaysUseATSU(f);
679 }
680
681 + (BOOL)canShowFile:(NSString *)path
682 {
683     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
684 }
685
686 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
687 {
688     return WKGetPreferredExtensionForMIMEType(type);
689 }
690
691 - (BOOL)_isClosed
692 {
693     if (!_private || _private->closed)
694         return YES;
695     return NO;
696 }
697
698 - (void)_close
699 {
700     if (!_private || _private->closed)
701         return;
702
703     if (Frame* mainFrame = core([self mainFrame]))
704         mainFrame->loader()->detachFromParent();
705
706     [self _removeFromAllWebViewsSet];
707     [self setHostWindow:nil];
708
709     [self setDownloadDelegate:nil];
710     [self setEditingDelegate:nil];
711     [self setFrameLoadDelegate:nil];
712     [self setPolicyDelegate:nil];
713     [self setResourceLoadDelegate:nil];
714     [self setScriptDebugDelegate:nil];
715     [self setUIDelegate:nil];
716
717     [_private->inspector webViewClosed];
718
719     // setHostWindow:nil must be called before this value is set (see 5408186)
720     _private->closed = YES;
721
722     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
723     [self removeDragCaret];
724
725     // Deleteing the WebCore::Page will clear the page cache so we call destroy on 
726     // all the plug-ins in the page cache to break any retain cycles.
727     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
728     delete _private->page;
729     _private->page = 0;
730
731     if (_private->hasSpellCheckerDocumentTag) {
732         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
733         _private->hasSpellCheckerDocumentTag = NO;
734     }
735     
736     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
737     [[NSNotificationCenter defaultCenter] removeObserver:self];
738
739     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
740
741     WebPreferences *preferences = _private->preferences;
742     _private->preferences = nil;
743     [preferences didRemoveFromWebView];
744     [preferences release];
745
746     pluginDatabaseClientCount--;
747     
748     // Make sure to close both sets of plug-ins databases because plug-ins need an opportunity to clean up files, etc.
749     
750     // Unload the WebView local plug-in database. 
751     if (_private->pluginDatabase) {
752         [_private->pluginDatabase close];
753         [_private->pluginDatabase release];
754         _private->pluginDatabase = nil;
755     }
756     
757     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
758     if (!pluginDatabaseClientCount && applicationIsTerminating)
759         [WebPluginDatabase closeSharedDatabase];
760 }
761
762 + (NSString *)_MIMETypeForFile:(NSString *)path
763 {
764     NSString *extension = [path pathExtension];
765     NSString *MIMEType = nil;
766
767     // Get the MIME type from the extension.
768     if ([extension length] != 0) {
769         MIMEType = WKGetMIMETypeForExtension(extension);
770     }
771
772     // If we can't get a known MIME type from the extension, sniff.
773     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
774         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
775         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
776         [handle closeFile];
777         if ([data length] != 0) {
778             MIMEType = [data _webkit_guessedMIMEType];
779         }
780         if ([MIMEType length] == 0) {
781             MIMEType = @"application/octet-stream";
782         }
783     }
784
785     return MIMEType;
786 }
787
788 - (WebDownload *)_downloadURL:(NSURL *)URL
789 {
790     ASSERT(URL);
791     
792     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
793     WebDownload *download = [WebDownload _downloadWithRequest:request
794                                                      delegate:_private->downloadDelegate
795                                                     directory:nil];
796     [request release];
797     
798     return download;
799 }
800
801 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
802 {
803     NSDictionary *features = [[NSDictionary alloc] init];
804     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
805                                             createWebViewWithRequest:nil
806                                                       windowFeatures:features];
807     [features release];
808     if (!newWindowWebView)
809         return nil;
810
811     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
812     return newWindowWebView;
813 }
814
815 - (WebInspector *)inspector
816 {
817     if (!_private->inspector)
818         _private->inspector = [[WebInspector alloc] initWithWebView:self];
819     return _private->inspector;
820 }
821
822 - (WebCore::Page*)page
823 {
824     return _private->page;
825 }
826
827 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
828 {
829     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
830
831     NSArray *menuItems = CallUIDelegate(self, @selector(webView:contextMenuItemsForElement:defaultMenuItems:), element, defaultMenuItems);
832     if (!menuItems)
833         return nil;
834
835     unsigned count = [menuItems count];
836     if (!count)
837         return nil;
838
839     NSMenu *menu = [[NSMenu alloc] init];
840     for (unsigned i = 0; i < count; i++)
841         [menu addItem:[menuItems objectAtIndex:i]];
842
843     return [menu autorelease];
844 }
845
846 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
847 {
848     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
849     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
850     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
851     if (!dictionary)
852         return;
853     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
854 }
855
856 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
857 {
858     if (!_private->page)
859         return;
860     
861     if (!otherView->_private->page)
862         return;
863     
864     // It turns out the right combination of behavior is done with the back/forward load
865     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
866     // in the back forward list, and go to the current one.
867
868     BackForwardList* backForwardList = _private->page->backForwardList();
869     ASSERT(!backForwardList->currentItem()); // destination list should be empty
870
871     BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
872     if (!otherBackForwardList->currentItem())
873         return; // empty back forward list, bail
874     
875     HistoryItem* newItemToGoTo = 0;
876
877     int lastItemIndex = otherBackForwardList->forwardListCount();
878     for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
879         if (i == 0) {
880             // If this item is showing , save away its current scroll and form state,
881             // since that might have changed since loading and it is normally not saved
882             // until we leave that page.
883             otherView->_private->page->mainFrame()->loader()->saveDocumentAndScrollState();
884         }
885         RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
886         if (i == 0) 
887             newItemToGoTo = newItem.get();
888         backForwardList->addItem(newItem.release());
889     }
890     
891     ASSERT(newItemToGoTo);
892     _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
893 }
894
895 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
896 {
897     _private->formDelegate = delegate;
898 }
899
900 - (id<WebFormDelegate>)_formDelegate
901 {
902     return _private->formDelegate;
903 }
904
905 - (BOOL)_needsAdobeFrameReloadingQuirk
906 {
907     static BOOL checked = NO;
908     static BOOL needsQuirk = NO;
909
910     if (checked)
911         return needsQuirk;
912
913     needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
914         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
915         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
916         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
917         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
918         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
919         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
920         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
921         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
922         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
923     checked = YES;
924
925     return needsQuirk;
926 }
927
928 - (BOOL)_needsKeyboardEventDisambiguationQuirks
929 {
930     static BOOL checked = NO;
931     static BOOL needsQuirks = NO;
932
933     if (checked)
934         return needsQuirks;
935
936     needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH)
937         && ![[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"];
938     checked = YES;
939
940     return needsQuirks;
941 }
942
943 - (void)_preferencesChangedNotification:(NSNotification *)notification
944 {
945     WebPreferences *preferences = (WebPreferences *)[notification object];
946     ASSERT(preferences == [self preferences]);
947     
948     if (!_private->userAgentOverridden)
949         *_private->userAgent = String();
950
951     // Cache this value so we don't have to read NSUserDefaults on each page load
952     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
953
954     // Update corresponding WebCore Settings object.
955     if (!_private->page)
956         return;
957     
958     Settings* settings = _private->page->settings();
959     
960     settings->setCursiveFontFamily([preferences cursiveFontFamily]);
961     settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
962     settings->setDefaultFontSize([preferences defaultFontSize]);
963     settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
964     settings->setFantasyFontFamily([preferences fantasyFontFamily]);
965     settings->setFixedFontFamily([preferences fixedFontFamily]);
966     settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
967     settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
968     settings->setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
969     settings->setJavaEnabled([preferences isJavaEnabled]);
970     settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
971     settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
972     settings->setMinimumFontSize([preferences minimumFontSize]);
973     settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
974     settings->setPluginsEnabled([preferences arePlugInsEnabled]);
975     settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
976     settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
977     settings->setSerifFontFamily([preferences serifFontFamily]);
978     settings->setStandardFontFamily([preferences standardFontFamily]);
979     settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
980     settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
981     settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
982     settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
983     settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
984     settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
985     settings->setUsesPageCache([self usesPageCache]);
986     settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
987     settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
988     settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
989     if ([preferences userStyleSheetEnabled]) {
990         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
991         settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
992     } else
993         settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
994     settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
995     settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
996     settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
997     settings->setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
998     settings->setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
999 }
1000
1001 static inline IMP getMethod(id o, SEL s)
1002 {
1003     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1004 }
1005
1006 - (void)_cacheResourceLoadDelegateImplementations
1007 {
1008     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1009     id delegate = _private->resourceProgressDelegate;
1010
1011     if (!delegate) {
1012         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1013         return;
1014     }
1015
1016     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1017     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1018     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1019     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1020     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1021     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1022     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1023     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1024     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1025     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1026     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1027 }
1028
1029 WebResourceDelegateImplementationCache* WebViewGetResourceLoadDelegateImplementations(WebView *webView)
1030 {
1031     static WebResourceDelegateImplementationCache empty;
1032     if (!webView)
1033         return &empty;
1034     return &webView->_private->resourceLoadDelegateImplementations;
1035 }
1036
1037 - (void)_cacheFrameLoadDelegateImplementations
1038 {
1039     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1040     id delegate = _private->frameLoadDelegate;
1041
1042     if (!delegate) {
1043         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1044         return;
1045     }
1046
1047     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1048     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1049     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1050     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1051     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1052     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1053     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1054     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1055     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1056     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1057     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1058     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1059     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1060     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1061     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1062     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1063     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1064 }
1065
1066 WebFrameLoadDelegateImplementationCache* WebViewGetFrameLoadDelegateImplementations(WebView *webView)
1067 {
1068     static WebFrameLoadDelegateImplementationCache empty;
1069     if (!webView)
1070         return &empty;
1071     return &webView->_private->frameLoadDelegateImplementations;
1072 }
1073
1074 - (id)_policyDelegateForwarder
1075 {
1076     if (!_private->policyDelegateForwarder)
1077         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1078     return _private->policyDelegateForwarder;
1079 }
1080
1081 - (id)_UIDelegateForwarder
1082 {
1083     if (!_private->UIDelegateForwarder)
1084         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1085     return _private->UIDelegateForwarder;
1086 }
1087
1088 - (id)_editingDelegateForwarder
1089 {
1090     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1091     // Not sure if that is a bug or not.
1092     if (!_private)
1093         return nil;
1094
1095     if (!_private->editingDelegateForwarder)
1096         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1097     return _private->editingDelegateForwarder;
1098 }
1099
1100 - (id)_scriptDebugDelegateForwarder
1101 {
1102     if (!_private->scriptDebugDelegateForwarder)
1103         _private->scriptDebugDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->scriptDebugDelegate defaultTarget:[WebDefaultScriptDebugDelegate sharedScriptDebugDelegate] catchExceptions:_private->catchesDelegateExceptions];
1104     return _private->scriptDebugDelegateForwarder;
1105 }
1106
1107 - (void)_closeWindow
1108 {
1109     [[self _UIDelegateForwarder] webViewClose:self];
1110 }
1111
1112 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType;
1113 {
1114     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1115     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1116     
1117     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1118     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1119     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1120     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1121 }
1122
1123 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
1124 {
1125     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1126     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1127
1128     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1129     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1130     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1131     if ([viewClass class] == [WebHTMLView class])
1132         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1133     
1134     // This is used to make _representationExistsForURLScheme faster.
1135     // Without this set, we'd have to create the MIME type each time.
1136     if (schemesWithRepresentationsSet == nil) {
1137         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1138     }
1139     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1140 }
1141
1142 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1143 {
1144     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1145 }
1146
1147 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1148 {
1149     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1150 }
1151
1152 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1153 {
1154     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed
1155     if (!request)
1156         return NO;
1157
1158     if ([NSURLConnection canHandleRequest:request])
1159         return YES;
1160
1161     NSString *scheme = [[request URL] scheme];
1162
1163     if ([self _representationExistsForURLScheme:scheme])
1164         return YES;
1165         
1166     return ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"]);
1167 }
1168
1169 + (NSString *)_decodeData:(NSData *)data
1170 {
1171     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1172     RefPtr<TextResourceDecoder> decoder = new TextResourceDecoder("text/html"); // bookmark files are HTML
1173     String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1174     result += decoder->flush();
1175     return result;
1176 }
1177
1178 - (void)_pushPerformingProgrammaticFocus
1179 {
1180     _private->programmaticFocusCount++;
1181 }
1182
1183 - (void)_popPerformingProgrammaticFocus
1184 {
1185     _private->programmaticFocusCount--;
1186 }
1187
1188 - (BOOL)_isPerformingProgrammaticFocus
1189 {
1190     return _private->programmaticFocusCount != 0;
1191 }
1192
1193 - (void)_didChangeValueForKey: (NSString *)key
1194 {
1195     LOG (Bindings, "calling didChangeValueForKey: %@", key);
1196     [self didChangeValueForKey: key];
1197 }
1198
1199 - (void)_willChangeValueForKey: (NSString *)key
1200 {
1201     LOG (Bindings, "calling willChangeValueForKey: %@", key);
1202     [self willChangeValueForKey: key];
1203 }
1204
1205 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1206     static NSSet *manualNotifyKeys = nil;
1207     if (!manualNotifyKeys)
1208         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1209             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1210     if ([manualNotifyKeys containsObject:key])
1211         return NO;
1212     return YES;
1213 }
1214
1215 - (NSArray *)_declaredKeys {
1216     static NSArray *declaredKeys = nil;
1217     if (!declaredKeys)
1218         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1219             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1220     return declaredKeys;
1221 }
1222
1223 - (void)setObservationInfo:(void *)info
1224 {
1225     _private->observationInfo = info;
1226 }
1227
1228 - (void *)observationInfo
1229 {
1230     return _private->observationInfo;
1231 }
1232
1233 - (void)_willChangeBackForwardKeys
1234 {
1235     [self _willChangeValueForKey: _WebCanGoBackKey];
1236     [self _willChangeValueForKey: _WebCanGoForwardKey];
1237 }
1238
1239 - (void)_didChangeBackForwardKeys
1240 {
1241     [self _didChangeValueForKey: _WebCanGoBackKey];
1242     [self _didChangeValueForKey: _WebCanGoForwardKey];
1243 }
1244
1245 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1246 {
1247     [self _willChangeBackForwardKeys];
1248     if (frame == [self mainFrame]){
1249         // Force an observer update by sending a will/did.
1250         [self _willChangeValueForKey: _WebIsLoadingKey];
1251         [self _didChangeValueForKey: _WebIsLoadingKey];
1252
1253         [self _willChangeValueForKey: _WebMainFrameURLKey];
1254     }
1255
1256     [NSApp setWindowsNeedUpdate:YES];
1257 }
1258
1259 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1260 {
1261     if (frame == [self mainFrame])
1262         [self _didChangeValueForKey: _WebMainFrameURLKey];
1263     [NSApp setWindowsNeedUpdate:YES];
1264 }
1265
1266 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1267 {
1268     [self _didChangeBackForwardKeys];
1269     if (frame == [self mainFrame]){
1270         // Force an observer update by sending a will/did.
1271         [self _willChangeValueForKey: _WebIsLoadingKey];
1272         [self _didChangeValueForKey: _WebIsLoadingKey];
1273     }
1274     [NSApp setWindowsNeedUpdate:YES];
1275 }
1276
1277 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1278 {
1279     [self _didChangeBackForwardKeys];
1280     if (frame == [self mainFrame]){
1281         // Force an observer update by sending a will/did.
1282         [self _willChangeValueForKey: _WebIsLoadingKey];
1283         [self _didChangeValueForKey: _WebIsLoadingKey];
1284     }
1285     [NSApp setWindowsNeedUpdate:YES];
1286 }
1287
1288 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1289 {
1290     [self _didChangeBackForwardKeys];
1291     if (frame == [self mainFrame]){
1292         // Force an observer update by sending a will/did.
1293         [self _willChangeValueForKey: _WebIsLoadingKey];
1294         [self _didChangeValueForKey: _WebIsLoadingKey];
1295         
1296         [self _didChangeValueForKey: _WebMainFrameURLKey];
1297     }
1298     [NSApp setWindowsNeedUpdate:YES];
1299 }
1300
1301 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1302 {
1303     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1304     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1305     NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1306     [request release];
1307     return cachedResponse;
1308 }
1309
1310 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1311 {
1312     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1313     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1314     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1315                         element:domElement
1316                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1317                           title:[element objectForKey:WebElementImageAltStringKey] 
1318                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1319                           types:types
1320                          source:nil];
1321 }
1322
1323 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1324 {
1325     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1326                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1327                         types:types];
1328 }
1329
1330 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1331 {
1332     if (!_private->page)
1333         return;
1334     _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
1335 }
1336
1337 #if ENABLE(DASHBOARD_SUPPORT)
1338
1339 #define DASHBOARD_CONTROL_LABEL @"control"
1340
1341 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1342 {
1343     // Add scroller regions for NSScroller and KWQScrollBar
1344     int i, count = [views count];
1345     
1346     for (i = 0; i < count; i++) {
1347         NSView *aView = [views objectAtIndex:i];
1348         
1349         if ([aView isKindOfClass:[NSScroller class]] ||
1350             [aView isKindOfClass:NSClassFromString (@"KWQScrollBar")]) {
1351             NSRect bounds = [aView bounds];
1352             NSRect adjustedBounds;
1353             adjustedBounds.origin = [self convertPoint:bounds.origin fromView:aView];
1354             adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1355             
1356             // AppKit has horrible hack of placing absent scrollers at -100,-100
1357             if (adjustedBounds.origin.y == -100)
1358                 continue;
1359             adjustedBounds.size = bounds.size;
1360             NSRect clip = [aView visibleRect];
1361             NSRect adjustedClip;
1362             adjustedClip.origin = [self convertPoint:clip.origin fromView:aView];
1363             adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1364             adjustedClip.size = clip.size;
1365             WebDashboardRegion *aRegion = 
1366                         [[[WebDashboardRegion alloc] initWithRect:adjustedBounds 
1367                                     clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle] autorelease];
1368             NSMutableArray *scrollerRegions;
1369             scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1370             if (!scrollerRegions) {
1371                 scrollerRegions = [NSMutableArray array];
1372                 [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1373             }
1374             [scrollerRegions addObject:aRegion];
1375         }
1376         [self _addScrollerDashboardRegions:regions from:[aView subviews]];
1377     }
1378 }
1379
1380 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1381 {
1382     [self _addScrollerDashboardRegions:regions from:[self subviews]];
1383 }
1384
1385 - (NSDictionary *)_dashboardRegions
1386 {
1387     // Only return regions from main frame.
1388     Frame* mainFrame = core([self mainFrame]);
1389     if (!mainFrame)
1390         return nil;
1391     NSMutableDictionary *regions = mainFrame->dashboardRegionsDictionary();
1392     [self _addScrollerDashboardRegions:regions];
1393     return regions;
1394 }
1395
1396 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
1397 {
1398     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
1399     // specific support for the backward compatibility mode flag.
1400     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
1401         _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
1402     
1403     switch (behavior) {
1404         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1405             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1406             break;
1407         }
1408         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1409             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1410             break;
1411         }
1412         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1413             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1414             break;
1415         }
1416         case WebDashboardBehaviorAllowWheelScrolling: {
1417             _private->dashboardBehaviorAllowWheelScrolling = flag;
1418             break;
1419         }
1420         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1421             if (_private->page)
1422                 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
1423             break;
1424         }
1425     }
1426 }
1427
1428 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1429 {
1430     switch (behavior) {
1431         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1432             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1433         }
1434         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1435             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1436         }
1437         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1438             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1439         }
1440         case WebDashboardBehaviorAllowWheelScrolling: {
1441             return _private->dashboardBehaviorAllowWheelScrolling;
1442         }
1443         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1444             return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
1445         }
1446     }
1447     return NO;
1448 }
1449
1450 #endif /* ENABLE(DASHBOARD_SUPPORT) */
1451
1452 + (void)_setShouldUseFontSmoothing:(BOOL)f
1453 {
1454     WebCoreSetShouldUseFontSmoothing(f);
1455 }
1456
1457 + (BOOL)_shouldUseFontSmoothing
1458 {
1459     return WebCoreShouldUseFontSmoothing();
1460 }
1461
1462 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
1463 {
1464     setUsesTestModeFocusRingColor(f);
1465 }
1466
1467 + (BOOL)_usesTestModeFocusRingColor
1468 {
1469     return usesTestModeFocusRingColor();
1470 }
1471
1472 // This is only used by versions of Safari up to and including 3.0 and should be removed in a future release. 
1473 + (NSString *)_minimumRequiredSafariBuildNumber
1474 {
1475     return @"420+";
1476 }
1477
1478 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1479 {
1480     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1481     if (flag) {
1482         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
1483     } else {
1484         [scrollview setVerticalScrollingModeLocked:NO];
1485         [scrollview setVerticalScrollingMode:ScrollbarAuto];
1486     }
1487 }
1488
1489 - (BOOL)alwaysShowVerticalScroller
1490 {
1491     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1492     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
1493 }
1494
1495 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1496 {
1497     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1498     if (flag) {
1499         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
1500     } else {
1501         [scrollview setHorizontalScrollingModeLocked:NO];
1502         [scrollview setHorizontalScrollingMode:ScrollbarAuto];
1503     }
1504 }
1505
1506 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1507 {
1508     Frame* mainFrame = core([self mainFrame]);
1509     if (mainFrame)
1510         mainFrame->setProhibitsScrolling(prohibits);
1511 }
1512
1513 - (BOOL)alwaysShowHorizontalScroller
1514 {
1515     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1516     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
1517 }
1518
1519 - (void)_setInViewSourceMode:(BOOL)flag
1520 {
1521     Frame* mainFrame = core([self mainFrame]);
1522     if (mainFrame)
1523         mainFrame->setInViewSourceMode(flag);
1524 }
1525
1526 - (BOOL)_inViewSourceMode
1527 {
1528     Frame* mainFrame = core([self mainFrame]);
1529     return mainFrame && mainFrame->inViewSourceMode();
1530 }
1531
1532 - (void)_setUseFastImageScalingMode:(BOOL)flag
1533 {
1534     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
1535         _private->page->setInLowQualityImageInterpolationMode(flag);
1536         [self setNeedsDisplay:YES];
1537     }
1538 }
1539
1540 - (BOOL)_inFastImageScalingMode
1541 {
1542     if (_private->page)
1543         return _private->page->inLowQualityImageInterpolationMode();
1544     return NO;
1545 }
1546
1547 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1548 {
1549     if (!_private->pluginDatabase)
1550         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1551         
1552     [_private->pluginDatabase setPlugInPaths:newPaths];
1553     [_private->pluginDatabase refresh];
1554 }
1555
1556 - (void)_attachScriptDebuggerToAllFrames
1557 {
1558     for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1559         [kit(frame) _attachScriptDebugger];
1560 }
1561
1562 - (void)_detachScriptDebuggerFromAllFrames
1563 {
1564     for (Frame* frame = core([self mainFrame]); frame; frame = frame->tree()->traverseNext())
1565         [kit(frame) _detachScriptDebugger];
1566 }
1567
1568 - (void)setBackgroundColor:(NSColor *)backgroundColor
1569 {
1570     if ([_private->backgroundColor isEqual:backgroundColor])
1571         return;
1572
1573     id old = _private->backgroundColor;
1574     _private->backgroundColor = [backgroundColor retain];
1575     [old release];
1576
1577     [[self mainFrame] _updateBackground];
1578 }
1579
1580 - (NSColor *)backgroundColor
1581 {
1582     return _private->backgroundColor;
1583 }
1584
1585 - (BOOL)defersCallbacks
1586 {
1587     if (!_private->page)
1588         return NO;
1589     return _private->page->defersLoading();
1590 }
1591
1592 - (void)setDefersCallbacks:(BOOL)defer
1593 {
1594     if (!_private->page)
1595         return;
1596     return _private->page->setDefersLoading(defer);
1597 }
1598
1599 // For backwards compatibility with the WebBackForwardList API, we honor both
1600 // a per-WebView and a per-preferences setting for whether to use the page cache.
1601
1602 - (BOOL)usesPageCache
1603 {
1604     return _private->usesPageCache && [[self preferences] usesPageCache];
1605 }
1606
1607 - (void)setUsesPageCache:(BOOL)usesPageCache
1608 {
1609     _private->usesPageCache = usesPageCache;
1610
1611     // Post a notification so the WebCore settings update.
1612     [[self preferences] _postPreferencesChangesNotification];
1613 }
1614
1615 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource 
1616 {
1617     NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window]; 
1618     [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window]; 
1619
1620
1621 - (void)_clearUndoRedoOperations
1622 {
1623     if (!_private->page)
1624         return;
1625     _private->page->clearUndoRedoOperations();
1626 }
1627
1628 - (void)_setCatchesDelegateExceptions:(BOOL)f
1629 {
1630     _private->catchesDelegateExceptions = f;
1631 }
1632
1633 - (BOOL)_catchesDelegateExceptions
1634 {
1635     return _private->catchesDelegateExceptions;
1636 }
1637
1638 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
1639 {
1640     Frame* coreFrame = core([self mainFrame]);
1641     if (!coreFrame)
1642         return;
1643     coreFrame->editor()->command(name).execute(value);
1644 }
1645
1646 @end
1647
1648 @implementation _WebSafeForwarder
1649
1650 // Used to send messages to delegates that implement informal protocols.
1651
1652 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
1653 {
1654     self = [super init];
1655     if (!self)
1656         return nil;
1657     target = t; // Non retained.
1658     defaultTarget = dt;
1659     catchExceptions = c;
1660     return self;
1661 }
1662
1663 - (void)forwardInvocation:(NSInvocation *)invocation
1664 {
1665     if ([target respondsToSelector:[invocation selector]]) {
1666         if (catchExceptions) {
1667             @try {
1668                 [invocation invokeWithTarget:target];
1669             } @catch(id exception) {
1670                 ReportDiscardedDelegateException([invocation selector], exception);
1671             }
1672         } else
1673             [invocation invokeWithTarget:target];
1674         return;
1675     }
1676
1677     if ([defaultTarget respondsToSelector:[invocation selector]])
1678         [invocation invokeWithTarget:defaultTarget];
1679
1680     // Do nothing quietly if method not implemented.
1681 }
1682
1683 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
1684 {
1685     return [defaultTarget methodSignatureForSelector:aSelector];
1686 }
1687
1688 @end
1689
1690 @implementation WebView
1691
1692 + (void)initialize
1693 {
1694     static BOOL initialized = NO;
1695     if (initialized)
1696         return;
1697     initialized = YES;
1698
1699     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
1700     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedNotification object:nil];
1701     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];
1702 }
1703
1704 + (void)_applicationWillTerminate
1705 {   
1706     applicationIsTerminating = YES;
1707     if (!pluginDatabaseClientCount)
1708         [WebPluginDatabase closeSharedDatabase];
1709 }
1710
1711 + (BOOL)canShowMIMEType:(NSString *)MIMEType
1712 {
1713     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType];
1714 }
1715
1716 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
1717 {
1718     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
1719     if (pluginPackage)
1720         return pluginPackage;
1721     
1722     if (_private->pluginDatabase)
1723         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
1724     
1725     return nil;
1726 }
1727
1728 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
1729 {
1730     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
1731     if (pluginPackage)
1732         return pluginPackage;
1733     
1734     if (_private->pluginDatabase)
1735         return [_private->pluginDatabase pluginForExtension:extension];
1736     
1737     return nil;
1738 }
1739
1740 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
1741 {
1742     if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
1743         return YES;
1744         
1745     if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
1746         return YES;
1747     
1748     return NO;
1749 }
1750
1751 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
1752 {
1753     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
1754 }
1755
1756 + (NSArray *)MIMETypesShownAsHTML
1757 {
1758     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
1759     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1760     id key;
1761     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
1762     
1763     while ((key = [enumerator nextObject])) {
1764         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1765             [array addObject:key];
1766     }
1767     
1768     return array;
1769 }
1770
1771 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
1772 {
1773     NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
1774     NSEnumerator *enumerator = [viewTypes keyEnumerator];
1775     id key;
1776     while ((key = [enumerator nextObject])) {
1777         if ([viewTypes objectForKey:key] == [WebHTMLView class])
1778             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
1779     }
1780     
1781     int i, count = [MIMETypes count];
1782     for (i = 0; i < count; i++) {
1783         [WebView registerViewClass:[WebHTMLView class] 
1784                 representationClass:[WebHTMLRepresentation class] 
1785                 forMIMEType:[MIMETypes objectAtIndex:i]];
1786     }
1787     [viewTypes release];
1788 }
1789
1790 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
1791 {
1792     return [pasteboard _web_bestURL];
1793 }
1794
1795 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
1796 {
1797     return [pasteboard stringForType:WebURLNamePboardType];
1798 }
1799
1800 + (void)registerURLSchemeAsLocal:(NSString *)protocol
1801 {
1802     FrameLoader::registerURLSchemeAsLocal(protocol);
1803 }
1804
1805 - (void)_registerDraggedTypes
1806 {
1807     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1808     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1809     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1810     [types addObjectsFromArray:URLTypes];
1811     [self registerForDraggedTypes:[types allObjects]];
1812     [types release];
1813 }
1814
1815 static void WebKitInitializeApplicationCachePathIfNecessary()
1816 {
1817     static BOOL initialized = NO;
1818     if (initialized)
1819         return;
1820
1821     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
1822     if (!appName)
1823         appName = [[NSProcessInfo processInfo] processName];
1824     
1825     ASSERT(appName);
1826
1827     NSString* cacheDir = nil;
1828     
1829 #ifdef BUILDING_ON_TIGER
1830     cacheDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
1831 #else
1832     char cacheDirectory[MAXPATHLEN];
1833     size_t cacheDirectoryLen = confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDirectory, MAXPATHLEN);
1834     
1835     if (cacheDirectoryLen)
1836         cacheDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:cacheDirectory length:cacheDirectoryLen - 1];
1837 #endif
1838
1839     cacheDir = [cacheDir stringByAppendingPathComponent:appName];    
1840
1841     cacheStorage().setCacheDirectory(cacheDir);
1842     initialized = YES;
1843 }
1844
1845 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1846 {
1847     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1848     [standardPreferences willAddToWebView];
1849
1850     _private->preferences = [standardPreferences retain];
1851     _private->catchesDelegateExceptions = YES;
1852     _private->mainFrameDocumentReady = NO;
1853     _private->drawsBackground = YES;
1854     _private->smartInsertDeleteEnabled = YES;
1855     _private->backgroundColor = [[NSColor whiteColor] retain];
1856
1857     NSRect f = [self frame];
1858     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1859     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1860     [self addSubview:frameView];
1861     [frameView release];
1862
1863     WebKitInitializeLoggingChannelsIfNecessary();
1864     WebCore::InitializeLoggingChannelsIfNecessary();
1865     [WebHistoryItem initWindowWatcherIfNecessary];
1866     WebKitInitializeDatabasesIfNecessary();
1867     WebKitInitializeApplicationCachePathIfNecessary();
1868     
1869     _private->page = new Page(new WebChromeClient(self), new WebContextMenuClient(self), new WebEditorClient(self), new WebDragClient(self), new WebInspectorClient(self));
1870
1871     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1872
1873 #ifndef BUILDING_ON_TIGER
1874     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1875         [self scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
1876     else
1877         [self scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
1878 #endif
1879
1880     [self _addToAllWebViewsSet];
1881     [self setGroupName:groupName];
1882     
1883     // If there's already a next key view (e.g., from a nib), wire it up to our
1884     // contained frame view. In any case, wire our next key view up to the our
1885     // contained frame view. This works together with our becomeFirstResponder 
1886     // and setNextKeyView overrides.
1887     NSView *nextKeyView = [self nextKeyView];
1888     if (nextKeyView && nextKeyView != frameView)
1889         [frameView setNextKeyView:nextKeyView];
1890     [super setNextKeyView:frameView];
1891
1892     ++WebViewCount;
1893
1894     [self _registerDraggedTypes];
1895
1896     // initialize WebScriptDebugServer here so listeners can register before any pages are loaded.
1897     if ([WebView _scriptDebuggerEnabled])
1898         [WebScriptDebugServer sharedScriptDebugServer];
1899
1900     WebPreferences *prefs = [self preferences];
1901     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1902                                                  name:WebPreferencesChangedNotification object:prefs];
1903
1904     // Post a notification so the WebCore settings update.
1905     [[self preferences] _postPreferencesChangesNotification];
1906
1907
1908     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION))
1909         FrameLoader::setRestrictAccessToLocal(false);
1910 }
1911
1912 - (id)initWithFrame:(NSRect)f
1913 {
1914     return [self initWithFrame:f frameName:nil groupName:nil];
1915 }
1916
1917 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName;
1918 {
1919     self = [super initWithFrame:f];
1920     if (!self)
1921         return nil;
1922
1923 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1924     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1925     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1926     // need for Safari to unset it to prevent it from being passed to applications it launches.
1927     // Unsetting it when a WebView is first created is as good a place as any.
1928     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1929     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1930         unsetenv("DYLD_FRAMEWORK_PATH");
1931         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1932     }
1933 #endif
1934
1935     _private = [[WebViewPrivate alloc] init];
1936     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1937     [self setMaintainsBackForwardList: YES];
1938     return self;
1939 }
1940
1941 - (id)initWithCoder:(NSCoder *)decoder
1942 {
1943     WebView *result = nil;
1944
1945     @try {
1946         NSString *frameName;
1947         NSString *groupName;
1948         WebPreferences *preferences;
1949         BOOL useBackForwardList = NO;
1950         BOOL allowsUndo = YES;
1951         
1952         result = [super initWithCoder:decoder];
1953         result->_private = [[WebViewPrivate alloc] init];
1954
1955         // We don't want any of the archived subviews. The subviews will always
1956         // be created in _commonInitializationFrameName:groupName:.
1957         [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
1958
1959         if ([decoder allowsKeyedCoding]) {
1960             frameName = [decoder decodeObjectForKey:@"FrameName"];
1961             groupName = [decoder decodeObjectForKey:@"GroupName"];
1962             preferences = [decoder decodeObjectForKey:@"Preferences"];
1963             useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
1964             if ([decoder containsValueForKey:@"AllowsUndo"])
1965                 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
1966         } else {
1967             int version;
1968             [decoder decodeValueOfObjCType:@encode(int) at:&version];
1969             frameName = [decoder decodeObject];
1970             groupName = [decoder decodeObject];
1971             preferences = [decoder decodeObject];
1972             if (version > 1)
1973                 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
1974             // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
1975             // version 3 NIBs that have this field encoded, we still need to read it in.
1976             if (version == 3)
1977                 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
1978         }
1979
1980         if (![frameName isKindOfClass:[NSString class]])
1981             frameName = nil;
1982         if (![groupName isKindOfClass:[NSString class]])
1983             groupName = nil;
1984         if (![preferences isKindOfClass:[WebPreferences class]])
1985             preferences = nil;
1986
1987         LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
1988         [result _commonInitializationWithFrameName:frameName groupName:groupName];
1989         [result page]->backForwardList()->setEnabled(useBackForwardList);
1990         result->_private->allowsUndo = allowsUndo;
1991         if (preferences)
1992             [result setPreferences:preferences];
1993     } @catch (NSException *localException) {
1994         result = nil;
1995         [self release];
1996     }
1997
1998     return result;
1999 }
2000
2001 - (void)encodeWithCoder:(NSCoder *)encoder
2002 {
2003     // Set asside the subviews before we archive. We don't want to archive any subviews.
2004     // The subviews will always be created in _commonInitializationFrameName:groupName:.
2005     id originalSubviews = _subviews;
2006     _subviews = nil;
2007
2008     [super encodeWithCoder:encoder];
2009
2010     // Restore the subviews we set aside.
2011     _subviews = originalSubviews;
2012
2013     BOOL useBackForwardList = _private->page && _private->page->backForwardList()->enabled();
2014     if ([encoder allowsKeyedCoding]) {
2015         [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
2016         [encoder encodeObject:[self groupName] forKey:@"GroupName"];
2017         [encoder encodeObject:[self preferences] forKey:@"Preferences"];
2018         [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
2019         [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
2020     } else {
2021         int version = WebViewVersion;
2022         [encoder encodeValueOfObjCType:@encode(int) at:&version];
2023         [encoder encodeObject:[[self mainFrame] name]];
2024         [encoder encodeObject:[self groupName]];
2025         [encoder encodeObject:[self preferences]];
2026         [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
2027         // DO NOT encode any new fields here, doing so will break older WebKit releases.
2028     }
2029
2030     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
2031 }
2032
2033 - (void)dealloc
2034 {
2035     // call close to ensure we tear-down completely
2036     // this maintains our old behavior for existing applications
2037     [self _close];
2038
2039     --WebViewCount;
2040     
2041     [_private release];
2042     // [super dealloc] can end up dispatching against _private (3466082)
2043     _private = nil;
2044
2045     [super dealloc];
2046 }
2047
2048 - (void)finalize
2049 {
2050     ASSERT(_private->closed);
2051
2052     --WebViewCount;
2053
2054     [super finalize];
2055 }
2056
2057 - (void)close
2058 {
2059     [self _close];
2060 }
2061
2062 - (void)setShouldCloseWithWindow:(BOOL)close
2063 {
2064     _private->shouldCloseWithWindow = close;
2065 }
2066
2067 - (BOOL)shouldCloseWithWindow
2068 {
2069     return _private->shouldCloseWithWindow;
2070 }
2071
2072 - (void)viewWillMoveToWindow:(NSWindow *)window
2073 {
2074     // Don't do anything if we aren't initialized.  This happens when decoding a WebView.
2075     if (!_private)
2076         return;
2077     
2078     if ([self window])
2079         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
2080
2081     if (window) {
2082         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
2083
2084         // Ensure that we will receive the events that WebHTMLView (at least) needs. It's expensive enough
2085         // that we don't want to call it over and over.
2086         [window setAcceptsMouseMovedEvents:YES];
2087         WKSetNSWindowShouldPostEventNotifications(window, YES);
2088     }
2089 }
2090
2091 - (void)_windowWillClose:(NSNotification *)notification
2092 {
2093     if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
2094         [self _close];
2095 }
2096
2097 - (void)setPreferences:(WebPreferences *)prefs
2098 {
2099     if (!prefs)
2100         prefs = [WebPreferences standardPreferences];
2101
2102     if (_private->preferences == prefs)
2103         return;
2104
2105     [prefs willAddToWebView];
2106
2107     WebPreferences *oldPrefs = _private->preferences;
2108
2109     [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
2110     [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
2111
2112     _private->preferences = [prefs retain];
2113
2114     // After registering for the notification, post it so the WebCore settings update.
2115     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
2116         name:WebPreferencesChangedNotification object:[self preferences]];
2117     [[self preferences] _postPreferencesChangesNotification];
2118
2119     [oldPrefs didRemoveFromWebView];
2120     [oldPrefs release];
2121 }
2122
2123 - (WebPreferences *)preferences
2124 {
2125     return _private->preferences;
2126 }
2127
2128 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
2129 {
2130     if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
2131         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
2132         [self setPreferences:prefs];
2133         [prefs release];
2134     }
2135 }
2136
2137 - (NSString *)preferencesIdentifier
2138 {
2139     return [[self preferences] identifier];
2140 }
2141
2142
2143 - (void)setUIDelegate:delegate
2144 {
2145     _private->UIDelegate = delegate;
2146     [_private->UIDelegateForwarder release];
2147     _private->UIDelegateForwarder = nil;
2148 }
2149
2150 - UIDelegate
2151 {
2152     return _private->UIDelegate;
2153 }
2154
2155 - (void)setResourceLoadDelegate: delegate
2156 {
2157     _private->resourceProgressDelegate = delegate;
2158     [self _cacheResourceLoadDelegateImplementations];
2159 }
2160
2161 - resourceLoadDelegate
2162 {
2163     return _private->resourceProgressDelegate;
2164 }
2165
2166 - (void)setDownloadDelegate: delegate
2167 {
2168     _private->downloadDelegate = delegate;
2169 }
2170
2171
2172 - downloadDelegate
2173 {
2174     return _private->downloadDelegate;
2175 }
2176
2177 - (void)setPolicyDelegate:delegate
2178 {
2179     _private->policyDelegate = delegate;
2180     [_private->policyDelegateForwarder release];
2181     _private->policyDelegateForwarder = nil;
2182 }
2183
2184 - policyDelegate
2185 {
2186     return _private->policyDelegate;
2187 }
2188
2189 - (void)setFrameLoadDelegate:delegate
2190 {
2191     _private->frameLoadDelegate = delegate;
2192     [self _cacheFrameLoadDelegateImplementations];
2193
2194     // If this delegate wants callbacks for icons, fire up the icon database.
2195     if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
2196         [WebIconDatabase sharedIconDatabase];
2197 }
2198
2199 - frameLoadDelegate
2200 {
2201     return _private->frameLoadDelegate;
2202 }
2203
2204 - (WebFrame *)mainFrame
2205 {
2206     // This can be called in initialization, before _private has been set up (3465613)
2207     if (!_private)
2208         return nil;
2209     if (!_private->page)
2210         return nil;
2211     return kit(_private->page->mainFrame());
2212 }
2213
2214 - (WebFrame *)selectedFrame
2215 {
2216     // If the first responder is a view in our tree, we get the frame containing the first responder.
2217     // This is faster than searching the frame hierarchy, and will give us a result even in the case
2218     // where the focused frame doesn't actually contain a selection.
2219     WebFrame *focusedFrame = [self _focusedFrame];
2220     if (focusedFrame)
2221         return focusedFrame;
2222     
2223     // If the first responder is outside of our view tree, we search for a frame containing a selection.
2224     // There should be at most only one of these.
2225     return [[self mainFrame] _findFrameWithSelection];
2226 }
2227
2228 - (WebBackForwardList *)backForwardList
2229 {
2230     if (!_private->page)
2231         return nil;
2232     if (!_private->page->backForwardList()->enabled())
2233         return nil;
2234     return kit(_private->page->backForwardList());
2235 }
2236
2237 - (void)setMaintainsBackForwardList: (BOOL)flag
2238 {
2239     if (!_private->page)
2240         return;
2241     _private->page->backForwardList()->setEnabled(flag);
2242 }
2243
2244 - (BOOL)goBack
2245 {
2246     if (!_private->page)
2247         return NO;
2248     
2249     return _private->page->goBack();
2250 }
2251
2252 - (BOOL)goForward
2253 {
2254     if (!_private->page)
2255         return NO;
2256
2257     return _private->page->goForward();
2258 }
2259
2260 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
2261 {
2262     if (!_private->page)
2263         return NO;
2264
2265     _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
2266     return YES;
2267 }
2268
2269 - (void)setTextSizeMultiplier:(float)m
2270 {
2271     [self _setZoomMultiplier:m isTextOnly:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2272 }
2273
2274 - (float)textSizeMultiplier
2275 {
2276     return _private->zoomMultiplierIsTextOnly ? _private->zoomMultiplier : 1.0f;
2277 }
2278
2279 - (void)_setZoomMultiplier:(float)m isTextOnly:(BOOL)isTextOnly
2280 {
2281     // NOTE: This has no visible effect when viewing a PDF (see <rdar://problem/4737380>)
2282     _private->zoomMultiplier = m;
2283     _private->zoomMultiplierIsTextOnly = isTextOnly;
2284     Frame* coreFrame = core([self mainFrame]);
2285     if (coreFrame)
2286         coreFrame->setZoomFactor(m, isTextOnly);
2287 }
2288
2289 - (float)_zoomMultiplier:(BOOL)isTextOnly
2290 {
2291     if (isTextOnly != _private->zoomMultiplierIsTextOnly)
2292         return 1.0f;
2293     return _private->zoomMultiplier;
2294 }
2295
2296 - (float)_realZoomMultiplier
2297 {
2298     return _private->zoomMultiplier;
2299 }
2300
2301 - (BOOL)_realZoomMultiplierIsTextOnly
2302 {
2303     return _private->zoomMultiplierIsTextOnly;
2304 }
2305
2306 #define MinimumZoomMultiplier       0.5f
2307 #define MaximumZoomMultiplier       3.0f
2308 #define ZoomMultiplierRatio         1.2f
2309
2310 - (BOOL)_canZoomOut:(BOOL)isTextOnly
2311 {
2312     id docView = [[[self mainFrame] frameView] documentView];
2313     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2314         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2315         return [zoomingDocView _canZoomOut];
2316     }
2317     return [self _zoomMultiplier:isTextOnly] / ZoomMultiplierRatio > MinimumZoomMultiplier;
2318 }
2319
2320
2321 - (BOOL)_canZoomIn:(BOOL)isTextOnly
2322 {
2323     id docView = [[[self mainFrame] frameView] documentView];
2324     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2325         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2326         return [zoomingDocView _canZoomIn];
2327     }
2328     return [self _zoomMultiplier:isTextOnly] * ZoomMultiplierRatio < MaximumZoomMultiplier;
2329 }
2330
2331 - (IBAction)_zoomOut:(id)sender isTextOnly:(BOOL)isTextOnly
2332 {
2333     id docView = [[[self mainFrame] frameView] documentView];
2334     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2335         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2336         return [zoomingDocView _zoomOut:sender];
2337     }
2338     float newScale = [self _zoomMultiplier:isTextOnly] / ZoomMultiplierRatio;
2339     if (newScale > MinimumZoomMultiplier)
2340         [self _setZoomMultiplier:newScale isTextOnly:isTextOnly];
2341 }
2342
2343 - (IBAction)_zoomIn:(id)sender isTextOnly:(BOOL)isTextOnly
2344 {
2345     id docView = [[[self mainFrame] frameView] documentView];
2346     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2347         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2348         return [zoomingDocView _zoomIn:sender];
2349     }
2350     float newScale = [self _zoomMultiplier:isTextOnly] * ZoomMultiplierRatio;
2351     if (newScale < MaximumZoomMultiplier)
2352         [self _setZoomMultiplier:newScale isTextOnly:isTextOnly];
2353 }
2354
2355 - (BOOL)_canResetZoom:(BOOL)isTextOnly
2356 {
2357     id docView = [[[self mainFrame] frameView] documentView];
2358     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2359         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2360         return [zoomingDocView _canResetZoom];
2361     }
2362     return [self _zoomMultiplier:isTextOnly] != 1.0f;
2363 }
2364
2365 - (IBAction)_resetZoom:(id)sender isTextOnly:(BOOL)isTextOnly
2366 {
2367     id docView = [[[self mainFrame] frameView] documentView];
2368     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
2369         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
2370         return [zoomingDocView _resetZoom:sender];
2371     }
2372     if ([self _zoomMultiplier:isTextOnly] != 1.0f)
2373         [self _setZoomMultiplier:1.0f isTextOnly:isTextOnly];
2374 }
2375
2376 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
2377 {
2378     NSString *name = [applicationName copy];
2379     [_private->applicationNameForUserAgent release];
2380     _private->applicationNameForUserAgent = name;
2381     if (!_private->userAgentOverridden)
2382         *_private->userAgent = String();
2383 }
2384
2385 - (NSString *)applicationNameForUserAgent
2386 {
2387     return [[_private->applicationNameForUserAgent retain] autorelease];
2388 }
2389
2390 - (void)setCustomUserAgent:(NSString *)userAgentString
2391 {
2392     *_private->userAgent = userAgentString;
2393     _private->userAgentOverridden = userAgentString != nil;
2394 }
2395
2396 - (NSString *)customUserAgent
2397 {
2398     if (!_private->userAgentOverridden)
2399         return nil;
2400     return *_private->userAgent;
2401 }
2402
2403 - (void)setMediaStyle:(NSString *)mediaStyle
2404 {
2405     if (_private->mediaStyle != mediaStyle) {
2406         [_private->mediaStyle release];
2407         _private->mediaStyle = [mediaStyle copy];
2408     }
2409 }
2410
2411 - (NSString *)mediaStyle
2412 {
2413     return _private->mediaStyle;
2414 }
2415
2416 - (BOOL)supportsTextEncoding
2417 {
2418     id documentView = [[[self mainFrame] frameView] documentView];
2419     return [documentView conformsToProtocol:@protocol(WebDocumentText)]
2420         && [documentView supportsTextEncoding];
2421 }
2422
2423 - (void)setCustomTextEncodingName:(NSString *)encoding
2424 {
2425     NSString *oldEncoding = [self customTextEncodingName];
2426     if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding])
2427         return;
2428     if (Frame* mainFrame = core([self mainFrame]))
2429         mainFrame->loader()->reloadAllowingStaleData(encoding);
2430 }
2431
2432 - (NSString *)_mainFrameOverrideEncoding
2433 {
2434     WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
2435     if (dataSource == nil)
2436         dataSource = [[self mainFrame] _dataSource];
2437     if (dataSource == nil)
2438         return nil;
2439     return nsStringNilIfEmpty([dataSource _documentLoader]->overrideEncoding());
2440 }
2441
2442 - (NSString *)customTextEncodingName
2443 {
2444     return [self _mainFrameOverrideEncoding];
2445 }
2446
2447 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
2448 {
2449     // Return statements are only valid in a function but some applications pass in scripts
2450     // prefixed with return (<rdar://problems/5103720&4616860>) since older WebKit versions
2451     // silently ignored the return. If the application is linked against an earlier version
2452     // of WebKit we will strip the return so the script wont fail.
2453     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_JAVASCRIPT_RETURN_QUIRK)) {
2454         NSRange returnStringRange = [script rangeOfString:@"return "];
2455         if (returnStringRange.length && !returnStringRange.location)
2456             script = [script substringFromIndex:returnStringRange.location + returnStringRange.length];
2457     }
2458
2459     NSString *result = [[self mainFrame] _stringByEvaluatingJavaScriptFromString:script];
2460     // The only way stringByEvaluatingJavaScriptFromString can return nil is if the frame was removed by the script
2461     // Since there's no way to get rid of the main frame, result will never ever be nil here.
2462     ASSERT(result);
2463
2464     return result;
2465 }
2466
2467 - (WebScriptObject *)windowScriptObject
2468 {
2469     Frame* coreFrame = core([self mainFrame]);
2470     if (!coreFrame)
2471         return nil;
2472     return coreFrame->windowScriptObject();
2473 }
2474
2475 // Get the appropriate user-agent string for a particular URL.
2476 - (NSString *)userAgentForURL:(NSURL *)url
2477 {
2478     return [self _userAgentForURL:KURL([url absoluteURL])];
2479 }
2480
2481 - (void)setHostWindow:(NSWindow *)hostWindow
2482 {
2483     if (!_private->closed && hostWindow != _private->hostWindow) {
2484         Frame* coreFrame = core([self mainFrame]);
2485         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame))
2486             [[[kit(frame) frameView] documentView] viewWillMoveToHostWindow:hostWindow];
2487         if (_private->hostWindow)
2488             [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
2489         if (hostWindow)
2490             [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
2491         [_private->hostWindow release];
2492         _private->hostWindow = [hostWindow retain];
2493         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame))
2494             [[[kit(frame) frameView] documentView] viewDidMoveToHostWindow];
2495     }
2496 }
2497
2498 - (NSWindow *)hostWindow
2499 {
2500     return _private->hostWindow;
2501 }
2502
2503 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
2504 {
2505     return [[self _frameViewAtWindowPoint:point] documentView];
2506 }
2507
2508 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
2509 {
2510     WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
2511     if (!frameView)
2512         return nil;
2513     NSView <WebDocumentView> *documentView = [frameView documentView];
2514     if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
2515         NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
2516         return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
2517     }
2518     return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
2519 }
2520
2521 - (NSDictionary *)elementAtPoint:(NSPoint)point
2522 {
2523     return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
2524 }
2525
2526 // The following 2 internal NSView methods are called on the drag destination by make scrolling while dragging work.
2527 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination. 
2528 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination. 
2529 // Forward these calls to the document subview to make its scroll view scroll.
2530 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
2531 {
2532     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2533     [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
2534 }
2535
2536 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
2537 {
2538     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2539     return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
2540 }
2541
2542 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
2543 {
2544     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2545     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2546     IntPoint client([draggingInfo draggingLocation]);
2547     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2548     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2549     return core(self)->dragController()->dragEntered(&dragData);
2550 }
2551
2552 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
2553 {
2554     Page* page = core(self);
2555     if (!page)
2556         return NSDragOperationNone;
2557
2558     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2559     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2560     IntPoint client([draggingInfo draggingLocation]);
2561     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2562     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2563     return page->dragController()->dragUpdated(&dragData);
2564 }
2565
2566 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
2567 {
2568     Page* page = core(self);
2569     if (!page)
2570         return;
2571
2572     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2573     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
2574     IntPoint client([draggingInfo draggingLocation]);
2575     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2576     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2577     page->dragController()->dragExited(&dragData);
2578 }
2579
2580 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
2581 {
2582     return YES;
2583 }
2584
2585 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
2586 {
2587     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
2588     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]]? (WebHTMLView*)view : nil);
2589     IntPoint client([draggingInfo draggingLocation]);
2590     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
2591     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
2592     return core(self)->dragController()->performDrag(&dragData);
2593 }
2594
2595 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types
2596 {
2597     NSView *hitView = [super _hitTest:aPoint dragTypes:types];
2598     if (!hitView && [[self superview] mouse:*aPoint inRect:[self frame]]) {
2599         return self;
2600     } else {
2601         return hitView;
2602     }
2603 }
2604
2605 - (BOOL)acceptsFirstResponder
2606 {
2607     return [[[self mainFrame] frameView] acceptsFirstResponder];
2608 }
2609
2610 - (BOOL)becomeFirstResponder
2611 {
2612     if (_private->becomingFirstResponder) {
2613         // Fix for unrepro infinite recursion reported in radar 4448181. If we hit this assert on
2614         // a debug build, we should figure out what causes the problem and do a better fix.
2615         ASSERT_NOT_REACHED();
2616         return NO;
2617     }
2618     
2619     // This works together with setNextKeyView to splice the WebView into
2620     // the key loop similar to the way NSScrollView does this. Note that
2621     // WebFrameView has very similar code.
2622     NSWindow *window = [self window];
2623     WebFrameView *mainFrameView = [[self mainFrame] frameView];
2624
2625     NSResponder *previousFirstResponder = [[self window] _oldFirstResponderBeforeBecoming];
2626     BOOL fromOutside = ![previousFirstResponder isKindOfClass:[NSView class]] || (![(NSView *)previousFirstResponder isDescendantOf:self] && previousFirstResponder != self);
2627     
2628     if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
2629         NSView *previousValidKeyView = [self previousValidKeyView];
2630         if ((previousValidKeyView != self) && (previousValidKeyView != mainFrameView)) {
2631             _private->becomingFirstResponder = YES;
2632             _private->becomingFirstResponderFromOutside = fromOutside;
2633             [window makeFirstResponder:previousValidKeyView];
2634             _private->becomingFirstResponderFromOutside = NO;
2635             _private->becomingFirstResponder = NO;
2636             return YES;
2637         } else {
2638             return NO;
2639         }
2640     }
2641     
2642     if ([mainFrameView acceptsFirstResponder]) {
2643         _private->becomingFirstResponder = YES;
2644         _private->becomingFirstResponderFromOutside = fromOutside;
2645         [window makeFirstResponder:mainFrameView];
2646         _private->becomingFirstResponderFromOutside = NO;
2647         _private->becomingFirstResponder = NO;
2648         return YES;
2649     } 
2650     
2651     return NO;
2652 }
2653
2654 - (NSView *)_webcore_effectiveFirstResponder
2655 {
2656     WebFrameView *frameView = [[self mainFrame] frameView];
2657     return frameView ? [frameView _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder];
2658 }
2659
2660 - (void)setNextKeyView:(NSView *)aView
2661 {
2662     // This works together with becomeFirstResponder to splice the WebView into
2663     // the key loop similar to the way NSScrollView does this. Note that
2664     // WebFrameView has very similar code.
2665     WebFrameView *mainFrameView = [[self mainFrame] frameView];
2666     if (mainFrameView != nil) {
2667         [mainFrameView setNextKeyView:aView];
2668     } else {
2669         [super setNextKeyView:aView];
2670     }
2671 }
2672
2673 static WebFrame *incrementFrame(WebFrame *curr, BOOL forward, BOOL wrapFlag)
2674 {
2675     Frame* coreFrame = core(curr);
2676     return kit(forward
2677         ? coreFrame->tree()->traverseNextWithWrap(wrapFlag)
2678         : coreFrame->tree()->traversePreviousWithWrap(wrapFlag));
2679 }
2680
2681 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2682 {
2683     return [self searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag startInSelection:NO];
2684 }
2685
2686 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
2687 {
2688     [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
2689     [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
2690     
2691     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2692     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2693     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2694     if ([viewClass class] == [WebHTMLView class])
2695         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2696 }
2697
2698 - (void)setGroupName:(NSString *)groupName
2699 {
2700     if (!_private->page)
2701         return;
2702     _private->page->setGroupName(groupName);
2703 }
2704
2705 - (NSString *)groupName
2706 {
2707     if (!_private->page)
2708         return nil;
2709     return _private->page->groupName();
2710 }
2711
2712 - (double)estimatedProgress
2713 {
2714     if (!_private->page)
2715         return 0.0;
2716
2717     return _private->page->progress()->estimatedProgress();
2718 }
2719
2720 - (NSArray *)pasteboardTypesForSelection
2721 {
2722     NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
2723     if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
2724         return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
2725     }
2726     return [NSArray array];
2727 }
2728
2729 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2730 {
2731     WebFrame *frame = [self _selectedOrMainFrame];
2732     if (frame && [frame _hasSelection]) {
2733         NSView <WebDocumentView> *documentView = [[frame frameView] documentView];
2734         if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)])
2735             [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2736     }
2737 }
2738
2739 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
2740 {
2741     if ([element objectForKey:WebElementImageURLKey] != nil) {
2742         return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
2743     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2744         return [NSPasteboard _web_writableTypesForURL];
2745     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2746         return [self pasteboardTypesForSelection];
2747     }
2748     return [NSArray array];
2749 }
2750
2751 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2752 {
2753     if ([element objectForKey:WebElementImageURLKey] != nil) {
2754         [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2755     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
2756         [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
2757     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2758         [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2759     }
2760 }
2761
2762 - (void)moveDragCaretToPoint:(NSPoint)point
2763 {
2764     if (Page* page = core(self))
2765         page->dragController()->placeDragCaret(IntPoint([self convertPoint:point toView:nil]));
2766 }
2767
2768 - (void)removeDragCaret
2769 {
2770     if (Page* page = core(self))
2771         page->dragController()->dragEnded();
2772 }
2773
2774 - (void)setMainFrameURL:(NSString *)URLString
2775 {
2776     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2777 }
2778
2779 - (NSString *)mainFrameURL
2780 {
2781     WebDataSource *ds;
2782     ds = [[self mainFrame] provisionalDataSource];
2783     if (!ds)
2784         ds = [[self mainFrame] _dataSource];
2785     return [[[ds request] URL] _web_originalDataAsString];
2786 }
2787
2788 - (BOOL)isLoading
2789 {
2790     LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
2791     return [self _isLoading];
2792 }
2793
2794 - (NSString *)mainFrameTitle
2795 {
2796     NSString *mainFrameTitle = [[[self mainFrame] _dataSource] pageTitle];
2797     return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
2798 }
2799
2800 - (NSImage *)mainFrameIcon
2801 {
2802     return [[WebIconDatabase sharedIconDatabase] iconForURL:[[[[self mainFrame] _dataSource] _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
2803 }
2804
2805 - (DOMDocument *)mainFrameDocument
2806 {
2807     // only return the actual value if the state we're in gives NSTreeController
2808     // enough time to release its observers on the old model
2809     if (_private->mainFrameDocumentReady)
2810         return [[self mainFrame] DOMDocument];
2811     return nil;
2812 }
2813
2814 - (void)setDrawsBackground:(BOOL)drawsBackground
2815 {
2816     if (_private->drawsBackground == drawsBackground)
2817         return;
2818     _private->drawsBackground = drawsBackground;
2819     [[self mainFrame] _updateBackground];
2820 }
2821
2822 - (BOOL)drawsBackground
2823 {
2824     return _private->drawsBackground;
2825 }
2826
2827 @end
2828
2829 @implementation WebView (WebIBActions)
2830
2831 - (IBAction)takeStringURLFrom: sender
2832 {
2833     NSString *URLString = [sender stringValue];
2834     
2835     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
2836 }
2837
2838 - (BOOL)canGoBack
2839 {
2840     if (!_private->page)
2841         return NO;
2842
2843     return !!_private->page->backForwardList()->backItem();
2844 }
2845
2846 - (BOOL)canGoForward
2847 {
2848     if (!_private->page)
2849         return NO;
2850
2851     return !!_private->page->backForwardList()->forwardItem();
2852 }
2853
2854 - (IBAction)goBack:(id)sender
2855 {
2856     [self goBack];
2857 }
2858
2859 - (IBAction)goForward:(id)sender
2860 {
2861     [self goForward];
2862 }
2863
2864 - (IBAction)stopLoading:(id)sender
2865 {
2866     [[self mainFrame] stopLoading];
2867 }
2868
2869 - (IBAction)reload:(id)sender
2870 {
2871     [[self mainFrame] reload];
2872 }
2873
2874 // FIXME: This code should move into WebCore so that it is not duplicated in each WebKit.
2875 // (This includes canMakeTextSmaller/Larger, makeTextSmaller/Larger, and canMakeTextStandardSize/makeTextStandardSize)
2876 - (BOOL)canMakeTextSmaller
2877 {
2878     return [self _canZoomOut:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2879 }
2880
2881 - (IBAction)makeTextSmaller:(id)sender
2882 {
2883     return [self _zoomOut:sender isTextOnly:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2884 }
2885
2886 - (BOOL)canMakeTextLarger
2887 {
2888     return [self _canZoomIn:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2889 }
2890
2891 - (IBAction)makeTextLarger:(id)sender
2892 {
2893     return [self _zoomIn:sender isTextOnly:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2894 }
2895
2896 - (BOOL)canMakeTextStandardSize
2897 {
2898     return [self _canResetZoom:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2899 }
2900
2901 - (IBAction)makeTextStandardSize:(id)sender
2902 {
2903    return [self _resetZoom:sender isTextOnly:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
2904 }
2905
2906 - (IBAction)toggleSmartInsertDelete:(id)sender
2907 {
2908     [self setSmartInsertDeleteEnabled:![self smartInsertDeleteEnabled]];
2909 }
2910
2911 - (IBAction)toggleContinuousSpellChecking:(id)sender
2912 {
2913     [self setContinuousSpellCheckingEnabled:![self isContinuousSpellCheckingEnabled]];
2914 }
2915
2916 - (BOOL)_responderValidateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2917 {
2918     id responder = [self _responderForResponderOperations];
2919     if (responder != self && [responder respondsToSelector:[item action]]) {
2920         if ([responder respondsToSelector:@selector(validateUserInterfaceItemWithoutDelegate:)])
2921             return [responder validateUserInterfaceItemWithoutDelegate:item];
2922         if ([responder respondsToSelector:@selector(validateUserInterfaceItem:)])
2923             return [responder validateUserInterfaceItem:item];
2924         return YES;
2925     }
2926     return NO;
2927 }
2928
2929 #define VALIDATE(name) \
2930     else if (action == @selector(name:)) { return [self _responderValidateUserInterfaceItem:item]; }
2931
2932 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item
2933 {
2934     SEL action = [item action];
2935
2936     if (action == @selector(goBack:)) {
2937         return [self canGoBack];
2938     } else if (action == @selector(goForward:)) {
2939         return [self canGoForward];
2940     } else if (action == @selector(makeTextLarger:)) {
2941         return [self canMakeTextLarger];
2942     } else if (action == @selector(makeTextSmaller:)) {
2943         return [self canMakeTextSmaller];
2944     } else if (action == @selector(makeTextStandardSize:)) {
2945         return [self canMakeTextStandardSize];
2946     } else if (action == @selector(reload:)) {
2947         return [[self mainFrame] _dataSource] != nil;
2948     } else if (action == @selector(stopLoading:)) {
2949         return [self _isLoading];
2950     } else if (action == @selector(toggleContinuousSpellChecking:)) {
2951         BOOL checkMark = NO;
2952         BOOL retVal = NO;
2953         if ([self _continuousCheckingAllowed]) {
2954             checkMark = [self isContinuousSpellCheckingEnabled];
2955             retVal = YES;
2956         }
2957         if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2958             NSMenuItem *menuItem = (NSMenuItem *)item;
2959             [menuItem setState:checkMark ? NSOnState : NSOffState];
2960         }
2961         return retVal;
2962 #ifndef BUILDING_ON_TIGER
2963     } else if (action == @selector(toggleGrammarChecking:)) {
2964         BOOL checkMark = [self isGrammarCheckingEnabled];
2965         if ([(NSObject *)item isKindOfClass:[NSMenuItem class]]) {
2966             NSMenuItem *menuItem = (NSMenuItem *)item;
2967             [menuItem setState:checkMark ? NSOnState : NSOffState];
2968         }
2969         return YES;
2970 #endif
2971     }
2972     FOR_EACH_RESPONDER_SELECTOR(VALIDATE)
2973
2974     return YES;
2975 }
2976
2977 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
2978 {
2979     BOOL result = [self validateUserInterfaceItemWithoutDelegate:item];
2980     return CallUIDelegateReturningBoolean(result, self, @selector(webView:validateUserInterfaceItem:defaultValidation:), item, result);
2981 }
2982
2983 @end
2984
2985 @implementation WebView (WebPendingPublic)
2986
2987 - (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode
2988 {
2989 #ifndef BUILDING_ON_TIGER
2990     if (runLoop && mode)
2991         core(self)->addSchedulePair(SchedulePair::create(runLoop, (CFStringRef)mode));
2992 #endif
2993 }
2994
2995 - (void)unscheduleFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode
2996 {
2997 #ifndef BUILDING_ON_TIGER
2998     if (runLoop && mode)
2999         core(self)->removeSchedulePair(SchedulePair::create(runLoop, (CFStringRef)mode));
3000 #endif
3001 }
3002
3003 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
3004 {
3005     if (_private->closed)
3006         return NO;
3007     
3008     // Get the frame holding the selection, or start with the main frame
3009     WebFrame *startFrame = [self _selectedOrMainFrame];
3010     
3011     // Search the first frame, then all the other frames, in order
3012     NSView <WebDocumentSearching> *startSearchView = nil;
3013     WebFrame *frame = startFrame;
3014     do {
3015         WebFrame *nextFrame = incrementFrame(frame, forward, wrapFlag);
3016         
3017         BOOL onlyOneFrame = (frame == nextFrame);
3018         ASSERT(!onlyOneFrame || frame == startFrame);
3019         
3020         id <WebDocumentView> view = [[frame frameView] documentView];
3021         if ([view conformsToProtocol:@protocol(WebDocumentSearching)]) {
3022             NSView <WebDocumentSearching> *searchView = (NSView <WebDocumentSearching> *)view;
3023             
3024             if (frame == startFrame)
3025                 startSearchView = searchView;
3026             
3027             BOOL foundString;
3028             // In some cases we have to search some content twice; see comment later in this method.
3029             // We can avoid ever doing this in the common one-frame case by passing YES for wrapFlag 
3030             // here, and then bailing out before we get to the code that would search again in the
3031             // same content.
3032             BOOL wrapOnThisPass = wrapFlag && onlyOneFrame;
3033             if ([searchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
3034                 foundString = [(NSView <WebDocumentIncrementalSearching> *)searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass startInSelection:startInSelection];
3035             else
3036                 foundString = [searchView searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapOnThisPass];
3037             
3038             if (foundString) {
3039                 if (frame != startFrame)
3040                     [startFrame _clearSelection];
3041                 [[self window] makeFirstResponder:searchView];
3042                 return YES;
3043             }
3044             
3045             if (onlyOneFrame)
3046                 return NO;
3047         }
3048         frame = nextFrame;
3049     } while (frame && frame != startFrame);
3050     
3051     // If there are multiple frames and wrapFlag is true and we've visited each one without finding a result, we still need to search in the 
3052     // first-searched frame up to the selection. However, the API doesn't provide a way to search only up to a particular point. The only 
3053     // way to make sure the entire frame is searched is to pass YES for the wrapFlag. When there are no matches, this will search again
3054     // some content that we already searched on the first pass. In the worst case, we could search the entire contents of this frame twice.
3055     // To fix this, we'd need to add a mechanism to specify a range in which to search.
3056     if (wrapFlag && startSearchView) {
3057         BOOL foundString;
3058         if ([startSearchView conformsToProtocol:@protocol(WebDocumentIncrementalSearching)])
3059             foundString = [(NSView <WebDocumentIncrementalSearching> *)startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES startInSelection:startInSelection];
3060         else
3061             foundString = [startSearchView searchFor:string direction:forward caseSensitive:caseFlag wrap:YES];
3062         if (foundString) {
3063             [[self window] makeFirstResponder:startSearchView];
3064             return YES;
3065         }
3066     }
3067     return NO;
3068 }
3069
3070 - (void)setHoverFeedbackSuspended:(BOOL)newValue
3071 {
3072     if (_private->hoverFeedbackSuspended == newValue)
3073         return;
3074     
3075     _private->hoverFeedbackSuspended = newValue;
3076     id <WebDocumentView> documentView = [[[self mainFrame] frameView] documentView];
3077     // FIXME: in a perfect world we'd do this in a general way that worked with any document view,
3078     // such as by calling a protocol method or using respondsToSelector or sending a notification.
3079     // But until there is any need for these more general solutions, we'll just hardwire it to work
3080     // with WebHTMLView.
3081     // Note that _hoverFeedbackSuspendedChanged needs to be called only on the main WebHTMLView, not
3082     // on each subframe separately.
3083     if ([documentView isKindOfClass:[WebHTMLView class]])
3084         [(WebHTMLView *)documentView _hoverFeedbackSuspendedChanged];
3085 }
3086
3087 - (BOOL)isHoverFeedbackSuspended
3088 {
3089     return _private->hoverFeedbackSuspended;
3090 }
3091
3092 - (void)setMainFrameDocumentReady:(BOOL)mainFrameDocumentReady
3093 {
3094     // by setting this to NO, calls to mainFrameDocument are forced to return nil
3095     // setting this to YES lets it return the actual DOMDocument value
3096     // we use this to tell NSTreeController to reset its observers and clear its state
3097     if (_private->mainFrameDocumentReady == mainFrameDocumentReady)
3098         return;
3099     [self _willChangeValueForKey:_WebMainFrameDocumentKey];
3100     _private->mainFrameDocumentReady = mainFrameDocumentReady;
3101     [self _didChangeValueForKey:_WebMainFrameDocumentKey];
3102     // this will cause observers to call mainFrameDocument where this flag will be checked
3103 }
3104
3105 // This method name is used by Mail on Tiger (but not post-Tiger), so we shouldn't delete it 
3106 // until the day comes when we're no longer supporting Mail on Tiger.
3107 - (WebFrame *)_frameForCurrentSelection
3108 {
3109     return [self _selectedOrMainFrame];
3110 }
3111
3112 - (void)setTabKeyCyclesThroughElements:(BOOL)cyclesElements
3113 {
3114     _private->tabKeyCyclesThroughElementsChanged = YES;
3115     if (_private->page)
3116         _private->page->setTabKeyCyclesThroughElements(cyclesElements);
3117 }
3118
3119 - (BOOL)tabKeyCyclesThroughElements
3120 {
3121     return _private->page && _private->page->tabKeyCyclesThroughElements();
3122 }
3123
3124 - (void)setScriptDebugDelegate:(id)delegate
3125 {
3126     _private->scriptDebugDelegate = delegate;
3127     [_private->scriptDebugDelegateForwarder release];
3128     _private->scriptDebugDelegateForwarder = nil;
3129     if (delegate)
3130         [self _attachScriptDebuggerToAllFrames];
3131     else
3132         [self _detachScriptDebuggerFromAllFrames];
3133 }
3134
3135 - (id)scriptDebugDelegate
3136 {
3137     return _private->scriptDebugDelegate;
3138 }
3139
3140 - (BOOL)shouldClose
3141 {
3142     Frame* coreFrame = core([self mainFrame]);
3143     if (!coreFrame)
3144         return YES;
3145     return coreFrame->shouldClose();
3146 }
3147
3148 static NSAppleEventDescriptor* aeDescFromJSValue(ExecState* exec, JSValue* jsValue)
3149 {
3150     NSAppleEventDescriptor* aeDesc = 0;
3151     switch (jsValue->type()) {
3152         case BooleanType:
3153             aeDesc = [NSAppleEventDescriptor descriptorWithBoolean:jsValue->getBoolean()];
3154             break;
3155         case StringType:
3156             aeDesc = [NSAppleEventDescriptor descriptorWithString:String(jsValue->getString())];
3157             break;
3158         case NumberType: {
3159             double value = jsValue->getNumber();
3160             int intValue = (int)value;
3161             if (value == intValue)
3162                 aeDesc = [NSAppleEventDescriptor descriptorWithDescriptorType:typeSInt32 bytes:&intValue length:sizeof(intValue)];
3163             else
3164                 aeDesc = [NSAppleEventDescriptor descriptorWithDescriptorType:typeIEEE64BitFloatingPoint bytes:&value length:sizeof(value)];
3165             break;
3166         }
3167         case ObjectType: {
3168             JSObject* object = jsValue->getObject();
3169             if (object->inherits(&DateInstance::info)) {
3170                 DateInstance* date = static_cast<DateInstance*>(object);
3171                 double ms = 0;
3172                 int tzOffset = 0;
3173                 if (date->getTime(ms, tzOffset)) {
3174                     CFAbsoluteTime utcSeconds = ms / 1000 - kCFAbsoluteTimeIntervalSince1970;
3175                     LongDateTime ldt;
3176                     if (noErr == UCConvertCFAbsoluteTimeToLongDateTime(utcSeconds, &ldt))
3177                         aeDesc = [NSAppleEventDescriptor descriptorWithDescriptorType:typeLongDateTime bytes:&ldt length:sizeof(ldt)];
3178                 }
3179             }
3180             else if (object->inherits(&ArrayInstance::info)) {
3181                 static HashSet<JSObject*> visitedElems;
3182                 if (!visitedElems.contains(object)) {
3183                     visitedElems.add(object);
3184                     
3185                     ArrayInstance* array = static_cast<ArrayInstance*>(object);
3186                     aeDesc = [NSAppleEventDescriptor listDescriptor];
3187                     unsigned numItems = array->getLength();
3188                     for (unsigned i = 0; i < numItems; ++i)
3189                         [aeDesc insertDescriptor:aeDescFromJSValue(exec, array->getItem(i)) atIndex:0];
3190                     
3191                     visitedElems.remove(object);
3192                 }
3193             }
3194             if (!aeDesc) {
3195                 JSValue* primitive = object->toPrimitive(exec);
3196                 if (exec->hadException()) {
3197                     exec->clearException();
3198                     return [NSAppleEventDescriptor nullDescriptor];
3199                 }
3200                 return aeDescFromJSValue(exec, primitive);
3201             }
3202             break;
3203         }
3204         case UndefinedType:
3205             aeDesc = [NSAppleEventDescriptor descriptorWithTypeCode:cMissingValue];
3206             break;
3207         default:
3208             LOG_ERROR("Unknown JavaScript type: %d", jsValue->type());
3209             // no break;
3210         case UnspecifiedType:
3211         case NullType:
3212         case GetterSetterType:
3213             aeDesc = [NSAppleEventDescriptor nullDescriptor];
3214             break;
3215     }
3216     
3217     return aeDesc;
3218 }
3219
3220 - (NSAppleEventDescriptor *)aeDescByEvaluatingJavaScriptFromString:(NSString *)script
3221 {
3222     Frame* coreFrame = core([self mainFrame]);
3223     if (!coreFrame)
3224         return nil;
3225     if (!coreFrame->document())
3226         return nil;
3227     JSValue* result = coreFrame->loader()->executeScript(script, true);
3228     if (!result) // FIXME: pass errors
3229         return 0;
3230     JSLock lock;
3231     return aeDescFromJSValue(coreFrame->scriptProxy()->globalObject()->globalExec(), result);
3232 }
3233
3234 - (BOOL)canMarkAllTextMatches
3235 {
3236     WebFrame *frame = [self mainFrame];
3237     do {
3238         id <WebDocumentView> view = [[frame frameView] documentView];
3239         if (view && ![view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3240             return NO;
3241         
3242         frame = incrementFrame(frame, YES, NO);
3243     } while (frame);
3244     
3245     return YES;
3246 }
3247
3248 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag highlight:(BOOL)highlight limit:(NSUInteger)limit
3249 {
3250     WebFrame *frame = [self mainFrame];
3251     unsigned matchCount = 0;
3252     do {
3253         id <WebDocumentView> view = [[frame frameView] documentView];
3254         if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3255             [(NSView <WebMultipleTextMatches>*)view  setMarkedTextMatchesAreHighlighted:highlight];
3256         
3257             ASSERT(limit == 0 || matchCount < limit);
3258             matchCount += [(NSView <WebMultipleTextMatches>*)view markAllMatchesForText:string caseSensitive:caseFlag limit:limit == 0 ? 0 : limit - matchCount];
3259
3260             // Stop looking if we've reached the limit. A limit of 0 means no limit.
3261             if (limit > 0 && matchCount >= limit)
3262                 break;
3263         }
3264         
3265         frame = incrementFrame(frame, YES, NO);
3266     } while (frame);
3267     
3268     return matchCount;
3269 }
3270
3271 - (void)unmarkAllTextMatches
3272 {
3273     WebFrame *frame = [self mainFrame];
3274     do {
3275         id <WebDocumentView> view = [[frame frameView] documentView];
3276         if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)])
3277             [(NSView <WebMultipleTextMatches>*)view unmarkAllTextMatches];
3278         
3279         frame = incrementFrame(frame, YES, NO);
3280     } while (frame);
3281 }
3282
3283 - (NSArray *)rectsForTextMatches
3284 {
3285     NSMutableArray *result = [NSMutableArray array];
3286     WebFrame *frame = [self mainFrame];
3287     do {
3288         id <WebDocumentView> view = [[frame frameView] documentView];
3289         if ([view conformsToProtocol:@protocol(WebMultipleTextMatches)]) {
3290             NSView <WebMultipleTextMatches> *documentView = (NSView <WebMultipleTextMatches> *)view;
3291             NSRect documentViewVisibleRect = [documentView visibleRect];
3292             NSArray *originalRects = [documentView rectsForTextMatches];
3293             unsigned rectCount = [originalRects count];
3294             unsigned rectIndex;
3295             NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
3296             for (rectIndex = 0; rectIndex < rectCount; ++rectIndex) {
3297                 NSRect r = [[originalRects objectAtIndex:rectIndex] rectValue];
3298                 // Clip rect to document view's visible rect so rect is confined to subframe
3299                 r = NSIntersectionRect(r, documentViewVisibleRect);
3300                 if (NSIsEmptyRect(r))
3301                     continue;
3302                 
3303                 // Convert rect to our coordinate system
3304                 r = [documentView convertRect:r toView:self];
3305                 [result addObject:[NSValue valueWithRect:r]];
3306                 if (rectIndex % 10 == 0) {
3307                     [pool drain];
3308                     pool = [[NSAutoreleasePool alloc] init];
3309                 }
3310             }
3311             [pool drain];
3312         }
3313         
3314         frame = incrementFrame(frame, YES, NO);
3315     } while (frame);
3316     
3317     return result;
3318 }
3319
3320 - (void)scrollDOMRangeToVisible:(DOMRange *)range
3321 {
3322     [[[[range startContainer] ownerDocument] webFrame] _scrollDOMRangeToVisible:range];
3323 }
3324
3325 - (BOOL)allowsUndo
3326 {
3327     return _private->allowsUndo;
3328 }
3329
3330 - (void)setAllowsUndo:(BOOL)flag
3331 {
3332     _private->allowsUndo = flag;
3333 }
3334
3335 - (void)setPageSizeMultiplier:(float)m
3336 {
3337     [self _setZoomMultiplier:m isTextOnly:NO];
3338 }
3339
3340 - (float)pageSizeMultiplier
3341 {
3342     return !_private->zoomMultiplierIsTextOnly ? _private->zoomMultiplier : 1.0f;
3343 }
3344
3345 - (BOOL)canZoomPageIn
3346 {
3347     return [self _canZoomIn:NO];
3348 }
3349
3350 - (IBAction)zoomPageIn:(id)sender
3351 {
3352     return [self _zoomIn:sender isTextOnly:NO];
3353 }
3354
3355 - (BOOL)canZoomPageOut
3356 {
3357     return [self _canZoomOut:NO];
3358 }
3359
3360 - (IBAction)zoomPageOut:(id)sender
3361 {
3362     return [self _zoomOut:sender isTextOnly:NO];
3363 }
3364
3365 - (BOOL)canResetPageZoom
3366 {
3367     return [self _canResetZoom:NO];
3368 }
3369
3370 - (IBAction)resetPageZoom:(id)sender
3371 {
3372     return [self _resetZoom:sender isTextOnly:NO];
3373 }
3374
3375 @end
3376
3377 @implementation WebView (WebViewPrintingPrivate)
3378
3379 - (float)_headerHeight
3380 {
3381     return CallUIDelegateReturningFloat(self, @selector(webViewHeaderHeight:));
3382 }
3383
3384 - (float)_footerHeight
3385 {
3386     return CallUIDelegateReturningFloat(self, @selector(webViewFooterHeight:));
3387 }
3388
3389 - (void)_drawHeaderInRect:(NSRect)rect
3390 {
3391 #ifdef DEBUG_HEADER_AND_FOOTER
3392     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3393     [currentContext saveGraphicsState];
3394     [[NSColor yellowColor] set];
3395     NSRectFill(rect);
3396     [currentContext restoreGraphicsState];
3397 #endif
3398
3399     SEL selector = @selector(webView:drawHeaderInRect:);
3400     if (![_private->UIDelegate respondsToSelector:selector])
3401         return;
3402
3403     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3404     [currentContext saveGraphicsState];
3405
3406     NSRectClip(rect);
3407     CallUIDelegate(self, selector, rect);
3408
3409     [currentContext restoreGraphicsState];
3410 }
3411
3412 - (void)_drawFooterInRect:(NSRect)rect
3413 {
3414 #ifdef DEBUG_HEADER_AND_FOOTER
3415     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3416     [currentContext saveGraphicsState];
3417     [[NSColor cyanColor] set];
3418     NSRectFill(rect);
3419     [currentContext restoreGraphicsState];
3420 #endif
3421     
3422     SEL selector = @selector(webView:drawFooterInRect:);
3423     if (![_private->UIDelegate respondsToSelector:selector])
3424         return;
3425
3426     NSGraphicsContext *currentContext = [NSGraphicsContext currentContext];
3427     [currentContext saveGraphicsState];
3428
3429     NSRectClip(rect);
3430     CallUIDelegate(self, selector, rect);
3431
3432     [currentContext restoreGraphicsState];
3433 }
3434
3435 - (void)_adjustPrintingMarginsForHeaderAndFooter
3436 {
3437     NSPrintOperation *op = [NSPrintOperation currentOperation];
3438     NSPrintInfo *info = [op printInfo];
3439     NSMutableDictionary *infoDictionary = [info dictionary];
3440     
3441     // We need to modify the top and bottom margins in the NSPrintInfo to account for the space needed by the
3442     // header and footer. Because this method can be called more than once on the same NSPrintInfo (see 5038087),
3443     // we stash away the unmodified top and bottom margins the first time this method is called, and we read from
3444     // those stashed-away values on subsequent calls.
3445     float originalTopMargin;
3446     float originalBottomMargin;
3447     NSNumber *originalTopMarginNumber = [infoDictionary objectForKey:WebKitOriginalTopPrintingMarginKey];
3448     if (!originalTopMarginNumber) {
3449         ASSERT(![infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey]);
3450         originalTopMargin = [info topMargin];
3451         originalBottomMargin = [info bottomMargin];
3452         [infoDictionary setObject:[NSNumber numberWithFloat:originalTopMargin] forKey:WebKitOriginalTopPrintingMarginKey];
3453         [infoDictionary setObject:[NSNumber numberWithFloat:originalBottomMargin] forKey:WebKitOriginalBottomPrintingMarginKey];
3454     } else {
3455         ASSERT([originalTopMarginNumber isKindOfClass:[NSNumber class]]);
3456         ASSERT([[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] isKindOfClass:[NSNumber class]]);
3457         originalTopMargin = [originalTopMarginNumber floatValue];
3458         originalBottomMargin = [[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] floatValue];
3459     }
3460     
3461     float scale = [op _web_pageSetupScaleFactor];
3462     [info setTopMargin:originalTopMargin + [self _headerHeight] * scale];
3463     [info setBottomMargin:originalBottomMargin + [self _footerHeight] * scale];
3464 }
3465
3466 - (void)_drawHeaderAndFooter
3467 {
3468     // The header and footer rect height scales with the page, but the width is always
3469     // all the way across the printed page (inset by printing margins).
3470     NSPrintOperation *op = [NSPrintOperation currentOperation];
3471     float scale = [op _web_pageSetupScaleFactor];
3472     NSPrintInfo *printInfo = [op printInfo];
3473     NSSize paperSize = [printInfo paperSize];
3474     float headerFooterLeft = [printInfo leftMargin]/scale;
3475     float headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin]))/scale;
3476     NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin]/scale - [self _footerHeight] , 
3477                                    headerFooterWidth, [self _footerHeight]);
3478     NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin])/scale, 
3479                                    headerFooterWidth, [self _headerHeight]);
3480     
3481     [self _drawHeaderInRect:headerRect];
3482     [self _drawFooterInRect:footerRect];
3483 }
3484 @end
3485
3486 @implementation WebView (WebDebugBinding)
3487
3488 - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
3489 {
3490     LOG (Bindings, "addObserver:%p forKeyPath:%@ options:%x context:%p", anObserver, keyPath, options, context);
3491     [super addObserver:anObserver forKeyPath:keyPath options:options context:context];
3492 }
3493
3494 - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath
3495 {
3496     LOG (Bindings, "removeObserver:%p forKeyPath:%@", anObserver, keyPath);
3497     [super removeObserver:anObserver forKeyPath:keyPath];
3498 }
3499
3500 @end
3501
3502 //==========================================================================================
3503 // Editing
3504
3505 @implementation WebView (WebViewCSS)
3506
3507 - (DOMCSSStyleDeclaration *)computedStyleForElement:(DOMElement *)element pseudoElement:(NSString *)pseudoElement
3508 {
3509     // FIXME: is this the best level for this conversion?
3510     if (pseudoElement == nil)
3511         pseudoElement = @"";
3512
3513     return [[element ownerDocument] getComputedStyle:element pseudoElement:pseudoElement];
3514 }
3515
3516 @end
3517
3518 @implementation WebView (WebViewEditing)
3519
3520 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
3521 {
3522     Page* page = core(self);
3523     if (!page)
3524         return nil;
3525     return kit(page->mainFrame()->editor()->rangeForPoint(IntPoint([self convertPoint:point toView:nil])).get());
3526 }
3527
3528 - (BOOL)_shouldChangeSelectedDOMRange:(DOMRange *)currentRange toDOMRange:(DOMRange *)proposedRange affinity:(NSSelectionAffinity)selectionAffinity stillSelecting:(BOOL)flag;
3529 {
3530     // FIXME: This quirk is needed due to <rdar://problem/4985321> - We can phase it out once Aperture can adopt the new behavior on their end
3531     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_APERTURE_QUIRK) && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Aperture"])
3532         return YES;
3533     return [[self _editingDelegateForwarder] webView:self shouldChangeSelectedDOMRange:currentRange toDOMRange:proposedRange affinity:selectionAffinity stillSelecting:flag];
3534 }
3535
3536 - (BOOL)maintainsInactiveSelection
3537 {
3538     return NO;
3539 }
3540
3541 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
3542 {
3543     Frame* coreFrame = core([self _selectedOrMainFrame]);
3544     if (!coreFrame)
3545         return;
3546
3547     if (range == nil)
3548         coreFrame->selectionController()->clear();
3549     else {
3550         // Derive the frame to use from the range passed in.
3551         // Using _selectedOrMainFrame could give us a different document than
3552         // the one the range uses.
3553         coreFrame = core([range startContainer])->document()->frame();
3554         if (!coreFrame)
3555             return;
3556
3557         coreFrame->selectionController()->setSelectedRange([range _range], core(selectionAffinity), true);
3558     }
3559 }
3560
3561 - (DOMRange *)selectedDOMRange
3562 {
3563     Frame* coreFrame = core([self _selectedOrMainFrame]);
3564     if (!coreFrame)
3565         return nil;
3566     return kit(coreFrame->selectionController()->toRange().get());
3567 }
3568
3569 - (NSSelectionAffinity)selectionAffinity
3570 {
3571     Frame* coreFrame = core([self _selectedOrMainFrame]);
3572     if (!coreFrame)
3573         return NSSelectionAffinityDownstream;
3574     return kit(coreFrame->selectionController()->affinity());
3575 }
3576
3577 - (void)setEditable:(BOOL)flag
3578 {
3579     if (_private->editable != flag) {
3580         _private->editable = flag;
3581         if (!_private->tabKeyCyclesThroughElementsChanged && _private->page)
3582             _private->page->setTabKeyCyclesThroughElements(!flag);
3583         Frame* mainFrame = core([self mainFrame]);
3584         if (mainFrame) {
3585             if (flag) {
3586                 mainFrame->applyEditingStyleToBodyElement();
3587                 // If the WebView is made editable and the selection is empty, set it to something.
3588                 if (![self selectedDOMRange])
3589                     mainFrame->setSelectionFromNone();
3590             } else
3591                 mainFrame->removeEditingStyleFromBodyElement();
3592         }
3593     }
3594 }
3595
3596 - (BOOL)isEditable
3597 {
3598     return _private->editable;
3599 }
3600
3601 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style
3602 {
3603     // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3604     // change the API to allow this.
3605     [[self _selectedOrMainFrame] _setTypingStyle:style withUndoAction:EditActionUnspecified];
3606 }
3607
3608 - (DOMCSSStyleDeclaration *)typingStyle
3609 {
3610     return [[self _selectedOrMainFrame] _typingStyle];
3611 }
3612
3613 - (void)setSmartInsertDeleteEnabled:(BOOL)flag
3614 {
3615     _private->smartInsertDeleteEnabled = flag;
3616 }
3617
3618 - (BOOL)smartInsertDeleteEnabled
3619 {
3620     return _private->smartInsertDeleteEnabled;
3621 }
3622
3623 - (void)setContinuousSpellCheckingEnabled:(BOOL)flag
3624 {
3625     if (continuousSpellCheckingEnabled != flag) {
3626         continuousSpellCheckingEnabled = flag;
3627         [[NSUserDefaults standardUserDefaults] setBool:continuousSpellCheckingEnabled forKey:WebContinuousSpellCheckingEnabled];
3628     }
3629     
3630     if ([self isContinuousSpellCheckingEnabled]) {
3631         [[self class] _preflightSpellChecker];
3632     } else {
3633         [[self mainFrame] _unmarkAllMisspellings];
3634     }
3635 }
3636
3637 - (BOOL)isContinuousSpellCheckingEnabled
3638 {
3639     return (continuousSpellCheckingEnabled && [self _continuousCheckingAllowed]);
3640 }
3641
3642 - (NSInteger)spellCheckerDocumentTag
3643 {
3644     if (!_private->hasSpellCheckerDocumentTag) {
3645         _private->spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag];
3646         _private->hasSpellCheckerDocumentTag = YES;
3647     }
3648     return _private->spellCheckerDocumentTag;
3649 }
3650
3651 - (NSUndoManager *)undoManager
3652 {
3653     if (!_private->allowsUndo)
3654         return nil;
3655
3656     NSUndoManager *undoManager = [[self _editingDelegateForwarder] undoManagerForWebView:self];
3657     if (undoManager)
3658         return undoManager;
3659
3660     return [super undoManager];
3661 }
3662
3663 - (void)registerForEditingDelegateNotification:(NSString *)name selector:(SEL)selector
3664 {
3665     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3666     if ([_private->editingDelegate respondsToSelector:selector])
3667         [defaultCenter addObserver:_private->editingDelegate selector:selector name:name object:self];
3668 }
3669
3670 - (void)setEditingDelegate:(id)delegate
3671 {
3672     if (_private->editingDelegate == delegate)
3673         return;
3674
3675     NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
3676
3677     // remove notifications from current delegate
3678     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidBeginEditingNotification object:self];
3679     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeNotification object:self];
3680     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidEndEditingNotification object:self];
3681     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeTypingStyleNotification object:self];
3682     [defaultCenter removeObserver:_private->editingDelegate name:WebViewDidChangeSelectionNotification object:self];
3683     
3684     _private->editingDelegate = delegate;
3685     [_private->editingDelegateForwarder release];
3686     _private->editingDelegateForwarder = nil;
3687     
3688     // add notifications for new delegate
3689     [self registerForEditingDelegateNotification:WebViewDidBeginEditingNotification selector:@selector(webViewDidBeginEditing:)];
3690     [self registerForEditingDelegateNotification:WebViewDidChangeNotification selector:@selector(webViewDidChange:)];
3691     [self registerForEditingDelegateNotification:WebViewDidEndEditingNotification selector:@selector(webViewDidEndEditing:)];
3692     [self registerForEditingDelegateNotification:WebViewDidChangeTypingStyleNotification selector:@selector(webViewDidChangeTypingStyle:)];
3693     [self registerForEditingDelegateNotification:WebViewDidChangeSelectionNotification selector:@selector(webViewDidChangeSelection:)];
3694 }
3695
3696 - (id)editingDelegate
3697 {
3698     return _private->editingDelegate;
3699 }
3700
3701 - (DOMCSSStyleDeclaration *)styleDeclarationWithText:(NSString *)text
3702 {
3703     // FIXME: Should this really be attached to the document with the current selection?
3704     DOMCSSStyleDeclaration *decl = [[[self _selectedOrMainFrame] DOMDocument] createCSSStyleDeclaration];
3705     [decl setCssText:text];
3706     return decl;
3707 }
3708
3709 @end
3710
3711 @implementation WebView (WebViewGrammarChecking)
3712
3713 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3714 - (BOOL)isGrammarCheckingEnabled
3715 {
3716 #ifdef BUILDING_ON_TIGER
3717     return NO;
3718 #else
3719     return grammarCheckingEnabled;
3720 #endif
3721 }
3722
3723 #ifndef BUILDING_ON_TIGER
3724 // FIXME: This method should be merged into WebViewEditing when we're not in API freeze
3725 - (void)setGrammarCheckingEnabled:(BOOL)flag
3726 {
3727     if (grammarCheckingEnabled == flag)
3728         return;
3729     
3730     grammarCheckingEnabled = flag;
3731     [[NSUserDefaults standardUserDefaults] setBool:grammarCheckingEnabled forKey:WebGrammarCheckingEnabled];    
3732     
3733     // FIXME 4811447: workaround for lack of API
3734     NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
3735     if ([spellChecker respondsToSelector:@selector(_updateGrammar)])
3736         [spellChecker performSelector:@selector(_updateGrammar)];
3737     
3738     // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3739     // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3740     
3741     if (![self isGrammarCheckingEnabled])
3742         [[self mainFrame] _unmarkAllBadGrammar];
3743 }
3744
3745 // FIXME: This method should be merged into WebIBActions when we're not in API freeze
3746 - (void)toggleGrammarChecking:(id)sender
3747 {
3748     [self setGrammarCheckingEnabled:![self isGrammarCheckingEnabled]];
3749 }
3750 #endif
3751
3752 @end
3753
3754 @implementation WebView (WebViewUndoableEditing)
3755
3756 - (void)replaceSelectionWithNode:(DOMNode *)node
3757 {
3758     [[self _selectedOrMainFrame] _replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:NO];
3759 }    
3760
3761 - (void)replaceSelectionWithText:(NSString *)text
3762 {
3763     [[self _selectedOrMainFrame] _replaceSelectionWithText:text selectReplacement:YES smartReplace:NO];
3764 }
3765
3766 - (void)replaceSelectionWithMarkupString:(NSString *)markupString
3767 {
3768     [[self _selectedOrMainFrame] _replaceSelectionWithMarkupString:markupString baseURLString:nil selectReplacement:YES smartReplace:NO];
3769 }
3770
3771 - (void)replaceSelectionWithArchive:(WebArchive *)archive
3772 {
3773     [[[self _selectedOrMainFrame] _dataSource] _replaceSelectionWithArchive:archive selectReplacement:YES];
3774 }
3775
3776 - (void)deleteSelection
3777 {
3778     WebFrame *webFrame = [self _selectedOrMainFrame];
3779     Frame* coreFrame = core(webFrame);
3780     if (coreFrame)
3781         coreFrame->editor()->deleteSelectionWithSmartDelete([(WebHTMLView *)[[webFrame frameView] documentView] _canSmartCopyOrDelete]);
3782 }
3783     
3784 - (void)applyStyle:(DOMCSSStyleDeclaration *)style
3785 {
3786     // We don't know enough at thls level to pass in a relevant WebUndoAction; we'd have to
3787     // change the API to allow this.
3788     WebFrame *webFrame = [self _selectedOrMainFrame];
3789     Frame* coreFrame = core(webFrame);
3790     if (coreFrame)
3791         coreFrame->editor()->applyStyle(core(style));
3792 }
3793
3794 @end
3795
3796 @implementation WebView (WebViewEditingActions)
3797
3798 - (void)_performResponderOperation:(SEL)selector with:(id)parameter
3799 {
3800     static BOOL reentered = NO;
3801     if (reentered) {
3802         [[self nextResponder] tryToPerform:selector with:parameter];
3803         return;
3804     }
3805
3806     // There are two possibilities here.
3807     //
3808     // One is that WebView has been called in its role as part of the responder chain.
3809     // In that case, it's fine to call the first responder and end up calling down the
3810     // responder chain again. Later we will return here with reentered = YES and continue
3811     // past the WebView.
3812     //
3813     // The other is that we are being called directly, in which case we want to pass the
3814     // selector down to the view inside us that can handle it, and continue down the
3815     // responder chain as usual.
3816
3817     // Pass this selector down to the first responder.
3818     NSResponder *responder = [self _responderForResponderOperations];
3819     reentered = YES;
3820     [responder tryToPerform:selector with:parameter];
3821     reentered = NO;
3822 }
3823
3824 #define FORWARD(name) \
3825     - (void)name:(id)sender { [self _performResponderOperation:_cmd with:sender]; }
3826
3827 FOR_EACH_RESPONDER_SELECTOR(FORWARD)
3828
3829 - (void)insertText:(NSString *)text
3830 {
3831     [self _performResponderOperation:_cmd with:text];
3832 }
3833
3834 @end
3835
3836 @implementation WebView (WebViewEditingInMail)
3837
3838 - (void)_insertNewlineInQuotedContent;
3839 {
3840     [[self _selectedOrMainFrame] _insertParagraphSeparatorInQuotedContent];
3841 }
3842
3843 - (void)_replaceSelectionWithNode:(DOMNode *)node matchStyle:(BOOL)matchStyle
3844 {
3845     [[self _selectedOrMainFrame] _replaceSelectionWithNode:node selectReplacement:YES smartReplace:NO matchStyle:matchStyle];
3846 }
3847
3848 @end
3849
3850 static WebFrameView *containingFrameView(NSView *view)
3851 {
3852     while (view && ![view isKindOfClass:[WebFrameView class]])
3853         view = [view superview];
3854     return (WebFrameView *)view;    
3855 }
3856
3857 @implementation WebView (WebFileInternal)
3858
3859 + (void)_setCacheModel:(WebCacheModel)cacheModel
3860 {
3861     if (s_didSetCacheModel && cacheModel == s_cacheModel)
3862         return;
3863
3864     NSString *nsurlCacheDirectory = [(NSString *)WKCopyFoundationCacheDirectory() autorelease];
3865     if (!nsurlCacheDirectory)
3866         nsurlCacheDirectory = NSHomeDirectory();
3867
3868     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
3869     // count doesn't align exactly to a megabyte boundary.
3870     vm_size_t memSize = WebMemorySize() / 1024 / 1000;
3871     unsigned long long diskFreeSize = WebVolumeFreeSize(nsurlCacheDirectory) / 1024 / 1000;
3872     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
3873
3874     unsigned cacheTotalCapacity = 0;
3875     unsigned cacheMinDeadCapacity = 0;
3876     unsigned cacheMaxDeadCapacity = 0;
3877
3878     unsigned pageCacheCapacity = 0;
3879
3880     NSUInteger nsurlCacheMemoryCapacity = 0;
3881     NSUInteger nsurlCacheDiskCapacity = 0;
3882
3883     switch (cacheModel) {
3884     case WebCacheModelDocumentViewer: {
3885         // Page cache capacity (in pages)
3886         pageCacheCapacity = 0;
3887
3888         // Object cache capacities (in bytes)
3889         if (memSize >= 4096)
3890             cacheTotalCapacity = 256 * 1024 * 1024;
3891         else if (memSize >= 3072)
3892             cacheTotalCapacity = 192 * 1024 * 1024;
3893         else if (memSize >= 2048)
3894             cacheTotalCapacity = 128 * 1024 * 1024;
3895         else if (memSize >= 1536)
3896             cacheTotalCapacity = 86 * 1024 * 1024;
3897         else if (memSize >= 1024)
3898             cacheTotalCapacity = 64 * 1024 * 1024;
3899         else if (memSize >= 512)
3900             cacheTotalCapacity = 32 * 1024 * 1024;
3901         else if (memSize >= 256)
3902             cacheTotalCapacity = 16 * 1024 * 1024; 
3903
3904         cacheMinDeadCapacity = 0;
3905         cacheMaxDeadCapacity = 0;
3906
3907         // Foundation memory cache capacity (in bytes)
3908         nsurlCacheMemoryCapacity = 0;
3909
3910         // Foundation disk cache capacity (in bytes)
3911         nsurlCacheDiskCapacity = [nsurlCache diskCapacity];
3912
3913         break;
3914     }
3915     case WebCacheModelDocumentBrowser: {
3916         // Page cache capacity (in pages)
3917         if (memSize >= 1024)
3918             pageCacheCapacity = 3;
3919         else if (memSize >= 512)
3920             pageCacheCapacity = 2;
3921         else if (memSize >= 256)
3922             pageCacheCapacity = 1;
3923         else
3924             pageCacheCapacity = 0;
3925
3926         // Object cache capacities (in bytes)
3927         if (memSize >= 4096)
3928             cacheTotalCapacity = 256 * 1024 * 1024;
3929         else if (memSize >= 3072)
3930             cacheTotalCapacity = 192 * 1024 * 1024;
3931         else if (memSize >= 2048)
3932             cacheTotalCapacity = 128 * 1024 * 1024;
3933         else if (memSize >= 1536)
3934             cacheTotalCapacity = 86 * 1024 * 1024;
3935         else if (memSize >= 1024)
3936             cacheTotalCapacity = 64 * 1024 * 1024;
3937         else if (memSize >= 512)
3938             cacheTotalCapacity = 32 * 1024 * 1024;
3939         else if (memSize >= 256)
3940             cacheTotalCapacity = 16 * 1024 * 1024; 
3941
3942         cacheMinDeadCapacity = cacheTotalCapacity / 8;
3943         cacheMaxDeadCapacity = cacheTotalCapacity / 4;
3944
3945         // Foundation memory cache capacity (in bytes)
3946         if (memSize >= 2048)
3947             nsurlCacheMemoryCapacity = 4 * 1024 * 1024;
3948         else if (memSize >= 1024)
3949             nsurlCacheMemoryCapacity = 2 * 1024 * 1024;
3950         else if (memSize >= 512)
3951             nsurlCacheMemoryCapacity = 1 * 1024 * 1024;
3952         else
3953             nsurlCacheMemoryCapacity =      512 * 1024; 
3954
3955         // Foundation disk cache capacity (in bytes)
3956         if (diskFreeSize >= 16384)
3957             nsurlCacheDiskCapacity = 50 * 1024 * 1024;
3958         else if (diskFreeSize >= 8192)
3959             nsurlCacheDiskCapacity = 40 * 1024 * 1024;
3960         else if (diskFreeSize >= 4096)
3961             nsurlCacheDiskCapacity = 30 * 1024 * 1024;
3962         else
3963             nsurlCacheDiskCapacity = 20 * 1024 * 1024;
3964
3965         break;
3966     }
3967     case WebCacheModelPrimaryWebBrowser: {
3968         // Page cache capacity (in pages)
3969         // (Research indicates that value / page drops substantially after 3 pages.)
3970         if (memSize >= 8192)
3971             pageCacheCapacity = 7;
3972         if (memSize >= 4096)
3973             pageCacheCapacity = 6;
3974         else if (memSize >= 2048)
3975             pageCacheCapacity = 5;
3976         else if (memSize >= 1024)
3977             pageCacheCapacity = 4;
3978         else if (memSize >= 512)
3979             pageCacheCapacity = 3;
3980         else if (memSize >= 256)
3981             pageCacheCapacity = 2;
3982         else
3983             pageCacheCapacity = 1;
3984
3985         // Object cache capacities (in bytes)
3986         // (Testing indicates that value / MB depends heavily on content and
3987         // browsing pattern. Even growth above 128MB can have substantial 
3988         // value / MB for some content / browsing patterns.)
3989         if (memSize >= 4096)
3990             cacheTotalCapacity = 512 * 1024 * 1024;
3991         else if (memSize >= 3072)
3992             cacheTotalCapacity = 384 * 1024 * 1024;
3993         else if (memSize >= 2048)
3994             cacheTotalCapacity = 256 * 1024 * 1024;
3995         else if (memSize >= 1536)
3996             cacheTotalCapacity = 172 * 1024 * 1024;
3997         else if (memSize >= 1024)
3998             cacheTotalCapacity = 128 * 1024 * 1024;
3999         else if (memSize >= 512)
4000             cacheTotalCapacity = 64 * 1024 * 1024;
4001         else if (memSize >= 256)
4002             cacheTotalCapacity = 32 * 1024 * 1024; 
4003
4004         cacheMinDeadCapacity = cacheTotalCapacity / 4;
4005         cacheMaxDeadCapacity = cacheTotalCapacity / 2;
4006
4007         // This code is here to avoid a PLT regression. We can remove it if we
4008         // can prove that the overall system gain would justify the regression.
4009         cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
4010
4011         // Foundation memory cache capacity (in bytes)
4012         // (These values are small because WebCore does most caching itself.)
4013         if (memSize >= 1024)
4014             nsurlCacheMemoryCapacity = 4 * 1024 * 1024;
4015         else if (memSize >= 512)
4016             nsurlCacheMemoryCapacity = 2 * 1024 * 1024;
4017         else if (memSize >= 256)
4018             nsurlCacheMemoryCapacity = 1 * 1024 * 1024;
4019         else
4020             nsurlCacheMemoryCapacity =      512 * 1024; 
4021
4022         // Foundation disk cache capacity (in bytes)
4023         if (diskFreeSize >= 16384)
4024             nsurlCacheDiskCapacity = 175 * 1024 * 1024;
4025         else if (diskFreeSize >= 8192)
4026             nsurlCacheDiskCapacity = 150 * 1024 * 1024;
4027         else if (diskFreeSize >= 4096)
4028             nsurlCacheDiskCapacity = 125 * 1024 * 1024;
4029         else if (diskFreeSize >= 2048)
4030             nsurlCacheDiskCapacity = 100 * 1024 * 1024;
4031         else if (diskFreeSize >= 1024)
4032             nsurlCacheDiskCapacity = 75 * 1024 * 1024;
4033         else
4034             nsurlCacheDiskCapacity = 50 * 1024 * 1024;
4035
4036         break;
4037     }
4038     default:
4039         ASSERT_NOT_REACHED();
4040     };
4041
4042 #ifdef BUILDING_ON_TIGER
4043     // Don't use a big Foundation disk cache on Tiger because, according to the 
4044     // PLT, the Foundation disk cache on Tiger is slower than the network. 
4045     nsurlCacheDiskCapacity = [nsurlCache diskCapacity];
4046 #endif
4047
4048     // Don't shrink a big disk cache, since that would cause churn.
4049     nsurlCacheDiskCapacity = max(nsurlCacheDiskCapacity, [nsurlCache diskCapacity]);
4050
4051     cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
4052     pageCache()->setCapacity(pageCacheCapacity);
4053     [nsurlCache setMemoryCapacity:nsurlCacheMemoryCapacity];
4054     [nsurlCache setDiskCapacity:nsurlCacheDiskCapacity];
4055
4056     s_cacheModel = cacheModel;
4057     s_didSetCacheModel = YES;
4058 }
4059
4060 + (WebCacheModel)_cacheModel
4061 {
4062     return s_cacheModel;
4063 }
4064
4065 + (WebCacheModel)_didSetCacheModel
4066 {
4067     return s_didSetCacheModel;
4068 }
4069
4070 + (WebCacheModel)_maxCacheModelInAnyInstance
4071 {
4072     WebCacheModel cacheModel = WebCacheModelDocumentViewer;
4073     NSEnumerator *enumerator = [(NSMutableSet *)allWebViewsSet objectEnumerator];
4074     while (WebPreferences *preferences = [[enumerator nextObject] preferences])
4075         cacheModel = max(cacheModel, [preferences cacheModel]);
4076     return cacheModel;
4077 }
4078
4079 + (void)_preferencesChangedNotification:(NSNotification *)notification
4080 {
4081     WebPreferences *preferences = (WebPreferences *)[notification object];
4082     ASSERT([preferences isKindOfClass:[WebPreferences class]]);
4083
4084     WebCacheModel cacheModel = [preferences cacheModel];
4085     if (![self _didSetCacheModel] || cacheModel > [self _cacheModel])
4086         [self _setCacheModel:cacheModel];
4087     else if (cacheModel < [self _cacheModel])
4088         [self _setCacheModel:max([[WebPreferences standardPreferences] cacheModel], [self _maxCacheModelInAnyInstance])];
4089 }
4090
4091 + (void)_preferencesRemovedNotification:(NSNotification *)notification
4092 {
4093     WebPreferences *preferences = (WebPreferences *)[notification object];
4094     ASSERT([preferences isKindOfClass:[WebPreferences class]]);
4095
4096     if ([preferences cacheModel] == [self _cacheModel])
4097         [self _setCacheModel:max([[WebPreferences standardPreferences] cacheModel], [self _maxCacheModelInAnyInstance])];
4098 }
4099
4100 - (WebFrame *)_focusedFrame
4101 {
4102     NSResponder *resp = [[self window] firstResponder];
4103     if (resp && [resp isKindOfClass:[NSView class]] && [(NSView *)resp isDescendantOf:[[self mainFrame] frameView]]) {
4104         WebFrameView *frameView = containingFrameView((NSView *)resp);
4105         ASSERT(frameView != nil);
4106         return [frameView webFrame];
4107     }
4108     
4109     return nil;
4110 }
4111
4112 - (WebFrame *)_selectedOrMainFrame
4113 {
4114     WebFrame *result = [self selectedFrame];
4115     if (result == nil)
4116         result = [self mainFrame];
4117     return result;
4118 }
4119
4120 - (BOOL)_isLoading
4121 {
4122     WebFrame *mainFrame = [self mainFrame];
4123     return [[mainFrame _dataSource] isLoading]
4124         || [[mainFrame provisionalDataSource] isLoading];
4125 }
4126
4127 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point
4128 {
4129     if (_private->closed)
4130         return nil;
4131     NSView *view = [self hitTest:[[self superview] convertPoint:point fromView:nil]];
4132     if (![view isDescendantOf:[[self mainFrame] frameView]])
4133         return nil;
4134     WebFrameView *frameView = containingFrameView(view);
4135     ASSERT(frameView);
4136     return frameView;
4137 }
4138
4139 + (void)_preflightSpellCheckerNow:(id)sender
4140 {
4141     [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
4142 }
4143
4144 + (void)_preflightSpellChecker
4145 {
4146     // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
4147     if ([NSSpellChecker sharedSpellCheckerExists]) {
4148         [self _preflightSpellCheckerNow:self];
4149     } else {
4150         [self performSelector:@selector(_preflightSpellCheckerNow:) withObject:self afterDelay:2.0];
4151     }
4152 }
4153
4154 - (BOOL)_continuousCheckingAllowed
4155 {
4156     static BOOL allowContinuousSpellChecking = YES;
4157     static BOOL readAllowContinuousSpellCheckingDefault = NO;
4158     if (!readAllowContinuousSpellCheckingDefault) {
4159         if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NSAllowContinuousSpellChecking"]) {
4160             allowContinuousSpellChecking = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSAllowContinuousSpellChecking"];
4161         }
4162         readAllowContinuousSpellCheckingDefault = YES;
4163     }
4164     return allowContinuousSpellChecking;
4165 }
4166
4167 - (NSResponder *)_responderForResponderOperations
4168 {
4169     NSResponder *responder = [[self window] firstResponder];
4170     WebFrameView *mainFrameView = [[self mainFrame] frameView];
4171     
4172     // If the current responder is outside of the webview, use our main frameView or its
4173     // document view. We also do this for subviews of self that are siblings of the main
4174     // frameView since clients might insert non-webview-related views there (see 4552713).
4175     if (responder != self && ![mainFrameView _web_firstResponderIsSelfOrDescendantView]) {
4176         responder = [mainFrameView documentView];
4177         if (!responder)
4178             responder = mainFrameView;
4179     }
4180     return responder;
4181 }
4182
4183 - (void)_openFrameInNewWindowFromMenu:(NSMenuItem *)sender
4184 {
4185     ASSERT_ARG(sender, [sender isKindOfClass:[NSMenuItem class]]);
4186
4187     NSDictionary *element = [sender representedObject];
4188     ASSERT([element isKindOfClass:[NSDictionary class]]);
4189     
4190     NSURLRequest *request = [[[[element objectForKey:WebElementFrameKey] dataSource] request] copy];
4191     ASSERT(request);
4192     
4193     [self _openNewWindowWithRequest:request];
4194     [request release];
4195 }
4196
4197 - (void)_searchWithGoogleFromMenu:(id)sender
4198 {
4199     id documentView = [[[self selectedFrame] frameView] documentView];
4200     if (![documentView conformsToProtocol:@protocol(WebDocumentText)]) {
4201         return;
4202     }
4203     
4204     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
4205     if ([selectedString length] == 0) {
4206         return;
4207     }
4208     
4209     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName];
4210     [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
4211     NSMutableString *s = [selectedString mutableCopy];
4212     const unichar nonBreakingSpaceCharacter = 0xA0;
4213     NSString *nonBreakingSpaceString = [NSString stringWithCharacters:&nonBreakingSpaceCharacter length:1];
4214     [s replaceOccurrencesOfString:nonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
4215     [pasteboard setString:s forType:NSStringPboardType];
4216     [s release];
4217     
4218     // FIXME: seems fragile to use the service by name, but this is what AppKit does
4219     NSPerformService(@"Search With Google", pasteboard);
4220 }
4221
4222 - (void)_searchWithSpotlightFromMenu:(id)sender
4223 {
4224     id documentView = [[[self selectedFrame] frameView] documentView];
4225     if (![documentView conformsToProtocol:@protocol(WebDocumentText)])
4226         return;
4227     
4228     NSString *selectedString = [(id <WebDocumentText>)documentView selectedString];
4229     if ([selectedString length] == 0) {
4230         return;
4231     }
4232
4233     (void)HISearchWindowShow((CFStringRef)selectedString, kNilOptions);
4234 }
4235 @end
4236
4237 @implementation WebView (WebViewInternal)
4238
4239 - (BOOL)_becomingFirstResponderFromOutside
4240 {
4241     return _private->becomingFirstResponderFromOutside;
4242 }
4243
4244 - (void)_receivedIconChangedNotification:(NSNotification *)notification
4245 {
4246     // Get the URL for this notification
4247     NSDictionary *userInfo = [notification userInfo];
4248     ASSERT([userInfo isKindOfClass:[NSDictionary class]]);
4249     NSString *urlString = [userInfo objectForKey:WebIconNotificationUserInfoURLKey];
4250     ASSERT([urlString isKindOfClass:[NSString class]]);
4251     
4252     // If that URL matches the current main frame, dispatch the delegate call, which will also unregister
4253     // us for this notification
4254     if ([[self mainFrameURL] isEqualTo:urlString])
4255         [self _dispatchDidReceiveIconFromWebFrame:[self mainFrame]];
4256 }
4257
4258 - (void)_registerForIconNotification:(BOOL)listen
4259 {
4260     if (listen)
4261         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_receivedIconChangedNotification:) name:WebIconDatabaseDidAddIconNotification object:nil];        
4262     else
4263         [[NSNotificationCenter defaultCenter] removeObserver:self name:WebIconDatabaseDidAddIconNotification object:nil];
4264 }
4265
4266 - (void)_dispatchDidReceiveIconFromWebFrame:(WebFrame *)webFrame
4267 {
4268     // FIXME: This willChangeValueForKey call is too late, because the icon has already changed by now.
4269     [self _willChangeValueForKey:_WebMainFrameIconKey];
4270     
4271     // Since we definitely have an icon and are about to send out the delegate call for that, this WebView doesn't need to listen for the general
4272     // notification any longer
4273     [self _registerForIconNotification:NO];
4274
4275     WebFrameLoadDelegateImplementationCache* cache = &_private->frameLoadDelegateImplementations;
4276     if (cache->didReceiveIconForFrameFunc) {
4277         Image* image = iconDatabase()->iconForPageURL(core(webFrame)->loader()->url().string(), IntSize(16, 16));
4278         if (NSImage *icon = webGetNSImage(image, NSMakeSize(16, 16)))
4279             CallFrameLoadDelegate(cache->didReceiveIconForFrameFunc, self, @selector(webView:didReceiveIcon:forFrame:), icon, webFrame);
4280     }
4281
4282     [self _didChangeValueForKey:_WebMainFrameIconKey];
4283 }
4284
4285 - (NSString *)_userVisibleBundleVersionFromFullVersion:(NSString *)fullVersion
4286 {
4287     // If the version is 4 digits long or longer, then the first digit represents
4288     // the version of the OS. Our user agent string should not include this first digit,
4289     // so strip it off and report the rest as the version. <rdar://problem/4997547>
4290     NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
4291     if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
4292         return [fullVersion substringFromIndex:1];
4293     if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
4294         return [fullVersion substringFromIndex:1];
4295     return fullVersion;
4296 }
4297
4298 static inline int callGestalt(OSType selector)
4299 {
4300     SInt32 value = 0;
4301     Gestalt(selector, &value);
4302     return value;
4303 }
4304
4305 // Uses underscores instead of dots because if "4." ever appears in a user agent string, old DHTML libraries treat it as Netscape 4.
4306 static NSString *createMacOSXVersionString()
4307 {
4308     // Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want.
4309     int major = callGestalt(gestaltSystemVersionMajor);
4310     ASSERT(major);
4311
4312     int minor = callGestalt(gestaltSystemVersionMinor);
4313     int bugFix = callGestalt(gestaltSystemVersionBugFix);
4314     if (bugFix)
4315         return [[NSString alloc] initWithFormat:@"%d_%d_%d", major, minor, bugFix];
4316     if (minor)
4317         return [[NSString alloc] initWithFormat:@"%d_%d", major, minor];
4318     return [[NSString alloc] initWithFormat:@"%d", major];
4319 }
4320
4321 - (NSString *)_userAgentWithApplicationName:(NSString *)applicationName andWebKitVersion:(NSString *)version
4322 {
4323     // Note: Do *not* move the initialization of osVersion into the declaration.
4324     // Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
4325     static NSString *osVersion;
4326     if (!osVersion)
4327         osVersion = createMacOSXVersionString();
4328     NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
4329     if ([applicationName length])
4330         return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X %@; %@) AppleWebKit/%@ (KHTML, like Gecko) %@",
4331             osVersion, language, version, applicationName];
4332     return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X %@; %@) AppleWebKit/%@ (KHTML, like Gecko)",
4333         osVersion, language, version];
4334 }
4335
4336 // Get the appropriate user-agent string for a particular URL.
4337 - (WebCore::String)_userAgentForURL:(const WebCore::KURL&)url
4338 {