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