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