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