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