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