WebKit:
[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/WebDefaultUIDelegate.h>
42 #import <WebKit/WebDocumentInternal.h>
43 #import <WebKit/WebDOMOperationsPrivate.h>
44 #import <WebKit/WebEditingDelegate.h>
45 #import <WebKit/WebFramePrivate.h>
46 #import <WebKit/WebFrameInternal.h>
47 #import <WebKit/WebFrameViewInternal.h>
48 #import <WebKit/WebHTMLViewInternal.h>
49 #import <WebKit/WebHTMLRepresentationPrivate.h>
50 #import <WebKit/WebImageRenderer.h>
51 #import <WebKit/WebImageRendererFactory.h>
52 #import <WebKit/WebKitLogging.h>
53 #import <WebKit/WebKitNSStringExtras.h>
54 #import <WebKit/WebNetscapePluginEmbeddedView.h>
55 #import <WebKit/WebNSAttributedStringExtras.h>
56 #import <WebKit/WebNSEventExtras.h>
57 #import <WebKit/WebNSFileManagerExtras.h>
58 #import <WebKit/WebNSImageExtras.h>
59 #import <WebKit/WebNSObjectExtras.h>
60 #import <WebKit/WebNSPasteboardExtras.h>
61 #import <WebKit/WebNSPrintOperationExtras.h>
62 #import <WebKit/WebNSURLExtras.h>
63 #import <WebKit/WebNSViewExtras.h>
64 #import <WebKit/WebPluginController.h>
65 #import <WebKit/WebPreferences.h>
66 #import <WebKit/WebPreferencesPrivate.h>
67 #import <WebKit/WebResourcePrivate.h>
68 #import <WebKit/WebStringTruncator.h>
69 #import <WebKit/WebTextRenderer.h>
70 #import <WebKit/WebTextRendererFactory.h>
71 #import <WebKit/WebUIDelegatePrivate.h>
72 #import <WebKit/WebViewInternal.h>
73 #import <WebKit/WebViewPrivate.h>
74 #import <WebKitSystemInterface.h>
75 #import <WebCore/WebCoreImageRenderer.h>
76
77 #import <AppKit/NSAccessibility.h>
78
79 // Included so usage of _NSSoftLinkingGetFrameworkFuncPtr will compile
80 #import <mach-o/dyld.h> 
81
82
83 // need to declare this because AppKit does not make it available as API or SPI
84 extern NSString *NSMarkedClauseSegmentAttributeName; 
85 extern NSString *NSTextInputReplacementRangeAttributeName; 
86
87 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
88 void _NSInitializeKillRing(void);
89 void _NSAppendToKillRing(NSString *);
90 void _NSPrependToKillRing(NSString *);
91 NSString *_NSYankFromKillRing(void);
92 NSString *_NSYankPreviousFromKillRing(void);
93 void _NSNewKillRingSequence(void);
94 void _NSSetKillRingToYankedState(void);
95 void _NSResetKillRingOperationFlag(void);
96
97 @interface NSView (AppKitSecretsIKnowAbout)
98 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
99 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
100 - (NSRect)_dirtyRect;
101 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
102 - (void)_propagateDirtyRectsToOpaqueAncestors;
103 @end
104
105 @interface NSApplication (AppKitSecretsIKnowAbout)
106 - (void)speakString:(NSString *)string;
107 @end
108
109 @interface NSWindow (AppKitSecretsIKnowAbout)
110 - (id)_newFirstResponderAfterResigning;
111 @end
112
113 @interface NSAttributedString (AppKitSecretsIKnowAbout)
114 - (id)_initWithDOMRange:(DOMRange *)domRange;
115 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
116 @end
117
118 @interface NSSpellChecker (CurrentlyPrivateForTextView)
119 - (void)learnWord:(NSString *)word;
120 @end
121
122 // By imaging to a width a little wider than the available pixels,
123 // thin pages will be scaled down a little, matching the way they
124 // print in IE and Camino. This lets them use fewer sheets than they
125 // would otherwise, which is presumably why other browsers do this.
126 // Wide pages will be scaled down more than this.
127 #define PrintingMinimumShrinkFactor     1.25
128
129 // This number determines how small we are willing to reduce the page content
130 // in order to accommodate the widest line. If the page would have to be
131 // reduced smaller to make the widest line fit, we just clip instead (this
132 // behavior matches MacIE and Mozilla, at least)
133 #define PrintingMaximumShrinkFactor     2.0
134
135 #define AUTOSCROLL_INTERVAL             0.1
136
137 #define DRAG_LABEL_BORDER_X             4.0
138 #define DRAG_LABEL_BORDER_Y             2.0
139 #define DRAG_LABEL_RADIUS               5.0
140 #define DRAG_LABEL_BORDER_Y_OFFSET              2.0
141
142 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP        120.0
143 #define MAX_DRAG_LABEL_WIDTH                    320.0
144
145 #define DRAG_LINK_LABEL_FONT_SIZE   11.0
146 #define DRAG_LINK_URL_FONT_SIZE   10.0
147
148 // Any non-zero value will do, but using something recognizable might help us debug some day.
149 #define TRACKING_RECT_TAG 0xBADFACE
150
151 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
152 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
153
154 #define STANDARD_WEIGHT 5
155 #define MIN_BOLD_WEIGHT 9
156 #define STANDARD_BOLD_WEIGHT 10
157
158 typedef enum {
159     deleteSelectionAction,
160     deleteKeyAction,
161     forwardDeleteKeyAction
162 } WebDeletionAction;
163
164 // if YES, do the standard NSView hit test (which can't give the right result when HTML overlaps a view)
165 static BOOL forceNSViewHitTest = NO;
166
167 // 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])
168 static BOOL forceWebHTMLViewHitTest = NO;
169
170 // Used to avoid linking with ApplicationServices framework for _DCMDictionaryServiceWindowShow
171 void *_NSSoftLinkingGetFrameworkFuncPtr(NSString *inUmbrellaFrameworkName,
172                                         NSString *inFrameworkName,
173                                         const char *inFuncName,
174                                         const struct mach_header **ioCachedFrameworkImageHeaderPtr);
175
176
177 @interface WebHTMLView (WebTextSizing) <_WebDocumentTextSizing>
178 @end
179
180 @interface WebHTMLView (WebHTMLViewFileInternal)
181 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
182 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText;
183 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
184 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
185 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
186 - (float)_calculatePrintHeight;
187 - (void)_updateTextSizeMultiplier;
188 - (DOMRange *)_selectedRange;
189 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
190 - (void)_deleteRange:(DOMRange *)range 
191             killRing:(BOOL)killRing 
192              prepend:(BOOL)prepend 
193        smartDeleteOK:(BOOL)smartDeleteOK
194       deletionAction:(WebDeletionAction)deletionAction;
195 - (void)_deleteSelection;
196 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
197 - (NSView *)_hitViewForEvent:(NSEvent *)event;
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 @end
631
632 @implementation WebHTMLView (WebPrivate)
633
634 - (void)_reset
635 {
636     [WebImageRenderer stopAnimationsInView:self];
637 }
638
639 + (NSArray *)supportedMIMETypes
640 {
641     return [WebHTMLRepresentation supportedMIMETypes];
642 }
643
644 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
645 {
646     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
647         location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
648         modifierFlags:[flagsChangedEvent modifierFlags]
649         timestamp:[flagsChangedEvent timestamp]
650         windowNumber:[flagsChangedEvent windowNumber]
651         context:[flagsChangedEvent context]
652         eventNumber:0 clickCount:0 pressure:0];
653
654     // Pretend it's a mouse move.
655     [[NSNotificationCenter defaultCenter]
656         postNotificationName:WKMouseMovedNotification() object:self
657         userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
658 }
659
660 - (void)_updateMouseoverWithFakeEvent
661 {
662     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
663         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
664         modifierFlags:[[NSApp currentEvent] modifierFlags]
665         timestamp:[NSDate timeIntervalSinceReferenceDate]
666         windowNumber:[[self window] windowNumber]
667         context:[[NSApp currentEvent] context]
668         eventNumber:0 clickCount:0 pressure:0];
669     
670     [self _updateMouseoverWithEvent:fakeEvent];
671 }
672
673 - (void)_frameOrBoundsChanged
674 {
675     if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
676         [self setNeedsLayout:YES];
677         [self setNeedsDisplay:YES];
678         [_private->compController endRevertingChange:NO moveLeft:NO];
679     }
680
681     NSPoint origin = [[self superview] bounds].origin;
682     if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
683         [[self _bridge] sendScrollEvent];
684         [_private->compController endRevertingChange:NO moveLeft:NO];
685     }
686     _private->lastScrollPosition = origin;
687
688     SEL selector = @selector(_updateMouseoverWithFakeEvent);
689     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
690     [self performSelector:selector withObject:nil afterDelay:0];
691 }
692
693 - (void)_setAsideSubviews
694 {
695     ASSERT(!_private->subviewsSetAside);
696     ASSERT(_private->savedSubviews == nil);
697     _private->savedSubviews = _subviews;
698     _subviews = nil;
699     _private->subviewsSetAside = YES;
700  }
701  
702  - (void)_restoreSubviews
703  {
704     ASSERT(_private->subviewsSetAside);
705     ASSERT(_subviews == nil);
706     _subviews = _private->savedSubviews;
707     _private->savedSubviews = nil;
708     _private->subviewsSetAside = NO;
709 }
710
711 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
712 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
713 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
714 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
715 // need to be redrawn (in case the layout causes some things to get dirtied).
716 - (void)_propagateDirtyRectsToOpaqueAncestors
717 {
718     if (![[self _webView] drawsBackground]) {
719         [self _web_layoutIfNeededRecursive];
720     }
721     [super _propagateDirtyRectsToOpaqueAncestors];
722 }
723
724 // Don't let AppKit even draw subviews. We take care of that.
725 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
726 {
727     // This helps when we print as part of a larger print process.
728     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
729     BOOL wasInPrintingMode = _private->printing;
730     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
731     if (wasInPrintingMode != isPrinting) {
732         if (isPrinting) {
733             [self _web_setPrintingModeRecursive];
734         } else {
735             [self _web_clearPrintingModeRecursive];
736         }
737     }
738
739     [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
740     [_subviews makeObjectsPerformSelector:@selector(_propagateDirtyRectsToOpaqueAncestors)];
741
742     [self _setAsideSubviews];
743     [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
744         rectIsVisibleRectForView:visibleView topView:topView];
745     [self _restoreSubviews];
746
747     if (wasInPrintingMode != isPrinting) {
748         if (wasInPrintingMode) {
749             [self _web_setPrintingModeRecursive];
750         } else {
751             [self _web_clearPrintingModeRecursive];
752         }
753     }
754 }
755
756 // Don't let AppKit even draw subviews. We take care of that.
757 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
758 {
759     BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
760
761     BOOL wasInPrintingMode = _private->printing;
762     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
763
764     if (needToSetAsideSubviews) {
765         // This helps when we print as part of a larger print process.
766         // If the WebHTMLView itself is what we're printing, then we will never have to do this.
767         if (wasInPrintingMode != isPrinting) {
768             if (isPrinting) {
769                 [self _web_setPrintingModeRecursive];
770             } else {
771                 [self _web_clearPrintingModeRecursive];
772             }
773         }
774
775         NSRect boundsBeforeLayout = [self bounds];
776         [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
777
778         // If layout changes the view's bounds, then we need to recompute the visRect.
779         // That's because the visRect passed to us was based on the bounds at the time
780         // we were called. This method is only displayed to draw "all", so it's safe
781         // to just call visibleRect to compute the entire rectangle.
782         if (!NSEqualRects(boundsBeforeLayout, [self bounds])) {
783             visRect = [self visibleRect];
784         }
785
786         [self _setAsideSubviews];
787     }
788     
789     [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
790     
791     if (needToSetAsideSubviews) {
792         if (wasInPrintingMode != isPrinting) {
793             if (wasInPrintingMode) {
794                 [self _web_setPrintingModeRecursive];
795             } else {
796                 [self _web_clearPrintingModeRecursive];
797             }
798         }
799
800         [self _restoreSubviews];
801     }
802 }
803
804 - (BOOL)_insideAnotherHTMLView
805 {
806     NSView *view = self;
807     while ((view = [view superview])) {
808         if ([view isKindOfClass:[WebHTMLView class]]) {
809             return YES;
810         }
811     }
812     return NO;
813 }
814
815 - (void)scrollPoint:(NSPoint)point
816 {
817     // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
818     // If we get called during the handling of a key down event, we assume the call came from
819     // NSTextView, and ignore it and use our own code to decide how to page up and page down
820     // We are smarter about how far to scroll, and we have "superview scrolling" logic.
821     NSEvent *event = [[self window] currentEvent];
822     if ([event type] == NSKeyDown) {
823         const unichar pageUp = NSPageUpFunctionKey;
824         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
825             [self tryToPerform:@selector(scrollPageUp:) with:nil];
826             return;
827         }
828         const unichar pageDown = NSPageDownFunctionKey;
829         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
830             [self tryToPerform:@selector(scrollPageDown:) with:nil];
831             return;
832         }
833     }
834     
835     [super scrollPoint:point];
836 }
837
838 - (NSView *)hitTest:(NSPoint)point
839 {
840     // WebHTMLView objects handle all events for objects inside them.
841     // To get those events, we prevent hit testing from AppKit.
842
843     // But there are three exceptions to this:
844     //   1) For right mouse clicks and control clicks we don't yet have an implementation
845     //      that works for nested views, so we let the hit testing go through the
846     //      standard NSView code path (needs to be fixed, see bug 4361618).
847     //   2) Java depends on doing a hit test inside it's mouse moved handling,
848     //      so we let the hit testing go through the standard NSView code path
849     //      when the current event is a mouse move (except when we are calling
850     //      from _updateMouseoverWithEvent, so we have to use a global,
851     //      forceWebHTMLViewHitTest, for that)
852     //   3) The acceptsFirstMouse: and shouldDelayWindowOrderingForEvent: methods
853     //      both need to figure out which view to check with inside the WebHTMLView.
854     //      They use a global to change the behavior of hitTest: so they can get the
855     //      right view. The global is forceNSViewHitTest and the method they use to
856     //      do the hit testing is _hitViewForEvent:. (But this does not work correctly
857     //      when there is HTML overlapping the view, see bug 4361626)
858     //   4) NSAccessibilityHitTest relies on this for checking the cursor position.
859     //      Our check for that is whether the event is NSFlagsChanged.  This works
860     //      for VoiceOver's cntl-opt-f5 command (move focus to item under cursor)
861     //      and Dictionary's cmd-cntl-D (open dictionary popup for item under cursor).
862     //      This is of course a hack.
863
864     BOOL captureHitsOnSubviews;
865     if (forceNSViewHitTest)
866         captureHitsOnSubviews = NO;
867     else if (forceWebHTMLViewHitTest)
868         captureHitsOnSubviews = YES;
869     else {
870         NSEvent *event = [[self window] currentEvent];
871         captureHitsOnSubviews = !([event type] == NSMouseMoved
872             || [event type] == NSRightMouseDown
873             || ([event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) != 0)
874             || [event type] == NSFlagsChanged);
875     }
876
877     if (!captureHitsOnSubviews)
878         return [super hitTest:point];
879     if ([[self superview] mouse:point inRect:[self frame]])
880         return self;
881     return nil;
882 }
883
884 static WebHTMLView *lastHitView = nil;
885
886 - (void)_clearLastHitViewIfSelf
887 {
888     if (lastHitView == self) {
889         lastHitView = nil;
890     }
891 }
892
893 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
894 {
895     ASSERT(_private->trackingRectOwner == nil);
896     _private->trackingRectOwner = owner;
897     _private->trackingRectUserData = data;
898     return TRACKING_RECT_TAG;
899 }
900
901 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
902 {
903     ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
904     ASSERT(_private->trackingRectOwner == nil);
905     _private->trackingRectOwner = owner;
906     _private->trackingRectUserData = data;
907     return TRACKING_RECT_TAG;
908 }
909
910 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
911 {
912     ASSERT(count == 1);
913     ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
914     ASSERT(_private->trackingRectOwner == nil);
915     _private->trackingRectOwner = owner;
916     _private->trackingRectUserData = userDataList[0];
917     trackingNums[0] = TRACKING_RECT_TAG;
918 }
919
920 - (void)removeTrackingRect:(NSTrackingRectTag)tag
921 {
922     if (tag == 0)
923         return;
924     ASSERT(tag == TRACKING_RECT_TAG);
925     if (_private != nil) {
926         _private->trackingRectOwner = nil;
927     }
928 }
929
930 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
931 {
932     int i;
933     for (i = 0; i < count; ++i) {
934         int tag = tags[i];
935         if (tag == 0)
936             continue;
937         ASSERT(tag == TRACKING_RECT_TAG);
938         if (_private != nil) {
939             _private->trackingRectOwner = nil;
940         }
941     }
942 }
943
944 - (void)_sendToolTipMouseExited
945 {
946     // Nothing matters except window, trackingNumber, and userData.
947     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
948         location:NSMakePoint(0, 0)
949         modifierFlags:0
950         timestamp:0
951         windowNumber:[[self window] windowNumber]
952         context:NULL
953         eventNumber:0
954         trackingNumber:TRACKING_RECT_TAG
955         userData:_private->trackingRectUserData];
956     [_private->trackingRectOwner mouseExited:fakeEvent];
957 }
958
959 - (void)_sendToolTipMouseEntered
960 {
961     // Nothing matters except window, trackingNumber, and userData.
962     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
963         location:NSMakePoint(0, 0)
964         modifierFlags:0
965         timestamp:0
966         windowNumber:[[self window] windowNumber]
967         context:NULL
968         eventNumber:0
969         trackingNumber:TRACKING_RECT_TAG
970         userData:_private->trackingRectUserData];
971     [_private->trackingRectOwner mouseEntered:fakeEvent];
972 }
973
974 - (void)_setToolTip:(NSString *)string
975 {
976     NSString *toolTip = [string length] == 0 ? nil : string;
977     NSString *oldToolTip = _private->toolTip;
978     if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
979         return;
980     }
981     if (oldToolTip) {
982         [self _sendToolTipMouseExited];
983         [oldToolTip release];
984     }
985     _private->toolTip = [toolTip copy];
986     if (toolTip) {
987         [self removeAllToolTips];
988         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
989         [self addToolTipRect:wideOpenRect owner:self userData:NULL];
990         [self _sendToolTipMouseEntered];
991     }
992 }
993
994 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
995 {
996     return [[_private->toolTip copy] autorelease];
997 }
998
999 - (void)_updateMouseoverWithEvent:(NSEvent *)event
1000 {
1001     NSView *contentView = [[event window] contentView];
1002     NSPoint locationForHitTest = [[contentView superview] convertPoint:[event locationInWindow] fromView:nil];
1003     
1004     forceWebHTMLViewHitTest = YES;
1005     NSView *hitView = [contentView hitTest:locationForHitTest];
1006     forceWebHTMLViewHitTest = NO;
1007     
1008     WebHTMLView *view = nil;
1009     if ([hitView isKindOfClass:[WebHTMLView class]]) 
1010         view = (WebHTMLView *)hitView; 
1011
1012     if (view)
1013         [view retain];
1014
1015     if (lastHitView != view && lastHitView != nil) {
1016         // If we are moving out of a view (or frame), let's pretend the mouse moved
1017         // all the way out of that view. But we have to account for scrolling, because
1018         // khtml doesn't understand our clipping.
1019         NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
1020         float yScroll = visibleRect.origin.y;
1021         float xScroll = visibleRect.origin.x;
1022
1023         event = [NSEvent mouseEventWithType:NSMouseMoved
1024                          location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1025                          modifierFlags:[[NSApp currentEvent] modifierFlags]
1026                          timestamp:[NSDate timeIntervalSinceReferenceDate]
1027                          windowNumber:[[view window] windowNumber]
1028                          context:[[NSApp currentEvent] context]
1029                          eventNumber:0 clickCount:0 pressure:0];
1030         [[lastHitView _bridge] mouseMoved:event];
1031     }
1032
1033     lastHitView = view;
1034
1035     if (view) {
1036         [[view _bridge] mouseMoved:event];
1037
1038         NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1039         NSDictionary *element = [view elementAtPoint:point];
1040
1041         // Have the web view send a message to the delegate so it can do status bar display.
1042         [[view _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1043
1044         // Set a tool tip; it won't show up right away but will if the user pauses.
1045         NSString *newToolTip = nil;
1046         if (_private->showsURLsInToolTips) {
1047             DOMHTMLElement *domElement = [element objectForKey:WebElementDOMNodeKey];
1048             if ([domElement isKindOfClass:[DOMHTMLInputElement class]]) {
1049                 if ([[(DOMHTMLInputElement *)domElement type] isEqualToString:@"submit"])
1050                     newToolTip = [[(DOMHTMLInputElement *) domElement form] action];
1051             }
1052             if (newToolTip == nil)
1053                 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
1054         }
1055         if (newToolTip == nil)
1056             newToolTip = [element objectForKey:WebCoreElementTitleKey];
1057         [view _setToolTip:newToolTip];
1058
1059         [view release];
1060     }
1061 }
1062
1063 + (NSArray *)_insertablePasteboardTypes
1064 {
1065     static NSArray *types = nil;
1066     if (!types) {
1067         types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1068             NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType, 
1069             NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1070     }
1071     return types;
1072 }
1073
1074 + (NSArray *)_selectionPasteboardTypes
1075 {
1076     // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1077     return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1078 }
1079
1080 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1081 {
1082     NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1083
1084     BOOL drawURLString = YES;
1085     BOOL clipURLString = NO, clipLabelString = NO;
1086     
1087     NSString *label = [element objectForKey: WebElementLinkLabelKey];
1088     NSString *urlString = [linkURL _web_userVisibleString];
1089     
1090     if (!label) {
1091         drawURLString = NO;
1092         label = urlString;
1093     }
1094     
1095     NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1096                                                    toHaveTrait:NSBoldFontMask];
1097     NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1098     NSSize labelSize;
1099     labelSize.width = [label _web_widthWithFont: labelFont];
1100     labelSize.height = [labelFont ascender] - [labelFont descender];
1101     if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1102         labelSize.width = MAX_DRAG_LABEL_WIDTH;
1103         clipLabelString = YES;
1104     }
1105     
1106     NSSize imageSize, urlStringSize;
1107     imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
1108     imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
1109     if (drawURLString) {
1110         urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1111         urlStringSize.height = [urlFont ascender] - [urlFont descender];
1112         imageSize.height += urlStringSize.height;
1113         if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1114             imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1115             clipURLString = YES;
1116         } else {
1117             imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
1118         }
1119     }
1120     NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1121     [dragImage lockFocus];
1122     
1123     [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
1124     
1125     // Drag a rectangle with rounded corners/
1126     NSBezierPath *path = [NSBezierPath bezierPath];
1127     [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1128     [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1129     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1130     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1131     
1132     [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
1133     [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1134     [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1135     [path fill];
1136         
1137     NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
1138     NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
1139     if (drawURLString) {
1140         if (clipURLString)
1141             urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
1142
1143         [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
1144              withTopColor:topColor bottomColor:bottomColor font:urlFont];
1145     }
1146
1147     if (clipLabelString)
1148         label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
1149     [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1150              withTopColor:topColor bottomColor:bottomColor font:labelFont];
1151     
1152     [dragImage unlockFocus];
1153     
1154     return dragImage;
1155 }
1156
1157 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1158 {
1159     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1160     NSDictionary *element = [self elementAtPoint:mouseDownPoint];
1161
1162     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1163     NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1164     BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1165
1166     [_private->draggingImageURL release];
1167     _private->draggingImageURL = nil;
1168
1169     NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1170     _private->webCoreDragOp = op;     // will be DragNone if WebCore doesn't care
1171     NSImage *dragImage = nil;
1172     NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1173
1174     // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1175     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1176     // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1177     if (wcDragImage) {
1178         dragImage = wcDragImage;
1179         // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1180         // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1181         if (linkURL) {
1182             // see HACK below
1183             dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1184         } else {
1185             dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1186         }
1187         _private->dragOffset = wcDragLoc;
1188     }
1189     
1190     WebView *webView = [self _webView];
1191     NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1192     BOOL startedDrag = YES;  // optimism - we almost always manage to start the drag
1193
1194     // note per kwebster, the offset arg below is always ignored in positioning the image
1195     DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1196     if (imageURL != nil && [imageElement _image] != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1197         id source = self;
1198         if (!dhtmlWroteData) {
1199             // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1200             ASSERT(imageElement != nil);
1201             [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityDownstream];
1202             _private->draggingImageURL = [imageURL retain];
1203             source = [pasteboard _web_declareAndWriteDragImage:nil
1204                                                        element:imageElement
1205                                                            URL:linkURL ? linkURL : imageURL
1206                                                          title:[element objectForKey:WebElementImageAltStringKey]
1207                                                        archive:[imageElement webArchive]
1208                                                         source:self];
1209         }
1210         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1211         if (dragImage == nil) {
1212             [self _web_dragImage:nil
1213                          element:[element objectForKey:WebElementDOMNodeKey]
1214                             rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1215                            event:_private->mouseDownEvent
1216                       pasteboard:pasteboard
1217                           source:source
1218                           offset:&_private->dragOffset];
1219         } else {
1220             [self dragImage:dragImage
1221                          at:dragLoc
1222                      offset:NSZeroSize
1223                       event:_private->mouseDownEvent
1224                  pasteboard:pasteboard
1225                      source:source
1226                   slideBack:YES];
1227         }
1228     } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1229         if (!dhtmlWroteData) {
1230             NSArray *types = [NSPasteboard _web_writableTypesForURL];
1231             [pasteboard declareTypes:types owner:self];
1232             [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];            
1233         }
1234         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1235         if (dragImage == nil) {
1236             dragImage = [self _dragImageForLinkElement:element];
1237             NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1238             dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1239             _private->dragOffset.x = offset.width;
1240             _private->dragOffset.y = -offset.height;        // inverted because we are flipped
1241         }
1242         // HACK:  We should pass the mouseDown event instead of the mouseDragged!  This hack gets rid of
1243         // a flash of the image at the mouseDown location when the drag starts.
1244         [self dragImage:dragImage
1245                      at:dragLoc
1246                  offset:NSZeroSize
1247                   event:mouseDraggedEvent
1248              pasteboard:pasteboard
1249                  source:self
1250               slideBack:YES];
1251     } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1252         if (!dhtmlWroteData) {
1253             [self _writeSelectionToPasteboard:pasteboard];
1254         }
1255         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1256         if (dragImage == nil) {
1257             dragImage = [self _selectionDraggingImage];
1258             NSRect draggingRect = [self _selectionDraggingRect];
1259             dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1260             _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1261             _private->dragOffset.y = dragLoc.y - mouseDownPoint.y;        // inverted because we are flipped
1262         }
1263         [self dragImage:dragImage
1264                      at:dragLoc
1265                  offset:NSZeroSize
1266                   event:_private->mouseDownEvent
1267              pasteboard:pasteboard
1268                  source:self
1269               slideBack:YES];
1270     } else if (srcIsDHTML) {
1271         ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1272         [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1273         if (dragImage == nil) {
1274             // WebCore should have given us an image, but we'll make one up
1275             NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1276             dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1277             NSSize imageSize = [dragImage size];
1278             dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1279             _private->dragOffset.x = imageSize.width/2;
1280             _private->dragOffset.y = imageSize.height/2;        // inverted because we are flipped
1281         }
1282         [self dragImage:dragImage
1283                      at:dragLoc
1284                  offset:NSZeroSize
1285                   event:_private->mouseDownEvent
1286              pasteboard:pasteboard
1287                  source:self
1288               slideBack:YES];
1289     } else {
1290         // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1291         // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1292         startedDrag = NO;
1293     }
1294     return startedDrag;
1295 }
1296
1297 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1298 {
1299     [self autoscroll:event];
1300     [self _startAutoscrollTimer:event];
1301 }
1302
1303 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1304 {
1305     NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1306     NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1307
1308     ASSERT([self _webView]);
1309     if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1310         [mouseDownElement objectForKey: WebElementImageURLKey] != nil && 
1311         [[[self _webView] preferences] loadsImagesAutomatically] && 
1312         (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1313         return YES;
1314     }
1315     
1316     if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil && 
1317         (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1318         return YES;
1319     }
1320     
1321     if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1322         (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1323         return YES;
1324     }
1325     
1326     return NO;
1327 }
1328
1329 - (WebPluginController *)_pluginController
1330 {
1331     return _private->pluginController;
1332 }
1333
1334 - (void)_web_setPrintingModeRecursive
1335 {
1336     [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1337     [super _web_setPrintingModeRecursive];
1338 }
1339
1340 - (void)_web_clearPrintingModeRecursive
1341 {
1342     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1343     [super _web_clearPrintingModeRecursive];
1344 }
1345
1346 - (void)_layoutIfNeeded
1347 {
1348     ASSERT(!_private->subviewsSetAside);
1349
1350     if ([[self _bridge] needsLayout])
1351         _private->needsLayout = YES;
1352     if (_private->needsToApplyStyles || _private->needsLayout)
1353         [self layout];
1354 }
1355
1356 - (void)_web_layoutIfNeededRecursive
1357 {
1358     [self _layoutIfNeeded];
1359     [super _web_layoutIfNeededRecursive];
1360 }
1361
1362 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1363 {
1364     ASSERT(!_private->subviewsSetAside);
1365     displayRect = NSIntersectionRect(displayRect, [self bounds]);
1366
1367     if (!testDirtyRect || [self needsDisplay]) {
1368         if (testDirtyRect) {
1369             NSRect dirtyRect = [self _dirtyRect];
1370             displayRect = NSIntersectionRect(displayRect, dirtyRect);
1371         }
1372         if (!NSIsEmptyRect(displayRect)) {
1373             [self _layoutIfNeeded];
1374         }
1375     }
1376
1377     [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1378 }
1379
1380 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1381 {
1382     if (_private->autoscrollTimer == nil) {
1383         _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1384             target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1385         _private->autoscrollTriggerEvent = [triggerEvent retain];
1386     }
1387 }
1388
1389 // FIXME: _selectionRect is deprecated in favor of selectionRect, which is in protocol WebDocumentSelection.
1390 // We can't remove this yet because it's still in use by Mail.
1391 - (NSRect)_selectionRect
1392 {
1393     return [self selectionRect];
1394 }
1395
1396 - (void)_stopAutoscrollTimer
1397 {
1398     NSTimer *timer = _private->autoscrollTimer;
1399     _private->autoscrollTimer = nil;
1400     [_private->autoscrollTriggerEvent release];
1401     _private->autoscrollTriggerEvent = nil;
1402     [timer invalidate];
1403     [timer release];
1404 }
1405
1406 - (void)_autoscroll
1407 {
1408     // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1409     // a mouse up event.
1410     BOOL isStillDown = WKMouseIsDown();   
1411     if (!isStillDown){
1412         [self _stopAutoscrollTimer];
1413         return;
1414     }
1415
1416     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1417         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1418         modifierFlags:[[NSApp currentEvent] modifierFlags]
1419         timestamp:[NSDate timeIntervalSinceReferenceDate]
1420         windowNumber:[[self window] windowNumber]
1421         context:[[NSApp currentEvent] context]
1422         eventNumber:0 clickCount:0 pressure:0];
1423     [self mouseDragged:fakeEvent];
1424 }
1425
1426 - (BOOL)_canCopy
1427 {
1428     // Copying can be done regardless of whether you can edit.
1429     return [self _hasSelection];
1430 }
1431
1432 - (BOOL)_canCut
1433 {
1434     return [self _hasSelection] && [self _isEditable];
1435 }
1436
1437 - (BOOL)_canDelete
1438 {
1439     return [self _hasSelection] && [self _isEditable];
1440 }
1441
1442 - (BOOL)_canPaste
1443 {
1444     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1445 }
1446
1447 - (BOOL)_canEdit
1448 {
1449     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1450 }
1451
1452 - (BOOL)_canAlterCurrentSelection
1453 {
1454     return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1455 }
1456
1457 - (BOOL)_hasSelection
1458 {
1459     return [[self _bridge] selectionState] == WebSelectionStateRange;
1460 }
1461
1462 - (BOOL)_hasSelectionOrInsertionPoint
1463 {
1464     return [[self _bridge] selectionState] != WebSelectionStateNone;
1465 }
1466
1467 - (BOOL)_hasInsertionPoint
1468 {
1469     return [[self _bridge] selectionState] == WebSelectionStateCaret;
1470 }
1471
1472 - (BOOL)_isEditable
1473 {
1474     return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1475 }
1476
1477 - (BOOL)_isSelectionMisspelled
1478 {
1479     NSString *selectedString = [self selectedString];
1480     unsigned length = [selectedString length];
1481     if (length == 0) {
1482         return NO;
1483     }
1484     NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1485                                                                     startingAt:0
1486                                                                       language:nil
1487                                                                           wrap:NO
1488                                                         inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1489                                                                      wordCount:NULL];
1490     return range.length == length;
1491 }
1492
1493 - (NSArray *)_guessesForMisspelledSelection
1494 {
1495     ASSERT([[self selectedString] length] != 0);
1496     return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1497 }
1498
1499 - (void)_changeSpellingFromMenu:(id)sender
1500 {
1501     ASSERT([[self selectedString] length] != 0);
1502     if ([self _shouldReplaceSelectionWithText:[sender title] givenAction:WebViewInsertActionPasted]) {
1503         [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1504     }
1505 }
1506
1507 - (void)_ignoreSpellingFromMenu:(id)sender
1508 {
1509     ASSERT([[self selectedString] length] != 0);
1510     [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1511 }
1512
1513 - (void)_learnSpellingFromMenu:(id)sender
1514 {
1515     ASSERT([[self selectedString] length] != 0);
1516     [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1517 }
1518
1519 - (void)_lookUpInDictionaryFromMenu:(id)sender
1520 {
1521     // This should only be called when there's a selection, but play it safe.
1522     if (![self _hasSelection]) {
1523         return;
1524     }
1525     
1526     // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1527     static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1528     static const struct mach_header *frameworkImageHeader = NULL;
1529     static BOOL lookedForFunction = NO;
1530     if (!lookedForFunction) {
1531         __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1532         lookedForFunction = YES;
1533     }
1534     if (!__dictionaryServiceWindowShow) {
1535         ERROR("Couldn't find _DCMDictionaryServiceWindowShow"); 
1536         return;
1537     }
1538     
1539     // FIXME: must check for right-to-left here
1540     NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1541     
1542     NSAttributedString *attrString = [self selectedAttributedString];
1543     // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1544     // the rect for the entire selection, as we do here, positions the pop-up window near
1545     // the bottom of the selection rather than at the selected word.
1546     NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1547     rect.origin = [[self window] convertBaseToScreen:rect.origin];
1548     NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1549     (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1550 }
1551
1552 - (BOOL)_transparentBackground
1553 {
1554     return _private->transparentBackground;
1555 }
1556
1557 - (void)_setTransparentBackground:(BOOL)f
1558 {
1559     _private->transparentBackground = f;
1560 }
1561
1562 - (NSImage *)_selectionDraggingImage
1563 {
1564     if ([self _hasSelection]) {
1565         NSImage *dragImage = [[self _bridge] selectionImage];
1566         [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1567         return dragImage;
1568     }
1569     return nil;
1570 }
1571
1572 - (NSRect)_selectionDraggingRect
1573 {
1574     if ([self _hasSelection]) {
1575         return [[self _bridge] visibleSelectionRect];
1576     }
1577     return NSZeroRect;
1578 }
1579
1580 - (void)_updateFocusState
1581 {
1582     // This method does the job of updating the view based on the view's firstResponder-ness and
1583     // the window key-ness of the window containing this view. This involves four kinds of 
1584     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
1585     // 
1586     // The four display attributes are as follows:
1587     // 
1588     // 1. The background color used to draw behind selected content (active | inactive color)
1589     // 2. Caret blinking (blinks | does not blink)
1590     // 3. The drawing of a focus ring around links in web pages.
1591     // 4. Changing the tint of controls from clear to aqua/graphite and vice versa
1592     //
1593     // Also, this is responsible for letting the bridge know if the window has gained or lost focus
1594     // so we can send focus and blur events.
1595
1596     BOOL windowIsKey = [[self window] isKeyWindow];
1597     BOOL displaysWithFocusAttributes = !_private->resigningFirstResponder && windowIsKey && [self _web_firstResponderCausesFocusDisplay];
1598     
1599     [[self _bridge] setWindowHasFocus:windowIsKey];
1600     [[self _bridge] setDisplaysWithFocusAttributes:displaysWithFocusAttributes];
1601 }
1602
1603 - (unsigned)highlightAllMatchesForString:(NSString *)string caseSensitive:(BOOL)caseFlag
1604 {
1605     return [[self _bridge] highlightAllMatchesForString:string caseSensitive:caseFlag];
1606 }
1607
1608 - (void)clearHighlightedMatches
1609 {
1610     return [[self _bridge] clearHighlightedMatches];
1611 }
1612
1613 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1614 {
1615     ASSERT([self _hasSelection]);
1616     NSArray *types = [self pasteboardTypesForSelection];
1617
1618     // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1619     NSAttributedString *attributedString = [self selectedAttributedString];
1620     NSMutableArray *mutableTypes = nil;
1621     if (![attributedString containsAttachments]) {
1622         mutableTypes = [types mutableCopy];
1623         [mutableTypes removeObject:NSRTFDPboardType];
1624         types = mutableTypes;
1625     }
1626
1627     [pasteboard declareTypes:types owner:nil];
1628     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1629     [mutableTypes release];
1630 }
1631
1632 @end
1633
1634 @implementation NSView (WebHTMLViewFileInternal)
1635
1636 - (void)_web_setPrintingModeRecursive
1637 {
1638     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1639 }
1640
1641 - (void)_web_clearPrintingModeRecursive
1642 {
1643     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1644 }
1645
1646 - (void)_web_layoutIfNeededRecursive
1647 {
1648     [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1649 }
1650
1651 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1652 {
1653     unsigned index, count;
1654     for (index = 0, count = [(NSArray *)_subviews count]; index < count; index++) {
1655         NSView *subview = [_subviews objectAtIndex:index];
1656         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1657         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1658     }
1659 }
1660
1661 @end
1662
1663 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1664
1665 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1666 {
1667     if (object == nil) {
1668         [self removeObjectForKey:key];
1669     } else {
1670         [self setObject:object forKey:key];
1671     }
1672 }
1673
1674 @end
1675
1676 // The following is a workaround for
1677 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1678 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1679 // Since the category will be searched before the real class, we'll prevent the flag from being
1680 // set on the tool tip panel.
1681
1682 @interface NSToolTipPanel : NSPanel
1683 @end
1684
1685 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1686 @end
1687
1688 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1689
1690 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1691 {
1692     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1693 }
1694
1695 @end
1696
1697 @interface NSArray (WebHTMLView)
1698 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1699 @end
1700
1701 @implementation WebHTMLView
1702
1703 + (void)initialize
1704 {
1705     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] 
1706                              returnTypes:[[self class] _insertablePasteboardTypes]];
1707     _NSInitializeKillRing();
1708 }
1709
1710 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1711 {
1712     WebPreferences *preferences = [[self _webView] preferences];
1713     // Check for nil because we might not yet have an associated webView when this is called
1714     if (preferences == nil) {
1715         preferences = [WebPreferences standardPreferences];
1716     }
1717     _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1718 }
1719
1720 - (id)initWithFrame:(NSRect)frame
1721 {
1722     self = [super initWithFrame:frame];
1723     if (!self)
1724         return nil;
1725     
1726     // Make all drawing go through us instead of subviews.
1727     if (NSAppKitVersionNumber >= 711) {
1728         [self _setDrawsOwnDescendants:YES];
1729     }
1730     
1731     _private = [[WebHTMLViewPrivate alloc] init];
1732
1733     _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1734     _private->needsLayout = YES;
1735     [self _resetCachedWebPreferences:nil];
1736     [[NSNotificationCenter defaultCenter] 
1737             addObserver:self selector:@selector(_resetCachedWebPreferences:) 
1738                    name:WebPreferencesChangedNotification object:nil];
1739     
1740     return self;
1741 }
1742
1743 - (void)dealloc
1744 {
1745     [self _clearLastHitViewIfSelf];
1746     [self _reset];
1747     [[NSNotificationCenter defaultCenter] removeObserver:self];
1748     [_private->pluginController destroyAllPlugins];
1749     [_private release];
1750     _private = nil;
1751     [super dealloc];
1752 }
1753
1754 - (void)finalize
1755 {
1756     [self _clearLastHitViewIfSelf];
1757     [self _reset];
1758     [[NSNotificationCenter defaultCenter] removeObserver:self];
1759     [_private->pluginController destroyAllPlugins];
1760     _private = nil;
1761     [super finalize];
1762 }
1763
1764 - (IBAction)takeFindStringFromSelection:(id)sender
1765 {
1766     if (![self _hasSelection]) {
1767         NSBeep();
1768         return;
1769     }
1770
1771     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1772 }
1773
1774 - (NSArray *)pasteboardTypesForSelection
1775 {
1776     if ([self _canSmartCopyOrDelete]) {
1777         NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1778         [types addObject:WebSmartPastePboardType];
1779         return types;
1780     } else {
1781         return [[self class] _selectionPasteboardTypes];
1782     }
1783 }
1784
1785 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1786 {
1787     [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:nil];
1788 }
1789
1790 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1791 {
1792     [pasteboard declareTypes:types owner:nil];
1793     [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1794     return YES;
1795 }
1796
1797 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1798 {
1799     [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1800     return YES;
1801 }
1802
1803 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1804 {
1805     if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1806         return self;
1807     } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1808         return self;
1809     }
1810     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1811 }
1812
1813 - (void)selectAll:(id)sender
1814 {
1815     [self selectAll];
1816 }
1817
1818 // jumpToSelection is the old name for what AppKit now calls centerSelectionInVisibleArea. Safari
1819 // was using the old jumpToSelection selector in its menu. Newer versions of Safari will us the
1820 // selector centerSelectionInVisibleArea. We'll leave this old selector in place for two reasons:
1821 // (1) compatibility between older Safari and newer WebKit; (2) other WebKit-based applications
1822 // might be using the jumpToSelection: selector, and we don't want to break them.
1823 - (void)jumpToSelection:(id)sender
1824 {
1825     [self centerSelectionInVisibleArea:sender];
1826 }
1827
1828 - (NSRect)selectionRect
1829 {
1830     return [[self _bridge] selectionRect];
1831 }
1832
1833 - (NSView *)selectionView
1834 {
1835     return self;
1836 }
1837
1838 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
1839 {
1840     SEL action = [item action];
1841     WebFrameBridge *bridge = [self _bridge];
1842     
1843     if (action == @selector(alignCenter:)
1844             || action == @selector(alignLeft:)
1845             || action == @selector(alignJustified:)
1846             || action == @selector(alignRight:)
1847             || action == @selector(changeAttributes:)
1848             || action == @selector(changeBaseWritingDirection:) // FIXME: check menu item based on writing direction
1849             || action == @selector(changeColor:)
1850             || action == @selector(changeFont:)
1851             || action == @selector(changeSpelling:)
1852             || action == @selector(_changeSpellingFromMenu:)
1853             || action == @selector(checkSpelling:)
1854             || action == @selector(complete:)
1855             || action == @selector(deleteBackward:)
1856             || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
1857             || action == @selector(deleteForward:)
1858             || action == @selector(deleteToBeginningOfLine:)
1859             || action == @selector(deleteToBeginningOfParagraph:)
1860             || action == @selector(deleteToEndOfLine:)
1861             || action == @selector(deleteToEndOfParagraph:)
1862             || action == @selector(deleteToMark:)
1863             || action == @selector(deleteWordBackward:)
1864             || action == @selector(deleteWordForward:)
1865             || action == @selector(insertBacktab:)
1866             || action == @selector(insertLineBreak:)
1867             || action == @selector(insertNewline:)
1868             || action == @selector(insertNewlineIgnoringFieldEditor:)
1869             || action == @selector(insertParagraphSeparator:)
1870             || action == @selector(insertTab:)
1871             || action == @selector(insertTabIgnoringFieldEditor:)
1872             || action == @selector(moveBackward:)
1873             || action == @selector(moveBackwardAndModifySelection:)
1874             || action == @selector(moveDown:)
1875             || action == @selector(moveDownAndModifySelection:)
1876             || action == @selector(moveForward:)
1877             || action == @selector(moveForwardAndModifySelection:)
1878             || action == @selector(moveLeft:)
1879             || action == @selector(moveLeftAndModifySelection:)
1880             || action == @selector(moveParagraphBackwardAndModifySelection:)
1881             || action == @selector(moveParagraphForwardAndModifySelection:)
1882             || action == @selector(moveRight:)
1883             || action == @selector(moveRightAndModifySelection:)
1884             || action == @selector(moveToBeginningOfDocument:)
1885             || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
1886             || action == @selector(moveToBeginningOfLine:)
1887             || action == @selector(moveToBeginningOfLineAndModifySelection:)
1888             || action == @selector(moveToBeginningOfParagraph:)
1889             || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
1890             || action == @selector(moveToEndOfDocument:)
1891             || action == @selector(moveToEndOfDocumentAndModifySelection:)
1892             || action == @selector(moveToEndOfLine:)
1893             || action == @selector(moveToEndOfLineAndModifySelection:)
1894             || action == @selector(moveToEndOfParagraph:)
1895             || action == @selector(moveToEndOfParagraphAndModifySelection:)
1896             || action == @selector(moveUp:)
1897             || action == @selector(moveUpAndModifySelection:)
1898             || action == @selector(moveWordBackward:)
1899             || action == @selector(moveWordBackwardAndModifySelection:)
1900             || action == @selector(moveWordForward:)
1901             || action == @selector(moveWordForwardAndModifySelection:)
1902             || action == @selector(moveWordLeft:)
1903             || action == @selector(moveWordLeftAndModifySelection:)
1904             || action == @selector(moveWordRight:)
1905             || action == @selector(moveWordRightAndModifySelection:)
1906             || action == @selector(pageDown:)
1907             || action == @selector(pageDownAndModifySelection:)
1908             || action == @selector(pageUp:)
1909             || action == @selector(pageUpAndModifySelection:)
1910             || action == @selector(pasteFont:)
1911             || action == @selector(showGuessPanel:)
1912             || action == @selector(toggleBaseWritingDirection:)
1913             || action == @selector(transpose:)
1914             || action == @selector(yank:)
1915             || action == @selector(yankAndSelect:)) {
1916         return [self _canEdit];
1917     } else if (action == @selector(capitalizeWord:)
1918                || action == @selector(lowercaseWord:)
1919                || action == @selector(uppercaseWord:)) {
1920         return [self _hasSelection] && [self _isEditable];
1921     } else if (action == @selector(centerSelectionInVisibleArea:)
1922                || action == @selector(jumpToSelection:)
1923                || action == @selector(copyFont:)
1924                || action == @selector(setMark:)) {
1925         return [self _hasSelection] || ([self _isEditable] && [self _hasInsertionPoint]);
1926     } else if (action == @selector(changeDocumentBackgroundColor:)) {
1927         return [[self _webView] isEditable];
1928     } else if (action == @selector(copy:)) {
1929         return [bridge mayDHTMLCopy] || [self _canCopy];
1930     } else if (action == @selector(cut:)) {
1931         return [bridge mayDHTMLCut] || [self _canDelete];
1932     } else if (action == @selector(delete:)) {
1933         return [self _canDelete];
1934     } else if (action == @selector(_ignoreSpellingFromMenu:)
1935             || action == @selector(_learnSpellingFromMenu:)
1936             || action == @selector(takeFindStringFromSelection:)) {
1937         return [self _hasSelection];
1938     } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:) || action == @selector(pasteAsRichText:)) {
1939         return [bridge mayDHTMLPaste] || [self _canPaste];
1940     } else if (action == @selector(performFindPanelAction:)) {
1941         // FIXME: Not yet implemented.
1942         return NO;
1943     } else if (action == @selector(selectToMark:)
1944             || action == @selector(swapWithMark:)) {
1945         return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
1946     } else if (action == @selector(subscript:)) {
1947         NSMenuItem *menuItem = (NSMenuItem *)item;
1948         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1949             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1950             [style setVerticalAlign:@"sub"];
1951             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1952         }
1953         return [self _canEdit];
1954     } else if (action == @selector(superscript:)) {
1955         NSMenuItem *menuItem = (NSMenuItem *)item;
1956         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1957             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1958             [style setVerticalAlign:@"super"];
1959             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1960         }
1961         return [self _canEdit];
1962     } else if (action == @selector(underline:)) {
1963         NSMenuItem *menuItem = (NSMenuItem *)item;
1964         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1965             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1966             [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
1967             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1968         }
1969         return [self _canEdit];
1970     } else if (action == @selector(unscript:)) {
1971         NSMenuItem *menuItem = (NSMenuItem *)item;
1972         if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1973             DOMCSSStyleDeclaration *style = [self _emptyStyle];
1974             [style setVerticalAlign:@"baseline"];
1975             [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1976         }
1977         return [self _canEdit];
1978     } else if (action == @selector(_lookUpInDictionaryFromMenu:)) {
1979         return [self _hasSelection];
1980     }
1981     
1982     return YES;
1983 }
1984
1985 - (BOOL)acceptsFirstResponder
1986 {
1987     // Don't accept first responder when we first click on this view.
1988     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1989     // Do accept first responder at any other time, for example from keyboard events,
1990     // or from calls back from WebCore once we begin mouse-down event handling.
1991     NSEvent *event = [NSApp currentEvent];
1992     if ([event type] == NSLeftMouseDown
1993             && !_private->handlingMouseDownEvent
1994             && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1995         return NO;
1996     }
1997     return YES;
1998 }
1999
2000 - (BOOL)maintainsInactiveSelection
2001 {
2002     // This method helps to determing whether the view should maintain
2003     // an inactive selection when the view is not first responder.
2004     // Traditionally, these views have not maintained such selections,
2005     // clearing them when the view was not first responder. However,
2006     // to fix bugs like this one:
2007     // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even 
2008     //                            when they're not firstResponder"
2009     // it was decided to add a switch to act more like an NSTextView.
2010     // For now, however, the view only acts in this way when the
2011     // web view is set to be editable. This will maintain traditional
2012     // behavior for WebKit clients dating back to before this change,
2013     // and will likely be a decent switch for the long term, since
2014     // clients to ste the web view to be editable probably want it
2015     // to act like a "regular" Cocoa view in terms of its selection
2016     // behavior.
2017     id nextResponder = [[self window] _newFirstResponderAfterResigning];
2018
2019     // Predict the case where we are losing first responder status only to
2020     // gain it back again.  Want to keep the selection in that case.
2021     if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2022         id contentView = [nextResponder contentView];
2023         if (contentView) {
2024             nextResponder = contentView;
2025         }
2026     }
2027     if ([nextResponder isKindOfClass:[NSClipView class]]) {
2028         id documentView = [nextResponder documentView];
2029         if (documentView) {
2030             nextResponder = documentView;
2031         }
2032     }
2033
2034     if (nextResponder == self)
2035         return YES;
2036
2037     if (![[self _webView] maintainsInactiveSelection])
2038         return NO;
2039     
2040     // editable views lose selection when losing first responder status
2041     // to a widget in the same page, but not otherwise
2042     BOOL loseSelection = [nextResponder isKindOfClass:[NSView class]]
2043         && [nextResponder isDescendantOf:[self _webView]];
2044
2045     return !loseSelection;
2046 }
2047
2048 - (void)addMouseMovedObserver
2049 {
2050     // Always add a mouse move observer if the DB requested, or if we're the key window.
2051     if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
2052         [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
2053         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2054             name:WKMouseMovedNotification() object:nil];
2055         [self _frameOrBoundsChanged];
2056     }
2057 }
2058
2059 - (void)removeMouseMovedObserver
2060 {
2061     // Don't remove the observer if we're running the DB
2062     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2063         return;
2064         
2065     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2066     [[NSNotificationCenter defaultCenter] removeObserver:self
2067         name:WKMouseMovedNotification() object:nil];
2068 }
2069
2070 - (void)addSuperviewObservers
2071 {
2072     // We watch the bounds of our superview, so that we can do a layout when the size
2073     // of the superview changes. This is different from other scrollable things that don't
2074     // need this kind of thing because their layout doesn't change.
2075     
2076     // We need to pay attention to both height and width because our "layout" has to change
2077     // to extend the background the full height of the space and because some elements have
2078     // sizes that are based on the total size of the view.
2079     
2080     NSView *superview = [self superview];
2081     if (superview && [self window]) {
2082         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2083             name:NSViewFrameDidChangeNotification object:superview];
2084         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
2085             name:NSViewBoundsDidChangeNotification object:superview];
2086
2087         // In addition to registering for frame/bounds change notifications, call -_frameOrBoundsChanged.
2088         // It will check the current size/scroll against the previous layout's size/scroll.  We need to
2089         // do this here to catch the case where the WebView is laid out at one size, removed from its
2090         // window, resized, and inserted into another window.  Our frame/bounds changed notifications
2091         // will not be sent in that situation, since we only watch for changes while in the view hierarchy.
2092         [self _frameOrBoundsChanged];
2093     }
2094 }
2095
2096 - (void)removeSuperviewObservers
2097 {
2098     NSView *superview = [self superview];
2099     if (superview && [self window]) {
2100         [[NSNotificationCenter defaultCenter] removeObserver:self
2101             name:NSViewFrameDidChangeNotification object:superview];
2102         [[NSNotificationCenter defaultCenter] removeObserver:self
2103             name:NSViewBoundsDidChangeNotification object:superview];
2104     }
2105 }
2106
2107 - (void)addWindowObservers
2108 {
2109     NSWindow *window = [self window];
2110     if (window) {
2111         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2112             name:NSWindowDidBecomeKeyNotification object:window];
2113         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2114             name:NSWindowDidResignKeyNotification object:window];
2115         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2116             name:NSWindowWillCloseNotification object:window];
2117     }
2118 }
2119
2120 - (void)removeWindowObservers
2121 {
2122     NSWindow *window = [self window];
2123     if (window) {
2124         [[NSNotificationCenter defaultCenter] removeObserver:self
2125             name:NSWindowDidBecomeKeyNotification object:window];
2126         [[NSNotificationCenter defaultCenter] removeObserver:self
2127             name:NSWindowDidResignKeyNotification object:window];
2128         [[NSNotificationCenter defaultCenter] removeObserver:self
2129             name:NSWindowWillCloseNotification object:window];
2130     }
2131 }
2132
2133 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2134 {
2135     [self removeSuperviewObservers];
2136 }
2137
2138 - (void)viewDidMoveToSuperview
2139 {
2140     // Do this here in case the text size multiplier changed when a non-HTML
2141     // view was installed.
2142     if ([self superview] != nil) {
2143         [self _updateTextSizeMultiplier];
2144         [self addSuperviewObservers];
2145     }
2146 }
2147
2148 - (void)viewWillMoveToWindow:(NSWindow *)window
2149 {
2150     // Don't do anything if we aren't initialized.  This happens
2151     // when decoding a WebView.  When WebViews are decoded their subviews
2152     // are created by initWithCoder: and so won't be normally
2153     // initialized.  The stub views are discarded by WebView.
2154     if (_private){
2155         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2156         [self removeMouseMovedObserver];
2157         [self removeWindowObservers];
2158         [self removeSuperviewObservers];
2159         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2160     
2161         [[self _pluginController] stopAllPlugins];
2162     }
2163 }
2164
2165 - (void)viewDidMoveToWindow
2166 {
2167     // Don't do anything if we aren't initialized.  This happens
2168     // when decoding a WebView.  When WebViews are decoded their subviews
2169     // are created by initWithCoder: and so won't be normally
2170     // initialized.  The stub views are discarded by WebView.
2171     if (_private) {
2172         [self _stopAutoscrollTimer];
2173         if ([self window]) {
2174             _private->lastScrollPosition = [[self superview] bounds].origin;
2175             [self addWindowObservers];
2176             [self addSuperviewObservers];
2177             [self addMouseMovedObserver];
2178
2179             // Schedule this update, rather than making the call right now.
2180             // The reason is that placing the caret in the just-installed view requires
2181             // the HTML/XML document to be available on the WebCore side, but it is not
2182             // at the time this code is running. However, it will be there on the next
2183             // crank of the run loop. Doing this helps to make a blinking caret appear 
2184             // in a new, empty window "automatic".
2185             [self performSelector:@selector(_updateFocusState) withObject:nil afterDelay:0];
2186
2187             [[self _pluginController] startAllPlugins];
2188     
2189             _private->lastScrollPosition = NSZeroPoint;
2190             
2191             _private->inWindow = YES;
2192         } else {
2193             // Reset when we are moved out of a window after being moved into one.
2194             // Without this check, we reset ourselves before we even start.
2195             // This is only needed because viewDidMoveToWindow is called even when
2196             // the window is not changing (bug in AppKit).
2197             if (_private->inWindow) {
2198                 [self _reset];
2199                 _private->inWindow = NO;
2200             }
2201         }
2202     }
2203 }
2204
2205 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2206 {
2207     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2208 }
2209
2210 - (void)viewDidMoveToHostWindow
2211 {
2212     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2213 }
2214
2215
2216 - (void)addSubview:(NSView *)view
2217 {
2218     [super addSubview:view];
2219
2220     if ([WebPluginController isPlugInView:view]) {
2221         [[self _pluginController] addPlugin:view];
2222     }
2223 }
2224
2225 - (void)willRemoveSubview:(NSView *)subview
2226 {
2227     if ([WebPluginController isPlugInView:subview])
2228         [[self _pluginController] destroyPlugin:subview];
2229     [super willRemoveSubview:subview];
2230 }
2231
2232 - (void)reapplyStyles
2233 {
2234     if (!_private->needsToApplyStyles) {
2235         return;
2236     }
2237     
2238 #ifdef _KWQ_TIMING        
2239     double start = CFAbsoluteTimeGetCurrent();
2240 #endif
2241
2242     [[self _bridge] reapplyStylesForDeviceType:
2243         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2244     
2245 #ifdef _KWQ_TIMING        
2246     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2247     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2248 #endif
2249
2250     _private->needsToApplyStyles = NO;
2251 }
2252
2253 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2254 // minPageWidth==0 implies a non-printing layout
2255 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2256 {
2257     [self reapplyStyles];
2258     
2259     // Ensure that we will receive mouse move events.  Is this the best place to put this?
2260     [[self window] setAcceptsMouseMovedEvents: YES];
2261     WKSetNSWindowShouldPostEventNotifications([self window], YES);
2262
2263     if (!_private->needsLayout) {
2264         return;
2265     }
2266
2267 #ifdef _KWQ_TIMING        
2268     double start = CFAbsoluteTimeGetCurrent();
2269 #endif
2270
2271     LOG(View, "%@ doing layout", self);
2272
2273     if (minPageWidth > 0.0) {
2274         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2275     } else {
2276         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2277     }
2278     _private->needsLayout = NO;
2279     
2280     if (!_private->printing) {
2281         // get size of the containing dynamic scrollview, so
2282         // appearance and disappearance of scrollbars will not show up
2283         // as a size change
2284         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2285         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2286             [[self _bridge] sendResizeEvent];
2287         }
2288         _private->laidOutAtLeastOnce = YES;
2289         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2290         _private->lastLayoutFrameSize = newLayoutFrameSize;
2291     }
2292
2293 #ifdef _KWQ_TIMING        
2294     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2295     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2296 #endif
2297 }
2298
2299 - (void)layout
2300 {
2301     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2302 }
2303
2304 - (NSMenu *)menuForEvent:(NSEvent *)event
2305 {
2306     [_private->compController endRevertingChange:NO moveLeft:NO];
2307
2308     if ([[self _bridge] sendContextMenuEvent:event]) {
2309         return nil;
2310     }
2311     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2312     NSDictionary *element = [self elementAtPoint:point];
2313     return [[self _webView] _menuForElement:element defaultItems:nil];
2314 }
2315
2316 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2317 {
2318     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
2319 }
2320
2321 - (DOMRange *)_documentRange
2322 {
2323     return [[[self _bridge] DOMDocument] _documentRange];
2324 }
2325
2326 - (NSString *)string
2327 {
2328     return [[self _bridge] stringForRange:[self _documentRange]];
2329 }
2330
2331 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2332 {
2333     NSAttributedString *attributedString;
2334 #if !LOG_DISABLED        
2335     double start = CFAbsoluteTimeGetCurrent();
2336 #endif    
2337     attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2338 #if !LOG_DISABLED
2339     double duration = CFAbsoluteTimeGetCurrent() - start;
2340     LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2341 #endif
2342     return attributedString;
2343 }
2344
2345 - (NSAttributedString *)attributedString
2346 {
2347     WebFrameBridge *bridge = [self _bridge];
2348     DOMDocument *document = [bridge DOMDocument];
2349     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2350     if (attributedString == nil) {
2351         attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2352     }
2353     return attributedString;
2354 }
2355
2356 - (NSString *)selectedString
2357 {
2358     return [[self _bridge] selectedString];
2359 }
2360
2361 - (NSAttributedString *)selectedAttributedString
2362 {
2363     WebFrameBridge *bridge = [self _bridge];
2364     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2365     if (attributedString == nil) {
2366         attributedString = [bridge selectedAttributedString];
2367     }
2368     return attributedString;
2369 }
2370
2371 - (void)selectAll
2372 {
2373     [[self _bridge] selectAll];
2374 }
2375
2376 // Remove the selection.
2377 - (void)deselectAll
2378 {
2379     [[self _bridge] deselectAll];
2380 }
2381
2382 - (void)deselectText
2383 {
2384     [[self _bridge] deselectText];
2385 }
2386
2387 - (BOOL)isOpaque
2388 {
2389     return [[self _webView] drawsBackground];
2390 }
2391
2392 - (void)setNeedsDisplay:(BOOL)flag
2393 {
2394     LOG(View, "%@ flag = %d", self, (int)flag);
2395     [super setNeedsDisplay: flag];
2396 }
2397
2398 - (void)setNeedsLayout: (BOOL)flag
2399 {
2400     LOG(View, "%@ flag = %d", self, (int)flag);
2401     _private->needsLayout = flag;
2402 }
2403
2404
2405 - (void)setNeedsToApplyStyles: (BOOL)flag
2406 {
2407     LOG(View, "%@ flag = %d", self, (int)flag);
2408     _private->needsToApplyStyles = flag;
2409 }
2410
2411 - (void)drawRect:(NSRect)rect
2412 {
2413     LOG(View, "%@ drawing", self);
2414
2415     // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2416     // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2417     // This does a better job of clipping out rects that are entirely outside the visible area.
2418     const NSRect *rects;
2419     int count;
2420     [self getRectsBeingDrawn:&rects count:&count];
2421
2422     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2423     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2424     // The reason for the workaround is that this method is called explicitly from the code
2425     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2426     if (count > 0) {
2427         rect = NSZeroRect;
2428         int i;
2429         for (i = 0; i < count; ++i) {
2430             rect = NSUnionRect(rect, rects[i]);
2431         }
2432         if (rect.size.height == 0 || rect.size.width == 0) {
2433             return;
2434         }
2435     }
2436
2437     BOOL subviewsWereSetAside = _private->subviewsSetAside;
2438     if (subviewsWereSetAside) {
2439         [self _restoreSubviews];
2440     }
2441
2442 #ifdef _KWQ_TIMING
2443     double start = CFAbsoluteTimeGetCurrent();
2444 #endif
2445
2446     [NSGraphicsContext saveGraphicsState];
2447     NSRectClip(rect);
2448         
2449     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2450
2451     [(WebClipView *)[self superview] setAdditionalClip:rect];
2452
2453     NS_DURING {
2454         if ([self _transparentBackground]) {
2455             [[NSColor clearColor] set];
2456             NSRectFill (rect);
2457         }
2458         
2459         [[self _bridge] drawRect:rect];
2460
2461         [(WebClipView *)[self superview] resetAdditionalClip];
2462
2463         [NSGraphicsContext restoreGraphicsState];
2464     } NS_HANDLER {
2465         [(WebClipView *)[self superview] resetAdditionalClip];
2466         [NSGraphicsContext restoreGraphicsState];
2467         ERROR("Exception caught while drawing: %@", localException);
2468         [localException raise];
2469     } NS_ENDHANDLER
2470
2471 #ifdef DEBUG_LAYOUT
2472     NSRect vframe = [self frame];
2473     [[NSColor blackColor] set];
2474     NSBezierPath *path;
2475     path = [NSBezierPath bezierPath];
2476     [path setLineWidth:(float)0.1];
2477     [path moveToPoint:NSMakePoint(0, 0)];
2478     [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2479     [path closePath];
2480     [path stroke];
2481     path = [NSBezierPath bezierPath];
2482     [path setLineWidth:(float)0.1];
2483     [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2484     [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2485     [path closePath];
2486     [path stroke];
2487 #endif
2488
2489 #ifdef _KWQ_TIMING
2490     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2491     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2492 #endif
2493
2494     if (subviewsWereSetAside) {
2495         [self _setAsideSubviews];
2496     }
2497 }
2498
2499 // Turn off the additional clip while computing our visibleRect.
2500 - (NSRect)visibleRect
2501 {
2502     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2503         return [super visibleRect];
2504         
2505     WebClipView *clipView = (WebClipView *)[self superview];
2506
2507     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2508     if (!hasAdditionalClip) {
2509         return [super visibleRect];
2510     }
2511     
2512     NSRect additionalClip = [clipView additionalClip];
2513     [clipView resetAdditionalClip];
2514     NSRect visibleRect = [super visibleRect];
2515     [clipView setAdditionalClip:additionalClip];
2516     return visibleRect;
2517 }
2518
2519 - (BOOL)isFlipped 
2520 {
2521     return YES;
2522 }
2523
2524 - (void)windowDidBecomeKey:(NSNotification *)notification
2525 {
2526     ASSERT([notification object] == [self window]);
2527     [self addMouseMovedObserver];
2528     [self _updateFocusState];
2529 }
2530
2531 - (void)windowDidResignKey: (NSNotification *)notification
2532 {
2533     ASSERT([notification object] == [self window]);
2534     [_private->compController endRevertingChange:NO moveLeft:NO];
2535     [self removeMouseMovedObserver];
2536     [self _updateFocusState];
2537 }
2538
2539 - (void)windowWillClose:(NSNotification *)notification
2540 {
2541     [_private->compController endRevertingChange:NO moveLeft:NO];
2542     [[self _pluginController] destroyAllPlugins];
2543 }
2544
2545 - (void)scrollWheel:(NSEvent *)event
2546 {
2547     [self retain];
2548     
2549     if (![[self _bridge] sendScrollWheelEvent:event]) {
2550         [[self nextResponder] scrollWheel:event];
2551     }    
2552     
2553     [self release];
2554 }
2555
2556 - (BOOL)_isSelectionEvent:(NSEvent *)event
2557 {
2558     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2559     return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2560 }
2561
2562 - (void)_setMouseDownEvent:(NSEvent *)event
2563 {
2564     ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2565
2566     if (event == _private->mouseDownEvent) {
2567         return;
2568     }
2569
2570     [event retain];
2571     [_private->mouseDownEvent release];
2572     _private->mouseDownEvent = event;
2573
2574     [_private->firstResponderAtMouseDownTime release];
2575     _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2576 }
2577
2578 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2579 {
2580     NSView *hitView = [self _hitViewForEvent:event];
2581     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2582     [hitHTMLView _setMouseDownEvent:event];
2583     
2584     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2585         return YES;
2586     
2587     if (hitHTMLView != nil) {
2588         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2589         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2590     } else {
2591         return [hitView acceptsFirstMouse:event];
2592     }
2593 }
2594
2595 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2596 {
2597     NSView *hitView = [self _hitViewForEvent:event];
2598     WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2599     if (hitHTMLView != nil) {
2600         [hitHTMLView _setMouseDownEvent:event];
2601         return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2602     } else {
2603         return [hitView shouldDelayWindowOrderingForEvent:event];
2604     }
2605 }
2606
2607 - (void)mouseDown:(NSEvent *)event
2608 {
2609     [self retain];
2610
2611     _private->handlingMouseDownEvent = YES;
2612
2613     // Record the mouse down position so we can determine drag hysteresis.
2614     [self _setMouseDownEvent:event];
2615
2616     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2617     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2618         goto done;
2619
2620     [_private->compController endRevertingChange:NO moveLeft:NO];
2621
2622     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2623     // We don't want to pass them along to KHTML a second time.
2624     if (!([event modifierFlags] & NSControlKeyMask)) {
2625         _private->ignoringMouseDraggedEvents = NO;
2626
2627         // Don't do any mouseover while the mouse is down.
2628         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2629
2630         // Let KHTML get a chance to deal with the event. This will call back to us
2631         // to start the autoscroll timer if appropriate.
2632         [[self _bridge] mouseDown:event];
2633     }
2634
2635 done:
2636     [_private->firstResponderAtMouseDownTime release];
2637     _private->firstResponderAtMouseDownTime = nil;
2638
2639     _private->handlingMouseDownEvent = NO;
2640     
2641     [self release];
2642 }
2643
2644 - (void)dragImage:(NSImage *)dragImage
2645                at:(NSPoint)at
2646            offset:(NSSize)offset
2647             event:(NSEvent *)event
2648        pasteboard:(NSPasteboard *)pasteboard
2649            source:(id)source
2650         slideBack:(BOOL)slideBack
2651 {
2652     WebView *webView = [self _webView];
2653     [self _stopAutoscrollTimer];
2654
2655     _private->initiatedDrag = YES;
2656     [webView _setInitiatedDrag:YES];
2657
2658     // Retain this view during the drag because it may be released before the drag ends.
2659     [self retain];
2660
2661     id UIDelegate = [webView UIDelegate];
2662     // If a delegate takes over the drag but never calls draggedImage: endedAt:, we'll leak the WebHTMLView.
2663     if ([UIDelegate respondsToSelector:@selector(webView:dragImage:at:offset:event:pasteboard:source:slideBack:forView:)])
2664         [UIDelegate webView:webView dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack forView:self];
2665     else
2666         [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2667 }
2668
2669 - (void)mouseDragged:(NSEvent *)event
2670 {
2671     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2672     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2673         return;
2674
2675     [self retain];
2676
2677     if (!_private->ignoringMouseDraggedEvents)
2678         [[self _bridge] mouseDragged:event];
2679
2680     [self release];
2681 }
2682
2683 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2684 {
2685     if (_private->webCoreDragOp == NSDragOperationNone) {
2686         return (NSDragOperationGeneric | NSDragOperationCopy);
2687     } else {
2688         return _private->webCoreDragOp;
2689     }
2690 }
2691
2692 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2693 {
2694     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2695     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2696     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2697 }
2698
2699 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2700 {
2701     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2702     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2703     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2704
2705     _private->initiatedDrag = NO;
2706     [[self _webView] _setInitiatedDrag:NO];
2707     
2708     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2709     _private->ignoringMouseDraggedEvents = YES;
2710     
2711     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2712     // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2713     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2714                                             location:windowMouseLoc
2715                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2716                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2717                                         windowNumber:[[self window] windowNumber]
2718                                              context:[[NSApp currentEvent] context]
2719                                          eventNumber:0 clickCount:0 pressure:0];
2720     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2721     
2722     // Balance the previous retain from when the drag started.
2723     [self release];
2724 }
2725
2726 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2727 {
2728     ASSERT(_private->draggingImageURL);
2729     
2730     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2731     if (wrapper == nil) {
2732         ERROR("Failed to create image file. Did the source image change while dragging? (<rdar://problem/4244861>)");
2733         return nil;
2734     }
2735     
2736     // FIXME: Report an error if we fail to create a file.
2737     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2738     path = [[NSFileManager defaultManager] _webkit_pathWithUniqueFilenameForPath:path];
2739     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2740         ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2741     }
2742     
2743     return [NSArray arrayWithObject:[path lastPathComponent]];
2744 }
2745
2746 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2747 {
2748     NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2749     NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2750     [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2751     if ([types count] == 0) {
2752         return NO;
2753     } else if ([types count] == 1 && 
2754                [types containsObject:NSFilenamesPboardType] && 
2755                ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2756         return NO;
2757     }
2758     
2759     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2760     NSDictionary *element = [self elementAtPoint:point];
2761     if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2762         if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2763             // Can't drag onto the selection being dragged.
2764             return NO;
2765         }
2766         return YES;
2767     }
2768     
2769     return NO;
2770 }
2771
2772 - (BOOL)_isMoveDrag
2773 {
2774     return _private->initiatedDrag && 
2775     ([self _isEditable] && [self _hasSelection]) &&
2776     ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2777 }
2778
2779 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2780 {
2781     return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2782 }
2783
2784 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2785 {
2786     NSDragOperation operation = NSDragOperationNone;
2787     
2788     if (actionMask & WebDragDestinationActionDHTML) {
2789         operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2790     }
2791     _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2792     
2793     if ((actionMask & WebDragDestinationActionEdit) &&
2794         !_private->webCoreHandlingDrag
2795         && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2796         if ([self _isNSColorDrag:draggingInfo]) {
2797             operation = NSDragOperationGeneric;
2798         }
2799         else {
2800             WebView *webView = [self _webView];
2801             [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2802             operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2803         }
2804     } else {
2805         [[self _webView] removeDragCaret];
2806     }
2807     
2808     return operation;
2809 }
2810
2811 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2812 {
2813     [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2814     [[self _webView] removeDragCaret];
2815 }
2816
2817 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2818 {
2819     WebView *webView = [self _webView];
2820     WebFrameBridge *bridge = [self _bridge];
2821     if (_private->webCoreHandlingDrag) {
2822         ASSERT(actionMask & WebDragDestinationActionDHTML);
2823         [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2824         [bridge concludeDragForDraggingInfo:draggingInfo];
2825         return YES;
2826     } else if (actionMask & WebDragDestinationActionEdit) {
2827         if ([self _isNSColorDrag:draggingInfo]) {
2828             NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2829             if (!color)
2830                 return NO;
2831             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2832             [style setProperty:@"color" :[self _colorAsString:color] :@""];
2833             if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2834                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2835                 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2836                 return YES;
2837             }
2838             return NO;
2839         }
2840         else {
2841             BOOL didInsert = NO;
2842             if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2843                 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2844                 BOOL chosePlainText;
2845                 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES chosePlainText:&chosePlainText];
2846                 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2847                     [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2848                     if ([self _isMoveDrag]) {
2849                         BOOL smartMove = [[self _bridge] selectionGranularity] == WebBridgeSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2850                         [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2851                     } else {
2852                         [bridge setSelectionToDragCaret];
2853                         [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
2854                     }
2855                     didInsert = YES;
2856                 }
2857             }
2858             [webView removeDragCaret];
2859             return didInsert;
2860         }
2861     }
2862     return NO;
2863 }
2864
2865 - (NSDictionary *)elementAtPoint:(NSPoint)point
2866 {
2867     NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2868     NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2869     
2870     // Convert URL strings to NSURLs.
2871     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2872     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2873     if ([elementInfoWC objectForKey:WebElementImageURLKey])
2874         [elementInfo _web_setObjectIfNotNil:[[elementInfoWC objectForKey:WebElementDOMNodeKey] _image] forKey:WebElementImageKey];
2875
2876     WebFrameView *webFrameView = [self _web_parentWebFrameView];
2877     ASSERT(webFrameView);
2878     WebFrame *webFrame = [webFrameView webFrame];
2879     
2880     if (webFrame) {
2881         NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2882         if ([frameName length] == 0) {
2883             [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2884         } else {
2885             WebFrame *wf = [webFrame findFrameNamed:frameName];
2886             if (wf != nil)
2887                 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2888             else
2889                 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2890         }
2891         
2892         [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2893     }
2894     
2895     return [elementInfo autorelease];
2896 }
2897
2898 - (void)mouseUp:(NSEvent *)event
2899 {
2900     NSInputManager *currentInputManager = [NSInputManager currentInputManager];
2901     if ([currentInputManager wantsToHandleMouseEvents] && [currentInputManager handleMouseEvent:event])
2902         return;
2903
2904     [self retain];
2905
2906     [self _stopAutoscrollTimer];
2907     [[self _bridge] mouseUp:event];
2908     [self _updateMouseoverWithFakeEvent];
2909
2910     [self release];
2911 }
2912
2913 - (void)mouseMovedNotification:(NSNotification *)notification
2914 {
2915     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2916 }
2917
2918 - (BOOL)supportsTextEncoding
2919 {
2920     return YES;
2921 }
2922
2923 - (NSView *)nextValidKeyView
2924 {
2925     NSView *view = nil;
2926     BOOL lookInsideWebFrameViews = YES;
2927     if ([self isHiddenOrHasHiddenAncestor]) {
2928         lookInsideWebFrameViews = NO;
2929     } else if ([self _frame] == [[self _webView] mainFrame]) {
2930         // Check for case where first responder is last frame in a frameset, and we are
2931         // the top-level documentView.
2932         NSResponder *firstResponder = [[self window] firstResponder];
2933         if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
2934             lookInsideWebFrameViews = NO;
2935         }
2936     }
2937     
2938     if (lookInsideWebFrameViews) {
2939         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2940     }
2941     
2942     if (view == nil) {
2943         view = [super nextValidKeyView];
2944         // If there's no next view wired up, we must be in the last subframe.
2945         // There's no direct link to the next valid key view; get it from the bridge.
2946         // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
2947         // We'll check for both nil and self in case the AppKit oddness goes away.
2948         // WebFrameView has this same kind of logic for the previousValidKeyView case.
2949         if (view == nil || view == self) {
2950             ASSERT([self _frame] != [[self _webView] mainFrame]);
2951             view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
2952         }
2953     }
2954         
2955     return view;
2956 }
2957
2958 - (NSView *)previousValidKeyView
2959 {
2960     NSView *view = nil;
2961     if (![self isHiddenOrHasHiddenAncestor]) {
2962         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2963     }
2964     if (view == nil) {
2965         view = [super previousValidKeyView];
2966     }
2967     return view;
2968 }
2969
2970 - (BOOL)becomeFirstResponder
2971 {
2972     NSView *view = nil;
2973     if (![[self _webView] _isPerformingProgrammaticFocus]) {
2974         switch ([[self window] keyViewSelectionDirection]) {
2975         case NSDirectSelection:
2976             break;
2977         case NSSelectingNext:
2978             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2979             break;
2980         case NSSelectingPrevious:
2981             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2982             break;
2983         }
2984     }
2985     if (view)
2986         [[self window] makeFirstResponder:view];
2987     [[[self _web_parentWebFrameView] webFrame] _clearSelectionInOtherFrames];
2988     [self _updateFocusState];
2989     [self _updateFontPanel];
2990     _private->startNewKillRingSequence = YES;
2991     return YES;
2992 }
2993
2994 - (BOOL)resignFirstResponder
2995 {
2996     BOOL resign = [super resignFirstResponder];
2997     if (resign) {
2998         [_private->compController endRevertingChange:NO moveLeft:NO];
2999         _private->resigningFirstResponder = YES;
3000         if (![self maintainsInactiveSelection]) { 
3001             if ([[self _webView] _isPerformingProgrammaticFocus]) {
3002                 [self deselectText];
3003             }
3004             else {
3005                 [self deselectAll];
3006             }
3007         }
3008         [self _updateFocusState];
3009         _private->resigningFirstResponder = NO;
3010     }
3011     return resign;
3012 }
3013
3014 //------------------------------------------------------------------------------------
3015 // WebDocumentView protocol
3016 //------------------------------------------------------------------------------------
3017 - (void)setDataSource:(WebDataSource *)dataSource 
3018 {
3019 }
3020
3021 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3022 {
3023 }
3024
3025 // This is an override of an NSControl method that wants to repaint the entire view when the window resigns/becomes
3026 // key.  WebHTMLView is an NSControl only because it hosts NSCells that are painted by WebCore's Aqua theme
3027 // renderer (and those cells must be hosted by an enclosing NSControl in order to paint properly).
3028 - (void)updateCell:(NSCell*)cell
3029 {
3030 }
3031
3032 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3033 // pageWidth != 0 implies we will relayout to a new width
3034 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3035 {
3036     WebFrame *frame = [self _frame];
3037     NSArray *subframes = [frame childFrames];
3038     unsigned n = [subframes count];
3039     unsigned i;
3040     for (i = 0; i != n; ++i) {
3041         WebFrame *subframe = [subframes objectAtIndex:i];
3042         WebFrameView *frameView = [subframe frameView];
3043         if ([[subframe dataSource] _isDocumentHTML]) {
3044             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
3045         }
3046     }
3047
3048     if (printing != _private->printing) {
3049         [_private->pageRects release];
3050         _private->pageRects = nil;
3051         _private->printing = printing;
3052         [self setNeedsToApplyStyles:YES];
3053         [self setNeedsLayout:YES];
3054         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3055         if (!printing) {
3056             // Can't do this when starting printing or nested printing won't work, see 3491427.
3057             [self setNeedsDisplay:NO];
3058         }
3059     }
3060 }
3061
3062 - (BOOL)canPrintHeadersAndFooters
3063 {
3064     return YES;
3065 }
3066
3067 // This is needed for the case where the webview is embedded in the view that's being printed.
3068 // It shouldn't be called when the webview is being printed directly.
3069 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3070 {
3071     // This helps when we print as part of a larger print process.
3072     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3073     BOOL wasInPrintingMode = _private->printing;
3074     if (!wasInPrintingMode) {
3075         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3076     }
3077     
3078     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3079     
3080     if (!wasInPrintingMode) {
3081         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3082     }
3083 }
3084
3085 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3086 {
3087     NSPrintInfo *printInfo = [printOperation printInfo];
3088     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3089 }
3090
3091 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3092 {
3093     float viewWidth = NSWidth([self bounds]);
3094     if (viewWidth < 1) {
3095         ERROR("%@ has no width when printing", self);
3096         return 1.0;
3097     }
3098
3099     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3100     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
3101     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3102     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3103 }
3104
3105 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3106 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3107 // if AppKit makes it SPI/API.
3108 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
3109 {
3110     return [self _scaleFactorForPrintOperation:printOperation];
3111 }
3112
3113 // This is used for Carbon printing. At some point we might want to make this public API.
3114 - (void)setPageWidthForPrinting:(float)pageWidth
3115 {
3116     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
3117     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3118 }
3119
3120 - (void)_endPrintMode
3121 {
3122     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3123     [[self window] setAutodisplay:YES];
3124 }
3125
3126 - (void)_delayedEndPrintMode:(NSPrintOperation *)initiatingOperation
3127 {
3128     ASSERT_ARG(initiatingOperation, initiatingOperation != nil);
3129     NSPrintOperation *currentOperation = [NSPrintOperation currentOperation];
3130     
3131     if (initiatingOperation == currentOperation) {
3132         // The print operation is still underway. We don't expect this to ever happen, hence the assert, but we're
3133         // being extra paranoid here since the printing code is so fragile. Delay the cleanup
3134         // further.
3135         ASSERT_NOT_REACHED();
3136         [self performSelector:@selector(_delayedEndPrintMode:) withObject:initiatingOperation afterDelay:0];
3137     } else if ([currentOperation view] == self) {
3138         // A new print job has started, but it is printing the same WebHTMLView again. We don't expect
3139         // this to ever happen, hence the assert, but we're being extra paranoid here since the printing code is so
3140         // fragile. Do nothing, because we don't want to break the print job currently in progress, and
3141         // the print job currently in progress is responsible for its own cleanup.
3142         ASSERT_NOT_REACHED();
3143     } else {
3144         // The print job that kicked off this delayed call has finished, and this view is not being
3145         // printed again. We expect that no other print job has started. Since this delayed call wasn't
3146         // cancelled, beginDocument and endDocument must not have been called, and we need to clean up
3147         // the print mode here.
3148         ASSERT(currentOperation == nil);
3149         [self _endPrintMode];
3150     }
3151 }
3152
3153 // Return the number of pages available for printing
3154 - (BOOL)knowsPageRange:(NSRangePointer)range {
3155     // Must do this explicit display here, because otherwise the view might redisplay while the print
3156     // sheet was up, using printer fonts (and looking different).
3157     [self displayIfNeeded];
3158     [[self window] setAutodisplay:NO];
3159     
3160     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3161     // according to the paper size
3162     float minLayoutWidth = 0.0;
3163     float maxLayoutWidth = 0.0;
3164     if (![[self _bridge] isFrameSet]) {
3165         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3166         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
3167         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
3168     }
3169     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3170     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3171     // Certain types of errors, including invalid page ranges, can cause beginDocument and
3172     // endDocument to be skipped after we've put ourselves in print mode (see 4145905). In those cases
3173     // we need to get out of print mode without relying on any more callbacks from the printing mechanism.
3174     // If we get as far as beginDocument without trouble, then this delayed request will be cancelled.
3175     // If not cancelled, this delayed call will be invoked in the next pass through the main event loop,
3176     // which is after beginDocument and endDocument would be called.
3177     [self performSelector:@selector(_delayedEndPrintMode:) withObject:printOperation afterDelay:0];
3178     [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3179     
3180     // There is a theoretical chance that someone could do some drawing between here and endDocument,
3181     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3182     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3183
3184     range->location = 1;
3185     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3186     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3187     [_private->pageRects release];
3188     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3189                                                                           printHeight:floorf([self _calculatePrintHeight]/totalScaleFactor)];
3190     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3191     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3192     // a blank page (with correct-looking header and footer if that option is on), which matches
3193     // the behavior of IE and Camino at least.
3194     if ([newPageRects count] == 0) {
3195         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
3196     }
3197     _private->pageRects = [newPageRects retain];
3198     
3199     range->length = [_private->pageRects count];
3200     
3201     return YES;
3202 }
3203
3204 // Return the drawing rectangle for a particular page number
3205 - (NSRect)rectForPage:(int)page {
3206     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
3207 }
3208
3209 - (void)drawPageBorderWithSize:(NSSize)borderSize
3210 {
3211     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
3212     [[self _webView] _drawHeaderAndFooter];
3213 }
3214
3215 - (void)beginDocument
3216 {
3217     NS_DURING
3218         // From now on we'll get a chance to call _endPrintMode in either beginDocument or
3219         // endDocument, so we can cancel the "just in case" pending call.
3220         [NSObject cancelPreviousPerformRequestsWithTarget:self
3221                                                  selector:@selector(_delayedEndPrintMode:)
3222                                                    object:[NSPrintOperation currentOperation]];
3223         [super beginDocument];
3224     NS_HANDLER
3225         // Exception during [super beginDocument] means that endDocument will not get called,
3226         // so we need to clean up our "print mode" here.
3227         [self _endPrintMode];
3228     NS_ENDHANDLER
3229 }
3230
3231 - (void)endDocument
3232 {
3233     [super endDocument];
3234     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
3235     [self _endPrintMode];
3236 }
3237
3238 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3239 {   
3240     // Use the isEditable state to determine whether or not to process tab key events.
3241     // The idea here is that isEditable will be NO when this WebView is being used
3242     // in a browser, and we desire the behavior where tab moves to the next element
3243     // in tab order. If isEditable is YES, it is likely that the WebView is being
3244     // embedded as the whole view, as in Mail, and tabs should input tabs as expected
3245     // in a text editor.
3246     if (![[self _webView] isEditable] && [event _web_isTabKeyEvent]) 
3247         return NO;
3248     
3249     // Now process the key normally
3250     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3251     return YES;
3252 }
3253
3254 - (void)keyDown:(NSEvent *)event
3255 {
3256     [self retain];
3257
3258     BOOL callSuper = NO;
3259
3260     _private->keyDownEvent = event;
3261
3262     WebFrameBridge *bridge = [self _bridge];
3263     if ([bridge interceptKeyEvent:event toView:self]) {
3264         // WebCore processed a key event, bail on any outstanding complete: UI
3265         [_private->compController endRevertingChange:YES moveLeft:NO];
3266     } else if (_private->compController && [_private->compController filterKeyDown:event]) {
3267         // Consumed by complete: popup window
3268     } else {
3269         // We're going to process a key event, bail on any outstanding complete: UI
3270         [_private->compController endRevertingChange:YES moveLeft:NO];
3271         if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
3272             // Consumed by key bindings manager.
3273         } else {
3274             callSuper = YES;
3275         }
3276     }
3277     if (callSuper) {
3278         [super keyDown:event];
3279     } else {
3280         [NSCursor setHiddenUntilMouseMoves:YES];
3281     }
3282
3283     _private->keyDownEvent = nil;
3284     
3285     [self release];
3286 }
3287
3288 - (void)keyUp:(NSEvent *)event
3289 {
3290     [self retain];
3291     
3292     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
3293         [super keyUp:event];
3294     }
3295     
3296     [self release];
3297 }
3298
3299 - (id)accessibilityAttributeValue:(NSString*)attributeName
3300 {
3301     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
3302         id accTree = [[self _bridge] accessibilityTree];
3303         if (accTree)
3304             return [NSArray arrayWithObject: accTree];
3305         return nil;
3306     }
3307     return [super accessibilityAttributeValue:attributeName];
3308 }
3309
3310 - (id)accessibilityFocusedUIElement
3311 {
3312     id accTree = [[self _bridge] accessibilityTree];
3313     if (accTree)
3314         return [accTree accessibilityFocusedUIElement];
3315     else
3316         return self;
3317 }
3318
3319 - (id)accessibilityHitTest:(NSPoint)point
3320 {
3321     id accTree = [[self _bridge] accessibilityTree];
3322     if (accTree) {
3323         NSPoint windowCoord = [[self window] convertScreenToBase: point];
3324         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
3325     }
3326     else
3327         return self;
3328 }
3329
3330 - (id)_accessibilityParentForSubview:(NSView *)subview
3331 {
3332     id accTree = [[self _bridge] accessibilityTree];
3333     if (!accTree)
3334         return self;
3335         
3336     id parent = [accTree _accessibilityParentForSubview:subview];
3337     if (parent == nil)
3338         return self;
3339
3340     return parent;
3341 }
3342
3343 - (void)centerSelectionInVisibleArea:(id)sender
3344 {
3345     [[self _bridge] centerSelectionInVisibleArea];
3346 }
3347
3348 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebBridgeSelectionDirection)direction granularity:(WebBridgeSelectionGranularity)granularity
3349 {
3350     if (![self _canAlterCurrentSelection])
3351         return;
3352         
3353     WebFrameBridge *bridge = [self _bridge];
3354     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
3355     WebView *webView = [self _webView];
3356     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3357         [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
3358     }
3359 }
3360
3361 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
3362 {
3363     if (![self _canAlterCurrentSelection])
3364         return;
3365         
3366     WebFrameBridge *bridge = [self _bridge];
3367     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
3368     WebView *webView = [self _webView];
3369     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3370         [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
3371     }
3372 }
3373
3374 - (void)moveBackward:(id)sender
3375 {
3376     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectByCharacter];
3377 }
3378
3379 - (void)moveBackwardAndModifySelection:(id)sender
3380 {
3381     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectByCharacter];
3382 }
3383
3384 - (void)moveDown:(id)sender
3385 {
3386     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectByLine];
3387 }
3388
3389 - (void)moveDownAndModifySelection:(id)sender
3390 {
3391     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectByLine];
3392 }
3393
3394 - (void)moveForward:(id)sender
3395 {
3396     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectByCharacter];
3397 }
3398
3399 - (void)moveForwardAndModifySelection:(id)sender
3400 {
3401     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectByCharacter];
3402 }
3403
3404 - (void)moveLeft:(id)sender
3405 {
3406     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectLeft granularity:WebBridgeSelectByCharacter];
3407 }
3408
3409 - (void)moveLeftAndModifySelection:(id)sender
3410 {
3411     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectLeft granularity:WebBridgeSelectByCharacter];
3412 }
3413
3414 - (void)moveRight:(id)sender
3415 {
3416     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectRight granularity:WebBridgeSelectByCharacter];
3417 }
3418
3419 - (void)moveRightAndModifySelection:(id)sender
3420 {
3421     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectRight granularity:WebBridgeSelectByCharacter];
3422 }
3423
3424 - (void)moveToBeginningOfDocument:(id)sender
3425 {
3426     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToDocumentBoundary];
3427 }
3428
3429 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3430 {
3431     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToDocumentBoundary];
3432 }
3433
3434 - (void)moveToBeginningOfLine:(id)sender
3435 {
3436     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToLineBoundary];
3437 }
3438
3439 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3440 {
3441     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToLineBoundary];
3442 }
3443
3444 - (void)moveToBeginningOfParagraph:(id)sender
3445 {
3446     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectToParagraphBoundary];
3447 }
3448
3449 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3450 {
3451     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectToParagraphBoundary];
3452 }
3453
3454 - (void)moveToEndOfDocument:(id)sender
3455 {
3456     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectToDocumentBoundary];
3457 }
3458
3459 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3460 {
3461     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectToDocumentBoundary];
3462 }
3463
3464 - (void)moveToEndOfLine:(id)sender
3465 {
3466     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectToLineBoundary];
3467 }
3468
3469 - (void)moveToEndOfLineAndModifySelection:(id)sender
3470 {
3471     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectToLineBoundary];
3472 }
3473
3474 - (void)moveToEndOfParagraph:(id)sender
3475 {
3476     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectToParagraphBoundary];
3477 }
3478
3479 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3480 {
3481     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectToParagraphBoundary];
3482 }
3483
3484 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3485 {
3486     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectByParagraph];
3487 }
3488
3489 - (void)moveParagraphForwardAndModifySelection:(id)sender
3490 {
3491     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectForward granularity:WebBridgeSelectByParagraph];
3492 }
3493
3494 - (void)moveUp:(id)sender
3495 {
3496     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectByLine];
3497 }
3498
3499 - (void)moveUpAndModifySelection:(id)sender
3500 {
3501     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectByLine];
3502 }
3503
3504 - (void)moveWordBackward:(id)sender
3505 {
3506     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectBackward granularity:WebBridgeSelectByWord];
3507 }
3508
3509 - (void)moveWordBackwardAndModifySelection:(id)sender
3510 {
3511     [self _alterCurrentSelection:WebSelectByExtending direction:WebBridgeSelectBackward granularity:WebBridgeSelectByWord];
3512 }
3513
3514 - (void)moveWordForward:(id)sender
3515 {
3516     [self _alterCurrentSelection:WebSelectByMoving direction:WebBridgeSelectForward granularity:WebBridgeSelectByWord];