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