- fixed the following bugs:
[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/WebBridge.h>
10 #import <WebKit/WebClipView.h>
11 #import <WebKit/WebDataSourcePrivate.h>
12 #import <WebKit/WebDocumentInternal.h>
13 #import <WebKit/WebException.h>
14 #import <WebKit/WebFrame.h>
15 #import <WebKit/WebFramePrivate.h>
16 #import <WebKit/WebFrameViewPrivate.h>
17 #import <WebKit/WebHTMLViewPrivate.h>
18 #import <WebKit/WebHTMLRepresentationPrivate.h>
19 #import <WebKit/WebNetscapePluginEmbeddedView.h>
20 #import <WebKit/WebKitLogging.h>
21 #import <WebKit/WebNSPasteboardExtras.h>
22 #import "WebNSPrintOperationExtras.h"
23 #import <WebKit/WebNSViewExtras.h>
24 #import <WebKit/WebPluginController.h>
25 #import <WebKit/WebResourcePrivate.h>
26 #import <WebKit/WebTextRenderer.h>
27 #import <WebKit/WebTextRendererFactory.h>
28 #import <WebKit/WebUIDelegatePrivate.h>
29 #import <WebKit/WebUnicode.h>
30 #import <WebKit/WebViewPrivate.h>
31
32 #import <AppKit/NSGraphicsContextPrivate.h>
33 #import <AppKit/NSResponder_Private.h>
34 #import <CoreGraphics/CGContextGState.h>
35
36 #import <AppKit/NSAccessibility.h>
37
38 #import <WebKit/WebImageRenderer.h>
39 #import <WebKit/WebKitNSStringExtras.h>
40 #import <WebKit/WebNSEventExtras.h>
41 #import <WebKit/WebNSImageExtras.h>
42 #import <WebKit/WebNSURLExtras.h>
43 #import <WebKit/WebPreferences.h>
44 #import <WebKit/WebStringTruncator.h>
45
46 #import <Foundation/NSFileManager_NSURLExtras.h>
47 #import <Foundation/NSURL_NSURLExtras.h>
48
49 // The link drag hysteresis is much larger than the others because there
50 // needs to be enough space to cancel the link press without starting a link drag,
51 // and because dragging links is rare.
52 #define LinkDragHysteresis              40.0
53 #define ImageDragHysteresis             5.0
54 #define TextDragHysteresis              3.0
55 #define TextDragDelay                   0.15
56
57 // By imaging to a width a little wider than the available pixels,
58 // thin pages will be scaled down a little, matching the way they
59 // print in IE and Camino. This lets them use fewer sheets than they
60 // would otherwise, which is presumably why other browsers do this.
61 // Wide pages will be scaled down more than this.
62 #define PrintingMinimumShrinkFactor     1.25
63
64 // This number determines how small we are willing to reduce the page content
65 // in order to accommodate the widest line. If the page would have to be
66 // reduced smaller to make the widest line fit, we just clip instead (this
67 // behavior matches MacIE and Mozilla, at least)
68 #define PrintingMaximumShrinkFactor     2.0
69
70 #define AUTOSCROLL_INTERVAL             0.1
71
72 #define DRAG_LABEL_BORDER_X             4.0
73 #define DRAG_LABEL_BORDER_Y             2.0
74 #define DRAG_LABEL_RADIUS               5.0
75 #define DRAG_LABEL_BORDER_Y_OFFSET              2.0
76
77 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP        120.0
78 #define MAX_DRAG_LABEL_WIDTH                    320.0
79
80 #define DRAG_LINK_LABEL_FONT_SIZE   11.0
81 #define DRAG_LINK_URL_FONT_SIZE   10.0
82
83 static BOOL forceRealHitTest = NO;
84
85 @interface WebHTMLView (WebHTMLViewPrivate)
86 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
87 - (void)_updateTextSizeMultiplier;
88 - (float)_calculatePrintHeight;
89 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation;
90 @end
91
92 // Any non-zero value will do, but using somethign recognizable might help us debug some day.
93 #define TRACKING_RECT_TAG 0xBADFACE
94
95
96 @interface NSView (AppKitSecretsIKnowAbout)
97 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
98 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
99 - (NSRect)_dirtyRect;
100 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
101 @end
102
103 @interface NSView (WebHTMLViewPrivate)
104 - (void)_web_setPrintingModeRecursive;
105 - (void)_web_clearPrintingModeRecursive;
106 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
107 @end
108
109 @interface NSMutableDictionary (WebHTMLViewPrivate)
110 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
111 @end
112
113 @implementation WebHTMLViewPrivate
114
115 - (void)dealloc
116 {
117     ASSERT(autoscrollTimer == nil);
118     ASSERT(autoscrollTriggerEvent == nil);
119     
120     [pluginController destroyAllPlugins];
121     
122     [mouseDownEvent release];
123     [draggingImageURL release];
124     [pluginController release];
125     [toolTip release];
126     
127     [super dealloc];
128 }
129
130 @end
131
132
133 @implementation WebHTMLView (WebPrivate)
134
135 - (void)_reset
136 {
137     [WebImageRenderer stopAnimationsInView:self];
138 }
139
140 - (WebView *)_webView
141 {
142     // We used to use the view hierarchy exclusively here, but that won't work
143     // right when the first viewDidMoveToSuperview call is done, and this wil.
144     return [[self _frame] webView];
145 }
146
147 - (WebFrame *)_frame
148 {
149     WebFrameView *webFrameView = [self _web_parentWebFrameView];
150     return [webFrameView webFrame];
151 }
152
153 // Required so view can access the part's selection.
154 - (WebBridge *)_bridge
155 {
156     return [[self _frame] _bridge];
157 }
158
159 - (WebDataSource *)_dataSource
160 {
161     return [[self _frame] dataSource];
162 }
163
164 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
165 {
166     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
167         location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
168         modifierFlags:[flagsChangedEvent modifierFlags]
169         timestamp:[flagsChangedEvent timestamp]
170         windowNumber:[flagsChangedEvent windowNumber]
171         context:[flagsChangedEvent context]
172         eventNumber:0 clickCount:0 pressure:0];
173
174     // Pretend it's a mouse move.
175     [[NSNotificationCenter defaultCenter]
176         postNotificationName:NSMouseMovedNotification object:self
177         userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
178 }
179
180 - (void)_updateMouseoverWithFakeEvent
181 {
182     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
183         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
184         modifierFlags:[[NSApp currentEvent] modifierFlags]
185         timestamp:[NSDate timeIntervalSinceReferenceDate]
186         windowNumber:[[self window] windowNumber]
187         context:[[NSApp currentEvent] context]
188         eventNumber:0 clickCount:0 pressure:0];
189     
190     [self _updateMouseoverWithEvent:fakeEvent];
191 }
192
193 - (void)_frameOrBoundsChanged
194 {
195     if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
196         [self setNeedsLayout:YES];
197         [self setNeedsDisplay:YES];
198     }
199
200     NSPoint origin = [[self superview] bounds].origin;
201     if (!NSEqualPoints(_private->lastScrollPosition, origin))
202         [[self _bridge] sendScrollEvent];
203     _private->lastScrollPosition = origin;
204
205     SEL selector = @selector(_updateMouseoverWithFakeEvent);
206     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
207     [self performSelector:selector withObject:nil afterDelay:0];
208 }
209
210 - (NSDictionary *)_elementAtPoint:(NSPoint)point
211 {
212     NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
213     NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
214
215     // Convert URL strings to NSURLs
216     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
217     [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
218     
219     WebFrameView *webFrameView = [self _web_parentWebFrameView];
220     ASSERT(webFrameView);
221     WebFrame *webFrame = [webFrameView webFrame];
222     
223     if (webFrame) {
224         NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
225         if ([frameName length] == 0) {
226             [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
227         } else {
228             WebFrame *wf = [webFrame findFrameNamed:frameName];
229             if (wf != nil)
230                 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
231             else
232                 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
233         }
234     
235         [elementInfo setObject:webFrame forKey:WebElementFrameKey];
236     }
237     
238     return [elementInfo autorelease];
239 }
240
241 - (void)_setAsideSubviews
242 {
243     ASSERT(!_private->subviewsSetAside);
244     ASSERT(_private->savedSubviews == nil);
245     _private->savedSubviews = _subviews;
246     _subviews = nil;
247     _private->subviewsSetAside = YES;
248  }
249  
250  - (void)_restoreSubviews
251  {
252     ASSERT(_private->subviewsSetAside);
253     ASSERT(_subviews == nil);
254     _subviews = _private->savedSubviews;
255     _private->savedSubviews = nil;
256     _private->subviewsSetAside = NO;
257 }
258
259 // Don't let AppKit even draw subviews. We take care of that.
260 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
261 {
262     // This helps when we print as part of a larger print process.
263     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
264     BOOL wasInPrintingMode = _private->printing;
265     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
266     if (wasInPrintingMode != isPrinting) {
267         if (isPrinting) {
268             [self _web_setPrintingModeRecursive];
269         } else {
270             [self _web_clearPrintingModeRecursive];
271         }
272     }
273
274     [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
275
276     [self _setAsideSubviews];
277     [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
278         rectIsVisibleRectForView:visibleView topView:topView];
279     [self _restoreSubviews];
280
281     if (wasInPrintingMode != isPrinting) {
282         if (wasInPrintingMode) {
283             [self _web_setPrintingModeRecursive];
284         } else {
285             [self _web_clearPrintingModeRecursive];
286         }
287     }
288 }
289
290 // Don't let AppKit even draw subviews. We take care of that.
291 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
292 {
293     BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
294
295     BOOL wasInPrintingMode = _private->printing;
296     BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
297
298     if (needToSetAsideSubviews) {
299         // This helps when we print as part of a larger print process.
300         // If the WebHTMLView itself is what we're printing, then we will never have to do this.
301         if (wasInPrintingMode != isPrinting) {
302             if (isPrinting) {
303                 [self _web_setPrintingModeRecursive];
304             } else {
305                 [self _web_clearPrintingModeRecursive];
306             }
307         }
308
309         [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
310
311         [self _setAsideSubviews];
312     }
313     
314     [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
315     
316     if (needToSetAsideSubviews) {
317         if (wasInPrintingMode != isPrinting) {
318             if (wasInPrintingMode) {
319                 [self _web_setPrintingModeRecursive];
320             } else {
321                 [self _web_clearPrintingModeRecursive];
322             }
323         }
324
325         [self _restoreSubviews];
326     }
327 }
328
329 - (BOOL)_insideAnotherHTMLView
330 {
331     NSView *view = self;
332     while ((view = [view superview])) {
333         if ([view isKindOfClass:[WebHTMLView class]]) {
334             return YES;
335         }
336     }
337     return NO;
338 }
339
340 - (void)scrollPoint:(NSPoint)point
341 {
342     // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
343     // If we get called during the handling of a key down event, we assume the call came from
344     // NSTextView, and ignore it and use our own code to decide how to page up and page down
345     // We are smarter about how far to scroll, and we have "superview scrolling" logic.
346     NSEvent *event = [[self window] currentEvent];
347     if ([event type] == NSKeyDown) {
348         const unichar pageUp = NSPageUpFunctionKey;
349         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
350             [self tryToPerform:@selector(scrollPageUp:) with:nil];
351             return;
352         }
353         const unichar pageDown = NSPageDownFunctionKey;
354         if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
355             [self tryToPerform:@selector(scrollPageDown:) with:nil];
356             return;
357         }
358     }
359     
360     [super scrollPoint:point];
361 }
362
363 - (NSView *)hitTest:(NSPoint)point
364 {
365     // WebHTMLView objects handle all left mouse clicks for objects inside them.
366     // That does not include left mouse clicks with the control key held down.
367     BOOL captureHitsOnSubviews;
368     if (forceRealHitTest) {
369         captureHitsOnSubviews = NO;
370     } else {
371         NSEvent *event = [[self window] currentEvent];
372         captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
373     }
374     if (!captureHitsOnSubviews) {
375         return [super hitTest:point];
376     }
377     if ([[self superview] mouse:point inRect:[self frame]]) {
378         return self;
379     }
380     return nil;
381 }
382
383 static WebHTMLView *lastHitView = nil;
384
385 - (void)_clearLastHitViewIfSelf
386 {
387     if (lastHitView == self) {
388         lastHitView = nil;
389     }
390 }
391
392 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
393 {
394     ASSERT(_private->trackingRectOwner == nil);
395     _private->trackingRectOwner = owner;
396     _private->trackingRectUserData = data;
397     return TRACKING_RECT_TAG;
398 }
399
400 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
401 {
402     ASSERT(tag == TRACKING_RECT_TAG);
403     return [self addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
404 }
405
406 - (void)removeTrackingRect:(NSTrackingRectTag)tag
407 {
408     ASSERT(tag == TRACKING_RECT_TAG);
409     if (_private != nil) {
410         ASSERT(_private->trackingRectOwner != nil);
411         _private->trackingRectOwner = nil;
412     }
413 }
414
415 - (void)_sendToolTipMouseExited
416 {
417     // Nothing matters except window, trackingNumber, and userData.
418     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
419         location:NSMakePoint(0, 0)
420         modifierFlags:0
421         timestamp:0
422         windowNumber:[[self window] windowNumber]
423         context:NULL
424         eventNumber:0
425         trackingNumber:TRACKING_RECT_TAG
426         userData:_private->trackingRectUserData];
427     [_private->trackingRectOwner mouseExited:fakeEvent];
428 }
429
430 - (void)_sendToolTipMouseEntered
431 {
432     // Nothing matters except window, trackingNumber, and userData.
433     NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
434         location:NSMakePoint(0, 0)
435         modifierFlags:0
436         timestamp:0
437         windowNumber:[[self window] windowNumber]
438         context:NULL
439         eventNumber:0
440         trackingNumber:TRACKING_RECT_TAG
441         userData:_private->trackingRectUserData];
442     [_private->trackingRectOwner mouseEntered:fakeEvent];
443 }
444
445 - (void)_setToolTip:(NSString *)string
446 {
447     NSString *toolTip = [string length] == 0 ? nil : string;
448     NSString *oldToolTip = _private->toolTip;
449     if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
450         return;
451     }
452     if (oldToolTip) {
453         [self _sendToolTipMouseExited];
454         [oldToolTip release];
455     }
456     _private->toolTip = [toolTip copy];
457     if (toolTip) {
458         [self removeAllToolTips];
459         NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
460         [self addToolTipRect:wideOpenRect owner:self userData:NULL];
461         [self _sendToolTipMouseEntered];
462     }
463 }
464
465 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
466 {
467     return [[_private->toolTip copy] autorelease];
468 }
469
470 - (void)_updateMouseoverWithEvent:(NSEvent *)event
471 {
472     WebHTMLView *view = nil;
473     if ([event window] == [self window]) {
474         forceRealHitTest = YES;
475         NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
476         forceRealHitTest = NO;
477         while (hitView) {
478             if ([hitView isKindOfClass:[WebHTMLView class]]) {
479                 view = (WebHTMLView *)hitView;
480                 break;
481             }
482             hitView = [hitView superview];
483         }
484     }
485
486     if (lastHitView != view && lastHitView != nil) {
487         // If we are moving out of a view (or frame), let's pretend the mouse moved
488         // all the way out of that view. But we have to account for scrolling, because
489         // khtml doesn't understand our clipping.
490         NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
491         float yScroll = visibleRect.origin.y;
492         float xScroll = visibleRect.origin.x;
493
494         event = [NSEvent mouseEventWithType:NSMouseMoved
495                          location:NSMakePoint(-1 - xScroll, -1 - yScroll )
496                          modifierFlags:[[NSApp currentEvent] modifierFlags]
497                          timestamp:[NSDate timeIntervalSinceReferenceDate]
498                          windowNumber:[[self window] windowNumber]
499                          context:[[NSApp currentEvent] context]
500                          eventNumber:0 clickCount:0 pressure:0];
501         [[lastHitView _bridge] mouseMoved:event];
502     }
503
504     lastHitView = view;
505     
506     NSDictionary *element;
507     if (view == nil) {
508         element = nil;
509     } else {
510         [[view _bridge] mouseMoved:event];
511
512         NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
513         element = [view _elementAtPoint:point];
514     }
515
516     // Have the web view send a message to the delegate so it can do status bar display.
517     [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
518
519     // Set a tool tip; it won't show up right away but will if the user pauses.
520     [self _setToolTip:[element objectForKey:WebCoreElementTitleKey]];
521 }
522
523 + (NSArray *)_selectionPasteboardTypes
524 {
525     return [NSArray arrayWithObjects:WebArchivePboardType, NSHTMLPboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
526 }
527
528 - (WebArchive *)_selectedWebArchive:(NSString **)markupString
529 {
530     NSArray *subresourceURLStrings;
531     WebHTMLRepresentation *rep = [[self _dataSource] representation];
532     *markupString = [[self _bridge] markupStringFromRange:[[self _bridge] selectedDOMRange] subresourceURLStrings:&subresourceURLStrings];
533     return [rep _webArchiveWithMarkupString:*markupString subresourceURLStrings:subresourceURLStrings];
534 }
535
536 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
537 {
538     [pasteboard declareTypes:[[self class] _selectionPasteboardTypes] owner:nil];
539
540     // Put HTML on the pasteboard.
541     NSString *markupString;
542     WebArchive *webArchive = [self _selectedWebArchive:&markupString];
543     [pasteboard setString:markupString forType:NSHTMLPboardType];
544     [pasteboard setData:[webArchive dataRepresentation] forType:WebArchivePboardType];
545     
546     // Put attributed string on the pasteboard (RTF format).
547     NSAttributedString *attributedString = [self selectedAttributedString];
548     NSRange range = NSMakeRange(0, [attributedString length]);
549     NSData *attributedData = [attributedString RTFFromRange:range documentAttributes:nil];
550     [pasteboard setData:attributedData forType:NSRTFPboardType];
551
552     attributedData = [attributedString RTFDFromRange:range documentAttributes:nil];
553     [pasteboard setData:attributedData forType:NSRTFDPboardType];
554     
555     // Put plain string on the pasteboard.
556     // Map &nbsp; to a plain old space because this is better for source code, other browsers do it,
557     // and because HTML forces you to do this any time you want two spaces in a row.
558     NSMutableString *s = [[self selectedString] mutableCopy];
559     const unichar NonBreakingSpaceCharacter = 0xA0;
560     NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
561     [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
562     [pasteboard setString:s forType:NSStringPboardType];
563     [s release];
564 }
565
566 - (BOOL)_haveSelection
567 {
568     return [[self _bridge] haveSelection];
569 }
570
571 - (BOOL)_canDelete
572 {
573     return [self _haveSelection] && [[self _bridge] isSelectionEditable];
574 }
575
576 - (BOOL)_canPaste
577 {
578     return [[self _bridge] isSelectionEditable];
579 }
580
581 - (void)_pasteMarkupFromPasteboard:(NSPasteboard *)pasteboard
582 {
583     NSArray *types = [pasteboard types];
584     NSString *markupString = nil;
585         
586     if ([types containsObject:WebArchivePboardType]) {
587         WebArchive *webArchive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
588         WebResource *mainResource = [webArchive mainResource];
589         if (mainResource) {
590             markupString = [[[NSString alloc] initWithData:[mainResource data] encoding:NSUTF8StringEncoding] autorelease];
591             [[self _dataSource] addSubresources:[webArchive subresources]];
592         }
593         [webArchive release];
594     }
595     
596     if (!markupString && [types containsObject:NSHTMLPboardType]) {
597         markupString = [pasteboard stringForType:NSHTMLPboardType];
598     }
599     if (!markupString && [types containsObject:NSStringPboardType]) {
600         markupString = [pasteboard stringForType:NSStringPboardType];
601     }
602     if (markupString) {
603         [[self _bridge] pasteMarkupString:markupString];
604     }
605 }
606
607 -(NSImage *)_dragImageForLinkElement:(NSDictionary *)element
608 {
609     NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
610
611     BOOL drawURLString = YES;
612     BOOL clipURLString = NO, clipLabelString = NO;
613     
614     NSString *label = [element objectForKey: WebElementLinkLabelKey];
615     NSString *urlString = [linkURL _web_userVisibleString];
616     
617     if (!label) {
618         drawURLString = NO;
619         label = urlString;
620     }
621     
622     NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
623                                                    toHaveTrait:NSBoldFontMask];
624     NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
625     NSSize labelSize;
626     labelSize.width = [label _web_widthWithFont: labelFont];
627     labelSize.height = [labelFont ascender] - [labelFont descender];
628     if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
629         labelSize.width = MAX_DRAG_LABEL_WIDTH;
630         clipLabelString = YES;
631     }
632     
633     NSSize imageSize, urlStringSize;
634     imageSize.width += labelSize.width + DRAG_LABEL_BORDER_X * 2;
635     imageSize.height += labelSize.height + DRAG_LABEL_BORDER_Y * 2;
636     if (drawURLString) {
637         urlStringSize.width = [urlString _web_widthWithFont: urlFont];
638         urlStringSize.height = [urlFont ascender] - [urlFont descender];
639         imageSize.height += urlStringSize.height;
640         if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
641             imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
642             clipURLString = YES;
643         } else {
644             imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
645         }
646     }
647     NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
648     [dragImage lockFocus];
649     
650     [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
651     
652     // Drag a rectangle with rounded corners/
653     NSBezierPath *path = [NSBezierPath bezierPath];
654     [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
655     [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
656     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
657     [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
658     
659     [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
660     [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
661     [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
662     [path fill];
663         
664     NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
665     NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
666     if (drawURLString) {
667         if (clipURLString)
668             urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
669
670         [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
671              withTopColor:topColor bottomColor:bottomColor font:urlFont];
672     }
673
674     if (clipLabelString)
675             label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
676     [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
677              withTopColor:topColor bottomColor:bottomColor font:labelFont];
678     
679     [dragImage unlockFocus];
680     
681     return dragImage;
682 }
683
684 - (void)_handleMouseDragged:(NSEvent *)event
685 {
686     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
687     NSDictionary *element = [self _elementAtPoint:mouseDownPoint];
688
689     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
690     NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
691     BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
692
693     [_private->draggingImageURL release];
694     _private->draggingImageURL = nil;
695
696     // We must have started over something draggable:
697     ASSERT((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
698            (!imageURL && linkURL) || isSelected); 
699
700     NSPoint mouseDraggedPoint = [self convertPoint:[event locationInWindow] fromView:nil];
701     float deltaX = ABS(mouseDraggedPoint.x - mouseDownPoint.x);
702     float deltaY = ABS(mouseDraggedPoint.y - mouseDownPoint.y);
703     
704     // Drag hysteresis hasn't been met yet but we don't want to do other drag actions like selection.
705     if ((imageURL && deltaX < ImageDragHysteresis && deltaY < ImageDragHysteresis) ||
706         (linkURL && deltaX < LinkDragHysteresis && deltaY < LinkDragHysteresis) ||
707         (isSelected && deltaX < TextDragHysteresis && deltaY < TextDragHysteresis)) {
708         return;
709     }
710     
711     if (imageURL) {
712         _private->draggingImageURL = [imageURL retain];
713         WebImageRenderer *image = [element objectForKey:WebElementImageKey];
714         ASSERT([image isKindOfClass:[WebImageRenderer class]]);
715         NSFileWrapper *fileWrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
716         ASSERT(fileWrapper);
717         [self _web_dragImage:image
718                  fileWrapper:fileWrapper
719                         rect:[[element objectForKey:WebElementImageRectKey] rectValue]
720                          URL:linkURL ? linkURL : imageURL
721                        title:[element objectForKey:WebElementImageAltStringKey]
722                   HTMLString:[[element objectForKey:WebCoreElementDOMNodeKey] HTMLString]
723                        event:_private->mouseDownEvent];
724         
725     } else if (linkURL) {
726         NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
727         NSString *label = [element objectForKey:WebElementLinkLabelKey];
728         [pasteboard _web_writeURL:linkURL andTitle:label withOwner:self];
729         NSImage *dragImage = [self _dragImageForLinkElement:element];
730         NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
731         [self dragImage:dragImage
732                      at:NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height)
733                  offset:offset
734                   event:event
735              pasteboard:pasteboard
736                  source:self
737               slideBack:NO];
738         
739     } else if (isSelected) {
740         NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
741         [self _writeSelectionToPasteboard:pasteboard];
742         NSImage *selectionImage = [[self _bridge] selectionImage];
743         [selectionImage _web_dissolveToFraction:WebDragImageAlpha];
744         NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
745         [self dragImage:selectionImage
746                      at:NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect))
747                  offset:NSMakeSize(mouseDraggedPoint.x - mouseDownPoint.x, mouseDraggedPoint.y - mouseDownPoint.y)
748                   event:_private->mouseDownEvent
749              pasteboard:pasteboard
750                  source:self
751               slideBack:YES];
752     } else {
753         ERROR("Attempt to drag unknown element");
754     }
755 }
756
757 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
758 {
759     [self autoscroll:event];
760     [self _startAutoscrollTimer:event];
761 }
762
763 - (BOOL)_mayStartDragWithMouseDragged:(NSEvent *)mouseDraggedEvent
764 {
765     NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
766     NSDictionary *mouseDownElement = [self _elementAtPoint:mouseDownPoint];
767
768     NSURL *imageURL = [mouseDownElement objectForKey: WebElementImageURLKey];
769
770     if ((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
771         (!imageURL && [mouseDownElement objectForKey: WebElementLinkURLKey]) ||
772         ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
773          ([mouseDraggedEvent timestamp] - [_private->mouseDownEvent timestamp]) > TextDragDelay)) {
774         return YES;
775     }
776
777     return NO;
778 }
779
780 - (WebPluginController *)_pluginController
781 {
782     return _private->pluginController;
783 }
784
785 - (void)_web_setPrintingModeRecursive
786 {
787     [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
788     [super _web_setPrintingModeRecursive];
789 }
790
791 - (void)_web_clearPrintingModeRecursive
792 {
793     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
794     [super _web_clearPrintingModeRecursive];
795 }
796
797 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
798 {
799     ASSERT(!_private->subviewsSetAside);
800     displayRect = NSIntersectionRect(displayRect, [self bounds]);
801
802     if (!testDirtyRect || [self needsDisplay]) {
803         if (testDirtyRect) {
804             NSRect dirtyRect = [self _dirtyRect];
805             displayRect = NSIntersectionRect(displayRect, dirtyRect);
806         }
807         if (!NSIsEmptyRect(displayRect)) {
808             if ([[self _bridge] needsLayout])
809                 _private->needsLayout = YES;
810             if (_private->needsToApplyStyles || _private->needsLayout)
811                 [self layout];
812         }
813     }
814
815     [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
816 }
817
818 - (NSRect)_selectionRect
819 {
820     return [[self _bridge] selectionRect];
821 }
822
823 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
824 {
825     if (_private->autoscrollTimer == nil) {
826         _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
827             target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
828         _private->autoscrollTriggerEvent = [triggerEvent retain];
829     }
830 }
831
832 - (void)_stopAutoscrollTimer
833 {
834     NSTimer *timer = _private->autoscrollTimer;
835     _private->autoscrollTimer = nil;
836     [_private->autoscrollTriggerEvent release];
837     _private->autoscrollTriggerEvent = nil;
838     [timer invalidate];
839     [timer release];
840 }
841
842
843 - (void)_autoscroll
844 {
845     int isStillDown;
846     
847     // Guarantee that the autoscroll timer is invalidated, even if we don't receive
848     // a mouse up event.
849     PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
850     if (!isStillDown){
851         [self _stopAutoscrollTimer];
852         return;
853     }
854
855     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
856         location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
857         modifierFlags:[[NSApp currentEvent] modifierFlags]
858         timestamp:[NSDate timeIntervalSinceReferenceDate]
859         windowNumber:[[self window] windowNumber]
860         context:[[NSApp currentEvent] context]
861         eventNumber:0 clickCount:0 pressure:0];
862     [self mouseDragged:fakeEvent];
863 }
864
865 @end
866
867 @implementation NSView (WebHTMLViewPrivate)
868
869 - (void)_web_setPrintingModeRecursive
870 {
871     [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
872 }
873
874 - (void)_web_clearPrintingModeRecursive
875 {
876     [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
877 }
878
879 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
880 {
881     unsigned index, count;
882     for (index = 0, count = [_subviews count]; index < count; index++) {
883         NSView *subview = [_subviews objectAtIndex:index];
884         NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
885         [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
886     }
887 }
888
889 @end
890
891 @implementation NSMutableDictionary (WebHTMLViewPrivate)
892
893 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
894 {
895     if (object == nil) {
896         [self removeObjectForKey:key];
897     } else {
898         [self setObject:object forKey:key];
899     }
900 }
901
902 @end
903
904 // The following is a workaround for
905 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
906 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
907 // Since the category will be searched before the real class, we'll prevent the flag from being
908 // set on the tool tip panel.
909
910 @interface NSToolTipPanel : NSPanel
911 @end
912
913 @interface NSToolTipPanel (WebHTMLViewPrivate)
914 @end
915
916 @implementation NSToolTipPanel (WebHTMLViewPrivate)
917
918 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
919 {
920     // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
921 }
922
923 @end
924
925
926 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
927 @end
928
929 @interface NSArray (WebHTMLView)
930 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
931 @end
932
933 @implementation WebHTMLView
934
935 + (void)initialize
936 {
937     WebKitInitializeUnicode();
938     [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] returnTypes:nil];
939 }
940
941 - (id)initWithFrame:(NSRect)frame
942 {
943     [super initWithFrame:frame];
944     
945     // Make all drawing go through us instead of subviews.
946     // The bulk of the code to handle this is in WebHTMLViewPrivate.m.
947     if (NSAppKitVersionNumber >= 711) {
948         [self _setDrawsOwnDescendants:YES];
949     }
950     
951     _private = [[WebHTMLViewPrivate alloc] init];
952
953     _private->pluginController = [[WebPluginController alloc] initWithHTMLView:self];
954     _private->needsLayout = YES;
955         
956     [self registerForDraggedTypes:[NSArray arrayWithObjects:WebArchivePboardType, NSHTMLPboardType, NSStringPboardType, nil]];
957
958     return self;
959 }
960
961 - (void)dealloc
962 {
963     [self _clearLastHitViewIfSelf];
964     [self _reset];
965     [[NSNotificationCenter defaultCenter] removeObserver:self];
966     [_private release];
967     _private = nil;
968     [super dealloc];
969 }
970
971 - (IBAction)takeFindStringFromSelection:(id)sender
972 {
973     if (![self _haveSelection]) {
974         NSBeep();
975         return;
976     }
977
978     [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
979 }
980
981 - (void)copy:(id)sender
982 {
983     [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
984 }
985
986 - (void)cut:(id)sender
987 {   
988         [self copy:sender];
989         [[self _bridge] deleteSelection];
990 }
991
992 - (void)delete:(id)sender
993 {
994         [[self _bridge] deleteSelection];
995 }
996
997 - (void)paste:(id)sender
998 {
999     [self _pasteMarkupFromPasteboard:[NSPasteboard generalPasteboard]];
1000 }
1001
1002 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1003 {
1004     [self _writeSelectionToPasteboard:pasteboard];
1005     return YES;
1006 }
1007
1008 - (void)selectAll:(id)sender
1009 {
1010     [self selectAll];
1011 }
1012
1013 - (void)jumpToSelection: sender
1014 {
1015     [[self _bridge] jumpToSelection];
1016 }
1017
1018 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item 
1019 {
1020     SEL action = [item action];
1021     
1022         if (action == @selector(cut:)) {
1023         return [self _canDelete];
1024     } else if (action == @selector(copy:)) {
1025         return [self _haveSelection];
1026     } else if (action == @selector(delete:)) {
1027         return [self _canDelete];
1028     } else if (action == @selector(paste:)) {
1029         return [self _canPaste];
1030     }else if (action == @selector(takeFindStringFromSelection:)) {
1031         return [self _haveSelection];
1032     }else if (action == @selector(jumpToSelection:)) {
1033         return [self _haveSelection];
1034         }
1035     
1036     return YES;
1037 }
1038
1039 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1040 {
1041     if (sendType && ([[[self class] _selectionPasteboardTypes] containsObject:sendType]) && [self _haveSelection]){
1042         return self;
1043     }
1044
1045     return [super validRequestorForSendType:sendType returnType:returnType];
1046 }
1047
1048 - (BOOL)acceptsFirstResponder
1049 {
1050     // Don't accept first responder when we first click on this view.
1051     // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1052     // Do accept first responder at any other time, for example from keyboard events,
1053     // or from calls back from WebCore once we begin mouse-down event handling.
1054     NSEvent *event = [NSApp currentEvent];
1055     if ([event type] == NSLeftMouseDown && event != _private->mouseDownEvent && 
1056         NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1057         return NO;
1058     }
1059     return YES;
1060 }
1061
1062 - (void)updateTextBackgroundColor
1063 {
1064     NSWindow *window = [self window];
1065     BOOL shouldUseInactiveTextBackgroundColor = !([window isKeyWindow] && [window firstResponder] == self);
1066     WebBridge *bridge = [self _bridge];
1067     if ([bridge usesInactiveTextBackgroundColor] != shouldUseInactiveTextBackgroundColor) {
1068         [bridge setUsesInactiveTextBackgroundColor:shouldUseInactiveTextBackgroundColor];
1069         [self setNeedsDisplayInRect:[bridge visibleSelectionRect]];
1070     }
1071 }
1072
1073 - (void)addMouseMovedObserver
1074 {
1075     if ([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) {
1076         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1077             name:NSMouseMovedNotification object:nil];
1078         [self _frameOrBoundsChanged];
1079     }
1080 }
1081
1082 - (void)removeMouseMovedObserver
1083 {
1084     [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1085     [[NSNotificationCenter defaultCenter] removeObserver:self
1086         name:NSMouseMovedNotification object:nil];
1087 }
1088
1089 - (void)updateShowsFirstResponder
1090 {
1091     [[self _bridge] setShowsFirstResponder:[[self window] isKeyWindow]];
1092 }
1093
1094 - (void)addSuperviewObservers
1095 {
1096     // We watch the bounds of our superview, so that we can do a layout when the size
1097     // of the superview changes. This is different from other scrollable things that don't
1098     // need this kind of thing because their layout doesn't change.
1099     
1100     // We need to pay attention to both height and width because our "layout" has to change
1101     // to extend the background the full height of the space and because some elements have
1102     // sizes that are based on the total size of the view.
1103     
1104     NSView *superview = [self superview];
1105     if (superview && [self window]) {
1106         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1107             name:NSViewFrameDidChangeNotification object:superview];
1108         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged) 
1109             name:NSViewBoundsDidChangeNotification object:superview];
1110     }
1111 }
1112
1113 - (void)removeSuperviewObservers
1114 {
1115     NSView *superview = [self superview];
1116     if (superview && [self window]) {
1117         [[NSNotificationCenter defaultCenter] removeObserver:self
1118             name:NSViewFrameDidChangeNotification object:superview];
1119         [[NSNotificationCenter defaultCenter] removeObserver:self
1120             name:NSViewBoundsDidChangeNotification object:superview];
1121     }
1122 }
1123
1124 - (void)addWindowObservers
1125 {
1126     NSWindow *window = [self window];
1127     if (window) {
1128         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1129             name:NSWindowDidBecomeKeyNotification object:window];
1130         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1131             name:NSWindowDidResignKeyNotification object:window];
1132         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1133             name:NSWindowWillCloseNotification object:window];
1134     }
1135 }
1136
1137 - (void)removeWindowObservers
1138 {
1139     NSWindow *window = [self window];
1140     if (window) {
1141         [[NSNotificationCenter defaultCenter] removeObserver:self
1142             name:NSWindowDidBecomeKeyNotification object:window];
1143         [[NSNotificationCenter defaultCenter] removeObserver:self
1144             name:NSWindowDidResignKeyNotification object:window];
1145         [[NSNotificationCenter defaultCenter] removeObserver:self
1146             name:NSWindowWillCloseNotification object:window];
1147     }
1148 }
1149
1150 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1151 {
1152     [self removeSuperviewObservers];
1153 }
1154
1155 - (void)viewDidMoveToSuperview
1156 {
1157     // Do this here in case the text size multiplier changed when a non-HTML
1158     // view was installed.
1159     if ([self superview] != nil) {
1160         [self _updateTextSizeMultiplier];
1161         [self addSuperviewObservers];
1162     }
1163 }
1164
1165 - (void)viewWillMoveToWindow:(NSWindow *)window
1166 {
1167     // Don't do anything if we aren't initialized.  This happens
1168     // when decoding a WebView.  When WebViews are decoded their subviews
1169     // are created by initWithCoder: and so won't be normally
1170     // initialized.  The stub views are discarded by WebView.
1171     if (_private){
1172         // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1173         [self removeMouseMovedObserver];
1174         [self removeWindowObservers];
1175         [self removeSuperviewObservers];
1176         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1177     
1178         [[self _pluginController] stopAllPlugins];
1179     }
1180 }
1181
1182 - (void)viewDidMoveToWindow
1183 {
1184     // Don't do anything if we aren't initialized.  This happens
1185     // when decoding a WebView.  When WebViews are decoded their subviews
1186     // are created by initWithCoder: and so won't be normally
1187     // initialized.  The stub views are discarded by WebView.
1188     if (_private) {
1189         [self _stopAutoscrollTimer];
1190         if ([self window]) {
1191             _private->lastScrollPosition = [[self superview] bounds].origin;
1192             [self addWindowObservers];
1193             [self addSuperviewObservers];
1194             [self addMouseMovedObserver];
1195             [self updateTextBackgroundColor];
1196     
1197             [[self _pluginController] startAllPlugins];
1198     
1199             _private->lastScrollPosition = NSZeroPoint;
1200             
1201             _private->inWindow = YES;
1202         } else {
1203             // Reset when we are moved out of a window after being moved into one.
1204             // Without this check, we reset ourselves before we even start.
1205             // This is only needed because viewDidMoveToWindow is called even when
1206             // the window is not changing (bug in AppKit).
1207             if (_private->inWindow) {
1208                 [self _reset];
1209                 _private->inWindow = NO;
1210             }
1211         }
1212     }
1213 }
1214
1215 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1216 {
1217     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1218 }
1219
1220 - (void)viewDidMoveToHostWindow
1221 {
1222     [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1223 }
1224
1225
1226 - (void)addSubview:(NSView *)view
1227 {
1228     [super addSubview:view];
1229
1230     if ([view conformsToProtocol:@protocol(WebPlugin)]) {
1231         [[self _pluginController] addPlugin:view];
1232     }
1233 }
1234
1235 - (void)reapplyStyles
1236 {
1237     if (!_private->needsToApplyStyles) {
1238         return;
1239     }
1240     
1241 #ifdef _KWQ_TIMING        
1242     double start = CFAbsoluteTimeGetCurrent();
1243 #endif
1244
1245     [[self _bridge] reapplyStylesForDeviceType:
1246         _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1247     
1248 #ifdef _KWQ_TIMING        
1249     double thisTime = CFAbsoluteTimeGetCurrent() - start;
1250     LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1251 #endif
1252
1253     _private->needsToApplyStyles = NO;
1254 }
1255
1256 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1257 // minPageWidth==0 implies a non-printing layout
1258 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1259 {
1260     [self reapplyStyles];
1261     
1262     // Ensure that we will receive mouse move events.  Is this the best place to put this?
1263     [[self window] setAcceptsMouseMovedEvents: YES];
1264     [[self window] _setShouldPostEventNotifications: YES];
1265
1266     if (!_private->needsLayout) {
1267         return;
1268     }
1269
1270 #ifdef _KWQ_TIMING        
1271     double start = CFAbsoluteTimeGetCurrent();
1272 #endif
1273
1274     LOG(View, "%@ doing layout", self);
1275
1276     if (minPageWidth > 0.0) {
1277         [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1278     } else {
1279         [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1280     }
1281     _private->needsLayout = NO;
1282     
1283     if (!_private->printing) {
1284         // get size of the containing dynamic scrollview, so
1285         // appearance and disappearance of scrollbars will not show up
1286         // as a size change
1287         NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1288         if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1289             [[self _bridge] sendResizeEvent];
1290         }
1291         _private->laidOutAtLeastOnce = YES;
1292         _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1293         _private->lastLayoutFrameSize = newLayoutFrameSize;
1294     }
1295
1296 #ifdef _KWQ_TIMING        
1297     double thisTime = CFAbsoluteTimeGetCurrent() - start;
1298     LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1299 #endif
1300 }
1301
1302 - (void)layout
1303 {
1304     [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1305 }
1306
1307 - (NSMenu *)menuForEvent:(NSEvent *)event
1308 {
1309     if ([[self _bridge] sendContextMenuEvent:event]) {
1310         return nil;
1311     }
1312     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1313     NSDictionary *element = [self _elementAtPoint:point];
1314     return [[self _webView] _menuForElement:element];
1315 }
1316
1317 // Search from the end of the currently selected location, or from the beginning of the
1318 // document if nothing is selected.
1319 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1320 {
1321     return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1322 }
1323
1324 - (NSString *)string
1325 {
1326     return [[self attributedString] string];
1327 }
1328
1329 - (NSAttributedString *)attributedString
1330 {
1331     WebBridge *b = [self _bridge];
1332     return [b attributedStringFrom:[b DOMDocument]
1333                        startOffset:0
1334                                 to:nil
1335                          endOffset:0];
1336 }
1337
1338 - (NSString *)selectedString
1339 {
1340     return [[self _bridge] selectedString];
1341 }
1342
1343 // Get an attributed string that represents the current selection.
1344 - (NSAttributedString *)selectedAttributedString
1345 {
1346     return [[self _bridge] selectedAttributedString];
1347 }
1348
1349 - (void)selectAll
1350 {
1351     [[self _bridge] selectAll];
1352 }
1353
1354 // Remove the selection.
1355 - (void)deselectAll
1356 {
1357     [[self _bridge] deselectAll];
1358 }
1359
1360 - (void)deselectText
1361 {
1362     [[self _bridge] deselectText];
1363 }
1364
1365 - (BOOL)isOpaque
1366 {
1367     return YES;
1368 }
1369
1370 - (void)setNeedsDisplay:(BOOL)flag
1371 {
1372     LOG(View, "%@ flag = %d", self, (int)flag);
1373     [super setNeedsDisplay: flag];
1374 }
1375
1376 - (void)setNeedsLayout: (BOOL)flag
1377 {
1378     LOG(View, "%@ flag = %d", self, (int)flag);
1379     _private->needsLayout = flag;
1380 }
1381
1382
1383 - (void)setNeedsToApplyStyles: (BOOL)flag
1384 {
1385     LOG(View, "%@ flag = %d", self, (int)flag);
1386     _private->needsToApplyStyles = flag;
1387 }
1388
1389 - (void)drawRect:(NSRect)rect
1390 {
1391     LOG(View, "%@ drawing", self);
1392     
1393     BOOL subviewsWereSetAside = _private->subviewsSetAside;
1394     if (subviewsWereSetAside) {
1395         [self _restoreSubviews];
1396     }
1397
1398 #ifdef _KWQ_TIMING
1399     double start = CFAbsoluteTimeGetCurrent();
1400 #endif
1401
1402     [NSGraphicsContext saveGraphicsState];
1403     NSRectClip(rect);
1404         
1405     ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
1406
1407     [(WebClipView *)[self superview] setAdditionalClip:rect];
1408
1409     NS_DURING {
1410         WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
1411         if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
1412             textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
1413             [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
1414         }
1415
1416         //double start = CFAbsoluteTimeGetCurrent();
1417         [[self _bridge] drawRect:rect];
1418         //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
1419
1420         if (textRendererFactoryIfCoalescing != nil) {
1421             [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
1422         }
1423
1424         [(WebClipView *)[self superview] resetAdditionalClip];
1425
1426         [NSGraphicsContext restoreGraphicsState];
1427     } NS_HANDLER {
1428         [(WebClipView *)[self superview] resetAdditionalClip];
1429         [NSGraphicsContext restoreGraphicsState];
1430         ERROR("Exception caught while drawing: %@", localException);
1431         [localException raise];
1432     } NS_ENDHANDLER
1433
1434 #ifdef DEBUG_LAYOUT
1435     NSRect vframe = [self frame];
1436     [[NSColor blackColor] set];
1437     NSBezierPath *path;
1438     path = [NSBezierPath bezierPath];
1439     [path setLineWidth:(float)0.1];
1440     [path moveToPoint:NSMakePoint(0, 0)];
1441     [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
1442     [path closePath];
1443     [path stroke];
1444     path = [NSBezierPath bezierPath];
1445     [path setLineWidth:(float)0.1];
1446     [path moveToPoint:NSMakePoint(0, vframe.size.height)];
1447     [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
1448     [path closePath];
1449     [path stroke];
1450 #endif
1451
1452 #ifdef _KWQ_TIMING
1453     double thisTime = CFAbsoluteTimeGetCurrent() - start;
1454     LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
1455 #endif
1456
1457     if (subviewsWereSetAside) {
1458         [self _setAsideSubviews];
1459     }
1460 }
1461
1462 // Turn off the additional clip while computing our visibleRect.
1463 - (NSRect)visibleRect
1464 {
1465     if (!([[self superview] isKindOfClass:[WebClipView class]]))
1466         return [super visibleRect];
1467         
1468     WebClipView *clipView = (WebClipView *)[self superview];
1469
1470     BOOL hasAdditionalClip = [clipView hasAdditionalClip];
1471     if (!hasAdditionalClip) {
1472         return [super visibleRect];
1473     }
1474     
1475     NSRect additionalClip = [clipView additionalClip];
1476     [clipView resetAdditionalClip];
1477     NSRect visibleRect = [super visibleRect];
1478     [clipView setAdditionalClip:additionalClip];
1479     return visibleRect;
1480 }
1481
1482 - (BOOL)isFlipped 
1483 {
1484     return YES;
1485 }
1486
1487 - (void)windowDidBecomeKey:(NSNotification *)notification
1488 {
1489     ASSERT([notification object] == [self window]);
1490     [self addMouseMovedObserver];
1491     [self updateTextBackgroundColor];
1492     [self updateShowsFirstResponder];
1493 }
1494
1495 - (void)windowDidResignKey: (NSNotification *)notification
1496 {
1497     ASSERT([notification object] == [self window]);
1498     [self removeMouseMovedObserver];
1499     [self updateTextBackgroundColor];
1500     [self updateShowsFirstResponder];
1501 }
1502
1503 - (void)windowWillClose:(NSNotification *)notification
1504 {
1505     [[self _pluginController] destroyAllPlugins];
1506 }
1507
1508 - (BOOL)_isSelectionEvent:(NSEvent *)event
1509 {
1510     NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1511     return [[[self _elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
1512 }
1513
1514 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1515 {
1516     return [self _isSelectionEvent:event];
1517 }
1518
1519 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1520 {
1521     return [self _isSelectionEvent:event];
1522 }
1523
1524 - (void)mouseDown:(NSEvent *)event
1525 {
1526     // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
1527     // We don't want to pass them along to KHTML a second time.
1528     if ([event modifierFlags] & NSControlKeyMask) {
1529         return;
1530     }
1531     
1532     _private->ignoringMouseDraggedEvents = NO;
1533     
1534     // Record the mouse down position so we can determine drag hysteresis.
1535     [_private->mouseDownEvent release];
1536     _private->mouseDownEvent = [event retain];
1537
1538     // Don't do any mouseover while the mouse is down.
1539     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1540
1541     // Let KHTML get a chance to deal with the event. This will call back to us
1542     // to start the autoscroll timer if appropriate.
1543     [[self _bridge] mouseDown:event];
1544 }
1545
1546 - (void)dragImage:(NSImage *)dragImage
1547                at:(NSPoint)at
1548            offset:(NSSize)offset
1549             event:(NSEvent *)event
1550        pasteboard:(NSPasteboard *)pasteboard
1551            source:(id)source
1552         slideBack:(BOOL)slideBack
1553 {   
1554     _private->isDragging = YES;
1555     
1556     [self _stopAutoscrollTimer];
1557
1558     // Don't allow drags to be accepted by this WebFrameView.
1559     [[self _webView] unregisterDraggedTypes];
1560     
1561     // Retain this view during the drag because it may be released before the drag ends.
1562     [self retain];
1563
1564     [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
1565 }
1566
1567 - (void)mouseDragged:(NSEvent *)event
1568 {
1569     if (!_private->ignoringMouseDraggedEvents) {
1570         [[self _bridge] mouseDragged:event];
1571     }
1572 }
1573
1574 - (unsigned)draggingSourceOperationMaskForLocal:(BOOL)isLocal
1575 {
1576     return (NSDragOperationGeneric|NSDragOperationCopy);
1577 }
1578
1579 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1580 {
1581     _private->isDragging = NO;
1582     
1583     // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1584     _private->ignoringMouseDraggedEvents = YES;
1585     
1586     // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
1587     // khtml expects to get balanced down/up's, so we must fake up a mouseup.
1588     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
1589                                             location:[[self window] convertScreenToBase:aPoint]
1590                                        modifierFlags:[[NSApp currentEvent] modifierFlags]
1591                                            timestamp:[NSDate timeIntervalSinceReferenceDate]
1592                                         windowNumber:[[self window] windowNumber]
1593                                              context:[[NSApp currentEvent] context]
1594                                          eventNumber:0 clickCount:0 pressure:0];
1595     [self mouseUp:fakeEvent];       // This will also update the mouseover state.
1596
1597     // Reregister for drag types because they were unregistered before the drag.
1598     [[self _webView] _registerDraggedTypes];
1599     
1600     // Balance the previous retain from when the drag started.
1601     [self release];
1602 }
1603
1604 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
1605 {
1606     ASSERT(_private->draggingImageURL);
1607     
1608     NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
1609     ASSERT(wrapper);    
1610     
1611     // FIXME: Report an error if we fail to create a file.
1612     NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
1613     path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
1614     if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
1615         ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
1616     }
1617     
1618     return [NSArray arrayWithObject:[path lastPathComponent]];
1619 }
1620
1621 - (NSDragOperation)_dragOperationForDraggingInfo:(id <NSDraggingInfo>)sender
1622 {
1623     NSPoint point = [self convertPoint:[sender draggingLocation] fromView:nil];
1624     NSDictionary *element = [self _elementAtPoint:point];
1625     if ([[element objectForKey:WebElementIsEditableKey] boolValue] && [[self _bridge] moveCaretToPoint:point]) {
1626         if (_private->isDragging) {
1627             if ([[element objectForKey:WebElementIsSelectedKey] boolValue]) {
1628                 return NSDragOperationMove;
1629             }
1630         } else {
1631             return NSDragOperationCopy;
1632         }
1633     }
1634     return NSDragOperationNone;
1635 }
1636
1637 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1638 {
1639     // If we're not handling the drag, forward this message to the WebView since it may want to handle it.
1640     NSDragOperation dragOperation = [self _dragOperationForDraggingInfo:sender];
1641     return dragOperation != NSDragOperationNone ? dragOperation : [[self _webView] draggingEntered:sender];
1642 }
1643
1644 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1645 {
1646     // If we're not handling the drag, forward this message to the WebView since it may want to handle it.
1647     NSDragOperation dragOperation = [self _dragOperationForDraggingInfo:sender];
1648     return dragOperation != NSDragOperationNone ? dragOperation : [[self _webView] draggingUpdated:sender];
1649 }
1650
1651 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
1652 {
1653     return YES;
1654 }
1655
1656 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1657 {
1658     return YES;
1659 }
1660
1661 - (void)concludeDragOperation:(id <NSDraggingInfo>)sender
1662 {
1663     if ([self _dragOperationForDraggingInfo:sender] != NSDragOperationNone) {
1664         // FIXME: We should delete the original selection if we're doing a move.
1665         [self _pasteMarkupFromPasteboard:[sender draggingPasteboard]];
1666     } else {
1667         // Since we're not handling the drag, forward this message to the WebView since it may want to handle it.
1668         [[self _webView] concludeDragOperation:sender];
1669     }
1670 }
1671
1672 - (void)mouseUp:(NSEvent *)event
1673 {
1674     [self _stopAutoscrollTimer];
1675     [[self _bridge] mouseUp:event];
1676     [self _updateMouseoverWithFakeEvent];
1677 }
1678
1679 - (void)mouseMovedNotification:(NSNotification *)notification
1680 {
1681     [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
1682 }
1683
1684 - (BOOL)supportsTextEncoding
1685 {
1686     return YES;
1687 }
1688
1689 - (NSView *)nextKeyView
1690 {
1691     return (_private && _private->inNextValidKeyView && ![[self _bridge] inNextKeyViewOutsideWebFrameViews])
1692         ? [[self _bridge] nextKeyView]
1693         : [super nextKeyView];
1694 }
1695
1696 - (NSView *)previousKeyView
1697 {
1698     return (_private && _private->inNextValidKeyView)
1699         ? [[self _bridge] previousKeyView]
1700         : [super previousKeyView];
1701 }
1702
1703 - (NSView *)nextValidKeyView
1704 {
1705     _private->inNextValidKeyView = YES;
1706     NSView *view = [super nextValidKeyView];
1707     _private->inNextValidKeyView = NO;
1708     return view;
1709 }
1710
1711 - (NSView *)previousValidKeyView
1712 {
1713     _private->inNextValidKeyView = YES;
1714     NSView *view = [super previousValidKeyView];
1715     _private->inNextValidKeyView = NO;
1716     return view;
1717 }
1718
1719 - (BOOL)becomeFirstResponder
1720 {
1721     NSView *view = nil;
1722     if (![[self _webView] _isPerformingProgrammaticFocus]) {
1723         switch ([[self window] keyViewSelectionDirection]) {
1724         case NSDirectSelection:
1725             break;
1726         case NSSelectingNext:
1727             view = [[self _bridge] nextKeyViewInsideWebFrameViews];
1728             break;
1729         case NSSelectingPrevious:
1730             view = [[self _bridge] previousKeyViewInsideWebFrameViews];
1731             break;
1732         }
1733     }
1734     if (view) {
1735         [[self window] makeFirstResponder:view];
1736     }
1737     [self updateTextBackgroundColor];
1738     return YES;
1739 }
1740
1741 // This approach could be relaxed when dealing with 3228554
1742 - (BOOL)resignFirstResponder
1743 {
1744     BOOL resign = [super resignFirstResponder];
1745     if (resign) {
1746         if ([[self _webView] _isPerformingProgrammaticFocus]) {
1747             [self deselectText];
1748         }
1749         else {
1750             [self deselectAll];
1751         }
1752         [self updateTextBackgroundColor];
1753     }
1754     return resign;
1755 }
1756
1757 //------------------------------------------------------------------------------------
1758 // WebDocumentView protocol
1759 //------------------------------------------------------------------------------------
1760 - (void)setDataSource:(WebDataSource *)dataSource 
1761 {
1762 }
1763
1764 - (void)dataSourceUpdated:(WebDataSource *)dataSource
1765 {
1766 }
1767
1768 // Does setNeedsDisplay:NO as a side effect when printing is ending.
1769 // pageWidth != 0 implies we will relayout to a new width
1770 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
1771 {
1772     WebFrame *frame = [self _frame];
1773     NSArray *subframes = [frame childFrames];
1774     unsigned n = [subframes count];
1775     unsigned i;
1776     for (i = 0; i != n; ++i) {
1777         WebFrame *subframe = [subframes objectAtIndex:i];
1778         WebFrameView *frameView = [subframe frameView];
1779         if ([[subframe dataSource] _isDocumentHTML]) {
1780             [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
1781         }
1782     }
1783
1784     if (printing != _private->printing) {
1785         [_private->pageRects release];
1786         _private->pageRects = nil;
1787         _private->printing = printing;
1788         [self setNeedsToApplyStyles:YES];
1789         [self setNeedsLayout:YES];
1790         [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1791         if (printing) {
1792             [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
1793         } else {
1794             // Can't do this when starting printing or nested printing won't work, see 3491427.
1795             [self setNeedsDisplay:NO];
1796         }
1797     }
1798 }
1799
1800 // This is needed for the case where the webview is embedded in the view that's being printed.
1801 // It shouldn't be called when the webview is being printed directly.
1802 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
1803 {
1804     // This helps when we print as part of a larger print process.
1805     // If the WebHTMLView itself is what we're printing, then we will never have to do this.
1806     BOOL wasInPrintingMode = _private->printing;
1807     if (!wasInPrintingMode) {
1808         [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1809     }
1810     
1811     [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
1812     
1813     if (!wasInPrintingMode) {
1814         [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1815     }
1816 }
1817
1818 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
1819 {
1820     NSPrintInfo *printInfo = [printOperation printInfo];
1821     return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
1822 }
1823
1824 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
1825 {
1826     float viewWidth = NSWidth([self bounds]);
1827     if (viewWidth < 1) {
1828         ERROR("%@ has no width when printing", self);
1829         return 1.0;
1830     }
1831         
1832     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
1833     float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
1834     float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
1835     return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
1836 }
1837
1838 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
1839 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
1840 // if AppKit makes it SPI/API.
1841 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation 
1842 {
1843     return [self _scaleFactorForPrintOperation:printOperation];
1844 }
1845
1846 // Return the number of pages available for printing
1847 - (BOOL)knowsPageRange:(NSRangePointer)range {
1848     // Must do this explicit display here, because otherwise the view might redisplay while the print
1849     // sheet was up, using printer fonts (and looking different).
1850     [self displayIfNeeded];
1851     [[self window] setAutodisplay:NO];
1852     
1853     // If we are a frameset just print with the layout we have onscreen, otherwise relayout
1854     // according to the paper size
1855     float minLayoutWidth = 0.0;
1856     float maxLayoutWidth = 0.0;
1857     if (![[self _bridge] isFrameSet]) {
1858         float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
1859         minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
1860         maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
1861     }
1862     [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
1863     
1864     // There is a theoretical chance that someone could do some drawing between here and endDocument,
1865     // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
1866     // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
1867
1868     range->location = 1;
1869     NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
1870     float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
1871     float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
1872     [_private->pageRects release];
1873     _private->pageRects = [[[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
1874                                                                          printHeight:[self _calculatePrintHeight]/totalScaleFactor] retain];
1875     range->length = [_private->pageRects count];
1876     return YES;
1877 }
1878
1879 // Return the drawing rectangle for a particular page number
1880 - (NSRect)rectForPage:(int)page {
1881     return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
1882 }
1883
1884 // Calculate the vertical size of the view that fits on a single page
1885 - (float)_calculatePrintHeight {
1886     // Obtain the print info object for the current operation
1887     NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
1888     
1889     // Calculate the page height in points
1890     NSSize paperSize = [pi paperSize];
1891     return paperSize.height - [pi topMargin] - [pi bottomMargin];
1892 }
1893
1894 - (void)drawPageBorderWithSize:(NSSize)borderSize
1895 {
1896     ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));    
1897     [[self _webView] _drawHeaderAndFooter];
1898 }
1899
1900 - (void)endDocument
1901 {
1902     [super endDocument];
1903     // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO 
1904     [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
1905     [[self window] setAutodisplay:YES];
1906 }
1907
1908 - (void)_updateTextSizeMultiplier
1909 {
1910     [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];    
1911 }
1912
1913 - (BOOL)performKeyEquivalent:(NSEvent *)event
1914 {
1915     // Pass command-key combos through WebCore so Command-return on an active link is treated
1916     // as a modified activation rather than ignored. Note that this means web pages have a crack 
1917     // at intercepting command-modified keypresses now. If this turns out to cause havoc we
1918     // can restrict this to only send the event through WebCore if it contains the Return or
1919     // Enter key.
1920     if ([[self _bridge] interceptKeyEvent:event toView:self]) {
1921         return YES;
1922     }
1923
1924     return [super performKeyEquivalent:event];
1925 }
1926
1927 - (void)keyDown:(NSEvent *)event
1928 {
1929     BOOL intercepted = [[self _bridge] interceptKeyEvent:event toView:self];
1930     if (!intercepted || [event _web_isTabKeyEvent]) {
1931         [super keyDown:event];
1932     }
1933 }
1934
1935 - (void)keyUp:(NSEvent *)event
1936 {
1937     if (![[self _bridge] interceptKeyEvent:event toView:self]) {
1938         [super keyUp:event];
1939     }
1940 }
1941
1942 - (id)accessibilityAttributeValue:(NSString*)attributeName
1943 {
1944     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
1945         id accTree = [[self _bridge] accessibilityTree];
1946         if (accTree)
1947             return [NSArray arrayWithObject: accTree];
1948         return nil;
1949     }
1950     return [super accessibilityAttributeValue:attributeName];
1951 }
1952
1953 - (id)accessibilityHitTest:(NSPoint)point
1954 {
1955     id accTree = [[self _bridge] accessibilityTree];
1956     if (accTree) {
1957         NSPoint windowCoord = [[self window] convertScreenToBase: point];
1958         return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
1959     }
1960     else
1961         return self;
1962 }
1963 @end
1964
1965 @implementation WebHTMLView (TextSizing)
1966
1967 - (void)_web_textSizeMultiplierChanged
1968 {
1969     [self _updateTextSizeMultiplier];
1970 }
1971
1972 @end
1973
1974 @implementation NSArray (WebHTMLView)
1975
1976 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object
1977 {
1978     NSEnumerator *enumerator = [self objectEnumerator];
1979     WebNetscapePluginEmbeddedView *view;
1980     while ((view = [enumerator nextObject]) != nil) {
1981         if ([view isKindOfClass:[WebNetscapePluginEmbeddedView class]]) {
1982             [view performSelector:selector withObject:object];
1983         }
1984     }
1985 }
1986
1987 @end