WebKit:
[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 - (BOOL)_transparentBackground
1272 {
1273     return _private->transparentBackground;
1274 }
1275
1276 - (void)_setTransparentBackground:(BOOL)f
1277 {
1278     _private->transparentBackground = f;
1279 }
1280
1281 @end
1282
1283 @implementation NSView (WebHTMLViewFileInternal)
1284
1285 - (void)_web_setPrintingModeRecursive
1286 {
1287     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1288 }
1289
1290 - (void)_web_clearPrintingModeRecursive
1291 {
1292     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1293 }
1294
1295 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1296 {
1297     unsigned index, count;
1298     for (index = 0, count = [_subviews count]; index < count; index++) {
1299         NSView *subview = [_subviews objectAtIndex:index];
1300         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1301         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1302     }
1303 }
1304
1305 @end
1306
1307 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1308
1309 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1310 {
1311     if (object == nil) {
1312         [self removeObjectForKey:key];
1313     } else {
1314         [self setObject:object forKey:key];
1315     }
1316 }
1317
1318 @end
1319
1320 // The following is a workaround for
1321 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1322 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1323 // Since the category will be searched before the real class, we'll prevent the flag from being
1324 // set on the tool tip panel.
1325
1326 @interface NSToolTipPanel : NSPanel
1327 @end
1328
1329 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1330 @end
1331
1332 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1333
1334 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1335 {
1336     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1337 }
1338
1339 @end
1340
1341
1342 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1343 @end
1344
1345 @interface NSArray (WebHTMLView)
1346 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1347 @end
1348
1349 @implementation WebHTMLView
1350
1351 + (void)initialize
1352 {
1353     WebKitInitializeUnicode();
1354     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] 
1355                              returnTypes:[[self class] _insertablePasteboardTypes]];
1356     _NSInitializeKillRing();
1357 }
1358
1359 - (id)initWithFrame:(NSRect)frame
1360 {
1361     [super initWithFrame:frame];
1362     
1363     // Make all drawing go through us instead of subviews.
1364     if (NSAppKitVersionNumber >= 711) {
1365         [self _setDrawsOwnDescendants:YES];
1366     }
1367     
1368     _private = [[WebHTMLViewPrivate alloc] init];
1369
1370     _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1371     _private->needsLayout = YES;
1372
1373     return self;
1374 }
1375
1376 - (void)dealloc
1377 {
1378     [self _clearLastHitViewIfSelf];
1379     [self _reset];
1380     [[NSNotificationCenter defaultCenter] removeObserver:self];
1381     [_private->pluginController destroyAllPlugins];
1382     [_private release];
1383     _private = nil;
1384     [super dealloc];
1385 }
1386
1387 - (void)finalize
1388 {
1389     [self _clearLastHitViewIfSelf];
1390     [self _reset];
1391     [[NSNotificationCenter defaultCenter] removeObserver:self];
1392     [_private->pluginController destroyAllPlugins];
1393     _private = nil;
1394     [super finalize];
1395 }
1396
1397 - (IBAction)takeFindStringFromSelection:(id)sender
1398 {
1399     if (![self _hasSelection]) {
1400         NSBeep();
1401         return;
1402     }
1403
1404     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1405 }
1406
1407 - (NSArray *)pasteboardTypesForSelection
1408 {
1409     if ([self _canSmartCopyOrDelete]) {
1410         NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1411         [types addObject:WebSmartPastePboardType];
1412         return types;
1413     } else {
1414         return [[self class] _selectionPasteboardTypes];
1415     }
1416 }
1417
1418 // This method is copied from NSTextView
1419 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
1420 {
1421     NSRange attachmentRange;
1422     NSString *originalString = [originalAttributedString string];
1423     static NSString *attachmentCharString = nil;
1424     
1425     if (!attachmentCharString) {
1426         unichar chars[2];
1427         if (!attachmentCharString) {
1428             chars[0] = NSAttachmentCharacter;
1429             chars[1] = 0;
1430             attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
1431         }
1432     }
1433     
1434     attachmentRange = [originalString rangeOfString:attachmentCharString];
1435     if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1436         NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
1437         
1438         while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1439             [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
1440             attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
1441         }
1442         return newAttributedString;
1443     } else {
1444         return originalAttributedString;
1445     }
1446 }
1447
1448 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1449 {
1450     // Put HTML on the pasteboard.
1451     if ([types containsObject:WebArchivePboardType]) {
1452         WebArchive *archive = [self _selectedArchive];
1453         [pasteboard setData:[archive data] forType:WebArchivePboardType];
1454     }
1455     
1456     // Put the attributed string on the pasteboard (RTF/RTFD format).
1457     NSAttributedString *attributedString = nil;
1458     if ([types containsObject:NSRTFDPboardType]) {
1459         attributedString = [self selectedAttributedString];
1460         if ([attributedString containsAttachments]) {
1461             NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1462             [pasteboard setData:RTFDData forType:NSRTFDPboardType];
1463         }
1464     }        
1465     if ([types containsObject:NSRTFPboardType]) {
1466         if (attributedString == nil) {
1467             attributedString = [self selectedAttributedString];
1468         }
1469         if ([attributedString containsAttachments]) {
1470             attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
1471         }
1472         NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1473         [pasteboard setData:RTFData forType:NSRTFPboardType];
1474     }
1475         
1476     // Put plain string on the pasteboard.
1477     if ([types containsObject:NSStringPboardType]) {
1478         // Map &nbsp; to a plain old space because this is better for source code, other browsers do it,
1479         // and because HTML forces you to do this any time you want two spaces in a row.
1480         NSMutableString *s = [[self selectedString] mutableCopy];
1481         const unichar NonBreakingSpaceCharacter = 0xA0;
1482         NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1483         [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1484         [pasteboard setString:s forType:NSStringPboardType];
1485         [s release];
1486     }
1487     
1488     if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
1489         [pasteboard setData:nil forType:WebSmartPastePboardType];
1490     }
1491 }
1492
1493 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1494 {
1495     [pasteboard declareTypes:types owner:nil];
1496     [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1497     return YES;
1498 }
1499
1500 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1501 {
1502     [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1503     return YES;
1504 }
1505
1506 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1507 {
1508     if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1509         return self;
1510     } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1511         return self;
1512     }
1513     return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1514 }
1515
1516 - (void)selectAll:(id)sender
1517 {
1518     [self selectAll];
1519 }
1520
1521 - (void)jumpToSelection: sender
1522 {
1523     [[self _bridge] jumpToSelection];
1524 }
1525
1526 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
1527 {
1528     SEL action = [item action];
1529     WebBridge *bridge = [self _bridge];
1530
1531     if (action == @selector(cut:)) {
1532         return [bridge mayDHTMLCut] || [self _canDelete];
1533     } else if (action == @selector(copy:)) {
1534         return [bridge mayDHTMLCopy] || [self _canCopy];
1535     } else if (action == @selector(delete:)) {
1536         return [self _canDelete];
1537     } else if (action == @selector(paste:)) {
1538         return [bridge mayDHTMLPaste] || [self _canPaste];
1539     } else if (action == @selector(takeFindStringFromSelection:)) {
1540         return [self _hasSelection];
1541     } else if (action == @selector(jumpToSelection:)) {
1542         return [self _hasSelection];
1543     } else if (action == @selector(checkSpelling:)
1544                || action == @selector(showGuessPanel:)
1545                || action == @selector(changeSpelling:)
1546                || action == @selector(ignoreSpelling:)) {
1547         return [[self _bridge] isSelectionEditable];
1548     }
1549
1550     return YES;
1551 }
1552
1553 - (BOOL)acceptsFirstResponder
1554 {
1555     // Don't accept first responder when we first click on this view.
1556     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1557     // Do accept first responder at any other time, for example from keyboard events,
1558     // or from calls back from WebCore once we begin mouse-down event handling.
1559     NSEvent *event = [NSApp currentEvent];
1560     if ([event type] == NSLeftMouseDown && event != _private->mouseDownEvent && 
1561         NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1562         return NO;
1563     }
1564     return YES;
1565 }
1566
1567 - (BOOL)maintainsInactiveSelection
1568 {
1569     // This method helps to determing whether the view should maintain
1570     // an inactive selection when the view is not first responder.
1571     // Traditionally, these views have not maintained such selections,
1572     // clearing them when the view was not first responder. However,
1573     // to fix bugs like this one:
1574     // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even 
1575     //                            when they're not firstResponder"
1576     // it was decided to add a switch to act more like an NSTextView.
1577     // For now, however, the view only acts in this way when the
1578     // web view is set to be editable. This will maintain traditional
1579     // behavior for WebKit clients dating back to before this change,
1580     // and will likely be a decent switch for the long term, since
1581     // clients to ste the web view to be editable probably want it
1582     // to act like a "regular" Cocoa view in terms of its selection
1583     // behavior.
1584     if (![[self _webView] isEditable])
1585         return NO;
1586         
1587     id nextResponder = [[self window] _newFirstResponderAfterResigning];
1588     return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1589 }
1590
1591 - (void)addMouseMovedObserver
1592 {
1593     // Always add a mouse move observer if the DB requested, or if we're the key window.
1594     if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1595         [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1596         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1597             name:NSMouseMovedNotification object:nil];
1598         [self _frameOrBoundsChanged];
1599     }
1600 }
1601
1602 - (void)removeMouseMovedObserver
1603 {
1604     // Don't remove the observer if we're running the DB
1605     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1606         return;
1607         
1608     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1609     [[NSNotificationCenter defaultCenter] removeObserver:self
1610         name:NSMouseMovedNotification object:nil];
1611 }
1612
1613 - (void)updateFocusDisplay
1614 {
1615     // This method does the job of updating the view based on the view's firstResponder-ness and
1616     // the window key-ness of the window containing this view. This involves three kinds of 
1617     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
1618     // 
1619     // The three display attributes are as follows:
1620     // 
1621     // 1. The background color used to draw behind selected content (active | inactive color)
1622     // 2. Caret blinking (blinks | does not blink)
1623     // 3. The drawing of a focus ring around links in web pages.
1624
1625     BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1626     [[self _bridge] setDisplaysWithFocusAttributes:flag];
1627 }
1628
1629 - (void)addSuperviewObservers
1630 {
1631     // We watch the bounds of our superview, so that we can do a layout when the size
1632     // of the superview changes. This is different from other scrollable things that don't
1633     // need this kind of thing because their layout doesn't change.
1634     
1635     // We need to pay attention to both height and width because our "layout" has to change
1636     // to extend the background the full height of the space and because some elements have
1637     // sizes that are based on the total size of the view.
1638     
1639     NSView *superview = [self superview];
1640     if (superview && [self window]) {
1641         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1642             name:NSViewFrameDidChangeNotification object:superview];
1643         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1644             name:NSViewBoundsDidChangeNotification object:superview];
1645     }
1646 }
1647
1648 - (void)removeSuperviewObservers
1649 {
1650     NSView *superview = [self superview];
1651     if (superview && [self window]) {
1652         [[NSNotificationCenter defaultCenter] removeObserver:self
1653             name:NSViewFrameDidChangeNotification object:superview];
1654         [[NSNotificationCenter defaultCenter] removeObserver:self
1655             name:NSViewBoundsDidChangeNotification object:superview];
1656     }
1657 }
1658
1659 - (void)addWindowObservers
1660 {
1661     NSWindow *window = [self window];
1662     if (window) {
1663         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1664             name:NSWindowDidBecomeKeyNotification object:window];
1665         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1666             name:NSWindowDidResignKeyNotification object:window];
1667         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1668             name:NSWindowWillCloseNotification object:window];
1669     }
1670 }
1671
1672 - (void)removeWindowObservers
1673 {
1674     NSWindow *window = [self window];
1675     if (window) {
1676         [[NSNotificationCenter defaultCenter] removeObserver:self
1677             name:NSWindowDidBecomeKeyNotification object:window];
1678         [[NSNotificationCenter defaultCenter] removeObserver:self
1679             name:NSWindowDidResignKeyNotification object:window];
1680         [[NSNotificationCenter defaultCenter] removeObserver:self
1681             name:NSWindowWillCloseNotification object:window];
1682     }
1683 }
1684
1685 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1686 {
1687     [self removeSuperviewObservers];
1688 }
1689
1690 - (void)viewDidMoveToSuperview
1691 {
1692     // Do this here in case the text size multiplier changed when a non-HTML
1693     // view was installed.
1694     if ([self superview] != nil) {
1695         [self _updateTextSizeMultiplier];
1696         [self addSuperviewObservers];
1697     }
1698 }
1699
1700 - (void)viewWillMoveToWindow:(NSWindow *)window
1701 {
1702     // Don't do anything if we aren't initialized.  This happens
1703     // when decoding a WebView.  When WebViews are decoded their subviews
1704     // are created by initWithCoder: and so won't be normally
1705     // initialized.  The stub views are discarded by WebView.
1706     if (_private){
1707         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1708         [self removeMouseMovedObserver];
1709         [self removeWindowObservers];
1710         [self removeSuperviewObservers];
1711         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1712     
1713         [[self _pluginController] stopAllPlugins];
1714     }
1715 }
1716
1717 - (void)viewDidMoveToWindow
1718 {
1719     // Don't do anything if we aren't initialized.  This happens
1720     // when decoding a WebView.  When WebViews are decoded their subviews
1721     // are created by initWithCoder: and so won't be normally
1722     // initialized.  The stub views are discarded by WebView.
1723     if (_private) {
1724         [self _stopAutoscrollTimer];
1725         if ([self window]) {
1726             _private->lastScrollPosition = [[self superview] bounds].origin;
1727             [self addWindowObservers];
1728             [self addSuperviewObservers];
1729             [self addMouseMovedObserver];
1730             // Schedule this update, rather than making the call right now.
1731             // The reason is that placing the caret in the just-installed view requires
1732             // the HTML/XML document to be available on the WebCore side, but it is not
1733             // at the time this code is running. However, it will be there on the next
1734             // crank of the run loop. Doing this helps to make a blinking caret appear 
1735             // in a new, empty window "automatic".
1736             [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1737     
1738             [[self _pluginController] startAllPlugins];
1739     
1740             _private->lastScrollPosition = NSZeroPoint;
1741             
1742             _private->inWindow = YES;
1743         } else {
1744             // Reset when we are moved out of a window after being moved into one.
1745             // Without this check, we reset ourselves before we even start.
1746             // This is only needed because viewDidMoveToWindow is called even when
1747             // the window is not changing (bug in AppKit).
1748             if (_private->inWindow) {
1749                 [self _reset];
1750                 _private->inWindow = NO;
1751             }
1752         }
1753     }
1754 }
1755
1756 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1757 {
1758     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1759 }
1760
1761 - (void)viewDidMoveToHostWindow
1762 {
1763     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1764 }
1765
1766
1767 - (void)addSubview:(NSView *)view
1768 {
1769     [super addSubview:view];
1770
1771     if ([WebPluginController isPlugInView:view]) {
1772         [[self _pluginController] addPlugin:view];
1773     }
1774 }
1775
1776 - (void)reapplyStyles
1777 {
1778     if (!_private->needsToApplyStyles) {
1779         return;
1780     }
1781     
1782 #ifdef _KWQ_TIMING        
1783     double start = CFAbsoluteTimeGetCurrent();
1784 #endif
1785
1786     [[self _bridge] reapplyStylesForDeviceType:
1787         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1788     
1789 #ifdef _KWQ_TIMING        
1790     double thisTime = CFAbsoluteTimeGetCurrent() - start;
1791     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1792 #endif
1793
1794     _private->needsToApplyStyles = NO;
1795 }
1796
1797 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1798 // minPageWidth==0 implies a non-printing layout
1799 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1800 {
1801     [self reapplyStyles];
1802     
1803     // Ensure that we will receive mouse move events.  Is this the best place to put this?
1804     [[self window] setAcceptsMouseMovedEvents: YES];
1805     [[self window] _setShouldPostEventNotifications: YES];
1806
1807     if (!_private->needsLayout) {
1808         return;
1809     }
1810
1811 #ifdef _KWQ_TIMING        
1812     double start = CFAbsoluteTimeGetCurrent();
1813 #endif
1814
1815     LOG(View, "%@ doing layout", self);
1816
1817     if (minPageWidth > 0.0) {
1818         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1819     } else {
1820         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1821     }
1822     _private->needsLayout = NO;
1823     
1824     if (!_private->printing) {
1825         // get size of the containing dynamic scrollview, so
1826         // appearance and disappearance of scrollbars will not show up
1827         // as a size change
1828         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1829         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1830             [[self _bridge] sendResizeEvent];
1831         }
1832         _private->laidOutAtLeastOnce = YES;
1833         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1834         _private->lastLayoutFrameSize = newLayoutFrameSize;
1835     }
1836
1837 #ifdef _KWQ_TIMING        
1838     double thisTime = CFAbsoluteTimeGetCurrent() - start;
1839     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1840 #endif
1841 }
1842
1843 - (void)layout
1844 {
1845     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1846 }
1847
1848 - (NSMenu *)menuForEvent:(NSEvent *)event
1849 {
1850     [_private->compController endRevertingChange:NO moveLeft:NO];
1851
1852     if ([[self _bridge] sendContextMenuEvent:event]) {
1853         return nil;
1854     }
1855     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1856     NSDictionary *element = [self elementAtPoint:point];
1857     return [[self _webView] _menuForElement:element];
1858 }
1859
1860 // Search from the end of the currently selected location, or from the beginning of the
1861 // document if nothing is selected.
1862 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1863 {
1864     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1865 }
1866
1867 - (DOMRange *)_documentRange
1868 {
1869     return [[[self _bridge] DOMDocument] _documentRange];
1870 }
1871
1872 - (NSString *)string
1873 {
1874     return [[self _bridge] stringForRange:[self _documentRange]];
1875 }
1876
1877 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
1878 {
1879     NSAttributedString *attributedString = nil;
1880 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
1881 #if !LOG_DISABLED        
1882     double start = CFAbsoluteTimeGetCurrent();
1883 #endif    
1884     attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
1885 #if !LOG_DISABLED
1886     double duration = CFAbsoluteTimeGetCurrent() - start;
1887     LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
1888 #endif
1889 #endif
1890     return attributedString;
1891 }
1892
1893 - (NSAttributedString *)attributedString
1894 {
1895     WebBridge *bridge = [self _bridge];
1896     DOMDocument *document = [bridge DOMDocument];
1897     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
1898     if (attributedString == nil) {
1899         attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
1900     }
1901     return attributedString;
1902 }
1903
1904 - (NSString *)selectedString
1905 {
1906     return [[self _bridge] selectedString];
1907 }
1908
1909 - (NSAttributedString *)selectedAttributedString
1910 {
1911     WebBridge *bridge = [self _bridge];
1912     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
1913     if (attributedString == nil) {
1914         attributedString = [bridge selectedAttributedString];
1915     }
1916     return attributedString;
1917 }
1918
1919 - (void)selectAll
1920 {
1921     [[self _bridge] selectAll];
1922 }
1923
1924 // Remove the selection.
1925 - (void)deselectAll
1926 {
1927     [[self _bridge] deselectAll];
1928 }
1929
1930 - (void)deselectText
1931 {
1932     [[self _bridge] deselectText];
1933 }
1934
1935 - (BOOL)isOpaque
1936 {
1937     return [[self _webView] drawsBackground];
1938 }
1939
1940 - (void)setNeedsDisplay:(BOOL)flag
1941 {
1942     LOG(View, "%@ flag = %d", self, (int)flag);
1943     [super setNeedsDisplay: flag];
1944 }
1945
1946 - (void)setNeedsLayout: (BOOL)flag
1947 {
1948     LOG(View, "%@ flag = %d", self, (int)flag);
1949     _private->needsLayout = flag;
1950 }
1951
1952
1953 - (void)setNeedsToApplyStyles: (BOOL)flag
1954 {
1955     LOG(View, "%@ flag = %d", self, (int)flag);
1956     _private->needsToApplyStyles = flag;
1957 }
1958
1959 - (void)drawRect:(NSRect)rect
1960 {
1961     LOG(View, "%@ drawing", self);
1962     
1963     BOOL subviewsWereSetAside = _private->subviewsSetAside;
1964     if (subviewsWereSetAside) {
1965         [self _restoreSubviews];
1966     }
1967
1968 #ifdef _KWQ_TIMING
1969     double start = CFAbsoluteTimeGetCurrent();
1970 #endif
1971
1972     [NSGraphicsContext saveGraphicsState];
1973     NSRectClip(rect);
1974         
1975     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
1976
1977     [(WebClipView *)[self superview] setAdditionalClip:rect];
1978
1979     NS_DURING {
1980         WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
1981         if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
1982             textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
1983             [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
1984         }
1985
1986         if (![self _transparentBackground]) {
1987             [[NSColor clearColor] set];
1988             NSRectFill (rect);
1989         }
1990         
1991         //double start = CFAbsoluteTimeGetCurrent();
1992         [[self _bridge] drawRect:rect];
1993         //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
1994
1995         if (textRendererFactoryIfCoalescing != nil) {
1996             [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
1997         }
1998
1999         [(WebClipView *)[self superview] resetAdditionalClip];
2000
2001         [NSGraphicsContext restoreGraphicsState];
2002     } NS_HANDLER {
2003         [(WebClipView *)[self superview] resetAdditionalClip];
2004         [NSGraphicsContext restoreGraphicsState];
2005         ERROR("Exception caught while drawing: %@", localException);
2006         [localException raise];
2007     } NS_ENDHANDLER
2008
2009 #ifdef DEBUG_LAYOUT
2010     NSRect vframe = [self frame];
2011     [[NSColor blackColor] set];
2012     NSBezierPath *path;
2013     path = [NSBezierPath bezierPath];
2014     [path setLineWidth:(float)0.1];
2015     [path moveToPoint:NSMakePoint(0, 0)];
2016     [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2017     [path closePath];
2018     [path stroke];
2019     path = [NSBezierPath bezierPath];
2020     [path setLineWidth:(float)0.1];
2021     [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2022     [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2023     [path closePath];
2024     [path stroke];
2025 #endif
2026
2027 #ifdef _KWQ_TIMING
2028     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2029     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2030 #endif
2031
2032     if (subviewsWereSetAside) {
2033         [self _setAsideSubviews];
2034     }
2035 }
2036
2037 // Turn off the additional clip while computing our visibleRect.
2038 - (NSRect)visibleRect
2039 {
2040     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2041         return [super visibleRect];
2042         
2043     WebClipView *clipView = (WebClipView *)[self superview];
2044
2045     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2046     if (!hasAdditionalClip) {
2047         return [super visibleRect];
2048     }
2049     
2050     NSRect additionalClip = [clipView additionalClip];
2051     [clipView resetAdditionalClip];
2052     NSRect visibleRect = [super visibleRect];
2053     [clipView setAdditionalClip:additionalClip];
2054     return visibleRect;
2055 }
2056
2057 - (BOOL)isFlipped 
2058 {
2059     return YES;
2060 }
2061
2062 - (void)windowDidBecomeKey:(NSNotification *)notification
2063 {
2064     ASSERT([notification object] == [self window]);
2065     [self addMouseMovedObserver];
2066     [self updateFocusDisplay];
2067 }
2068
2069 - (void)windowDidResignKey: (NSNotification *)notification
2070 {
2071     ASSERT([notification object] == [self window]);
2072     [_private->compController endRevertingChange:NO moveLeft:NO];
2073     [self removeMouseMovedObserver];
2074     [self updateFocusDisplay];
2075 }
2076
2077 - (void)windowWillClose:(NSNotification *)notification
2078 {
2079     [_private->compController endRevertingChange:NO moveLeft:NO];
2080     [[self _pluginController] destroyAllPlugins];
2081 }
2082
2083 - (void)scrollWheel:(NSEvent *)event
2084 {
2085     if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2086         [[self nextResponder] scrollWheel:event];
2087     }    
2088 }
2089
2090 - (BOOL)_isSelectionEvent:(NSEvent *)event
2091 {
2092     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2093     return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2094 }
2095
2096 - (void)_setMouseDownEvent:(NSEvent *)event
2097 {
2098     ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2099     [event retain];
2100     [_private->mouseDownEvent release];
2101     _private->mouseDownEvent = event;
2102 }
2103
2104 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2105 {
2106     [self _setMouseDownEvent:event];
2107     
2108     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2109         return YES;
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         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2120         return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2121     } else {
2122         return [hitView acceptsFirstMouse:event];
2123     }
2124 }
2125
2126 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2127 {
2128     [self _setMouseDownEvent:event];
2129
2130     // We hack AK's hitTest method to catch all events at the topmost WebHTMLView.  However, for
2131     // the purposes of this method we want to really query the deepest view, so we forward to it.
2132     forceRealHitTest = YES;
2133     NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2134     forceRealHitTest = NO;
2135     
2136     if ([hitView isKindOfClass:[self class]]) {
2137         WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2138         return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2139     } else {
2140         return [hitView shouldDelayWindowOrderingForEvent:event];
2141     }
2142 }
2143
2144 - (void)mouseDown:(NSEvent *)event
2145 {   
2146     // Record the mouse down position so we can determine drag hysteresis.
2147     [self _setMouseDownEvent:event];
2148
2149     // TEXTINPUT: if there is marked text and the current input
2150     // manager wants to handle mouse events, we need to make sure to
2151     // pass it to them. If not, then we need to notify the input
2152     // manager when the marked text is abandoned (user clicks outside
2153     // the marked area)
2154
2155     [_private->compController endRevertingChange:NO moveLeft:NO];
2156
2157     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2158     // We don't want to pass them along to KHTML a second time.
2159     if ([event modifierFlags] & NSControlKeyMask) {
2160         return;
2161     }
2162     
2163     _private->ignoringMouseDraggedEvents = NO;
2164     
2165     // Don't do any mouseover while the mouse is down.
2166     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2167
2168     // Let KHTML get a chance to deal with the event. This will call back to us
2169     // to start the autoscroll timer if appropriate.
2170     [[self _bridge] mouseDown:event];
2171 }
2172
2173 - (void)dragImage:(NSImage *)dragImage
2174                at:(NSPoint)at
2175            offset:(NSSize)offset
2176             event:(NSEvent *)event
2177        pasteboard:(NSPasteboard *)pasteboard
2178            source:(id)source
2179         slideBack:(BOOL)slideBack
2180 {   
2181     [self _stopAutoscrollTimer];
2182     
2183     _private->initiatedDrag = YES;
2184     [[self _webView] _setInitiatedDrag:YES];
2185     
2186     // Retain this view during the drag because it may be released before the drag ends.
2187     [self retain];
2188
2189     [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2190 }
2191
2192 - (void)mouseDragged:(NSEvent *)event
2193 {
2194     // TEXTINPUT: if there is marked text and the current input
2195     // manager wants to handle mouse events, we need to make sure to
2196     // pass it to them.
2197
2198     if (!_private->ignoringMouseDraggedEvents) {
2199         [[self _bridge] mouseDragged:event];
2200     }
2201 }
2202
2203 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2204 {
2205     if (_private->webCoreDragOp == NSDragOperationNone) {
2206         return (NSDragOperationGeneric | NSDragOperationCopy);
2207     } else {
2208         return _private->webCoreDragOp;
2209     }
2210 }
2211
2212 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2213 {
2214     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2215     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2216     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2217 }
2218
2219 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2220 {
2221     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2222     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2223     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2224
2225     _private->initiatedDrag = NO;
2226     [[self _webView] _setInitiatedDrag:NO];
2227     
2228     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2229     _private->ignoringMouseDraggedEvents = YES;
2230     
2231     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2232     // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2233     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2234                                             location:windowMouseLoc
2235                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2236                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2237                                         windowNumber:[[self window] windowNumber]
2238                                              context:[[NSApp currentEvent] context]
2239                                          eventNumber:0 clickCount:0 pressure:0];
2240     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2241     
2242     // Balance the previous retain from when the drag started.
2243     [self release];
2244 }
2245
2246 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2247 {
2248     ASSERT(_private->draggingImageURL);
2249     
2250     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2251     ASSERT(wrapper);    
2252     
2253     // FIXME: Report an error if we fail to create a file.
2254     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2255     path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2256     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2257         ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2258     }
2259     
2260     return [NSArray arrayWithObject:[path lastPathComponent]];
2261 }
2262
2263 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2264 {
2265     NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2266     NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2267     [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2268     if ([types count] == 0) {
2269         return NO;
2270     } else if ([types count] == 1 && 
2271                [types containsObject:NSFilenamesPboardType] && 
2272                ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2273         return NO;
2274     }
2275     
2276     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2277     NSDictionary *element = [self elementAtPoint:point];
2278     if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2279         if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2280             // Can't drag onto the selection being dragged.
2281             return NO;
2282         }
2283         return YES;
2284     }
2285     
2286     return NO;
2287 }
2288
2289 - (BOOL)_isMoveDrag
2290 {
2291     return _private->initiatedDrag && 
2292     ([self _isEditable] && [self _hasSelection]) &&
2293     ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2294 }
2295
2296 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2297 {
2298     return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2299 }
2300
2301 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2302 {
2303     NSDragOperation operation = NSDragOperationNone;
2304     
2305     if (actionMask & WebDragDestinationActionDHTML) {
2306         operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2307     }
2308     _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2309     
2310     if ((actionMask & WebDragDestinationActionEdit) &&
2311         !_private->webCoreHandlingDrag
2312         && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2313         if ([self _isNSColorDrag:draggingInfo]) {
2314             operation = NSDragOperationGeneric;
2315         }
2316         else {
2317             WebView *webView = [self _webView];
2318             [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2319             operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2320         }
2321     } else {
2322         [[self _webView] removeDragCaret];
2323     }
2324     
2325     return operation;
2326 }
2327
2328 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2329 {
2330     [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2331     [[self _webView] removeDragCaret];
2332 }
2333
2334 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2335 {
2336     WebView *webView = [self _webView];
2337     WebBridge *bridge = [self _bridge];
2338     if (_private->webCoreHandlingDrag) {
2339         ASSERT(actionMask & WebDragDestinationActionDHTML);
2340         [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2341         [bridge concludeDragForDraggingInfo:draggingInfo];
2342         return YES;
2343     } else if (actionMask & WebDragDestinationActionEdit) {
2344         if ([self _isNSColorDrag:draggingInfo]) {
2345             NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2346             if (!color)
2347                 return NO;
2348             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2349             [style setProperty:@"color" :[self _colorAsString:color] :@""];
2350             if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2351                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2352                 [bridge applyStyle:style];
2353                 return YES;
2354             }
2355             return NO;
2356         }
2357         else {
2358             BOOL didInsert = NO;
2359             if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2360                 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2361                 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2362                 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2363                     [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2364                     if ([self _isMoveDrag]) {
2365                         BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2366                         [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2367                     } else {
2368                         [bridge setSelectionToDragCaret];
2369                         [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2370                     }
2371                     didInsert = YES;
2372                 }
2373             }
2374             [webView removeDragCaret];
2375             return didInsert;
2376         }
2377     }
2378     return NO;
2379 }
2380
2381 - (NSDictionary *)elementAtPoint:(NSPoint)point
2382 {
2383     NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2384     NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2385     
2386     // Convert URL strings to NSURLs
2387     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2388     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2389     
2390     WebFrameView *webFrameView = [self _web_parentWebFrameView];
2391     ASSERT(webFrameView);
2392     WebFrame *webFrame = [webFrameView webFrame];
2393     
2394     if (webFrame) {
2395         NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2396         if ([frameName length] == 0) {
2397             [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2398         } else {
2399             WebFrame *wf = [webFrame findFrameNamed:frameName];
2400             if (wf != nil)
2401                 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2402             else
2403                 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2404         }
2405         
2406         [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2407     }
2408     
2409     return [elementInfo autorelease];
2410 }
2411
2412 - (void)mouseUp:(NSEvent *)event
2413 {
2414     // TEXTINPUT: if there is marked text and the current input
2415     // manager wants to handle mouse events, we need to make sure to
2416     // pass it to them.
2417
2418     [self _stopAutoscrollTimer];
2419     [[self _bridge] mouseUp:event];
2420     [self _updateMouseoverWithFakeEvent];
2421 }
2422
2423 - (void)mouseMovedNotification:(NSNotification *)notification
2424 {
2425     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2426 }
2427
2428 - (BOOL)supportsTextEncoding
2429 {
2430     return YES;
2431 }
2432
2433 - (NSView *)nextValidKeyView
2434 {
2435     NSView *view = nil;
2436     if (![self isHiddenOrHasHiddenAncestor]) {
2437         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2438     }
2439     if (view == nil) {
2440         view = [super nextValidKeyView];
2441     }
2442     return view;
2443 }
2444
2445 - (NSView *)previousValidKeyView
2446 {
2447     NSView *view = nil;
2448     if (![self isHiddenOrHasHiddenAncestor]) {
2449         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2450     }
2451     if (view == nil) {
2452         view = [super previousValidKeyView];
2453     }
2454     return view;
2455 }
2456
2457 - (BOOL)becomeFirstResponder
2458 {
2459     NSView *view = nil;
2460     if (![[self _webView] _isPerformingProgrammaticFocus]) {
2461         switch ([[self window] keyViewSelectionDirection]) {
2462         case NSDirectSelection:
2463             break;
2464         case NSSelectingNext:
2465             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2466             break;
2467         case NSSelectingPrevious:
2468             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2469             break;
2470         }
2471     }
2472     if (view) {
2473         [[self window] makeFirstResponder:view];
2474     }
2475     [self updateFocusDisplay];
2476     _private->startNewKillRingSequence = YES;
2477     return YES;
2478 }
2479
2480 // This approach could be relaxed when dealing with 3228554.
2481 // Some alteration to the selection behavior was done to deal with 3672088.
2482 - (BOOL)resignFirstResponder
2483 {
2484     BOOL resign = [super resignFirstResponder];
2485     if (resign) {
2486         [_private->compController endRevertingChange:NO moveLeft:NO];
2487         _private->resigningFirstResponder = YES;
2488         if (![self maintainsInactiveSelection]) { 
2489             if ([[self _webView] _isPerformingProgrammaticFocus]) {
2490                 [self deselectText];
2491             }
2492             else {
2493                 [self deselectAll];
2494             }
2495         }
2496         [self updateFocusDisplay];
2497         _private->resigningFirstResponder = NO;
2498     }
2499     return resign;
2500 }
2501
2502 //------------------------------------------------------------------------------------
2503 // WebDocumentView protocol
2504 //------------------------------------------------------------------------------------
2505 - (void)setDataSource:(WebDataSource *)dataSource 
2506 {
2507 }
2508
2509 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2510 {
2511 }
2512
2513 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2514 // pageWidth != 0 implies we will relayout to a new width
2515 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2516 {
2517     WebFrame *frame = [self _frame];
2518     NSArray *subframes = [frame childFrames];
2519     unsigned n = [subframes count];
2520     unsigned i;
2521     for (i = 0; i != n; ++i) {
2522         WebFrame *subframe = [subframes objectAtIndex:i];
2523         WebFrameView *frameView = [subframe frameView];
2524         if ([[subframe dataSource] _isDocumentHTML]) {
2525             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2526         }
2527     }
2528
2529     if (printing != _private->printing) {
2530         [_private->pageRects release];
2531         _private->pageRects = nil;
2532         _private->printing = printing;
2533         [self setNeedsToApplyStyles:YES];
2534         [self setNeedsLayout:YES];
2535         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2536         if (printing) {
2537             [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2538         } else {
2539             // Can't do this when starting printing or nested printing won't work, see 3491427.
2540             [self setNeedsDisplay:NO];
2541         }
2542     }
2543 }
2544
2545 // This is needed for the case where the webview is embedded in the view that's being printed.
2546 // It shouldn't be called when the webview is being printed directly.
2547 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2548 {
2549     // This helps when we print as part of a larger print process.
2550     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2551     BOOL wasInPrintingMode = _private->printing;
2552     if (!wasInPrintingMode) {
2553         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2554     }
2555     
2556     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2557     
2558     if (!wasInPrintingMode) {
2559         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2560     }
2561 }
2562
2563 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2564 {
2565     NSPrintInfo *printInfo = [printOperation printInfo];
2566     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2567 }
2568
2569 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2570 {
2571     float viewWidth = NSWidth([self bounds]);
2572     if (viewWidth < 1) {
2573         ERROR("%@ has no width when printing", self);
2574         return 1.0;
2575     }
2576
2577     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2578     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2579     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2580     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2581 }
2582
2583 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2584 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2585 // if AppKit makes it SPI/API.
2586 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
2587 {
2588     return [self _scaleFactorForPrintOperation:printOperation];
2589 }
2590
2591 - (void)setPageWidthForPrinting:(float)pageWidth
2592 {
2593     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2594     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2595 }
2596
2597
2598 // Return the number of pages available for printing
2599 - (BOOL)knowsPageRange:(NSRangePointer)range {
2600     // Must do this explicit display here, because otherwise the view might redisplay while the print
2601     // sheet was up, using printer fonts (and looking different).
2602     [self displayIfNeeded];
2603     [[self window] setAutodisplay:NO];
2604     
2605     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2606     // according to the paper size
2607     float minLayoutWidth = 0.0;
2608     float maxLayoutWidth = 0.0;
2609     if (![[self _bridge] isFrameSet]) {
2610         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2611         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2612         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2613     }
2614     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2615     
2616     // There is a theoretical chance that someone could do some drawing between here and endDocument,
2617     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2618     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2619
2620     range->location = 1;
2621     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2622     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2623     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2624     [_private->pageRects release];
2625     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2626                                                                           printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2627     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2628     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2629     // a blank page (with correct-looking header and footer if that option is on), which matches
2630     // the behavior of IE and Camino at least.
2631     if ([newPageRects count] == 0) {
2632         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2633     }
2634     _private->pageRects = [newPageRects retain];
2635     
2636     range->length = [_private->pageRects count];
2637     
2638     return YES;
2639 }
2640
2641 // Return the drawing rectangle for a particular page number
2642 - (NSRect)rectForPage:(int)page {
2643     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2644 }
2645
2646 - (void)drawPageBorderWithSize:(NSSize)borderSize
2647 {
2648     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
2649     [[self _webView] _drawHeaderAndFooter];
2650 }
2651
2652 - (void)endDocument
2653 {
2654     [super endDocument];
2655     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
2656     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2657     [[self window] setAutodisplay:YES];
2658 }
2659
2660 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2661 {   
2662     // Work around this bug:
2663     // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2664     [NSKeyBindingManager sharedKeyBindingManager];
2665     
2666     // Use the isEditable state to determine whether or not to process tab key events.
2667     // The idea here is that isEditable will be NO when this WebView is being used
2668     // in a browser, and we desire the behavior where tab moves to the next element
2669     // in tab order. If isEditable is YES, it is likely that the WebView is being
2670     // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2671     // in a text editor.
2672     if (![[self _webView] isEditable] && [event _web_isTabKeyEvent]) 
2673         return NO;
2674     
2675     // Now process the key normally
2676     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2677     return YES;
2678 }
2679
2680 - (void)keyDown:(NSEvent *)event
2681 {
2682     BOOL callSuper = NO;
2683
2684     _private->keyDownEvent = event;
2685
2686     WebBridge *bridge = [self _bridge];
2687     if ([bridge interceptKeyEvent:event toView:self]) {
2688         // WebCore processed a key event, bail on any outstanding complete: UI
2689         [_private->compController endRevertingChange:YES moveLeft:NO];
2690     } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2691         // Consumed by complete: popup window
2692     } else {
2693         // We're going to process a key event, bail on any outstanding complete: UI
2694         [_private->compController endRevertingChange:YES moveLeft:NO];
2695         if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2696             // Consumed by key bindings manager.
2697         } else {
2698             callSuper = YES;
2699         }
2700     }
2701     if (callSuper) {
2702         [super keyDown:event];
2703     } else {
2704         [NSCursor setHiddenUntilMouseMoves:YES];
2705     }
2706
2707     _private->keyDownEvent = nil;
2708 }
2709
2710 - (void)keyUp:(NSEvent *)event
2711 {
2712     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2713         [super keyUp:event];
2714     }
2715 }
2716
2717 - (id)accessibilityAttributeValue:(NSString*)attributeName
2718 {
2719     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2720         id accTree = [[self _bridge] accessibilityTree];
2721         if (accTree)
2722             return [NSArray arrayWithObject: accTree];
2723         return nil;
2724     }
2725     return [super accessibilityAttributeValue:attributeName];
2726 }
2727
2728 - (id)accessibilityHitTest:(NSPoint)point
2729 {
2730     id accTree = [[self _bridge] accessibilityTree];
2731     if (accTree) {
2732         NSPoint windowCoord = [[self window] convertScreenToBase: point];
2733         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2734     }
2735     else
2736         return self;
2737 }
2738
2739 - (void)centerSelectionInVisibleArea:(id)sender
2740 {
2741     [[self _bridge] centerSelectionInVisibleArea];
2742 }
2743
2744 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2745 {
2746     WebBridge *bridge = [self _bridge];
2747     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2748     WebView *webView = [self _webView];
2749     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2750         [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2751     }
2752 }
2753
2754 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
2755 {
2756     WebBridge *bridge = [self _bridge];
2757     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
2758     WebView *webView = [self _webView];
2759     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2760         [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
2761     }
2762 }
2763
2764 - (void)moveBackward:(id)sender
2765 {
2766     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2767 }
2768
2769 - (void)moveBackwardAndModifySelection:(id)sender
2770 {
2771     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2772 }
2773
2774 - (void)moveDown:(id)sender
2775 {
2776     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2777 }
2778
2779 - (void)moveDownAndModifySelection:(id)sender
2780 {
2781     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2782 }
2783
2784 - (void)moveForward:(id)sender
2785 {
2786     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2787 }
2788
2789 - (void)moveForwardAndModifySelection:(id)sender
2790 {
2791     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2792 }
2793
2794 - (void)moveLeft:(id)sender
2795 {
2796     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2797 }
2798
2799 - (void)moveLeftAndModifySelection:(id)sender
2800 {
2801     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2802 }
2803
2804 - (void)moveRight:(id)sender
2805 {
2806     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2807 }
2808
2809 - (void)moveRightAndModifySelection:(id)sender
2810 {
2811     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2812 }
2813
2814 - (void)moveToBeginningOfDocument:(id)sender
2815 {
2816     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2817 }
2818
2819 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2820 {
2821     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2822 }
2823
2824 - (void)moveToBeginningOfLine:(id)sender
2825 {
2826     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2827 }
2828
2829 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
2830 {
2831     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2832 }
2833
2834 - (void)moveToBeginningOfParagraph:(id)sender
2835 {
2836     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2837 }
2838
2839 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
2840 {
2841     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2842 }
2843
2844 - (void)moveToEndOfDocument:(id)sender
2845 {
2846     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2847 }
2848
2849 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
2850 {
2851     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2852 }
2853
2854 - (void)moveToEndOfLine:(id)sender
2855 {
2856     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
2857 }
2858
2859 - (void)moveToEndOfLineAndModifySelection:(id)sender
2860 {
2861     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
2862 }
2863
2864 - (void)moveToEndOfParagraph:(id)sender
2865 {
2866     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2867 }
2868
2869 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
2870 {
2871     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2872 }
2873
2874 - (void)moveParagraphBackwardAndModifySelection:(id)sender
2875 {
2876     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
2877 }
2878
2879 - (void)moveParagraphForwardAndModifySelection:(id)sender
2880 {
2881     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
2882 }
2883
2884 - (void)moveUp:(id)sender
2885 {
2886     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
2887 }
2888
2889 - (void)moveUpAndModifySelection:(id)sender
2890 {
2891     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
2892 }
2893
2894 - (void)moveWordBackward:(id)sender
2895 {
2896     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
2897 }
2898
2899 - (void)moveWordBackwardAndModifySelection:(id)sender
2900 {
2901     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
2902 }
2903
2904 - (void)moveWordForward:(id)sender
2905 {
2906     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
2907 }
2908
2909 - (void)moveWordForwardAndModifySelection:(id)sender
2910 {
2911     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
2912 }
2913
2914 - (void)moveWordLeft:(id)sender
2915 {
2916     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
2917 }
2918
2919 - (void)moveWordLeftAndModifySelection:(id)sender
2920 {
2921     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
2922 }
2923
2924 - (void)moveWordRight:(id)sender
2925 {
2926     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
2927 }
2928
2929 - (void)moveWordRightAndModifySelection:(id)sender
2930 {
2931     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
2932 }
2933
2934 - (void)pageUp:(id)sender
2935 {
2936     WebFrameView *frameView = [self _web_parentWebFrameView];
2937     if (frameView == nil)
2938         return;
2939     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
2940 }
2941
2942 - (void)pageDown:(id)sender
2943 {
2944     WebFrameView *frameView = [self _web_parentWebFrameView];
2945     if (frameView == nil)
2946         return;
2947     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
2948 }
2949
2950 - (void)pageUpAndModifySelection:(id)sender
2951 {
2952     WebFrameView *frameView = [self _web_parentWebFrameView];
2953     if (frameView == nil)
2954         return;
2955     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
2956 }
2957
2958 - (void)pageDownAndModifySelection:(id)sender
2959 {
2960     WebFrameView *frameView = [self _web_parentWebFrameView];
2961     if (frameView == nil)
2962         return;
2963     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
2964 }
2965
2966 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
2967 {
2968     WebBridge *bridge = [self _bridge];
2969     DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
2970     if (range && ![range collapsed]) {
2971         WebView *webView = [self _webView];
2972         if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2973             [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
2974         }
2975     }
2976 }
2977
2978 - (void)selectParagraph:(id)sender
2979 {
2980     [self _expandSelectionToGranularity:WebSelectByParagraph];
2981 }
2982
2983 - (void)selectLine:(id)sender
2984 {
2985     [self _expandSelectionToGranularity:WebSelectByLine];
2986 }
2987
2988 - (void)selectWord:(id)sender
2989 {
2990     [self _expandSelectionToGranularity:WebSelectByWord];
2991 }
2992
2993 - (void)copy:(id)sender
2994 {
2995     if ([[self _bridge] tryDHTMLCopy]) {
2996         return;     // DHTML did the whole operation
2997     }
2998     if (![self _canCopy]) {
2999         NSBeep();
3000         return;
3001     }
3002     [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3003 }
3004
3005 - (void)delete:(id)sender
3006 {
3007     if (![self _canDelete]) {
3008         NSBeep();
3009         return;
3010     }
3011     [self _deleteSelection];
3012 }
3013
3014 - (void)cut:(id)sender
3015 {
3016     WebBridge *bridge = [self _bridge];
3017     if ([bridge tryDHTMLCut]) {
3018         return;     // DHTML did the whole operation
3019     }
3020     if (![self _canCut]) {
3021         NSBeep();
3022         return;
3023     }
3024     DOMRange *range = [self _selectedRange];
3025     if ([self _shouldDeleteRange:range]) {
3026         [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3027         [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3028    }
3029 }
3030
3031 - (void)paste:(id)sender
3032 {
3033     if ([[self _bridge] tryDHTMLPaste]) {
3034         return;     // DHTML did the whole operation
3035     }
3036     if (![self _canPaste]) {
3037         return;
3038     }
3039     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3040 }
3041
3042 - (NSData *)_selectionStartFontAttributesAsRTF
3043 {
3044     NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3045         attributes:[[self _bridge] fontAttributesForSelectionStart]];
3046     NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3047     [string release];
3048     return data;
3049 }
3050
3051 - (NSDictionary *)_fontAttributesFromFontPasteboard
3052 {
3053     NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3054     if (fontPasteboard == nil)
3055         return nil;
3056     NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3057     if (data == nil || [data length] == 0)
3058         return nil;
3059     // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3060     NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3061     if (string == nil || [string length] == 0)
3062         return nil;
3063     return [string fontAttributesInRange:NSMakeRange(0, 1)];
3064 }
3065
3066 - (DOMCSSStyleDeclaration *)_emptyStyle
3067 {
3068     return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3069 }
3070
3071 - (NSString *)_colorAsString:(NSColor *)color
3072 {
3073     NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3074     // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3075     // of fancy color that can't be converted to RGB. Changing that to "transparent"
3076     // might not be great, but it's probably OK.
3077     if (rgbColor == nil)
3078         return @"transparent";
3079     float r = [rgbColor redComponent];
3080     float g = [rgbColor greenComponent];
3081     float b = [rgbColor blueComponent];
3082     float a = [rgbColor alphaComponent];
3083     if (a == 0)
3084         return @"transparent";
3085     if (r == 0 && g == 0 && b == 0 && a == 1)
3086         return @"black";
3087     if (r == 1 && g == 1 && b == 1 && a == 1)
3088         return @"white";
3089     // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3090     if (a == 1)
3091         return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3092     return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3093 }
3094
3095 - (NSString *)_shadowAsString:(NSShadow *)shadow
3096 {
3097     if (shadow == nil)
3098         return @"none";
3099     NSSize offset = [shadow shadowOffset];
3100     float blurRadius = [shadow shadowBlurRadius];
3101     if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3102         return @"none";
3103     NSColor *color = [shadow shadowColor];
3104     if (color == nil)
3105         return @"none";
3106     // FIXME: Handle non-integral values here?
3107     if (blurRadius == 0)
3108         return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3109     return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3110 }
3111
3112 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3113 {
3114     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3115
3116     NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3117     if (color != nil) {
3118         [style setBackgroundColor:[self _colorAsString:color]];
3119     }
3120
3121     NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3122     if (font != nil) {
3123         NSFontManager *fm = [NSFontManager sharedFontManager];
3124         [style setFontFamily:[font familyName]];
3125         [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3126         if ([fm weightOfFont:font] >= 9) {
3127             [style setFontWeight:@"bold"];
3128         } else {
3129             [style setFontWeight:@"normal"];
3130         }
3131         if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3132             [style setFontStyle:@"italic"];
3133         } else {
3134             [style setFontStyle:@"normal"];
3135         }
3136     }
3137
3138     color = [dictionary objectForKey:NSForegroundColorAttributeName];
3139     if (color != nil) {
3140         [style setColor:[self _colorAsString:color]];
3141     }
3142
3143     NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3144     if (shadow) {
3145         [style setTextShadow:[self _shadowAsString:shadow]];
3146     }
3147
3148     // FIXME: NSStrikethroughStyleAttributeName
3149     // FIXME: NSSuperscriptAttributeName
3150     // FIXME: NSUnderlineStyleAttributeName
3151
3152     return style;
3153 }
3154
3155 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style
3156 {
3157     if (style == nil || [style length] == 0 || ![self _canEdit])
3158         return;
3159     WebView *webView = [self _webView];
3160     WebBridge *bridge = [self _bridge];
3161     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3162         [bridge applyStyle:style];
3163     }
3164 }
3165
3166 - (void)_toggleBold
3167 {
3168     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3169     [style setFontWeight:@"bold"];
3170     if ([[self _bridge] selectionStartHasStyle:style])
3171         [style setFontWeight:@"normal"];
3172     [self _applyStyleToSelection:style];
3173 }
3174
3175 - (void)_toggleItalic
3176 {
3177     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3178     [style setFontStyle:@"italic"];
3179     if ([[self _bridge] selectionStartHasStyle:style])
3180         [style setFontStyle:@"normal"];
3181     [self _applyStyleToSelection:style];
3182 }
3183
3184 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3185 {
3186     if (![[WebPreferences standardPreferences] respectStandardStyleKeyEquivalents]) {
3187         return NO;
3188     }
3189     
3190     if (![self _canEdit])
3191         return NO;
3192     
3193     NSString *string = [event charactersIgnoringModifiers];
3194     if ([string isEqualToString:@"b"]) {
3195         [self _toggleBold];
3196         return YES;
3197     }
3198     if ([string isEqualToString:@"i"]) {
3199         [self _toggleItalic];
3200         return YES;
3201     }
3202     
3203     return NO;
3204 }
3205
3206 - (BOOL)performKeyEquivalent:(NSEvent *)event
3207 {
3208     if ([self _handleStyleKeyEquivalent:event]) {
3209         return YES;
3210     }
3211     
3212     // Pass command-key combos through WebCore if there is a key binding available for
3213     // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3214     // But don't do it if we have already handled the event.
3215     if (event != _private->keyDownEvent
3216             && [self _web_firstResponderIsSelfOrDescendantView]
3217             && [[self _bridge] interceptKeyEvent:event toView:self]) {
3218         return YES;
3219     }
3220     return [super performKeyEquivalent:event];
3221 }
3222
3223 - (void)copyFont:(id)sender
3224 {
3225     // Put RTF with font attributes on the pasteboard.
3226     // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3227     NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3228     [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3229     [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3230 }
3231
3232 - (void)pasteFont:(id)sender
3233 {
3234     // Read RTF with font attributes from the pasteboard.
3235     // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3236     [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]]];
3237 }
3238
3239 - (void)pasteAsPlainText:(id)sender
3240 {
3241     if (![self _canEdit])
3242         return;
3243         
3244     NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3245     NSString *text = [pasteboard stringForType:NSStringPboardType];
3246     WebBridge *bridge = [self _bridge];
3247     if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3248         [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3249     }
3250 }
3251
3252 - (void)pasteAsRichText:(id)sender
3253 {
3254     // Since rich text always beats plain text when both are on the pasteboard, it's not
3255     // clear how this is different from plain old paste.
3256     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3257 }
3258
3259 - (NSFont *)_originalFontA
3260 {
3261     return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:5 size:10];
3262 }
3263
3264 - (NSFont *)_originalFontB
3265 {
3266     return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12];
3267 }
3268
3269 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3270 {
3271     if (a == nil || b == nil)
3272         return;
3273
3274     NSFontManager *fm = [NSFontManager sharedFontManager];
3275
3276     NSFont *oa = [self _originalFontA];
3277
3278     NSString *fa = [a familyName];
3279     NSString *fb = [b familyName];
3280     if ([fa isEqualToString:fb]) {
3281         [style setFontFamily:fa];
3282     }
3283
3284     int sa = [a pointSize];
3285     int sb = [b pointSize];
3286     int soa = [oa pointSize];
3287     if (sa == sb) {
3288         [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
3289     } else if (sa < soa) {
3290         // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel smaller
3291     } else if (sa > soa) {
3292         // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel larger
3293     }
3294
3295     int wa = [fm weightOfFont:a];
3296     int wb = [fm weightOfFont:b];
3297     if (wa == wb) {
3298         if (wa >= 9) {
3299             [style setFontWeight:@"bold"];
3300         } else {
3301             [style setFontWeight:@"normal"];
3302         }
3303     }
3304
3305     BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3306     BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3307     if (ia == ib) {
3308         if (ia) {
3309             [style setFontStyle:@"italic"];
3310         } else {
3311             [style setFontStyle:@"normal"];
3312         }
3313     }
3314 }
3315
3316 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3317 {
3318     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3319
3320     NSFontManager *fm = [NSFontManager sharedFontManager];
3321
3322     NSFont *oa = [self _originalFontA];
3323     NSFont *ob = [self _originalFontB];    
3324     [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
3325
3326     return style;
3327 }
3328
3329 - (void)changeFont:(id)sender
3330 {
3331     [self _applyStyleToSelection:[self _styleFromFontManagerOperation]];
3332 }
3333
3334 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
3335 {
3336     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3337
3338     NSShadow *shadow = [[NSShadow alloc] init];
3339     [shadow setShadowOffset:NSMakeSize(1, 1)];
3340
3341     NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
3342         [self _originalFontA], NSFontAttributeName,
3343         nil];
3344     NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
3345         [NSColor blackColor], NSBackgroundColorAttributeName,
3346         [self _originalFontB], NSFontAttributeName,
3347         [NSColor whiteColor], NSForegroundColorAttributeName,
3348         shadow, NSShadowAttributeName,
3349         [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
3350         [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
3351         [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
3352         nil];
3353
3354     [shadow release];
3355
3356 #if 0
3357
3358 NSObliquenessAttributeName        /* float; skew to be applied to glyphs, default 0: no skew */
3359     // font-style, but that is just an on-off switch
3360
3361 NSExpansionAttributeName          /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
3362     // font-stretch?
3363
3364 NSKernAttributeName               /* float, amount to modify default kerning, if 0, kerning off */
3365     // letter-spacing? probably not good enough
3366
3367 NSUnderlineColorAttributeName     /* NSColor, default nil: same as foreground color */
3368 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
3369     // text-decoration-color?
3370
3371 NSLigatureAttributeName           /* int, default 1: default ligatures, 0: no ligatures, 2: all ligatures */
3372 NSBaselineOffsetAttributeName     /* float, in points; offset from baseline, default 0 */
3373 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) */
3374 NSStrokeColorAttributeName        /* NSColor, default nil: same as foreground color */
3375     // need extensions?
3376
3377 #endif
3378     
3379     NSDictionary *a = [sender convertAttributes:oa];
3380     NSDictionary *b = [sender convertAttributes:ob];
3381
3382     NSColor *ca = [a objectForKey:NSBackgroundColorAttributeName];
3383     NSColor *cb = [b objectForKey:NSBackgroundColorAttributeName];
3384     if (ca == cb) {
3385         [style setBackgroundColor:[self _colorAsString:ca]];
3386     }
3387
3388     [self _addToStyle:style fontA:[a objectForKey:NSFontAttributeName] fontB:[b objectForKey:NSFontAttributeName]];
3389
3390     ca = [a objectForKey:NSForegroundColorAttributeName];
3391     cb = [b objectForKey:NSForegroundColorAttributeName];
3392     if (ca == cb) {
3393         [style setColor:[self _colorAsString:ca]];
3394     }
3395
3396     NSShadow *sha = [a objectForKey:NSShadowAttributeName];
3397     if (sha) {
3398         [style setTextShadow:[self _shadowAsString:sha]];
3399     } else if ([b objectForKey:NSShadowAttributeName] == nil) {
3400         [style setTextShadow:@"none"];
3401     }
3402
3403     int sa = [[a objectForKey:NSStrikethroughStyleAttributeName] intValue];
3404     int sb = [[b objectForKey:NSStrikethroughStyleAttributeName] intValue];
3405     if (sa == sb) {
3406         if (sa == NSUnderlineStyleNone)
3407             [style setTextDecoration:@"none"]; // we really mean "no line-through" rather than "none"
3408         else
3409             [style setTextDecoration:@"line-through"]; // we really mean "add line-through" rather than "line-through"
3410     }
3411
3412     sa = [[a objectForKey:NSSuperscriptAttributeName] intValue];
3413     sb = [[b objectForKey:NSSuperscriptAttributeName] intValue];
3414     if (sa == sb) {
3415         if (sa > 0)
3416             [style setVerticalAlign:@"super"];
3417         else if (sa < 0)
3418             [style setVerticalAlign:@"sub"];
3419         else
3420             [style setVerticalAlign:@"baseline"];
3421     }
3422
3423     int ua = [[a objectForKey:NSUnderlineStyleAttributeName] intValue];
3424     int ub = [[b objectForKey:NSUnderlineStyleAttributeName] intValue];
3425     if (ua == ub) {
3426         if (ua == NSUnderlineStyleNone)
3427             [style setTextDecoration:@"none"]; // we really mean "no underline" rather than "none"
3428         else
3429             [style setTextDecoration:@"underline"]; // we really mean "add underline" rather than "underline"
3430     }
3431
3432     return style;
3433 }
3434
3435 - (void)changeAttributes:(id)sender
3436 {
3437     [self _applyStyleToSelection:[self _styleForAttributeChange:sender]];
3438 }
3439
3440 - (DOMCSSStyleDeclaration *)_styleFromColorPanelWithSelector:(SEL)selector
3441 {
3442     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3443
3444     ASSERT([style respondsToSelector:selector]);
3445     [style performSelector:selector withObject:[self _colorAsString:[[NSColorPanel sharedColorPanel] color]]];
3446     
3447     return style;
3448 }
3449
3450 - (void)_changeCSSColorUsingSelector:(SEL)selector inRange:(DOMRange *)range
3451 {
3452     DOMCSSStyleDeclaration *style = [self _styleFromColorPanelWithSelector:selector];
3453     WebView *webView = [self _webView];
3454     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:range]) {
3455         [[self _bridge] applyStyle:style];
3456     }
3457 }
3458
3459 - (void)changeDocumentBackgroundColor:(id)sender
3460 {
3461     // Mimicking NSTextView, this method sets the background color for the
3462     // entire document. There is no NSTextView API for setting the background
3463     // color on the selected range only. Note that this method is currently
3464     // never called from the UI (see comment in changeColor:).
3465     // FIXME: this actually has no effect when called, probably due to 3654850. _documentRange seems
3466     // to do the right thing because it works in startSpeaking:, and I know setBackgroundColor: does the
3467     // right thing because I tested it with [self _selectedRange].
3468     // FIXME: This won't actually apply the style to the entire range here, because it ends up calling
3469     // [bridge applyStyle:], which operates on the current selection. To make this work right, we'll
3470     // need to save off the selection, temporarily set it to the entire range, make the change, then
3471     // restore the old selection.
3472     [self _changeCSSColorUsingSelector:@selector(setBackgroundColor:) inRange:[self _documentRange]];
3473 }
3474
3475 - (void)changeColor:(id)sender
3476 {
3477     // FIXME: in NSTextView, this method calls changeDocumentBackgroundColor: when a
3478     // private call has earlier been made by [NSFontFontEffectsBox changeColor:], see 3674493. 
3479     // AppKit will have to be revised to allow this to work with anything that isn't an 
3480     // NSTextView. However, this might not be required for Tiger, since the background-color 
3481     // changing box in the font panel doesn't work in Mail (3674481), though it does in TextEdit.
3482     [self _applyStyleToSelection:[self _styleFromColorPanelWithSelector:@selector(setColor:)]];
3483 }
3484
3485 - (void)_alignSelectionUsingCSSValue:(NSString *)CSSAlignmentValue