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