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