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