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