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