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