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