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