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