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