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