Reviewed by Darin.
[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     id nextResponder = [[self window] _newFirstResponderAfterResigning];
1787
1788     // Predict the case where we are losing first responder status only to
1789     // gain it back again.  Want to keep the selection in that case.
1790     if ([nextResponder isKindOfClass:[NSScrollView class]]) {
1791         id contentView = [nextResponder contentView];
1792         if (contentView) {
1793             nextResponder = contentView;
1794         }
1795     }
1796     if ([nextResponder isKindOfClass:[NSClipView class]]) {
1797         id documentView = [nextResponder documentView];
1798         if (documentView) {
1799             nextResponder = documentView;
1800         }
1801     }
1802
1803     if (nextResponder == self)
1804         return YES;
1805
1806     // non-editable views lose selection whenever losing first responder status
1807     if (![[self _webView] isEditable])
1808         return NO;
1809     
1810     // editable views lose selection when losing first responder status
1811     // to a widget in the same page, but not otherwise
1812     BOOL loseSelection = [nextResponder isKindOfClass:[NSView class]]
1813         && [nextResponder isDescendantOf:[self _webView]];
1814
1815     return !loseSelection;
1816 }
1817
1818 - (void)addMouseMovedObserver
1819 {
1820     // Always add a mouse move observer if the DB requested, or if we're the key window.
1821     if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1822         [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1823         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1824             name:NSMouseMovedNotification object:nil];
1825         [self _frameOrBoundsChanged];
1826     }
1827 }
1828
1829 - (void)removeMouseMovedObserver
1830 {
1831     // Don't remove the observer if we're running the DB
1832     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1833         return;
1834         
1835     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1836     [[NSNotificationCenter defaultCenter] removeObserver:self
1837         name:NSMouseMovedNotification object:nil];
1838 }
1839
1840 - (void)updateFocusDisplay
1841 {
1842     // This method does the job of updating the view based on the view's firstResponder-ness and
1843     // the window key-ness of the window containing this view. This involves three kinds of 
1844     // drawing updates right now, all handled in WebCore in response to the call over the bridge. 
1845     // 
1846     // The three display attributes are as follows:
1847     // 
1848     // 1. The background color used to draw behind selected content (active | inactive color)
1849     // 2. Caret blinking (blinks | does not blink)
1850     // 3. The drawing of a focus ring around links in web pages.
1851
1852     BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1853     [[self _bridge] setDisplaysWithFocusAttributes:flag];
1854 }
1855
1856 - (void)addSuperviewObservers
1857 {
1858     // We watch the bounds of our superview, so that we can do a layout when the size
1859     // of the superview changes. This is different from other scrollable things that don't
1860     // need this kind of thing because their layout doesn't change.
1861     
1862     // We need to pay attention to both height and width because our "layout" has to change
1863     // to extend the background the full height of the space and because some elements have
1864     // sizes that are based on the total size of the view.
1865     
1866     NSView *superview = [self superview];
1867     if (superview && [self window]) {
1868         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1869             name:NSViewFrameDidChangeNotification object:superview];
1870         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1871             name:NSViewBoundsDidChangeNotification object:superview];
1872     }
1873 }
1874
1875 - (void)removeSuperviewObservers
1876 {
1877     NSView *superview = [self superview];
1878     if (superview && [self window]) {
1879         [[NSNotificationCenter defaultCenter] removeObserver:self
1880             name:NSViewFrameDidChangeNotification object:superview];
1881         [[NSNotificationCenter defaultCenter] removeObserver:self
1882             name:NSViewBoundsDidChangeNotification object:superview];
1883     }
1884 }
1885
1886 - (void)addWindowObservers
1887 {
1888     NSWindow *window = [self window];
1889     if (window) {
1890         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1891             name:NSWindowDidBecomeKeyNotification object:window];
1892         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1893             name:NSWindowDidResignKeyNotification object:window];
1894         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1895             name:NSWindowWillCloseNotification object:window];
1896     }
1897 }
1898
1899 - (void)removeWindowObservers
1900 {
1901     NSWindow *window = [self window];
1902     if (window) {
1903         [[NSNotificationCenter defaultCenter] removeObserver:self
1904             name:NSWindowDidBecomeKeyNotification object:window];
1905         [[NSNotificationCenter defaultCenter] removeObserver:self
1906             name:NSWindowDidResignKeyNotification object:window];
1907         [[NSNotificationCenter defaultCenter] removeObserver:self
1908             name:NSWindowWillCloseNotification object:window];
1909     }
1910 }
1911
1912 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1913 {
1914     [self removeSuperviewObservers];
1915 }
1916
1917 - (void)viewDidMoveToSuperview
1918 {
1919     // Do this here in case the text size multiplier changed when a non-HTML
1920     // view was installed.
1921     if ([self superview] != nil) {
1922         [self _updateTextSizeMultiplier];
1923         [self addSuperviewObservers];
1924     }
1925 }
1926
1927 - (void)viewWillMoveToWindow:(NSWindow *)window
1928 {
1929     // Don't do anything if we aren't initialized.  This happens
1930     // when decoding a WebView.  When WebViews are decoded their subviews
1931     // are created by initWithCoder: and so won't be normally
1932     // initialized.  The stub views are discarded by WebView.
1933     if (_private){
1934         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1935         [self removeMouseMovedObserver];
1936         [self removeWindowObservers];
1937         [self removeSuperviewObservers];
1938         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1939     
1940         [[self _pluginController] stopAllPlugins];
1941     }
1942 }
1943
1944 - (void)viewDidMoveToWindow
1945 {
1946     // Don't do anything if we aren't initialized.  This happens
1947     // when decoding a WebView.  When WebViews are decoded their subviews
1948     // are created by initWithCoder: and so won't be normally
1949     // initialized.  The stub views are discarded by WebView.
1950     if (_private) {
1951         [self _stopAutoscrollTimer];
1952         if ([self window]) {
1953             _private->lastScrollPosition = [[self superview] bounds].origin;
1954             [self addWindowObservers];
1955             [self addSuperviewObservers];
1956             [self addMouseMovedObserver];
1957             // Schedule this update, rather than making the call right now.
1958             // The reason is that placing the caret in the just-installed view requires
1959             // the HTML/XML document to be available on the WebCore side, but it is not
1960             // at the time this code is running. However, it will be there on the next
1961             // crank of the run loop. Doing this helps to make a blinking caret appear 
1962             // in a new, empty window "automatic".
1963             [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1964     
1965             [[self _pluginController] startAllPlugins];
1966     
1967             _private->lastScrollPosition = NSZeroPoint;
1968             
1969             _private->inWindow = YES;
1970         } else {
1971             // Reset when we are moved out of a window after being moved into one.
1972             // Without this check, we reset ourselves before we even start.
1973             // This is only needed because viewDidMoveToWindow is called even when
1974             // the window is not changing (bug in AppKit).
1975             if (_private->inWindow) {
1976                 [self _reset];
1977                 _private->inWindow = NO;
1978             }
1979         }
1980     }
1981 }
1982
1983 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1984 {
1985     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1986 }
1987
1988 - (void)viewDidMoveToHostWindow
1989 {
1990     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1991 }
1992
1993
1994 - (void)addSubview:(NSView *)view
1995 {
1996     [super addSubview:view];
1997
1998     if ([WebPluginController isPlugInView:view]) {
1999         [[self _pluginController] addPlugin:view];
2000     }
2001 }
2002
2003 - (void)reapplyStyles
2004 {
2005     if (!_private->needsToApplyStyles) {
2006         return;
2007     }
2008     
2009 #ifdef _KWQ_TIMING        
2010     double start = CFAbsoluteTimeGetCurrent();
2011 #endif
2012
2013     [[self _bridge] reapplyStylesForDeviceType:
2014         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2015     
2016 #ifdef _KWQ_TIMING        
2017     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2018     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2019 #endif
2020
2021     _private->needsToApplyStyles = NO;
2022 }
2023
2024 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2025 // minPageWidth==0 implies a non-printing layout
2026 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2027 {
2028     [self reapplyStyles];
2029     
2030     // Ensure that we will receive mouse move events.  Is this the best place to put this?
2031     [[self window] setAcceptsMouseMovedEvents: YES];
2032     [[self window] _setShouldPostEventNotifications: YES];
2033
2034     if (!_private->needsLayout) {
2035         return;
2036     }
2037
2038 #ifdef _KWQ_TIMING        
2039     double start = CFAbsoluteTimeGetCurrent();
2040 #endif
2041
2042     LOG(View, "%@ doing layout", self);
2043
2044     if (minPageWidth > 0.0) {
2045         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2046     } else {
2047         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2048     }
2049     _private->needsLayout = NO;
2050     
2051     if (!_private->printing) {
2052         // get size of the containing dynamic scrollview, so
2053         // appearance and disappearance of scrollbars will not show up
2054         // as a size change
2055         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2056         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2057             [[self _bridge] sendResizeEvent];
2058         }
2059         _private->laidOutAtLeastOnce = YES;
2060         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2061         _private->lastLayoutFrameSize = newLayoutFrameSize;
2062     }
2063
2064 #ifdef _KWQ_TIMING        
2065     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2066     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2067 #endif
2068 }
2069
2070 - (void)layout
2071 {
2072     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2073 }
2074
2075 - (NSMenu *)menuForEvent:(NSEvent *)event
2076 {
2077     [_private->compController endRevertingChange:NO moveLeft:NO];
2078
2079     if ([[self _bridge] sendContextMenuEvent:event]) {
2080         return nil;
2081     }
2082     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2083     NSDictionary *element = [self elementAtPoint:point];
2084     return [[self _webView] _menuForElement:element];
2085 }
2086
2087 // Search from the end of the currently selected location, or from the beginning of the
2088 // document if nothing is selected.
2089 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
2090 {
2091     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
2092 }
2093
2094 - (DOMRange *)_documentRange
2095 {
2096     return [[[self _bridge] DOMDocument] _documentRange];
2097 }
2098
2099 - (NSString *)string
2100 {
2101     return [[self _bridge] stringForRange:[self _documentRange]];
2102 }
2103
2104 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2105 {
2106     NSAttributedString *attributedString = nil;
2107 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
2108 #if !LOG_DISABLED        
2109     double start = CFAbsoluteTimeGetCurrent();
2110 #endif    
2111     attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2112 #if !LOG_DISABLED
2113     double duration = CFAbsoluteTimeGetCurrent() - start;
2114     LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2115 #endif
2116 #endif
2117     return attributedString;
2118 }
2119
2120 - (NSAttributedString *)attributedString
2121 {
2122     WebBridge *bridge = [self _bridge];
2123     DOMDocument *document = [bridge DOMDocument];
2124     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2125     if (attributedString == nil) {
2126         attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2127     }
2128     return attributedString;
2129 }
2130
2131 - (NSString *)selectedString
2132 {
2133     return [[self _bridge] selectedString];
2134 }
2135
2136 - (NSAttributedString *)selectedAttributedString
2137 {
2138     WebBridge *bridge = [self _bridge];
2139     NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2140     if (attributedString == nil) {
2141         attributedString = [bridge selectedAttributedString];
2142     }
2143     return attributedString;
2144 }
2145
2146 - (void)selectAll
2147 {
2148     [[self _bridge] selectAll];
2149 }
2150
2151 // Remove the selection.
2152 - (void)deselectAll
2153 {
2154     [[self _bridge] deselectAll];
2155 }
2156
2157 - (void)deselectText
2158 {
2159     [[self _bridge] deselectText];
2160 }
2161
2162 - (BOOL)isOpaque
2163 {
2164     return [[self _webView] drawsBackground];
2165 }
2166
2167 - (void)setNeedsDisplay:(BOOL)flag
2168 {
2169     LOG(View, "%@ flag = %d", self, (int)flag);
2170     [super setNeedsDisplay: flag];
2171 }
2172
2173 - (void)setNeedsLayout: (BOOL)flag
2174 {
2175     LOG(View, "%@ flag = %d", self, (int)flag);
2176     _private->needsLayout = flag;
2177 }
2178
2179
2180 - (void)setNeedsToApplyStyles: (BOOL)flag
2181 {
2182     LOG(View, "%@ flag = %d", self, (int)flag);
2183     _private->needsToApplyStyles = flag;
2184 }
2185
2186 - (void)drawRect:(NSRect)rect
2187 {
2188     LOG(View, "%@ drawing", self);
2189
2190     // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2191     // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2192     // This does a better job of clipping out rects that are entirely outside the visible area.
2193     const NSRect *rects;
2194     int count;
2195     [self getRectsBeingDrawn:&rects count:&count];
2196
2197     // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2198     // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2199     // The reason for the workaround is that this method is called explicitly from the code
2200     // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2201     if (count > 0) {
2202         rect = NSZeroRect;
2203         int i;
2204         for (i = 0; i < count; ++i) {
2205             rect = NSUnionRect(rect, rects[i]);
2206         }
2207         if (rect.size.height == 0 || rect.size.width == 0) {
2208             return;
2209         }
2210     }
2211
2212     BOOL subviewsWereSetAside = _private->subviewsSetAside;
2213     if (subviewsWereSetAside) {
2214         [self _restoreSubviews];
2215     }
2216
2217 #ifdef _KWQ_TIMING
2218     double start = CFAbsoluteTimeGetCurrent();
2219 #endif
2220
2221     [NSGraphicsContext saveGraphicsState];
2222     NSRectClip(rect);
2223         
2224     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2225
2226     [(WebClipView *)[self superview] setAdditionalClip:rect];
2227
2228     NS_DURING {
2229         WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2230         if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2231             textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2232             [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2233         }
2234
2235         if ([self _transparentBackground]) {
2236             [[NSColor clearColor] set];
2237             NSRectFill (rect);
2238         }
2239         
2240         //double start = CFAbsoluteTimeGetCurrent();
2241         [[self _bridge] drawRect:rect];
2242         //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2243
2244         if (textRendererFactoryIfCoalescing != nil) {
2245             [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2246         }
2247
2248         [(WebClipView *)[self superview] resetAdditionalClip];
2249
2250         [NSGraphicsContext restoreGraphicsState];
2251     } NS_HANDLER {
2252         [(WebClipView *)[self superview] resetAdditionalClip];
2253         [NSGraphicsContext restoreGraphicsState];
2254         ERROR("Exception caught while drawing: %@", localException);
2255         [localException raise];
2256     } NS_ENDHANDLER
2257
2258 #ifdef DEBUG_LAYOUT
2259     NSRect vframe = [self frame];
2260     [[NSColor blackColor] set];
2261     NSBezierPath *path;
2262     path = [NSBezierPath bezierPath];
2263     [path setLineWidth:(float)0.1];
2264     [path moveToPoint:NSMakePoint(0, 0)];
2265     [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2266     [path closePath];
2267     [path stroke];
2268     path = [NSBezierPath bezierPath];
2269     [path setLineWidth:(float)0.1];
2270     [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2271     [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2272     [path closePath];
2273     [path stroke];
2274 #endif
2275
2276 #ifdef _KWQ_TIMING
2277     double thisTime = CFAbsoluteTimeGetCurrent() - start;
2278     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2279 #endif
2280
2281     if (subviewsWereSetAside) {
2282         [self _setAsideSubviews];
2283     }
2284 }
2285
2286 // Turn off the additional clip while computing our visibleRect.
2287 - (NSRect)visibleRect
2288 {
2289     if (!([[self superview] isKindOfClass:[WebClipView class]]))
2290         return [super visibleRect];
2291         
2292     WebClipView *clipView = (WebClipView *)[self superview];
2293
2294     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2295     if (!hasAdditionalClip) {
2296         return [super visibleRect];
2297     }
2298     
2299     NSRect additionalClip = [clipView additionalClip];
2300     [clipView resetAdditionalClip];
2301     NSRect visibleRect = [super visibleRect];
2302     [clipView setAdditionalClip:additionalClip];
2303     return visibleRect;
2304 }
2305
2306 - (BOOL)isFlipped 
2307 {
2308     return YES;
2309 }
2310
2311 - (void)windowDidBecomeKey:(NSNotification *)notification
2312 {
2313     ASSERT([notification object] == [self window]);
2314     [self addMouseMovedObserver];
2315     [self updateFocusDisplay];
2316 }
2317
2318 - (void)windowDidResignKey: (NSNotification *)notification
2319 {
2320     ASSERT([notification object] == [self window]);
2321     [_private->compController endRevertingChange:NO moveLeft:NO];
2322     [self removeMouseMovedObserver];
2323     [self updateFocusDisplay];
2324 }
2325
2326 - (void)windowWillClose:(NSNotification *)notification
2327 {
2328     [_private->compController endRevertingChange:NO moveLeft:NO];
2329     [[self _pluginController] destroyAllPlugins];
2330 }
2331
2332 - (void)scrollWheel:(NSEvent *)event
2333 {
2334     if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2335         [[self nextResponder] scrollWheel:event];
2336     }    
2337 }
2338
2339 - (BOOL)_isSelectionEvent:(NSEvent *)event
2340 {
2341     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2342     return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2343 }
2344
2345 - (void)_setMouseDownEvent:(NSEvent *)event
2346 {
2347     ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2348
2349     if (event == _private->mouseDownEvent) {
2350         return;
2351     }
2352
2353     [event retain];
2354     [_private->mouseDownEvent release];
2355     _private->mouseDownEvent = event;
2356
2357     [_private->firstResponderAtMouseDownTime release];
2358     _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2359 }
2360
2361 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2362 {
2363     [self _setMouseDownEvent:event];
2364     
2365     if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2366         return YES;
2367         
2368     // We hack AK's hitTest method to catch all events at the topmost WebHTMLView.  However, for
2369     // the purposes of this method we want to really query the deepest view, so we forward to it.
2370     forceRealHitTest = YES;
2371     NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2372     forceRealHitTest = NO;
2373     
2374     if ([hitView isKindOfClass:[self class]]) {
2375         WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2376         [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2377         return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2378     } else {
2379         return [hitView acceptsFirstMouse:event];
2380     }
2381 }
2382
2383 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2384 {
2385     [self _setMouseDownEvent:event];
2386
2387     // We hack AK's hitTest method to catch all events at the topmost WebHTMLView.  However, for
2388     // the purposes of this method we want to really query the deepest view, so we forward to it.
2389     forceRealHitTest = YES;
2390     NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2391     forceRealHitTest = NO;
2392     
2393     if ([hitView isKindOfClass:[self class]]) {
2394         WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2395         return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2396     } else {
2397         return [hitView shouldDelayWindowOrderingForEvent:event];
2398     }
2399 }
2400
2401 - (void)mouseDown:(NSEvent *)event
2402 {
2403     _private->handlingMouseDownEvent = YES;
2404
2405     // Record the mouse down position so we can determine drag hysteresis.
2406     [self _setMouseDownEvent:event];
2407
2408     // TEXTINPUT: if there is marked text and the current input
2409     // manager wants to handle mouse events, we need to make sure to
2410     // pass it to them. If not, then we need to notify the input
2411     // manager when the marked text is abandoned (user clicks outside
2412     // the marked area)
2413
2414     [_private->compController endRevertingChange:NO moveLeft:NO];
2415
2416     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2417     // We don't want to pass them along to KHTML a second time.
2418     if (!([event modifierFlags] & NSControlKeyMask)) {
2419         _private->ignoringMouseDraggedEvents = NO;
2420
2421         // Don't do any mouseover while the mouse is down.
2422         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2423
2424         // Let KHTML get a chance to deal with the event. This will call back to us
2425         // to start the autoscroll timer if appropriate.
2426         [[self _bridge] mouseDown:event];
2427     }
2428
2429     [_private->firstResponderAtMouseDownTime release];
2430     _private->firstResponderAtMouseDownTime = nil;
2431
2432     _private->handlingMouseDownEvent = NO;
2433 }
2434
2435 - (void)dragImage:(NSImage *)dragImage
2436                at:(NSPoint)at
2437            offset:(NSSize)offset
2438             event:(NSEvent *)event
2439        pasteboard:(NSPasteboard *)pasteboard
2440            source:(id)source
2441         slideBack:(BOOL)slideBack
2442 {   
2443     [self _stopAutoscrollTimer];
2444     
2445     _private->initiatedDrag = YES;
2446     [[self _webView] _setInitiatedDrag:YES];
2447     
2448     // Retain this view during the drag because it may be released before the drag ends.
2449     [self retain];
2450
2451     [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2452 }
2453
2454 - (void)mouseDragged:(NSEvent *)event
2455 {
2456     // TEXTINPUT: if there is marked text and the current input
2457     // manager wants to handle mouse events, we need to make sure to
2458     // pass it to them.
2459
2460     if (!_private->ignoringMouseDraggedEvents) {
2461         [[self _bridge] mouseDragged:event];
2462     }
2463 }
2464
2465 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2466 {
2467     if (_private->webCoreDragOp == NSDragOperationNone) {
2468         return (NSDragOperationGeneric | NSDragOperationCopy);
2469     } else {
2470         return _private->webCoreDragOp;
2471     }
2472 }
2473
2474 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2475 {
2476     NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2477     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2478     [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2479 }
2480
2481 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2482 {
2483     NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2484     NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2485     [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2486
2487     _private->initiatedDrag = NO;
2488     [[self _webView] _setInitiatedDrag:NO];
2489     
2490     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2491     _private->ignoringMouseDraggedEvents = YES;
2492     
2493     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2494     // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2495     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2496                                             location:windowMouseLoc
2497                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
2498                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
2499                                         windowNumber:[[self window] windowNumber]
2500                                              context:[[NSApp currentEvent] context]
2501                                          eventNumber:0 clickCount:0 pressure:0];
2502     [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2503     
2504     // Balance the previous retain from when the drag started.
2505     [self release];
2506 }
2507
2508 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2509 {
2510     ASSERT(_private->draggingImageURL);
2511     
2512     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2513     ASSERT(wrapper);    
2514     
2515     // FIXME: Report an error if we fail to create a file.
2516     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2517     path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2518     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2519         ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2520     }
2521     
2522     return [NSArray arrayWithObject:[path lastPathComponent]];
2523 }
2524
2525 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2526 {
2527     NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2528     NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2529     [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2530     if ([types count] == 0) {
2531         return NO;
2532     } else if ([types count] == 1 && 
2533                [types containsObject:NSFilenamesPboardType] && 
2534                ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2535         return NO;
2536     }
2537     
2538     NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2539     NSDictionary *element = [self elementAtPoint:point];
2540     if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2541         if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2542             // Can't drag onto the selection being dragged.
2543             return NO;
2544         }
2545         return YES;
2546     }
2547     
2548     return NO;
2549 }
2550
2551 - (BOOL)_isMoveDrag
2552 {
2553     return _private->initiatedDrag && 
2554     ([self _isEditable] && [self _hasSelection]) &&
2555     ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2556 }
2557
2558 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2559 {
2560     return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2561 }
2562
2563 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2564 {
2565     NSDragOperation operation = NSDragOperationNone;
2566     
2567     if (actionMask & WebDragDestinationActionDHTML) {
2568         operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2569     }
2570     _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2571     
2572     if ((actionMask & WebDragDestinationActionEdit) &&
2573         !_private->webCoreHandlingDrag
2574         && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2575         if ([self _isNSColorDrag:draggingInfo]) {
2576             operation = NSDragOperationGeneric;
2577         }
2578         else {
2579             WebView *webView = [self _webView];
2580             [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2581             operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2582         }
2583     } else {
2584         [[self _webView] removeDragCaret];
2585     }
2586     
2587     return operation;
2588 }
2589
2590 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2591 {
2592     [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2593     [[self _webView] removeDragCaret];
2594 }
2595
2596 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2597 {
2598     WebView *webView = [self _webView];
2599     WebBridge *bridge = [self _bridge];
2600     if (_private->webCoreHandlingDrag) {
2601         ASSERT(actionMask & WebDragDestinationActionDHTML);
2602         [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2603         [bridge concludeDragForDraggingInfo:draggingInfo];
2604         return YES;
2605     } else if (actionMask & WebDragDestinationActionEdit) {
2606         if ([self _isNSColorDrag:draggingInfo]) {
2607             NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2608             if (!color)
2609                 return NO;
2610             DOMCSSStyleDeclaration *style = [self _emptyStyle];
2611             [style setProperty:@"color" :[self _colorAsString:color] :@""];
2612             if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2613                 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2614                 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2615                 return YES;
2616             }
2617             return NO;
2618         }
2619         else {
2620             BOOL didInsert = NO;
2621             if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2622                 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2623                 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2624                 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2625                     [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2626                     if ([self _isMoveDrag]) {
2627                         BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2628                         [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2629                     } else {
2630                         [bridge setSelectionToDragCaret];
2631                         [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2632                     }
2633                     didInsert = YES;
2634                 }
2635             }
2636             [webView removeDragCaret];
2637             return didInsert;
2638         }
2639     }
2640     return NO;
2641 }
2642
2643 - (NSDictionary *)elementAtPoint:(NSPoint)point
2644 {
2645     NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2646     NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2647     
2648     // Convert URL strings to NSURLs
2649     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2650     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2651     
2652     WebFrameView *webFrameView = [self _web_parentWebFrameView];
2653     ASSERT(webFrameView);
2654     WebFrame *webFrame = [webFrameView webFrame];
2655     
2656     if (webFrame) {
2657         NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2658         if ([frameName length] == 0) {
2659             [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2660         } else {
2661             WebFrame *wf = [webFrame findFrameNamed:frameName];
2662             if (wf != nil)
2663                 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2664             else
2665                 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2666         }
2667         
2668         [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2669     }
2670     
2671     return [elementInfo autorelease];
2672 }
2673
2674 - (void)mouseUp:(NSEvent *)event
2675 {
2676     // TEXTINPUT: if there is marked text and the current input
2677     // manager wants to handle mouse events, we need to make sure to
2678     // pass it to them.
2679
2680     [self _stopAutoscrollTimer];
2681     [[self _bridge] mouseUp:event];
2682     [self _updateMouseoverWithFakeEvent];
2683 }
2684
2685 - (void)mouseMovedNotification:(NSNotification *)notification
2686 {
2687     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2688 }
2689
2690 - (BOOL)supportsTextEncoding
2691 {
2692     return YES;
2693 }
2694
2695 - (NSView *)nextValidKeyView
2696 {
2697     NSView *view = nil;
2698     if (![self isHiddenOrHasHiddenAncestor]) {
2699         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2700     }
2701     if (view == nil) {
2702         view = [super nextValidKeyView];
2703     }
2704     return view;
2705 }
2706
2707 - (NSView *)previousValidKeyView
2708 {
2709     NSView *view = nil;
2710     if (![self isHiddenOrHasHiddenAncestor]) {
2711         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2712     }
2713     if (view == nil) {
2714         view = [super previousValidKeyView];
2715     }
2716     return view;
2717 }
2718
2719 - (BOOL)becomeFirstResponder
2720 {
2721     NSView *view = nil;
2722     if (![[self _webView] _isPerformingProgrammaticFocus]) {
2723         switch ([[self window] keyViewSelectionDirection]) {
2724         case NSDirectSelection:
2725             break;
2726         case NSSelectingNext:
2727             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2728             break;
2729         case NSSelectingPrevious:
2730             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2731             break;
2732         }
2733     }
2734     if (view) {
2735         [[self window] makeFirstResponder:view];
2736     }
2737     [self updateFocusDisplay];
2738     _private->startNewKillRingSequence = YES;
2739     return YES;
2740 }
2741
2742 // This approach could be relaxed when dealing with 3228554.
2743 // Some alteration to the selection behavior was done to deal with 3672088.
2744 - (BOOL)resignFirstResponder
2745 {
2746     BOOL resign = [super resignFirstResponder];
2747     if (resign) {
2748         [_private->compController endRevertingChange:NO moveLeft:NO];
2749         _private->resigningFirstResponder = YES;
2750         if (![self maintainsInactiveSelection]) { 
2751             if ([[self _webView] _isPerformingProgrammaticFocus]) {
2752                 [self deselectText];
2753             }
2754             else {
2755                 [self deselectAll];
2756             }
2757         }
2758         [self updateFocusDisplay];
2759         _private->resigningFirstResponder = NO;
2760     }
2761     return resign;
2762 }
2763
2764 //------------------------------------------------------------------------------------
2765 // WebDocumentView protocol
2766 //------------------------------------------------------------------------------------
2767 - (void)setDataSource:(WebDataSource *)dataSource 
2768 {
2769 }
2770
2771 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2772 {
2773 }
2774
2775 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2776 // pageWidth != 0 implies we will relayout to a new width
2777 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2778 {
2779     WebFrame *frame = [self _frame];
2780     NSArray *subframes = [frame childFrames];
2781     unsigned n = [subframes count];
2782     unsigned i;
2783     for (i = 0; i != n; ++i) {
2784         WebFrame *subframe = [subframes objectAtIndex:i];
2785         WebFrameView *frameView = [subframe frameView];
2786         if ([[subframe dataSource] _isDocumentHTML]) {
2787             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2788         }
2789     }
2790
2791     if (printing != _private->printing) {
2792         [_private->pageRects release];
2793         _private->pageRects = nil;
2794         _private->printing = printing;
2795         [self setNeedsToApplyStyles:YES];
2796         [self setNeedsLayout:YES];
2797         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2798         if (printing) {
2799             [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2800         } else {
2801             // Can't do this when starting printing or nested printing won't work, see 3491427.
2802             [self setNeedsDisplay:NO];
2803         }
2804     }
2805 }
2806
2807 - (BOOL)canPrintHeadersAndFooters
2808 {
2809     return YES;
2810 }
2811
2812 // This is needed for the case where the webview is embedded in the view that's being printed.
2813 // It shouldn't be called when the webview is being printed directly.
2814 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2815 {
2816     // This helps when we print as part of a larger print process.
2817     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2818     BOOL wasInPrintingMode = _private->printing;
2819     if (!wasInPrintingMode) {
2820         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2821     }
2822     
2823     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2824     
2825     if (!wasInPrintingMode) {
2826         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2827     }
2828 }
2829
2830 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2831 {
2832     NSPrintInfo *printInfo = [printOperation printInfo];
2833     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2834 }
2835
2836 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2837 {
2838     float viewWidth = NSWidth([self bounds]);
2839     if (viewWidth < 1) {
2840         ERROR("%@ has no width when printing", self);
2841         return 1.0;
2842     }
2843
2844     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2845     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2846     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2847     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2848 }
2849
2850 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2851 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2852 // if AppKit makes it SPI/API.
2853 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
2854 {
2855     return [self _scaleFactorForPrintOperation:printOperation];
2856 }
2857
2858 - (void)setPageWidthForPrinting:(float)pageWidth
2859 {
2860     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2861     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2862 }
2863
2864
2865 // Return the number of pages available for printing
2866 - (BOOL)knowsPageRange:(NSRangePointer)range {
2867     // Must do this explicit display here, because otherwise the view might redisplay while the print
2868     // sheet was up, using printer fonts (and looking different).
2869     [self displayIfNeeded];
2870     [[self window] setAutodisplay:NO];
2871     
2872     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2873     // according to the paper size
2874     float minLayoutWidth = 0.0;
2875     float maxLayoutWidth = 0.0;
2876     if (![[self _bridge] isFrameSet]) {
2877         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2878         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2879         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2880     }
2881     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2882     
2883     // There is a theoretical chance that someone could do some drawing between here and endDocument,
2884     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2885     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2886
2887     range->location = 1;
2888     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2889     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2890     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2891     [_private->pageRects release];
2892     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2893                                                                           printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2894     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2895     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2896     // a blank page (with correct-looking header and footer if that option is on), which matches
2897     // the behavior of IE and Camino at least.
2898     if ([newPageRects count] == 0) {
2899         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2900     }
2901     _private->pageRects = [newPageRects retain];
2902     
2903     range->length = [_private->pageRects count];
2904     
2905     return YES;
2906 }
2907
2908 // Return the drawing rectangle for a particular page number
2909 - (NSRect)rectForPage:(int)page {
2910     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2911 }
2912
2913 - (void)drawPageBorderWithSize:(NSSize)borderSize
2914 {
2915     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
2916     [[self _webView] _drawHeaderAndFooter];
2917 }
2918
2919 - (void)beginDocument
2920 {
2921     NS_DURING
2922         [super beginDocument];
2923     NS_HANDLER
2924         // Exception during [super beginDocument] means that endDocument will not get called,
2925         // so we need to clean up our "print mode" here.
2926         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2927         [[self window] setAutodisplay:YES];
2928     NS_ENDHANDLER
2929 }
2930
2931 - (void)endDocument
2932 {
2933     [super endDocument];
2934     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
2935     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2936     [[self window] setAutodisplay:YES];
2937 }
2938
2939 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2940 {   
2941     // Work around this bug:
2942     // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2943     [NSKeyBindingManager sharedKeyBindingManager];
2944     
2945     // Use the isEditable state to determine whether or not to process tab key events.
2946     // The idea here is that isEditable will be NO when this WebView is being used
2947     // in a browser, and we desire the behavior where tab moves to the next element
2948     // in tab order. If isEditable is YES, it is likely that the WebView is being
2949     // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2950     // in a text editor.
2951     if (![[self _webView] isEditable] && [event _web_isTabKeyEvent]) 
2952         return NO;
2953     
2954     // Now process the key normally
2955     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2956     return YES;
2957 }
2958
2959 - (void)keyDown:(NSEvent *)event
2960 {
2961     BOOL callSuper = NO;
2962
2963     _private->keyDownEvent = event;
2964
2965     WebBridge *bridge = [self _bridge];
2966     if ([bridge interceptKeyEvent:event toView:self]) {
2967         // WebCore processed a key event, bail on any outstanding complete: UI
2968         [_private->compController endRevertingChange:YES moveLeft:NO];
2969     } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2970         // Consumed by complete: popup window
2971     } else {
2972         // We're going to process a key event, bail on any outstanding complete: UI
2973         [_private->compController endRevertingChange:YES moveLeft:NO];
2974         if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2975             // Consumed by key bindings manager.
2976         } else {
2977             callSuper = YES;
2978         }
2979     }
2980     if (callSuper) {
2981         [super keyDown:event];
2982     } else {
2983         [NSCursor setHiddenUntilMouseMoves:YES];
2984     }
2985
2986     _private->keyDownEvent = nil;
2987 }
2988
2989 - (void)keyUp:(NSEvent *)event
2990 {
2991     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2992         [super keyUp:event];
2993     }
2994 }
2995
2996 - (id)accessibilityAttributeValue:(NSString*)attributeName
2997 {
2998     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2999         id accTree = [[self _bridge] accessibilityTree];
3000         if (accTree)
3001             return [NSArray arrayWithObject: accTree];
3002         return nil;
3003     }
3004     return [super accessibilityAttributeValue:attributeName];
3005 }
3006
3007 - (id)accessibilityFocusedUIElement
3008 {
3009     id accTree = [[self _bridge] accessibilityTree];
3010     if (accTree)
3011         return [accTree accessibilityFocusedUIElement];
3012     else
3013         return self;
3014 }
3015
3016 - (id)accessibilityHitTest:(NSPoint)point
3017 {
3018     id accTree = [[self _bridge] accessibilityTree];
3019     if (accTree) {
3020         NSPoint windowCoord = [[self window] convertScreenToBase: point];
3021         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
3022     }
3023     else
3024         return self;
3025 }
3026
3027 - (id)_accessibilityParentForSubview:(NSView *)subview {
3028     id accTree = [[self _bridge] accessibilityTree];
3029     if (!accTree)
3030         return self;
3031         
3032     id parent = [accTree _accessibilityParentForSubview:subview];
3033     if (parent == nil)
3034         return self;
3035
3036     return parent;
3037 }
3038
3039 - (void)centerSelectionInVisibleArea:(id)sender
3040 {
3041     [[self _bridge] centerSelectionInVisibleArea];
3042 }
3043
3044 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
3045 {
3046     WebBridge *bridge = [self _bridge];
3047     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
3048     WebView *webView = [self _webView];
3049     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3050         [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
3051     }
3052 }
3053
3054 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
3055 {
3056     WebBridge *bridge = [self _bridge];
3057     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
3058     WebView *webView = [self _webView];
3059     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3060         [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
3061     }
3062 }
3063
3064 - (void)moveBackward:(id)sender
3065 {
3066     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
3067 }
3068
3069 - (void)moveBackwardAndModifySelection:(id)sender
3070 {
3071     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
3072 }
3073
3074 - (void)moveDown:(id)sender
3075 {
3076     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
3077 }
3078
3079 - (void)moveDownAndModifySelection:(id)sender
3080 {
3081     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
3082 }
3083
3084 - (void)moveForward:(id)sender
3085 {
3086     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
3087 }
3088
3089 - (void)moveForwardAndModifySelection:(id)sender
3090 {
3091     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
3092 }
3093
3094 - (void)moveLeft:(id)sender
3095 {
3096     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
3097 }
3098
3099 - (void)moveLeftAndModifySelection:(id)sender
3100 {
3101     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
3102 }
3103
3104 - (void)moveRight:(id)sender
3105 {
3106     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
3107 }
3108
3109 - (void)moveRightAndModifySelection:(id)sender
3110 {
3111     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
3112 }
3113
3114 - (void)moveToBeginningOfDocument:(id)sender
3115 {
3116     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3117 }
3118
3119 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3120 {
3121     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3122 }
3123
3124 - (void)moveToBeginningOfLine:(id)sender
3125 {
3126     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3127 }
3128
3129 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3130 {
3131     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3132 }
3133
3134 - (void)moveToBeginningOfParagraph:(id)sender
3135 {
3136     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3137 }
3138
3139 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3140 {
3141     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3142 }
3143
3144 - (void)moveToEndOfDocument:(id)sender
3145 {
3146     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3147 }
3148
3149 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3150 {
3151     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3152 }
3153
3154 - (void)moveToEndOfLine:(id)sender
3155 {
3156     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
3157 }
3158
3159 - (void)moveToEndOfLineAndModifySelection:(id)sender
3160 {
3161     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
3162 }
3163
3164 - (void)moveToEndOfParagraph:(id)sender
3165 {
3166     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3167 }
3168
3169 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3170 {
3171     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3172 }
3173
3174 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3175 {
3176     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
3177 }
3178
3179 - (void)moveParagraphForwardAndModifySelection:(id)sender
3180 {
3181     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
3182 }
3183
3184 - (void)moveUp:(id)sender
3185 {
3186     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
3187 }
3188
3189 - (void)moveUpAndModifySelection:(id)sender
3190 {
3191     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3192 }
3193
3194 - (void)moveWordBackward:(id)sender
3195 {
3196     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3197 }
3198
3199 - (void)moveWordBackwardAndModifySelection:(id)sender
3200 {
3201     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3202 }
3203
3204 - (void)moveWordForward:(id)sender
3205 {
3206     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3207 }
3208
3209 - (void)moveWordForwardAndModifySelection:(id)sender
3210 {
3211     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3212 }
3213
3214 - (void)moveWordLeft:(id)sender
3215 {
3216     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3217 }
3218
3219 - (void)moveWordLeftAndModifySelection:(id)sender
3220 {
3221     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3222 }
3223
3224 - (void)moveWordRight:(id)sender
3225 {
3226     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3227 }
3228
3229 - (void)moveWordRightAndModifySelection:(id)sender
3230 {
3231     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3232 }
3233
3234 - (void)pageUp:(id)sender
3235 {
3236     WebFrameView *frameView = [self _web_parentWebFrameView];
3237     if (frameView == nil)
3238         return;
3239     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3240 }
3241
3242 - (void)pageDown:(id)sender
3243 {
3244     WebFrameView *frameView = [self _web_parentWebFrameView];
3245     if (frameView == nil)
3246         return;
3247     [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3248 }
3249
3250 - (void)pageUpAndModifySelection:(id)sender
3251 {
3252     WebFrameView *frameView = [self _web_parentWebFrameView];
3253     if (frameView == nil)
3254         return;
3255     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3256 }
3257
3258 - (void)pageDownAndModifySelection:(id)sender
3259 {
3260     WebFrameView *frameView = [self _web_parentWebFrameView];
3261     if (frameView == nil)
3262         return;
3263     [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3264 }
3265
3266 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3267 {
3268     WebBridge *bridge = [self _bridge];
3269     DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3270     if (range && ![range collapsed]) {
3271         WebView *webView = [self _webView];
3272         if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3273             [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
3274         }
3275     }
3276 }
3277
3278 - (void)selectParagraph:(id)sender
3279 {
3280     [self _expandSelectionToGranularity:WebSelectByParagraph];
3281 }
3282
3283 - (void)selectLine:(id)sender
3284 {
3285     [self _expandSelectionToGranularity:WebSelectByLine];
3286 }
3287
3288 - (void)selectWord:(id)sender
3289 {
3290     [self _expandSelectionToGranularity:WebSelectByWord];
3291 }
3292
3293 - (void)copy:(id)sender
3294 {
3295     if ([[self _bridge] tryDHTMLCopy]) {
3296         return;     // DHTML did the whole operation
3297     }
3298     if (![self _canCopy]) {
3299         NSBeep();
3300         return;
3301     }
3302     [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3303 }
3304
3305 - (void)delete:(id)sender
3306 {
3307     if (![self _canDelete]) {
3308         NSBeep();
3309         return;
3310     }
3311     [self _deleteSelection];
3312 }
3313
3314 - (void)cut:(id)sender
3315 {
3316     WebBridge *bridge = [self _bridge];
3317     if ([bridge tryDHTMLCut]) {
3318         return;     // DHTML did the whole operation
3319     }
3320     if (![self _canCut]) {
3321         NSBeep();
3322         return;
3323     }
3324     DOMRange *range = [self _selectedRange];
3325     if ([self _shouldDeleteRange:range]) {
3326         [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3327         [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3328    }
3329 }
3330
3331 - (void)paste:(id)sender
3332 {
3333     if ([[self _bridge] tryDHTMLPaste]) {
3334         return;     // DHTML did the whole operation
3335     }
3336     if (![self _canPaste]) {
3337         return;
3338     }
3339     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3340 }
3341
3342 - (NSData *)_selectionStartFontAttributesAsRTF
3343 {
3344     NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3345         attributes:[[self _bridge] fontAttributesForSelectionStart]];
3346     NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3347     [string release];
3348     return data;
3349 }
3350
3351 - (NSDictionary *)_fontAttributesFromFontPasteboard
3352 {
3353     NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3354     if (fontPasteboard == nil)
3355         return nil;
3356     NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3357     if (data == nil || [data length] == 0)
3358         return nil;
3359     // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3360     NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3361     if (string == nil || [string length] == 0)
3362         return nil;
3363     return [string fontAttributesInRange:NSMakeRange(0, 1)];
3364 }
3365
3366 - (DOMCSSStyleDeclaration *)_emptyStyle
3367 {
3368     return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3369 }
3370
3371 - (NSString *)_colorAsString:(NSColor *)color
3372 {
3373     NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3374     // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3375     // of fancy color that can't be converted to RGB. Changing that to "transparent"
3376     // might not be great, but it's probably OK.
3377     if (rgbColor == nil)
3378         return @"transparent";
3379     float r = [rgbColor redComponent];
3380     float g = [rgbColor greenComponent];
3381     float b = [rgbColor blueComponent];
3382     float a = [rgbColor alphaComponent];
3383     if (a == 0)
3384         return @"transparent";
3385     if (r == 0 && g == 0 && b == 0 && a == 1)
3386         return @"black";
3387     if (r == 1 && g == 1 && b == 1 && a == 1)
3388         return @"white";
3389     // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3390     if (a == 1)
3391         return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3392     return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3393 }
3394
3395 - (NSString *)_shadowAsString:(NSShadow *)shadow
3396 {
3397     if (shadow == nil)
3398         return @"none";
3399     NSSize offset = [shadow shadowOffset];
3400     float blurRadius = [shadow shadowBlurRadius];
3401     if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3402         return @"none";
3403     NSColor *color = [shadow shadowColor];
3404     if (color == nil)
3405         return @"none";
3406     // FIXME: Handle non-integral values here?
3407     if (blurRadius == 0)
3408         return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3409     return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3410 }
3411
3412 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3413 {
3414     DOMCSSStyleDeclaration *style = [self _emptyStyle];
3415
3416     NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3417     [style setBackgroundColor:[self _colorAsString:color]];
3418
3419     NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3420     if (font == nil) {
3421         [style setFontFamily:@"Helvetica"];
3422         [style setFontSize:@"12px"];
3423         [style setFontWeight:@"normal"];
3424         [style setFontStyle:@"normal"];
3425     } else {
3426         NSFontManager *fm = [NSFontManager sharedFontManager];
3427         [style setFontFamily:[font familyName]];
3428         [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3429         if ([fm weightOfFont:font] >= 9) {
3430             [style setFontWeight:@"bold"];
3431         } else {
3432             [style setFontWeight:@"normal"];
3433         }
3434         if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3435             [style setFontStyle:@"italic"];
3436         } else {
3437             [style setFontStyle:@"normal"];
3438         }
3439     }
3440
3441     color = [dictionary objectForKey:NSForegroundColorAttributeName];
3442     [style setColor:color ? [self _colorAsString:color] : @"black"];
3443
3444     NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3445     [style setTextShadow:[self _shadowAsString:shadow]];
3446
3447     int strikethroughInt = [[dictionary objectForKey:NSStrikethroughStyleAttributeName] intValue];
3448
3449     int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3450     if (superscriptInt > 0)
3451         [style setVerticalAlign:@"super"];
3452     else if (superscriptInt < 0)
3453         [style setVerticalAlign:@"sub"];
3454     else
3455         [style setVerticalAlign:@"baseline"];
3456     int underlineInt = [[dictionary objectForKey:NSUnderlineStyleAttributeName] intValue];
3457     // FIXME: Underline wins here if we have both (see bug 3790443).
3458     if (strikethroughInt == NSUnderlineStyleNone && underlineInt == NSUnderlineStyleNone)
3459         [style setProperty:@"-khtml-text-decorations-in-effect" :@"none" :@""];
3460     else if (underlineInt == NSUnderlineStyleNone)
3461         [style setProperty:@"-khtml-text-decorations-in-effect" :@"line-through" :@""];
3462     else
3463         [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
3464
3465     return style;
3466 }
3467
3468 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3469 {
3470     if (style == nil || [style length] == 0 || ![self _canEdit])
3471         return;
3472     WebView *webView = [self _webView];
3473     WebBridge *bridge = [self _bridge];
3474     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3475         [bridge applyStyle:style withUndoAction:undoAction];
3476     }
3477 }
3478
3479 - (void)_toggleBold
3480 {