2010-04-30 Simon Fraser <simon.fraser@apple.com>
[WebKit-https.git] / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 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 #import "WebViewData.h"
32
33 #import "DOMCSSStyleDeclarationInternal.h"
34 #import "DOMNodeInternal.h"
35 #import "DOMRangeInternal.h"
36 #import "WebBackForwardListInternal.h"
37 #import "WebBaseNetscapePluginView.h"
38 #import "WebCache.h"
39 #import "WebChromeClient.h"
40 #import "WebContextMenuClient.h"
41 #import "WebDOMOperationsPrivate.h"
42 #import "WebDataSourceInternal.h"
43 #import "WebDatabaseManagerInternal.h"
44 #import "WebDefaultEditingDelegate.h"
45 #import "WebDefaultPolicyDelegate.h"
46 #import "WebDefaultUIDelegate.h"
47 #import "WebDelegateImplementationCaching.h"
48 #import "WebDocument.h"
49 #import "WebDocumentInternal.h"
50 #import "WebDownload.h"
51 #import "WebDownloadInternal.h"
52 #import "WebDragClient.h"
53 #import "WebDynamicScrollBarsViewInternal.h"
54 #import "WebEditingDelegate.h"
55 #import "WebEditorClient.h"
56 #import "WebFormDelegatePrivate.h"
57 #import "WebFrameInternal.h"
58 #import "WebFrameViewInternal.h"
59 #import "WebGeolocationControllerClient.h"
60 #import "WebGeolocationPositionInternal.h"
61 #import "WebHTMLRepresentation.h"
62 #import "WebHTMLViewInternal.h"
63 #import "WebHistoryItemInternal.h"
64 #import "WebIconDatabaseInternal.h"
65 #import "WebInspector.h"
66 #import "WebInspectorClient.h"
67 #import "WebKitErrors.h"
68 #import "WebKitLogging.h"
69 #import "WebKitNSStringExtras.h"
70 #import "WebKitStatisticsPrivate.h"
71 #import "WebKitSystemBits.h"
72 #import "WebKitVersionChecks.h"
73 #import "WebLocalizableStrings.h"
74 #import "WebNSDataExtras.h"
75 #import "WebNSDataExtrasPrivate.h"
76 #import "WebNSDictionaryExtras.h"
77 #import "WebNSEventExtras.h"
78 #import "WebNSObjectExtras.h"
79 #import "WebNSPasteboardExtras.h"
80 #import "WebNSPrintOperationExtras.h"
81 #import "WebNSURLExtras.h"
82 #import "WebNSURLRequestExtras.h"
83 #import "WebNSUserDefaultsExtras.h"
84 #import "WebNSViewExtras.h"
85 #import "WebNodeHighlight.h"
86 #import "WebPDFView.h"
87 #import "WebPanelAuthenticationHandler.h"
88 #import "WebPasteboardHelper.h"
89 #import "WebPluginDatabase.h"
90 #import "WebPluginHalterClient.h"
91 #import "WebPolicyDelegate.h"
92 #import "WebPreferenceKeysPrivate.h"
93 #import "WebPreferencesPrivate.h"
94 #import "WebScriptDebugDelegate.h"
95 #import "WebScriptWorldInternal.h"
96 #import "WebSystemInterface.h"
97 #import "WebTextCompletionController.h"
98 #import "WebTextIterator.h"
99 #import "WebUIDelegate.h"
100 #import "WebUIDelegatePrivate.h"
101 #import "WebVideoFullscreenController.h"
102 #import <CoreFoundation/CFSet.h>
103 #import <Foundation/NSURLConnection.h>
104 #import <JavaScriptCore/APICast.h>
105 #import <JavaScriptCore/JSValueRef.h>
106 #import <WebCore/ApplicationCacheStorage.h>
107 #import <WebCore/BackForwardList.h>
108 #import <WebCore/Cache.h>
109 #import <WebCore/ColorMac.h>
110 #import <WebCore/CSSComputedStyleDeclaration.h>
111 #import <WebCore/Cursor.h>
112 #import <WebCore/Database.h>
113 #import <WebCore/Document.h>
114 #import <WebCore/DocumentLoader.h>
115 #import <WebCore/DragController.h>
116 #import <WebCore/DragData.h>
117 #import <WebCore/Editor.h>
118 #import <WebCore/EventHandler.h>
119 #import <WebCore/ExceptionHandlers.h>
120 #import <WebCore/FocusController.h>
121 #import <WebCore/Frame.h>
122 #import <WebCore/FrameLoader.h>
123 #import <WebCore/FrameTree.h>
124 #import <WebCore/FrameView.h>
125 #import <WebCore/GCController.h>
126 #import <WebCore/HTMLMediaElement.h>
127 #import <WebCore/HTMLNames.h>
128 #import <WebCore/HistoryItem.h>
129 #import <WebCore/IconDatabase.h>
130 #import <WebCore/JSCSSStyleDeclaration.h>
131 #import <WebCore/JSElement.h>
132 #import <WebCore/Logging.h>
133 #import <WebCore/MIMETypeRegistry.h>
134 #import <WebCore/Page.h>
135 #import <WebCore/PageCache.h>
136 #import <WebCore/PageGroup.h>
137 #import <WebCore/PlatformMouseEvent.h>
138 #import <WebCore/ProgressTracker.h>
139 #import <WebCore/RenderWidget.h>
140 #import <WebCore/ResourceHandle.h>
141 #import <WebCore/RuntimeApplicationChecks.h>
142 #import <WebCore/ScriptController.h>
143 #import <WebCore/ScriptValue.h>
144 #import <WebCore/SecurityOrigin.h>
145 #import <WebCore/SelectionController.h>
146 #import <WebCore/Settings.h>
147 #import <WebCore/TextResourceDecoder.h>
148 #import <WebCore/ThreadCheck.h>
149 #import <WebCore/WebCoreObjCExtras.h>
150 #import <WebCore/WebCoreView.h>
151 #import <WebCore/Widget.h>
152 #import <WebKit/DOM.h>
153 #import <WebKit/DOMExtensions.h>
154 #import <WebKit/DOMPrivate.h>
155 #import <WebKitSystemInterface.h>
156 #import <mach-o/dyld.h>
157 #import <objc/objc-auto.h>
158 #import <objc/objc-runtime.h>
159 #import <runtime/ArrayPrototype.h>
160 #import <runtime/DateInstance.h>
161 #import <runtime/InitializeThreading.h>
162 #import <runtime/JSLock.h>
163 #import <runtime/JSValue.h>
164 #import <wtf/Assertions.h>
165 #import <wtf/HashTraits.h>
166 #import <wtf/RefCountedLeakCounter.h>
167 #import <wtf/RefPtr.h>
168 #import <wtf/StdLibExtras.h>
169 #import <wtf/Threading.h>
170
171 #if ENABLE(DASHBOARD_SUPPORT)
172 #import <WebKit/WebDashboardRegion.h>
173 #endif
174
175 #if ENABLE(CLIENT_BASED_GEOLOCATION)
176 #import <WebCore/GeolocationController.h>
177 #import <WebCore/GeolocationError.h>
178 #endif
179
180 @interface NSSpellChecker (WebNSSpellCheckerDetails)
181 - (void)_preflightChosenSpellServer;
182 @end
183
184 @interface NSView (WebNSViewDetails)
185 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
186 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
187 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
188 @end
189
190 @interface NSWindow (WebNSWindowDetails) 
191 - (id)_oldFirstResponderBeforeBecoming;
192 @end
193
194 using namespace WebCore;
195 using namespace JSC;
196
197 #if defined(__ppc__) || defined(__ppc64__)
198 #define PROCESSOR "PPC"
199 #elif defined(__i386__) || defined(__x86_64__)
200 #define PROCESSOR "Intel"
201 #else
202 #error Unknown architecture
203 #endif
204
205 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
206 macro(alignCenter) \
207 macro(alignJustified) \
208 macro(alignLeft) \
209 macro(alignRight) \
210 macro(capitalizeWord) \
211 macro(centerSelectionInVisibleArea) \
212 macro(changeAttributes) \
213 macro(changeBaseWritingDirection) \
214 macro(changeBaseWritingDirectionToLTR) \
215 macro(changeBaseWritingDirectionToRTL) \
216 macro(changeColor) \
217 macro(changeDocumentBackgroundColor) \
218 macro(changeFont) \
219 macro(changeSpelling) \
220 macro(checkSpelling) \
221 macro(complete) \
222 macro(copy) \
223 macro(copyFont) \
224 macro(cut) \
225 macro(delete) \
226 macro(deleteBackward) \
227 macro(deleteBackwardByDecomposingPreviousCharacter) \
228 macro(deleteForward) \
229 macro(deleteToBeginningOfLine) \
230 macro(deleteToBeginningOfParagraph) \
231 macro(deleteToEndOfLine) \
232 macro(deleteToEndOfParagraph) \
233 macro(deleteToMark) \
234 macro(deleteWordBackward) \
235 macro(deleteWordForward) \
236 macro(ignoreSpelling) \
237 macro(indent) \
238 macro(insertBacktab) \
239 macro(insertLineBreak) \
240 macro(insertNewline) \
241 macro(insertNewlineIgnoringFieldEditor) \
242 macro(insertParagraphSeparator) \
243 macro(insertTab) \
244 macro(insertTabIgnoringFieldEditor) \
245 macro(lowercaseWord) \
246 macro(makeBaseWritingDirectionLeftToRight) \
247 macro(makeBaseWritingDirectionRightToLeft) \
248 macro(makeTextWritingDirectionLeftToRight) \
249 macro(makeTextWritingDirectionNatural) \
250 macro(makeTextWritingDirectionRightToLeft) \
251 macro(moveBackward) \
252 macro(moveBackwardAndModifySelection) \
253 macro(moveDown) \
254 macro(moveDownAndModifySelection) \
255 macro(moveForward) \
256 macro(moveForwardAndModifySelection) \
257 macro(moveLeft) \
258 macro(moveLeftAndModifySelection) \
259 macro(moveParagraphBackwardAndModifySelection) \
260 macro(moveParagraphForwardAndModifySelection) \
261 macro(moveRight) \
262 macro(moveRightAndModifySelection) \
263 macro(moveToBeginningOfDocument) \
264 macro(moveToBeginningOfDocumentAndModifySelection) \
265 macro(moveToBeginningOfLine) \
266 macro(moveToBeginningOfLineAndModifySelection) \
267 macro(moveToBeginningOfParagraph) \
268 macro(moveToBeginningOfParagraphAndModifySelection) \
269 macro(moveToBeginningOfSentence) \
270 macro(moveToBeginningOfSentenceAndModifySelection) \
271 macro(moveToEndOfDocument) \
272 macro(moveToEndOfDocumentAndModifySelection) \
273 macro(moveToEndOfLine) \
274 macro(moveToEndOfLineAndModifySelection) \
275 macro(moveToEndOfParagraph) \
276 macro(moveToEndOfParagraphAndModifySelection) \
277 macro(moveToEndOfSentence) \
278 macro(moveToEndOfSentenceAndModifySelection) \
279 macro(moveToLeftEndOfLine) \
280 macro(moveToLeftEndOfLineAndModifySelection) \
281 macro(moveToRightEndOfLine) \
282 macro(moveToRightEndOfLineAndModifySelection) \
283 macro(moveUp) \
284 macro(moveUpAndModifySelection) \
285 macro(moveWordBackward) \
286 macro(moveWordBackwardAndModifySelection) \
287 macro(moveWordForward) \
288 macro(moveWordForwardAndModifySelection) \
289 macro(moveWordLeft) \
290 macro(moveWordLeftAndModifySelection) \
291 macro(moveWordRight) \
292 macro(moveWordRightAndModifySelection) \
293 macro(outdent) \
294 macro(orderFrontSubstitutionsPanel) \
295 macro(pageDown) \
296 macro(pageDownAndModifySelection) \
297 macro(pageUp) \
298 macro(pageUpAndModifySelection) \
299 macro(paste) \
300 macro(pasteAsPlainText) \
301 macro(pasteAsRichText) \
302 macro(pasteFont) \
303 macro(performFindPanelAction) \
304 macro(scrollLineDown) \
305 macro(scrollLineUp) \
306 macro(scrollPageDown) \
307 macro(scrollPageUp) \
308 macro(scrollToBeginningOfDocument) \
309 macro(scrollToEndOfDocument) \
310 macro(selectAll) \
311 macro(selectLine) \
312 macro(selectParagraph) \
313 macro(selectSentence) \
314 macro(selectToMark) \
315 macro(selectWord) \
316 macro(setMark) \
317 macro(showGuessPanel) \
318 macro(startSpeaking) \
319 macro(stopSpeaking) \
320 macro(subscript) \
321 macro(superscript) \
322 macro(swapWithMark) \
323 macro(takeFindStringFromSelection) \
324 macro(toggleBaseWritingDirection) \
325 macro(transpose) \
326 macro(underline) \
327 macro(unscript) \
328 macro(uppercaseWord) \
329 macro(yank) \
330 macro(yankAndSelect) \
331
332 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
333 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
334
335 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
336 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
337 #define UniversalAccessDomain CFSTR("com.apple.universalaccess")
338
339 static BOOL s_didSetCacheModel;
340 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
341
342 #ifndef NDEBUG
343 static const char webViewIsOpen[] = "At least one WebView is still open.";
344 #endif
345
346 @interface NSObject (WebValidateWithoutDelegate)
347 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
348 @end
349
350 @interface _WebSafeForwarder : NSObject
351 {
352     id target; // Non-retained. Don't retain delegates.
353     id defaultTarget;
354     BOOL catchExceptions;
355 }
356 - (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget catchExceptions:(BOOL)catchExceptions;
357 @end
358
359 @interface WebView (WebFileInternal)
360 - (BOOL)_isLoading;
361 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
362 - (WebFrame *)_focusedFrame;
363 + (void)_preflightSpellChecker;
364 - (BOOL)_continuousCheckingAllowed;
365 - (NSResponder *)_responderForResponderOperations;
366 #if USE(ACCELERATED_COMPOSITING)
367 - (void)_clearLayerSyncLoopObserver;
368 #endif
369 @end
370
371 static void patchMailRemoveAttributesMethod();
372
373 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
374 NSString *WebElementFrameKey =              @"WebElementFrame";
375 NSString *WebElementImageKey =              @"WebElementImage";
376 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
377 NSString *WebElementImageRectKey =          @"WebElementImageRect";
378 NSString *WebElementImageURLKey =           @"WebElementImageURL";
379 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
380 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
381 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
382 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
383 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
384 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
385 NSString *WebElementTitleKey =              @"WebElementTitle";
386 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
387 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
388 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
389
390 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
391 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
392 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
393
394 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
395 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
396 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
397 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
398 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
399
400 enum { WebViewVersion = 4 };
401
402 #define timedLayoutSize 4096
403
404 static NSMutableSet *schemesWithRepresentationsSet;
405
406 NSString *_WebCanGoBackKey =            @"canGoBack";
407 NSString *_WebCanGoForwardKey =         @"canGoForward";
408 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
409 NSString *_WebIsLoadingKey =            @"isLoading";
410 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
411 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
412 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
413 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
414
415 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
416
417 @interface WebProgressItem : NSObject
418 {
419 @public
420     long long bytesReceived;
421     long long estimatedLength;
422 }
423 @end
424
425 @implementation WebProgressItem
426 @end
427
428 static BOOL continuousSpellCheckingEnabled;
429 #ifndef BUILDING_ON_TIGER
430 static BOOL grammarCheckingEnabled;
431 #endif
432 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
433 static BOOL automaticQuoteSubstitutionEnabled;
434 static BOOL automaticLinkDetectionEnabled;
435 static BOOL automaticDashSubstitutionEnabled;
436 static BOOL automaticTextReplacementEnabled;
437 static BOOL automaticSpellingCorrectionEnabled;
438 #endif
439
440 @implementation WebView (AllWebViews)
441
442 static CFSetCallBacks NonRetainingSetCallbacks = {
443     0,
444     NULL,
445     NULL,
446     CFCopyDescription,
447     CFEqual,
448     CFHash
449 };
450
451 static CFMutableSetRef allWebViewsSet;
452
453 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
454 {
455     if (!allWebViewsSet)
456         return;
457
458     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
459 }
460
461 - (void)_removeFromAllWebViewsSet
462 {
463     if (allWebViewsSet)
464         CFSetRemoveValue(allWebViewsSet, self);
465 }
466
467 - (void)_addToAllWebViewsSet
468 {
469     if (!allWebViewsSet)
470         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
471
472     CFSetSetValue(allWebViewsSet, self);
473 }
474
475 @end
476
477 @implementation WebView (WebPrivate)
478
479 static inline int callGestalt(OSType selector)
480 {
481     SInt32 value = 0;
482     Gestalt(selector, &value);
483     return value;
484 }
485
486 // Uses underscores instead of dots because if "4." ever appears in a user agent string, old DHTML libraries treat it as Netscape 4.
487 static NSString *createMacOSXVersionString()
488 {
489     // Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want.
490     int major = callGestalt(gestaltSystemVersionMajor);
491     ASSERT(major);
492
493     int minor = callGestalt(gestaltSystemVersionMinor);
494     int bugFix = callGestalt(gestaltSystemVersionBugFix);
495     if (bugFix)
496         return [[NSString alloc] initWithFormat:@"%d_%d_%d", major, minor, bugFix];
497     if (minor)
498         return [[NSString alloc] initWithFormat:@"%d_%d", major, minor];
499     return [[NSString alloc] initWithFormat:@"%d", major];
500 }
501
502 static NSString *createUserVisibleWebKitVersionString()
503 {
504     // If the version is 4 digits long or longer, then the first digit represents
505     // the version of the OS. Our user agent string should not include this first digit,
506     // so strip it off and report the rest as the version. <rdar://problem/4997547>
507     NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
508     NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
509     if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
510         return [[fullVersion substringFromIndex:1] copy];
511     if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
512         return [[fullVersion substringFromIndex:1] copy];
513     return [fullVersion copy];
514 }
515
516 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
517 {
518     // Note: Do *not* move the initialization of osVersion nor webKitVersion into the declaration.
519     // Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
520     static NSString *osVersion;
521     static NSString *webKitVersion;
522     if (!osVersion)
523         osVersion = createMacOSXVersionString();
524     if (!webKitVersion)
525         webKitVersion = createUserVisibleWebKitVersionString();
526     NSString *language = [NSUserDefaults _webkit_preferredLanguageCode];
527     if ([applicationName length])
528         return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X %@; %@) AppleWebKit/%@ (KHTML, like Gecko) %@", osVersion, language, webKitVersion, applicationName];
529     return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; U; " PROCESSOR " Mac OS X %@; %@) AppleWebKit/%@ (KHTML, like Gecko)", osVersion, language, webKitVersion];
530 }
531
532 static void WebKitInitializeApplicationCachePathIfNecessary()
533 {
534 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
535     static BOOL initialized = NO;
536     if (initialized)
537         return;
538
539     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
540     if (!appName)
541         appName = [[NSProcessInfo processInfo] processName];
542     
543     ASSERT(appName);
544
545     NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
546
547     cacheStorage().setCacheDirectory(cacheDir);
548     initialized = YES;
549 #endif
550 }
551
552 static bool runningLeopardMail()
553 {
554 #ifdef BUILDING_ON_LEOPARD
555     return applicationIsAppleMail();
556 #endif
557     return NO;
558 }
559
560 static bool runningTigerMail()
561 {
562 #ifdef BUILDING_ON_TIGER
563     return applicationIsAppleMail();
564 #endif
565     return NO;    
566 }
567
568 static bool coreVideoHas7228836Fix()
569 {
570 #ifdef BUILDING_ON_LEOPARD
571     NSBundle* coreVideoFrameworkBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/CoreVideo.framework"];
572     double version = [[coreVideoFrameworkBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] doubleValue];
573     return (version >= 48);
574 #endif
575     return true;
576 }
577
578 static bool shouldEnableLoadDeferring()
579 {
580     return !applicationIsAdobeInstaller();
581 }
582
583 - (void)_dispatchPendingLoadRequests
584 {
585     cache()->loader()->servePendingRequests();
586 }
587
588 - (void)_registerDraggedTypes
589 {
590     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
591     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
592     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
593     [types addObjectsFromArray:URLTypes];
594     [self registerForDraggedTypes:[types allObjects]];
595     [types release];
596 }
597
598 - (BOOL)_usesDocumentViews
599 {
600     return _private->usesDocumentViews;
601 }
602
603 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
604 {
605     WebCoreThreadViolationCheckRoundTwo();
606
607 #ifndef NDEBUG
608     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
609 #endif
610     
611     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
612     [standardPreferences willAddToWebView];
613
614     _private->preferences = [standardPreferences retain];
615     _private->catchesDelegateExceptions = YES;
616     _private->mainFrameDocumentReady = NO;
617     _private->drawsBackground = YES;
618     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
619     _private->usesDocumentViews = usesDocumentViews;
620     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
621
622     WebFrameView *frameView = nil;
623     if (_private->usesDocumentViews) {
624         NSRect f = [self frame];
625         frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
626         [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
627         [self addSubview:frameView];
628         [frameView release];
629     }
630
631     static bool didOneTimeInitialization = false;
632     if (!didOneTimeInitialization) {
633         WebKitInitializeLoggingChannelsIfNecessary();
634         WebCore::InitializeLoggingChannelsIfNecessary();
635         [WebHistoryItem initWindowWatcherIfNecessary];
636 #if ENABLE(DATABASE)
637         WebKitInitializeDatabasesIfNecessary();
638 #endif
639         WebKitInitializeApplicationCachePathIfNecessary();
640         patchMailRemoveAttributesMethod();
641         didOneTimeInitialization = true;
642     }
643
644 #if ENABLE(CLIENT_BASED_GEOLOCATION)
645     WebGeolocationControllerClient* geolocationControllerClient = new WebGeolocationControllerClient(self);
646 #else
647     WebGeolocationControllerClient* geolocationControllerClient = 0;
648 #endif
649     _private->page = new Page(new WebChromeClient(self), new WebContextMenuClient(self), new WebEditorClient(self), new WebDragClient(self), new WebInspectorClient(self), new WebPluginHalterClient(self), geolocationControllerClient);
650
651     _private->page->setCanStartMedia([self window]);
652     _private->page->settings()->setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
653
654     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
655
656 #ifndef BUILDING_ON_TIGER
657     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
658 #else
659     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
660 #endif
661
662     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
663         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
664     else
665         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
666
667     [self _addToAllWebViewsSet];
668     [self setGroupName:groupName];
669     
670     // If there's already a next key view (e.g., from a nib), wire it up to our
671     // contained frame view. In any case, wire our next key view up to the our
672     // contained frame view. This works together with our becomeFirstResponder 
673     // and setNextKeyView overrides.
674     NSView *nextKeyView = [self nextKeyView];
675     if (nextKeyView && nextKeyView != frameView)
676         [frameView setNextKeyView:nextKeyView];
677     [super setNextKeyView:frameView];
678
679     if ([[self class] shouldIncludeInWebKitStatistics])
680         ++WebViewCount;
681
682     [self _registerDraggedTypes];
683
684     WebPreferences *prefs = [self preferences];
685     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
686                                                  name:WebPreferencesChangedNotification object:prefs];
687
688     // Post a notification so the WebCore settings update.
689     [[self preferences] _postPreferencesChangesNotification];
690
691     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
692         // Originally, we allowed all local loads.
693         SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForAll);
694     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
695         // Later, we allowed local loads for local URLs and documents loaded
696         // with substitute data.
697         SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalAndSubstituteData);
698     }
699
700     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
701         ResourceHandle::forceContentSniffing();
702 }
703
704 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
705 {
706     self = [super initWithFrame:f];
707     if (!self)
708         return nil;
709
710 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
711     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
712     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
713     // need for Safari to unset it to prevent it from being passed to applications it launches.
714     // Unsetting it when a WebView is first created is as good a place as any.
715     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
716     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
717         unsetenv("DYLD_FRAMEWORK_PATH");
718         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
719     }
720 #endif
721
722     _private = [[WebViewPrivate alloc] init];
723     [self _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:usesDocumentViews];
724     [self setMaintainsBackForwardList: YES];
725     return self;
726 }
727
728 - (BOOL)_mustDrawUnionedRect:(NSRect)rect singleRects:(const NSRect *)rects count:(NSInteger)count
729 {
730     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
731     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
732     // The reason for the workaround is that this method is called explicitly from the code
733     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
734     const int cRectThreshold = 10;
735     const float cWastedSpaceThreshold = 0.75f;
736     BOOL useUnionedRect = (count <= 1) || (count > cRectThreshold);
737     if (!useUnionedRect) {
738         // Attempt to guess whether or not we should use the unioned rect or the individual rects.
739         // We do this by computing the percentage of "wasted space" in the union.  If that wasted space
740         // is too large, then we will do individual rect painting instead.
741         float unionPixels = (rect.size.width * rect.size.height);
742         float singlePixels = 0;
743         for (int i = 0; i < count; ++i)
744             singlePixels += rects[i].size.width * rects[i].size.height;
745         float wastedSpace = 1 - (singlePixels / unionPixels);
746         if (wastedSpace <= cWastedSpaceThreshold)
747             useUnionedRect = YES;
748     }
749     return useUnionedRect;
750 }
751
752 - (void)drawSingleRect:(NSRect)rect
753 {
754     ASSERT(!_private->usesDocumentViews);
755     
756     [NSGraphicsContext saveGraphicsState];
757     NSRectClip(rect);
758
759     @try {
760         [[self mainFrame] _drawRect:rect contentsOnly:NO];
761
762         [[self _UIDelegateForwarder] webView:self didDrawRect:rect];
763
764         if (WebNodeHighlight *currentHighlight = [self currentNodeHighlight])
765             [currentHighlight setNeedsUpdateInTargetViewRect:rect];
766
767         [NSGraphicsContext restoreGraphicsState];
768     } @catch (NSException *localException) {
769         [NSGraphicsContext restoreGraphicsState];
770         LOG_ERROR("Exception caught while drawing: %@", localException);
771         [localException raise];
772     }
773 }
774
775 - (BOOL)isFlipped 
776 {
777     return _private && !_private->usesDocumentViews;
778 }
779
780 - (void)setFrameSize:(NSSize)size
781 {
782     if (!_private->usesDocumentViews && !NSEqualSizes(_private->lastLayoutSize, size)) {
783         Frame* frame = [self _mainCoreFrame];
784         // FIXME: Viewless WebKit is broken with Safari banners (e.g., the Find banner).  We'll have to figure out a way for
785         // Safari to communicate that this space is being consumed.  For WebKit with document views, there's no
786         // need to do an explicit resize, since WebFrameViews have auto resizing turned on and will handle changing
787         // their bounds automatically. See <rdar://problem/6835573> for details.
788         frame->view()->resize(IntSize(size));
789         frame->view()->setNeedsLayout();
790         [self setNeedsDisplay:YES];
791         _private->lastLayoutSize = size;
792     }
793
794     [super setFrameSize:size];
795 }
796
797 #if USE(ACCELERATED_COMPOSITING) || !defined(BUILDING_ON_TIGER)
798
799 - (void)_viewWillDrawInternal
800 {
801     Frame* frame = [self _mainCoreFrame];
802     if (frame && frame->view())
803         frame->view()->layoutIfNeededRecursive();
804 }
805
806 #endif
807
808 #ifndef BUILDING_ON_TIGER
809
810 - (void)viewWillDraw
811 {
812     if (!_private->usesDocumentViews)
813         [self _viewWillDrawInternal];
814     [super viewWillDraw];
815 }
816
817 #endif
818
819
820 - (void)drawRect:(NSRect)rect
821 {
822     if (_private->usesDocumentViews)
823         return [super drawRect:rect];
824     
825     ASSERT_MAIN_THREAD();
826
827     const NSRect *rects;
828     NSInteger count;
829     [self getRectsBeingDrawn:&rects count:&count];
830
831     
832     if ([self _mustDrawUnionedRect:rect singleRects:rects count:count])
833         [self drawSingleRect:rect];
834     else
835         for (int i = 0; i < count; ++i)
836             [self drawSingleRect:rects[i]];
837 }
838
839 + (NSArray *)_supportedMIMETypes
840 {
841     // Load the plug-in DB allowing plug-ins to install types.
842     [WebPluginDatabase sharedDatabase];
843     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
844 }
845
846 + (NSArray *)_supportedFileExtensions
847 {
848     NSMutableSet *extensions = [[NSMutableSet alloc] init];
849     NSArray *MIMETypes = [self _supportedMIMETypes];
850     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
851     NSString *MIMEType;
852     while ((MIMEType = [enumerator nextObject]) != nil) {
853         NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
854         if (extensionsForType) {
855             [extensions addObjectsFromArray:extensionsForType];
856         }
857     }
858     NSArray *uniqueExtensions = [extensions allObjects];
859     [extensions release];
860     return uniqueExtensions;
861 }
862
863 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
864 {
865     MIMEType = [MIMEType lowercaseString];
866     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
867     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
868
869     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
870         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
871
872         if (allowPlugins) {
873             // Load the plug-in DB allowing plug-ins to install types.
874             [WebPluginDatabase sharedDatabase];
875         }
876
877         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
878         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
879         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
880     }
881     
882     if (viewClass && repClass) {
883         // Special-case WebHTMLView for text types that shouldn't be shown.
884         if (viewClass == [WebHTMLView class] &&
885             repClass == [WebHTMLRepresentation class] &&
886             [[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType]) {
887             return NO;
888         }
889         if (vClass)
890             *vClass = viewClass;
891         if (rClass)
892             *rClass = repClass;
893         return YES;
894     }
895     
896     return NO;
897 }
898
899 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
900 {
901     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
902         return YES;
903
904     if (_private->pluginDatabase) {
905         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
906         if (pluginPackage) {
907             if (vClass)
908                 *vClass = [WebHTMLView class];
909             if (rClass)
910                 *rClass = [WebHTMLRepresentation class];
911             return YES;
912         }
913     }
914     
915     return NO;
916 }
917
918 + (void)_setAlwaysUseATSU:(BOOL)f
919 {
920     [self _setAlwaysUsesComplexTextCodePath:f];
921 }
922
923 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
924 {
925     Font::setCodePath(f ? Font::Complex : Font::Auto);
926 }
927
928 + (BOOL)canCloseAllWebViews
929 {
930     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
931 }
932
933 + (void)closeAllWebViews
934 {
935     DOMWindow::dispatchAllPendingUnloadEvents();
936
937     // This will close the WebViews in a random order. Change this if close order is important.
938     NSEnumerator *enumerator = [(NSMutableSet *)allWebViewsSet objectEnumerator];
939     while (WebView *webView = [enumerator nextObject])
940         [webView close];
941 }
942
943 + (BOOL)canShowFile:(NSString *)path
944 {
945     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
946 }
947
948 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
949 {
950     return WKGetPreferredExtensionForMIMEType(type);
951 }
952
953 - (BOOL)_isClosed
954 {
955     return !_private || _private->closed;
956 }
957
958 - (void)_closePluginDatabases
959 {
960     pluginDatabaseClientCount--;
961
962     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
963
964     // Unload the WebView local plug-in database. 
965     if (_private->pluginDatabase) {
966         [_private->pluginDatabase destroyAllPluginInstanceViews];
967         [_private->pluginDatabase close];
968         [_private->pluginDatabase release];
969         _private->pluginDatabase = nil;
970     }
971     
972     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
973     if (!pluginDatabaseClientCount && applicationIsTerminating)
974         [WebPluginDatabase closeSharedDatabase];
975 }
976
977 - (void)_closeWithFastTeardown 
978 {
979 #ifndef NDEBUG
980     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
981 #endif
982
983     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
984     [[NSNotificationCenter defaultCenter] removeObserver:self];
985
986     [self _closePluginDatabases];
987 }
988
989 static bool fastDocumentTeardownEnabled()
990 {
991 #ifdef NDEBUG
992     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
993 #else
994     static bool initialized = false;
995     static bool enabled = false;
996     if (!initialized) {
997         // This allows debug builds to default to not have fast teardown, so leak checking still works.
998         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
999         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1000         if (setting)
1001             enabled = ![setting boolValue];
1002         initialized = true;
1003     }
1004 #endif
1005     return enabled;
1006 }
1007
1008 // _close is here only for backward compatibility; clients and subclasses should use
1009 // public method -close instead.
1010 - (void)_close
1011 {
1012     if (!_private || _private->closed)
1013         return;
1014
1015     _private->closed = YES;
1016
1017     [self _closingEventHandling];
1018
1019 #ifndef NDEBUG
1020     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1021 #endif
1022
1023     // To quit the apps fast we skip document teardown, except plugins
1024     // need to be destroyed and unloaded.
1025     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1026         [self _closeWithFastTeardown];
1027         return;
1028     }
1029
1030 #if ENABLE(VIDEO)
1031     [self _exitFullscreen];
1032 #endif
1033
1034     if (Frame* mainFrame = [self _mainCoreFrame])
1035         mainFrame->loader()->detachFromParent();
1036
1037     [self _removeFromAllWebViewsSet];
1038     [self setHostWindow:nil];
1039
1040     [self setDownloadDelegate:nil];
1041     [self setEditingDelegate:nil];
1042     [self setFrameLoadDelegate:nil];
1043     [self setPolicyDelegate:nil];
1044     [self setResourceLoadDelegate:nil];
1045     [self setScriptDebugDelegate:nil];
1046     [self setUIDelegate:nil];
1047
1048     [_private->inspector webViewClosed];
1049
1050     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1051     [self removeDragCaret];
1052
1053     // Deleteing the WebCore::Page will clear the page cache so we call destroy on 
1054     // all the plug-ins in the page cache to break any retain cycles.
1055     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1056     delete _private->page;
1057     _private->page = 0;
1058
1059     if (_private->hasSpellCheckerDocumentTag) {
1060         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1061         _private->hasSpellCheckerDocumentTag = NO;
1062     }
1063
1064 #if USE(ACCELERATED_COMPOSITING)
1065     [self _clearLayerSyncLoopObserver];
1066 #endif
1067     
1068     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1069     [[NSNotificationCenter defaultCenter] removeObserver:self];
1070
1071     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1072
1073     WebPreferences *preferences = _private->preferences;
1074     _private->preferences = nil;
1075     [preferences didRemoveFromWebView];
1076     [preferences release];
1077
1078     [self _closePluginDatabases];
1079
1080 #ifndef NDEBUG
1081     // Need this to make leak messages accurate.
1082     if (applicationIsTerminating) {
1083         gcController().garbageCollectNow();
1084         [WebCache setDisabled:YES];
1085     }
1086 #endif
1087 }
1088
1089 // Indicates if the WebView is in the midst of a user gesture.
1090 - (BOOL)_isProcessingUserGesture
1091 {
1092     WebFrame *frame = [self mainFrame];
1093     return core(frame)->loader()->isProcessingUserGesture();
1094 }
1095
1096 + (NSString *)_MIMETypeForFile:(NSString *)path
1097 {
1098     NSString *extension = [path pathExtension];
1099     NSString *MIMEType = nil;
1100
1101     // Get the MIME type from the extension.
1102     if ([extension length] != 0) {
1103         MIMEType = WKGetMIMETypeForExtension(extension);
1104     }
1105
1106     // If we can't get a known MIME type from the extension, sniff.
1107     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1108         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1109         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1110         [handle closeFile];
1111         if ([data length] != 0) {
1112             MIMEType = [data _webkit_guessedMIMEType];
1113         }
1114         if ([MIMEType length] == 0) {
1115             MIMEType = @"application/octet-stream";
1116         }
1117     }
1118
1119     return MIMEType;
1120 }
1121
1122 - (WebDownload *)_downloadURL:(NSURL *)URL
1123 {
1124     ASSERT(URL);
1125     
1126     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1127     WebDownload *download = [WebDownload _downloadWithRequest:request
1128                                                      delegate:_private->downloadDelegate
1129                                                     directory:nil];
1130     [request release];
1131     
1132     return download;
1133 }
1134
1135 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1136 {
1137     NSDictionary *features = [[NSDictionary alloc] init];
1138     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1139                                             createWebViewWithRequest:nil
1140                                                       windowFeatures:features];
1141     [features release];
1142     if (!newWindowWebView)
1143         return nil;
1144
1145     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1146     return newWindowWebView;
1147 }
1148
1149 - (WebInspector *)inspector
1150 {
1151     if (!_private->inspector)
1152         _private->inspector = [[WebInspector alloc] initWithWebView:self];
1153     return _private->inspector;
1154 }
1155
1156 - (WebCore::Page*)page
1157 {
1158     return _private->page;
1159 }
1160
1161 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1162 {
1163     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1164
1165     NSArray *menuItems = CallUIDelegate(self, @selector(webView:contextMenuItemsForElement:defaultMenuItems:), element, defaultMenuItems);
1166     if (!menuItems)
1167         return nil;
1168
1169     unsigned count = [menuItems count];
1170     if (!count)
1171         return nil;
1172
1173     NSMenu *menu = [[NSMenu alloc] init];
1174     for (unsigned i = 0; i < count; i++)
1175         [menu addItem:[menuItems objectAtIndex:i]];
1176
1177     return [menu autorelease];
1178 }
1179
1180 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1181 {
1182     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1183     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1184     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1185     if (!dictionary)
1186         return;
1187     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1188 }
1189
1190 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1191 {
1192     if (!_private->page)
1193         return;
1194     
1195     if (!otherView->_private->page)
1196         return;
1197     
1198     // It turns out the right combination of behavior is done with the back/forward load
1199     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
1200     // in the back forward list, and go to the current one.
1201
1202     BackForwardList* backForwardList = _private->page->backForwardList();
1203     ASSERT(!backForwardList->currentItem()); // destination list should be empty
1204
1205     BackForwardList* otherBackForwardList = otherView->_private->page->backForwardList();
1206     if (!otherBackForwardList->currentItem())
1207         return; // empty back forward list, bail
1208     
1209     HistoryItem* newItemToGoTo = 0;
1210
1211     int lastItemIndex = otherBackForwardList->forwardListCount();
1212     for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
1213         if (i == 0) {
1214             // If this item is showing , save away its current scroll and form state,
1215             // since that might have changed since loading and it is normally not saved
1216             // until we leave that page.
1217             otherView->_private->page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
1218         }
1219         RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
1220         if (i == 0) 
1221             newItemToGoTo = newItem.get();
1222         backForwardList->addItem(newItem.release());
1223     }
1224     
1225     ASSERT(newItemToGoTo);
1226     _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
1227 }
1228
1229 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
1230 {
1231     _private->formDelegate = delegate;
1232 }
1233
1234 - (id<WebFormDelegate>)_formDelegate
1235 {
1236     return _private->formDelegate;
1237 }
1238
1239 - (BOOL)_needsAdobeFrameReloadingQuirk
1240 {
1241     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
1242         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
1243         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
1244         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
1245         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
1246         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
1247         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
1248         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
1249         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
1250         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
1251
1252     return needsQuirk;
1253 }
1254
1255 - (BOOL)_needsLinkElementTextCSSQuirk
1256 {
1257     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
1258         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
1259     return needsQuirk;
1260 }
1261
1262 - (BOOL)_needsKeyboardEventDisambiguationQuirks
1263 {
1264     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
1265     return needsQuirks;
1266 }
1267
1268 - (BOOL)_needsFrameLoadDelegateRetainQuirk
1269 {
1270     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
1271     return needsQuirk;
1272 }
1273
1274 - (void)_preferencesChangedNotification:(NSNotification *)notification
1275 {
1276     WebPreferences *preferences = (WebPreferences *)[notification object];
1277     ASSERT(preferences == [self preferences]);
1278     
1279     if (!_private->userAgentOverridden)
1280         _private->userAgent = String();
1281
1282     // Cache this value so we don't have to read NSUserDefaults on each page load
1283     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
1284
1285     // Update corresponding WebCore Settings object.
1286     if (!_private->page)
1287         return;
1288     
1289     Settings* settings = _private->page->settings();
1290     
1291     settings->setCursiveFontFamily([preferences cursiveFontFamily]);
1292     settings->setDefaultFixedFontSize([preferences defaultFixedFontSize]);
1293     settings->setDefaultFontSize([preferences defaultFontSize]);
1294     settings->setDefaultTextEncodingName([preferences defaultTextEncodingName]);
1295     settings->setUsesEncodingDetector([preferences usesEncodingDetector]);
1296     settings->setFantasyFontFamily([preferences fantasyFontFamily]);
1297     settings->setFixedFontFamily([preferences fixedFontFamily]);
1298     settings->setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
1299     settings->setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
1300     settings->setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
1301     settings->setJavaEnabled([preferences isJavaEnabled]);
1302     settings->setJavaScriptEnabled([preferences isJavaScriptEnabled]);
1303     settings->setWebSecurityEnabled([preferences isWebSecurityEnabled]);
1304     settings->setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
1305     settings->setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
1306     settings->setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
1307     settings->setMinimumFontSize([preferences minimumFontSize]);
1308     settings->setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
1309     settings->setPluginsEnabled([preferences arePlugInsEnabled]);
1310 #if ENABLE(DATABASE)
1311     Database::setIsAvailable([preferences databasesEnabled]);
1312 #endif
1313     settings->setLocalStorageEnabled([preferences localStorageEnabled]);
1314     settings->setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
1315     settings->setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
1316     settings->setSansSerifFontFamily([preferences sansSerifFontFamily]);
1317     settings->setSerifFontFamily([preferences serifFontFamily]);
1318     settings->setStandardFontFamily([preferences standardFontFamily]);
1319     settings->setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
1320     settings->setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
1321     settings->setTextAreasAreResizable([preferences textAreasAreResizable]);
1322     settings->setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
1323     settings->setEditableLinkBehavior(core([preferences editableLinkBehavior]));
1324     settings->setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
1325     settings->setDOMPasteAllowed([preferences isDOMPasteAllowed]);
1326     settings->setUsesPageCache([self usesPageCache]);
1327     settings->setShowsURLsInToolTips([preferences showsURLsInToolTips]);
1328     settings->setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
1329     settings->setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
1330     settings->setApplicationChromeMode([preferences applicationChromeModeEnabled]);
1331     if ([preferences userStyleSheetEnabled]) {
1332         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
1333         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
1334             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
1335         settings->setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
1336     } else
1337         settings->setUserStyleSheetLocation([NSURL URLWithString:@""]);
1338     settings->setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
1339     settings->setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
1340     settings->setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
1341     settings->setNeedsLeopardMailQuirks(runningLeopardMail());
1342     settings->setNeedsTigerMailQuirks(runningTigerMail());
1343     settings->setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
1344     settings->setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
1345     settings->setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
1346     settings->setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
1347     settings->setZoomMode([preferences zoomsTextOnly] ? ZoomTextOnly : ZoomPage);
1348     settings->setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
1349     settings->setEnforceCSSMIMETypeInStrictMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
1350     
1351     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
1352     // Until we fix that, I will comment out the test (CFM)
1353     settings->setAcceleratedCompositingEnabled((coreVideoHas7228836Fix() || [preferences webGLEnabled]) && [preferences acceleratedCompositingEnabled]);
1354     settings->setShowDebugBorders([preferences showDebugBorders]);
1355     settings->setShowRepaintCounter([preferences showRepaintCounter]);
1356     settings->setPluginAllowedRunTime([preferences pluginAllowedRunTime]);
1357     settings->setWebGLEnabled([preferences webGLEnabled]);
1358     settings->setLoadDeferringEnabled(shouldEnableLoadDeferring());
1359     settings->setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
1360 }
1361
1362 static inline IMP getMethod(id o, SEL s)
1363 {
1364     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
1365 }
1366
1367 - (void)_cacheResourceLoadDelegateImplementations
1368 {
1369     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
1370     id delegate = _private->resourceProgressDelegate;
1371
1372     if (!delegate) {
1373         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
1374         return;
1375     }
1376
1377     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1378     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
1379     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
1380     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
1381     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
1382 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1383     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
1384 #endif
1385     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
1386     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
1387     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
1388     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
1389     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
1390     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
1391     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
1392 }
1393
1394 - (void)_cacheFrameLoadDelegateImplementations
1395 {
1396     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
1397     id delegate = _private->frameLoadDelegate;
1398
1399     if (!delegate) {
1400         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
1401         return;
1402     }
1403
1404     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
1405     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
1406     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
1407     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
1408     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
1409     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
1410     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
1411     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
1412     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
1413     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
1414     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
1415     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
1416     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
1417     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
1418     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
1419     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
1420     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
1421     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
1422     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
1423     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
1424     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
1425     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
1426     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
1427     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
1428     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
1429 }
1430
1431 - (void)_cacheScriptDebugDelegateImplementations
1432 {
1433     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
1434     id delegate = _private->scriptDebugDelegate;
1435
1436     if (!delegate) {
1437         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
1438         return;
1439     }
1440
1441     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
1442     if (cache->didParseSourceFunc)
1443         cache->didParseSourceExpectsBaseLineNumber = YES;
1444     else
1445         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
1446
1447     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
1448     cache->didEnterCallFrameFunc = getMethod(delegate, @selector(webView:didEnterCallFrame:sourceId:line:forWebFrame:));
1449     cache->willExecuteStatementFunc = getMethod(delegate, @selector(webView:willExecuteStatement:sourceId:line:forWebFrame:));
1450     cache->willLeaveCallFrameFunc = getMethod(delegate, @selector(webView:willLeaveCallFrame:sourceId:line:forWebFrame:));
1451     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
1452 }
1453
1454 - (void)_cacheHistoryDelegateImplementations
1455 {
1456     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
1457     id delegate = _private->historyDelegate;
1458
1459     if (!delegate) {
1460         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
1461         return;
1462     }
1463
1464     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
1465     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
1466     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
1467     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
1468     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
1469 }
1470
1471 - (id)_policyDelegateForwarder
1472 {
1473     if (!_private->policyDelegateForwarder)
1474         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate] catchExceptions:_private->catchesDelegateExceptions];
1475     return _private->policyDelegateForwarder;
1476 }
1477
1478 - (id)_UIDelegateForwarder
1479 {
1480     if (!_private->UIDelegateForwarder)
1481         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate] catchExceptions:_private->catchesDelegateExceptions];
1482     return _private->UIDelegateForwarder;
1483 }
1484
1485 - (id)_editingDelegateForwarder
1486 {
1487     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
1488     // Not sure if that is a bug or not.
1489     if (!_private)
1490         return nil;
1491
1492     if (!_private->editingDelegateForwarder)
1493         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate] catchExceptions:_private->catchesDelegateExceptions];
1494     return _private->editingDelegateForwarder;
1495 }
1496
1497 - (void)_closeWindow
1498 {
1499     [[self _UIDelegateForwarder] webViewClose:self];
1500 }
1501
1502 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
1503 {
1504     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1505     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
1506     
1507     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1508     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1509     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1510     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
1511 }
1512
1513 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
1514 {
1515     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
1516     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
1517
1518     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
1519     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
1520     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
1521     if ([viewClass class] == [WebHTMLView class])
1522         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
1523     
1524     // This is used to make _representationExistsForURLScheme faster.
1525     // Without this set, we'd have to create the MIME type each time.
1526     if (schemesWithRepresentationsSet == nil) {
1527         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
1528     }
1529     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
1530 }
1531
1532 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
1533 {
1534     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
1535 }
1536
1537 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
1538 {
1539     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
1540 }
1541
1542 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
1543 {
1544     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
1545     if (!request)
1546         return NO;
1547
1548     if ([NSURLConnection canHandleRequest:request])
1549         return YES;
1550
1551     NSString *scheme = [[request URL] scheme];
1552
1553     // Representations for URL schemes work at the top level.
1554     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
1555         return YES;
1556         
1557     return [scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"];
1558 }
1559
1560 + (BOOL)_canHandleRequest:(NSURLRequest *)request
1561 {
1562     return [self _canHandleRequest:request forMainFrame:YES];
1563 }
1564
1565 + (NSString *)_decodeData:(NSData *)data
1566 {
1567     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
1568     RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
1569     String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
1570     result += decoder->flush();
1571     return result;
1572 }
1573
1574 - (void)_pushPerformingProgrammaticFocus
1575 {
1576     _private->programmaticFocusCount++;
1577 }
1578
1579 - (void)_popPerformingProgrammaticFocus
1580 {
1581     _private->programmaticFocusCount--;
1582 }
1583
1584 - (BOOL)_isPerformingProgrammaticFocus
1585 {
1586     return _private->programmaticFocusCount != 0;
1587 }
1588
1589 - (void)_didChangeValueForKey: (NSString *)key
1590 {
1591     LOG (Bindings, "calling didChangeValueForKey: %@", key);
1592     [self didChangeValueForKey: key];
1593 }
1594
1595 - (void)_willChangeValueForKey: (NSString *)key
1596 {
1597     LOG (Bindings, "calling willChangeValueForKey: %@", key);
1598     [self willChangeValueForKey: key];
1599 }
1600
1601 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
1602     static NSSet *manualNotifyKeys = nil;
1603     if (!manualNotifyKeys)
1604         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1605             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
1606             nil];
1607     if ([manualNotifyKeys containsObject:key])
1608         return NO;
1609     return YES;
1610 }
1611
1612 - (NSArray *)_declaredKeys {
1613     static NSArray *declaredKeys = nil;
1614     if (!declaredKeys)
1615         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
1616             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
1617     return declaredKeys;
1618 }
1619
1620 - (void)setObservationInfo:(void *)info
1621 {
1622     _private->observationInfo = info;
1623 }
1624
1625 - (void *)observationInfo
1626 {
1627     return _private->observationInfo;
1628 }
1629
1630 - (void)_willChangeBackForwardKeys
1631 {
1632     [self _willChangeValueForKey: _WebCanGoBackKey];
1633     [self _willChangeValueForKey: _WebCanGoForwardKey];
1634 }
1635
1636 - (void)_didChangeBackForwardKeys
1637 {
1638     [self _didChangeValueForKey: _WebCanGoBackKey];
1639     [self _didChangeValueForKey: _WebCanGoForwardKey];
1640 }
1641
1642 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
1643 {
1644     [self _willChangeBackForwardKeys];
1645     if (frame == [self mainFrame]){
1646         // Force an observer update by sending a will/did.
1647         [self _willChangeValueForKey: _WebIsLoadingKey];
1648         [self _didChangeValueForKey: _WebIsLoadingKey];
1649
1650         [self _willChangeValueForKey: _WebMainFrameURLKey];
1651     }
1652
1653     [NSApp setWindowsNeedUpdate:YES];
1654 }
1655
1656 - (void)_didCommitLoadForFrame:(WebFrame *)frame
1657 {
1658     if (frame == [self mainFrame])
1659         [self _didChangeValueForKey: _WebMainFrameURLKey];
1660     [NSApp setWindowsNeedUpdate:YES];
1661 }
1662
1663 - (void)_didFinishLoadForFrame:(WebFrame *)frame
1664 {
1665     [self _didChangeBackForwardKeys];
1666     if (frame == [self mainFrame]){
1667         // Force an observer update by sending a will/did.
1668         [self _willChangeValueForKey: _WebIsLoadingKey];
1669         [self _didChangeValueForKey: _WebIsLoadingKey];
1670     }
1671     [NSApp setWindowsNeedUpdate:YES];
1672 }
1673
1674 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1675 {
1676     [self _didChangeBackForwardKeys];
1677     if (frame == [self mainFrame]){
1678         // Force an observer update by sending a will/did.
1679         [self _willChangeValueForKey: _WebIsLoadingKey];
1680         [self _didChangeValueForKey: _WebIsLoadingKey];
1681     }
1682     [NSApp setWindowsNeedUpdate:YES];
1683 }
1684
1685 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1686 {
1687     [self _didChangeBackForwardKeys];
1688     if (frame == [self mainFrame]){
1689         // Force an observer update by sending a will/did.
1690         [self _willChangeValueForKey: _WebIsLoadingKey];
1691         [self _didChangeValueForKey: _WebIsLoadingKey];
1692         
1693         [self _didChangeValueForKey: _WebMainFrameURLKey];
1694     }
1695     [NSApp setWindowsNeedUpdate:YES];
1696 }
1697
1698 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
1699 {
1700     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
1701     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
1702     NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
1703     [request release];
1704     return cachedResponse;
1705 }
1706
1707 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1708 {
1709     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1710     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1711     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
1712                         element:domElement
1713                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
1714                           title:[element objectForKey:WebElementImageAltStringKey] 
1715                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
1716                           types:types
1717                          source:nil];
1718 }
1719
1720 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1721 {
1722     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
1723                      andTitle:[element objectForKey:WebElementLinkLabelKey]
1724                         types:types];
1725 }
1726
1727 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
1728 {
1729     if (!_private->page)
1730         return;
1731     _private->page->dragController()->setDidInitiateDrag(initiatedDrag);
1732 }
1733
1734 #if ENABLE(DASHBOARD_SUPPORT)
1735
1736 #define DASHBOARD_CONTROL_LABEL @"control"
1737
1738 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
1739 {
1740     NSRect adjustedBounds = bounds;
1741     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
1742     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
1743     adjustedBounds.size = bounds.size;
1744
1745     NSRect adjustedClip;
1746     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
1747     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
1748     adjustedClip.size = clip.size;
1749
1750     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
1751         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
1752     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
1753     if (!scrollerRegions) {
1754         scrollerRegions = [[NSMutableArray alloc] init];
1755         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
1756         [scrollerRegions release];
1757     }
1758     [scrollerRegions addObject:region];
1759     [region release];
1760 }
1761
1762 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
1763 {    
1764     NSView *documentView = [[kit(frameView->frame()) frameView] documentView];
1765
1766     const HashSet<RefPtr<Widget> >* children = frameView->children();
1767     HashSet<RefPtr<Widget> >::const_iterator end = children->end();
1768     for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != end; ++it) {
1769         Widget* widget = (*it).get();
1770         if (widget->isFrameView()) {
1771             [self _addScrollerDashboardRegionsForFrameView:static_cast<FrameView*>(widget) dashboardRegions:regions];
1772             continue;
1773         }
1774
1775         if (!widget->isScrollbar())
1776             continue;
1777
1778         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
1779         // it's not common to need this to be correct in Dashboard widgets.
1780         NSRect bounds = widget->frameRect();
1781         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
1782     }
1783 }
1784
1785 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
1786 {
1787     // Add scroller regions for NSScroller and WebCore scrollbars
1788     NSUInteger count = [views count];
1789     for (NSUInteger i = 0; i < count; i++) {
1790         NSView *view = [views objectAtIndex:i];
1791         
1792         if ([view isKindOfClass:[WebHTMLView class]]) {
1793             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
1794                 if (FrameView* coreView = coreFrame->view())
1795                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
1796             }
1797         } else if ([view isKindOfClass:[NSScroller class]]) {
1798             // AppKit places absent scrollers at -100,-100
1799             if ([view frame].origin.y < 0)
1800                 continue;
1801             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
1802         }
1803         [self _addScrollerDashboardRegions:regions from:[view subviews]];
1804     }
1805 }
1806
1807 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
1808 {
1809     [self _addScrollerDashboardRegions:regions from:[self subviews]];
1810 }
1811
1812 - (NSDictionary *)_dashboardRegions
1813 {
1814     // Only return regions from main frame.
1815     Frame* mainFrame = [self _mainCoreFrame];
1816     if (!mainFrame)
1817         return nil;
1818     NSMutableDictionary *regions = mainFrame->dashboardRegionsDictionary();
1819     [self _addScrollerDashboardRegions:regions];
1820     return regions;
1821 }
1822
1823 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
1824 {
1825     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
1826     // specific support for the backward compatibility mode flag.
1827     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
1828         _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(true);
1829     
1830     switch (behavior) {
1831         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1832             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
1833             break;
1834         }
1835         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1836             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
1837             break;
1838         }
1839         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1840             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
1841             break;
1842         }
1843         case WebDashboardBehaviorAllowWheelScrolling: {
1844             _private->dashboardBehaviorAllowWheelScrolling = flag;
1845             break;
1846         }
1847         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1848             if (_private->page)
1849                 _private->page->settings()->setUsesDashboardBackwardCompatibilityMode(flag);
1850             break;
1851         }
1852     }
1853 }
1854
1855 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
1856 {
1857     switch (behavior) {
1858         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
1859             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
1860         }
1861         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
1862             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
1863         }
1864         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
1865             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
1866         }
1867         case WebDashboardBehaviorAllowWheelScrolling: {
1868             return _private->dashboardBehaviorAllowWheelScrolling;
1869         }
1870         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
1871             return _private->page && _private->page->settings()->usesDashboardBackwardCompatibilityMode();
1872         }
1873     }
1874     return NO;
1875 }
1876
1877 #endif /* ENABLE(DASHBOARD_SUPPORT) */
1878
1879 + (void)_setShouldUseFontSmoothing:(BOOL)f
1880 {
1881     Font::setShouldUseSmoothing(f);
1882 }
1883
1884 + (BOOL)_shouldUseFontSmoothing
1885 {
1886     return Font::shouldUseSmoothing();
1887 }
1888
1889 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
1890 {
1891     setUsesTestModeFocusRingColor(f);
1892 }
1893
1894 + (BOOL)_usesTestModeFocusRingColor
1895 {
1896     return usesTestModeFocusRingColor();
1897 }
1898
1899 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
1900 {
1901     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1902     if (flag) {
1903         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
1904     } else {
1905         [scrollview setVerticalScrollingModeLocked:NO];
1906         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
1907     }
1908 }
1909
1910 - (BOOL)alwaysShowVerticalScroller
1911 {
1912     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1913     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
1914 }
1915
1916 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
1917 {
1918     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1919     if (flag) {
1920         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
1921     } else {
1922         [scrollview setHorizontalScrollingModeLocked:NO];
1923         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
1924     }
1925 }
1926
1927 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
1928 {
1929     if (Frame* mainFrame = [self _mainCoreFrame])
1930         mainFrame->view()->setProhibitsScrolling(prohibits);
1931 }
1932
1933 - (BOOL)alwaysShowHorizontalScroller
1934 {
1935     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
1936     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
1937 }
1938
1939 - (void)_setInViewSourceMode:(BOOL)flag
1940 {
1941     if (Frame* mainFrame = [self _mainCoreFrame])
1942         mainFrame->setInViewSourceMode(flag);
1943 }
1944
1945 - (BOOL)_inViewSourceMode
1946 {
1947     Frame* mainFrame = [self _mainCoreFrame];
1948     return mainFrame && mainFrame->inViewSourceMode();
1949 }
1950
1951 - (void)_setUseFastImageScalingMode:(BOOL)flag
1952 {
1953     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
1954         _private->page->setInLowQualityImageInterpolationMode(flag);
1955         [self setNeedsDisplay:YES];
1956     }
1957 }
1958
1959 - (BOOL)_inFastImageScalingMode
1960 {
1961     if (_private->page)
1962         return _private->page->inLowQualityImageInterpolationMode();
1963     return NO;
1964 }
1965
1966 - (BOOL)_cookieEnabled
1967 {
1968     if (_private->page)
1969         return _private->page->cookieEnabled();
1970     return YES;
1971 }
1972
1973 - (void)_setCookieEnabled:(BOOL)enable
1974 {
1975     if (_private->page)
1976         _private->page->setCookieEnabled(enable);
1977 }
1978
1979 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
1980 {
1981     if (!_private->pluginDatabase)
1982         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
1983         
1984     [_private->pluginDatabase setPlugInPaths:newPaths];
1985     [_private->pluginDatabase refresh];
1986 }
1987
1988 - (void)_attachScriptDebuggerToAllFrames
1989 {
1990     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
1991         [kit(frame) _attachScriptDebugger];
1992 }
1993
1994 - (void)_detachScriptDebuggerFromAllFrames
1995 {
1996     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree()->traverseNext())
1997         [kit(frame) _detachScriptDebugger];
1998 }
1999
2000 - (void)setBackgroundColor:(NSColor *)backgroundColor
2001 {
2002     if ([_private->backgroundColor isEqual:backgroundColor])
2003         return;
2004
2005     id old = _private->backgroundColor;
2006     _private->backgroundColor = [backgroundColor retain];
2007     [old release];
2008
2009     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
2010 }
2011
2012 - (NSColor *)backgroundColor
2013 {
2014     return _private->backgroundColor;
2015 }
2016
2017 - (BOOL)defersCallbacks
2018 {
2019     if (!_private->page)
2020         return NO;
2021     return _private->page->defersLoading();
2022 }
2023
2024 - (void)setDefersCallbacks:(BOOL)defer
2025 {
2026     if (!_private->page)
2027         return;
2028     return _private->page->setDefersLoading(defer);
2029 }
2030
2031 // For backwards compatibility with the WebBackForwardList API, we honor both
2032 // a per-WebView and a per-preferences setting for whether to use the page cache.
2033
2034 - (BOOL)usesPageCache
2035 {
2036     return _private->usesPageCache && [[self preferences] usesPageCache];
2037 }
2038
2039 - (void)setUsesPageCache:(BOOL)usesPageCache
2040 {
2041     _private->usesPageCache = usesPageCache;
2042
2043     // Post a notification so the WebCore settings update.
2044     [[self preferences] _postPreferencesChangesNotification];
2045 }
2046
2047 - (WebHistoryItem *)_globalHistoryItem
2048 {
2049     if (!_private->page)
2050         return nil;
2051     return kit(_private->page->globalHistoryItem());
2052 }
2053
2054 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
2055 {
2056     IntPoint rectStart(rect.origin.x, rect.origin.y);
2057     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
2058     
2059     Frame* coreFrame = [self _mainCoreFrame];
2060     if (!coreFrame)
2061         return nil;
2062     
2063     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
2064     
2065     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
2066 }
2067
2068 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource 
2069 {
2070     NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window]; 
2071     [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window]; 
2072
2073
2074 - (void)_clearUndoRedoOperations
2075 {
2076     if (!_private->page)
2077         return;
2078     _private->page->clearUndoRedoOperations();
2079 }
2080
2081 - (void)_setCatchesDelegateExceptions:(BOOL)f
2082 {
2083     _private->catchesDelegateExceptions = f;
2084 }
2085
2086 - (BOOL)_catchesDelegateExceptions
2087 {
2088     return _private->catchesDelegateExceptions;
2089 }
2090
2091 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
2092 {
2093     Frame* coreFrame = [self _mainCoreFrame];
2094     if (!coreFrame)
2095         return;
2096     coreFrame->editor()->command(name).execute(value);
2097 }
2098
2099 - (void)_setCustomHTMLTokenizerTimeDelay:(double)timeDelay
2100 {
2101     if (!_private->page)
2102         return;
2103     return _private->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
2104 }
2105
2106 - (void)_setCustomHTMLTokenizerChunkSize:(int)chunkSize
2107 {
2108     if (!_private->page)
2109         return;
2110     return _private->page->setCustomHTMLTokenizerChunkSize(chunkSize);
2111 }
2112
2113 - (void)_clearMainFrameName
2114 {
2115     _private->page->mainFrame()->tree()->clearName();
2116 }
2117
2118 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
2119 {
2120     _private->selectTrailingWhitespaceEnabled = flag;
2121     if (flag)
2122         [self setSmartInsertDeleteEnabled:false];
2123 }
2124
2125 - (BOOL)isSelectTrailingWhitespaceEnabled
2126 {
2127     return _private->selectTrailingWhitespaceEnabled;
2128 }
2129
2130 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
2131 {
2132     _private->page->setMemoryCacheClientCallsEnabled(enabled);
2133 }
2134
2135 - (BOOL)areMemoryCacheDelegateCallsEnabled
2136 {
2137     return _private->page->areMemoryCacheClientCallsEnabled();
2138 }
2139
2140 - (void)_setJavaScriptURLsAreAllowed:(BOOL)areAllowed
2141 {
2142     _private->page->setJavaScriptURLsAreAllowed(areAllowed);
2143 }
2144
2145 + (NSCursor *)_pointingHandCursor
2146 {
2147     return handCursor().impl();
2148 }
2149
2150 - (BOOL)_postsAcceleratedCompositingNotifications
2151 {
2152 #if USE(ACCELERATED_COMPOSITING)
2153     return _private->postsAcceleratedCompositingNotifications;
2154 #else
2155     return NO;
2156 #endif
2157
2158 }
2159 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
2160 {
2161 #if USE(ACCELERATED_COMPOSITING)
2162     _private->postsAcceleratedCompositingNotifications = flag;
2163 #endif
2164 }
2165
2166 - (BOOL)_isUsingAcceleratedCompositing
2167 {
2168 #if USE(ACCELERATED_COMPOSITING)
2169     if (_private->usesDocumentViews) {
2170         Frame* coreFrame = [self _mainCoreFrame];
2171         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2172             NSView *documentView = [[kit(frame) frameView] documentView];
2173             if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
2174                 return YES;
2175         }
2176     }
2177 #endif
2178     return NO;
2179 }
2180
2181 - (BOOL)_isSoftwareRenderable
2182 {
2183 #if USE(ACCELERATED_COMPOSITING)
2184     if (_private->usesDocumentViews) {
2185         Frame* coreFrame = [self _mainCoreFrame];
2186         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame)) {
2187             if (FrameView* view = frame->view()) {
2188                 if (!view->isSoftwareRenderable())
2189                     return NO;
2190             }
2191         }
2192     }
2193 #endif
2194     return YES;
2195 }
2196
2197 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
2198 {
2199     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
2200 }
2201
2202 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
2203 {
2204     return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
2205 }
2206
2207 static WebBaseNetscapePluginView *_pluginViewForNode(DOMNode *node)
2208 {
2209     if (!node)
2210         return nil;
2211     
2212     Node* coreNode = core(node);
2213     if (!coreNode)
2214         return nil;
2215     
2216     RenderObject* renderer = coreNode->renderer();
2217     if (!renderer || !renderer->isWidget())
2218         return nil;
2219     
2220     Widget* widget = toRenderWidget(renderer)->widget();
2221     if (!widget || !widget->platformWidget())
2222         return nil;
2223     
2224     NSView *view = widget->platformWidget();
2225     if (![view isKindOfClass:[WebBaseNetscapePluginView class]])
2226         return nil;
2227     
2228     return (WebBaseNetscapePluginView *)view;
2229 }
2230
2231 + (BOOL)_isNodeHaltedPlugin:(DOMNode *)node
2232 {
2233     return [_pluginViewForNode(node) isHalted];
2234 }
2235
2236 + (BOOL)_hasPluginForNodeBeenHalted:(DOMNode *)node
2237 {
2238     return [_pluginViewForNode(node) hasBeenHalted];
2239 }
2240 + (void)_restartHaltedPluginForNode:(DOMNode *)node
2241 {
2242     if (!node)
2243         return;
2244     
2245     [_pluginViewForNode(node) resumeFromHalt];
2246 }
2247
2248 - (NSPasteboard *)_insertionPasteboard
2249 {
2250     return _private ? _private->insertionPasteboard : nil;
2251 }
2252
2253 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2254 {
2255     SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2256 }
2257
2258 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
2259 {
2260     SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
2261 }
2262
2263 +(void)_resetOriginAccessWhitelists
2264 {
2265     SecurityOrigin::resetOriginAccessWhitelists();
2266 }
2267
2268 - (void)_updateActiveState
2269 {
2270     if (_private && _private->page)
2271         _private->page->focusController()->setActive([[self window] isKeyWindow]);
2272 }
2273
2274 static PassOwnPtr<Vector<String> > toStringVector(NSArray* patterns)
2275 {
2276     // Convert the patterns into Vectors.
2277     NSUInteger count = [patterns count];
2278     if (count == 0)
2279         return 0;
2280     Vector<String>* patternsVector = new Vector<String>;
2281     for (NSUInteger i = 0; i < count; ++i) {
2282         id entry = [patterns objectAtIndex:i];
2283         if ([entry isKindOfClass:[NSString class]])
2284             patternsVector->append(String((NSString*)entry));
2285     }
2286     return patternsVector;
2287 }
2288
2289 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2290                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist injectionTime:(WebUserScriptInjectionTime)injectionTime
2291 {
2292     String group(groupName);
2293     if (group.isEmpty())
2294         return;
2295     
2296     PageGroup* pageGroup = PageGroup::pageGroup(group);
2297     if (!pageGroup)
2298         return;
2299     
2300     pageGroup->addUserScriptToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist), 
2301                                     injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd);
2302 }
2303
2304 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
2305                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
2306 {
2307     String group(groupName);
2308     if (group.isEmpty())
2309         return;
2310     
2311     PageGroup* pageGroup = PageGroup::pageGroup(group);
2312     if (!pageGroup)
2313         return;
2314
2315     pageGroup->addUserStyleSheetToWorld(core(world), source, url, toStringVector(whitelist), toStringVector(blacklist));
2316 }
2317
2318 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2319 {
2320     String group(groupName);
2321     if (group.isEmpty())
2322         return;
2323     
2324     PageGroup* pageGroup = PageGroup::pageGroup(group);
2325     if (!pageGroup)
2326         return;
2327
2328     pageGroup->removeUserScriptFromWorld(core(world), url);
2329 }
2330
2331 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
2332 {
2333     String group(groupName);
2334     if (group.isEmpty())
2335         return;
2336     
2337     PageGroup* pageGroup = PageGroup::pageGroup(group);
2338     if (!pageGroup)
2339         return;
2340
2341     pageGroup->removeUserStyleSheetFromWorld(core(world), url);
2342 }
2343
2344 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2345 {
2346     String group(groupName);
2347     if (group.isEmpty())
2348         return;
2349     
2350     PageGroup* pageGroup = PageGroup::pageGroup(group);
2351     if (!pageGroup)
2352         return;
2353
2354     pageGroup->removeUserScriptsFromWorld(core(world));
2355 }
2356
2357 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
2358 {
2359     String group(groupName);
2360     if (group.isEmpty())
2361         return;
2362     
2363     PageGroup* pageGroup = PageGroup::pageGroup(group);
2364     if (!pageGroup)
2365         return;
2366
2367     pageGroup->removeUserStyleSheetsFromWorld(core(world));
2368 }
2369
2370 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
2371 {
2372     String group(groupName);
2373     if (group.isEmpty())
2374         return;
2375     
2376     PageGroup* pageGroup = PageGroup::pageGroup(group);
2377     if (!pageGroup)
2378         return;
2379     
2380     pageGroup->removeAllUserContent();
2381 }
2382
2383 - (BOOL)cssAnimationsSuspended
2384 {
2385     return _private->cssAnimationsSuspended;
2386 }
2387
2388 - (void)setCSSAnimationsSuspended:(BOOL)suspended
2389 {
2390     if (suspended == _private->cssAnimationsSuspended)
2391         return;
2392         
2393     _private->cssAnimationsSuspended = suspended;
2394     
2395     Frame* frame = core([self mainFrame]);
2396     if (suspended)
2397         frame->animation()->suspendAnimations(frame->document());
2398     else
2399         frame->animation()->resumeAnimations(frame->document());
2400 }
2401
2402 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
2403 {
2404     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
2405 }
2406
2407 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
2408 {
2409     SecurityOrigin::registerURLSchemeAsSecure(scheme);
2410 }
2411
2412 @end
2413
2414 @implementation _WebSafeForwarder
2415
2416 // Used to send messages to delegates that implement informal protocols.
2417
2418 - (id)initWithTarget:(id)t defaultTarget:(id)dt catchExceptions:(BOOL)c
2419 {
2420     self = [super init];
2421     if (!self)
2422         return nil;
2423     target = t; // Non retained.
2424     defaultTarget = dt;
2425     catchExceptions = c;
2426     return self;
2427 }
2428
2429 - (void)forwardInvocation:(NSInvocation *)invocation
2430 {
2431     if ([target respondsToSelector:[invocation selector]]) {
2432         if (catchExceptions) {
2433             @try {
2434                 [invocation invokeWithTarget:target];
2435             } @catch(id exception) {
2436                 ReportDiscardedDelegateException([invocation selector], exception);
2437             }
2438         } else
2439             [invocation invokeWithTarget:target];
2440         return;
2441     }
2442
2443     if ([defaultTarget respondsToSelector:[invocation selector]])
2444         [invocation invokeWithTarget:defaultTarget];
2445
2446     // Do nothing quietly if method not implemented.
2447 }
2448
2449 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
2450 {
2451     return [defaultTarget methodSignatureForSelector:aSelector];
2452 }
2453
2454 @end
2455
2456 @implementation WebView
2457
2458 + (void)initialize
2459 {
2460     static BOOL initialized = NO;
2461     if (initialized)
2462         return;
2463     initialized = YES;
2464
2465     InitWebCoreSystemInterface();
2466     JSC::initializeThreading();
2467     WTF::initializeMainThreadToProcessMainThread();
2468
2469     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_applicationWillTerminate) name:NSApplicationWillTerminateNotification object:NSApp];
2470     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:) name:WebPreferencesChangedNotification object:nil];
2471     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesRemovedNotification:) name:WebPreferencesRemovedNotification object:nil];    
2472
2473     continuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled];
2474 #ifndef BUILDING_ON_TIGER
2475     grammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled];
2476 #endif
2477
2478 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
2479     automaticQuoteSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticQuoteSubstitutionEnabled];
2480     automaticLinkDetectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticLinkDetectionEnabled];
2481     automaticDashSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticDashSubstitutionEnabled];
2482     automaticTextReplacementEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticTextReplacementEnabled];
2483     automaticSpellingCorrectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticSpellingCorrectionEnabled];
2484 #endif
2485 }
2486
2487 + (void)_applicationWillTerminate
2488 {   
2489     applicationIsTerminating = YES;
2490
2491     if (fastDocumentTeardownEnabled())
2492         [self closeAllWebViews];
2493
2494     if (!pluginDatabaseClientCount)
2495         [WebPluginDatabase closeSharedDatabase];
2496
2497     PageGroup::closeLocalStorage();
2498 }
2499
2500 + (BOOL)_canShowMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2501 {
2502     return [self _viewClass:nil andRepresentationClass:nil forMIMEType:MIMEType allowingPlugins:allowPlugins];
2503 }
2504
2505 + (BOOL)canShowMIMEType:(NSString *)MIMEType
2506 {
2507     return [self _canShowMIMEType:MIMEType allowingPlugins:YES];
2508 }
2509
2510 - (BOOL)_canShowMIMEType:(NSString *)MIMEType
2511 {
2512     return [[self class] _canShowMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]];
2513 }
2514
2515 - (WebBasePluginPackage *)_pluginForMIMEType:(NSString *)MIMEType
2516 {
2517     if (![_private->preferences arePlugInsEnabled])
2518         return nil;
2519
2520     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
2521     if (pluginPackage)
2522         return pluginPackage;
2523     
2524     if (_private->pluginDatabase)
2525         return [_private->pluginDatabase pluginForMIMEType:MIMEType];
2526     
2527     return nil;
2528 }
2529
2530 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
2531 {
2532     if (![_private->preferences arePlugInsEnabled])
2533         return nil;
2534
2535     WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForExtension:extension];
2536     if (pluginPackage)
2537         return pluginPackage;
2538     
2539     if (_private->pluginDatabase)
2540         return [_private->pluginDatabase pluginForExtension:extension];
2541     
2542     return nil;
2543 }
2544
2545 - (void)addPluginInstanceView:(NSView *)view
2546 {
2547     if (!_private->pluginDatabase)
2548         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
2549     [_private->pluginDatabase addPluginInstanceView:view];
2550 }
2551
2552 - (void)removePluginInstanceView:(NSView *)view
2553 {
2554     if (_private->pluginDatabase)
2555         [_private->pluginDatabase removePluginInstanceView:view];    
2556 }
2557
2558 - (void)removePluginInstanceViewsFor:(WebFrame*)webFrame 
2559 {
2560     if (_private->pluginDatabase)
2561         [_private->pluginDatabase removePluginInstanceViewsFor:webFrame];    
2562 }
2563
2564 - (BOOL)_isMIMETypeRegisteredAsPlugin:(NSString *)MIMEType
2565 {
2566     if (![_private->preferences arePlugInsEnabled])
2567         return NO;
2568
2569     if ([[WebPluginDatabase sharedDatabase] isMIMETypeRegistered:MIMEType])
2570         return YES;
2571         
2572     if (_private->pluginDatabase && [_private->pluginDatabase isMIMETypeRegistered:MIMEType])
2573         return YES;
2574     
2575     return NO;
2576 }
2577
2578 + (BOOL)canShowMIMETypeAsHTML:(NSString *)MIMEType
2579 {
2580     return [WebFrameView _canShowMIMETypeAsHTML:MIMEType];
2581 }
2582
2583 + (NSArray *)MIMETypesShownAsHTML
2584 {
2585     NSMutableDictionary *viewTypes = [WebFrameView _viewTypesAllowImageTypeOmission:YES];
2586     NSEnumerator *enumerator = [viewTypes keyEnumerator];
2587     id key;
2588     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
2589     
2590     while ((key = [enumerator nextObject])) {
2591         if ([viewTypes objectForKey:key] == [WebHTMLView class])
2592             [array addObject:key];
2593     }
2594     
2595     return array;
2596 }
2597
2598 + (void)setMIMETypesShownAsHTML:(NSArray *)MIMETypes
2599 {
2600     NSDictionary *viewTypes = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] copy];
2601     NSEnumerator *enumerator = [viewTypes keyEnumerator];
2602     id key;
2603     while ((key = [enumerator nextObject])) {
2604         if ([viewTypes objectForKey:key] == [WebHTMLView class])
2605             [WebView _unregisterViewClassAndRepresentationClassForMIMEType:key];
2606     }
2607     
2608     int i, count = [MIMETypes count];
2609     for (i = 0; i < count; i++) {
2610         [WebView registerViewClass:[WebHTMLView class] 
2611                 representationClass:[WebHTMLRepresentation class] 
2612                 forMIMEType:[MIMETypes objectAtIndex:i]];
2613     }
2614     [viewTypes release];
2615 }
2616
2617 + (NSURL *)URLFromPasteboard:(NSPasteboard *)pasteboard
2618 {
2619     return [pasteboard _web_bestURL];
2620 }
2621
2622 + (NSString *)URLTitleFromPasteboard:(NSPasteboard *)pasteboard
2623 {
2624     return [pasteboard stringForType:WebURLNamePboardType];
2625 }
2626
2627 + (void)registerURLSchemeAsLocal:(NSString *)protocol
2628 {
2629     SecurityOrigin::registerURLSchemeAsLocal(protocol);
2630 }
2631
2632 - (id)_initWithArguments:(NSDictionary *) arguments
2633 {
2634     NSCoder *decoder = [arguments objectForKey:@"decoder"];
2635     if (decoder) {
2636         self = [self initWithCoder:decoder];
2637     } else {
2638         ASSERT([arguments objectForKey:@"frame"]);
2639         NSValue *frameValue = [arguments objectForKey:@"frame"];
2640         NSRect frame = (frameValue ? [frameValue rectValue] : NSZeroRect);
2641         NSString *frameName = [arguments objectForKey:@"frameName"];
2642         NSString *groupName = [arguments objectForKey:@"groupName"];
2643         self = [self initWithFrame:frame frameName:frameName groupName:groupName];
2644     }
2645
2646     return self;
2647 }
2648
2649 static bool clientNeedsWebViewInitThreadWorkaround()
2650 {
2651     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_WEBVIEW_INIT_THREAD_WORKAROUND))
2652         return false;
2653
2654     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
2655
2656     // Installer.
2657     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.installer"])
2658         return true;
2659
2660     // Automator.
2661     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Automator"])
2662         return true;
2663
2664     // Automator Runner.
2665     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.AutomatorRunner"])
2666         return true;
2667
2668     // Automator workflows.
2669     if ([bundleIdentifier _webkit_hasCaseInsensitivePrefix:@"com.apple.Automator."])
2670         return true;
2671
2672 #if defined(BUILDING_ON_TIGER) || defined(BUILDING_ON_LEOPARD)
2673     // Mail.
2674     if ([bundleIdentifier _webkit_isCaseInsensitiveEqualToString:@"com.apple.Mail"])
2675         return true;
2676 #endif
2677
2678     return false;
2679 }
2680
2681 static bool needsWebViewInitThreadWorkaround()
2682 {
2683     static bool isOldClient = clientNeedsWebViewInitThreadWorkaround();
2684     return isOldClient && !pthread_main_np();
2685 }
2686
2687 - (id)initWithFrame:(NSRect)f
2688 {
2689     return [self initWithFrame:f frameName:nil groupName:nil];
2690 }
2691
2692 - (id)initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
2693 {
2694     if (needsWebViewInitThreadWorkaround())
2695         return [[self _webkit_invokeOnMainThread] initWithFrame:f frameName:frameName groupName:groupName];
2696
2697     WebCoreThreadViolationCheckRoundTwo();
2698     return [self _initWithFrame:f frameName:frameName groupName:groupName usesDocumentViews:YES];
2699 }
2700
2701 - (id)initWithCoder:(NSCoder *)decoder
2702 {
2703     if (needsWebViewInitThreadWorkaround())
2704         return [[self _webkit_invokeOnMainThread] initWithCoder:decoder];
2705
2706     WebCoreThreadViolationCheckRoundTwo();
2707     WebView *result = nil;
2708
2709     @try {
2710         NSString *frameName;
2711         NSString *groupName;
2712         WebPreferences *preferences;
2713         BOOL useBackForwardList = NO;
2714         BOOL allowsUndo = YES;
2715         
2716         result = [super initWithCoder:decoder];
2717         result->_private = [[WebViewPrivate alloc] init];
2718
2719         // We don't want any of the archived subviews. The subviews will always
2720         // be created in _commonInitializationFrameName:groupName:.
2721         [[result subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
2722
2723         if ([decoder allowsKeyedCoding]) {
2724             frameName = [decoder decodeObjectForKey:@"FrameName"];
2725             groupName = [decoder decodeObjectForKey:@"GroupName"];
2726             preferences = [decoder decodeObjectForKey:@"Preferences"];
2727             useBackForwardList = [decoder decodeBoolForKey:@"UseBackForwardList"];
2728             if ([decoder containsValueForKey:@"AllowsUndo"])
2729                 allowsUndo = [decoder decodeBoolForKey:@"AllowsUndo"];
2730         } else {
2731             int version;
2732             [decoder decodeValueOfObjCType:@encode(int) at:&version];
2733             frameName = [decoder decodeObject];
2734             groupName = [decoder decodeObject];
2735             preferences = [decoder decodeObject];
2736             if (version > 1)
2737                 [decoder decodeValuesOfObjCTypes:"c", &useBackForwardList];
2738             // The allowsUndo field is no longer written out in encodeWithCoder, but since there are
2739             // version 3 NIBs that have this field encoded, we still need to read it in.
2740             if (version == 3)
2741                 [decoder decodeValuesOfObjCTypes:"c", &allowsUndo];
2742         }
2743
2744         if (![frameName isKindOfClass:[NSString class]])
2745             frameName = nil;
2746         if (![groupName isKindOfClass:[NSString class]])
2747             groupName = nil;
2748         if (![preferences isKindOfClass:[WebPreferences class]])
2749             preferences = nil;
2750
2751         LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", frameName, groupName, (int)useBackForwardList);
2752         [result _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:YES];
2753         [result page]->backForwardList()->setEnabled(useBackForwardList);
2754         result->_private->allowsUndo = allowsUndo;
2755         if (preferences)
2756             [result setPreferences:preferences];
2757     } @catch (NSException *localException) {
2758         result = nil;
2759         [self release];
2760     }
2761
2762     return result;
2763 }
2764
2765 - (void)encodeWithCoder:(NSCoder *)encoder
2766 {
2767     // Set asside the subviews before we archive. We don't want to archive any subviews.
2768     // The subviews will always be created in _commonInitializationFrameName:groupName:.
2769     id originalSubviews = _subviews;
2770     _subviews = nil;
2771
2772     [super encodeWithCoder:encoder];
2773
2774     // Restore the subviews we set aside.
2775     _subviews = originalSubviews;
2776
2777     BOOL useBackForwardList = _private->page && _private->page->backForwardList()->enabled();
2778     if ([encoder allowsKeyedCoding]) {
2779         [encoder encodeObject:[[self mainFrame] name] forKey:@"FrameName"];
2780         [encoder encodeObject:[self groupName] forKey:@"GroupName"];
2781         [encoder encodeObject:[self preferences] forKey:@"Preferences"];
2782         [encoder encodeBool:useBackForwardList forKey:@"UseBackForwardList"];
2783         [encoder encodeBool:_private->allowsUndo forKey:@"AllowsUndo"];
2784     } else {
2785         int version = WebViewVersion;
2786         [encoder encodeValueOfObjCType:@encode(int) at:&version];
2787         [encoder encodeObject:[[self mainFrame] name]];
2788         [encoder encodeObject:[self groupName]];
2789         [encoder encodeObject:[self preferences]];
2790         [encoder encodeValuesOfObjCTypes:"c", &useBackForwardList];
2791         // DO NOT encode any new fields here, doing so will break older WebKit releases.
2792     }
2793
2794     LOG(Encoding, "FrameName = %@, GroupName = %@, useBackForwardList = %d\n", [[self mainFrame] name], [self groupName], (int)useBackForwardList);
2795 }
2796
2797 - (void)dealloc
2798 {
2799     if (WebCoreObjCScheduleDeallocateOnMainThread([WebView class], self))
2800         return;
2801
2802     // call close to ensure we tear-down completely
2803     // this maintains our old behavior for existing applications
2804     [self close];
2805
2806     if ([[self class] shouldIncludeInWebKitStatistics])
2807         --WebViewCount;
2808
2809     if ([self _needsFrameLoadDelegateRetainQuirk])
2810         [_private->frameLoadDelegate release];
2811         
2812     [_private release];
2813     // [super dealloc] can end up dispatching against _private (3466082)
2814     _private = nil;
2815
2816     [super dealloc];
2817 }
2818
2819 - (void)finalize
2820 {
2821     ASSERT(_private->closed);
2822
2823     --WebViewCount;
2824
2825     [super finalize];
2826 }
2827
2828 - (void)close
2829 {
2830     // _close existed first, and some clients might be calling or overriding it, so call through.
2831     [self _close];
2832 }
2833
2834 - (void)setShouldCloseWithWindow:(BOOL)close
2835 {
2836     _private->shouldCloseWithWindow = close;
2837 }
2838
2839 - (BOOL)shouldCloseWithWindow
2840 {
2841     return _private->shouldCloseWithWindow;
2842 }
2843
2844 - (void)addWindowObserversForWindow:(NSWindow *)window
2845 {
2846     if (window) {
2847         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:)
2848             name:NSWindowDidBecomeKeyNotification object:nil];
2849         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:)
2850             name:NSWindowDidResignKeyNotification object:nil];
2851         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOnScreen:)
2852             name:WKWindowWillOrderOnScreenNotification() object:window];
2853     }
2854 }
2855
2856 - (void)removeWindowObservers
2857 {
2858     NSWindow *window = [self window];
2859     if (window) {
2860         [[NSNotificationCenter defaultCenter] removeObserver:self
2861             name:NSWindowDidBecomeKeyNotification object:nil];
2862         [[NSNotificationCenter defaultCenter] removeObserver:self
2863             name:NSWindowDidResignKeyNotification object:nil];
2864         [[NSNotificationCenter defaultCenter] removeObserver:self
2865             name:WKWindowWillOrderOnScreenNotification() object:window];
2866     }
2867 }
2868
2869 - (void)viewWillMoveToWindow:(NSWindow *)window
2870 {
2871     // Don't do anything if the WebView isn't initialized.
2872     // This happens when decoding a WebView in a nib.
2873     // FIXME: What sets up the observer of NSWindowWillCloseNotification in this case?
2874     if (!_private || _private->closed)
2875         return;
2876     
2877     if ([self window] && [self window] != [self hostWindow])
2878         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:[self window]];
2879
2880     if (window) {
2881         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:window];
2882          
2883         // Ensure that we will receive the events that WebHTMLView (at least) needs.
2884         // The following are expensive enough that we don't want to call them over
2885         // and over, so do them when we move into a window.
2886         [window setAcceptsMouseMovedEvents:YES];
2887         WKSetNSWindowShouldPostEventNotifications(window, YES);
2888     } else {
2889         _private->page->setCanStartMedia(false);
2890         _private->page->willMoveOffscreen();
2891     }
2892         
2893     if (window != [self window]) {
2894         [self removeWindowObservers];
2895         [self addWindowObserversForWindow:window];
2896     }
2897 }
2898
2899 - (void)viewDidMoveToWindow
2900 {
2901     // Don't do anything if we aren't initialized.  This happens
2902     // when decoding a WebView.  When WebViews are decoded their subviews
2903     // are created by initWithCoder: and so won't be normally
2904     // initialized.  The stub views are discarded by WebView.
2905     if (!_private || _private->closed)
2906         return;
2907
2908     if ([self window]) {
2909         _private->page->setCanStartMedia(true);
2910         _private->page->didMoveOnscreen();
2911     }
2912     
2913     [self _updateActiveState];
2914 }
2915
2916 - (void)_windowDidBecomeKey:(NSNotification *)notification
2917 {
2918     NSWindow *keyWindow = [notification object];
2919     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
2920         [self _updateActiveState];
2921 }
2922
2923 - (void)_windowDidResignKey:(NSNotification *)notification
2924 {
2925     NSWindow *formerKeyWindow = [notification object];
2926     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet])
2927         [self _updateActiveState];
2928 }
2929
2930 - (void)_windowWillOrderOnScreen:(NSNotification *)notification
2931 {
2932     if (![self shouldUpdateWhileOffscreen])
2933         [self setNeedsDisplay:YES];
2934 }
2935
2936 - (void)_windowWillClose:(NSNotification *)notification
2937 {
2938     if ([self shouldCloseWithWindow] && ([self window] == [self hostWindow] || ([self window] && ![self hostWindow]) || (![self window] && [self hostWindow])))
2939         [self close];
2940 }
2941
2942 - (void)setPreferences:(WebPreferences *)prefs
2943 {
2944     if (!prefs)
2945         prefs = [WebPreferences standardPreferences];
2946
2947     if (_private->preferences == prefs)
2948         return;
2949
2950     [prefs willAddToWebView];
2951
2952     WebPreferences *oldPrefs = _private->preferences;
2953
2954     [[NSNotificationCenter defaultCenter] removeObserver:self name:WebPreferencesChangedNotification object:[self preferences]];
2955     [WebPreferences _removeReferenceForIdentifier:[oldPrefs identifier]];
2956
2957     _private->preferences = [prefs retain];
2958
2959     // After registering for the notification, post it so the WebCore settings update.
2960     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
2961         name:WebPreferencesChangedNotification object:[self preferences]];
2962     [[self preferences] _postPreferencesChangesNotification];
2963
2964     [oldPrefs didRemoveFromWebView];
2965     [oldPrefs release];
2966 }
2967
2968 - (WebPreferences *)preferences
2969 {
2970     return _private->preferences;
2971 }
2972
2973 - (void)setPreferencesIdentifier:(NSString *)anIdentifier
2974 {
2975     if (!_private->closed && ![anIdentifier isEqual:[[self preferences] identifier]]) {
2976         WebPreferences *prefs = [[WebPreferences alloc] initWithIdentifier:anIdentifier];
2977         [self setPreferences:prefs];
2978         [prefs release];
2979     }
2980 }
2981
2982 - (NSString *)preferencesIdentifier
2983 {
2984     return [[self preferences] identifier];
2985 }
2986
2987
2988 - (void)setUIDelegate:delegate
2989 {
2990     _private->UIDelegate = delegate;
2991     [_private->UIDelegateForwarder release];
2992     _private->UIDelegateForwarder = nil;
2993 }
2994
2995 - UIDelegate
2996 {
2997     return _private->UIDelegate;
2998 }
2999
3000 - (void)setResourceLoadDelegate: delegate
3001 {
3002     _private->resourceProgressDelegate = delegate;
3003     [self _cacheResourceLoadDelegateImplementations];
3004 }
3005
3006 - resourceLoadDelegate
3007 {
3008     return _private->resourceProgressDelegate;
3009 }
3010
3011 - (void)setDownloadDelegate: delegate
3012 {
3013     _private->downloadDelegate = delegate;
3014 }
3015
3016
3017 - downloadDelegate
3018 {
3019     return _private->downloadDelegate;
3020 }
3021
3022 - (void)setPolicyDelegate:delegate
3023 {
3024     _private->policyDelegate = delegate;
3025     [_private->policyDelegateForwarder release];
3026     _private->policyDelegateForwarder = nil;
3027 }
3028
3029 - policyDelegate
3030 {
3031     return _private->policyDelegate;
3032 }
3033
3034 - (void)setFrameLoadDelegate:delegate
3035 {
3036     // <rdar://problem/6950660> - Due to some subtle WebKit changes - presumably to delegate callback behavior - we've
3037     // unconvered a latent bug in at least one WebKit app where the delegate wasn't properly retained by the app and
3038     // was dealloc'ed before being cleared.
3039     // This is an effort to keep such apps working for now.
3040     if ([self _needsFrameLoadDelegateRetainQuirk]) {
3041         [delegate retain];
3042         [_private->frameLoadDelegate release];
3043     }
3044     
3045     _private->frameLoadDelegate = delegate;
3046     [self _cacheFrameLoadDelegateImplementations];
3047
3048 #if ENABLE(ICONDATABASE)
3049     // If this delegate wants callbacks for icons, fire up the icon database.
3050     if (_private->frameLoadDelegateImplementations.didReceiveIconForFrameFunc)
3051         [WebIconDatabase sharedIconDatabase];
3052 #endif
3053 }
3054
3055 - frameLoadDelegate
3056 {
3057     return _private->frameLoadDelegate;
3058 }
3059
3060 - (WebFrame *)mainFrame
3061 {
3062     // This can be called in initialization, before _private has been set up (3465613)
3063     if (!_private || !_private->page)
3064         return nil;
3065     return kit(_private->page->mainFrame());
3066 }
3067
3068 - (WebFrame *)selectedFrame
3069 {
3070     if (_private->usesDocumentViews) {
3071         // If the first responder is a view in our tree, we get the frame containing the first responder.
3072         // This is faster than searching the frame hierarchy, and will give us a result even in the case
3073         // where the focused frame doesn't actually contain a selection.
3074         WebFrame *focusedFrame = [self _focusedFrame];
3075         if (focusedFrame)
3076             return focusedFrame;
3077     }
3078     
3079     // If the first responder is outside of our view tree, we search for a frame containing a selection.
3080     // There should be at most only one of these.
3081     return [[self mainFrame] _findFrameWithSelection];
3082 }
3083
3084 - (WebBackForwardList *)backForwardList
3085 {
3086     if (!_private->page)
3087         return nil;
3088     if (!_private->page->backForwardList()->enabled())
3089         return nil;
3090     return kit(_private->page->backForwardList());
3091 }
3092
3093 - (void)setMaintainsBackForwardList:(BOOL)flag
3094 {
3095     if (!_private->page)
3096         return;
3097     _private->page->backForwardList()->setEnabled(flag);
3098 }
3099
3100 - (BOOL)goBack
3101 {
3102     if (!_private->page)
3103         return NO;
3104     
3105     return _private->page->goBack();
3106 }
3107
3108 - (BOOL)goForward
3109 {
3110     if (!_private->page)
3111         return NO;
3112
3113     return _private->page->goForward();
3114 }
3115
3116 - (BOOL)goToBackForwardItem:(WebHistoryItem *)item
3117 {
3118     if (!_private->page)
3119         return NO;
3120
3121     _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
3122     return YES;
3123 }
3124
3125 - (void)setTextSizeMultiplier:(float)m
3126 {
3127     [self _setZoomMultiplier:m isTextOnly:![[NSUserDefaults standardUserDefaults] boolForKey:WebKitDebugFullPageZoomPreferenceKey]];
3128 }
3129
3130 - (float)textSizeMultiplier
3131 {
3132     return [self _realZoomMultiplierIsTextOnly] ? _private->zoomMultiplier : 1.0f;
3133 }
3134
3135 - (void)_setZoomMultiplier:(float)m isTextOnly:(BOOL)isTextOnly
3136 {
3137     // NOTE: This has no visible effect when viewing a PDF (see <rdar://problem/4737380>)
3138     _private->zoomMultiplier = m;
3139     ASSERT(_private->page);
3140     if (_private->page)
3141         _private->page->settings()->setZoomMode(isTextOnly ? ZoomTextOnly : ZoomPage);
3142     
3143     // FIXME: it would be nice to rework this code so that _private->zoomMultiplier doesn't exist and callers
3144     // all access _private->page->settings().
3145     Frame* coreFrame = [self _mainCoreFrame];
3146     if (coreFrame)
3147         coreFrame->setZoomFactor(m, isTextOnly ? ZoomTextOnly : ZoomPage);
3148 }
3149
3150 - (float)_zoomMultiplier:(BOOL)isTextOnly
3151 {
3152     if (isTextOnly != [self _realZoomMultiplierIsTextOnly])
3153         return 1.0f;
3154     return _private->zoomMultiplier;
3155 }
3156
3157 - (float)_realZoomMultiplier
3158 {
3159     return _private->zoomMultiplier;
3160 }
3161
3162 - (BOOL)_realZoomMultiplierIsTextOnly
3163 {
3164     if (!_private->page)
3165         return NO;
3166     
3167     return _private->page->settings()->zoomMode() == ZoomTextOnly;
3168 }
3169
3170 #define MinimumZoomMultiplier       0.5f
3171 #define MaximumZoomMultiplier       3.0f
3172 #define ZoomMultiplierRatio         1.2f
3173
3174 - (BOOL)_canZoomOut:(BOOL)isTextOnly
3175 {
3176     id docView = [[[self mainFrame] frameView] documentView];
3177     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3178         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3179         return [zoomingDocView _canZoomOut];
3180     }
3181     return [self _zoomMultiplier:isTextOnly] / ZoomMultiplierRatio > MinimumZoomMultiplier;
3182 }
3183
3184
3185 - (BOOL)_canZoomIn:(BOOL)isTextOnly
3186 {
3187     id docView = [[[self mainFrame] frameView] documentView];
3188     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3189         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3190         return [zoomingDocView _canZoomIn];
3191     }
3192     return [self _zoomMultiplier:isTextOnly] * ZoomMultiplierRatio < MaximumZoomMultiplier;
3193 }
3194
3195 - (IBAction)_zoomOut:(id)sender isTextOnly:(BOOL)isTextOnly
3196 {
3197     id docView = [[[self mainFrame] frameView] documentView];
3198     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3199         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3200         return [zoomingDocView _zoomOut:sender];
3201     }
3202     float newScale = [self _zoomMultiplier:isTextOnly] / ZoomMultiplierRatio;
3203     if (newScale > MinimumZoomMultiplier)
3204         [self _setZoomMultiplier:newScale isTextOnly:isTextOnly];
3205 }
3206
3207 - (IBAction)_zoomIn:(id)sender isTextOnly:(BOOL)isTextOnly
3208 {
3209     id docView = [[[self mainFrame] frameView] documentView];
3210     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3211         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3212         return [zoomingDocView _zoomIn:sender];
3213     }
3214     float newScale = [self _zoomMultiplier:isTextOnly] * ZoomMultiplierRatio;
3215     if (newScale < MaximumZoomMultiplier)
3216         [self _setZoomMultiplier:newScale isTextOnly:isTextOnly];
3217 }
3218
3219 - (BOOL)_canResetZoom:(BOOL)isTextOnly
3220 {
3221     id docView = [[[self mainFrame] frameView] documentView];
3222     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3223         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3224         return [zoomingDocView _canResetZoom];
3225     }
3226     return [self _zoomMultiplier:isTextOnly] != 1.0f;
3227 }
3228
3229 - (IBAction)_resetZoom:(id)sender isTextOnly:(BOOL)isTextOnly
3230 {
3231     id docView = [[[self mainFrame] frameView] documentView];
3232     if ([docView conformsToProtocol:@protocol(_WebDocumentZooming)]) {
3233         id <_WebDocumentZooming> zoomingDocView = (id <_WebDocumentZooming>)docView;
3234         return [zoomingDocView _resetZoom:sender];
3235     }
3236     if ([self _zoomMultiplier:isTextOnly] != 1.0f)
3237         [self _setZoomMultiplier:1.0f isTextOnly:isTextOnly];
3238 }
3239
3240 - (void)setApplicationNameForUserAgent:(NSString *)applicationName
3241 {
3242     NSString *name = [applicationName copy];
3243     [_private->applicationNameForUserAgent release];
3244     _private->applicationNameForUserAgent = name;
3245     if (!_private->userAgentOverridden)
3246         _private->userAgent = String();
3247 }
3248
3249 - (NSString *)applicationNameForUserAgent
3250 {
3251     return [[_private->applicationNameForUserAgent retain] autorelease];
3252 }
3253
3254 - (void)setCustomUserAgent:(NSString *)userAgentString
3255 {
3256     _private->userAgent = userAgentString;
3257     _private->userAgentOverridden = userAgentString != nil;
3258 }
3259
3260 - (NSString *)customUserAgent
3261 {
3262     if (!_private->userAgentOverridden)
3263         return nil;
3264     return _private->userAgent;
3265 }
3266
3267 - (void)setMediaStyle:(NSString *)mediaStyle
3268 {
3269     if (_private->mediaStyle != mediaStyle) {
3270         [_private->mediaStyle release];
3271         _private->mediaStyle = [mediaStyle copy];
3272     }
3273 }
3274
3275 - (NSString *)mediaStyle
3276 {
3277     return _private->mediaStyle;
3278 }
3279
3280 - (BOOL)supportsTextEncoding
3281 {
3282     id documentView = [[[self mainFrame] frameView] documentView];
3283     return [documentView conformsToProtocol:@protocol(WebDocumentText)]
3284         && [documentView supportsTextEncoding];
3285 }
3286
3287 - (void)setCustomTextEncodingName:(NSString *)encoding
3288 {
3289     NSString *oldEncoding = [self customTextEncodingName];
3290     if (encoding == oldEncoding || [encoding isEqualToString:oldEncoding])
3291         return;
3292     if (Frame* mainFrame = [self _mainCoreFrame])
3293         mainFrame->loader()->reloadWithOverrideEncoding(encoding);
3294 }
3295
3296 - (NSString *)_mainFrameOverrideEncoding
3297 {
3298     WebDataSource *dataSource = [[self mainFrame] provisionalDataSource];
3299     if (dataSource == nil)
3300         dataSource = [[self mainFrame] _dataSource];
3301     if (dataSource == nil)
3302         return nil;
3303     return nsStringNilIfEmpty([dataSource _documentLoader]->overrideEncoding());
3304 }
3305
3306 - (NSString *)customTextEncodingName
3307 {
3308     return [self _mainFrameOverrideEncoding];
3309 }
3310
3311 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
3312 {
3313     // Return statements are only valid in a function but some applications pass in scripts
3314     // prefixed with return (<rdar://problems/5103720&4616860>) since older WebKit versions
3315     // silently ignored the return. If the application is linked against an earlier version
3316     // of WebKit we will strip the return so the script wont fail.
3317     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_JAVASCRIPT_RETURN_QUIRK)) {
3318         NSRange returnStringRange = [script rangeOfString:@"return "];
3319         if (returnStringRange.length && !returnStringRange.location)
3320             script = [script substringFromIndex:returnStringRange.location + returnStringRange.length];
3321     }
3322
3323     NSString *result = [[self mainFrame] _stringByEvaluatingJavaScriptFromString:script];
3324     // The only way stringByEvaluatingJavaScriptFromString can return nil is if the frame was removed by the script
3325     // Since there's no way to get rid of the main frame, result will never ever be nil here.
3326     ASSERT(result);
3327
3328     return result;
3329 }
3330
3331 - (WebScriptObject *)windowScriptObject
3332 {
3333     Frame* coreFrame = [self _mainCoreFrame];
3334     if (!coreFrame)
3335         return nil;
3336     return coreFrame->script()->windowScriptObject();
3337 }
3338
3339 // Get the appropriate user-agent string for a particular URL.
3340 - (NSString *)userAgentForURL:(NSURL *)url
3341 {
3342     if (_private->useSiteSpecificSpoofing) {
3343         // No current site-specific spoofs.
3344     }
3345
3346     if (_private->userAgent.isNull())
3347         _private->userAgent = [[self class] _standardUserAgentWithApplicationName:_private->applicationNameForUserAgent];
3348
3349     return _private->userAgent;
3350 }
3351
3352 - (void)setHostWindow:(NSWindow *)hostWindow
3353 {
3354     if (_private->closed && hostWindow)
3355         return;
3356     if (hostWindow == _private->hostWindow)
3357         return;
3358
3359     Frame* coreFrame = [self _mainCoreFrame];
3360     if (_private->usesDocumentViews) {
3361         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame))
3362             [[[kit(frame) frameView] documentView] viewWillMoveToHostWindow:hostWindow];
3363     }
3364     if (_private->hostWindow && [self window] != _private->hostWindow)
3365         [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowWillCloseNotification object:_private->hostWindow];
3366     if (hostWindow)
3367         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillClose:) name:NSWindowWillCloseNotification object:hostWindow];
3368     [_private->hostWindow release];
3369     _private->hostWindow = [hostWindow retain];
3370     if (_private->usesDocumentViews) {
3371         for (Frame* frame = coreFrame; frame; frame = frame->tree()->traverseNext(coreFrame))
3372             [[[kit(frame) frameView] documentView] viewDidMoveToHostWindow];
3373     }
3374 }
3375
3376 - (NSWindow *)hostWindow
3377 {
3378     // -[WebView hostWindow] can sometimes be called from the WebView's [super dealloc] method
3379     // so we check here to make sure it's not null.
3380     if (!_private)
3381         return nil;
3382     
3383     return _private->hostWindow;
3384 }
3385
3386 - (NSView <WebDocumentView> *)documentViewAtWindowPoint:(NSPoint)point
3387 {
3388     return [[self _frameViewAtWindowPoint:point] documentView];
3389 }
3390
3391 - (NSDictionary *)_elementAtWindowPoint:(NSPoint)windowPoint
3392 {
3393     WebFrameView *frameView = [self _frameViewAtWindowPoint:windowPoint];
3394     if (!frameView)
3395         return nil;
3396     NSView <WebDocumentView> *documentView = [frameView documentView];
3397     if ([documentView conformsToProtocol:@protocol(WebDocumentElement)]) {
3398         NSPoint point = [documentView convertPoint:windowPoint fromView:nil];
3399         return [(NSView <WebDocumentElement> *)documentView elementAtPoint:point];
3400     }
3401     return [NSDictionary dictionaryWithObject:[frameView webFrame] forKey:WebElementFrameKey];
3402 }
3403
3404 - (NSDictionary *)elementAtPoint:(NSPoint)point
3405 {
3406     return [self _elementAtWindowPoint:[self convertPoint:point toView:nil]];
3407 }
3408
3409 // The following 2 internal NSView methods are called on the drag destination to make scrolling while dragging work.
3410 // Scrolling while dragging will only work if the drag destination is in a scroll view. The WebView is the drag destination. 
3411 // When dragging to a WebView, the document subview should scroll, but it doesn't because it is not the drag destination. 
3412 // Forward these calls to the document subview to make its scroll view scroll.
3413 - (void)_autoscrollForDraggingInfo:(id)draggingInfo timeDelta:(NSTimeInterval)repeatDelta
3414 {
3415     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3416     [documentView _autoscrollForDraggingInfo:draggingInfo timeDelta:repeatDelta];
3417 }
3418
3419 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)draggingInfo
3420 {
3421     NSView <WebDocumentView> *documentView = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3422     return [documentView _shouldAutoscrollForDraggingInfo:draggingInfo];
3423 }
3424
3425 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
3426 {
3427     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3428     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
3429     IntPoint client([draggingInfo draggingLocation]);
3430     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
3431     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
3432     return core(self)->dragController()->dragEntered(&dragData);
3433 }
3434
3435 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
3436 {
3437     Page* page = core(self);
3438     if (!page)
3439         return NSDragOperationNone;
3440
3441     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3442     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
3443     IntPoint client([draggingInfo draggingLocation]);
3444     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
3445     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
3446     return page->dragController()->dragUpdated(&dragData);
3447 }
3448
3449 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
3450 {
3451     Page* page = core(self);
3452     if (!page)
3453         return;
3454
3455     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3456     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]] ? (WebHTMLView*)view : nil);
3457     IntPoint client([draggingInfo draggingLocation]);
3458     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
3459     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
3460     page->dragController()->dragExited(&dragData);
3461 }
3462
3463 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
3464 {
3465     return YES;
3466 }
3467
3468 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
3469 {
3470     NSView <WebDocumentView>* view = [self documentViewAtWindowPoint:[draggingInfo draggingLocation]];
3471     WebPasteboardHelper helper([view isKindOfClass:[WebHTMLView class]]? (WebHTMLView*)view : nil);
3472     IntPoint client([draggingInfo draggingLocation]);
3473     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
3474     DragData dragData(draggingInfo, client, global, (DragOperation)[draggingInfo draggingSourceOperationMask], &helper);
3475     return core(self)->dragController()->performDrag(&dragData);
3476 }
3477
3478 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
3479 {
3480     NSView *hitView = [super _hitTest:point dragTypes:types];
3481     if (!hitView && [[self superview] mouse:*point inRect:[self frame]])
3482         return self;
3483     return hitView;
3484 }
3485
3486 - (BOOL)acceptsFirstResponder
3487 {
3488     if (_private->usesDocumentViews)
3489         return [[[self mainFrame] frameView] acceptsFirstResponder];
3490
3491     // FIXME (Viewless): Need more code from WebHTMLView here.
3492     return YES;
3493 }
3494
3495 - (BOOL)becomeFirstResponder
3496 {
3497     if (_private->usesDocumentViews) {
3498         if (_private->becomingFirstResponder) {
3499             // Fix for unrepro infinite recursion reported in Radar 4448181. If we hit this assert on
3500             // a debug build, we should figure out what causes the problem and do a better fix.
3501             ASSERT_NOT_REACHED();
3502             return NO;
3503         }
3504         
3505         // This works together with setNextKeyView to splice the WebView into
3506         // the key loop similar to the way NSScrollView does this. Note that
3507         // WebFrameView has very similar code.
3508         NSWindow *window = [self window];
3509         WebFrameView *mainFrameView = [[self mainFrame] frameView];
3510
3511         NSResponder *previousFirstResponder = [[self window] _oldFirstResponderBeforeBecoming];
3512         BOOL fromOutside = ![previousFirstResponder isKindOfClass:[NSView class]] || (![(NSView *)previousFirstResponder isDescendantOf:self] && previousFirstResponder != self);
3513
3514         if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
3515             NSView *previousValidKeyView = [self previousValidKeyView];
3516             if (previousValidKeyView != self && previousValidKeyView != mainFrameView) {
3517                 _private->becomingFirstResponder = YES;
3518                 _private->becomingFirstResponderFromOutside = fromOutside;
3519                 [window makeFirstResponder:previousValidKeyView];
3520                 _private->becomingFirstResponderFromOutside = NO;
3521                 _private->becomingFirstResponder = NO;
3522                 return YES;
3523             }
3524             return NO;
3525         }
3526
3527         if ([mainFrameView acceptsFirstResponder]) {
3528             _private->becomingFirstResponder = YES;
3529             _private->becomingFirstResponderFromOutside = fromOutside;
3530             [window makeFirstResponder:mainFrameView];
3531             _private->becomingFirstResponderFromOutside = NO;
3532             _private->becomingFirstResponder = NO;
3533             return YES;
3534         } 
3535
3536         return NO;
3537     }
3538
3539     // FIXME (Viewless): Need more code from WebHTMLView here.
3540     return YES;
3541 }
3542
3543 - (NSView *)_webcore_effectiveFirstResponder
3544 {
3545     if (_private && _private->usesDocumentViews) {
3546         if (WebFrameView *frameView = [[self mainFrame] frameView])
3547             return [frameView _webcore_effectiveFirstResponder];
3548     }
3549     return [super _webcore_effectiveFirstResponder];
3550 }
3551
3552 - (void)setNextKeyView:(NSView *)view
3553 {
3554     if (_private && _private->usesDocumentViews) {
3555         // This works together with becomeFirstResponder to splice the WebView into
3556         // the key loop similar to the way NSScrollView does this. Note that
3557         // WebFrameView has similar code.
3558         if (WebFrameView *mainFrameView = [[self mainFrame] frameView]) {
3559             [mainFrameView setNextKeyView:view];
3560             return;
3561         }
3562     }
3563
3564     [super setNextKeyView:view];
3565 }
3566
3567 static WebFrame *incrementFrame(WebFrame *frame, BOOL forward, BOOL wrapFlag)
3568 {
3569     Frame* coreFrame = core(frame);
3570     return kit(forward
3571         ? coreFrame->tree()->traverseNextWithWrap(wrapFlag)
3572         : coreFrame->tree()->traversePreviousWithWrap(wrapFlag));
3573 }
3574
3575 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
3576 {
3577     return [self searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag startInSelection:NO];
3578 }
3579
3580 + (void)registerViewClass:(Class)viewClass representationClass:(Class)representationClass forMIMEType:(NSString *)MIMEType
3581 {
3582     [[WebFrameView _viewTypesAllowImageTypeOmission:YES] setObject:viewClass forKey:MIMEType];
3583     [[WebDataSource _repTypesAllowImageTypeOmission:YES] setObject:representationClass forKey:MIMEType];
3584     
3585     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3586     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3587     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3588     if ([viewClass class] == [WebHTMLView class])
3589         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3590 }
3591
3592 - (void)setGroupName:(NSString *)groupName
3593 {
3594     if (!_private->page)
3595         return;
3596     _private->page->setGroupName(groupName);
3597 }
3598
3599 - (NSString *)groupName
3600 {
3601     if (!_private->page)
3602         return nil;
3603     return _private->page->groupName();
3604 }
3605
3606 - (double)estimatedProgress
3607 {
3608     if (!_private->page)
3609         return 0.0;
3610     return _private->page->progress()->estimatedProgress();
3611 }
3612
3613 - (NSArray *)pasteboardTypesForSelection
3614 {
3615     NSView <WebDocumentView> *documentView = [[[self _selectedOrMainFrame] frameView] documentView];
3616     if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)]) {
3617         return [(NSView <WebDocumentSelection> *)documentView pasteboardTypesForSelection];
3618     }
3619     return [NSArray array];
3620 }
3621
3622 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3623 {
3624     WebFrame *frame = [self _selectedOrMainFrame];
3625     if (frame && [frame _hasSelection]) {
3626         NSView <WebDocumentView> *documentView = [[frame frameView] documentView];
3627         if ([documentView conformsToProtocol:@protocol(WebDocumentSelection)])
3628             [(NSView <WebDocumentSelection> *)documentView writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
3629     }
3630 }
3631
3632 - (NSArray *)pasteboardTypesForElement:(NSDictionary *)element
3633 {
3634     if ([element objectForKey:WebElementImageURLKey] != nil) {
3635         return [NSPasteboard _web_writableTypesForImageIncludingArchive:([element objectForKey:WebElementDOMNodeKey] != nil)];
3636     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
3637         return [NSPasteboard _web_writableTypesForURL];
3638     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
3639         return [self pasteboardTypesForSelection];
3640     }
3641     return [NSArray array];
3642 }
3643
3644 - (void)writeElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3645 {
3646     if ([element objectForKey:WebElementImageURLKey] != nil) {
3647         [self _writeImageForElement:element withPasteboardTypes:types toPasteboard:pasteboard];
3648     } else if ([element objectForKey:WebElementLinkURLKey] != nil) {
3649         [self _writeLinkElement:element withPasteboardTypes:types toPasteboard:pasteboard];
3650     } else if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
3651         [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
3652     }
3653 }
3654
3655 - (void)moveDragCaretToPoint:(NSPoint)point
3656 {
3657     if (Page* page = core(self))
3658         page->dragController()->placeDragCaret(IntPoint([self convertPoint:point toView:nil]));
3659 }
3660
3661 - (void)removeDragCaret
3662 {
3663     if (Page* page = core(self))
3664         page->dragController()->dragEnded();
3665 }
3666
3667 - (void)setMainFrameURL:(NSString *)URLString
3668 {
3669     [[self mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL _web_URLWithDataAsString: URLString]]];
3670 }
3671
3672 - (NSString *)mainFrameURL
3673 {
3674     WebDataSource *ds;
3675     ds = [[self mainFrame] provisionalDataSource];
3676     if (!ds)
3677         ds = [[self mainFrame] _dataSource];
3678     return [[[ds request] URL] _web_originalDataAsString];
3679 }
3680
3681 - (BOOL)isLoading
3682 {
3683     LOG (Bindings, "isLoading = %d", (int)[self _isLoading]);
3684     return [self _isLoading];
3685 }
3686
3687 - (NSString *)mainFrameTitle
3688 {
3689     NSString *mainFrameTitle = [[[self mainFrame] _dataSource] pageTitle];
3690     return (mainFrameTitle != nil) ? mainFrameTitle : (NSString *)@"";
3691 }
3692
3693 - (NSImage *)mainFrameIcon