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