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