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