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