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