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