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