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