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