WebCore:
[WebKit-https.git] / WebKit / WebView.subproj / WebHTMLView.m
1 /*
2     WebHTMLView.m
3     Copyright 2002, Apple, Inc. All rights reserved.
4 */
5
6 #import <WebKit/WebHTMLView.h>
7
8 #import <WebKit/DOM.h>
9 #import <WebKit/DOMExtensions.h>
10 #import <WebKit/WebArchive.h>
11 #import <WebKit/WebBridge.h>
12 #import <WebKit/WebClipView.h>
13 #import <WebKit/WebDataProtocol.h>
14 #import <WebKit/WebDataSourcePrivate.h>
15 #import <WebKit/WebDocumentInternal.h>
16 #import <WebKit/WebDOMOperations.h>
17 #import <WebKit/WebEditingDelegate.h>
18 #import <WebKit/WebException.h>
19 #import <WebKit/WebFramePrivate.h>
20 #import <WebKit/WebFrameViewPrivate.h>
21 #import <WebKit/WebHTMLViewInternal.h>
22 #import <WebKit/WebHTMLRepresentationPrivate.h>
23 #import <WebKit/WebImageRenderer.h>
24 #import <WebKit/WebImageRendererFactory.h>
25 #import <WebKit/WebKitLogging.h>
26 #import <WebKit/WebKitNSStringExtras.h>
27 #import <WebKit/WebNetscapePluginEmbeddedView.h>
28 #import <WebKit/WebNSEventExtras.h>
29 #import <WebKit/WebNSImageExtras.h>
30 #import <WebKit/WebNSObjectExtras.h>
31 #import <WebKit/WebNSPasteboardExtras.h>
32 #import <WebKit/WebNSPrintOperationExtras.h>
33 #import <WebKit/WebNSURLExtras.h>
34 #import <WebKit/WebNSViewExtras.h>
35 #import <WebKit/WebPluginController.h>
36 #import <WebKit/WebPreferences.h>
37 #import <WebKit/WebResourcePrivate.h>
38 #import <WebKit/WebStringTruncator.h>
39 #import <WebKit/WebTextRenderer.h>
40 #import <WebKit/WebTextRendererFactory.h>
41 #import <WebKit/WebUIDelegatePrivate.h>
42 #import <WebKit/WebUnicode.h>
43 #import <WebKit/WebViewInternal.h>
44 #import <WebKit/WebViewPrivate.h>
45
46 #import <AppKit/NSAccessibility.h>
47 #import <AppKit/NSGraphicsContextPrivate.h>
48 #import <AppKit/NSResponder_Private.h>
49
50 #import <Foundation/NSFileManager_NSURLExtras.h>
51 #import <Foundation/NSURL_NSURLExtras.h>
52 #import <Foundation/NSURLFileTypeMappings.h>
53
54 #import <CoreGraphics/CGContextGState.h>
55
56 // 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 *)nextValidKeyView
2036 {
2037     NSView *view = nil;
2038     if (![self isHiddenOrHasHiddenAncestor]) {
2039         view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2040     }
2041     if (view == nil) {
2042         view = [super nextValidKeyView];
2043     }
2044     return view;
2045 }
2046
2047 - (NSView *)previousValidKeyView
2048 {
2049     NSView *view = nil;
2050     if (![self isHiddenOrHasHiddenAncestor]) {
2051         view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2052     }
2053     if (view == nil) {
2054         view = [super previousValidKeyView];
2055     }
2056     return view;
2057 }
2058
2059 - (BOOL)becomeFirstResponder
2060 {
2061     NSView *view = nil;
2062     if (![[self _webView] _isPerformingProgrammaticFocus]) {
2063         switch ([[self window] keyViewSelectionDirection]) {
2064         case NSDirectSelection:
2065             break;
2066         case NSSelectingNext:
2067             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2068             break;
2069         case NSSelectingPrevious:
2070             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2071             break;
2072         }
2073     }
2074     if (view) {
2075         [[self window] makeFirstResponder:view];
2076     }
2077     [self updateFocusDisplay];
2078     return YES;
2079 }
2080
2081 // This approach could be relaxed when dealing with 3228554.
2082 // Some alteration to the selection behavior was done to deal with 3672088.
2083 - (BOOL)resignFirstResponder
2084 {
2085     BOOL resign = [super resignFirstResponder];
2086     if (resign) {
2087         _private->resigningFirstResponder = YES;
2088         if (![self maintainsInactiveSelection]) { 
2089             if ([[self _webView] _isPerformingProgrammaticFocus]) {
2090                 [self deselectText];
2091             }
2092             else {
2093                 [self deselectAll];
2094             }
2095         }
2096         [self updateFocusDisplay];
2097         _private->resigningFirstResponder = NO;
2098     }
2099     return resign;
2100 }
2101
2102 //------------------------------------------------------------------------------------
2103 // WebDocumentView protocol
2104 //------------------------------------------------------------------------------------
2105 - (void)setDataSource:(WebDataSource *)dataSource 
2106 {
2107 }
2108
2109 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2110 {
2111 }
2112
2113 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2114 // pageWidth != 0 implies we will relayout to a new width
2115 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2116 {
2117     WebFrame *frame = [self _frame];
2118     NSArray *subframes = [frame childFrames];
2119     unsigned n = [subframes count];
2120     unsigned i;
2121     for (i = 0; i != n; ++i) {
2122         WebFrame *subframe = [subframes objectAtIndex:i];
2123         WebFrameView *frameView = [subframe frameView];
2124         if ([[subframe dataSource] _isDocumentHTML]) {
2125             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2126         }
2127     }
2128
2129     if (printing != _private->printing) {
2130         [_private->pageRects release];
2131         _private->pageRects = nil;
2132         _private->printing = printing;
2133         [self setNeedsToApplyStyles:YES];
2134         [self setNeedsLayout:YES];
2135         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2136         if (printing) {
2137             [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2138         } else {
2139             // Can't do this when starting printing or nested printing won't work, see 3491427.
2140             [self setNeedsDisplay:NO];
2141         }
2142     }
2143 }
2144
2145 // This is needed for the case where the webview is embedded in the view that's being printed.
2146 // It shouldn't be called when the webview is being printed directly.
2147 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2148 {
2149     // This helps when we print as part of a larger print process.
2150     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2151     BOOL wasInPrintingMode = _private->printing;
2152     if (!wasInPrintingMode) {
2153         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2154     }
2155     
2156     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2157     
2158     if (!wasInPrintingMode) {
2159         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2160     }
2161 }
2162
2163 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2164 {
2165     NSPrintInfo *printInfo = [printOperation printInfo];
2166     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2167 }
2168
2169 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2170 {
2171     float viewWidth = NSWidth([self bounds]);
2172     if (viewWidth < 1) {
2173         ERROR("%@ has no width when printing", self);
2174         return 1.0;
2175     }
2176
2177     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2178     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2179     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2180     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2181 }
2182
2183 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2184 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2185 // if AppKit makes it SPI/API.
2186 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
2187 {
2188     return [self _scaleFactorForPrintOperation:printOperation];
2189 }
2190
2191 - (void)setPageWidthForPrinting:(float)pageWidth
2192 {
2193     [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2194     [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2195 }
2196
2197
2198 // Return the number of pages available for printing
2199 - (BOOL)knowsPageRange:(NSRangePointer)range {
2200     // Must do this explicit display here, because otherwise the view might redisplay while the print
2201     // sheet was up, using printer fonts (and looking different).
2202     [self displayIfNeeded];
2203     [[self window] setAutodisplay:NO];
2204     
2205     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2206     // according to the paper size
2207     float minLayoutWidth = 0.0;
2208     float maxLayoutWidth = 0.0;
2209     if (![[self _bridge] isFrameSet]) {
2210         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2211         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2212         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2213     }
2214     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2215     
2216     // There is a theoretical chance that someone could do some drawing between here and endDocument,
2217     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2218     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2219
2220     range->location = 1;
2221     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2222     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2223     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2224     [_private->pageRects release];
2225     NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2226                                                                           printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2227     // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2228     // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2229     // a blank page (with correct-looking header and footer if that option is on), which matches
2230     // the behavior of IE and Camino at least.
2231     if ([newPageRects count] == 0) {
2232         newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2233     }
2234     _private->pageRects = [newPageRects retain];
2235     
2236     range->length = [_private->pageRects count];
2237     
2238     return YES;
2239 }
2240
2241 // Return the drawing rectangle for a particular page number
2242 - (NSRect)rectForPage:(int)page {
2243     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2244 }
2245
2246 // Calculate the vertical size of the view that fits on a single page
2247 - (float)_calculatePrintHeight {
2248     // Obtain the print info object for the current operation
2249     NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
2250     
2251     // Calculate the page height in points
2252     NSSize paperSize = [pi paperSize];
2253     return paperSize.height - [pi topMargin] - [pi bottomMargin];
2254 }
2255
2256 - (void)drawPageBorderWithSize:(NSSize)borderSize
2257 {
2258     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
2259     [[self _webView] _drawHeaderAndFooter];
2260 }
2261
2262 - (void)endDocument
2263 {
2264     [super endDocument];
2265     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
2266     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2267     [[self window] setAutodisplay:YES];
2268 }
2269
2270 - (void)_updateTextSizeMultiplier
2271 {
2272     [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];    
2273 }
2274
2275 - (BOOL)performKeyEquivalent:(NSEvent *)event
2276 {
2277     // Pass command-key combos through WebCore if there is a key binding available for
2278     // this event. This lets web pages have a crack at intercepting command-modified keypresses.
2279     if ([self _web_firstResponderIsSelfOrDescendantView] && [[self _bridge] interceptKeyEvent:event toView:self]) {
2280         return YES;
2281     }
2282     return [super performKeyEquivalent:event];
2283 }
2284
2285 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2286 {   
2287     // Work around this bug:
2288     // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2289     [NSKeyBindingManager sharedKeyBindingManager];
2290     
2291     // Use the isEditable state to determine whether or not to process tab key events.
2292     // The idea here is that isEditable will be NO when this WebView is being used
2293     // in a browser, and we desire the behavior where tab moves to the next element
2294     // in tab order. If isEditable is YES, it is likely that the WebView is being
2295     // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2296     // in a text editor.
2297     if (![[self _webView] isEditable] && [event _web_isTabKeyEvent]) 
2298         return NO;
2299     
2300     // Now process the key normally
2301     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2302     return YES;
2303 }
2304
2305 - (void)keyDown:(NSEvent *)event
2306 {
2307     WebBridge *bridge = [self _bridge];
2308     if ([bridge interceptKeyEvent:event toView:self])
2309         return;
2310         
2311     if (([[self _webView] isEditable] || [bridge isSelectionEditable]) && [self _interceptEditingKeyEvent:event]) 
2312         return;
2313     
2314     [super keyDown:event];
2315 }
2316
2317 - (void)keyUp:(NSEvent *)event
2318 {
2319     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2320         [super keyUp:event];
2321     }
2322 }
2323
2324 - (id)accessibilityAttributeValue:(NSString*)attributeName
2325 {
2326     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2327         id accTree = [[self _bridge] accessibilityTree];
2328         if (accTree)
2329             return [NSArray arrayWithObject: accTree];
2330         return nil;
2331     }
2332     return [super accessibilityAttributeValue:attributeName];
2333 }
2334
2335 - (id)accessibilityHitTest:(NSPoint)point
2336 {
2337     id accTree = [[self _bridge] accessibilityTree];
2338     if (accTree) {
2339         NSPoint windowCoord = [[self window] convertScreenToBase: point];
2340         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2341     }
2342     else
2343         return self;
2344 }
2345
2346 - (void)centerSelectionInVisibleArea:(id)sender
2347 {
2348     // FIXME: Does this do the right thing when the selection is not a caret?
2349     [[self _bridge] ensureCaretVisible];
2350 }
2351
2352 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2353 {
2354     WebBridge *bridge = [self _bridge];
2355     DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2356     WebView *webView = [self _webView];
2357     if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[bridge selectedDOMRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2358         [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2359     }
2360 }
2361
2362 - (void)moveBackward:(id)sender
2363 {
2364     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2365 }
2366
2367 - (void)moveBackwardAndModifySelection:(id)sender
2368 {
2369     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2370 }
2371
2372 - (void)moveDown:(id)sender
2373 {
2374     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2375 }
2376
2377 - (void)moveDownAndModifySelection:(id)sender
2378 {
2379     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2380 }
2381
2382 - (void)moveForward:(id)sender
2383 {
2384     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2385 }
2386
2387 - (void)moveForwardAndModifySelection:(id)sender
2388 {
2389     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2390 }
2391
2392 - (void)moveLeft:(id)sender
2393 {
2394     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2395 }
2396
2397 - (void)moveLeftAndModifySelection:(id)sender
2398 {
2399     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2400 }
2401
2402 - (void)moveRight:(id)sender
2403 {
2404     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2405 }
2406
2407 - (void)moveRightAndModifySelection:(id)sender
2408 {
2409     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2410 }
2411
2412 - (void)moveToBeginningOfDocument:(id)sender
2413 {
2414     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByDocument];
2415 }
2416
2417 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2418 {
2419     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByDocument];
2420 }
2421
2422 - (void)moveToBeginningOfLine:(id)sender
2423 {
2424     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectToLineBoundary];
2425 }
2426
2427 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
2428 {
2429     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectToLineBoundary];
2430 }
2431
2432 - (void)moveToBeginningOfParagraph:(id)sender
2433 {
2434     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByParagraph];
2435 }
2436
2437 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
2438 {
2439     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByParagraph];
2440 }
2441
2442 - (void)moveToEndOfDocument:(id)sender
2443 {
2444     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByDocument];
2445 }
2446
2447 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
2448 {
2449     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByDocument];
2450 }
2451
2452 - (void)moveToEndOfLine:(id)sender
2453 {
2454     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectToLineBoundary];
2455 }
2456
2457 - (void)moveToEndOfLineAndModifySelection:(id)sender
2458 {
2459     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectToLineBoundary];
2460 }
2461
2462 - (void)moveToEndOfParagraph:(id)sender
2463 {
2464     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByParagraph];
2465 }
2466
2467 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
2468 {
2469     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByParagraph];
2470 }
2471
2472 - (void)moveUp:(id)sender
2473 {
2474     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
2475 }
2476
2477 - (void)moveUpAndModifySelection:(id)sender
2478 {
2479     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
2480 }
2481
2482 - (void)moveWordBackward:(id)sender
2483 {
2484     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
2485 }
2486
2487 - (void)moveWordBackwardAndModifySelection:(id)sender
2488 {
2489     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
2490 }
2491
2492 - (void)moveWordForward:(id)sender
2493 {
2494     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
2495 }
2496
2497 - (void)moveWordForwardAndModifySelection:(id)sender
2498 {
2499     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
2500 }
2501
2502 - (void)moveWordLeft:(id)sender
2503 {
2504     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
2505 }
2506
2507 - (void)moveWordLeftAndModifySelection:(id)sender
2508 {
2509     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
2510 }
2511
2512 - (void)moveWordRight:(id)sender
2513 {
2514     [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
2515 }
2516
2517 - (void)moveWordRightAndModifySelection:(id)sender
2518 {
2519     [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
2520 }
2521
2522 - (void)pageDown:(id)sender
2523 {
2524     // FIXME: This should to scroll page down, then move the caret to the top left.
2525     ERROR("unimplemented");
2526 }
2527
2528 - (void)pageUp:(id)sender
2529 {
2530     // FIXME: This should to scroll page up, then move the caret to the top left.
2531     ERROR("unimplemented");
2532 }
2533
2534 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
2535 {
2536     WebBridge *bridge = [self _bridge];
2537     DOMRange *range = [bridge selectedDOMRangeWithGranularity:granularity];
2538     if (range && ![range collapsed]) {
2539         WebView *webView = [self _webView];
2540         if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[bridge selectedDOMRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2541             [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
2542         }
2543     }
2544 }
2545
2546 - (void)selectParagraph:(id)sender
2547 {
2548     [self _expandSelectionToGranularity:WebSelectByParagraph];
2549 }
2550
2551 - (void)selectLine:(id)sender
2552 {
2553     [self _expandSelectionToGranularity:WebSelectByLine];
2554 }
2555
2556 - (void)selectWord:(id)sender
2557 {
2558     [self _expandSelectionToGranularity:WebSelectByWord];
2559 }
2560
2561 - (void)copy:(id)sender
2562 {
2563     if ([[self _bridge] tryDHTMLCopy]) {
2564         return;     // DHTML did the whole operation
2565     }
2566
2567     if (![self _haveSelection]) {
2568         NSBeep();
2569         return;
2570     }
2571     [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
2572 }
2573
2574 - (void)cut:(id)sender
2575 {
2576     if ([[self _bridge] tryDHTMLCut]) {
2577         return;     // DHTML did the whole operation
2578     }
2579
2580     if (![self _haveSelection]) {
2581         NSBeep();
2582         return;
2583     }
2584     [self copy:sender];
2585     [[self _bridge] deleteSelection];
2586 }
2587
2588 - (void)delete:(id)sender
2589 {
2590     if (![self _haveSelection]) {
2591         NSBeep();
2592         return;
2593     }
2594     [[self _bridge] deleteSelection];
2595 }
2596
2597 - (void)paste:(id)sender
2598 {
2599     if ([[self _bridge] tryDHTMLPaste]) {
2600         return;     // DHTML did the whole operation
2601     }
2602
2603     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
2604 }
2605
2606 - (void)copyFont:(id)sender
2607 {
2608     // Font is RTF with a single character in it.
2609     // NSTextView uses the first character in the selection, or a space if there are no characters.
2610     ERROR("unimplemented");
2611 }
2612
2613 - (void)pasteFont:(id)sender
2614 {
2615     // FIXME: Support RTF to HTML (or DOM) conversion.
2616     // Font is RTF. Call fontAttributesInRange to extract the attributes to apply.
2617     // Then convert the RTF into CSS.
2618     ERROR("unimplemented");
2619 }
2620
2621 - (void)pasteAsPlainText:(id)sender
2622 {
2623     NSString *text = [[NSPasteboard generalPasteboard] stringForType:NSStringPboardType];
2624     WebView *webView = [self _webView];
2625     WebBridge *bridge = [self _bridge];
2626     if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
2627         [bridge replaceSelectionWithText:text selectReplacement:NO];
2628     }
2629 }
2630
2631 - (void)pasteAsRichText:(id)sender
2632 {
2633     [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
2634 }
2635
2636 - (DOMCSSStyleDeclaration *)_fontManagerOperationAsStyle
2637 {
2638     WebBridge *bridge = [self _bridge];
2639     DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2640
2641     NSFontManager *fm = [NSFontManager sharedFontManager];
2642
2643     NSFont *a = [fm convertFont:[fm fontWithFamily:@"Helvetica" traits:0 weight:5 size:10]];
2644     NSFont *b = [fm convertFont:[fm fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12]];
2645     
2646     NSString *fa = [a familyName];
2647     NSString *fb = [b familyName];
2648     if ([fa isEqualToString:fb]) {
2649         [style setFontFamily:fa];
2650     }
2651
2652     int sa = [a pointSize];
2653     int sb = [b pointSize];
2654     if (sa == sb) {
2655         [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
2656     }
2657
2658     int wa = [fm weightOfFont:a];
2659     int wb = [fm weightOfFont:b];
2660     if (wa == wb) {
2661         if (wa >= 9) {
2662             [style setFontWeight:@"bold"];
2663         } else {
2664             [style setFontWeight:@"normal"];
2665         }
2666     }
2667
2668     BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
2669     BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
2670     if (ia == ib) {
2671         if (ia) {
2672             [style setFontStyle:@"italic"];
2673         } else {
2674             [style setFontStyle:@"normal"];
2675         }
2676     }
2677
2678     return style;
2679 }
2680
2681 - (void)changeFont:(id)sender
2682 {
2683     DOMCSSStyleDeclaration *style = [self _fontManagerOperationAsStyle];
2684     WebView *webView = [self _webView];
2685     WebBridge *bridge = [self _bridge];
2686     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2687         [bridge applyStyle:style];
2688     }
2689 }
2690
2691 - (void)changeAttributes:(id)sender
2692 {
2693     // Used for various fancy stuff from the font panel.
2694     // Turn the attributes into CSS and then call applyStyle.
2695     ERROR("unimplemented");
2696 }
2697
2698 - (DOMCSSStyleDeclaration *)_colorPanelColorAsStyleUsingSelector:(SEL)selector
2699 {
2700     WebBridge *bridge = [self _bridge];
2701     DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2702     NSColor *color = [[NSColorPanel sharedColorPanel] color];
2703     NSString *colorAsString = [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", [color redComponent]*255, [color greenComponent]*255, [color blueComponent]*255];
2704     ASSERT([style respondsToSelector:selector]);
2705     [style performSelector:selector withObject:colorAsString];
2706     
2707     return style;
2708 }
2709
2710 - (void)_changeCSSColorUsingSelector:(SEL)selector inRange:(DOMRange *)range
2711 {
2712     DOMCSSStyleDeclaration *style = [self _colorPanelColorAsStyleUsingSelector:selector];
2713     WebView *webView = [self _webView];
2714     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:range]) {
2715         [[self _bridge] applyStyle:style];
2716     }
2717 }
2718
2719 - (DOMRange *)_entireDOMRange
2720 {
2721     DOMDocument *document = [[self _bridge] DOMDocument];
2722     DOMRange *range = [document createRange];
2723     [range selectNode:[document documentElement]];
2724     return range;
2725 }
2726
2727 - (void)changeDocumentBackgroundColor:(id)sender
2728 {
2729     // Mimicking NSTextView, this method sets the background color for the
2730     // entire document. There is no NSTextView API for setting the background
2731     // color on the selected range only. Note that this method is currently
2732     // never called from the UI (see comment in changeColor:).
2733     // FIXME: this actually has no effect when called, probably due to 3654850. _entireDOMRange seems
2734     // to do the right thing because it works in startSpeaking:, and I know setBackgroundColor: does the
2735     // right thing because I tested it with [[self _bridge] selectedDOMRange].
2736     // FIXME: This won't actually apply the style to the entire range here, because it ends up calling
2737     // [bridge applyStyle:], which operates on the current selection. To make this work right, we'll
2738     // need to save off the selection, temporarily set it to the entire range, make the change, then
2739     // restore the old selection.
2740     [self _changeCSSColorUsingSelector:@selector(setBackgroundColor:) inRange:[self _entireDOMRange]];
2741 }
2742
2743 - (void)changeColor:(id)sender
2744 {
2745     // FIXME: in NSTextView, this method calls changeDocumentBackgroundColor: when a
2746     // private call has earlier been made by [NSFontFontEffectsBox changeColor:], see 3674493. 
2747     // AppKit will have to be revised to allow this to work with anything that isn't an 
2748     // NSTextView. However, this might not be required for Tiger, since the background-color 
2749     // changing box in the font panel doesn't work in Mail (3674481), though it does in TextEdit.
2750     [self _changeCSSColorUsingSelector:@selector(setColor:) inRange:[[self _bridge] selectedDOMRange]];
2751 }
2752
2753 - (void)_alignSelectionUsingCSSValue:(NSString *)CSSAlignmentValue
2754 {
2755     // FIXME 3675191: This doesn't work yet. Maybe it's blocked by 3654850, or maybe something other than
2756     // just applyStyle: needs to be called for block-level attributes like this.
2757     WebBridge *bridge = [self _bridge];
2758     DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2759     [style setTextAlign:CSSAlignmentValue];
2760     WebView *webView = [self _webView];
2761     if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2762         [[self _bridge] applyStyle:style];
2763     }
2764 }
2765
2766 - (void)alignCenter:(id)sender
2767 {
2768     [self _alignSelectionUsingCSSValue:@"center"];
2769 }
2770
2771 - (void)alignJustified:(id)sender
2772 {
2773     [self _alignSelectionUsingCSSValue:@"justify"];
2774 }
2775
2776 - (void)alignLeft:(id)sender
2777 {
2778     [self _alignSelectionUsingCSSValue:@"left"];
2779 }
2780
2781 - (void)alignRight:(id)sender
2782 {
2783     [self _alignSelectionUsingCSSValue:@"right"];
2784 }
2785
2786 - (void)indent:(id)sender
2787 {
2788     // Figure out current indent level.
2789     // Turn new indent level into CSS, then call applyStyle:.
2790     ERROR("unimplemented");
2791 }
2792
2793 - (void)insertTab:(id)sender
2794 {
2795     WebView *webView = [self _webView];
2796     WebBridge *bridge = [self _bridge];
2797     if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:@"\t" replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
2798         [bridge insertText:@"\t"];
2799     }
2800 }
2801
2802 - (void)insertBacktab:(id)sender
2803 {
2804     // Doing nothing matches normal NSTextView behavior. If we ever use WebView for a field-editor-type purpose
2805     // we might add code here.
2806 }
2807
2808 - (void)insertNewline:(id)sender
2809 {
2810     // Perhaps we should make this delegate call sensitive to the real DOM operation we actually do.
2811     WebView *webView = [self _webView];
2812     WebBridge *bridge = [self _bridge];
2813     if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:@"\n" replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
2814         [bridge insertNewline];
2815     }
2816 }
2817
2818 - (void)insertParagraphSeparator:(id)sender
2819 {
2820     // FIXME: Should this do something different?
2821     [self insertNewline:sender];
2822 }
2823
2824 - (void)changeCaseOfLetter:(id)sender
2825 {
2826     ERROR("unimplemented");
2827 }
2828
2829 - (void)_changeWordCaseWithSelector:(SEL)selector
2830 {
2831     WebView *webView = [self _webView];
2832     WebBridge *bridge = [self _bridge];
2833     [self selectWord:nil];
2834     NSString *word = [[bridge selectedString] performSelector:selector];
2835     // FIXME: Does this need a different action context other than "typed"?
2836     if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:word replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
2837         [bridge replaceSelectionWithText:word selectReplacement:NO];
2838     }
2839 }
2840
2841 - (void)uppercaseWord:(id)sender
2842 {
2843     [self _changeWordCaseWithSelector:@selector(uppercaseString)];
2844 }
2845
2846 - (void)lowercaseWord:(id)sender
2847 {
2848     [self _changeWordCaseWithSelector:@selector(lowercaseString)];
2849 }
2850
2851 - (void)capitalizeWord:(id)sender
2852 {
2853     [self _changeWordCaseWithSelector:@selector(capitalizedString)];
2854 }
2855
2856 - (void)deleteForward:(id)sender
2857 {
2858     ERROR("unimplemented");
2859 }
2860
2861 - (void)deleteBackward:(id)sender
2862 {
2863     WebBridge *bridge = [self _bridge];
2864     if ([bridge isSelectionEditable]) {
2865         WebView *webView = [self _webView];
2866         if ([[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:[bridge selectedDOMRange]]) {
2867             [bridge deleteKeyPressed];
2868         }
2869     }
2870 }
2871
2872 - (void)deleteBackwardByDecomposingPreviousCharacter:(id)sender
2873 {
2874     ERROR("unimplemented");
2875 }
2876
2877 - (void)deleteWordForward:(id)sender
2878 {
2879     [self moveWordForwardAndModifySelection:sender];
2880     [self delete:sender];
2881 }
2882
2883 - (void)deleteWordBackward:(id)sender
2884 {
2885     [self moveWordBackwardAndModifySelection:sender];
2886     [self delete:sender];
2887 }
2888
2889 - (void)deleteToBeginningOfLine:(id)sender
2890 {
2891     [self moveToBeginningOfLine:sender];
2892     [self delete:sender];
2893 }
2894
2895 - (void)deleteToEndOfLine:(id)sender
2896 {
2897     [self moveToEndOfLine:sender];
2898     [self delete:sender];
2899 }
2900
2901 - (void)deleteToBeginningOfParagraph:(id)sender
2902 {
2903     [self moveToBeginningOfParagraph:sender];
2904     [self delete:sender];
2905 }
2906
2907 - (void)deleteToEndOfParagraph:(id)sender
2908 {
2909     [self moveToEndOfParagraph:sender];
2910     [self delete:sender];
2911 }
2912
2913 - (void)complete:(id)sender
2914 {
2915     ERROR("unimplemented");
2916 }
2917
2918 - (void)checkSpelling:(id)sender
2919 {
2920     // WebCore does everything but update the spelling panel
2921     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2922     if (!checker) {
2923         return;
2924     }
2925     NSString *badWord = [[self _bridge] advanceToNextMisspelling];
2926     if (badWord) {
2927         [checker updateSpellingPanelWithMisspelledWord:badWord];
2928     }
2929 }
2930 #if APPKIT_CODE_FOR_REFERENCE
2931     NSTextStorage *text = _getTextStorage(self);
2932     NSTextViewSharedData *sharedData = _getSharedData(self);
2933     if (text && ([text length] > 0) && [self isSelectable]) {
2934         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2935         NSRange selCharRange = [self selectedRange];
2936         NSRange misspellCharRange = {0, 0}, grammarCharRange = {0, 0};
2937         unsigned i, count;
2938         NSArray *grammarRanges = nil, *grammarDescriptions = nil;
2939
2940         if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
2941
2942         misspellCharRange = [checker checkSpellingOfString:[text string] startingAt:NSMaxRange(selCharRange) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] wordCount:NULL];
2943 #if GRAMMAR_CHECKING
2944         grammarCharRange = [checker checkGrammarOfString:[text string] startingAt:NSMaxRange(selCharRange) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] ranges:&grammarRanges descriptions:&grammarDescriptions reconnectOnError:YES];
2945 #endif
2946
2947         if (misspellCharRange.length > 0 && (grammarCharRange.length == 0 || misspellCharRange.location <= grammarCharRange.location)) {
2948             // select the text and drive the panel
2949             [self setSelectedRange:misspellCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2950             if ([self isEditable]) {
2951                 [self _addSpellingAttributeForRange:misspellCharRange];
2952                 sharedData->_excludedSpellingCharRange = misspellCharRange;
2953             }
2954             [self scrollRangeToVisible:misspellCharRange];
2955             [checker updateSpellingPanelWithMisspelledWord:[[text string] substringWithRange:misspellCharRange]];
2956         } else if (grammarCharRange.length > 0) {
2957             [self setSelectedRange:grammarCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2958             count = [grammarRanges count];
2959             if ([self isEditable]) {
2960                 for (i = 0; i < count; i++) {
2961                     NSRange range = [grammarRanges rangeAtIndex:i];
2962                     range.location += grammarCharRange.location;
2963                     [self _addSpellingAttributeForRange:range];
2964                     [_getLayoutManager(self) addTemporaryAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[grammarDescriptions objectAtIndex:i], NSToolTipAttributeName, nil] forCharacterRange:range];
2965                 }
2966             }
2967             [self scrollRangeToVisible:grammarCharRange];
2968         } else {
2969             // Cause the beep to indicate there are no more misspellings.
2970             [checker updateSpellingPanelWithMisspelledWord:@""];
2971         }
2972     }
2973 #endif
2974
2975
2976 - (void)showGuessPanel:(id)sender
2977 {
2978     // WebCore does everything but update the spelling panel
2979     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2980     if (!checker) {
2981         return;
2982     }
2983
2984     NSString *badWord = [[self _bridge] advanceToNextMisspelling];
2985     if (badWord) {
2986         [checker updateSpellingPanelWithMisspelledWord:badWord];
2987     }
2988     [[checker spellingPanel] orderFront:sender];
2989 }
2990 #if APPKIT_CODE_FOR_REFERENCE
2991     NSTextStorage *text = _getTextStorage(self);
2992     NSTextViewSharedData *sharedData = _getSharedData(self);
2993     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2994     if (text && ([text length] > 0) && [self isSelectable]) {
2995         NSRange selCharRange = [self selectedRange];
2996         NSRange misspellCharRange = {0, 0};
2997         if (checker && ![checker windowIsSpellingPanel:[self window]]) {
2998             misspellCharRange = [checker checkSpellingOfString:[text string] startingAt:((selCharRange.location > 0) ? (selCharRange.location - 1) : 0) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] wordCount:NULL];
2999             if (misspellCharRange.length) {
3000                 // select the text and drive the panel
3001                 [self setSelectedRange:misspellCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
3002                 if ([self isEditable]) {
3003                     [self _addSpellingAttributeForRange:misspellCharRange];
3004                     sharedData->_excludedSpellingCharRange = misspellCharRange;
3005                 }
3006                 [self scrollRangeToVisible:misspellCharRange];
3007                 [checker updateSpellingPanelWithMisspelledWord:[[text string] substringWithRange:misspellCharRange]];
3008             }
3009         }
3010     }
3011     if (checker) {
3012         [[checker spellingPanel] orderFront:sender];
3013     }
3014 #endif
3015
3016 - (void)_changeSpellingToWord:(NSString *)newWord
3017 {
3018     WebBridge *bridge = [self _bridge];
3019     if (![bridge isSelectionEditable]) {
3020         return;
3021     }
3022     
3023     // Don't correct to empty string.  (AppKit checked this, we might as well too.)
3024     if (![NSSpellChecker sharedSpellChecker] || [newWord isEqualToString:@""]) {
3025         return;
3026     }
3027
3028     WebView *webView = [self _webView];
3029     if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:newWord replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
3030         [bridge replaceSelectionWithText:newWord selectReplacement:YES];
3031     }
3032 }
3033 #if APPKIT_CODE_FOR_REFERENCE
3034     NSRange charRange = [self rangeForUserTextChange];
3035     if ([self isEditable] && charRange.location != NSNotFound) {
3036         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3037         if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
3038         
3039         // Don't correct to empty string.
3040         if ([newWord isEqualToString:@""]) return;
3041         
3042         if ([self shouldChangeTextInRange:charRange replacementString:newWord]) {
3043             [self replaceCharactersInRange:charRange withString:newWord];
3044             charRange.length = [newWord length];
3045             [self setSelectedRange:charRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
3046             [self didChangeText];
3047         }
3048     }
3049 #endif
3050
3051 - (void)changeSpelling:(id)sender {
3052     [self _changeSpellingToWord:[[sender selectedCell] stringValue]];
3053 }
3054
3055 - (void)ignoreSpelling:(id)sender {
3056     WebBridge *bridge = [self _bridge];
3057     if (![bridge isSelectionEditable]) {
3058         return;
3059     }
3060     
3061     NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3062     if (!checker) {
3063         return;
3064     }
3065     
3066     NSString *stringToIgnore = [sender stringValue];
3067     unsigned int length = [stringToIgnore length];
3068     if (stringToIgnore && length > 0) {
3069         [checker ignoreWord:stringToIgnore inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
3070         //??? need to clear any special markup for misspelled words
3071     }
3072 }
3073 #if APPKIT_CODE_FOR_REFERENCE
3074     NSRange charRange = [self rangeForUserTextChange];
3075     if ([self isEditable]) {
3076         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3077         NSString *stringToIgnore;
3078         unsigned int length;
3079         
3080         if (!checker) return;
3081         
3082         stringToIgnore = [sender stringValue];
3083         length = [stringToIgnore length];
3084         if (stringToIgnore && length > 0) {
3085             [checker ignoreWord:stringToIgnore inSpellDocumentWithTag:[self spellCheckerDocumentTag]];
3086             if (length == charRange.length && [stringToIgnore isEqualToString:[[_getTextStorage(self) string] substringWithRange:charRange]]) {
3087                 [self _removeSpellingAttributeForRange:charRange];
3088             }
3089         }
3090     }
3091 #endif
3092
3093
3094 #if APPKIT_CODE_FOR_REFERENCE
3095
3096 - (void)_changeSpellingFromMenu:(id)sender {
3097     [self _changeSpellingToWord:[sender title]];
3098 }
3099
3100 - (void)_ignoreSpellingFromMenu:(id)sender {
3101     NSRange charRange = [self rangeForUserTextChange];
3102     if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
3103         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3104         if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
3105         [self _removeSpellingAttributeForRange:charRange];
3106         [checker ignoreWord:[[_getTextStorage(self) string] substringWithRange:charRange] inSpellDocumentWithTag:[self spellCheckerDocumentTag]];
3107     }
3108 }
3109
3110 - (void)_learnSpellingFromMenu:(id)sender {
3111     NSRange charRange = [self rangeForUserTextChange];
3112     if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
3113         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3114         if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
3115         [self _removeSpellingAttributeForRange:charRange];
3116         [checker learnWord:[[_getTextStorage(self) string] substringWithRange:charRange]];
3117     }
3118 }
3119
3120 - (void)_forgetSpellingFromMenu:(id)sender {
3121     NSRange charRange = [self rangeForUserTextChange];
3122     if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
3123         NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3124         if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
3125         [checker forgetWord:[[_getTextStorage(self) string] substringWithRange:charRange]];
3126     }
3127 }
3128
3129 - (void)_openLinkFromMenu:(id)sender {
3130     NSTextStorage *text = _getTextStorage(self);
3131     NSRange charRange = [self selectedRange];
3132     if (charRange.location != NSNotFound && charRange.length > 0) {
3133         id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
3134         if (link) {
3135             [self clickedOnLink:link atIndex:charRange.location];
3136         } else {
3137             NSString *string = [[text string] substringWithRange:charRange];
3138             link = [NSURL URLWithString:string];
3139             if (link) [[NSWorkspace sharedWorkspace] openURL:link];
3140         }
3141     }
3142 }
3143
3144 #endif
3145
3146 - (void)performFindPanelAction:(id)sender
3147 {
3148     ERROR("unimplemented");
3149 }
3150
3151 - (void)startSpeaking:(id)sender
3152 {
3153     WebBridge *bridge = [self _bridge];
3154     DOMRange *range = [bridge selectedDOMRange];
3155     if (!range || [range collapsed]) {
3156         range = [self _entireDOMRange];
3157     }
3158     [NSApp speakString:[bridge stringForRange:range]];
3159 }
3160
3161 - (void)stopSpeaking:(id)sender
3162 {
3163     [NSApp stopSpeaking:sender];
3164 }
3165
3166 @end
3167
3168 @implementation WebHTMLView (WebTextSizing)
3169
3170 - (void)_web_textSizeMultiplierChanged
3171 {
3172     [self _updateTextSizeMultiplier];
3173 }
3174
3175 @end
3176
3177 @implementation NSArray (WebHTMLView)
3178
3179 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object
3180 {
3181     NSEnumerator *enumerator = [self objectEnumerator];
3182     WebNetscapePluginEmbeddedView *view;
3183     while ((view = [enumerator nextObject]) != nil) {
3184         if ([view isKindOfClass:[WebNetscapePluginEmbeddedView class]]) {
3185             [view performSelector:selector withObject:object];
3186         }
3187     }
3188 }
3189
3190 @end
3191
3192 @implementation WebElementOrTextFilter
3193
3194 + (WebElementOrTextFilter *)filter 
3195 {
3196     if (!elementOrTextFilterInstance)
3197         elementOrTextFilterInstance = [[WebElementOrTextFilter alloc] init];
3198     return elementOrTextFilterInstance;
3199 }
3200
3201 - (short)acceptNode:(DOMNode *)n
3202 {
3203     return ([n isKindOfClass:[DOMElement class]] || [n isKindOfClass:[DOMText class]]) ? DOM_FILTER_ACCEPT : DOM_FILTER_SKIP;
3204 }
3205
3206 @end
3207
3208 @implementation WebHTMLView (WebInternal)
3209
3210 - (void)_selectionChanged
3211 {
3212     // TEXTINPUT: if there is marked text, we need to tell the input
3213     // manager that the selection changed
3214
3215     [self _updateFontPanel];
3216 }
3217
3218 - (void)_updateFontPanel
3219 {
3220     // FIXME: NSTextView bails out if becoming or resigning first responder, for which it has ivar flags. Not
3221     // sure if we need to do something similar.
3222     
3223     WebBridge *bridge = [self _bridge];
3224
3225     if (![bridge isSelectionEditable]) {
3226         return;
3227     }
3228     
3229     NSWindow *window = [self window];
3230     // FIXME: is this first-responder check correct? What happens if a subframe is editable and is first responder?
3231     if ([NSApp keyWindow] != window || [window firstResponder] != self) {
3232         return;
3233     }
3234     
3235     BOOL onlyOneFontInSelection = YES;
3236     NSFont *font = nil;
3237     
3238     if (![bridge haveSelection]) {
3239         font = [bridge fontForCurrentPosition];
3240     } 
3241     else {
3242         DOMRange *selection = [bridge selectedDOMRange];
3243         DOMNode *startContainer = [selection startContainer];
3244         DOMNode *endContainer = [selection endContainer];
3245         
3246         ASSERT(startContainer);
3247         ASSERT(endContainer);
3248         ASSERT([[WebElementOrTextFilter filter] acceptNode:startContainer] == DOM_FILTER_ACCEPT);
3249         ASSERT([[WebElementOrTextFilter filter] acceptNode:endContainer] == DOM_FILTER_ACCEPT);
3250         
3251         font = [bridge renderedFontForNode:startContainer];
3252         
3253         if (startContainer != endContainer) {
3254             DOMDocument *document = [bridge DOMDocument];
3255             DOMTreeWalker *treeWalker = [document createTreeWalker:document :DOM_SHOW_ALL :[WebElementOrTextFilter filter] :NO];
3256             DOMNode *node = startContainer;
3257             [treeWalker setCurrentNode:node];
3258             while (node) {
3259                 NSFont *otherFont = [bridge renderedFontForNode:node];
3260                 if (![font isEqual:otherFont]) {
3261                     onlyOneFontInSelection = NO;
3262                     break;
3263                 }
3264                 if (node == endContainer)
3265                     break;
3266                 node = [treeWalker nextNode];
3267             }
3268         }
3269     }
3270     
3271     // FIXME: for now, return a bogus font that distinguishes the empty selection from the non-empty
3272     // selection. We should be able to remove this once the rest of this code works properly.
3273     if (font == nil) {
3274         if (![bridge haveSelection]) {
3275             font = [NSFont toolTipsFontOfSize:17];
3276         } else {
3277             font = [NSFont menuFontOfSize:23];
3278         }
3279     }
3280     ASSERT(font != nil);
3281         
3282     NSFontManager *fm = [NSFontManager sharedFontManager];
3283     [fm setSelectedFont:font isMultiple:!onlyOneFontInSelection];
3284     // FIXME: we don't keep track of selected attributes, or set them on the font panel. This
3285     // appears to have no effect on the UI. E.g., underlined text in Mail or TextEdit is
3286     // not reflected in the font panel. Maybe someday this will change.
3287 }
3288
3289 - (unsigned int)_delegateDragSourceActionMask
3290 {
3291     WebView *webView = [self _webView];
3292     NSPoint point = [webView convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
3293     _private->dragSourceActionMask = [[webView _UIDelegateForwarder] webView:webView dragSourceActionMaskForPoint:point];
3294     return _private->dragSourceActionMask;
3295 }
3296
3297 @end
3298
3299
3300 @implementation WebHTMLView (WebNSTextInputSupport)
3301
3302 - (NSArray *)validAttributesForMarkedText
3303 {
3304     ERROR("TEXTINPUT: validAttributesForMarkedText not yet implemented");
3305     return [NSArray array];
3306 }
3307
3308 - (unsigned int)characterIndexForPoint:(NSPoint)thePoint
3309 {
3310     ERROR("TEXTINPUT: characterIndexForPoint: not yet implemented");
3311     return 0;
3312 }
3313
3314 - (NSRect)firstRectForCharacterRange:(NSRange)theRange
3315 {
3316     ERROR("TEXTINPUT: firstRectForCharacterRange: not yet implemented");
3317     return NSMakeRect(0,0,0,0);
3318 }
3319
3320 - (NSRange)selectedRange
3321 {
3322     ERROR("TEXTINPUT: selectedRange not yet implemented");
3323     return NSMakeRange(0,0);
3324 }
3325
3326 - (NSRange)markedRange
3327 {
3328     ERROR("TEXTINPUT: markedRange not yet implemented");
3329     return NSMakeRange(0,0);
3330 }
3331
3332 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)theRange
3333 {
3334     ERROR("TEXTINPUT: attributedSubstringFromRange: not yet implemented");
3335     return nil;
3336 }
3337
3338 - (long)conversationIdentifier
3339 {
3340     ERROR("TEXTINPUT: conversationIdentifier not yet implemented");
3341     return 0;
3342 }
3343
3344 - (BOOL)hasMarkedText
3345 {
3346     ERROR("TEXTINPUT: hasMarkedText not yet implemented");
3347     return FALSE;
3348 }
3349
3350 - (void)unmarkText
3351 {
3352     ERROR("TEXTINPUT: unmarkText not yet implemented");
3353 }
3354
3355 - (void)setMarkedText:(id)aString selectedRange:(NSRange)selRange
3356 {
3357     ERROR("TEXTINPUT: setMarkedText:selectedRange: not yet implemented");
3358 }
3359
3360 - (void)doCommandBySelector:(SEL)aSelector
3361 {
3362     [super doCommandBySelector:aSelector];
3363 }
3364         
3365 - (void)insertText:(id)string
3366 {
3367     WebBridge *bridge = [self _bridge];
3368
3369     NSString *text;
3370
3371     if ([string isKindOfClass:[NSAttributedString class]]) {
3372         ERROR("TEXTINPUT: requested insert of attributed string");
3373         text = [string string];
3374     } else {
3375         text = string;
3376     }
3377
3378     // avoid entering empty strings because it confuses WebCore
3379     if ([text length] == 0) {
3380         return;
3381     }
3382
3383     if ([bridge isSelectionEditable]) {
3384         WebView *webView = [self _webView];
3385         if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
3386             [bridge insertText:text];
3387         }
3388     }
3389 }
3390
3391 @end