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