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