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