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