LayoutTests:
[WebKit-https.git] / WebKit / WebView / WebHTMLView.m
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import <WebKit/WebHTMLView.h>
30
31 #import <ApplicationServices/ApplicationServices.h>
32 #import <WebKit/DOM.h>
33 #import <WebKit/DOMExtensions.h>
34 #import <WebKit/DOMPrivate.h>
35 #import <WebKit/WebArchive.h>
36 #import <WebKit/WebArchiver.h>
37 #import <WebKit/WebBaseNetscapePluginViewInternal.h>
38 #import <WebKit/WebFrameBridge.h>
39 #import <WebKit/WebClipView.h>
40 #import <WebKit/WebDataProtocol.h>
41 #import <WebKit/WebDataSourceInternal.h>
42 #import <WebKit/WebDefaultUIDelegate.h>
43 #import <WebKit/WebDocumentInternal.h>
44 #import <WebKit/WebDOMOperationsPrivate.h>
45 #import <WebKit/WebEditingDelegate.h>
46 #import <WebKit/WebElementDictionary.h>
47 #import <WebKit/WebFramePrivate.h>
48 #import <WebKit/WebFrameInternal.h>
49 #import <WebKit/WebFrameViewInternal.h>
50 #import <WebKit/WebHTMLViewInternal.h>
51 #import <WebKit/WebHTMLRepresentationPrivate.h>
52 #import <WebKit/WebKitLogging.h>
53 #import <WebKit/WebKitNSStringExtras.h>
54 #import <WebKit/WebNetscapePluginEmbeddedView.h>
55 #import <WebKit/WebNSAttributedStringExtras.h>
56 #import <WebKit/WebNSEventExtras.h>
57 #import <WebKit/WebNSFileManagerExtras.h>
58 #import <WebKit/WebNSImageExtras.h>
59 #import <WebKit/WebNSObjectExtras.h>
60 #import <WebKit/WebNSPasteboardExtras.h>
61 #import <WebKit/WebNSPrintOperationExtras.h>
62 #import <WebKit/WebNSURLExtras.h>
63 #import <WebKit/WebNSViewExtras.h>
64 #import <WebKit/WebPluginController.h>
65 #import <WebKit/WebPreferences.h>
66 #import <WebKit/WebPreferencesPrivate.h>
67 #import <WebKit/WebResourcePrivate.h>
68 #import <WebKit/WebStringTruncator.h>
69 #import <WebKit/WebUIDelegatePrivate.h>
70 #import <WebKit/WebViewInternal.h>
71 #import <WebKitSystemInterface.h>
72 #import <WebCore/WebCoreTextRenderer.h>
73
74 #import <AppKit/NSAccessibility.h>
75
76 // Included so usage of _NSSoftLinkingGetFrameworkFuncPtr will compile
77 #import <mach-o/dyld.h> 
78
79
80 // need to declare this because AppKit does not make it available as API or SPI
81 extern NSString *NSMarkedClauseSegmentAttributeName; 
82 extern NSString *NSTextInputReplacementRangeAttributeName; 
83
84 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
85 void _NSInitializeKillRing(void);
86 void _NSAppendToKillRing(NSString *);
87 void _NSPrependToKillRing(NSString *);
88 NSString *_NSYankFromKillRing(void);
89 NSString *_NSYankPreviousFromKillRing(void);
90 void _NSNewKillRingSequence(void);
91 void _NSSetKillRingToYankedState(void);
92 void _NSResetKillRingOperationFlag(void);
93
94 @interface NSView (AppKitSecretsIKnowAbout)
95 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
96 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
97 - (NSRect)_dirtyRect;
98 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
99 - (void)_propagateDirtyRectsToOpaqueAncestors;
100 @end
101
102 @interface NSApplication (AppKitSecretsIKnowAbout)
103 - (void)speakString:(NSString *)string;
104 @end
105
106 @interface NSWindow (AppKitSecretsIKnowAbout)
107 - (id)_newFirstResponderAfterResigning;
108 @end
109
110 @interface NSAttributedString (AppKitSecretsIKnowAbout)
111 - (id)_initWithDOMRange:(DOMRange *)domRange;
112 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
113 @end
114
115 @interface NSSpellChecker (CurrentlyPrivateForTextView)
116 - (void)learnWord:(NSString *)word;
117 @end
118
119 // By imaging to a width a little wider than the available pixels,
120 // thin pages will be scaled down a little, matching the way they
121 // print in IE and Camino. This lets them use fewer sheets than they
122 // would otherwise, which is presumably why other browsers do this.
123 // Wide pages will be scaled down more than this.
124 #define PrintingMinimumShrinkFactor     1.25
125
126 // This number determines how small we are willing to reduce the page content
127 // in order to accommodate the widest line. If the page would have to be
128 // reduced smaller to make the widest line fit, we just clip instead (this
129 // behavior matches MacIE and Mozilla, at least)
130 #define PrintingMaximumShrinkFactor     2.0
131
132 #define AUTOSCROLL_INTERVAL             0.1
133
134 #define DRAG_LABEL_BORDER_X             4.0
135 #define DRAG_LABEL_BORDER_Y             2.0
136 #define DRAG_LABEL_RADIUS               5.0
137 #define DRAG_LABEL_BORDER_Y_OFFSET              2.0
138
139 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP        120.0
140 #define MAX_DRAG_LABEL_WIDTH                    320.0
141
142 #define DRAG_LINK_LABEL_FONT_SIZE   11.0
143 #define DRAG_LINK_URL_FONT_SIZE   10.0
144
145 // Any non-zero value will do, but using something recognizable might help us debug some day.
146 #define TRACKING_RECT_TAG 0xBADFACE
147
148 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
149 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
150
151 #define STANDARD_WEIGHT 5
152 #define MIN_BOLD_WEIGHT 9
153 #define STANDARD_BOLD_WEIGHT 10
154
155 typedef enum {
156     deleteSelectionAction,
157     deleteKeyAction,
158     forwardDeleteKeyAction
159 } WebDeletionAction;
160
161 // if YES, do the standard NSView hit test (which can't give the right result when HTML overlaps a view)
162 static BOOL forceNSViewHitTest = NO;
163
164 // if YES, do the "top WebHTMLView" it test (which we'd like to do all the time but can't because of Java requirements [see bug 4349721])
165 static BOOL forceWebHTMLViewHitTest = NO;
166
167 // Used to avoid linking with ApplicationServices framework for _DCMDictionaryServiceWindowShow
168 void *_NSSoftLinkingGetFrameworkFuncPtr(NSString *inUmbrellaFrameworkName,
169                                         NSString *inFrameworkName,
170                                         const char *inFuncName,
171                                         const struct mach_header **ioCachedFrameworkImageHeaderPtr);
172
173
174 @interface WebHTMLView (WebTextSizing) <_WebDocumentTextSizing>
175 @end
176
177 @interface WebHTMLView (WebHTMLViewFileInternal)
178 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
179 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText;
180 - (NSString *)_plainTextFromPasteboard:(NSPasteboard *)pasteboard;
181 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
182 - (void)_pasteAsPlainTextWithPasteboard:(NSPasteboard *)pasteboard;
183 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
184 - (BOOL)_shouldInsertText:(NSString *)text replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
185 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
186 - (float)_calculatePrintHeight;
187 - (void)_updateTextSizeMultiplier;
188 - (DOMRange *)_selectedRange;
189 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
190 - (void)_deleteRange:(DOMRange *)range 
191             killRing:(BOOL)killRing 
192              prepend:(BOOL)prepend 
193        smartDeleteOK:(BOOL)smartDeleteOK
194       deletionAction:(WebDeletionAction)deletionAction
195          granularity:(WebBridgeSelectionGranularity)granularity;
196 - (void)_deleteSelection;
197 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
198 - (NSView *)_hitViewForEvent:(NSEvent *)event;
199 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString;
200 @end
201
202 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
203 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
204 @end
205
206 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
207 - (void)_updateSelectionForInputManager;
208 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
209 @end
210
211 @interface WebHTMLView (WebEditingStyleSupport)
212 - (DOMCSSStyleDeclaration *)_emptyStyle;
213 - (NSString *)_colorAsString:(NSColor *)color;
214 @end
215
216 @interface NSView (WebHTMLViewFileInternal)
217 - (void)_web_setPrintingModeRecursive;
218 - (void)_web_clearPrintingModeRecursive;
219 - (void)_web_layoutIfNeededRecursive;
220 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
221 @end
222
223 @interface NSMutableDictionary (WebHTMLViewFileInternal)
224 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
225 @end
226
227 // Handles the complete: text command
228 @interface WebTextCompleteController : NSObject
229 {
230 @private
231     WebHTMLView *_view;
232     NSWindow *_popupWindow;
233     NSTableView *_tableView;
234     NSArray *_completions;
235     NSString *_originalString;
236     int prefixLength;
237 }
238 - (id)initWithHTMLView:(WebHTMLView *)view;
239 - (void)doCompletion;
240 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
241 - (BOOL)filterKeyDown:(NSEvent *)event;
242 - (void)_reflectSelection;
243 @end
244
245 @implementation WebHTMLViewPrivate
246
247 - (void)dealloc
248 {
249     ASSERT(autoscrollTimer == nil);
250     ASSERT(autoscrollTriggerEvent == nil);
251     
252     [mouseDownEvent release];
253     [draggingImageURL release];
254     [pluginController release];
255     [toolTip release];
256     [compController release];
257     [firstResponderAtMouseDownTime release];
258     [dataSource release];
259     [highlighters release];
260
261     [super dealloc];
262 }
263
264 @end
265
266 @implementation WebHTMLView (WebHTMLViewFileInternal)
267
268 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
269 {
270     NSArray *imageMIMETypes = [WebFrameBridge supportedImageResourceMIMETypes];
271     NSEnumerator *enumerator = [paths objectEnumerator];
272     NSString *path;
273     
274     while ((path = [enumerator nextObject]) != nil) {
275         NSString *MIMEType = WKGetMIMETypeForExtension([path pathExtension]);
276         if ([imageMIMETypes containsObject:MIMEType]) {
277             return YES;
278         }
279     }
280     
281     return NO;
282 }
283
284 - (WebDataSource *)_dataSource
285 {
286     return _private->dataSource;
287 }
288
289 - (WebFrameBridge *)_bridge
290 {
291     return [_private->dataSource _bridge];
292 }
293
294 - (WebView *)_webView
295 {
296     return [_private->dataSource _webView];
297 }
298
299 - (WebFrameView *)_frameView
300 {
301     return [[_private->dataSource webFrame] frameView];
302 }
303
304 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
305 {
306     DOMDocumentFragment *fragment;
307     NSArray *imageMIMETypes = [WebFrameBridge supportedImageResourceMIMETypes];
308     NSEnumerator *enumerator = [paths objectEnumerator];
309     WebDataSource *dataSource = [self _dataSource];
310     NSMutableArray *domNodes = [[NSMutableArray alloc] init];
311     NSString *path;
312     
313     while ((path = [enumerator nextObject]) != nil) {
314         NSString *MIMEType = WKGetMIMETypeForExtension([path pathExtension]);
315         if ([imageMIMETypes containsObject:MIMEType]) {
316             WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
317                                                                   URL:[NSURL fileURLWithPath:path]
318                                                              MIMEType:MIMEType 
319                                                      textEncodingName:nil
320                                                             frameName:nil];
321             if (resource) {
322                 [domNodes addObject:[dataSource _imageElementWithImageResource:resource]];
323                 [resource release];
324             }
325         } else {
326             // Non-image file types
327             NSString *url = [[[NSURL fileURLWithPath:path] _webkit_canonicalize] _web_userVisibleString];
328             [domNodes addObject:[[[self _bridge] DOMDocument] createTextNode: url]];
329         }
330     }
331     
332     fragment = [[self _bridge] documentFragmentWithNodesAsParagraphs:domNodes]; 
333     
334     [domNodes release];
335     
336     return [fragment firstChild] != nil ? fragment : nil;
337 }
338
339 + (NSArray *)_excludedElementsForAttributedStringConversion
340 {
341     static NSArray *elements = nil;
342     if (elements == nil) {
343         elements = [[NSArray alloc] initWithObjects:
344             // Omit style since we want style to be inline so the fragment can be easily inserted.
345             @"style",
346             // Omit xml so the result is not XHTML.
347             @"xml", 
348             // Omit tags that will get stripped when converted to a fragment anyway.
349             @"doctype", @"html", @"head", @"body",
350             // Omit deprecated tags.
351             @"applet", @"basefont", @"center", @"dir", @"font", @"isindex", @"menu", @"s", @"strike", @"u",
352             // Omit object so no file attachments are part of the fragment.
353             @"object", nil];
354     }
355     return elements;
356 }
357
358 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText
359 {
360     NSArray *types = [pasteboard types];
361     *chosePlainText = NO;
362
363     if ([types containsObject:WebArchivePboardType]) {
364         WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
365         if (archive) {
366             DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
367             [archive release];
368             if (fragment) {
369                 return fragment;
370             }
371         }
372     }
373     
374     if ([types containsObject:NSFilenamesPboardType]) {
375         DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
376         if (fragment != nil) {
377             return fragment;
378         }
379     }
380     
381     NSURL *URL;
382     
383     if ([types containsObject:NSHTMLPboardType]) {
384         NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
385         // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
386         if ([HTMLString hasPrefix:@"Version:"]) {
387             NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
388             if (range.location != NSNotFound) {
389                 HTMLString = [HTMLString substringFromIndex:range.location];
390             }
391         }
392         if ([HTMLString length] != 0) {
393             return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
394         }
395     }
396         
397     NSAttributedString *string = nil;
398     if ([types containsObject:NSRTFDPboardType]) {
399         string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
400     }
401     if (string == nil && [types containsObject:NSRTFPboardType]) {
402         string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
403     }
404     if (string != nil) {
405         NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
406             [[self class] _excludedElementsForAttributedStringConversion], NSExcludedElementsDocumentAttribute,
407             self, @"WebResourceHandler", nil];
408         NSArray *subresources;
409         DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length]) 
410                                                           document:[[self _bridge] DOMDocument] 
411                                                 documentAttributes:documentAttributes
412                                                       subresources:&subresources];
413         [documentAttributes release];
414         [string release];
415         return fragment;
416     }
417     
418     if ([types containsObject:NSTIFFPboardType]) {
419         WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
420                                                               URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
421                                                          MIMEType:@"image/tiff" 
422                                                  textEncodingName:nil
423                                                         frameName:nil];
424         DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
425         [resource release];
426         return fragment;
427     }
428     
429     if ([types containsObject:NSPICTPboardType]) {
430         WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
431                                                               URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
432                                                          MIMEType:@"image/pict" 
433                                                  textEncodingName:nil
434                                                         frameName:nil];
435         DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
436         [resource release];
437         return fragment;
438     }    
439     
440     if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
441         DOMDocument* document = [[self _bridge] DOMDocument];
442         ASSERT(document);
443         if (document) {
444             DOMHTMLAnchorElement* anchor = (DOMHTMLAnchorElement*)[document createElement:@"a"];
445             NSString *URLString = [URL _web_userVisibleString];
446             NSString *URLTitleString = [pasteboard stringForType:WebURLNamePboardType];
447             DOMText* text = [document createTextNode:URLTitleString];
448             [anchor setHref:URLString];
449             [anchor appendChild:text];
450             DOMDocumentFragment* fragment = [document createDocumentFragment];
451             [fragment appendChild:anchor];
452             if ([URLString length] > 0)
453                 return fragment;
454         }
455     }
456     
457     if (allowPlainText && [types containsObject:NSStringPboardType]) {
458         *chosePlainText = YES;
459         return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
460     }
461     
462     return nil;
463 }
464
465 - (NSString *)_plainTextFromPasteboard:(NSPasteboard *)pasteboard
466 {
467     NSArray *types = [pasteboard types];
468     
469     if ([types containsObject:NSStringPboardType])
470         return [pasteboard stringForType:NSStringPboardType];
471     
472     NSAttributedString *attributedString = nil;
473     NSString *string;
474
475     if ([types containsObject:NSRTFDPboardType])
476         attributedString = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
477     if (attributedString == nil && [types containsObject:NSRTFPboardType])
478         attributedString = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
479     if (attributedString != nil) {
480         string = [[attributedString string] copy];
481         [attributedString release];
482         return [string autorelease];
483     }
484     
485     if ([types containsObject:NSFilenamesPboardType]) {
486         string = [[pasteboard propertyListForType:NSFilenamesPboardType] componentsJoinedByString:@"\n"];
487         if (string != nil)
488             return string;
489     }
490     
491     NSURL *URL;
492     
493     if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
494         string = [URL _web_userVisibleString];
495         if ([string length] > 0)
496             return string;
497     }
498     
499     return nil;
500 }
501
502 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
503 {
504     BOOL chosePlainText;
505     DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText chosePlainText:&chosePlainText];
506     WebFrameBridge *bridge = [self _bridge];
507     if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
508         [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
509     }
510 }
511
512 - (void)_pasteAsPlainTextWithPasteboard:(NSPasteboard *)pasteboard
513 {
514     NSString *text = [self _plainTextFromPasteboard:pasteboard];
515     if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted])
516         [[self _bridge] replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
517 }
518
519 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
520 {
521     WebView *webView = [self _webView];
522     DOMNode *child = [fragment firstChild];
523     if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]])
524         return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
525     return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
526 }
527
528 - (BOOL)_shouldInsertText:(NSString *)text replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
529 {
530     WebView *webView = [self _webView];
531     return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:range givenAction:action];
532 }
533
534 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
535 {
536     return [self _shouldInsertText:text replacingDOMRange:[self _selectedRange] givenAction:action];
537 }
538
539 // Calculate the vertical size of the view that fits on a single page
540 - (float)_calculatePrintHeight
541 {
542     // Obtain the print info object for the current operation
543     NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
544     
545     // Calculate the page height in points
546     NSSize paperSize = [pi paperSize];
547     return paperSize.height - [pi topMargin] - [pi bottomMargin];
548 }
549
550 - (void)_updateTextSizeMultiplier
551 {
552     [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];    
553 }
554
555 - (DOMRange *)_selectedRange
556 {
557     return [[self _bridge] selectedDOMRange];
558 }
559
560 - (BOOL)_shouldDeleteRange:(DOMRange *)range
561 {
562     if (range == nil || [range collapsed])
563         return NO;
564     
565     if (![[self _bridge] canDeleteRange:range])
566         return NO;
567         
568     WebView *webView = [self _webView];
569     return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
570 }
571
572 - (void)_deleteRange:(DOMRange *)range 
573             killRing:(BOOL)killRing 
574              prepend:(BOOL)prepend 
575        smartDeleteOK:(BOOL)smartDeleteOK 
576       deletionAction:(WebDeletionAction)deletionAction
577          granularity:(WebBridgeSelectionGranularity)granularity
578 {
579     WebFrameBridge *bridge = [self _bridge];
580     BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
581
582     BOOL startNewKillRingSequence = _private->startNewKillRingSequence;
583
584     if (killRing) {
585         if (startNewKillRingSequence) {
586             _NSNewKillRingSequence();
587         }
588         NSString *string = [bridge stringForRange:range];
589         if (prepend) {
590             _NSPrependToKillRing(string);
591         } else {
592             _NSAppendToKillRing(string);
593         }
594         startNewKillRingSequence = NO;
595     }
596
597     switch (deletionAction) {
598         case deleteSelectionAction:
599             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:YES];
600             [bridge deleteSelectionWithSmartDelete:smartDelete];
601             break;
602         case deleteKeyAction:
603             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:(granularity != WebBridgeSelectByCharacter)];
604             [bridge deleteKeyPressedWithSmartDelete:smartDelete granularity:granularity];
605             break;
606         case forwardDeleteKeyAction:
607             [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:(granularity != WebBridgeSelectByCharacter)];
608             [bridge forwardDeleteKeyPressedWithSmartDelete:smartDelete granularity:granularity];
609             break;
610     }
611
612     _private->startNewKillRingSequence = startNewKillRingSequence;
613 }
614
615 - (void)_deleteSelection
616 {
617     [self _deleteRange:[self _selectedRange]
618               killRing:YES 
619                prepend:NO
620          smartDeleteOK:YES
621         deletionAction:deleteSelectionAction
622            granularity:WebBridgeSelectByCharacter];
623 }
624
625 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
626 {
627     return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
628 }
629
630 - (NSView *)_hitViewForEvent:(NSEvent *)event
631 {
632     // Usually, we hack AK's hitTest method to catch all events at the topmost WebHTMLView.  
633     // Callers of this method, however, want to query the deepest view instead.
634     forceNSViewHitTest = YES;
635     NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
636     forceNSViewHitTest = NO;    
637     return hitView;
638 }
639
640 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString
641 {
642     // Put HTML on the pasteboard.
643     if ([types containsObject:WebArchivePboardType]) {
644         WebArchive *archive = [WebArchiver archiveSelectionInFrame:[self _frame]];
645         [pasteboard setData:[archive data] forType:WebArchivePboardType];
646     }
647     
648     // Put the attributed string on the pasteboard (RTF/RTFD format).
649     if ([types containsObject:NSRTFDPboardType]) {
650         if (attributedString == nil) {
651             attributedString = [self selectedAttributedString];
652         }        
653         NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
654         [pasteboard setData:RTFDData forType:NSRTFDPboardType];
655     }        
656     if ([types containsObject:NSRTFPboardType]) {
657         if (attributedString == nil) {
658             attributedString = [self selectedAttributedString];
659         }
660         if ([attributedString containsAttachments]) {
661             attributedString = [attributedString _web_attributedStringByStrippingAttachmentCharacters];
662         }
663         NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
664         [pasteboard setData:RTFData forType:NSRTFPboardType];
665     }
666     
667     // Put plain string on the pasteboard.
668     if ([types containsObject:NSStringPboardType]) {
669         // Map &nbsp; to a plain old space because this is better for source code, other browsers do it,
670         // and because HTML forces you to do this any time you want two spaces in a row.
671         NSMutableString *s = [[self selectedString] mutableCopy];
672         const unichar NonBreakingSpaceCharacter = 0xA0;
673         NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
674         [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
675         [pasteboard setString:s forType:NSStringPboardType];
676         [s release];
677     }
678     
679     if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
680         [pasteboard setData:nil forType:WebSmartPastePboardType];
681     }
682 }
683
684 @end
685
686 @implementation WebHTMLView (WebPrivate)
687
688 + (NSArray *)supportedMIMETypes
689 {
690     return [WebHTMLRepresentation supportedMIMETypes];
691 }
692
693 + (NSArray *)supportedImageMIMETypes
694 {
695     return [WebHTMLRepresentation supportedImageMIMETypes];
696 }
697
698 + (NSArray *)supportedNonImageMIMETypes
699 {
700     return [WebHTMLRepresentation supportedNonImageMIMETypes];
701 }
702
703 + (NSArray *)unsupportedTextMIMETypes
704 {
705     return [NSArray arrayWithObjects:
706         @"text/calendar",       // iCal
707         @"text/x-calendar",
708         @"text/x-vcalendar",
709         @"text/vcalendar",
710         @"text/vcard",          // vCard
711         @"text/x-vcard",
712         @"text/directory",
713         @"text/ldif",           // Netscape Address Book
714         @"text/qif",            // Quicken
715         @"text/x-qif",
716         @"text/x-csv",          // CSV (for Address Book and Microsoft Outlook)
717         @"text/x-vcf",          // vCard type used in Sun affinity app
718         @"text/rtf",            // Rich Text Format
719         nil];
720 }
721
722 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
723 {
724     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
725         location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
726         modifierFlags:[flagsChangedEvent modifierFlags]
727         timestamp:[flagsChangedEvent timestamp]
728         windowNumber:[flagsChangedEvent windowNumber]
729         context:[flagsChangedEvent context]
730         eventNumber:0 clickCount:0 pressure:0];
731
732     // Pretend it's a mouse move.
733     [[NSNotificationCenter defaultCenter]
734         postNotificationName:WKMouseMovedNotification() object:self
735         userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
736 }
737
738 - (void)_updateMouseoverWithFakeEvent
739 {
740     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
741         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
742         modifierFlags:[[NSApp currentEvent] modifierFlags]
743         timestamp:[NSDate timeIntervalSinceReferenceDate]
744         windowNumber:[[self window] windowNumber]
745         context:[[NSApp currentEvent] context]
746         eventNumber:0 clickCount:0 pressure:0];
747     
748     [self _updateMouseoverWithEvent:fakeEvent];
749 }
750
751 - (void)_frameOrBoundsChanged
752 {
753     if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
754         [self setNeedsLayout:YES];
755         [self setNeedsDisplay:YES];
756         [_private->compController endRevertingChange:NO moveLeft:NO];
757     }
758
759     NSPoint origin = [[self superview] bounds].origin;
760     if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
761         [[self _bridge] sendScrollEvent];
762         [_private->compController endRevertingChange:NO moveLeft:NO];
763         
764         WebView *webView = [self _webView];
765         [[webView _UIDelegateForwarder] webView:webView didScrollDocumentInFrameView:[self _frameView]];
766     }
767     _private->lastScrollPosition = origin;
768
769     SEL selector = @selector(_updateMouseoverWithFakeEvent);
770     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
771     [self performSelector:selector withObject:nil afterDelay:0];
772 }
773
774 - (void)_setAsideSubviews
775 {
776     ASSERT(!_private->subviewsSetAside);
777     ASSERT(_private->savedSubviews == nil);
778     _private->savedSubviews = _subviews;
779     _subviews = nil;
780     _private->subviewsSetAside = YES;
781  }
782  
783  - (void)_restoreSubviews
784  {
785     ASSERT(_private->subviewsSetAside);
786     ASSERT(_subviews == nil);
787     _subviews = _private->savedSubviews;
788     _private->savedSubviews = nil;
789     _private->subviewsSetAside = NO;
790 }
791
792 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
793 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
794 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
795 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
796 // need to be redrawn (in case the layout causes some things to get dirtied).
797 - (void)_propagateDirtyRectsToOpaqueAncestors
798 {
799     if (![[self _webView] drawsBackground]) {
800         [self _web_layoutIfNeededRecursive];
801     }
802     [super _propagateDirtyRectsToOpaqueAncestors];
803 }
804
805 // Don't let AppKit even draw subviews. We take care of that.
806 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
807 {
808     // This helps when we print as part of a larger print process.
809     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
810     BOOL wasInPrintingMode = _private->printing;
811     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
812     if (wasInPrintingMode != isPrinting) {
813         if (isPrinting) {
814             [self _web_setPrintingModeRecursive];
815         } else {
816             [self _web_clearPrintingModeRecursive];
817         }
818     }
819
820     [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
821     [_subviews makeObjectsPerformSelector:@selector(_propagateDirtyRectsToOpaqueAncestors)];
822
823     [self _setAsideSubviews];
824     [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
825         rectIsVisibleRectForView:visibleView topView:topView];
826     [self _restoreSubviews];
827
828     if (wasInPrintingMode != isPrinting) {
829         if (wasInPrintingMode) {
830             [self _web_setPrintingModeRecursive];
831         } else {
832             [self _web_clearPrintingModeRecursive];
833         }
834     }
835 }
836
837 // Don't let AppKit even draw subviews. We take care of that.
838 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
839 {
840     BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
841
842     BOOL wasInPrintingMode = _private->printing;
843     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
844
845     if (needToSetAsideSubviews) {
846         // This helps when we print as part of a larger print process.
847         // If the WebHTMLView itself is what we're printing, then we will never have to do this.
848         if (wasInPrintingMode != isPrinting) {
849             if (isPrinting) {
850                 [self _web_setPrintingModeRecursive];
851             } else {
852                 [self _web_clearPrintingModeRecursive];
853             }
854         }
855
856         NSRect boundsBeforeLayout = [self bounds];
857         [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
858
859         // If layout changes the view's bounds, then we need to recompute the visRect.
860         // That's because the visRect passed to us was based on the bounds at the time
861         // we were called. This method is only displayed to draw "all", so it's safe
862         // to just call visibleRect to compute the entire rectangle.
863         if (!NSEqualRects(boundsBeforeLayout, [self bounds])) {
864             visRect = [self visibleRect];
865         }
866
867         [self _setAsideSubviews];
868     }
869     
870     [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
871     
872     if (needToSetAsideSubviews) {
873         if (wasInPrintingMode != isPrinting) {
874             if (wasInPrintingMode) {
875                 [self _web_setPrintingModeRecursive];
876             } else {
877                 [self _web_clearPrintingModeRecursive];
878             }
879         }
880
881         [self _restoreSubviews];
882     }
883 }
884
885 - (WebHTMLView *)_topHTMLView
886 {
887     WebHTMLView *view = (WebHTMLView *)[[[[_private->dataSource _webView] mainFrame] frameView] documentView];
888     ASSERT([view isKindOfClass:[WebHTMLView class]]);
889     return view;
890 }
891
892 - (BOOL)_isTopHTMLView
893 {
894     return self == [self _topHTMLView];
895 }
896
897 - (BOOL)_insideAnotherHTMLView
898 {
899     return self != [self _topHTMLView];
900 }
901
902 - (void)scrollPoint:(NSPoint)point
903 {
904     // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
905     // If we get called during the handling of a key down event, we assume the call came from
906     // NSTextView, and ignore it and use our own code to decide how to page up and page down
907     // We are smarter about how far to scroll, and we have "superview scrolling" logic.
908     NSEvent *event = [[self window] currentEvent];
909     if ([event type] == NSKeyDown) {
910         const unichar pageUp = NSPageUpFunctionKey;
911         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
912             [self tryToPerform:@selector(scrollPageUp:) with:nil];
913             return;
914         }
915         const unichar pageDown = NSPageDownFunctionKey;
916         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
917             [self tryToPerform:@selector(scrollPageDown:) with:nil];
918             return;
919         }
920     }
921     
922     [super scrollPoint:point];
923 }
924
925 - (NSView *)hitTest:(NSPoint)point
926 {
927     // WebHTMLView objects handle all events for objects inside them.
928     // To get those events, we prevent hit testing from AppKit.
929
930     // But there are three exceptions to this:
931     //   1) For right mouse clicks and control clicks we don't yet have an implementation
932     //      that works for nested views, so we let the hit testing go through the
933     //      standard NSView code path (needs to be fixed, see bug 4361618).
934     //   2) Java depends on doing a hit test inside it's mouse moved handling,
935     //      so we let the hit testing go through the standard NSView code path
936     //      when the current event is a mouse move (except when we are calling
937     //      from _updateMouseoverWithEvent, so we have to use a global,
938     //      forceWebHTMLViewHitTest, for that)
939     //   3) The acceptsFirstMouse: and shouldDelayWindowOrderingForEvent: methods
940     //      both need to figure out which view to check with inside the WebHTMLView.
941     //      They use a global to change the behavior of hitTest: so they can get the
942     //      right view. The global is forceNSViewHitTest and the method they use to
943     //      do the hit testing is _hitViewForEvent:. (But this does not work correctly
944     //      when there is HTML overlapping the view, see bug 4361626)
945     //   4) NSAccessibilityHitTest relies on this for checking the cursor position.
946     //      Our check for that is whether the event is NSFlagsChanged.  This works
947     //      for VoiceOver's cntl-opt-f5 command (move focus to item under cursor)
948     //      and Dictionary's cmd-cntl-D (open dictionary popup for item under cursor).
949     //      This is of course a hack.
950
951     BOOL captureHitsOnSubviews;
952     if (forceNSViewHitTest)
953         captureHitsOnSubviews = NO;
954     else if (forceWebHTMLViewHitTest)
955         captureHitsOnSubviews = YES;
956     else {
957         NSEvent *event = [[self window] currentEvent];
958         captureHitsOnSubviews = !([event type] == NSMouseMoved
959             || [event type] == NSRightMouseDown
960             || ([event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) != 0)
961             || [event type] == NSFlagsChanged);
962     }
963
964     if (!captureHitsOnSubviews)
965         return [super hitTest:point];
966     if ([[self superview] mouse:point inRect:[self frame]])
967         return self;
968     return nil;
969 }
970
971 static WebHTMLView *lastHitView = nil;
972
973 - (void)_clearLastHitViewIfSelf
974 {
975     if (lastHitView == self) {
976         lastHitView = nil;
977     }
978 }
979
980 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
981 {
982     ASSERT(_private->trackingRectOwner == nil);
983     _private->trackingRectOwner = owner;
984     _private->trackingRectUserData = data;
985     return TRACKING_RECT_TAG;
986 }
987
988 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
989 {
990     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
991     ASSERT(_private->trackingRectOwner == nil);
992     _private->trackingRectOwner = owner;
993     _private->trackingRectUserData = data;
994     return TRACKING_RECT_TAG;
995 }
996
997 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
998 {
999     ASSERT(count == 1);
1000     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
1001     ASSERT(_private->trackingRectOwner == nil);
1002     _private->trackingRectOwner = owner;
1003     _private->trackingRectUserData = userDataList[0];
1004     trackingNums[0] = TRACKING_RECT_TAG;
1005 }
1006
1007 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1008 {
1009     if (tag == 0)
1010         return;
1011     
1012     if (_private && (tag == TRACKING_RECT_TAG)) {
1013         _private->trackingRectOwner = nil;
1014         return;
1015     }
1016     
1017     if (_private && (tag == _private->lastToolTipTag)) {
1018         [super removeTrackingRect:tag];
1019         _private->lastToolTipTag = 0;
1020         return;
1021     }
1022     
1023     // If any other tracking rect is being removed, we don't know how it was created
1024     // and it's possible there's a leak involved (see 3500217)
1025     ASSERT_NOT_REACHED();
1026 }
1027
1028 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1029 {
1030     int i;
1031     for (i = 0; i < count; ++i) {
1032         int tag = tags[i];
1033         if (tag == 0)
1034             continue;
1035         ASSERT(tag == TRACKING_RECT_TAG);
1036         if (_private != nil) {
1037             _private->trackingRectOwner = nil;
1038         }
1039     }
1040 }
1041
1042 - (void)_sendToolTipMouseExited
1043 {
1044     // Nothing matters except window, trackingNumber, and userData.
1045     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
1046         location:NSMakePoint(0, 0)
1047         modifierFlags:0
1048         timestamp:0
1049         windowNumber:[[self window] windowNumber]
1050         context:NULL
1051         eventNumber:0
1052         trackingNumber:TRACKING_RECT_TAG
1053         userData:_private->trackingRectUserData];
1054     [_private->trackingRectOwner mouseExited:fakeEvent];
1055 }
1056
1057 - (void)_sendToolTipMouseEntered
1058 {
1059     // Nothing matters except window, trackingNumber, and userData.
1060     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
1061         location:NSMakePoint(0, 0)
1062         modifierFlags:0
1063         timestamp:0
1064         windowNumber:[[self window] windowNumber]
1065         context:NULL
1066         eventNumber:0
1067         trackingNumber:TRACKING_RECT_TAG
1068         userData:_private->trackingRectUserData];
1069     [_private->trackingRectOwner mouseEntered:fakeEvent];
1070 }
1071
1072 - (void)_setToolTip:(NSString *)string
1073 {
1074     NSString *toolTip = [string length] == 0 ? nil : string;
1075     NSString *oldToolTip = _private->toolTip;
1076     if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
1077         return;
1078     }
1079     if (oldToolTip) {
1080         [self _sendToolTipMouseExited];
1081         [oldToolTip release];
1082     }
1083     _private->toolTip = [toolTip copy];
1084     if (toolTip) {
1085         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
1086         [self removeAllToolTips];
1087         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
1088         _private->lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
1089         [self _sendToolTipMouseEntered];
1090     }
1091 }
1092
1093 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1094 {
1095     return [[_private->toolTip copy] autorelease];
1096 }
1097
1098 - (void)_updateMouseoverWithEvent:(NSEvent *)event
1099 {
1100     NSView *contentView = [[event window] contentView];
1101     NSPoint locationForHitTest = [[contentView superview] convertPoint:[event locationInWindow] fromView:nil];
1102     
1103     forceWebHTMLViewHitTest = YES;
1104     NSView *hitView = [contentView hitTest:locationForHitTest];
1105     forceWebHTMLViewHitTest = NO;
1106     
1107     WebHTMLView *view = nil;
1108     if ([hitView isKindOfClass:[WebHTMLView class]]) 
1109         view = (WebHTMLView *)hitView; 
1110
1111     if (view)
1112         [view retain];
1113
1114     if (lastHitView != view && lastHitView != nil) {
1115         // If we are moving out of a view (or frame), let's pretend the mouse moved
1116         // all the way out of that view. But we have to account for scrolling, because
1117         // khtml doesn't understand our clipping.
1118         NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
1119         float yScroll = visibleRect.origin.y;
1120         float xScroll = visibleRect.origin.x;
1121
1122         event = [NSEvent mouseEventWithType:NSMouseMoved
1123                          location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1124                          modifierFlags:[[NSApp currentEvent] modifierFlags]
1125                          timestamp:[NSDate timeIntervalSinceReferenceDate]
1126                          windowNumber:[[view window] windowNumber]
1127                          context:[[NSApp currentEvent] context]
1128                          eventNumber:0 clickCount:0 pressure:0];
1129         [[lastHitView _bridge] mouseMoved:event];
1130     }
1131
1132     lastHitView = view;
1133
1134     if (view) {
1135         [[view _bridge] mouseMoved:event];
1136
1137         NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1138         NSDictionary *element = [view elementAtPoint:point];
1139
1140         // Have the web view send a message to the delegate so it can do status bar display.
1141         [[view _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1142
1143         // Set a tool tip; it won't show up right away but will if the user pauses.
1144         NSString *newToolTip = nil;
1145         if (_private->showsURLsInToolTips) {
1146             DOMHTMLElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1147             if ([domElement isKindOfClass:[DOMHTMLInputElement class]]) {
1148                 if ([[(DOMHTMLInputElement *)domElement type] isEqualToString:@"submit"])
1149                     newToolTip = [[(DOMHTMLInputElement *) domElement form] action];
1150             }
1151             if (newToolTip == nil)
1152                 newToolTip = [[element objectForKey:WebElementLinkURLKey] _web_userVisibleString];
1153         }
1154         if (newToolTip == nil)
1155             newToolTip = [element objectForKey:WebElementTitleKey];
1156         [view _setToolTip:newToolTip];
1157
1158         [view release];
1159     }
1160 }
1161
1162 + (NSArray *)_insertablePasteboardTypes
1163 {
1164     static NSArray *types = nil;
1165     if (!types) {
1166         types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1167             NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType, 
1168             NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1169     }
1170     return types;
1171 }
1172
1173 + (NSArray *)_selectionPasteboardTypes
1174 {
1175     // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1176     return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1177 }
1178
1179 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1180 {
1181     NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1182
1183     BOOL drawURLString = YES;
1184     BOOL clipURLString = NO, clipLabelString = NO;
1185     
1186     NSString *label = [element objectForKey: WebElementLinkLabelKey];
1187     NSString *urlString = [linkURL _web_userVisibleString];
1188     
1189     if (!label) {
1190         drawURLString = NO;
1191         label = urlString;
1192     }
1193     
1194     NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1195                                                    toHaveTrait:NSBoldFontMask];
1196     NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1197     NSSize labelSize;
1198     labelSize.width = [label _web_widthWithFont: labelFont];
1199     labelSize.height = [labelFont ascender] - [labelFont descender];
1200     if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1201         labelSize.width = MAX_DRAG_LABEL_WIDTH;
1202         clipLabelString = YES;
1203     }
1204     
1205     NSSize imageSize, urlStringSize;
1206     imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
1207     imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
1208     if (drawURLString) {
1209         urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1210         urlStringSize.height = [urlFont ascender] - [urlFont descender];
1211         imageSize.height += urlStringSize.height;
1212         if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1213             imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1214             clipURLString = YES;
1215         } else {
1216             imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
1217         }
1218     }
1219     NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1220     [dragImage lockFocus];
1221     
1222     [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
1223     
1224     // Drag a rectangle with rounded corners/
1225     NSBezierPath *path = [NSBezierPath bezierPath];
1226     [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1227     [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1228     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1229     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1230     
1231     [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
1232     [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1233     [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1234     [path fill];
1235         
1236     NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
1237     NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
1238     if (drawURLString) {
1239         if (clipURLString)
1240             urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
1241
1242         [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
1243              withTopColor:topColor bottomColor:bottomColor font:urlFont];
1244     }
1245
1246     if (clipLabelString)
1247         label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
1248     [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1249              withTopColor:topColor bottomColor:bottomColor font:labelFont];
1250     
1251     [dragImage unlockFocus];
1252     
1253     return dragImage;
1254 }
1255
1256 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1257 {
1258     WebHTMLView *topHTMLView = [self _topHTMLView];
1259     if (self != topHTMLView)
1260         return [topHTMLView _startDraggingImage:wcDragImage at:wcDragLoc operation:op event:mouseDraggedEvent sourceIsDHTML:srcIsDHTML DHTMLWroteData:dhtmlWroteData];
1261
1262     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1263     NSDictionary *element = [self elementAtPoint:mouseDownPoint allowShadowContent:YES];
1264
1265     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1266     NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1267     BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1268
1269     [_private->draggingImageURL release];
1270     _private->draggingImageURL = nil;
1271
1272     NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1273     _private->webCoreDragOp = op;     // will be DragNone if WebCore doesn't care
1274     NSImage *dragImage = nil;
1275     NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1276
1277     // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1278     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1279     // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1280     if (wcDragImage) {
1281         dragImage = wcDragImage;
1282         // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1283         // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1284         if (linkURL)
1285             // see HACK below
1286             dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1287         else
1288             dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1289         _private->dragOffset = wcDragLoc;
1290     }
1291     
1292     WebView *webView = [self _webView];
1293     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1294     BOOL startedDrag = YES;  // optimism - we almost always manage to start the drag
1295
1296     // note per kwebster, the offset arg below is always ignored in positioning the image
1297     DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
1298     WebHTMLView *innerHTMLView = (WebHTMLView *)[[[[node ownerDocument] webFrame] frameView] documentView];
1299     ASSERT([innerHTMLView isKindOfClass:[WebHTMLView class]]);
1300     if (imageURL != nil
1301             && [node isKindOfClass:[DOMElement class]]
1302             && [(DOMElement *)node image]
1303             && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1304         id source = self;
1305         if (!dhtmlWroteData) {
1306             // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1307             ASSERT(node != nil);
1308             [webView setSelectedDOMRange:[[node ownerDocument] _createRangeWithNode:node] affinity:NSSelectionAffinityDownstream];
1309             _private->draggingImageURL = [imageURL retain];
1310             
1311             WebArchive *archive;
1312             
1313             // If the image element comes from an ImageDocument, we don't want to 
1314             // create a web archive from the image element.
1315             if ([[self _bridge] canSaveAsWebArchive])
1316                 archive = [node webArchive];
1317             else
1318                 archive = [WebArchiver archiveMainResourceForFrame:[self _frame]];
1319             
1320             source = [pasteboard _web_declareAndWriteDragImageForElement:(DOMElement *)node
1321                                                                      URL:linkURL ? linkURL : imageURL
1322                                                                    title:[element objectForKey:WebElementImageAltStringKey]
1323                                                                  archive:archive
1324                                                                   source:self];
1325         }
1326         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1327         if (dragImage == nil)
1328             [self _web_DragImageForElement:(DOMElement *)node
1329                                       rect:[self convertRect:[[element objectForKey:WebElementImageRectKey] rectValue] fromView:innerHTMLView]
1330                                      event:_private->mouseDownEvent
1331                                 pasteboard:pasteboard
1332                                     source:source
1333                                     offset:&_private->dragOffset];
1334         else
1335             [self dragImage:dragImage
1336                          at:dragLoc
1337                      offset:NSZeroSize
1338                       event:_private->mouseDownEvent
1339                  pasteboard:pasteboard
1340                      source:source
1341                   slideBack:YES];
1342     } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1343         if (!dhtmlWroteData) {
1344             NSArray *types = [NSPasteboard _web_writableTypesForURL];
1345             [pasteboard declareTypes:types owner:self];
1346             [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];            
1347         }
1348         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1349         if (dragImage == nil) {
1350             dragImage = [self _dragImageForLinkElement:element];
1351             NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1352             dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1353             _private->dragOffset.x = offset.width;
1354             _private->dragOffset.y = -offset.height;        // inverted because we are flipped
1355         }
1356         // HACK:  We should pass the mouseDown event instead of the mouseDragged!  This hack gets rid of
1357         // a flash of the image at the mouseDown location when the drag starts.
1358         [self dragImage:dragImage
1359                      at:dragLoc
1360                  offset:NSZeroSize
1361                   event:mouseDraggedEvent
1362              pasteboard:pasteboard
1363                  source:self
1364               slideBack:YES];
1365     } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1366         if (!dhtmlWroteData)
1367             [innerHTMLView _writeSelectionToPasteboard:pasteboard];
1368         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1369         if (dragImage == nil) {
1370             dragImage = [innerHTMLView _selectionDraggingImage];
1371             NSRect draggingRect = [self convertRect:[innerHTMLView _selectionDraggingRect] fromView:innerHTMLView];
1372             dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1373             _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1374             _private->dragOffset.y = dragLoc.y - mouseDownPoint.y;        // inverted because we are flipped
1375         }
1376         [self dragImage:dragImage
1377                      at:dragLoc
1378                  offset:NSZeroSize
1379                   event:_private->mouseDownEvent
1380              pasteboard:pasteboard
1381                  source:self
1382               slideBack:YES];
1383     } else if (srcIsDHTML) {
1384         ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1385         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1386         if (dragImage == nil) {
1387             // WebCore should have given us an image, but we'll make one up
1388             // FIXME: Oops! I removed this image from WebKit. Is this a dead code path?
1389             NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1390             dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1391             NSSize imageSize = [dragImage size];
1392             dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width / 2, mouseDownPoint.y + imageSize.height / 2);
1393             _private->dragOffset.x = imageSize.width / 2;
1394             _private->dragOffset.y = imageSize.height / 2;
1395         }
1396         [self dragImage:dragImage
1397                      at:dragLoc
1398                  offset:NSZeroSize
1399                   event:_private->mouseDownEvent
1400              pasteboard:pasteboard
1401                  source:self
1402               slideBack:YES];
1403     } else {
1404         // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1405         // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1406         startedDrag = NO;
1407     }
1408     return startedDrag;
1409 }
1410
1411 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1412 {
1413     [self autoscroll:event];
1414     [self _startAutoscrollTimer:event];
1415 }
1416
1417 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1418 {
1419     WebHTMLView *topHTMLView = [self _topHTMLView];
1420     if (self != topHTMLView)
1421         return [topHTMLView _mayStartDragAtEventLocation:location];
1422
1423     NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1424     NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint allowShadowContent:YES];
1425
1426     ASSERT([self _webView]);
1427
1428     if ([mouseDownElement objectForKey:WebElementImageKey]
1429             && [mouseDownElement objectForKey:WebElementImageURLKey]
1430             && [[[self _webView] preferences] loadsImagesAutomatically]
1431             && (_private->dragSourceActionMask & WebDragSourceActionImage))
1432         return YES;
1433     
1434     if ([mouseDownElement objectForKey:WebElementLinkURLKey]
1435             && (_private->dragSourceActionMask & WebDragSourceActionLink))
1436         return YES;
1437     
1438     if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue]
1439             && (_private->dragSourceActionMask & WebDragSourceActionSelection))
1440         return YES;
1441     
1442     return NO;
1443 }
1444
1445 - (WebPluginController *)_pluginController
1446 {
1447     return _private->pluginController;
1448 }
1449
1450 - (void)_web_setPrintingModeRecursive
1451 {
1452     [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1453     [super _web_setPrintingModeRecursive];
1454 }
1455
1456 - (void)_web_clearPrintingModeRecursive
1457 {
1458     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1459     [super _web_clearPrintingModeRecursive];
1460 }
1461
1462 - (void)_layoutIfNeeded
1463 {
1464     ASSERT(!_private->subviewsSetAside);
1465
1466     if ([[self _bridge] needsLayout])
1467         _private->needsLayout = YES;
1468     if (_private->needsToApplyStyles || _private->needsLayout)
1469         [self layout];
1470 }
1471
1472 - (void)_web_layoutIfNeededRecursive
1473 {
1474     [self _layoutIfNeeded];
1475     [super _web_layoutIfNeededRecursive];
1476 }
1477
1478 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1479 {
1480     ASSERT(!_private->subviewsSetAside);
1481     displayRect = NSIntersectionRect(displayRect, [self bounds]);
1482
1483     if (!testDirtyRect || [self needsDisplay]) {
1484         if (testDirtyRect) {
1485             NSRect dirtyRect = [self _dirtyRect];
1486             displayRect = NSIntersectionRect(displayRect, dirtyRect);
1487         }
1488         if (!NSIsEmptyRect(displayRect)) {
1489             [self _layoutIfNeeded];
1490         }
1491     }
1492
1493     [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1494 }
1495
1496 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1497 {
1498     if (_private->autoscrollTimer == nil) {
1499         _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1500             target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1501         _private->autoscrollTriggerEvent = [triggerEvent retain];
1502     }
1503 }
1504
1505 // FIXME: _selectionRect is deprecated in favor of selectionRect, which is in protocol WebDocumentSelection.
1506 // We can't remove this yet because it's still in use by Mail.
1507 - (NSRect)_selectionRect
1508 {
1509     return [self selectionRect];
1510 }
1511
1512 - (void)_stopAutoscrollTimer
1513 {
1514     NSTimer *timer = _private->autoscrollTimer;
1515     _private->autoscrollTimer = nil;
1516     [_private->autoscrollTriggerEvent release];
1517     _private->autoscrollTriggerEvent = nil;
1518     [timer invalidate];
1519     [timer release];
1520 }
1521
1522 - (void)_autoscroll
1523 {
1524     // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1525     // a mouse up event.
1526     BOOL isStillDown = CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft);   
1527     if (!isStillDown){
1528         [self _stopAutoscrollTimer];
1529         return;
1530     }
1531
1532     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1533         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1534         modifierFlags:[[NSApp currentEvent] modifierFlags]
1535         timestamp:[NSDate timeIntervalSinceReferenceDate]
1536         windowNumber:[[self window] windowNumber]
1537         context:[[NSApp currentEvent] context]
1538         eventNumber:0 clickCount:0 pressure:0];
1539     [self mouseDragged:fakeEvent];
1540 }
1541
1542 - (BOOL)_canCopy
1543 {
1544     // Copying can be done regardless of whether you can edit.
1545     return [self _hasSelection];
1546 }
1547
1548 - (BOOL)_canCut
1549 {
1550     return [self _hasSelection] && [self _isEditable];
1551 }
1552
1553 - (BOOL)_canDelete
1554 {
1555     return [self _hasSelection] && [self _isEditable];
1556 }
1557
1558 - (BOOL)_canPaste
1559 {
1560     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1561 }
1562
1563 - (BOOL)_canEdit
1564 {
1565     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1566 }
1567
1568 - (BOOL)_canEditRichly
1569 {
1570     return [self _canEdit] && [[self _bridge] isSelectionRichlyEditable];
1571 }
1572
1573 - (BOOL)_canAlterCurrentSelection
1574 {
1575     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1576 }
1577
1578 - (BOOL)_hasSelection
1579 {
1580     return [[self _bridge] selectionState] == WebSelectionStateRange;
1581 }
1582
1583 - (BOOL)_hasSelectionOrInsertionPoint
1584 {
1585     return [[self _bridge] selectionState] != WebSelectionStateNone;
1586 }
1587
1588 - (BOOL)_hasInsertionPoint
1589 {
1590     return [[self _bridge] selectionState] == WebSelectionStateCaret;
1591 }
1592
1593 - (BOOL)_isEditable
1594 {
1595     return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1596 }
1597
1598 - (BOOL)_isSelectionMisspelled
1599 {
1600     NSString *selectedString = [self selectedString];
1601     unsigned length = [selectedString length];
1602     if (length == 0) {
1603         return NO;
1604     }
1605     NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1606                                                                     startingAt:0
1607                                                                       language:nil
1608                                                                           wrap:NO
1609                                                         inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1610                                                                      wordCount:NULL];
1611     return range.length == length;
1612 }
1613
1614 - (NSArray *)_guessesForMisspelledSelection
1615 {
1616     ASSERT([[self selectedString] length] != 0);
1617     return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1618 }
1619
1620 - (void)_changeSpellingFromMenu:(id)sender
1621 {
1622     ASSERT([[self selectedString] length] != 0);
1623     if ([self _shouldReplaceSelectionWithText:[sender title] givenAction:WebViewInsertActionPasted]) {
1624         [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1625     }
1626 }
1627
1628 - (void)_ignoreSpellingFromMenu:(id)sender
1629 {
1630     ASSERT([[self selectedString] length] != 0);
1631     [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1632 }
1633
1634 - (void)_learnSpellingFromMenu:(id)sender
1635 {
1636     ASSERT([[self selectedString] length] != 0);
1637     [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1638 }
1639
1640 - (void)_lookUpInDictionaryFromMenu:(id)sender
1641 {
1642     // This should only be called when there's a selection, but play it safe.
1643     if (![self _hasSelection]) {
1644         return;
1645     }
1646     
1647     // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1648     static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1649     static const struct mach_header *frameworkImageHeader = NULL;
1650     static BOOL lookedForFunction = NO;
1651     if (!lookedForFunction) {
1652         __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1653         lookedForFunction = YES;
1654     }
1655     if (!__dictionaryServiceWindowShow) {
1656         LOG_ERROR("Couldn't find _DCMDictionaryServiceWindowShow"); 
1657         return;
1658     }
1659     
1660     // FIXME: must check for right-to-left here
1661     NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1662     
1663     NSAttributedString *attrString = [self selectedAttributedString];
1664     // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1665     // the rect for the entire selection, as we do here, positions the pop-up window near
1666     // the bottom of the selection rather than at the selected word.
1667     NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1668     rect.origin = [[self window] convertBaseToScreen:rect.origin];
1669     NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1670     (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1671 }
1672
1673 - (BOOL)_transparentBackground
1674 {
1675     return _private->transparentBackground;
1676 }
1677
1678 - (void)_setTransparentBackground:(BOOL)f
1679 {
1680     _private->transparentBackground = f;
1681 }
1682
1683 - (NSImage *)_selectionDraggingImage
1684 {
1685     if ([self _hasSelection]) {
1686         NSImage *dragImage = [[self _bridge] selectionImageForcingWhiteText:NO];
1687         [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1688         return dragImage;
1689     }
1690     return nil;
1691 }
1692
1693 - (NSRect)_selectionDraggingRect
1694 {
1695     // Mail currently calls this method. We can eliminate it when Mail no longer calls it.
1696     return [self selectionImageRect];
1697 }
1698
1699 - (BOOL)_canIncreaseSelectionListLevel
1700 {
1701     return ([self _canEditRichly] && [[self _bridge] canIncreaseSelectionListLevel]);
1702 }
1703
1704 - (BOOL)_canDecreaseSelectionListLevel
1705 {
1706     return ([self _canEditRichly] && [[self _bridge] canDecreaseSelectionListLevel]);
1707 }
1708
1709 - (DOMNode *)_increaseSelectionListLevel
1710 {
1711     if (![self _canEditRichly])
1712         return nil;
1713         
1714     WebFrameBridge *bridge = [self _bridge];
1715     return [bridge increaseSelectionListLevel];
1716 }
1717
1718 - (DOMNode *)_increaseSelectionListLevelOrdered
1719 {
1720     if (![self _canEditRichly])
1721         return nil;
1722         
1723     WebFrameBridge *bridge = [self _bridge];
1724     return [bridge increaseSelectionListLevelOrdered];
1725 }
1726
1727 - (DOMNode *)_increaseSelectionListLevelUnordered
1728 {
1729     if (![self _canEditRichly])
1730         return nil;
1731         
1732     WebFrameBridge *bridge = [self _bridge];
1733     return [bridge increaseSelectionListLevelUnordered];
1734 }
1735
1736 - (void)_decreaseSelectionListLevel
1737 {
1738     if (![self _canEditRichly])
1739         return;
1740         
1741     WebFrameBridge *bridge = [self _bridge];
1742     [bridge decreaseSelectionListLevel];
1743 }
1744
1745 - (void)_setHighlighter:(id<WebHTMLHighlighter>)highlighter ofType:(NSString*)type
1746 {
1747     if (!_private->highlighters)
1748         _private->highlighters = [[NSMutableDictionary alloc] init];
1749     [_private->highlighters setObject:highlighter forKey:type];
1750 }
1751
1752 - (void)_removeHighlighterOfType:(NSString*)type
1753 {
1754     [_private->highlighters removeObjectForKey:type];
1755 }
1756
1757 - (BOOL)_web_firstResponderCausesFocusDisplay
1758 {
1759     return [self _web_firstResponderIsSelfOrDescendantView] || [[self window] firstResponder] == [self _frameView];
1760 }
1761
1762 - (void)_updateActiveState
1763 {
1764     // This method does the job of updating the view based on the view's firstResponder-ness and
1765     // the window key-ness of the window containing this view. This involves four kinds of 
1766     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
1767     // 
1768     // The four display attributes are as follows:
1769     // 
1770     // 1. The background color used to draw behind selected content (active | inactive color)
1771     // 2. Caret blinking (blinks | does not blink)
1772     // 3. The drawing of a focus ring around links in web pages.
1773     // 4. Changing the tint of controls from clear to aqua/graphite and vice versa
1774     //
1775     // Also, this is responsible for letting the bridge know if the window has gained or lost focus
1776     // so we can send focus and blur events.
1777
1778     NSWindow *window = [self window];
1779     BOOL windowIsKey = [window isKeyWindow];
1780     BOOL windowOrSheetIsKey = windowIsKey || [[window attachedSheet] isKeyWindow];
1781
1782     BOOL isActive = !_private->resigningFirstResponder && windowIsKey && (_private->descendantBecomingFirstResponder || [self _web_firstResponderCausesFocusDisplay]);
1783     
1784     [[self _bridge] setWindowHasFocus:windowOrSheetIsKey];
1785     [[self _bridge] setIsActive:isActive];
1786 }
1787
1788 - (unsigned)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag
1789 {
1790     return [[self _bridge] markAllMatchesForText:string caseSensitive:caseFlag];
1791 }
1792
1793 - (void)setMarkedTextMatchesAreHighlighted:(BOOL)newValue
1794 {
1795     [[self _bridge] setMarkedTextMatchesAreHighlighted:newValue];
1796 }
1797
1798 - (BOOL)markedTextMatchesAreHighlighted
1799 {
1800     return [[self _bridge] markedTextMatchesAreHighlighted];
1801 }
1802
1803 - (void)unmarkAllTextMatches
1804 {
1805     return [[self _bridge] unmarkAllTextMatches];
1806 }
1807
1808 - (NSArray *)rectsForTextMatches
1809 {
1810     return [[self _bridge] rectsForTextMatches];
1811 }
1812
1813 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1814 {
1815     ASSERT([self _hasSelection]);
1816     NSArray *types = [self pasteboardTypesForSelection];
1817
1818     // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1819     NSAttributedString *attributedString = [self selectedAttributedString];
1820     NSMutableArray *mutableTypes = nil;
1821     if (![attributedString containsAttachments]) {
1822         mutableTypes = [types mutableCopy];
1823         [mutableTypes removeObject:NSRTFDPboardType];
1824         types = mutableTypes;
1825     }
1826
1827     [pasteboard declareTypes:types owner:nil];
1828     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1829     [mutableTypes release];
1830 }
1831
1832 - (void)close
1833 {
1834     if (_private->closed)
1835         return;
1836     [self _clearLastHitViewIfSelf];
1837     // FIXME: This is slow; should remove individual observers instead.
1838     [[NSNotificationCenter defaultCenter] removeObserver:self];
1839     [_private->pluginController destroyAllPlugins];
1840     // remove tooltips before clearing _private so removeTrackingRect: will work correctly
1841     [self removeAllToolTips];
1842     _private->closed = YES;
1843 }
1844
1845 @end
1846
1847 @implementation NSView (WebHTMLViewFileInternal)
1848
1849 - (void)_web_setPrintingModeRecursive
1850 {
1851     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1852 }
1853
1854 - (void)_web_clearPrintingModeRecursive
1855 {
1856     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1857 }
1858
1859 - (void)_web_layoutIfNeededRecursive
1860 {
1861     [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1862 }
1863
1864 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1865 {
1866     unsigned index, count;
1867     for (index = 0, count = [(NSArray *)_subviews count]; index < count; index++) {
1868         NSView *subview = [_subviews objectAtIndex:index];
1869         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1870         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1871     }
1872 }
1873
1874 @end
1875
1876 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1877
1878 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1879 {
1880     if (object == nil) {
1881         [self removeObjectForKey:key];
1882     } else {
1883         [self setObject:object forKey:key];
1884     }
1885 }
1886
1887 @end
1888
1889 // The following is a workaround for
1890 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1891 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1892 // Since the category will be searched before the real class, we'll prevent the flag from being
1893 // set on the tool tip panel.
1894
1895 @interface NSToolTipPanel : NSPanel
1896 @end
1897
1898 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1899 @end
1900
1901 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1902
1903 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1904 {
1905     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1906 }
1907
1908 @end
1909
1910 @interface NSArray (WebHTMLView)
1911 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1912 @end
1913
1914 @implementation WebHTMLView
1915
1916 + (void)initialize
1917 {
1918     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] 
1919                              returnTypes:[[self class] _insertablePasteboardTypes]];
1920     _NSInitializeKillRing();
1921 }
1922
1923 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1924 {
1925     WebPreferences *preferences = [[self _webView] preferences];
1926     // Check for nil because we might not yet have an associated webView when this is called
1927     if (preferences == nil) {
1928         preferences = [WebPreferences standardPreferences];
1929     }
1930     _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1931 }
1932
1933 - (id)initWithFrame:(NSRect)frame
1934 {
1935     self = [super initWithFrame:frame];
1936     if (!self)
1937         return nil;
1938     
1939     // Make all drawing go through us instead of subviews.
1940     if (NSAppKitVersionNumber >= 711) {
1941         [self _setDrawsOwnDescendants:YES];
1942     }
1943     
1944     _private = [[WebHTMLViewPrivate alloc] init];
1945
1946     _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1947     _private->needsLayout = YES;
1948     [self _resetCachedWebPreferences:nil];
1949     [[NSNotificationCenter defaultCenter] 
1950             addObserver:self selector:@selector(_resetCachedWebPreferences:) 
1951                    name:WebPreferencesChangedNotification object:nil];
1952     
1953     return self;
1954 }
1955
1956 - (void)dealloc
1957 {
1958     // We can't assert that close has already been called because
1959     // this view can be removed from it's superview, even though
1960     // it could be needed later, so close if needed.
1961     [self close];
1962     [_private release];
1963     _private = nil;
1964     [super dealloc];
1965 }
1966
1967 - (void)finalize
1968 {
1969     // We can't assert that close has already been called because
1970     // this view can be removed from it's superview, even though
1971     // it could be needed later, so close if needed.
1972     [self close];
1973     [super finalize];
1974 }
1975
1976 - (IBAction)takeFindStringFromSelection:(id)sender
1977 {
1978     if (![self _hasSelection]) {
1979         NSBeep();
1980         return;
1981     }
1982
1983     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1984 }
1985
1986 - (NSArray *)pasteboardTypesForSelection
1987 {
1988     if ([self _canSmartCopyOrDelete]) {
1989         NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1990         [types addObject:WebSmartPastePboardType];
1991         return types;
1992     } else {
1993         return [[self class] _selectionPasteboardTypes];
1994     }
1995 }
1996
1997 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1998 {
1999     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:nil];
2000 }
2001
2002 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2003 {
2004     [pasteboard declareTypes:types owner:nil];
2005     [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2006     return YES;
2007 }
2008
2009 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2010 {
2011     if ([[self _bridge] isSelectionRichlyEditable])
2012         [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
2013     else
2014         [self _pasteAsPlainTextWithPasteboard:pasteboard];
2015     return YES;
2016 }
2017
2018 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2019 {
2020     if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
2021         return self;
2022     } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
2023         return self;
2024     }
2025     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
2026 }
2027
2028 - (void)selectAll:(id)sender
2029 {
2030     [self selectAll];
2031 }
2032
2033 // jumpToSelection is the old name for what AppKit now calls centerSelectionInVisibleArea. Safari
2034 // was using the old jumpToSelection selector in its menu. Newer versions of Safari will us the
2035 // selector centerSelectionInVisibleArea. We'll leave this old selector in place for two reasons:
2036 // (1) compatibility between older Safari and newer WebKit; (2) other WebKit-based applications
2037 // might be using the jumpToSelection: selector, and we don't want to break them.
2038 - (void)jumpToSelection:(id)sender
2039 {
2040     [self centerSelectionInVisibleArea:sender];
2041 }
2042
2043 - (NSRect)selectionRect
2044 {
2045     return [[self _bridge] selectionRect];
2046 }
2047
2048 - (NSView *)selectionView
2049 {
2050     return self;
2051 }
2052
2053 - (NSImage *)selectionImageForcingWhiteText:(BOOL)forceWhiteText
2054 {
2055     if ([self _hasSelection])
2056         return [[self _bridge] selectionImageForcingWhiteText:forceWhiteText];
2057
2058     return nil;
2059 }
2060
2061 - (NSRect)selectionImageRect
2062 {
2063     if ([self _hasSelection])
2064         return [[self _bridge] visibleSelectionRect];
2065     return NSZeroRect;
2066 }
2067
2068 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
2069 {
2070     SEL action = [item action];
2071     WebFrameBridge *bridge = [self _bridge];
2072
2073     if (action == @selector(changeBaseWritingDirection:) // FIXME: check menu item based on writing direction
2074             || action == @selector(changeSpelling:)
2075             || action == @selector(_changeSpellingFromMenu:)
2076             || action == @selector(checkSpelling:)
2077             || action == @selector(complete:)
2078             || action == @selector(deleteBackward:)
2079             || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
2080             || action == @selector(deleteForward:)
2081             || action == @selector(deleteToBeginningOfLine:)
2082             || action == @selector(deleteToBeginningOfParagraph:)
2083             || action == @selector(deleteToEndOfLine:)
2084             || action == @selector(deleteToEndOfParagraph:)
2085             || action == @selector(deleteToMark:)
2086             || action == @selector(deleteWordBackward:)
2087             || action == @selector(deleteWordForward:)
2088             || action == @selector(insertBacktab:)
2089             || action == @selector(insertLineBreak:)
2090             || action == @selector(insertNewline:)
2091             || action == @selector(insertNewlineIgnoringFieldEditor:)
2092             || action == @selector(insertParagraphSeparator:)
2093             || action == @selector(insertTab:)
2094             || action == @selector(insertTabIgnoringFieldEditor:)
2095             || action == @selector(moveBackward:)
2096             || action == @selector(moveBackwardAndModifySelection:)
2097             || action == @selector(moveDown:)
2098             || action == @selector(moveDownAndModifySelection:)
2099             || action == @selector(moveForward:)
2100             || action == @selector(moveForwardAndModifySelection:)
2101             || action == @selector(moveLeft:)
2102             || action == @selector(moveLeftAndModifySelection:)
2103             || action == @selector(moveParagraphBackwardAndModifySelection:)
2104             || action == @selector(moveParagraphForwardAndModifySelection:)
2105             || action == @selector(moveRight:)
2106             || action == @selector(moveRightAndModifySelection:)
2107             || action == @selector(moveToBeginningOfDocument:)
2108             || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
2109             || action == @selector(moveToBeginningOfSentence:)
2110             || action == @selector(moveToBeginningOfSentenceAndModifySelection:)
2111             || action == @selector(moveToBeginningOfLine:)
2112             || action == @selector(moveToBeginningOfLineAndModifySelection:)
2113             || action == @selector(moveToBeginningOfParagraph:)
2114             || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
2115             || action == @selector(moveToEndOfDocument:)
2116             || action == @selector(moveToEndOfDocumentAndModifySelection:)
2117             || action == @selector(moveToEndOfSentence:)
2118             || action == @selector(moveToEndOfSentenceAndModifySelection:)
2119             || action == @selector(moveToEndOfLine:)
2120             || action == @selector(moveToEndOfLineAndModifySelection:)
2121             || action == @selector(moveToEndOfParagraph:)
2122             || action == @selector(moveToEndOfParagraphAndModifySelection:)
2123             || action == @selector(moveUp:)
2124             || action == @selector(moveUpAndModifySelection:)
2125             || action == @selector(moveWordBackward:)
2126             || action == @selector(moveWordBackwardAndModifySelection:)
2127             || action == @selector(moveWordForward:)
2128             || action == @selector(moveWordForwardAndModifySelection:)
2129             || action == @selector(moveWordLeft:)
2130             || action == @selector(moveWordLeftAndModifySelection:)
2131             || action == @selector(moveWordRight:)
2132             || action == @selector(moveWordRightAndModifySelection:)
2133             || action == @selector(pageDown:)
2134             || action == @selector(pageDownAndModifySelection:)
2135             || action == @selector(pageUp:)
2136             || action == @selector(pageUpAndModifySelection:)
2137             || action == @selector(pasteFont:)
2138             || action == @selector(showGuessPanel:)
2139             || action == @selector(toggleBaseWritingDirection:)
2140             || action == @selector(transpose:)
2141             || action == @selector(yank:)
2142             || action == @selector(yankAndSelect:)) {
2143         return [self _canEdit];
2144     } else if (action == @selector(alignCenter:)
2145             || action == @selector(alignLeft:)
2146             || action == @selector(alignJustified:)
2147             || action == @selector(alignRight:)
2148             || action == @selector(changeAttributes:)
2149             || action == @selector(changeColor:)        
2150             || action == @selector(changeFont:)) {
2151         return [self _canEditRichly];
2152     } else if (action == @selector(capitalizeWord:)
2153                || action == @selector(lowercaseWord:)
2154                || action == @selector(uppercaseWord:)) {
2155         return [self _hasSelection] && [self _isEditable];
2156     } else if (action == @selector(centerSelectionInVisibleArea:)
2157                || action == @selector(jumpToSelection:)
2158                || action == @selector(copyFont:)
2159                || action == @selector(setMark:)) {
2160         return [self _hasSelection] || ([self _isEditable] && [self _hasInsertionPoint]);
2161     } else if (action == @selector(changeDocumentBackgroundColor:)) {
2162         return [[self _webView] isEditable] && [self _canEditRichly];
2163     } else if (action == @selector(copy:)) {
2164         return [bridge mayDHTMLCopy] || [self _canCopy];
2165     } else if (action == @selector(cut:)) {
2166         return [bridge mayDHTMLCut] || [self _canDelete];
2167     } else if (action == @selector(delete:)) {
2168         return [self _canDelete];
2169     } else if (action == @selector(_ignoreSpellingFromMenu:)
2170             || action == @selector(_learnSpellingFromMenu:)
2171             || action == @selector(takeFindStringFromSelection:)) {
2172         return [self _hasSelection];
2173     } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:)) {
2174         return [bridge mayDHTMLPaste] || [self _canPaste];
2175     } else if (action == @selector(pasteAsRichText:)) {
2176         return [bridge mayDHTMLPaste] || ([self _canPaste] && [[self _bridge] isSelectionRichlyEditable]);
2177     } else if (action == @selector(performFindPanelAction:)) {
2178         // FIXME: Not yet implemented.
2179         return NO;
2180     } else if (action == @selector(selectToMark:)
2181             || action == @selector(swapWithMark:)) {
2182         return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
2183     } else if (action == @selector(subscript:)) {
2184         NSMenuItem *menuItem = (NSMenuItem *)item;
2185         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2186             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2187             [style setVerticalAlign:@"sub"];
2188             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2189         }
2190         return [self _canEditRichly];
2191     } else if (action == @selector(superscript:)) {
2192         NSMenuItem *menuItem = (NSMenuItem *)item;
2193         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2194             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2195             [style setVerticalAlign:@"super"];
2196             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2197         }
2198         return [self _canEditRichly];
2199     } else if (action == @selector(underline:)) {
2200         NSMenuItem *menuItem = (NSMenuItem *)item;
2201         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2202             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2203             [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
2204             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2205         }
2206         return [self _canEditRichly];
2207     } else if (action == @selector(unscript:)) {
2208         NSMenuItem *menuItem = (NSMenuItem *)item;
2209         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2210             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2211             [style setVerticalAlign:@"baseline"];
2212             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2213         }
2214         return [self _canEditRichly];
2215     } else if (action == @selector(_lookUpInDictionaryFromMenu:)) {
2216         return [self _hasSelection];
2217     }
2218     
2219     return YES;
2220 }
2221
2222 - (BOOL)acceptsFirstResponder
2223 {
2224     // Don't accept first responder when we first click on this view.
2225     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
2226     // Do accept first responder at any other time, for example from keyboard events,
2227     // or from calls back from WebCore once we begin mouse-down event handling.
2228     NSEvent *event = [NSApp currentEvent];
2229     if ([event type] == NSLeftMouseDown
2230             && !_private->handlingMouseDownEvent
2231             && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
2232         return NO;
2233     }
2234     return YES;
2235 }
2236
2237 - (BOOL)maintainsInactiveSelection
2238 {
2239     // This method helps to determine whether the WebHTMLView should maintain
2240     // an inactive selection when it's not first responder.
2241     // Traditionally, these views have not maintained such selections,
2242     // clearing them when the view was not first responder. However,
2243     // to fix bugs like this one:
2244     // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even 
2245     //                            when they're not firstResponder"
2246     // it was decided to add a switch to act more like an NSTextView.
2247     id nextResponder = [[self window] _newFirstResponderAfterResigning];
2248
2249     // Predict the case where we are losing first responder status only to
2250     // gain it back again.  Want to keep the selection in that case.
2251     if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2252         id contentView = [nextResponder contentView];
2253         if (contentView) {
2254             nextResponder = contentView;
2255         }
2256     }
2257     if ([nextResponder isKindOfClass:[NSClipView class]]) {
2258         id documentView = [nextResponder documentView];
2259         if (documentView) {
2260             nextResponder = documentView;
2261         }
2262     }
2263
2264     if (nextResponder == self)
2265         return YES;
2266
2267     return [[self _webView] maintainsInactiveSelection] || [[self _bridge] isSelectionEditable];
2268 }
2269
2270 - (void)addMouseMovedObserver
2271 {
2272     if (!_private->dataSource || ![self _isTopHTMLView])
2273         return;
2274
2275     // Unless the Dashboard asks us to do this for all windows, keep an observer going only for the key window.
2276     if (!([[self window] isKeyWindow] || [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]))
2277         return;
2278
2279     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2280         name:WKMouseMovedNotification() object:nil];
2281     [self _frameOrBoundsChanged];
2282 }
2283
2284 - (void)removeMouseMovedObserver
2285 {
2286     // Don't remove the observer if we're running the Dashboard.
2287     // FIXME: Right for the windowDidResignKey: case, but wrong for the viewWillMoveToWindow: case.
2288     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2289         return;
2290
2291     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2292     [[NSNotificationCenter defaultCenter] removeObserver:self
2293         name:WKMouseMovedNotification() object:nil];
2294 }
2295
2296 - (void)addSuperviewObservers
2297 {
2298     // We watch the bounds of our superview, so that we can do a layout when the size
2299     // of the superview changes. This is different from other scrollable things that don't
2300     // need this kind of thing because their layout doesn't change.
2301     
2302     // We need to pay attention to both height and width because our "layout" has to change
2303     // to extend the background the full height of the space and because some elements have
2304     // sizes that are based on the total size of the view.
2305     
2306     NSView *superview = [self superview];
2307     if (superview && [self window]) {
2308         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2309             name:NSViewFrameDidChangeNotification object:superview];
2310         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2311             name:NSViewBoundsDidChangeNotification object:superview];
2312
2313         // In addition to registering for frame/bounds change notifications, call -_frameOrBoundsChanged.
2314         // It will check the current size/scroll against the previous layout's size/scroll.  We need to
2315         // do this here to catch the case where the WebView is laid out at one size, removed from its
2316         // window, resized, and inserted into another window.  Our frame/bounds changed notifications
2317         // will not be sent in that situation, since we only watch for changes while in the view hierarchy.
2318         [self _frameOrBoundsChanged];
2319     }
2320 }
2321
2322 - (void)removeSuperviewObservers
2323 {
2324     NSView *superview = [self superview];
2325     if (superview && [self window]) {
2326         [[NSNotificationCenter defaultCenter] removeObserver:self
2327             name:NSViewFrameDidChangeNotification object:superview];
2328         [[NSNotificationCenter defaultCenter] removeObserver:self
2329             name:NSViewBoundsDidChangeNotification object:superview];
2330     }
2331 }
2332
2333 - (void)addWindowObservers
2334 {
2335     NSWindow *window = [self window];
2336     if (window) {
2337         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2338             name:NSWindowDidBecomeKeyNotification object:nil];
2339         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2340             name:NSWindowDidResignKeyNotification object:nil];
2341         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2342             name:NSWindowWillCloseNotification object:window];
2343     }
2344 }
2345
2346 - (void)removeWindowObservers
2347 {
2348     NSWindow *window = [self window];
2349     if (window) {
2350         [[NSNotificationCenter defaultCenter] removeObserver:self
2351             name:NSWindowDidBecomeKeyNotification object:nil];
2352         [[NSNotificationCenter defaultCenter] removeObserver:self
2353             name:NSWindowDidResignKeyNotification object:nil];
2354         [[NSNotificationCenter defaultCenter] removeObserver:self
2355             name:NSWindowWillCloseNotification object:window];
2356     }
2357 }
2358
2359 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2360 {
2361     [self removeSuperviewObservers];
2362 }
2363
2364 - (void)viewDidMoveToSuperview
2365 {
2366     // Do this here in case the text size multiplier changed when a non-HTML
2367     // view was installed.
2368     if ([self superview] != nil) {
2369         [self _updateTextSizeMultiplier];
2370         [self addSuperviewObservers];
2371     }
2372 }
2373
2374 - (void)viewWillMoveToWindow:(NSWindow *)window
2375 {
2376     // Don't do anything if we aren't initialized.  This happens
2377     // when decoding a WebView.  When WebViews are decoded their subviews
2378     // are created by initWithCoder: and so won't be normally
2379     // initialized.  The stub views are discarded by WebView.
2380     if (_private) {
2381         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2382         [self removeMouseMovedObserver];
2383         [self removeWindowObservers];
2384         [self removeSuperviewObservers];
2385         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2386     
2387         [[self _pluginController] stopAllPlugins];
2388     }
2389 }
2390
2391 - (void)viewDidMoveToWindow
2392 {
2393     // Don't do anything if we aren't initialized.  This happens
2394     // when decoding a WebView.  When WebViews are decoded their subviews
2395     // are created by initWithCoder: and so won't be normally
2396     // initialized.  The stub views are discarded by WebView.
2397     if (_private) {
2398         [self _stopAutoscrollTimer];
2399         if ([self window]) {
2400             _private->lastScrollPosition = [[self superview] bounds].origin;
2401             [self addWindowObservers];
2402             [self addSuperviewObservers];
2403             [self addMouseMovedObserver];
2404
2405             // Schedule this update, rather than making the call right now.
2406             // The reason is that placing the caret in the just-installed view requires
2407             // the HTML/XML document to be available on the WebCore side, but it is not
2408             // at the time this code is running. However, it will be there on the next
2409             // crank of the run loop. Doing this helps to make a blinking caret appear 
2410             // in a new, empty window "automatic".
2411             [self performSelector:@selector(_updateActiveState) withObject:nil afterDelay:0];
2412
2413             [[self _pluginController] startAllPlugins];
2414     
2415             _private->lastScrollPosition = NSZeroPoint;
2416         }
2417     }
2418 }
2419
2420 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2421 {
2422     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2423 }
2424
2425 - (void)viewDidMoveToHostWindow
2426 {
2427     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2428 }
2429
2430
2431 - (void)addSubview:(NSView *)view
2432 {
2433     [super addSubview:view];
2434
2435     if ([WebPluginController isPlugInView:view]) {
2436         [[self _pluginController] addPlugin:view];
2437     }
2438 }
2439
2440 - (void)willRemoveSubview:(NSView *)subview
2441 {
2442     if ([WebPluginController isPlugInView:subview])
2443         [[self _pluginController] destroyPlugin:subview];
2444     [super willRemoveSubview:subview];
2445 }
2446
2447 - (void)reapplyStyles
2448 {
2449     if (!_private->needsToApplyStyles) {
2450         return;
2451     }
2452     
2453 #ifdef _KWQ_TIMING        
2454     double start = CFAbsoluteTimeGetCurrent();
2455 #endif
2456
2457     [[self _bridge] reapplyStylesForDeviceType:
2458         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2459     
2460 #ifdef _KWQ_TIMING        
2461     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2462     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2463 #endif
2464
2465     _private->needsToApplyStyles = NO;
2466 }
2467
2468 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2469 // minPageWidth==0 implies a non-printing layout
2470 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2471 {
2472     [self reapplyStyles];
2473     
2474     // Ensure that we will receive mouse move events.  Is this the best place to put this?
2475     [[self window] setAcceptsMouseMovedEvents: YES];
2476     WKSetNSWindowShouldPostEventNotifications([self window], YES);
2477
2478     if (!_private->needsLayout) {
2479         return;
2480     }
2481
2482 #ifdef _KWQ_TIMING        
2483     double start = CFAbsoluteTimeGetCurrent();
2484 #endif
2485
2486     LOG(View, "%@ doing layout", self);
2487
2488     if (minPageWidth > 0.0) {
2489         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2490     } else {
2491         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2492     }
2493     _private->needsLayout = NO;
2494     
2495     if (!_private->printing) {
2496         // get size of the containing dynamic scrollview, so
2497         // appearance and disappearance of scrollbars will not show up
2498         // as a size change
2499         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2500         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2501             [[self _bridge] sendResizeEvent];
2502             if ([[self _bridge] needsLayout])
2503                 [[self _bridge] forceLayoutAdjustingViewSize:NO];
2504         }
2505         _private->laidOutAtLeastOnce = YES;
2506         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2507         _private->lastLayoutFrameSize = newLayoutFrameSize;
2508     }
2509
2510 #ifdef _KWQ_TIMING        
2511     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2512     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2513 #endif
2514 }
2515
2516 - (void)layout
2517 {
2518     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2519 }
2520
2521 - (NSMenu *)menuForEvent:(NSEvent *)event
2522 {
2523     [_private->compController endRevertingChange:NO moveLeft:NO];
2524
2525     if ([[self _bridge] sendContextMenuEvent:event]) {
2526         return nil;
2527     }
2528     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2529     NSDictionary *element = [self elementAtPoint:point];
2530     return [[self _webView] _menuForElement:element defaultItems:nil];
2531 }
2532
2533 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2534 {
2535     if (![string length])
2536         return NO;
2537
2538     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
2539 }
2540
2541 - (DOMRange *)_documentRange
2542 {
2543     return [[[self _bridge] DOMDocument] _documentRange];
2544 }
2545
2546 - (NSString *)string
2547 {
2548     return [[self _bridge] stringForRange:[self _documentRange]];
2549 }
2550
2551 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2552 {
2553     NSAttributedString *attributedString;
2554 #if !LOG_DISABLED        
2555     double start = CFAbsoluteTimeGetCurrent();
2556 #endif    
2557     attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2558 #if !LOG_DISABLED
2559     double duration = CFAbsoluteTimeGetCurrent() - start;
2560     LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2561 #endif
2562     return attributedString;
2563 }
2564
2565 - (NSAttributedString *)attributedString
2566 {
2567     WebFrameBridge *bridge = [self _bridge];
2568     DOMDocument *document = [bridge DOMDocument];
2569     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2570     if (attributedString == nil) {
2571         attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2572     }
2573     return attributedString;
2574 }
2575
2576 - (NSString *)selectedString
2577 {
2578     return [[self _bridge] selectedString];
2579 }
2580
2581 - (NSAttributedString *)selectedAttributedString
2582 {
2583     WebFrameBridge *bridge = [self _bridge];
2584     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2585     if (attributedString == nil) {
2586         attributedString = [bridge selectedAttributedString];
2587     }
2588     return attributedString;
2589 }
2590
2591 - (void)selectAll
2592 {
2593     [[self _bridge] selectAll];
2594 }
2595
2596 // Remove the selection.
2597 - (void)deselectAll
2598 {
2599     [[self _bridge] deselectAll];
2600 }
2601
2602 - (void)deselectText
2603 {
2604     [[self _bridge] deselectText];
2605 }
2606
2607 - (BOOL)isOpaque
2608 {
2609     return [[self _webView] drawsBackground];
2610 }
2611
2612 - (void)setNeedsDisplay:(BOOL)flag
2613 {
2614     LOG(View, "%@ flag = %d", self, (int)flag);
2615     [super setNeedsDisplay: flag];
2616 }
2617
2618 - (void)setNeedsLayout: (BOOL)flag
2619 {
2620     LOG(View, "%@ flag = %d", self, (int)flag);
2621     _private->needsLayout = flag;
2622 }
2623
2624
2625 - (void)setNeedsToApplyStyles: (BOOL)flag
2626 {
2627     LOG(View, "%@ flag = %d", self, (int)flag);
2628     _private->needsToApplyStyles = flag;
2629 }
2630
2631 - (void)drawSingleRect:(NSRect)rect
2632 {
2633     [NSGraphicsContext saveGraphicsState];
2634     NSRectClip(rect);
2635         
2636     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2637
2638     [(WebClipView *)[self superview] setAdditionalClip:rect];
2639
2640     NS_DURING {
2641         if ([self _transparentBackground]) {
2642             [[NSColor clearColor] set];
2643             NSRectFill (rect);
2644         }
2645         
2646         [[self _bridge] drawRect:rect];        
2647         WebView *webView = [self _webView];
2648         [[webView _UIDelegateForwarder] webView:webView didDrawRect:[webView convertRect:rect fromView:self]];
2649         [(WebClipView *)[self superview] resetAdditionalClip];
2650
2651         [NSGraphicsContext restoreGraphicsState];
2652     } NS_HANDLER {
2653         [(WebClipView *)[self superview] resetAdditionalClip];
2654         [NSGraphicsContext restoreGraphicsState];
2655         LOG_ERROR("Exception caught while drawing: %@", localException);
2656         [localException raise];
2657     } NS_ENDHANDLER
2658 }
2659
2660 - (void)drawRect:(NSRect)rect
2661 {
2662     LOG(View, "%@ drawing", self);
2663
2664     const NSRect *rects;
2665     WebNSInteger count;
2666     [self getRectsBeingDrawn:&rects count:&count];
2667
2668     BOOL subviewsWereSetAside = _private->subviewsSetAside;
2669     if (subviewsWereSetAside)
2670         [self _restoreSubviews];
2671
2672 #ifdef _KWQ_TIMING
2673     double start = CFAbsoluteTimeGetCurrent();
2674 #endif
2675
2676     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2677     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2678     // The reason for the workaround is that this method is called explicitly from the code
2679     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2680     const int cRectThreshold = 10;
2681     const float cWastedSpaceThreshold = 0.75f;
2682     BOOL useUnionedRect = (count <= 1) || (count > cRectThreshold);
2683     if (!useUnionedRect) {
2684         // Attempt to guess whether or not we should use the unioned rect or the individual rects.
2685         // We do this by computing the percentage of "wasted space" in the union.  If that wasted space
2686         // is too large, then we will do individual rect painting instead.
2687         float unionPixels = (rect.size.width * rect.size.height);
2688         float singlePixels = 0;
2689         for (int i = 0; i < count; ++i)
2690             singlePixels += rects[i].size.width * rects[i].size.height;
2691         float wastedSpace = 1 - (singlePixels / unionPixels);
2692         if (wastedSpace <= cWastedSpaceThreshold)
2693             useUnionedRect = YES;
2694     }
2695     
2696     if (useUnionedRect)
2697         [self drawSingleRect:rect];
2698     else
2699         for (int i = 0; i < count; ++i)
2700             [self drawSingleRect:rects[i]];
2701
2702 #ifdef _KWQ_TIMING
2703     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2704     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2705 #endif
2706
2707     if (subviewsWereSetAside)
2708         [self _setAsideSubviews];
2709 }
2710
2711 // Turn off the additional clip while computing our visibleRect.
2712 - (NSRect)visibleRect
2713 {
2714     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2715         return [super visibleRect];
2716         
2717     WebClipView *clipView = (WebClipView *)[self superview];
2718
2719     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2720     if (!hasAdditionalClip) {
2721         return [super visibleRect];
2722     }
2723     
2724     NSRect additionalClip = [clipView additionalClip];
2725     [clipView resetAdditionalClip];
2726     NSRect visibleRect = [super visibleRect];
2727     [clipView setAdditionalClip:additionalClip];
2728     return visibleRect;
2729 }
2730
2731 - (BOOL)isFlipped 
2732 {
2733     return YES;
2734 }
2735
2736 - (void)windowDidBecomeKey:(NSNotification *)notification
2737 {
2738     NSWindow *keyWindow = [notification object];
2739
2740     if (keyWindow == [self window])
2741         [self addMouseMovedObserver];
2742
2743     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
2744         [self _updateActiveState];
2745 }
2746
2747 - (void)windowDidResignKey:(NSNotification *)notification
2748 {
2749     NSWindow *formerKeyWindow = [notification object];
2750
2751     if (formerKeyWindow == [self window])
2752         [self removeMouseMovedObserver];
2753
2754     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2755         [self _updateActiveState];
2756         [_private->compController endRevertingChange:NO moveLeft:NO];
2757     }
2758 }
2759
2760 - (void)windowWillClose:(NSNotification *)notification
2761 {
2762     [_private->compController endRevertingChange:NO moveLeft:NO];
2763     [[self _pluginController] destroyAllPlugins];
2764 }
2765
2766 - (void)scrollWheel:(NSEvent *)event
2767 {
2768     [self retain];
2769     
2770     if (![[self _bridge] sendScrollWheelEvent:event]) {
2771         [[self nextResponder] scrollWheel:event];
2772     }    
2773     
2774     [self release];
2775 }
2776
2777 - (BOOL)_isSelectionEvent:(NSEvent *)event
2778 {
2779     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2780     return [[[self elementAtPoint:point allowShadowContent:YES] objectForKey:WebElementIsSelectedKey] boolValue];
2781 }
2782
2783 - (void)_setMouseDownEvent:(NSEvent *)event
2784 {
2785     ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2786
2787     if (event == _private->mouseDownEvent) {
2788         return;
2789     }
2790
2791     [event retain];
2792     [_private->mouseDownEvent release];
2793     _private->mouseDownEvent = event;
2794
2795     [_private->firstResponderAtMouseDownTime release];
2796     _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2797 }
2798
2799 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2800 {
2801     NSView *hitView = [self _hitViewForEvent:event];
2802     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2803     [hitHTMLView _setMouseDownEvent:event];
2804     
2805     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2806         return YES;
2807     
2808     if (hitHTMLView != nil) {
2809         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2810         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2811     } else {
2812         return [hitView acceptsFirstMouse:event];
2813     }
2814 }
2815
2816 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2817 {
2818     NSView *hitView = [self _hitViewForEvent:event];
2819     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2820     if (hitHTMLView != nil) {
2821         [hitHTMLView _setMouseDownEvent:event];
2822         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2823     } else {
2824         return [hitView shouldDelayWindowOrderingForEvent:event];
2825     }
2826 }
2827
2828 - (void)mouseDown:(NSEvent *)event
2829 {
2830     [self retain];
2831
2832     _private->handlingMouseDownEvent = YES;
2833
2834     // Record the mouse down position so we can determine drag hysteresis.
2835     [self _setMouseDownEvent:event];
2836
2837     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2838     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2839         goto done;
2840
2841     [_private->compController endRevertingChange:NO moveLeft:NO];
2842
2843     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2844     // We don't want to pass them along to KHTML a second time.
2845     if (!([event modifierFlags] & NSControlKeyMask)) {
2846         _private->ignoringMouseDraggedEvents = NO;
2847
2848         // Don't do any mouseover while the mouse is down.
2849         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2850
2851         // Let KHTML get a chance to deal with the event. This will call back to us
2852         // to start the autoscroll timer if appropriate.
2853         [[self _bridge] mouseDown:event];
2854     }
2855
2856 done:
2857     [_private->firstResponderAtMouseDownTime release];
2858     _private->firstResponderAtMouseDownTime = nil;
2859
2860     _private->handlingMouseDownEvent = NO;
2861     
2862     [self release];
2863 }
2864
2865 - (void)dragImage:(NSImage *)dragImage
2866                at:(NSPoint)at
2867            offset:(NSSize)offset
2868             event:(NSEvent *)event
2869        pasteboard:(NSPasteboard *)pasteboard
2870            source:(id)source
2871         slideBack:(BOOL)slideBack
2872 {
2873     [self _stopAutoscrollTimer];
2874
2875     WebHTMLView *topHTMLView = [self _topHTMLView];
2876     if (self != topHTMLView) {
2877         [topHTMLView dragImage:dragImage at:[self convertPoint:at toView:topHTMLView]
2878             offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2879         return;
2880     }
2881
2882     WebView *webView = [self _webView];
2883
2884     _private->initiatedDrag = YES;
2885     [webView _setInitiatedDrag:YES];
2886
2887     // Retain this view during the drag because it may be released before the drag ends.
2888     [self retain];
2889
2890     id UIDelegate = [webView UIDelegate];
2891     // If a delegate takes over the drag but never calls draggedImage: endedAt:, we'll leak the WebHTMLView.
2892     if ([UIDelegate respondsToSelector:@selector(webView:dragImage:at:offset:event:pasteboard:source:slideBack:forView:)])
2893         [UIDelegate webView:webView dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack forView:self];
2894     else
2895         [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2896 }
2897
2898 - (void)mouseDragged:(NSEvent *)event
2899 {
2900     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2901     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2902         return;
2903
2904     [self retain];
2905
2906     if (!_private->ignoringMouseDraggedEvents)
2907         [[self _bridge] mouseDragged:event];
2908
2909     [self release];
2910 }
2911
2912 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2913 {
2914     ASSERT([self _isTopHTMLView]);
2915
2916     if (_private->webCoreDragOp == NSDragOperationNone)
2917         return NSDragOperationGeneric | NSDragOperationCopy;
2918     return _private->webCoreDragOp;
2919 }
2920
2921 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2922 {
2923     ASSERT([self _isTopHTMLView]);
2924
2925     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2926     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2927     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2928 }
2929
2930 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2931 {
2932     ASSERT(![self _webView] || [self _isTopHTMLView]);
2933
2934     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2935     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2936     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2937
2938     _private->initiatedDrag = NO;
2939     [[self _webView] _setInitiatedDrag:NO];
2940     
2941     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2942     _private->ignoringMouseDraggedEvents = YES;
2943     
2944     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2945     // WebCore expects to get balanced down/up's, so we must fake up a mouseup.
2946     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2947                                             location:windowMouseLoc
2948                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2949                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2950                                         windowNumber:[[self window] windowNumber]
2951                                              context:[[NSApp currentEvent] context]
2952                                          eventNumber:0 clickCount:0 pressure:0];
2953     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2954     
2955     // Balance the previous retain from when the drag started.
2956     [self release];
2957 }
2958
2959 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2960 {
2961     ASSERT([self _isTopHTMLView]);
2962     ASSERT(_private->draggingImageURL);
2963
2964     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2965     if (wrapper == nil) {
2966         LOG_ERROR("Failed to create image file. Did the source image change while dragging? (<rdar://problem/4244861>)");
2967         return nil;
2968     }
2969
2970     // FIXME: Report an error if we fail to create a file.
2971     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2972     path = [[NSFileManager defaultManager] _webkit_pathWithUniqueFilenameForPath:path];
2973     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES])
2974         LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2975
2976     return [NSArray arrayWithObject:[path lastPathComponent]];
2977 }
2978
2979 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2980 {
2981     ASSERT([self _isTopHTMLView]);
2982
2983     NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2984     NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2985     [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2986     if ([types count] == 0)
2987         return NO;
2988     if ([types count] == 1
2989             && [types containsObject:NSFilenamesPboardType]
2990             && ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]])
2991         return NO;
2992
2993     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2994     NSDictionary *element = [self elementAtPoint:point allowShadowContent:YES];
2995     if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2996         // Can't drag onto the selection being dragged.
2997         if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue])
2998             return NO;
2999         return YES;
3000     }
3001
3002     return NO;
3003 }
3004
3005 - (BOOL)_isMoveDrag
3006 {
3007     ASSERT([self _isTopHTMLView]);
3008     return _private->initiatedDrag
3009         && [self _isEditable] && [self _hasSelection]
3010         && !([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask);
3011 }
3012
3013 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
3014 {
3015     return [[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType];
3016 }
3017
3018 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
3019 {
3020     ASSERT([self _isTopHTMLView]);
3021
3022     NSDragOperation operation = NSDragOperationNone;
3023     if (actionMask & WebDragDestinationActionDHTML)
3024         operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
3025     _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
3026
3027     if ((actionMask & WebDragDestinationActionEdit) && !_private->webCoreHandlingDrag && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
3028         if ([self _isNSColorDrag:draggingInfo])
3029             operation = NSDragOperationGeneric;
3030         else {
3031             WebView *webView = [self _webView];
3032             [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
3033             operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
3034         }
3035     } else
3036         [[self _webView] removeDragCaret];
3037
3038     return operation;
3039 }
3040
3041 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
3042 {
3043     ASSERT([self _isTopHTMLView]);
3044
3045     [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
3046     [[self _webView] removeDragCaret];
3047 }
3048
3049 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
3050 {
3051     ASSERT([self _isTopHTMLView]);
3052
3053     WebView *webView = [self _webView];
3054     WebFrameBridge *bridge = [self _bridge];
3055     if (_private->webCoreHandlingDrag) {
3056         ASSERT(actionMask & WebDragDestinationActionDHTML);
3057         [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
3058         [bridge concludeDragForDraggingInfo:draggingInfo];
3059         return YES;
3060     }
3061
3062     if (!(actionMask & WebDragDestinationActionEdit))
3063         return NO;
3064
3065     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
3066     NSDictionary *element = [self elementAtPoint:point allowShadowContent:YES];
3067     ASSERT(element);
3068     WebFrame *innerFrame = (WebFrame *)[element objectForKey:WebElementFrameKey];
3069     ASSERT(innerFrame);
3070     ASSERT([innerFrame isKindOfClass:[WebFrame class]]);
3071     WebFrameBridge *innerBridge = [innerFrame _bridge];
3072
3073     if ([self _isNSColorDrag:draggingInfo]) {
3074         NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
3075         if (!color)
3076             return NO;
3077         DOMCSSStyleDeclaration *style = [self _emptyStyle];
3078         [style setProperty:@"color" :[self _colorAsString:color] :@""];
3079         if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[innerBridge selectedDOMRange]]) {
3080             [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
3081             [innerBridge applyStyle:style withUndoAction:WebUndoActionSetColor];
3082             return YES;
3083         }
3084         return NO;
3085     }
3086
3087     BOOL didInsert = NO;
3088     if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
3089         NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
3090         if ([self _isMoveDrag] || [innerBridge isDragCaretRichlyEditable]) { 
3091             BOOL chosePlainText;
3092             DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES chosePlainText:&chosePlainText];
3093             if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[innerBridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
3094                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
3095                 if ([self _isMoveDrag]) {
3096                     BOOL smartMove = [innerBridge selectionGranularity] == WebBridgeSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
3097                     [innerBridge moveSelectionToDragCaret:fragment smartMove:smartMove];
3098                 } else {
3099                     [innerBridge setSelectionToDragCaret];
3100                     [innerBridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
3101                 }
3102                 didInsert = YES;
3103             }
3104         } else {
3105             NSString *text = [self _plainTextFromPasteboard:pasteboard];
3106             if (text && [self _shouldInsertText:text replacingDOMRange:[innerBridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
3107                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
3108                 [innerBridge setSelectionToDragCaret];
3109                 [innerBridge replaceSelectionWithText:text selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3110                 didInsert = YES;
3111             }
3112         }
3113     }
3114     [webView removeDragCaret];
3115     return didInsert;
3116 }
3117
3118 - (NSDictionary *)elementAtPoint:(NSPoint)point
3119 {
3120     return [self elementAtPoint:point allowShadowContent:NO];
3121 }
3122
3123 - (NSDictionary *)elementAtPoint:(NSPoint)point allowShadowContent:(BOOL)allow;
3124 {
3125     DOMNode *innerNode = nil;
3126     DOMNode *innerNonSharedNode = nil;
3127     DOMElement *URLElement = nil;
3128     [[self _bridge] getInnerNonSharedNode:&innerNonSharedNode innerNode:&innerNode URLElement:&URLElement atPoint:point allowShadowContent:allow];
3129     NSView *innerView = [[[[innerNonSharedNode ownerDocument] webFrame] frameView] documentView];
3130     NSPoint innerPoint = innerView ? [self convertPoint:point toView:innerView] : point;
3131     return [[[WebElementDictionary alloc] initWithInnerNonSharedNode:innerNonSharedNode innerNode:innerNode URLElement:URLElement andPoint:innerPoint] autorelease];
3132 }
3133
3134 - (void)mouseUp:(NSEvent *)event
3135 {
3136     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
3137     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
3138         return;
3139
3140     [self retain];
3141
3142     [self _stopAutoscrollTimer];
3143     [[self _bridge] mouseUp:event];
3144     [self _updateMouseoverWithFakeEvent];
3145
3146     [self release];
3147 }
3148
3149 - (void)mouseMovedNotification:(NSNotification *)notification
3150 {
3151     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
3152 }
3153
3154 - (BOOL)supportsTextEncoding
3155 {
3156     return YES;
3157 }
3158
3159 // returning YES from this method is the way we tell AppKit that it is ok for this view
3160 // to be in the key loop even when "tab to all controls" is not on.
3161 - (BOOL)needsPanelToBecomeKey
3162 {
3163     return YES;
3164 }
3165
3166 - (NSView *)nextValidKeyView
3167 {
3168     NSView *view = nil;
3169     BOOL lookInsideWebFrameViews = YES;
3170     if ([self isHiddenOrHasHiddenAncestor]) {
3171         lookInsideWebFrameViews = NO;
3172     } else if ([self _frame] == [[self _webView] mainFrame]) {
3173         // Check for case where first responder is last frame in a frameset, and we are
3174         // the top-level documentView.
3175         NSResponder *firstResponder = [[self window] firstResponder];
3176         if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
3177             lookInsideWebFrameViews = NO;
3178         }
3179     }
3180     
3181     if (lookInsideWebFrameViews) {
3182         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3183     }
3184     
3185     if (view == nil) {
3186         view = [super nextValidKeyView];
3187         // If there's no next view wired up, we must be in the last subframe, or we are
3188         // being called at an unusual time when the views have not yet been wired together.
3189         // There's no direct link to the next valid key view; get it from the bridge.
3190         // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
3191         // We'll check for both nil and self in case the AppKit oddness goes away.
3192         // WebFrameView has this same kind of logic for the previousValidKeyView case.
3193         if (view == nil || view == self) {
3194             view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
3195         }
3196     }
3197         
3198     return view;
3199 }
3200
3201 - (NSView *)previousValidKeyView
3202 {
3203     NSView *view = nil;
3204     if (![self isHiddenOrHasHiddenAncestor])
3205         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3206     if (view == nil)
3207         view = [super previousValidKeyView];
3208     return view;
3209 }
3210
3211 - (BOOL)becomeFirstResponder
3212 {
3213     NSView *view = nil;
3214     if (![[self _webView] _isPerformingProgrammaticFocus] && !_private->willBecomeFirstResponderForNodeFocus) {
3215         switch ([[self window] keyViewSelectionDirection]) {
3216             case NSDirectSelection:
3217                 break;
3218             case NSSelectingNext:
3219                 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3220                 break;
3221             case NSSelectingPrevious:
3222                 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3223                 break;
3224         }
3225     }
3226     _private->willBecomeFirstResponderForNodeFocus = NO;
3227     if (view)
3228         [[self window] makeFirstResponder:view];
3229     [[self _frame] _clearSelectionInOtherFrames];
3230     [self _updateActiveState];
3231     [self _updateFontPanel];
3232     _private->startNewKillRingSequence = YES;
3233     return YES;
3234 }
3235
3236 - (BOOL)resignFirstResponder
3237 {
3238     BOOL resign = [super resignFirstResponder];
3239     if (resign) {
3240         [_private->compController endRevertingChange:NO moveLeft:NO];
3241         _private->resigningFirstResponder = YES;
3242         if (![self maintainsInactiveSelection]) { 
3243             if ([[self _webView] _isPerformingProgrammaticFocus])
3244                 [self deselectText];
3245             else
3246                 [self deselectAll];
3247         }
3248         [self _updateActiveState];
3249         _private->resigningFirstResponder = NO;
3250         _private->willBecomeFirstResponderForNodeFocus = NO;
3251     }
3252     return resign;
3253 }
3254
3255 - (void)setDataSource:(WebDataSource *)dataSource 
3256 {
3257     ASSERT(!_private->dataSource);
3258     _private->dataSource = [dataSource retain];
3259     [_private->pluginController setDataSource:dataSource];
3260     [self addMouseMovedObserver];
3261 }
3262
3263 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3264 {
3265 }
3266
3267 // This is an override of an NSControl method that wants to repaint the entire view when the window resigns/becomes
3268 // key.  WebHTMLView is an NSControl only because it hosts NSCells that are painted by WebCore's Aqua theme
3269 // renderer (and those cells must be hosted by an enclosing NSControl in order to paint properly).
3270 - (void)updateCell:(NSCell*)cell
3271 {
3272 }
3273
3274 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3275 // pageWidth != 0 implies we will relayout to a new width
3276 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3277 {
3278     WebFrame *frame = [self _frame];
3279     NSArray *subframes = [frame childFrames];
3280     unsigned n = [subframes count];
3281     unsigned i;
3282     for (i = 0; i != n; ++i) {
3283         WebFrame *subframe = [subframes objectAtIndex:i];
3284         WebFrameView *frameView = [subframe frameView];
3285         if ([[subframe dataSource] _isDocumentHTML]) {
3286             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
3287         }
3288     }
3289
3290     if (printing != _private->printing) {
3291         [_private->pageRects release];
3292         _private->pageRects = nil;
3293         _private->printing = printing;
3294         [self setNeedsToApplyStyles:YES];
3295         [self setNeedsLayout:YES];
3296         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3297         if (!printing) {
3298             // Can't do this when starting printing or nested printing won't work, see 3491427.
3299             [self setNeedsDisplay:NO];
3300         }
3301     }
3302 }
3303
3304 - (BOOL)canPrintHeadersAndFooters
3305 {
3306     return YES;
3307 }
3308
3309 // This is needed for the case where the webview is embedded in the view that's being printed.
3310 // It shouldn't be called when the webview is being printed directly.
3311 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3312 {
3313     // This helps when we print as part of a larger print process.
3314     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3315     BOOL wasInPrintingMode = _private->printing;
3316     if (!wasInPrintingMode)
3317         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3318
3319     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3320     
3321     if (!wasInPrintingMode)
3322         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3323 }
3324
3325 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3326 {
3327     NSPrintInfo *printInfo = [printOperation printInfo];
3328     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3329 }
3330
3331 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3332 {
3333     float viewWidth = NSWidth([self bounds]);
3334     if (viewWidth < 1) {
3335         LOG_ERROR("%@ has no width when printing", self);
3336         return 1.0;
3337     }
3338
3339     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3340     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
3341     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3342     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3343 }
3344
3345 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3346 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3347 // if AppKit makes it SPI/API.
3348 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
3349 {
3350     return [self _scaleFactorForPrintOperation:printOperation];
3351 }
3352
3353 // This is used for Carbon printing. At some point we might want to make this public API.
3354 - (void)setPageWidthForPrinting:(float)pageWidth
3355 {
3356     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
3357     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3358 }
3359
3360 - (void)_endPrintMode
3361 {
3362     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3363     [[self window] setAutodisplay:YES];
3364 }
3365
3366 - (void)_delayedEndPrintMode:(NSPrintOperation *)initiatingOperation
3367 {
3368     ASSERT_ARG(initiatingOperation, initiatingOperation != nil);
3369     NSPrintOperation *currentOperation = [NSPrintOperation currentOperation];
3370     if (initiatingOperation == currentOperation) {
3371         // The print operation is still underway. We don't expect this to ever happen, hence the assert, but we're
3372         // being extra paranoid here since the printing code is so fragile. Delay the cleanup
3373         // further.
3374         ASSERT_NOT_REACHED();
3375         [self performSelector:@selector(_delayedEndPrintMode:) withObject:initiatingOperation afterDelay:0];
3376     } else if ([currentOperation view] == self) {
3377         // A new print job has started, but it is printing the same WebHTMLView again. We don't expect
3378         // this to ever happen, hence the assert, but we're being extra paranoid here since the printing code is so
3379         // fragile. Do nothing, because we don't want to break the print job currently in progress, and
3380         // the print job currently in progress is responsible for its own cleanup.
3381         ASSERT_NOT_REACHED();
3382     } else {
3383         // The print job that kicked off this delayed call has finished, and this view is not being
3384         // printed again. We expect that no other print job has started. Since this delayed call wasn't
3385         // cancelled, beginDocument and endDocument must not have been called, and we need to clean up
3386         // the print mode here.
3387         ASSERT(currentOperation == nil);
3388         [self _endPrintMode];
3389     }
3390 }
3391
3392 // Return the number of pages available for printing
3393 - (BOOL)knowsPageRange:(NSRangePointer)range
3394 {
3395     // Must do this explicit display here, because otherwise the view might redisplay while the print
3396     // sheet was up, using printer fonts (and looking different).
3397     [self displayIfNeeded];
3398     [[self window] setAutodisplay:NO];
3399     
3400     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3401     // according to the paper size
3402     float minLayoutWidth = 0.0;
3403     float maxLayoutWidth = 0.0;
3404     if (![[self _bridge] isFrameSet]) {
3405         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3406         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
3407         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
3408     }
3409     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3410     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3411     // Certain types of errors, including invalid page ranges, can cause beginDocument and
3412     // endDocument to be skipped after we've put ourselves in print mode (see 4145905). In those cases
3413     // we need to get out of print mode without relying on any more callbacks from the printing mechanism.
3414     // If we get as far as beginDocument without trouble, then this delayed request will be cancelled.
3415     // If not cancelled, this delayed call will be invoked in the next pass through the main event loop,
3416     // which is after beginDocument and endDocument would be called.
3417     [self performSelector:@selector(_delayedEndPrintMode:) withObject:printOperation afterDelay:0];
3418     [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3419     
3420     // There is a theoretical chance that someone could do some drawing between here and endDocument,
3421     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3422     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3423
3424     range->location = 1;
3425     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3426     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3427     [_private->pageRects release];
3428     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3429                                                                           printHeight:floorf([self _calculatePrintHeight]/totalScaleFactor)];
3430     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3431     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3432     // a blank page (with correct-looking header and footer if that option is on), which matches
3433     // the behavior of IE and Camino at least.
3434     if ([newPageRects count] == 0)
3435         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect:NSMakeRect(0, 0, 1, 1)]];
3436     _private->pageRects = [newPageRects retain];
3437     
3438     range->length = [_private->pageRects count];
3439     
3440     return YES;
3441 }
3442
3443 // Return the drawing rectangle for a particular page number
3444 - (NSRect)rectForPage:(int)page
3445 {
3446     return [[_private->pageRects objectAtIndex:page - 1] rectValue];
3447 }
3448
3449 - (void)drawPageBorderWithSize:(NSSize)borderSize
3450 {
3451     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
3452     [[self _webView] _drawHeaderAndFooter];
3453 }
3454
3455 - (void)beginDocument
3456 {
3457     NS_DURING
3458         // From now on we'll get a chance to call _endPrintMode in either beginDocument or
3459         // endDocument, so we can cancel the "just in case" pending call.
3460         [NSObject cancelPreviousPerformRequestsWithTarget:self
3461                                                  selector:@selector(_delayedEndPrintMode:)
3462                                                    object:[NSPrintOperation currentOperation]];
3463         [super beginDocument];
3464     NS_HANDLER
3465         // Exception during [super beginDocument] means that endDocument will not get called,
3466         // so we need to clean up our "print mode" here.
3467         [self _endPrintMode];
3468     NS_ENDHANDLER
3469 }
3470
3471 - (void)endDocument
3472 {
3473     [super endDocument];
3474     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
3475     [self _endPrintMode];
3476 }
3477
3478 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3479 {   
3480     // Use WebView's tabKeyCyclesThroughElements state to determine whether or not
3481     // to process tab key events. The idea here is that tabKeyCyclesThroughElements
3482     // will be YES when this WebView is being used in a browser, and we desire the
3483     // behavior where tab moves to the next element in tab order. If tabKeyCyclesThroughElements
3484     // is NO, it is likely that the WebView is being embedded as the whole view, as in Mail,
3485     // and tabs should input tabs as expected in a text editor. Using Option-Tab always cycles
3486     // through elements.
3487
3488     if ([[self _webView] tabKeyCyclesThroughElements] && [event _web_isTabKeyEvent]) 
3489         return NO;
3490
3491     if (![[self _webView] tabKeyCyclesThroughElements] && [event _web_isOptionTabKeyEvent])
3492         return NO;
3493
3494     // Now process the key normally
3495     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3496     return YES;
3497 }
3498
3499 - (void)keyDown:(NSEvent *)event
3500 {
3501     [self retain];
3502
3503     BOOL callSuper = NO;
3504
3505     _private->keyDownEvent = event;
3506
3507     WebFrameBridge *bridge = [self _bridge];
3508     if ([bridge interceptKeyEvent:event toView:self]) {
3509         // WebCore processed a key event, bail on any outstanding complete: UI