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