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