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