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