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