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