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