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