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