Reviewed by thatcher
[WebKit-https.git] / WebKit / WebView / WebHTMLView.m
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import <WebKit/WebHTMLView.h>
30
31 #import <ApplicationServices/ApplicationServices.h>
32 #import <WebKit/DOM.h>
33 #import <WebKit/DOMExtensions.h>
34 #import <WebKit/DOMPrivate.h>
35 #import <WebKit/WebArchive.h>
36 #import <WebKit/WebArchiver.h>
37 #import <WebKit/WebBaseNetscapePluginViewInternal.h>
38 #import <WebKit/WebFrameBridge.h>
39 #import <WebKit/WebClipView.h>
40 #import <WebKit/WebDataProtocol.h>
41 #import <WebKit/WebDataSourceInternal.h>
42 #import <WebKit/WebDefaultUIDelegate.h>
43 #import <WebKit/WebDocumentInternal.h>
44 #import <WebKit/WebDOMOperationsPrivate.h>
45 #import <WebKit/WebEditingDelegate.h>
46 #import <WebKit/WebElementDictionary.h>
47 #import <WebKit/WebFramePrivate.h>
48 #import <WebKit/WebFrameInternal.h>
49 #import <WebKit/WebFrameViewInternal.h>
50 #import <WebKit/WebHTMLViewInternal.h>
51 #import <WebKit/WebHTMLRepresentationPrivate.h>
52 #import <WebKit/WebKitLogging.h>
53 #import <WebKit/WebKitNSStringExtras.h>
54 #import <WebKit/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
1032 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
1033 {
1034     ASSERT(_private->trackingRectOwner == nil);
1035     _private->trackingRectOwner = owner;
1036     _private->trackingRectUserData = data;
1037     return TRACKING_RECT_TAG;
1038 }
1039
1040 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
1041 {
1042     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
1043     ASSERT(_private->trackingRectOwner == nil);
1044     _private->trackingRectOwner = owner;
1045     _private->trackingRectUserData = data;
1046     return TRACKING_RECT_TAG;
1047 }
1048
1049 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
1050 {
1051     ASSERT(count == 1);
1052     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
1053     ASSERT(_private->trackingRectOwner == nil);
1054     _private->trackingRectOwner = owner;
1055     _private->trackingRectUserData = userDataList[0];
1056     trackingNums[0] = TRACKING_RECT_TAG;
1057 }
1058
1059 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1060 {
1061     if (tag == 0)
1062         return;
1063     
1064     if (_private && (tag == TRACKING_RECT_TAG)) {
1065         _private->trackingRectOwner = nil;
1066         return;
1067     }
1068     
1069     if (_private && (tag == _private->lastToolTipTag)) {
1070         [super removeTrackingRect:tag];
1071         _private->lastToolTipTag = 0;
1072         return;
1073     }
1074     
1075     // If any other tracking rect is being removed, we don't know how it was created
1076     // and it's possible there's a leak involved (see 3500217)
1077     ASSERT_NOT_REACHED();
1078 }
1079
1080 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1081 {
1082     int i;
1083     for (i = 0; i < count; ++i) {
1084         int tag = tags[i];
1085         if (tag == 0)
1086             continue;
1087         ASSERT(tag == TRACKING_RECT_TAG);
1088         if (_private != nil) {
1089             _private->trackingRectOwner = nil;
1090         }
1091     }
1092 }
1093
1094 - (void)_sendToolTipMouseExited
1095 {
1096     // Nothing matters except window, trackingNumber, and userData.
1097     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
1098         location:NSMakePoint(0, 0)
1099         modifierFlags:0
1100         timestamp:0
1101         windowNumber:[[self window] windowNumber]
1102         context:NULL
1103         eventNumber:0
1104         trackingNumber:TRACKING_RECT_TAG
1105         userData:_private->trackingRectUserData];
1106     [_private->trackingRectOwner mouseExited:fakeEvent];
1107 }
1108
1109 - (void)_sendToolTipMouseEntered
1110 {
1111     // Nothing matters except window, trackingNumber, and userData.
1112     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
1113         location:NSMakePoint(0, 0)
1114         modifierFlags:0
1115         timestamp:0
1116         windowNumber:[[self window] windowNumber]
1117         context:NULL
1118         eventNumber:0
1119         trackingNumber:TRACKING_RECT_TAG
1120         userData:_private->trackingRectUserData];
1121     [_private->trackingRectOwner mouseEntered:fakeEvent];
1122 }
1123
1124 - (void)_setToolTip:(NSString *)string
1125 {
1126     NSString *toolTip = [string length] == 0 ? nil : string;
1127     NSString *oldToolTip = _private->toolTip;
1128     if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
1129         return;
1130     }
1131     if (oldToolTip) {
1132         [self _sendToolTipMouseExited];
1133         [oldToolTip release];
1134     }
1135     _private->toolTip = [toolTip copy];
1136     if (toolTip) {
1137         // See radar 3500217 for why we remove all tooltips rather than just the single one we created.
1138         [self removeAllToolTips];
1139         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
1140         _private->lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
1141         [self _sendToolTipMouseEntered];
1142     }
1143 }
1144
1145 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1146 {
1147     return [[_private->toolTip copy] autorelease];
1148 }
1149
1150 - (void)_updateMouseoverWithEvent:(NSEvent *)event
1151 {
1152     if (_private->closed)
1153         return;
1154
1155     NSView *contentView = [[event window] contentView];
1156     NSPoint locationForHitTest = [[contentView superview] convertPoint:[event locationInWindow] fromView:nil];
1157     
1158     forceWebHTMLViewHitTest = YES;
1159     NSView *hitView = [contentView hitTest:locationForHitTest];
1160     forceWebHTMLViewHitTest = NO;
1161     
1162     WebHTMLView *view = nil;
1163     if ([hitView isKindOfClass:[WebHTMLView class]]) 
1164         view = (WebHTMLView *)hitView; 
1165
1166     if (view)
1167         [view retain];
1168
1169     if (lastHitView != view && lastHitView != nil) {
1170         // If we are moving out of a view (or frame), let's pretend the mouse moved
1171         // all the way out of that view. But we have to account for scrolling, because
1172         // khtml doesn't understand our clipping.
1173         NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
1174         float yScroll = visibleRect.origin.y;
1175         float xScroll = visibleRect.origin.x;
1176
1177         event = [NSEvent mouseEventWithType:NSMouseMoved
1178                          location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1179                          modifierFlags:[[NSApp currentEvent] modifierFlags]
1180                          timestamp:[NSDate timeIntervalSinceReferenceDate]
1181                          windowNumber:[[view window] windowNumber]
1182                          context:[[NSApp currentEvent] context]
1183                          eventNumber:0 clickCount:0 pressure:0];
1184         [[lastHitView _bridge] mouseMoved:event];
1185     }
1186
1187     lastHitView = view;
1188
1189     if (view) {
1190         [[view _bridge] mouseMoved:event];
1191
1192         NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1193         NSDictionary *element = [view elementAtPoint:point];
1194
1195         // Have the web view send a message to the delegate so it can do status bar display.
1196         [[view _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1197
1198         // Set a tool tip; it won't show up right away but will if the user pauses.
1199         NSString *newToolTip = nil;
1200         if (_private->showsURLsInToolTips) {
1201             DOMHTMLElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1202             if ([domElement isKindOfClass:[DOMHTMLInputElement class]]) {
1203                 if ([[(DOMHTMLInputElement *)domElement type] isEqualToString:@"submit"])
1204                     newToolTip = [[(DOMHTMLInputElement *) domElement form] action];
1205             }
1206             if (newToolTip == nil)
1207                 newToolTip = [[element objectForKey:WebElementLinkURLKey] _web_userVisibleString];
1208         }
1209         if (newToolTip == nil)
1210             newToolTip = [element objectForKey:WebElementTitleKey];
1211         [view _setToolTip:newToolTip];
1212
1213         [view release];
1214     }
1215 }
1216
1217 + (NSArray *)_insertablePasteboardTypes
1218 {
1219     static NSArray *types = nil;
1220     if (!types) {
1221         types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1222             NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType, 
1223             NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1224     }
1225     return types;
1226 }
1227
1228 + (NSArray *)_selectionPasteboardTypes
1229 {
1230     // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1231     return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1232 }
1233
1234 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1235 {
1236     NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1237
1238     BOOL drawURLString = YES;
1239     BOOL clipURLString = NO, clipLabelString = NO;
1240     
1241     NSString *label = [element objectForKey: WebElementLinkLabelKey];
1242     NSString *urlString = [linkURL _web_userVisibleString];
1243     
1244     if (!label) {
1245         drawURLString = NO;
1246         label = urlString;
1247     }
1248     
1249     NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1250                                                    toHaveTrait:NSBoldFontMask];
1251     NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1252     NSSize labelSize;
1253     labelSize.width = [label _web_widthWithFont: labelFont];
1254     labelSize.height = [labelFont ascender] - [labelFont descender];
1255     if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1256         labelSize.width = MAX_DRAG_LABEL_WIDTH;
1257         clipLabelString = YES;
1258     }
1259     
1260     NSSize imageSize, urlStringSize;
1261     imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2.0f;
1262     imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2.0f;
1263     if (drawURLString) {
1264         urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1265         urlStringSize.height = [urlFont ascender] - [urlFont descender];
1266         imageSize.height += urlStringSize.height;
1267         if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1268             imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2.0f, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1269             clipURLString = YES;
1270         } else {
1271             imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2.0f, urlStringSize.width + DRAG_LABEL_BORDER_X * 2.0f);
1272         }
1273     }
1274     NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1275     [dragImage lockFocus];
1276     
1277     [[NSColor colorWithCalibratedRed: 0.7f green: 0.7f blue: 0.7f alpha: 0.8f] set];
1278     
1279     // Drag a rectangle with rounded corners/
1280     NSBezierPath *path = [NSBezierPath bezierPath];
1281     [path appendBezierPathWithOvalInRect: NSMakeRect(0.0f, 0.0f, DRAG_LABEL_RADIUS * 2.0f, DRAG_LABEL_RADIUS * 2.0f)];
1282     [path appendBezierPathWithOvalInRect: NSMakeRect(0, 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, imageSize.height - DRAG_LABEL_RADIUS * 2.0f, DRAG_LABEL_RADIUS * 2.0f, DRAG_LABEL_RADIUS * 2.0f)];
1284     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2.0f, 0.0f, DRAG_LABEL_RADIUS * 2.0f, DRAG_LABEL_RADIUS * 2.0f)];
1285     
1286     [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0.0f, imageSize.width - DRAG_LABEL_RADIUS * 2.0f, imageSize.height)];
1287     [path appendBezierPathWithRect: NSMakeRect(0.0f, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10.0f, imageSize.height - 2.0f * DRAG_LABEL_RADIUS)];
1288     [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)];
1289     [path fill];
1290         
1291     NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0f alpha:0.75f];
1292     NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0f alpha:0.5f];
1293     if (drawURLString) {
1294         if (clipURLString)
1295             urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2.0f) withFont:urlFont];
1296
1297         [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
1298              withTopColor:topColor bottomColor:bottomColor font:urlFont];
1299     }
1300
1301     if (clipLabelString)
1302         label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2.0f) withFont:labelFont];
1303     [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1304              withTopColor:topColor bottomColor:bottomColor font:labelFont];
1305     
1306     [dragImage unlockFocus];
1307     
1308     return dragImage;
1309 }
1310
1311 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1312 {
1313     WebHTMLView *topHTMLView = [self _topHTMLView];
1314     if (self != topHTMLView) {
1315         [topHTMLView _setMouseDownEvent:_private->mouseDownEvent];
1316         BOOL result = [topHTMLView _startDraggingImage:wcDragImage at:wcDragLoc operation:op event:mouseDraggedEvent sourceIsDHTML:srcIsDHTML DHTMLWroteData:dhtmlWroteData];
1317         [topHTMLView _setMouseDownEvent:nil];
1318         return result;
1319     }
1320
1321     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1322     NSDictionary *element = [self elementAtPoint:mouseDownPoint allowShadowContent:YES];
1323
1324     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1325     NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1326     BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1327
1328     [_private->draggingImageURL release];
1329     _private->draggingImageURL = nil;
1330
1331     NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1332     _private->webCoreDragOp = op;     // will be DragNone if WebCore doesn't care
1333     NSImage *dragImage = nil;
1334     NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1335
1336     // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1337     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1338     // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1339     if (wcDragImage) {
1340         dragImage = wcDragImage;
1341         // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1342         // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1343         if (linkURL)
1344             // see HACK below
1345             dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1346         else
1347             dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1348         _private->dragOffset = wcDragLoc;
1349     }
1350     
1351     WebView *webView = [self _webView];
1352     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1353     BOOL startedDrag = YES;  // optimism - we almost always manage to start the drag
1354
1355     // note per kwebster, the offset arg below is always ignored in positioning the image
1356     DOMNode *node = [element objectForKey:WebElementDOMNodeKey];
1357     WebHTMLView *innerHTMLView = (WebHTMLView *)[[[[node ownerDocument] webFrame] frameView] documentView];
1358     ASSERT([innerHTMLView isKindOfClass:[WebHTMLView class]]);
1359     if (imageURL != nil
1360             && [node isKindOfClass:[DOMElement class]]
1361             && [(DOMElement *)node image]
1362             && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1363         id source = self;
1364         if (!dhtmlWroteData) {
1365             // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1366             ASSERT(node != nil);
1367             [webView setSelectedDOMRange:[[node ownerDocument] _createRangeWithNode:node] affinity:NSSelectionAffinityDownstream];
1368             _private->draggingImageURL = [imageURL retain];
1369             
1370             WebArchive *archive;
1371             
1372             // If the image element comes from an ImageDocument, we don't want to 
1373             // create a web archive from the image element.
1374             if ([[self _bridge] canSaveAsWebArchive])
1375                 archive = [node webArchive];
1376             else
1377                 archive = [WebArchiver archiveMainResourceForFrame:[self _frame]];
1378             
1379             source = [pasteboard _web_declareAndWriteDragImageForElement:(DOMElement *)node
1380                                                                      URL:linkURL ? linkURL : imageURL
1381                                                                    title:[element objectForKey:WebElementImageAltStringKey]
1382                                                                  archive:archive
1383                                                                   source:self];
1384         }
1385         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1386         if (dragImage == nil)
1387             [self _web_DragImageForElement:(DOMElement *)node
1388                                       rect:[self convertRect:[[element objectForKey:WebElementImageRectKey] rectValue] fromView:innerHTMLView]
1389                                      event:_private->mouseDownEvent
1390                                 pasteboard:pasteboard
1391                                     source:source
1392                                     offset:&_private->dragOffset];
1393         else
1394             [self dragImage:dragImage
1395                          at:dragLoc
1396                      offset:NSZeroSize
1397                       event:_private->mouseDownEvent
1398                  pasteboard:pasteboard
1399                      source:source
1400                   slideBack:YES];
1401     } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1402         if (!dhtmlWroteData) {
1403             NSArray *types = [NSPasteboard _web_writableTypesForURL];
1404             [pasteboard declareTypes:types owner:self];
1405             [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];            
1406         }
1407         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1408         if (dragImage == nil) {
1409             dragImage = [self _dragImageForLinkElement:element];
1410             NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1411             dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1412             _private->dragOffset.x = offset.width;
1413             _private->dragOffset.y = -offset.height;        // inverted because we are flipped
1414         }
1415         // HACK:  We should pass the mouseDown event instead of the mouseDragged!  This hack gets rid of
1416         // a flash of the image at the mouseDown location when the drag starts.
1417         [self dragImage:dragImage
1418                      at:dragLoc
1419                  offset:NSZeroSize
1420                   event:mouseDraggedEvent
1421              pasteboard:pasteboard
1422                  source:self
1423               slideBack:YES];
1424     } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1425         if (!dhtmlWroteData)
1426             [innerHTMLView _writeSelectionToPasteboard:pasteboard];
1427         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1428         if (dragImage == nil) {
1429             dragImage = [innerHTMLView _selectionDraggingImage];
1430             NSRect draggingRect = [self convertRect:[innerHTMLView _selectionDraggingRect] fromView:innerHTMLView];
1431             dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1432             _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1433             _private->dragOffset.y = dragLoc.y - mouseDownPoint.y;        // inverted because we are flipped
1434         }
1435         [self dragImage:dragImage
1436                      at:dragLoc
1437                  offset:NSZeroSize
1438                   event:_private->mouseDownEvent
1439              pasteboard:pasteboard
1440                  source:self
1441               slideBack:YES];
1442     } else if (srcIsDHTML) {
1443         ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1444         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1445         if (dragImage == nil) {
1446             // WebCore should have given us an image, but we'll make one up
1447             // FIXME: Oops! I removed this image from WebKit. Is this a dead code path?
1448             NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1449             dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1450             NSSize imageSize = [dragImage size];
1451             dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width / 2, mouseDownPoint.y + imageSize.height / 2);
1452             _private->dragOffset.x = imageSize.width / 2;
1453             _private->dragOffset.y = imageSize.height / 2;
1454         }
1455         [self dragImage:dragImage
1456                      at:dragLoc
1457                  offset:NSZeroSize
1458                   event:_private->mouseDownEvent
1459              pasteboard:pasteboard
1460                  source:self
1461               slideBack:YES];
1462     } else {
1463         // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1464         // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1465         startedDrag = NO;
1466     }
1467     return startedDrag;
1468 }
1469
1470 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1471 {
1472     [self autoscroll:event];
1473     [self _startAutoscrollTimer:event];
1474 }
1475
1476 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1477 {
1478     WebHTMLView *topHTMLView = [self _topHTMLView];
1479     if (self != topHTMLView)
1480         return [topHTMLView _mayStartDragAtEventLocation:location];
1481
1482     NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1483     NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint allowShadowContent:YES];
1484
1485     ASSERT([self _webView]);
1486
1487     if ([mouseDownElement objectForKey:WebElementImageKey]
1488             && [mouseDownElement objectForKey:WebElementImageURLKey]
1489             && [[[self _webView] preferences] loadsImagesAutomatically]
1490             && (_private->dragSourceActionMask & WebDragSourceActionImage))
1491         return YES;
1492     
1493     if ([mouseDownElement objectForKey:WebElementLinkURLKey]
1494             && (_private->dragSourceActionMask & WebDragSourceActionLink))
1495         return YES;
1496     
1497     if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue]
1498             && (_private->dragSourceActionMask & WebDragSourceActionSelection))
1499         return YES;
1500     
1501     return NO;
1502 }
1503
1504 - (WebPluginController *)_pluginController
1505 {
1506     return _private->pluginController;
1507 }
1508
1509 - (void)_web_setPrintingModeRecursive
1510 {
1511     [self _setPrinting:YES minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:NO];
1512     [super _web_setPrintingModeRecursive];
1513 }
1514
1515 - (void)_web_clearPrintingModeRecursive
1516 {
1517     [self _setPrinting:NO minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:NO];
1518     [super _web_clearPrintingModeRecursive];
1519 }
1520
1521 - (void)_layoutIfNeeded
1522 {
1523     ASSERT(!_private->subviewsSetAside);
1524
1525     if ([[self _bridge] needsLayout])
1526         _private->needsLayout = YES;
1527     if (_private->needsToApplyStyles || _private->needsLayout)
1528         [self layout];
1529 }
1530
1531 - (void)_web_layoutIfNeededRecursive
1532 {
1533     [self _layoutIfNeeded];
1534     [super _web_layoutIfNeededRecursive];
1535 }
1536
1537 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1538 {
1539     ASSERT(!_private->subviewsSetAside);
1540
1541     displayRect = NSIntersectionRect(displayRect, [self bounds]);
1542     if (testDirtyRect) {
1543         NSRect dirtyRect = [self _dirtyRect];
1544         displayRect = NSIntersectionRect(displayRect, dirtyRect);
1545     }
1546     if (!NSIsEmptyRect(displayRect))
1547         [self _layoutIfNeeded];
1548
1549     [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1550 }
1551
1552 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1553 {
1554     if (_private->autoscrollTimer == nil) {
1555         _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1556             target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1557         _private->autoscrollTriggerEvent = [triggerEvent retain];
1558     }
1559 }
1560
1561 // FIXME: _selectionRect is deprecated in favor of selectionRect, which is in protocol WebDocumentSelection.
1562 // We can't remove this yet because it's still in use by Mail.
1563 - (NSRect)_selectionRect
1564 {
1565     return [self selectionRect];
1566 }
1567
1568 - (void)_stopAutoscrollTimer
1569 {
1570     NSTimer *timer = _private->autoscrollTimer;
1571     _private->autoscrollTimer = nil;
1572     [_private->autoscrollTriggerEvent release];
1573     _private->autoscrollTriggerEvent = nil;
1574     [timer invalidate];
1575     [timer release];
1576 }
1577
1578 - (void)_autoscroll
1579 {
1580     // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1581     // a mouse up event.
1582     BOOL isStillDown = CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft);   
1583     if (!isStillDown){
1584         [self _stopAutoscrollTimer];
1585         return;
1586     }
1587
1588     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1589         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1590         modifierFlags:[[NSApp currentEvent] modifierFlags]
1591         timestamp:[NSDate timeIntervalSinceReferenceDate]
1592         windowNumber:[[self window] windowNumber]
1593         context:[[NSApp currentEvent] context]
1594         eventNumber:0 clickCount:0 pressure:0];
1595     [self mouseDragged:fakeEvent];
1596 }
1597
1598 - (BOOL)_canCopy
1599 {
1600     // Copying can be done regardless of whether you can edit.
1601     return [self _hasSelection] && [[self _bridge] mayCopy];
1602 }
1603
1604 - (BOOL)_canCut
1605 {
1606     return [self _canCopy] && [self _isEditable];
1607 }
1608
1609 - (BOOL)_canDelete
1610 {
1611     return [self _hasSelection] && [self _isEditable];
1612 }
1613
1614 - (BOOL)_canPaste
1615 {
1616     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1617 }
1618
1619 - (BOOL)_canEdit
1620 {
1621     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1622 }
1623
1624 - (BOOL)_canEditRichly
1625 {
1626     return [self _canEdit] && [[self _bridge] isSelectionRichlyEditable];
1627 }
1628
1629 - (BOOL)_canAlterCurrentSelection
1630 {
1631     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1632 }
1633
1634 - (BOOL)_hasSelection
1635 {
1636     return [[self _bridge] selectionState] == WebSelectionStateRange;
1637 }
1638
1639 - (BOOL)_hasSelectionOrInsertionPoint
1640 {
1641     return [[self _bridge] selectionState] != WebSelectionStateNone;
1642 }
1643
1644 - (BOOL)_hasInsertionPoint
1645 {
1646     return [[self _bridge] selectionState] == WebSelectionStateCaret;
1647 }
1648
1649 - (BOOL)_isEditable
1650 {
1651     return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1652 }
1653
1654 - (BOOL)_isSelectionInPasswordField
1655 {
1656     return [[self _bridge] isSelectionInPasswordField];
1657 }
1658
1659 - (BOOL)_isSelectionMisspelled
1660 {
1661     NSString *selectedString = [self selectedString];
1662     unsigned length = [selectedString length];
1663     if (length == 0) {
1664         return NO;
1665     }
1666     NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1667                                                                     startingAt:0
1668                                                                       language:nil
1669                                                                           wrap:NO
1670                                                         inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1671                                                                      wordCount:NULL];
1672     return range.length == length;
1673 }
1674
1675 - (NSArray *)_guessesForMisspelledSelection
1676 {
1677     ASSERT([[self selectedString] length] != 0);
1678     return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1679 }
1680
1681 - (void)_changeSpellingFromMenu:(id)sender
1682 {
1683     ASSERT([[self selectedString] length] != 0);
1684     if ([self _shouldReplaceSelectionWithText:[sender title] givenAction:WebViewInsertActionPasted]) {
1685         [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1686     }
1687 }
1688
1689 - (void)_ignoreSpellingFromMenu:(id)sender
1690 {
1691     ASSERT([[self selectedString] length] != 0);
1692     [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1693 }
1694
1695 - (void)_learnSpellingFromMenu:(id)sender
1696 {
1697     ASSERT([[self selectedString] length] != 0);
1698     [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1699 }
1700
1701 - (void)_lookUpInDictionaryFromMenu:(id)sender
1702 {
1703     // This should only be called when there's a selection, but play it safe.
1704     if (![self _hasSelection]) {
1705         return;
1706     }
1707     
1708     // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1709     static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1710     static const struct mach_header *frameworkImageHeader = NULL;
1711     static BOOL lookedForFunction = NO;
1712     if (!lookedForFunction) {
1713         __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1714         lookedForFunction = YES;
1715     }
1716     if (!__dictionaryServiceWindowShow) {
1717         LOG_ERROR("Couldn't find _DCMDictionaryServiceWindowShow"); 
1718         return;
1719     }
1720     
1721     // FIXME: must check for right-to-left here
1722     NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1723     
1724     NSAttributedString *attrString = [self selectedAttributedString];
1725     // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1726     // the rect for the entire selection, as we do here, positions the pop-up window near
1727     // the bottom of the selection rather than at the selected word.
1728     NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1729     rect.origin = [[self window] convertBaseToScreen:rect.origin];
1730     NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1731     (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1732 }
1733
1734 - (BOOL)_transparentBackground
1735 {
1736     return _private->transparentBackground;
1737 }
1738
1739 - (void)_setTransparentBackground:(BOOL)f
1740 {
1741     _private->transparentBackground = f;
1742 }
1743
1744 - (NSImage *)_selectionDraggingImage
1745 {
1746     if ([self _hasSelection]) {
1747         NSImage *dragImage = [[self _bridge] selectionImageForcingWhiteText:NO];
1748         [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1749         return dragImage;
1750     }
1751     return nil;
1752 }
1753
1754 - (NSRect)_selectionDraggingRect
1755 {
1756     // Mail currently calls this method. We can eliminate it when Mail no longer calls it.
1757     return [self selectionImageRect];
1758 }
1759
1760 - (BOOL)_canIncreaseSelectionListLevel
1761 {
1762     return ([self _canEditRichly] && [[self _bridge] canIncreaseSelectionListLevel]);
1763 }
1764
1765 - (BOOL)_canDecreaseSelectionListLevel
1766 {
1767     return ([self _canEditRichly] && [[self _bridge] canDecreaseSelectionListLevel]);
1768 }
1769
1770 - (DOMNode *)_increaseSelectionListLevel
1771 {
1772     if (![self _canEditRichly])
1773         return nil;
1774         
1775     WebFrameBridge *bridge = [self _bridge];
1776     return [bridge increaseSelectionListLevel];
1777 }
1778
1779 - (DOMNode *)_increaseSelectionListLevelOrdered
1780 {
1781     if (![self _canEditRichly])
1782         return nil;
1783         
1784     WebFrameBridge *bridge = [self _bridge];
1785     return [bridge increaseSelectionListLevelOrdered];
1786 }
1787
1788 - (DOMNode *)_increaseSelectionListLevelUnordered
1789 {
1790     if (![self _canEditRichly])
1791         return nil;
1792         
1793     WebFrameBridge *bridge = [self _bridge];
1794     return [bridge increaseSelectionListLevelUnordered];
1795 }
1796
1797 - (void)_decreaseSelectionListLevel
1798 {
1799     if (![self _canEditRichly])
1800         return;
1801         
1802     WebFrameBridge *bridge = [self _bridge];
1803     [bridge decreaseSelectionListLevel];
1804 }
1805
1806 - (void)_setHighlighter:(id<WebHTMLHighlighter>)highlighter ofType:(NSString*)type
1807 {
1808     if (!_private->highlighters)
1809         _private->highlighters = [[NSMutableDictionary alloc] init];
1810     [_private->highlighters setObject:highlighter forKey:type];
1811 }
1812
1813 - (void)_removeHighlighterOfType:(NSString*)type
1814 {
1815     [_private->highlighters removeObjectForKey:type];
1816 }
1817
1818 - (BOOL)_web_firstResponderCausesFocusDisplay
1819 {
1820     return [self _web_firstResponderIsSelfOrDescendantView] || [[self window] firstResponder] == [self _frameView];
1821 }
1822
1823 - (void)_updateActiveState
1824 {
1825     // This method does the job of updating the view based on the view's firstResponder-ness and
1826     // the window key-ness of the window containing this view. This involves four kinds of 
1827     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
1828     // 
1829     // The four display attributes are as follows:
1830     // 
1831     // 1. The background color used to draw behind selected content (active | inactive color)
1832     // 2. Caret blinking (blinks | does not blink)
1833     // 3. The drawing of a focus ring around links in web pages.
1834     // 4. Changing the tint of controls from clear to aqua/graphite and vice versa
1835     //
1836     // Also, this is responsible for letting the bridge know if the window has gained or lost focus
1837     // so we can send focus and blur events.
1838
1839     NSWindow *window = [self window];
1840     BOOL windowIsKey = [window isKeyWindow];
1841     BOOL windowOrSheetIsKey = windowIsKey || [[window attachedSheet] isKeyWindow];
1842
1843     BOOL isActive = !_private->resigningFirstResponder && windowIsKey && (_private->descendantBecomingFirstResponder || [self _web_firstResponderCausesFocusDisplay]);
1844     
1845     [[self _bridge] setWindowHasFocus:windowOrSheetIsKey];
1846     [[self _bridge] setIsActive:isActive];
1847 }
1848
1849 - (unsigned)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag limit:(unsigned)limit
1850 {
1851     return [[self _bridge] markAllMatchesForText:string caseSensitive:caseFlag limit:limit];
1852 }
1853
1854 - (void)setMarkedTextMatchesAreHighlighted:(BOOL)newValue
1855 {
1856     [[self _bridge] setMarkedTextMatchesAreHighlighted:newValue];
1857 }
1858
1859 - (BOOL)markedTextMatchesAreHighlighted
1860 {
1861     return [[self _bridge] markedTextMatchesAreHighlighted];
1862 }
1863
1864 - (void)unmarkAllTextMatches
1865 {
1866     return [[self _bridge] unmarkAllTextMatches];
1867 }
1868
1869 - (NSArray *)rectsForTextMatches
1870 {
1871     return [[self _bridge] rectsForTextMatches];
1872 }
1873
1874 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1875 {
1876     ASSERT([self _hasSelection]);
1877     NSArray *types = [self pasteboardTypesForSelection];
1878
1879     // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1880     NSAttributedString *attributedString = [self selectedAttributedString];
1881     NSMutableArray *mutableTypes = nil;
1882     if (![attributedString containsAttachments]) {
1883         mutableTypes = [types mutableCopy];
1884         [mutableTypes removeObject:NSRTFDPboardType];
1885         types = mutableTypes;
1886     }
1887
1888     [pasteboard declareTypes:types owner:nil];
1889     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1890     [mutableTypes release];
1891 }
1892
1893 - (void)close
1894 {
1895     if (_private->closed)
1896         return;
1897     [self _clearLastHitViewIfSelf];
1898     // FIXME: This is slow; should remove individual observers instead.
1899     [[NSNotificationCenter defaultCenter] removeObserver:self];
1900     [_private->pluginController destroyAllPlugins];
1901     // remove tooltips before clearing _private so removeTrackingRect: will work correctly
1902     [self removeAllToolTips];
1903     _private->closed = YES;
1904 }
1905
1906 @end
1907
1908 @implementation NSView (WebHTMLViewFileInternal)
1909
1910 - (void)_web_setPrintingModeRecursive
1911 {
1912     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1913 }
1914
1915 - (void)_web_clearPrintingModeRecursive
1916 {
1917     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1918 }
1919
1920 - (void)_web_layoutIfNeededRecursive
1921 {
1922     [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1923 }
1924
1925 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1926 {
1927     unsigned index, count;
1928     for (index = 0, count = [(NSArray *)_subviews count]; index < count; index++) {
1929         NSView *subview = [_subviews objectAtIndex:index];
1930         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1931         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1932     }
1933 }
1934
1935 @end
1936
1937 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1938
1939 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1940 {
1941     if (object == nil) {
1942         [self removeObjectForKey:key];
1943     } else {
1944         [self setObject:object forKey:key];
1945     }
1946 }
1947
1948 @end
1949
1950 // The following is a workaround for
1951 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1952 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1953 // Since the category will be searched before the real class, we'll prevent the flag from being
1954 // set on the tool tip panel.
1955
1956 @interface NSToolTipPanel : NSPanel
1957 @end
1958
1959 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1960 @end
1961
1962 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1963
1964 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1965 {
1966     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1967 }
1968
1969 @end
1970
1971 @interface NSArray (WebHTMLView)
1972 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1973 @end
1974
1975 @implementation WebHTMLView
1976
1977 + (void)initialize
1978 {
1979     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] 
1980                              returnTypes:[[self class] _insertablePasteboardTypes]];
1981     _NSInitializeKillRing();
1982 }
1983
1984 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1985 {
1986     WebPreferences *preferences = [[self _webView] preferences];
1987     // Check for nil because we might not yet have an associated webView when this is called
1988     if (preferences == nil) {
1989         preferences = [WebPreferences standardPreferences];
1990     }
1991     _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1992 }
1993
1994 - (id)initWithFrame:(NSRect)frame
1995 {
1996     self = [super initWithFrame:frame];
1997     if (!self)
1998         return nil;
1999     
2000     // Make all drawing go through us instead of subviews.
2001     if (NSAppKitVersionNumber >= 711) {
2002         [self _setDrawsOwnDescendants:YES];
2003     }
2004     
2005     _private = [[WebHTMLViewPrivate alloc] init];
2006
2007     _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
2008     _private->needsLayout = YES;
2009     [self _resetCachedWebPreferences:nil];
2010     [[NSNotificationCenter defaultCenter] 
2011             addObserver:self selector:@selector(_resetCachedWebPreferences:) 
2012                    name:WebPreferencesChangedNotification object:nil];
2013     
2014     return self;
2015 }
2016
2017 - (void)dealloc
2018 {
2019     // We can't assert that close has already been called because
2020     // this view can be removed from it's superview, even though
2021     // it could be needed later, so close if needed.
2022     [self close];
2023     [_private release];
2024     _private = nil;
2025     [super dealloc];
2026 }
2027
2028 - (void)finalize
2029 {
2030     // We can't assert that close has already been called because
2031     // this view can be removed from it's superview, even though
2032     // it could be needed later, so close if needed.
2033     [self close];
2034     [super finalize];
2035 }
2036
2037 - (IBAction)takeFindStringFromSelection:(id)sender
2038 {
2039     if (![self _hasSelection]) {
2040         NSBeep();
2041         return;
2042     }
2043
2044     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
2045 }
2046
2047 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
2048 {
2049     [pasteboard declareTypes:types owner:nil];
2050     [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
2051     return YES;
2052 }
2053
2054 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
2055 {
2056     if ([[self _bridge] isSelectionRichlyEditable])
2057         [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
2058     else
2059         [self _pasteAsPlainTextWithPasteboard:pasteboard];
2060     return YES;
2061 }
2062
2063 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
2064 {
2065     if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
2066         return self;
2067     } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
2068         return self;
2069     }
2070     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
2071 }
2072
2073 - (void)selectAll:(id)sender
2074 {
2075     [self selectAll];
2076 }
2077
2078 // jumpToSelection is the old name for what AppKit now calls centerSelectionInVisibleArea. Safari
2079 // was using the old jumpToSelection selector in its menu. Newer versions of Safari will us the
2080 // selector centerSelectionInVisibleArea. We'll leave this old selector in place for two reasons:
2081 // (1) compatibility between older Safari and newer WebKit; (2) other WebKit-based applications
2082 // might be using the jumpToSelection: selector, and we don't want to break them.
2083 - (void)jumpToSelection:(id)sender
2084 {
2085     [self centerSelectionInVisibleArea:sender];
2086 }
2087
2088 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
2089 {
2090     SEL action = [item action];
2091     WebFrameBridge *bridge = [self _bridge];
2092
2093     if (action == @selector(changeSpelling:)
2094             || action == @selector(_changeSpellingFromMenu:)
2095             || action == @selector(checkSpelling:)
2096             || action == @selector(complete:)
2097             || action == @selector(deleteBackward:)
2098             || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
2099             || action == @selector(deleteForward:)
2100             || action == @selector(deleteToBeginningOfLine:)
2101             || action == @selector(deleteToBeginningOfParagraph:)
2102             || action == @selector(deleteToEndOfLine:)
2103             || action == @selector(deleteToEndOfParagraph:)
2104             || action == @selector(deleteToMark:)
2105             || action == @selector(deleteWordBackward:)
2106             || action == @selector(deleteWordForward:)
2107             || action == @selector(insertBacktab:)
2108             || action == @selector(insertLineBreak:)
2109             || action == @selector(insertNewline:)
2110             || action == @selector(insertNewlineIgnoringFieldEditor:)
2111             || action == @selector(insertParagraphSeparator:)
2112             || action == @selector(insertTab:)
2113             || action == @selector(insertTabIgnoringFieldEditor:)
2114             || action == @selector(moveBackward:)
2115             || action == @selector(moveBackwardAndModifySelection:)
2116             || action == @selector(moveDown:)
2117             || action == @selector(moveDownAndModifySelection:)
2118             || action == @selector(moveForward:)
2119             || action == @selector(moveForwardAndModifySelection:)
2120             || action == @selector(moveLeft:)
2121             || action == @selector(moveLeftAndModifySelection:)
2122             || action == @selector(moveParagraphBackwardAndModifySelection:)
2123             || action == @selector(moveParagraphForwardAndModifySelection:)
2124             || action == @selector(moveRight:)
2125             || action == @selector(moveRightAndModifySelection:)
2126             || action == @selector(moveToBeginningOfDocument:)
2127             || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
2128             || action == @selector(moveToBeginningOfSentence:)
2129             || action == @selector(moveToBeginningOfSentenceAndModifySelection:)
2130             || action == @selector(moveToBeginningOfLine:)
2131             || action == @selector(moveToBeginningOfLineAndModifySelection:)
2132             || action == @selector(moveToBeginningOfParagraph:)
2133             || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
2134             || action == @selector(moveToEndOfDocument:)
2135             || action == @selector(moveToEndOfDocumentAndModifySelection:)
2136             || action == @selector(moveToEndOfSentence:)
2137             || action == @selector(moveToEndOfSentenceAndModifySelection:)
2138             || action == @selector(moveToEndOfLine:)
2139             || action == @selector(moveToEndOfLineAndModifySelection:)
2140             || action == @selector(moveToEndOfParagraph:)
2141             || action == @selector(moveToEndOfParagraphAndModifySelection:)
2142             || action == @selector(moveUp:)
2143             || action == @selector(moveUpAndModifySelection:)
2144             || action == @selector(moveWordBackward:)
2145             || action == @selector(moveWordBackwardAndModifySelection:)
2146             || action == @selector(moveWordForward:)
2147             || action == @selector(moveWordForwardAndModifySelection:)
2148             || action == @selector(moveWordLeft:)
2149             || action == @selector(moveWordLeftAndModifySelection:)
2150             || action == @selector(moveWordRight:)
2151             || action == @selector(moveWordRightAndModifySelection:)
2152             || action == @selector(pageDown:)
2153             || action == @selector(pageDownAndModifySelection:)
2154             || action == @selector(pageUp:)
2155             || action == @selector(pageUpAndModifySelection:)
2156             || action == @selector(pasteFont:)
2157             || action == @selector(showGuessPanel:)
2158             || action == @selector(transpose:)
2159             || action == @selector(yank:)
2160             || action == @selector(yankAndSelect:)) {
2161         return [self _canEdit];
2162     } else if (action == @selector(changeBaseWritingDirection:)) {
2163         NSMenuItem *menuItem = (NSMenuItem *)item;
2164         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2165             NSWritingDirection writingDirection = [item tag];
2166             if (writingDirection == NSWritingDirectionNatural) {
2167                 [menuItem setState:NO];
2168                 return NO;
2169             }
2170             DOMCSSStyleDeclaration* style = [self _emptyStyle];
2171             [style setDirection:writingDirection == NSWritingDirectionLeftToRight ? @"LTR" : @"RTL"];
2172             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2173         }
2174         return [self _canEdit];
2175     } else if (action == @selector(toggleBaseWritingDirection:)) {
2176         NSMenuItem *menuItem = (NSMenuItem *)item;
2177         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2178             DOMCSSStyleDeclaration* rtl = [self _emptyStyle];
2179             [rtl setDirection:@"RTL"];
2180             // Take control of the title of the menu item, instead of just checking/unchecking it because otherwise
2181             // we don't know what the check would mean.
2182             [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")];
2183         }
2184         return [self _canEdit];
2185     } else if (action == @selector(alignCenter:)
2186             || action == @selector(alignLeft:)
2187             || action == @selector(alignJustified:)
2188             || action == @selector(alignRight:)
2189             || action == @selector(changeAttributes:)
2190             || action == @selector(changeColor:)        
2191             || action == @selector(changeFont:)) {
2192         return [self _canEditRichly];
2193     } else if (action == @selector(capitalizeWord:)
2194                || action == @selector(lowercaseWord:)
2195                || action == @selector(uppercaseWord:)) {
2196         return [self _hasSelection] && [self _isEditable];
2197     } else if (action == @selector(centerSelectionInVisibleArea:)
2198                || action == @selector(jumpToSelection:)
2199                || action == @selector(copyFont:)
2200                || action == @selector(setMark:)) {
2201         return [self _hasSelection] || ([self _isEditable] && [self _hasInsertionPoint]);
2202     } else if (action == @selector(changeDocumentBackgroundColor:)) {
2203         return [[self _webView] isEditable] && [self _canEditRichly];
2204     } else if (action == @selector(copy:)) {
2205         return [bridge mayDHTMLCopy] || [self _canCopy];
2206     } else if (action == @selector(cut:)) {
2207         return [bridge mayDHTMLCut] || [self _canCut];
2208     } else if (action == @selector(delete:)) {
2209         return [self _canDelete];
2210     } else if (action == @selector(_ignoreSpellingFromMenu:)
2211             || action == @selector(_learnSpellingFromMenu:)
2212             || action == @selector(takeFindStringFromSelection:)) {
2213         return [self _hasSelection];
2214     } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:)) {
2215         return [bridge mayDHTMLPaste] || [self _canPaste];
2216     } else if (action == @selector(pasteAsRichText:)) {
2217         return [bridge mayDHTMLPaste] || ([self _canPaste] && [[self _bridge] isSelectionRichlyEditable]);
2218     } else if (action == @selector(performFindPanelAction:)) {
2219         // FIXME: Not yet implemented.
2220         return NO;
2221     } else if (action == @selector(selectToMark:)
2222             || action == @selector(swapWithMark:)) {
2223         return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
2224     } else if (action == @selector(subscript:)) {
2225         NSMenuItem *menuItem = (NSMenuItem *)item;
2226         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2227             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2228             [style setVerticalAlign:@"sub"];
2229             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2230         }
2231         return [self _canEditRichly];
2232     } else if (action == @selector(superscript:)) {
2233         NSMenuItem *menuItem = (NSMenuItem *)item;
2234         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2235             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2236             [style setVerticalAlign:@"super"];
2237             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2238         }
2239         return [self _canEditRichly];
2240     } else if (action == @selector(underline:)) {
2241         NSMenuItem *menuItem = (NSMenuItem *)item;
2242         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2243             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2244             [style setProperty:@"-khtml-text-decorations-in-effect" value:@"underline" priority:@""];
2245             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2246         }
2247         return [self _canEditRichly];
2248     } else if (action == @selector(unscript:)) {
2249         NSMenuItem *menuItem = (NSMenuItem *)item;
2250         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
2251             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2252             [style setVerticalAlign:@"baseline"];
2253             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
2254         }
2255         return [self _canEditRichly];
2256     } else if (action == @selector(_lookUpInDictionaryFromMenu:)) {
2257         return [self _hasSelection];
2258     }
2259     
2260     return YES;
2261 }
2262
2263 - (BOOL)acceptsFirstResponder
2264 {
2265     // Don't accept first responder when we first click on this view.
2266     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
2267     // Do accept first responder at any other time, for example from keyboard events,
2268     // or from calls back from WebCore once we begin mouse-down event handling.
2269     NSEvent *event = [NSApp currentEvent];
2270     if ([event type] == NSLeftMouseDown
2271             && !_private->handlingMouseDownEvent
2272             && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
2273         return NO;
2274     }
2275     return YES;
2276 }
2277
2278 - (BOOL)maintainsInactiveSelection
2279 {
2280     // This method helps to determine whether the WebHTMLView should maintain
2281     // an inactive selection when it's not first responder.
2282     // Traditionally, these views have not maintained such selections,
2283     // clearing them when the view was not first responder. However,
2284     // to fix bugs like this one:
2285     // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even 
2286     //                            when they're not firstResponder"
2287     // it was decided to add a switch to act more like an NSTextView.
2288     id nextResponder = [[self window] _newFirstResponderAfterResigning];
2289
2290     // Predict the case where we are losing first responder status only to
2291     // gain it back again.  Want to keep the selection in that case.
2292     if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2293         id contentView = [nextResponder contentView];
2294         if (contentView) {
2295             nextResponder = contentView;
2296         }
2297     }
2298     if ([nextResponder isKindOfClass:[NSClipView class]]) {
2299         id documentView = [nextResponder documentView];
2300         if (documentView) {
2301             nextResponder = documentView;
2302         }
2303     }
2304
2305     if (nextResponder == self)
2306         return YES;
2307
2308     return [[self _webView] maintainsInactiveSelection] || [[self _bridge] isSelectionEditable];
2309 }
2310
2311 - (void)addMouseMovedObserver
2312 {
2313     if (!_private->dataSource || ![self _isTopHTMLView])
2314         return;
2315
2316     // Unless the Dashboard asks us to do this for all windows, keep an observer going only for the key window.
2317     if (!([[self window] isKeyWindow] || [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]))
2318         return;
2319
2320     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2321         name:WKMouseMovedNotification() object:nil];
2322     [self _frameOrBoundsChanged];
2323 }
2324
2325 - (void)removeMouseMovedObserver
2326 {
2327     // Don't remove the observer if we're running the Dashboard.
2328     // FIXME: Right for the windowDidResignKey: case, but wrong for the viewWillMoveToWindow: case.
2329     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2330         return;
2331
2332     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2333     [[NSNotificationCenter defaultCenter] removeObserver:self
2334         name:WKMouseMovedNotification() object:nil];
2335 }
2336
2337 - (void)addSuperviewObservers
2338 {
2339     // We watch the bounds of our superview, so that we can do a layout when the size
2340     // of the superview changes. This is different from other scrollable things that don't
2341     // need this kind of thing because their layout doesn't change.
2342     
2343     // We need to pay attention to both height and width because our "layout" has to change
2344     // to extend the background the full height of the space and because some elements have
2345     // sizes that are based on the total size of the view.
2346     
2347     NSView *superview = [self superview];
2348     if (superview && [self window]) {
2349         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2350             name:NSViewFrameDidChangeNotification object:superview];
2351         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2352             name:NSViewBoundsDidChangeNotification object:superview];
2353
2354         // In addition to registering for frame/bounds change notifications, call -_frameOrBoundsChanged.
2355         // It will check the current size/scroll against the previous layout's size/scroll.  We need to
2356         // do this here to catch the case where the WebView is laid out at one size, removed from its
2357         // window, resized, and inserted into another window.  Our frame/bounds changed notifications
2358         // will not be sent in that situation, since we only watch for changes while in the view hierarchy.
2359         [self _frameOrBoundsChanged];
2360     }
2361 }
2362
2363 - (void)removeSuperviewObservers
2364 {
2365     NSView *superview = [self superview];
2366     if (superview && [self window]) {
2367         [[NSNotificationCenter defaultCenter] removeObserver:self
2368             name:NSViewFrameDidChangeNotification object:superview];
2369         [[NSNotificationCenter defaultCenter] removeObserver:self
2370             name:NSViewBoundsDidChangeNotification object:superview];
2371     }
2372 }
2373
2374 - (void)addWindowObservers
2375 {
2376     NSWindow *window = [self window];
2377     if (window) {
2378         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2379             name:NSWindowDidBecomeKeyNotification object:nil];
2380         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2381             name:NSWindowDidResignKeyNotification object:nil];
2382         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2383             name:NSWindowWillCloseNotification object:window];
2384     }
2385 }
2386
2387 - (void)removeWindowObservers
2388 {
2389     NSWindow *window = [self window];
2390     if (window) {
2391         [[NSNotificationCenter defaultCenter] removeObserver:self
2392             name:NSWindowDidBecomeKeyNotification object:nil];
2393         [[NSNotificationCenter defaultCenter] removeObserver:self
2394             name:NSWindowDidResignKeyNotification object:nil];
2395         [[NSNotificationCenter defaultCenter] removeObserver:self
2396             name:NSWindowWillCloseNotification object:window];
2397     }
2398 }
2399
2400 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2401 {
2402     [self removeSuperviewObservers];
2403 }
2404
2405 - (void)viewDidMoveToSuperview
2406 {
2407     // Do this here in case the text size multiplier changed when a non-HTML
2408     // view was installed.
2409     if ([self superview] != nil) {
2410         [self _updateTextSizeMultiplier];
2411         [self addSuperviewObservers];
2412     }
2413 }
2414
2415 - (void)viewWillMoveToWindow:(NSWindow *)window
2416 {
2417     // Don't do anything if we aren't initialized.  This happens
2418     // when decoding a WebView.  When WebViews are decoded their subviews
2419     // are created by initWithCoder: and so won't be normally
2420     // initialized.  The stub views are discarded by WebView.
2421     if (_private) {
2422         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2423         [self removeMouseMovedObserver];
2424         [self removeWindowObservers];
2425         [self removeSuperviewObservers];
2426         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2427     
2428         [[self _pluginController] stopAllPlugins];
2429     }
2430 }
2431
2432 - (void)viewDidMoveToWindow
2433 {
2434     // Don't do anything if we aren't initialized.  This happens
2435     // when decoding a WebView.  When WebViews are decoded their subviews
2436     // are created by initWithCoder: and so won't be normally
2437     // initialized.  The stub views are discarded by WebView.
2438     if (_private) {
2439         [self _stopAutoscrollTimer];
2440         if ([self window]) {
2441             _private->lastScrollPosition = [[self superview] bounds].origin;
2442             [self addWindowObservers];
2443             [self addSuperviewObservers];
2444             [self addMouseMovedObserver];
2445
2446             // Schedule this update, rather than making the call right now.
2447             // The reason is that placing the caret in the just-installed view requires
2448             // the HTML/XML document to be available on the WebCore side, but it is not
2449             // at the time this code is running. However, it will be there on the next
2450             // crank of the run loop. Doing this helps to make a blinking caret appear 
2451             // in a new, empty window "automatic".
2452             [self performSelector:@selector(_updateActiveState) withObject:nil afterDelay:0];
2453
2454             [[self _pluginController] startAllPlugins];
2455     
2456             _private->lastScrollPosition = NSZeroPoint;
2457         }
2458     }
2459 }
2460
2461 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2462 {
2463     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2464 }
2465
2466 - (void)viewDidMoveToHostWindow
2467 {
2468     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2469 }
2470
2471
2472 - (void)addSubview:(NSView *)view
2473 {
2474     [super addSubview:view];
2475
2476     if ([WebPluginController isPlugInView:view]) {
2477         [[self _pluginController] addPlugin:view];
2478     }
2479 }
2480
2481 - (void)willRemoveSubview:(NSView *)subview
2482 {
2483     if ([WebPluginController isPlugInView:subview])
2484         [[self _pluginController] destroyPlugin:subview];
2485     [super willRemoveSubview:subview];
2486 }
2487
2488 - (void)reapplyStyles
2489 {
2490     if (!_private->needsToApplyStyles) {
2491         return;
2492     }
2493     
2494 #ifdef _KWQ_TIMING        
2495     double start = CFAbsoluteTimeGetCurrent();
2496 #endif
2497
2498     [[self _bridge] reapplyStylesForDeviceType:
2499         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2500     
2501 #ifdef _KWQ_TIMING        
2502     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2503     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2504 #endif
2505
2506     _private->needsToApplyStyles = NO;
2507 }
2508
2509 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2510 // minPageWidth==0 implies a non-printing layout
2511 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2512 {
2513     [self reapplyStyles];
2514     
2515     // Ensure that we will receive mouse move events.  Is this the best place to put this?
2516     [[self window] setAcceptsMouseMovedEvents: YES];
2517     WKSetNSWindowShouldPostEventNotifications([self window], YES);
2518
2519     if (!_private->needsLayout) {
2520         return;
2521     }
2522
2523 #ifdef _KWQ_TIMING        
2524     double start = CFAbsoluteTimeGetCurrent();
2525 #endif
2526
2527     LOG(View, "%@ doing layout", self);
2528
2529     if (minPageWidth > 0.0) {
2530         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2531     } else {
2532         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2533     }
2534     _private->needsLayout = NO;
2535     
2536     if (!_private->printing) {
2537         // get size of the containing dynamic scrollview, so
2538         // appearance and disappearance of scrollbars will not show up
2539         // as a size change
2540         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2541         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2542             [[self _bridge] sendResizeEvent];
2543             if ([[self _bridge] needsLayout])
2544                 [[self _bridge] forceLayoutAdjustingViewSize:NO];
2545         }
2546         _private->laidOutAtLeastOnce = YES;
2547         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2548         _private->lastLayoutFrameSize = newLayoutFrameSize;
2549     }
2550
2551 #ifdef _KWQ_TIMING        
2552     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2553     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2554 #endif
2555 }
2556
2557 - (void)layout
2558 {
2559     [self layoutToMinimumPageWidth:0.0f maximumPageWidth:0.0f adjustingViewSize:NO];
2560 }
2561
2562 - (NSMenu *)menuForEvent:(NSEvent *)event
2563 {
2564     [_private->compController endRevertingChange:NO moveLeft:NO];
2565
2566     _private->handlingMouseDownEvent = YES;
2567     BOOL handledEvent = [[self _bridge] sendContextMenuEvent:event];
2568     _private->handlingMouseDownEvent = NO;
2569     if (handledEvent)
2570         return nil;
2571
2572     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2573     NSDictionary *element = [self elementAtPoint:point];
2574     return [[self _webView] _menuForElement:element defaultItems:nil];
2575 }
2576
2577 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2578 {
2579     if (![string length])
2580         return NO;
2581
2582     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
2583 }
2584
2585 - (void)deselectText
2586 {
2587     [[self _bridge] deselectText];
2588 }
2589
2590 - (BOOL)isOpaque
2591 {
2592     return [[self _webView] drawsBackground];
2593 }
2594
2595 - (void)setNeedsDisplay:(BOOL)flag
2596 {
2597     LOG(View, "%@ flag = %d", self, (int)flag);
2598     [super setNeedsDisplay: flag];
2599 }
2600
2601 - (void)setNeedsLayout: (BOOL)flag
2602 {
2603     LOG(View, "%@ flag = %d", self, (int)flag);
2604     _private->needsLayout = flag;
2605 }
2606
2607
2608 - (void)setNeedsToApplyStyles: (BOOL)flag
2609 {
2610     LOG(View, "%@ flag = %d", self, (int)flag);
2611     _private->needsToApplyStyles = flag;
2612 }
2613
2614 - (void)drawSingleRect:(NSRect)rect
2615 {
2616     [NSGraphicsContext saveGraphicsState];
2617     NSRectClip(rect);
2618         
2619     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2620
2621     [(WebClipView *)[self superview] setAdditionalClip:rect];
2622
2623     NS_DURING {
2624         if ([self _transparentBackground]) {
2625             [[NSColor clearColor] set];
2626             NSRectFill (rect);
2627         }
2628         
2629         [[self _bridge] drawRect:rect];        
2630         WebView *webView = [self _webView];
2631         [[webView _UIDelegateForwarder] webView:webView didDrawRect:[webView convertRect:rect fromView:self]];
2632         [(WebClipView *)[self superview] resetAdditionalClip];
2633
2634         [NSGraphicsContext restoreGraphicsState];
2635     } NS_HANDLER {
2636         [(WebClipView *)[self superview] resetAdditionalClip];
2637         [NSGraphicsContext restoreGraphicsState];
2638         LOG_ERROR("Exception caught while drawing: %@", localException);
2639         [localException raise];
2640     } NS_ENDHANDLER
2641 }
2642
2643 - (void)drawRect:(NSRect)rect
2644 {
2645     LOG(View, "%@ drawing", self);
2646
2647     const NSRect *rects;
2648     WebNSInteger count;
2649     [self getRectsBeingDrawn:&rects count:&count];
2650
2651     BOOL subviewsWereSetAside = _private->subviewsSetAside;
2652     if (subviewsWereSetAside)
2653         [self _restoreSubviews];
2654
2655 #ifdef _KWQ_TIMING
2656     double start = CFAbsoluteTimeGetCurrent();
2657 #endif
2658
2659     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2660     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2661     // The reason for the workaround is that this method is called explicitly from the code
2662     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2663     const int cRectThreshold = 10;
2664     const float cWastedSpaceThreshold = 0.75f;
2665     BOOL useUnionedRect = (count <= 1) || (count > cRectThreshold);
2666     if (!useUnionedRect) {
2667         // Attempt to guess whether or not we should use the unioned rect or the individual rects.
2668         // We do this by computing the percentage of "wasted space" in the union.  If that wasted space
2669         // is too large, then we will do individual rect painting instead.
2670         float unionPixels = (rect.size.width * rect.size.height);
2671         float singlePixels = 0;
2672         for (int i = 0; i < count; ++i)
2673             singlePixels += rects[i].size.width * rects[i].size.height;
2674         float wastedSpace = 1 - (singlePixels / unionPixels);
2675         if (wastedSpace <= cWastedSpaceThreshold)
2676             useUnionedRect = YES;
2677     }
2678     
2679     if (useUnionedRect)
2680         [self drawSingleRect:rect];
2681     else
2682         for (int i = 0; i < count; ++i)
2683             [self drawSingleRect:rects[i]];
2684
2685 #ifdef _KWQ_TIMING
2686     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2687     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2688 #endif
2689
2690     if (subviewsWereSetAside)
2691         [self _setAsideSubviews];
2692 }
2693
2694 // Turn off the additional clip while computing our visibleRect.
2695 - (NSRect)visibleRect
2696 {
2697     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2698         return [super visibleRect];
2699         
2700     WebClipView *clipView = (WebClipView *)[self superview];
2701
2702     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2703     if (!hasAdditionalClip) {
2704         return [super visibleRect];
2705     }
2706     
2707     NSRect additionalClip = [clipView additionalClip];
2708     [clipView resetAdditionalClip];
2709     NSRect visibleRect = [super visibleRect];
2710     [clipView setAdditionalClip:additionalClip];
2711     return visibleRect;
2712 }
2713
2714 - (BOOL)isFlipped 
2715 {
2716     return YES;
2717 }
2718
2719 - (void)windowDidBecomeKey:(NSNotification *)notification
2720 {
2721     NSWindow *keyWindow = [notification object];
2722
2723     if (keyWindow == [self window])
2724         [self addMouseMovedObserver];
2725
2726     if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet])
2727         [self _updateActiveState];
2728 }
2729
2730 - (void)windowDidResignKey:(NSNotification *)notification
2731 {
2732     NSWindow *formerKeyWindow = [notification object];
2733
2734     if (formerKeyWindow == [self window])
2735         [self removeMouseMovedObserver];
2736
2737     if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) {
2738         [self _updateActiveState];
2739         [_private->compController endRevertingChange:NO moveLeft:NO];
2740     }
2741 }
2742
2743 - (void)windowWillClose:(NSNotification *)notification
2744 {
2745     [_private->compController endRevertingChange:NO moveLeft:NO];
2746     [[self _pluginController] destroyAllPlugins];
2747 }
2748
2749 - (void)scrollWheel:(NSEvent *)event
2750 {
2751     [self retain];
2752     
2753     if (![[self _bridge] sendScrollWheelEvent:event]) {
2754         [[self nextResponder] scrollWheel:event];
2755     }    
2756     
2757     [self release];
2758 }
2759
2760 - (BOOL)_isSelectionEvent:(NSEvent *)event
2761 {
2762     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2763     return [[[self elementAtPoint:point allowShadowContent:YES] objectForKey:WebElementIsSelectedKey] boolValue];
2764 }
2765
2766 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2767 {
2768     NSView *hitView = [self _hitViewForEvent:event];
2769     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2770     
2771     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2772         return YES;
2773     
2774     if (hitHTMLView != nil) {
2775         [hitHTMLView _setMouseDownEvent:event];
2776         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2777         BOOL result = [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2778         [hitHTMLView _setMouseDownEvent:nil];
2779         return result;
2780     } else
2781         return [hitView acceptsFirstMouse:event];
2782 }
2783
2784 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2785 {
2786     NSView *hitView = [self _hitViewForEvent:event];
2787     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2788     if (hitHTMLView != nil) {
2789         [hitHTMLView _setMouseDownEvent:event];
2790         BOOL result = [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2791         [hitHTMLView _setMouseDownEvent:nil];
2792         return result;
2793     } else
2794         return [hitView shouldDelayWindowOrderingForEvent:event];
2795 }
2796
2797 - (void)mouseDown:(NSEvent *)event
2798 {
2799     [self retain];
2800
2801     _private->handlingMouseDownEvent = YES;
2802
2803     // Record the mouse down position so we can determine drag hysteresis.
2804     [self _setMouseDownEvent:event];
2805
2806     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2807     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2808         goto done;
2809
2810     [_private->compController endRevertingChange:NO moveLeft:NO];
2811
2812     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2813     // We don't want to pass them along to KHTML a second time.
2814     if (!([event modifierFlags] & NSControlKeyMask)) {
2815         _private->ignoringMouseDraggedEvents = NO;
2816
2817         // Don't do any mouseover while the mouse is down.
2818         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2819
2820         // Let KHTML get a chance to deal with the event. This will call back to us
2821         // to start the autoscroll timer if appropriate.
2822         [[self _bridge] mouseDown:event];
2823     }
2824
2825 done:
2826     [_private->firstResponderTextViewAtMouseDownTime release];
2827     _private->firstResponderTextViewAtMouseDownTime = nil;
2828
2829     _private->handlingMouseDownEvent = NO;
2830     
2831     [self release];
2832 }
2833
2834 - (void)dragImage:(NSImage *)dragImage
2835                at:(NSPoint)at
2836            offset:(NSSize)offset
2837             event:(NSEvent *)event
2838        pasteboard:(NSPasteboard *)pasteboard
2839            source:(id)source
2840         slideBack:(BOOL)slideBack
2841 {
2842     [self _stopAutoscrollTimer];
2843
2844     WebHTMLView *topHTMLView = [self _topHTMLView];
2845     if (self != topHTMLView) {
2846         [topHTMLView dragImage:dragImage at:[self convertPoint:at toView:topHTMLView]
2847             offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2848         return;
2849     }
2850
2851     WebView *webView = [self _webView];
2852     
2853     [webView _setInitiatedDrag:YES];
2854
2855     // Retain this view during the drag because it may be released before the drag ends.
2856     [self retain];
2857
2858     id UIDelegate = [webView UIDelegate];
2859     // If a delegate takes over the drag but never calls draggedImage: endedAt:, we'll leak the WebHTMLView.
2860     if ([UIDelegate respondsToSelector:@selector(webView:dragImage:at:offset:event:pasteboard:source:slideBack:forView:)])
2861         [UIDelegate webView:webView dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack forView:self];
2862     else
2863         [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2864 }
2865
2866 - (void)mouseDragged:(NSEvent *)event
2867 {
2868     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2869     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2870         return;
2871
2872     [self retain];
2873
2874     if (!_private->ignoringMouseDraggedEvents)
2875         [[self _bridge] mouseDragged:event];
2876
2877     [self release];
2878 }
2879
2880 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2881 {
2882     ASSERT([self _isTopHTMLView]);
2883
2884     if (_private->webCoreDragOp == NSDragOperationNone)
2885         return NSDragOperationGeneric | NSDragOperationCopy;
2886     return _private->webCoreDragOp;
2887 }
2888
2889 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2890 {
2891     ASSERT([self _isTopHTMLView]);
2892
2893     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2894     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2895     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2896 }
2897
2898 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2899 {
2900     ASSERT(![self _webView] || [self _isTopHTMLView]);
2901
2902     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2903     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2904     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2905
2906     _private->initiatedDrag = NO;
2907     [[self _webView] _setInitiatedDrag:NO];
2908     
2909     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2910     _private->ignoringMouseDraggedEvents = YES;
2911     
2912     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2913     // WebCore expects to get balanced down/up's, so we must fake up a mouseup.
2914     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2915                                             location:windowMouseLoc
2916                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2917                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2918                                         windowNumber:[[self window] windowNumber]
2919                                              context:[[NSApp currentEvent] context]
2920                                          eventNumber:0 clickCount:0 pressure:0];
2921     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2922     
2923     // Balance the previous retain from when the drag started.
2924     [self release];
2925 }
2926
2927 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2928 {
2929     ASSERT([self _isTopHTMLView]);
2930     ASSERT(_private->draggingImageURL);
2931
2932     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2933     if (wrapper == nil) {
2934         LOG_ERROR("Failed to create image file. Did the source image change while dragging? (<rdar://problem/4244861>)");
2935         return nil;
2936     }
2937
2938     // FIXME: Report an error if we fail to create a file.
2939     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2940     path = [[NSFileManager defaultManager] _webkit_pathWithUniqueFilenameForPath:path];
2941     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES])
2942         LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2943
2944     return [NSArray arrayWithObject:[path lastPathComponent]];
2945 }
2946
2947 - (void)mouseUp:(NSEvent *)event
2948 {
2949     [self _setMouseDownEvent:nil];
2950
2951     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2952     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2953         return;
2954
2955     [self retain];
2956
2957     [self _stopAutoscrollTimer];
2958     [[self _bridge] mouseUp:event];
2959     [self _updateMouseoverWithFakeEvent];
2960
2961     [self release];
2962 }
2963
2964 - (void)mouseMovedNotification:(NSNotification *)notification
2965 {
2966     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2967 }
2968
2969 // returning YES from this method is the way we tell AppKit that it is ok for this view
2970 // to be in the key loop even when "tab to all controls" is not on.
2971 - (BOOL)needsPanelToBecomeKey
2972 {
2973     return YES;
2974 }
2975
2976 - (NSView *)nextValidKeyView
2977 {
2978     NSView *view = nil;
2979     BOOL lookInsideWebFrameViews = YES;
2980     if ([self isHiddenOrHasHiddenAncestor]) {
2981         lookInsideWebFrameViews = NO;
2982     } else if ([self _frame] == [[self _webView] mainFrame]) {
2983         // Check for case where first responder is last frame in a frameset, and we are
2984         // the top-level documentView.
2985         NSResponder *firstResponder = [[self window] firstResponder];
2986         if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
2987             lookInsideWebFrameViews = NO;
2988         }
2989     }
2990     
2991     if (lookInsideWebFrameViews) {
2992         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2993     }
2994     
2995     if (view == nil) {
2996         view = [super nextValidKeyView];
2997         // If there's no next view wired up, we must be in the last subframe, or we are
2998         // being called at an unusual time when the views have not yet been wired together.
2999         // There's no direct link to the next valid key view; get it from the bridge.
3000         // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
3001         // We'll check for both nil and self in case the AppKit oddness goes away.
3002         // WebFrameView has this same kind of logic for the previousValidKeyView case.
3003         if (view == nil || view == self) {
3004             view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
3005         }
3006     }
3007         
3008     return view;
3009 }
3010
3011 - (NSView *)previousValidKeyView
3012 {
3013     NSView *view = nil;
3014     if (![self isHiddenOrHasHiddenAncestor])
3015         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3016     if (view == nil)
3017         view = [super previousValidKeyView];
3018     return view;
3019 }
3020
3021 - (BOOL)becomeFirstResponder
3022 {
3023     NSView *view = nil;
3024     if (![[self _webView] _isPerformingProgrammaticFocus] && !_private->willBecomeFirstResponderForNodeFocus) {
3025         switch ([[self window] keyViewSelectionDirection]) {
3026             case NSDirectSelection:
3027                 break;
3028             case NSSelectingNext:
3029                 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3030                 break;
3031             case NSSelectingPrevious:
3032                 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3033                 break;
3034         }
3035     }
3036     _private->willBecomeFirstResponderForNodeFocus = NO;
3037     if (view)
3038         [[self window] makeFirstResponder:view];
3039     [self _updateActiveState];
3040     [self _updateFontPanel];
3041     _private->startNewKillRingSequence = YES;
3042     return YES;
3043 }
3044
3045 - (BOOL)resignFirstResponder
3046 {
3047     BOOL resign = [super resignFirstResponder];
3048     if (resign) {
3049         [_private->compController endRevertingChange:NO moveLeft:NO];
3050         _private->resigningFirstResponder = YES;
3051         if (![self maintainsInactiveSelection]) { 
3052             if ([[self _webView] _isPerformingProgrammaticFocus])
3053                 [self deselectText];
3054             else
3055                 [self deselectAll];
3056         }
3057         [self _updateActiveState];
3058         _private->resigningFirstResponder = NO;
3059         _private->willBecomeFirstResponderForNodeFocus = NO;
3060     }
3061     return resign;
3062 }
3063
3064 - (void)setDataSource:(WebDataSource *)dataSource 
3065 {
3066     ASSERT(!_private->dataSource);
3067     _private->dataSource = [dataSource retain];
3068     [_private->pluginController setDataSource:dataSource];
3069     [self addMouseMovedObserver];
3070 }
3071
3072 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3073 {
3074 }
3075
3076 // This is an override of an NSControl method that wants to repaint the entire view when the window resigns/becomes
3077 // key.  WebHTMLView is an NSControl only because it hosts NSCells that are painted by WebCore's Aqua theme
3078 // renderer (and those cells must be hosted by an enclosing NSControl in order to paint properly).
3079 - (void)updateCell:(NSCell*)cell
3080 {
3081 }
3082
3083 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3084 // pageWidth != 0 implies we will relayout to a new width
3085 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3086 {
3087     WebFrame *frame = [self _frame];
3088     NSArray *subframes = [frame childFrames];
3089     unsigned n = [subframes count];
3090     unsigned i;
3091     for (i = 0; i != n; ++i) {
3092         WebFrame *subframe = [subframes objectAtIndex:i];
3093         WebFrameView *frameView = [subframe frameView];
3094         if ([[subframe dataSource] _isDocumentHTML]) {
3095             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:adjustViewSize];
3096         }
3097     }
3098
3099     if (printing != _private->printing) {
3100         [_private->pageRects release];
3101         _private->pageRects = nil;
3102         _private->printing = printing;
3103         [self setNeedsToApplyStyles:YES];
3104         [self setNeedsLayout:YES];
3105         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3106         if (!printing) {
3107             // Can't do this when starting printing or nested printing won't work, see 3491427.
3108             [self setNeedsDisplay:NO];
3109         }
3110     }
3111 }
3112
3113 - (BOOL)canPrintHeadersAndFooters
3114 {
3115     return YES;
3116 }
3117
3118 // This is needed for the case where the webview is embedded in the view that's being printed.
3119 // It shouldn't be called when the webview is being printed directly.
3120 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3121 {
3122     // This helps when we print as part of a larger print process.
3123     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3124     BOOL wasInPrintingMode = _private->printing;
3125     if (!wasInPrintingMode)
3126         [self _setPrinting:YES minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:NO];
3127
3128     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3129     
3130     if (!wasInPrintingMode)
3131         [self _setPrinting:NO minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:NO];
3132 }
3133
3134 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3135 {
3136     NSPrintInfo *printInfo = [printOperation printInfo];
3137     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3138 }
3139
3140 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3141 {
3142     float viewWidth = NSWidth([self bounds]);
3143     if (viewWidth < 1) {
3144         LOG_ERROR("%@ has no width when printing", self);
3145         return 1.0f;
3146     }
3147
3148     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3149     float maxShrinkToFitScaleFactor = 1.0f / PrintingMaximumShrinkFactor;
3150     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3151     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3152 }
3153
3154 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3155 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3156 // if AppKit makes it SPI/API.
3157 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
3158 {
3159     return [self _scaleFactorForPrintOperation:printOperation];
3160 }
3161
3162 // This is used for Carbon printing. At some point we might want to make this public API.
3163 - (void)setPageWidthForPrinting:(float)pageWidth
3164 {
3165     [self _setPrinting:NO minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:NO];
3166     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3167 }
3168
3169 - (void)_endPrintMode
3170 {
3171     [self _setPrinting:NO minimumPageWidth:0.0f maximumPageWidth:0.0f adjustViewSize:YES];
3172     [[self window] setAutodisplay:YES];
3173 }
3174
3175 - (void)_delayedEndPrintMode:(NSPrintOperation *)initiatingOperation
3176 {
3177     ASSERT_ARG(initiatingOperation, initiatingOperation != nil);
3178     NSPrintOperation *currentOperation = [NSPrintOperation currentOperation];
3179     if (initiatingOperation == currentOperation) {
3180         // The print operation is still underway. We don't expect this to ever happen, hence the assert, but we're
3181         // being extra paranoid here since the printing code is so fragile. Delay the cleanup
3182         // further.
3183         ASSERT_NOT_REACHED();
3184         [self performSelector:@selector(_delayedEndPrintMode:) withObject:initiatingOperation afterDelay:0];
3185     } else if ([currentOperation view] == self) {
3186         // A new print job has started, but it is printing the same WebHTMLView again. We don't expect
3187         // this to ever happen, hence the assert, but we're being extra paranoid here since the printing code is so
3188         // fragile. Do nothing, because we don't want to break the print job currently in progress, and
3189         // the print job currently in progress is responsible for its own cleanup.
3190         ASSERT_NOT_REACHED();
3191     } else {
3192         // The print job that kicked off this delayed call has finished, and this view is not being
3193         // printed again. We expect that no other print job has started. Since this delayed call wasn't
3194         // cancelled, beginDocument and endDocument must not have been called, and we need to clean up
3195         // the print mode here.
3196         ASSERT(currentOperation == nil);
3197         [self _endPrintMode];
3198     }
3199 }
3200
3201 // Return the number of pages available for printing
3202 - (BOOL)knowsPageRange:(NSRangePointer)range
3203 {
3204     // Must do this explicit display here, because otherwise the view might redisplay while the print
3205     // sheet was up, using printer fonts (and looking different).
3206     [self displayIfNeeded];
3207     [[self window] setAutodisplay:NO];
3208     
3209     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3210     // according to the paper size
3211     float minLayoutWidth = 0.0f;
3212     float maxLayoutWidth = 0.0f;
3213     if (![[self _bridge] isFrameSet]) {
3214         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3215         minLayoutWidth = paperWidth * PrintingMinimumShrinkFactor;
3216         maxLayoutWidth = paperWidth * PrintingMaximumShrinkFactor;
3217     }
3218     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3219     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3220     // Certain types of errors, including invalid page ranges, can cause beginDocument and
3221     // endDocument to be skipped after we've put ourselves in print mode (see 4145905). In those cases
3222     // we need to get out of print mode without relying on any more callbacks from the printing mechanism.
3223     // If we get as far as beginDocument without trouble, then this delayed request will be cancelled.
3224     // If not cancelled, this delayed call will be invoked in the next pass through the main event loop,
3225     // which is after beginDocument and endDocument would be called.
3226     [self performSelector:@selector(_delayedEndPrintMode:) withObject:printOperation afterDelay:0];
3227     [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3228     
3229     // There is a theoretical chance that someone could do some drawing between here and endDocument,
3230     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3231     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3232
3233     range->location = 1;
3234     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3235     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3236     [_private->pageRects release];
3237     float fullPageHeight = floorf([self _calculatePrintHeight]/totalScaleFactor);
3238     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3239                                                                           printHeight:fullPageHeight];
3240     
3241     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3242     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3243     // a blank page (with correct-looking header and footer if that option is on), which matches
3244     // the behavior of IE and Camino at least.
3245     if ([newPageRects count] == 0)
3246         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect:NSMakeRect(0, 0, 1, 1)]];
3247     else if ([newPageRects count] > 1) {
3248         // If the last page is a short orphan, try adjusting the print height slightly to see if this will squeeze the
3249         // content onto one fewer page. If it does, use the adjusted scale. If not, use the original scale.
3250         float lastPageHeight = NSHeight([[newPageRects lastObject] rectValue]);
3251         if (lastPageHeight/fullPageHeight < LastPrintedPageOrphanRatio) {
3252             NSArray *adjustedPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3253                                                                                        printHeight:fullPageHeight*PrintingOrphanShrinkAdjustment];
3254             // Use the adjusted rects only if the page count went down
3255             if ([adjustedPageRects count] < [newPageRects count])
3256                 newPageRects = adjustedPageRects;
3257         }
3258     }
3259     
3260     _private->pageRects = [newPageRects retain];
3261     
3262     range->length = [_private->pageRects count];
3263     
3264     return YES;
3265 }
3266
3267 // Return the drawing rectangle for a particular page number
3268 - (NSRect)rectForPage:(int)page
3269 {
3270     return [[_private->pageRects objectAtIndex:page - 1] rectValue];
3271 }
3272
3273 - (void)drawPageBorderWithSize:(NSSize)borderSize
3274 {
3275     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
3276     [[self _webView] _drawHeaderAndFooter];
3277 }
3278
3279 - (void)beginDocument
3280 {
3281     NS_DURING
3282         // From now on we'll get a chance to call _endPrintMode in either beginDocument or
3283         // endDocument, so we can cancel the "just in case" pending call.
3284         [NSObject cancelPreviousPerformRequestsWithTarget:self
3285                                                  selector:@selector(_delayedEndPrintMode:)
3286                                                    object:[NSPrintOperation currentOperation]];
3287         [super beginDocument];
3288     NS_HANDLER
3289         // Exception during [super beginDocument] means that endDocument will not get called,
3290         // so we need to clean up our "print mode" here.
3291         [self _endPrintMode];
3292     NS_ENDHANDLER
3293 }
3294
3295 - (void)endDocument
3296 {
3297     [super endDocument];
3298     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
3299     [self _endPrintMode];
3300 }
3301
3302 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3303 {   
3304     // Use WebView's tabKeyCyclesThroughElements state to determine whether or not
3305     // to process tab key events. The idea here is that tabKeyCyclesThroughElements
3306     // will be YES when this WebView is being used in a browser, and we desire the
3307     // behavior where tab moves to the next element in tab order. If tabKeyCyclesThroughElements
3308     // is NO, it is likely that the WebView is being embedded as the whole view, as in Mail,
3309     // and tabs should input tabs as expected in a text editor. Using Option-Tab always cycles
3310     // through elements.
3311
3312     if ([[self _webView] tabKeyCyclesThroughElements] && [event _web_isTabKeyEvent]) 
3313         return NO;
3314
3315     if (![[self _webView] tabKeyCyclesThroughElements] && [event _web_isOptionTabKeyEvent])
3316         return NO;
3317
3318     // Now process the key normally
3319     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3320     return YES;
3321 }
3322
3323 - (void)keyDown:(NSEvent *)event
3324 {
3325     [self retain];
3326
3327     BOOL callSuper = NO;
3328
3329     _private->keyDownEvent = event;
3330
3331     WebFrameBridge *bridge = [self _bridge];
3332     if ([bridge interceptKeyEvent:event toView:self]) {
3333         // WebCore processed a key event, bail on any outstanding complete: UI
3334         [_private->compController endRevertingChange:YES moveLeft:NO];
3335     } else if (_private->compController && [_private->compController filterKeyDown:event]) {
3336         // Consumed by complete: popup window
3337     } else {
3338         // We're going to process a key event, bail on any outstanding complete: UI
3339         [_private->compController endRevertingChange:YES moveLeft:NO];
3340         BOOL handledKey = [self _canEdit] && [self _interceptEditingKeyEvent:event];
3341         if (!handledKey)
3342             callSuper = YES;
3343     }
3344     if (callSuper)
3345         [super keyDown:event];
3346     else
3347         [NSCursor setHiddenUntilMouseMoves:YES];
3348
3349     _private->keyDownEvent = nil;
3350     
3351     [self release];
3352 }
3353
3354 - (void)keyUp:(NSEvent *)event
3355 {
3356     [self retain];
3357     if (![[self _bridge] interceptKeyEvent:event toView:self])
3358         [super keyUp:event];    
3359     [self release];
3360 }
3361
3362 - (id)accessibilityAttributeValue:(NSString*)attributeName
3363 {
3364     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
3365         id accTree = [[self _bridge] accessibilityTree];
3366         if (accTree)
3367             return [NSArray arrayWithObject:accTree];
3368         return nil;
3369     }
3370     return [super accessibilityAttributeValue:attributeName];
3371 }
3372
3373 - (id)accessibilityFocusedUIElement
3374 {
3375     id accTree = [[self _bridge] accessibilityTree];
3376     if (accTree)
3377         return [accTree accessibilityFocusedUIElement];
3378     return self;
3379 }
3380
3381 - (id)accessibilityHitTest:(NSPoint)point
3382 {
3383     id accTree = [[self _bridge] accessibilityTree];
3384     if (accTree) {
3385         NSPoint windowCoord = [[self window] convertScreenToBase:point];
3386         return [accTree accessibilityHitTest:[self convertPoint:windowCoord fromView:nil]];
3387     }
3388     return self;
3389 }
3390
3391 - (id)_accessibilityParentForSubview:(NSView *)subview
3392 {
3393     id accTree = [[self _bridge] accessibilityTree];
3394     if (!accTree)
3395         return self;
3396     id parent = [accTree _accessibilityParentForSubview:subview];
3397     if (!parent)
3398         return self;
3399     return parent;
3400 }
3401
3402 - (void)centerSelectionInVisibleArea:(id)sender
3403 {
3404     [[self _bridge] centerSelectionInVisibleArea];
3405 }
3406
3407 - (void)moveBackward:(id)sender
3408 {
3409     if ([self _canAlterCurrentSelection])
3410         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectByCharacter];
3411 }
3412
3413 - (void)moveBackwardAndModifySelection:(id)sender
3414 {
3415     if ([self _canAlterCurrentSelection])
3416         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectByCharacter];
3417 }
3418
3419 - (void)moveDown:(id)sender
3420 {
3421     if ([self _canAlterCurrentSelection])
3422         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectByLine];
3423 }
3424
3425 - (void)moveDownAndModifySelection:(id)sender
3426 {
3427     if ([self _canAlterCurrentSelection])
3428         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectByLine];
3429 }
3430
3431 - (void)moveForward:(id)sender
3432 {
3433     if ([self _canAlterCurrentSelection])
3434         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectByCharacter];
3435 }
3436
3437 - (void)moveForwardAndModifySelection:(id)sender
3438 {
3439     if ([self _canAlterCurrentSelection])
3440         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectByCharacter];
3441 }
3442
3443 - (void)moveLeft:(id)sender
3444 {
3445     if ([self _canAlterCurrentSelection])
3446         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectLeft granularity:WebBridgeSelectByCharacter];
3447 }
3448
3449 - (void)moveLeftAndModifySelection:(id)sender
3450 {
3451     if ([self _canAlterCurrentSelection])
3452         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectLeft granularity:WebBridgeSelectByCharacter];
3453 }
3454
3455 - (void)moveRight:(id)sender
3456 {
3457     if ([self _canAlterCurrentSelection])
3458         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectRight granularity:WebBridgeSelectByCharacter];
3459 }
3460
3461 - (void)moveRightAndModifySelection:(id)sender
3462 {
3463     if ([self _canAlterCurrentSelection])
3464         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectRight granularity:WebBridgeSelectByCharacter];
3465 }
3466
3467 - (void)moveToBeginningOfDocument:(id)sender
3468 {
3469     if ([self _canAlterCurrentSelection])
3470         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToDocumentBoundary];
3471 }
3472
3473 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3474 {
3475     if ([self _canAlterCurrentSelection])
3476         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToDocumentBoundary];
3477 }
3478
3479 - (void)moveToBeginningOfSentence:(id)sender
3480 {
3481     if ([self _canAlterCurrentSelection])
3482         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToSentenceBoundary];
3483 }
3484
3485 - (void)moveToBeginningOfSentenceAndModifySelection:(id)sender
3486 {
3487     if ([self _canAlterCurrentSelection])
3488         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToSentenceBoundary];
3489 }
3490
3491 - (void)moveToBeginningOfLine:(id)sender
3492 {
3493     if ([self _canAlterCurrentSelection])
3494         [[self _bridge] alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToLineBoundary];
3495 }
3496
3497 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3498 {
3499     if ([self _canAlterCurrentSelection])
3500         [[self _bridge] alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToLineBoundary];
3501 }
3502
3503 - (void)moveToBeginningOfParagraph:(id)sender