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