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