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