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