3 Copyright 2002, Apple, Inc. All rights reserved.
6 #import <WebKit/WebHTMLView.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/WebViewPrivate.h>
45 #import <AppKit/NSAccessibility.h>
46 #import <AppKit/NSGraphicsContextPrivate.h>
47 #import <AppKit/NSResponder_Private.h>
49 #import <Foundation/NSFileManager_NSURLExtras.h>
50 #import <Foundation/NSURL_NSURLExtras.h>
51 #import <Foundation/NSURLFileTypeMappings.h>
53 #import <CoreGraphics/CGContextGState.h>
55 // By imaging to a width a little wider than the available pixels,
56 // thin pages will be scaled down a little, matching the way they
57 // print in IE and Camino. This lets them use fewer sheets than they
58 // would otherwise, which is presumably why other browsers do this.
59 // Wide pages will be scaled down more than this.
60 #define PrintingMinimumShrinkFactor 1.25
62 // This number determines how small we are willing to reduce the page content
63 // in order to accommodate the widest line. If the page would have to be
64 // reduced smaller to make the widest line fit, we just clip instead (this
65 // behavior matches MacIE and Mozilla, at least)
66 #define PrintingMaximumShrinkFactor 2.0
68 #define AUTOSCROLL_INTERVAL 0.1
70 #define DRAG_LABEL_BORDER_X 4.0
71 #define DRAG_LABEL_BORDER_Y 2.0
72 #define DRAG_LABEL_RADIUS 5.0
73 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
75 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
76 #define MAX_DRAG_LABEL_WIDTH 320.0
78 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
79 #define DRAG_LINK_URL_FONT_SIZE 10.0
81 static BOOL forceRealHitTest = NO;
83 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
86 @interface WebHTMLView (WebFileInternal)
87 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
88 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
89 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
90 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
93 @interface WebHTMLView (WebHTMLViewPrivate)
94 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
95 - (void)_updateTextSizeMultiplier;
96 - (float)_calculatePrintHeight;
97 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation;
100 // Any non-zero value will do, but using somethign recognizable might help us debug some day.
101 #define TRACKING_RECT_TAG 0xBADFACE
103 @interface NSView (AppKitSecretsIKnowAbout)
104 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
105 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
106 - (NSRect)_dirtyRect;
107 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
110 @interface NSApplication (AppKitSecretsIKnowAbout)
111 - (void)speakString:(NSString *)string;
114 @interface NSWindow (AppKitSecretsIKnowAbout)
115 - (id)_newFirstResponderAfterResigning;
118 @interface NSView (WebHTMLViewPrivate)
119 - (void)_web_setPrintingModeRecursive;
120 - (void)_web_clearPrintingModeRecursive;
121 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
124 @interface NSMutableDictionary (WebHTMLViewPrivate)
125 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
128 @interface WebElementOrTextFilter : NSObject <DOMNodeFilter>
129 + (WebElementOrTextFilter *)filter;
132 static WebElementOrTextFilter *elementOrTextFilterInstance = nil;
134 @implementation WebHTMLViewPrivate
138 ASSERT(autoscrollTimer == nil);
139 ASSERT(autoscrollTriggerEvent == nil);
141 [mouseDownEvent release];
142 [draggingImageURL release];
143 [pluginController release];
151 @implementation WebHTMLView (WebFileInternal)
153 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
155 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
156 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
157 NSEnumerator *enumerator = [paths objectEnumerator];
160 while ((path = [enumerator nextObject]) != nil) {
161 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
162 if ([imageMIMETypes containsObject:MIMEType]) {
170 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
172 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
173 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
174 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
175 NSEnumerator *enumerator = [paths objectEnumerator];
176 WebDataSource *dataSource = [self _dataSource];
179 while ((path = [enumerator nextObject]) != nil) {
180 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
181 if ([imageMIMETypes containsObject:MIMEType]) {
182 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
183 URL:[NSURL fileURLWithPath:path]
188 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
194 return [fragment firstChild] != nil ? fragment : nil;
197 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
199 NSArray *types = [pasteboard types];
201 if ([types containsObject:WebArchivePboardType]) {
202 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
204 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
212 if ([types containsObject:NSFilenamesPboardType]) {
213 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
214 if (fragment != nil) {
221 if ([types containsObject:NSHTMLPboardType]) {
222 return [[self _bridge] documentFragmentWithMarkupString:[pasteboard stringForType:NSHTMLPboardType] baseURLString:nil];
223 } else if ([types containsObject:NSTIFFPboardType]) {
224 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
225 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
226 MIMEType:@"image/tiff"
229 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
232 } else if ([types containsObject:NSPICTPboardType]) {
233 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
234 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
235 MIMEType:@"image/pict"
238 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
241 } else if ((URL = [pasteboard _web_bestURL])) {
242 NSString *URLString = [URL _web_originalDataAsString];
243 NSString *linkLabel = [pasteboard stringForType:WebURLNamePboardType];
244 linkLabel = [linkLabel length] > 0 ? linkLabel : URLString;
246 DOMDocument *document = [[self _bridge] DOMDocument];
247 DOMDocumentFragment *fragment = [document createDocumentFragment];
248 DOMElement *anchorElement = [document createElement:@"a"];
249 [anchorElement setAttribute:@"href" :URLString];
250 [fragment appendChild:anchorElement];
251 [anchorElement appendChild:[document createTextNode:linkLabel]];
253 } else if ([types containsObject:NSRTFDPboardType]) {
254 // FIXME: Support RTFD to HTML (or DOM) conversion.
255 ERROR("RTFD to HTML conversion not yet supported.");
256 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
257 } else if ([types containsObject:NSRTFPboardType]) {
258 // FIXME: Support RTF to HTML (or DOM) conversion.
259 ERROR("RTF to HTML conversion not yet supported.");
260 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
261 } else if (allowPlainText && [types containsObject:NSStringPboardType]) {
262 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
268 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
270 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText];
271 WebBridge *bridge = [self _bridge];
272 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
273 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO];
277 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
279 WebView *webView = [self _webView];
280 DOMNode *child = [fragment firstChild];
281 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
282 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
284 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
290 @implementation WebHTMLView (WebPrivate)
294 [WebImageRenderer stopAnimationsInView:self];
297 - (WebView *)_webView
299 // We used to use the view hierarchy exclusively here, but that won't work
300 // right when the first viewDidMoveToSuperview call is done, and this wil.
301 return [[self _frame] webView];
306 WebFrameView *webFrameView = [self _web_parentWebFrameView];
307 return [webFrameView webFrame];
310 // Required so view can access the part's selection.
311 - (WebBridge *)_bridge
313 return [[self _frame] _bridge];
316 - (WebDataSource *)_dataSource
318 return [[self _frame] dataSource];
321 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
323 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
324 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
325 modifierFlags:[flagsChangedEvent modifierFlags]
326 timestamp:[flagsChangedEvent timestamp]
327 windowNumber:[flagsChangedEvent windowNumber]
328 context:[flagsChangedEvent context]
329 eventNumber:0 clickCount:0 pressure:0];
331 // Pretend it's a mouse move.
332 [[NSNotificationCenter defaultCenter]
333 postNotificationName:NSMouseMovedNotification object:self
334 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
337 - (void)_updateMouseoverWithFakeEvent
339 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
340 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
341 modifierFlags:[[NSApp currentEvent] modifierFlags]
342 timestamp:[NSDate timeIntervalSinceReferenceDate]
343 windowNumber:[[self window] windowNumber]
344 context:[[NSApp currentEvent] context]
345 eventNumber:0 clickCount:0 pressure:0];
347 [self _updateMouseoverWithEvent:fakeEvent];
350 - (void)_frameOrBoundsChanged
352 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
353 [self setNeedsLayout:YES];
354 [self setNeedsDisplay:YES];
357 NSPoint origin = [[self superview] bounds].origin;
358 if (!NSEqualPoints(_private->lastScrollPosition, origin))
359 [[self _bridge] sendScrollEvent];
360 _private->lastScrollPosition = origin;
362 SEL selector = @selector(_updateMouseoverWithFakeEvent);
363 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
364 [self performSelector:selector withObject:nil afterDelay:0];
367 - (void)_setAsideSubviews
369 ASSERT(!_private->subviewsSetAside);
370 ASSERT(_private->savedSubviews == nil);
371 _private->savedSubviews = _subviews;
373 _private->subviewsSetAside = YES;
376 - (void)_restoreSubviews
378 ASSERT(_private->subviewsSetAside);
379 ASSERT(_subviews == nil);
380 _subviews = _private->savedSubviews;
381 _private->savedSubviews = nil;
382 _private->subviewsSetAside = NO;
385 // Don't let AppKit even draw subviews. We take care of that.
386 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
388 // This helps when we print as part of a larger print process.
389 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
390 BOOL wasInPrintingMode = _private->printing;
391 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
392 if (wasInPrintingMode != isPrinting) {
394 [self _web_setPrintingModeRecursive];
396 [self _web_clearPrintingModeRecursive];
400 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
402 [self _setAsideSubviews];
403 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
404 rectIsVisibleRectForView:visibleView topView:topView];
405 [self _restoreSubviews];
407 if (wasInPrintingMode != isPrinting) {
408 if (wasInPrintingMode) {
409 [self _web_setPrintingModeRecursive];
411 [self _web_clearPrintingModeRecursive];
416 // Don't let AppKit even draw subviews. We take care of that.
417 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
419 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
421 BOOL wasInPrintingMode = _private->printing;
422 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
424 if (needToSetAsideSubviews) {
425 // This helps when we print as part of a larger print process.
426 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
427 if (wasInPrintingMode != isPrinting) {
429 [self _web_setPrintingModeRecursive];
431 [self _web_clearPrintingModeRecursive];
435 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
437 [self _setAsideSubviews];
440 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
442 if (needToSetAsideSubviews) {
443 if (wasInPrintingMode != isPrinting) {
444 if (wasInPrintingMode) {
445 [self _web_setPrintingModeRecursive];
447 [self _web_clearPrintingModeRecursive];
451 [self _restoreSubviews];
455 - (BOOL)_insideAnotherHTMLView
458 while ((view = [view superview])) {
459 if ([view isKindOfClass:[WebHTMLView class]]) {
466 - (void)scrollPoint:(NSPoint)point
468 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
469 // If we get called during the handling of a key down event, we assume the call came from
470 // NSTextView, and ignore it and use our own code to decide how to page up and page down
471 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
472 NSEvent *event = [[self window] currentEvent];
473 if ([event type] == NSKeyDown) {
474 const unichar pageUp = NSPageUpFunctionKey;
475 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
476 [self tryToPerform:@selector(scrollPageUp:) with:nil];
479 const unichar pageDown = NSPageDownFunctionKey;
480 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
481 [self tryToPerform:@selector(scrollPageDown:) with:nil];
486 [super scrollPoint:point];
489 - (NSView *)hitTest:(NSPoint)point
491 // WebHTMLView objects handle all left mouse clicks for objects inside them.
492 // That does not include left mouse clicks with the control key held down.
493 BOOL captureHitsOnSubviews;
494 if (forceRealHitTest) {
495 captureHitsOnSubviews = NO;
497 NSEvent *event = [[self window] currentEvent];
498 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
500 if (!captureHitsOnSubviews) {
501 return [super hitTest:point];
503 if ([[self superview] mouse:point inRect:[self frame]]) {
509 static WebHTMLView *lastHitView = nil;
511 - (void)_clearLastHitViewIfSelf
513 if (lastHitView == self) {
518 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
520 ASSERT(_private->trackingRectOwner == nil);
521 _private->trackingRectOwner = owner;
522 _private->trackingRectUserData = data;
523 return TRACKING_RECT_TAG;
526 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
528 ASSERT(tag == TRACKING_RECT_TAG);
529 return [self addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
532 - (void)removeTrackingRect:(NSTrackingRectTag)tag
534 ASSERT(tag == TRACKING_RECT_TAG);
535 if (_private != nil) {
536 _private->trackingRectOwner = nil;
540 - (void)_sendToolTipMouseExited
542 // Nothing matters except window, trackingNumber, and userData.
543 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
544 location:NSMakePoint(0, 0)
547 windowNumber:[[self window] windowNumber]
550 trackingNumber:TRACKING_RECT_TAG
551 userData:_private->trackingRectUserData];
552 [_private->trackingRectOwner mouseExited:fakeEvent];
555 - (void)_sendToolTipMouseEntered
557 // Nothing matters except window, trackingNumber, and userData.
558 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
559 location:NSMakePoint(0, 0)
562 windowNumber:[[self window] windowNumber]
565 trackingNumber:TRACKING_RECT_TAG
566 userData:_private->trackingRectUserData];
567 [_private->trackingRectOwner mouseEntered:fakeEvent];
570 - (void)_setToolTip:(NSString *)string
572 NSString *toolTip = [string length] == 0 ? nil : string;
573 NSString *oldToolTip = _private->toolTip;
574 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
578 [self _sendToolTipMouseExited];
579 [oldToolTip release];
581 _private->toolTip = [toolTip copy];
583 [self removeAllToolTips];
584 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
585 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
586 [self _sendToolTipMouseEntered];
590 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
592 return [[_private->toolTip copy] autorelease];
595 - (void)_updateMouseoverWithEvent:(NSEvent *)event
597 WebHTMLView *view = nil;
598 if ([event window] == [self window]) {
599 forceRealHitTest = YES;
600 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
601 forceRealHitTest = NO;
603 if ([hitView isKindOfClass:[WebHTMLView class]]) {
604 view = (WebHTMLView *)hitView;
607 hitView = [hitView superview];
611 if (lastHitView != view && lastHitView != nil) {
612 // If we are moving out of a view (or frame), let's pretend the mouse moved
613 // all the way out of that view. But we have to account for scrolling, because
614 // khtml doesn't understand our clipping.
615 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
616 float yScroll = visibleRect.origin.y;
617 float xScroll = visibleRect.origin.x;
619 event = [NSEvent mouseEventWithType:NSMouseMoved
620 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
621 modifierFlags:[[NSApp currentEvent] modifierFlags]
622 timestamp:[NSDate timeIntervalSinceReferenceDate]
623 windowNumber:[[self window] windowNumber]
624 context:[[NSApp currentEvent] context]
625 eventNumber:0 clickCount:0 pressure:0];
626 [[lastHitView _bridge] mouseMoved:event];
631 NSDictionary *element;
635 [[view _bridge] mouseMoved:event];
637 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
638 element = [view elementAtPoint:point];
641 // Have the web view send a message to the delegate so it can do status bar display.
642 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
644 // Set a tool tip; it won't show up right away but will if the user pauses.
645 [self _setToolTip:[element objectForKey:WebCoreElementTitleKey]];
648 + (NSArray *)_insertablePasteboardTypes
650 static NSArray *types = nil;
652 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
653 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
654 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
659 + (NSArray *)_selectionPasteboardTypes
661 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
662 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
665 - (WebArchive *)_selectedArchive
668 NSString *markupString = [[self _bridge] markupStringFromRange:[[self _bridge] selectedDOMRange] nodes:&nodes];
669 return [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
672 - (NSData *)_selectedRTFData
674 NSAttributedString *attributedString = [self selectedAttributedString];
675 NSRange range = NSMakeRange(0, [attributedString length]);
676 return [attributedString RTFFromRange:range documentAttributes:nil];
679 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
681 ASSERT([self _haveSelection]);
682 NSArray *types = [[self class] _selectionPasteboardTypes];
683 [pasteboard declareTypes:types owner:nil];
684 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
687 - (BOOL)_haveSelection
689 return [[self _bridge] haveSelection];
694 return [self _haveSelection] && [[self _bridge] isSelectionEditable];
699 return [[self _bridge] isSelectionEditable];
702 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
704 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
706 BOOL drawURLString = YES;
707 BOOL clipURLString = NO, clipLabelString = NO;
709 NSString *label = [element objectForKey: WebElementLinkLabelKey];
710 NSString *urlString = [linkURL _web_userVisibleString];
717 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
718 toHaveTrait:NSBoldFontMask];
719 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
721 labelSize.width = [label _web_widthWithFont: labelFont];
722 labelSize.height = [labelFont ascender] - [labelFont descender];
723 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
724 labelSize.width = MAX_DRAG_LABEL_WIDTH;
725 clipLabelString = YES;
728 NSSize imageSize, urlStringSize;
729 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
730 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
732 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
733 urlStringSize.height = [urlFont ascender] - [urlFont descender];
734 imageSize.height += urlStringSize.height;
735 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
736 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
739 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
742 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
743 [dragImage lockFocus];
745 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
747 // Drag a rectangle with rounded corners/
748 NSBezierPath *path = [NSBezierPath bezierPath];
749 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
750 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
751 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
752 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
754 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
755 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
756 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
759 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
760 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
763 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
765 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
766 withTopColor:topColor bottomColor:bottomColor font:urlFont];
770 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
771 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
772 withTopColor:topColor bottomColor:bottomColor font:labelFont];
774 [dragImage unlockFocus];
779 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
781 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
782 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
784 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
785 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
786 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
788 [_private->draggingImageURL release];
789 _private->draggingImageURL = nil;
791 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
792 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
793 NSImage *dragImage = nil;
796 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
797 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
798 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
800 dragImage = wcDragImage;
801 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
802 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
805 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
807 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
809 _private->dragOffset = wcDragLoc;
812 WebView *webView = [self _webView];
813 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
814 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
815 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
817 // note per kwebster, the offset arg below is always ignored in positioning the image
818 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
820 if (!dhtmlWroteData) {
821 _private->draggingImageURL = [imageURL retain];
822 source = [pasteboard _web_declareAndWriteDragImage:image
823 URL:linkURL ? linkURL : imageURL
824 title:[element objectForKey:WebElementImageAltStringKey]
825 archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
828 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
829 if (dragImage == nil) {
830 [self _web_dragImage:[element objectForKey:WebElementImageKey]
831 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
832 event:_private->mouseDownEvent
833 pasteboard:pasteboard
835 offset:&_private->dragOffset];
837 [self dragImage:dragImage
840 event:_private->mouseDownEvent
841 pasteboard:pasteboard
845 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
846 if (!dhtmlWroteData) {
847 NSArray *types = [NSPasteboard _web_writableTypesForURL];
848 [pasteboard declareTypes:types owner:self];
849 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
851 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
852 if (dragImage == nil) {
853 dragImage = [self _dragImageForLinkElement:element];
854 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
855 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
856 _private->dragOffset.x = offset.width;
857 _private->dragOffset.y = -offset.height; // inverted because we are flipped
859 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
860 // a flash of the image at the mouseDown location when the drag starts.
861 [self dragImage:dragImage
864 event:mouseDraggedEvent
865 pasteboard:pasteboard
868 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
869 if (!dhtmlWroteData) {
870 [self _writeSelectionToPasteboard:pasteboard];
872 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
873 if (dragImage == nil) {
874 dragImage = [[self _bridge] selectionImage];
875 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
876 NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
877 dragLoc = NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect));
878 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
879 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
881 [self dragImage:dragImage
884 event:_private->mouseDownEvent
885 pasteboard:pasteboard
888 } else if (srcIsDHTML) {
889 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
890 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
891 if (dragImage == nil) {
892 // WebCore should have given us an image, but we'll make one up
893 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
894 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
895 NSSize imageSize = [dragImage size];
896 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
897 _private->dragOffset.x = imageSize.width/2;
898 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
900 [self dragImage:dragImage
903 event:_private->mouseDownEvent
904 pasteboard:pasteboard
908 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
909 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
915 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
917 [self autoscroll:event];
918 [self _startAutoscrollTimer:event];
921 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
923 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
924 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
926 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
927 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
928 [[WebPreferences standardPreferences] loadsImagesAutomatically] &&
929 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
933 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
934 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
938 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
939 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
946 - (WebPluginController *)_pluginController
948 return _private->pluginController;
951 - (void)_web_setPrintingModeRecursive
953 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
954 [super _web_setPrintingModeRecursive];
957 - (void)_web_clearPrintingModeRecursive
959 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
960 [super _web_clearPrintingModeRecursive];
963 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
965 ASSERT(!_private->subviewsSetAside);
966 displayRect = NSIntersectionRect(displayRect, [self bounds]);
968 if (!testDirtyRect || [self needsDisplay]) {
970 NSRect dirtyRect = [self _dirtyRect];
971 displayRect = NSIntersectionRect(displayRect, dirtyRect);
973 if (!NSIsEmptyRect(displayRect)) {
974 if ([[self _bridge] needsLayout])
975 _private->needsLayout = YES;
976 if (_private->needsToApplyStyles || _private->needsLayout)
981 [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
984 - (NSRect)_selectionRect
986 return [[self _bridge] selectionRect];
989 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
991 if (_private->autoscrollTimer == nil) {
992 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
993 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
994 _private->autoscrollTriggerEvent = [triggerEvent retain];
998 - (void)_stopAutoscrollTimer
1000 NSTimer *timer = _private->autoscrollTimer;
1001 _private->autoscrollTimer = nil;
1002 [_private->autoscrollTriggerEvent release];
1003 _private->autoscrollTriggerEvent = nil;
1012 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1013 // a mouse up event.
1014 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1016 [self _stopAutoscrollTimer];
1020 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1021 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1022 modifierFlags:[[NSApp currentEvent] modifierFlags]
1023 timestamp:[NSDate timeIntervalSinceReferenceDate]
1024 windowNumber:[[self window] windowNumber]
1025 context:[[NSApp currentEvent] context]
1026 eventNumber:0 clickCount:0 pressure:0];
1027 [self mouseDragged:fakeEvent];
1032 @implementation NSView (WebHTMLViewPrivate)
1034 - (void)_web_setPrintingModeRecursive
1036 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1039 - (void)_web_clearPrintingModeRecursive
1041 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1044 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1046 unsigned index, count;
1047 for (index = 0, count = [_subviews count]; index < count; index++) {
1048 NSView *subview = [_subviews objectAtIndex:index];
1049 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1050 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1056 @implementation NSMutableDictionary (WebHTMLViewPrivate)
1058 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1060 if (object == nil) {
1061 [self removeObjectForKey:key];
1063 [self setObject:object forKey:key];
1069 // The following is a workaround for
1070 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1071 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1072 // Since the category will be searched before the real class, we'll prevent the flag from being
1073 // set on the tool tip panel.
1075 @interface NSToolTipPanel : NSPanel
1078 @interface NSToolTipPanel (WebHTMLViewPrivate)
1081 @implementation NSToolTipPanel (WebHTMLViewPrivate)
1083 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1085 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1091 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1094 @interface NSArray (WebHTMLView)
1095 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1098 @implementation WebHTMLView
1102 WebKitInitializeUnicode();
1103 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes] returnTypes:nil];
1106 - (id)initWithFrame:(NSRect)frame
1108 [super initWithFrame:frame];
1110 // Make all drawing go through us instead of subviews.
1111 // The bulk of the code to handle this is in WebHTMLViewPrivate.m.
1112 if (NSAppKitVersionNumber >= 711) {
1113 [self _setDrawsOwnDescendants:YES];
1116 _private = [[WebHTMLViewPrivate alloc] init];
1118 _private->pluginController = [[WebPluginController alloc] initWithHTMLView:self];
1119 _private->needsLayout = YES;
1126 [self _clearLastHitViewIfSelf];
1128 [[NSNotificationCenter defaultCenter] removeObserver:self];
1129 [_private->pluginController destroyAllPlugins];
1137 [self _clearLastHitViewIfSelf];
1139 [[NSNotificationCenter defaultCenter] removeObserver:self];
1140 [_private->pluginController destroyAllPlugins];
1145 - (IBAction)takeFindStringFromSelection:(id)sender
1147 if (![self _haveSelection]) {
1152 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1155 - (NSArray *)pasteboardTypesForSelection
1157 return [[self class] _selectionPasteboardTypes];
1160 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1162 // Put HTML on the pasteboard.
1163 if ([types containsObject:WebArchivePboardType]) {
1164 WebArchive *archive = [self _selectedArchive];
1165 [pasteboard setData:[archive data] forType:WebArchivePboardType];
1168 // Put attributed string on the pasteboard (RTF format).
1169 NSData *RTFData = nil;
1170 if ([types containsObject:NSRTFPboardType]) {
1171 RTFData = [self _selectedRTFData];
1172 [pasteboard setData:RTFData forType:NSRTFPboardType];
1174 if ([types containsObject:NSRTFDPboardType]) {
1176 RTFData = [self _selectedRTFData];
1178 [pasteboard setData:RTFData forType:NSRTFDPboardType];
1181 // Put plain string on the pasteboard.
1182 if ([types containsObject:NSStringPboardType]) {
1183 // Map to a plain old space because this is better for source code, other browsers do it,
1184 // and because HTML forces you to do this any time you want two spaces in a row.
1185 NSMutableString *s = [[self selectedString] mutableCopy];
1186 const unichar NonBreakingSpaceCharacter = 0xA0;
1187 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1188 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1189 [pasteboard setString:s forType:NSStringPboardType];
1194 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1196 [self _writeSelectionToPasteboard:pasteboard];
1200 - (void)selectAll:(id)sender
1205 - (void)jumpToSelection: sender
1207 [[self _bridge] jumpToSelection];
1210 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1212 SEL action = [item action];
1213 WebBridge *bridge = [self _bridge];
1215 if (action == @selector(cut:)) {
1216 return [bridge mayDHTMLCut] || [self _canDelete];
1217 } else if (action == @selector(copy:)) {
1218 return [bridge mayDHTMLCopy] || [self _haveSelection];
1219 } else if (action == @selector(delete:)) {
1220 return [self _canDelete];
1221 } else if (action == @selector(paste:)) {
1222 return [bridge mayDHTMLPaste] || [self _canPaste];
1223 } else if (action == @selector(takeFindStringFromSelection:)) {
1224 return [self _haveSelection];
1225 } else if (action == @selector(jumpToSelection:)) {
1226 return [self _haveSelection];
1232 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1234 if (sendType && ([[[self class] _selectionPasteboardTypes] containsObject:sendType]) && [self _haveSelection]){
1238 return [super validRequestorForSendType:sendType returnType:returnType];
1241 - (BOOL)acceptsFirstResponder
1243 // Don't accept first responder when we first click on this view.
1244 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1245 // Do accept first responder at any other time, for example from keyboard events,
1246 // or from calls back from WebCore once we begin mouse-down event handling.
1247 NSEvent *event = [NSApp currentEvent];
1248 if ([event type] == NSLeftMouseDown && event != _private->mouseDownEvent &&
1249 NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1255 - (void)updateTextBackgroundColor
1257 NSWindow *window = [self window];
1258 BOOL shouldUseInactiveTextBackgroundColor = !([window isKeyWindow] && [window firstResponder] == self) ||
1259 _private->resigningFirstResponder;
1260 WebBridge *bridge = [self _bridge];
1261 if ([bridge usesInactiveTextBackgroundColor] != shouldUseInactiveTextBackgroundColor) {
1262 [bridge setUsesInactiveTextBackgroundColor:shouldUseInactiveTextBackgroundColor];
1263 [self setNeedsDisplayInRect:[bridge visibleSelectionRect]];
1267 - (void)setCaretVisible:(BOOL)flag
1269 [[self _bridge] setCaretVisible:flag];
1272 - (BOOL)maintainsInactiveSelection
1274 // This method helps to determing whether the view should maintain
1275 // an inactive selection when the view is not first responder.
1276 // Traditionally, these views have not maintained such selections,
1277 // clearing them when the view was not first responder. However,
1278 // to fix bugs like this one:
1279 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
1280 // when they're not firstResponder"
1281 // it was decided to add a switch to act more like an NSTextView.
1282 // For now, however, the view only acts in this way when the
1283 // web view is set to be editable. This will maintain traditional
1284 // behavior for WebKit clients dating back to before this change,
1285 // and will likely be a decent switch for the long term, since
1286 // clients to ste the web view to be editable probably want it
1287 // to act like a "regular" Cocoa view in terms of its selection
1289 if (![[self _webView] isEditable])
1292 id nextResponder = [[self window] _newFirstResponderAfterResigning];
1293 return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1296 - (void)addMouseMovedObserver
1298 if ([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) {
1299 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1300 name:NSMouseMovedNotification object:nil];
1301 [self _frameOrBoundsChanged];
1305 - (void)removeMouseMovedObserver
1307 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1308 [[NSNotificationCenter defaultCenter] removeObserver:self
1309 name:NSMouseMovedNotification object:nil];
1312 - (void)updateShowsFirstResponder
1314 [[self _bridge] setShowsFirstResponder:[[self window] isKeyWindow]];
1317 - (void)addSuperviewObservers
1319 // We watch the bounds of our superview, so that we can do a layout when the size
1320 // of the superview changes. This is different from other scrollable things that don't
1321 // need this kind of thing because their layout doesn't change.
1323 // We need to pay attention to both height and width because our "layout" has to change
1324 // to extend the background the full height of the space and because some elements have
1325 // sizes that are based on the total size of the view.
1327 NSView *superview = [self superview];
1328 if (superview && [self window]) {
1329 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1330 name:NSViewFrameDidChangeNotification object:superview];
1331 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1332 name:NSViewBoundsDidChangeNotification object:superview];
1336 - (void)removeSuperviewObservers
1338 NSView *superview = [self superview];
1339 if (superview && [self window]) {
1340 [[NSNotificationCenter defaultCenter] removeObserver:self
1341 name:NSViewFrameDidChangeNotification object:superview];
1342 [[NSNotificationCenter defaultCenter] removeObserver:self
1343 name:NSViewBoundsDidChangeNotification object:superview];
1347 - (void)addWindowObservers
1349 NSWindow *window = [self window];
1351 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1352 name:NSWindowDidBecomeKeyNotification object:window];
1353 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1354 name:NSWindowDidResignKeyNotification object:window];
1355 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1356 name:NSWindowWillCloseNotification object:window];
1360 - (void)removeWindowObservers
1362 NSWindow *window = [self window];
1364 [[NSNotificationCenter defaultCenter] removeObserver:self
1365 name:NSWindowDidBecomeKeyNotification object:window];
1366 [[NSNotificationCenter defaultCenter] removeObserver:self
1367 name:NSWindowDidResignKeyNotification object:window];
1368 [[NSNotificationCenter defaultCenter] removeObserver:self
1369 name:NSWindowWillCloseNotification object:window];
1373 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1375 [self removeSuperviewObservers];
1378 - (void)viewDidMoveToSuperview
1380 // Do this here in case the text size multiplier changed when a non-HTML
1381 // view was installed.
1382 if ([self superview] != nil) {
1383 [self _updateTextSizeMultiplier];
1384 [self addSuperviewObservers];
1388 - (void)viewWillMoveToWindow:(NSWindow *)window
1390 // Don't do anything if we aren't initialized. This happens
1391 // when decoding a WebView. When WebViews are decoded their subviews
1392 // are created by initWithCoder: and so won't be normally
1393 // initialized. The stub views are discarded by WebView.
1395 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1396 [self removeMouseMovedObserver];
1397 [self removeWindowObservers];
1398 [self removeSuperviewObservers];
1399 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1401 [[self _pluginController] stopAllPlugins];
1405 - (void)viewDidMoveToWindow
1407 // Don't do anything if we aren't initialized. This happens
1408 // when decoding a WebView. When WebViews are decoded their subviews
1409 // are created by initWithCoder: and so won't be normally
1410 // initialized. The stub views are discarded by WebView.
1412 [self _stopAutoscrollTimer];
1413 if ([self window]) {
1414 _private->lastScrollPosition = [[self superview] bounds].origin;
1415 [self addWindowObservers];
1416 [self addSuperviewObservers];
1417 [self addMouseMovedObserver];
1418 [self updateTextBackgroundColor];
1420 [[self _pluginController] startAllPlugins];
1422 _private->lastScrollPosition = NSZeroPoint;
1424 _private->inWindow = YES;
1426 // Reset when we are moved out of a window after being moved into one.
1427 // Without this check, we reset ourselves before we even start.
1428 // This is only needed because viewDidMoveToWindow is called even when
1429 // the window is not changing (bug in AppKit).
1430 if (_private->inWindow) {
1432 _private->inWindow = NO;
1438 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1440 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1443 - (void)viewDidMoveToHostWindow
1445 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1449 - (void)addSubview:(NSView *)view
1451 [super addSubview:view];
1453 if ([[view class] respondsToSelector:@selector(plugInViewWithArguments:)] || [view respondsToSelector:@selector(pluginInitialize)]) {
1454 [[self _pluginController] addPlugin:view];
1458 - (void)reapplyStyles
1460 if (!_private->needsToApplyStyles) {
1465 double start = CFAbsoluteTimeGetCurrent();
1468 [[self _bridge] reapplyStylesForDeviceType:
1469 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1472 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1473 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1476 _private->needsToApplyStyles = NO;
1479 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1480 // minPageWidth==0 implies a non-printing layout
1481 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1483 [self reapplyStyles];
1485 // Ensure that we will receive mouse move events. Is this the best place to put this?
1486 [[self window] setAcceptsMouseMovedEvents: YES];
1487 [[self window] _setShouldPostEventNotifications: YES];
1489 if (!_private->needsLayout) {
1494 double start = CFAbsoluteTimeGetCurrent();
1497 LOG(View, "%@ doing layout", self);
1499 if (minPageWidth > 0.0) {
1500 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1502 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1504 _private->needsLayout = NO;
1506 if (!_private->printing) {
1507 // get size of the containing dynamic scrollview, so
1508 // appearance and disappearance of scrollbars will not show up
1510 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1511 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1512 [[self _bridge] sendResizeEvent];
1514 _private->laidOutAtLeastOnce = YES;
1515 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1516 _private->lastLayoutFrameSize = newLayoutFrameSize;
1520 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1521 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1527 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1530 - (NSMenu *)menuForEvent:(NSEvent *)event
1532 if ([[self _bridge] sendContextMenuEvent:event]) {
1535 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1536 NSDictionary *element = [self elementAtPoint:point];
1537 return [[self _webView] _menuForElement:element];
1540 // Search from the end of the currently selected location, or from the beginning of the
1541 // document if nothing is selected.
1542 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1544 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1547 - (NSString *)string
1549 return [[self attributedString] string];
1552 - (NSAttributedString *)attributedString
1554 WebBridge *b = [self _bridge];
1555 return [b attributedStringFrom:[b DOMDocument]
1561 - (NSString *)selectedString
1563 return [[self _bridge] selectedString];
1566 // Get an attributed string that represents the current selection.
1567 - (NSAttributedString *)selectedAttributedString
1569 return [[self _bridge] selectedAttributedString];
1574 [[self _bridge] selectAll];
1577 // Remove the selection.
1580 [[self _bridge] deselectAll];
1583 - (void)deselectText
1585 [[self _bridge] deselectText];
1590 return [[self _webView] drawsBackground];
1593 - (void)setNeedsDisplay:(BOOL)flag
1595 LOG(View, "%@ flag = %d", self, (int)flag);
1596 [super setNeedsDisplay: flag];
1599 - (void)setNeedsLayout: (BOOL)flag
1601 LOG(View, "%@ flag = %d", self, (int)flag);
1602 _private->needsLayout = flag;
1606 - (void)setNeedsToApplyStyles: (BOOL)flag
1608 LOG(View, "%@ flag = %d", self, (int)flag);
1609 _private->needsToApplyStyles = flag;
1612 - (void)drawRect:(NSRect)rect
1614 LOG(View, "%@ drawing", self);
1616 BOOL subviewsWereSetAside = _private->subviewsSetAside;
1617 if (subviewsWereSetAside) {
1618 [self _restoreSubviews];
1622 double start = CFAbsoluteTimeGetCurrent();
1625 [NSGraphicsContext saveGraphicsState];
1628 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
1630 [(WebClipView *)[self superview] setAdditionalClip:rect];
1633 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
1634 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
1635 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
1636 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
1639 if (![[self _webView] drawsBackground]) {
1640 [[NSColor clearColor] set];
1644 //double start = CFAbsoluteTimeGetCurrent();
1645 [[self _bridge] drawRect:rect];
1646 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
1648 if (textRendererFactoryIfCoalescing != nil) {
1649 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
1652 [(WebClipView *)[self superview] resetAdditionalClip];
1654 [NSGraphicsContext restoreGraphicsState];
1656 [(WebClipView *)[self superview] resetAdditionalClip];
1657 [NSGraphicsContext restoreGraphicsState];
1658 ERROR("Exception caught while drawing: %@", localException);
1659 [localException raise];
1663 NSRect vframe = [self frame];
1664 [[NSColor blackColor] set];
1666 path = [NSBezierPath bezierPath];
1667 [path setLineWidth:(float)0.1];
1668 [path moveToPoint:NSMakePoint(0, 0)];
1669 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
1672 path = [NSBezierPath bezierPath];
1673 [path setLineWidth:(float)0.1];
1674 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
1675 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
1681 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1682 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
1685 if (subviewsWereSetAside) {
1686 [self _setAsideSubviews];
1690 // Turn off the additional clip while computing our visibleRect.
1691 - (NSRect)visibleRect
1693 if (!([[self superview] isKindOfClass:[WebClipView class]]))
1694 return [super visibleRect];
1696 WebClipView *clipView = (WebClipView *)[self superview];
1698 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
1699 if (!hasAdditionalClip) {
1700 return [super visibleRect];
1703 NSRect additionalClip = [clipView additionalClip];
1704 [clipView resetAdditionalClip];
1705 NSRect visibleRect = [super visibleRect];
1706 [clipView setAdditionalClip:additionalClip];
1715 - (void)windowDidBecomeKey:(NSNotification *)notification
1717 ASSERT([notification object] == [self window]);
1718 [self addMouseMovedObserver];
1719 if ([self firstResponderIsSelfOrDescendantView]) {
1720 [self updateTextBackgroundColor];
1721 [self updateShowsFirstResponder];
1725 - (void)windowDidResignKey: (NSNotification *)notification
1727 ASSERT([notification object] == [self window]);
1728 [self removeMouseMovedObserver];
1729 if ([self firstResponderIsSelfOrDescendantView]) {
1730 [self updateTextBackgroundColor];
1731 [self updateShowsFirstResponder];
1735 - (void)windowWillClose:(NSNotification *)notification
1737 [[self _pluginController] destroyAllPlugins];
1740 - (BOOL)acceptsFirstMouse:(NSEvent *)event
1742 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
1743 // the purposes of this method we want to really query the deepest view, so we forward to it.
1744 forceRealHitTest = YES;
1745 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
1746 forceRealHitTest = NO;
1748 if ([hitView isKindOfClass:[self class]]) {
1749 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
1750 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
1751 return [[hitHTMLView _bridge] eventMayStartDrag:event];
1753 return [hitView acceptsFirstMouse:event];
1757 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
1759 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
1760 // the purposes of this method we want to really query the deepest view, so we forward to it.
1761 forceRealHitTest = YES;
1762 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
1763 forceRealHitTest = NO;
1765 if ([hitView isKindOfClass:[self class]]) {
1766 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
1767 return [[hitHTMLView _bridge] eventMayStartDrag:event];
1769 return [hitView shouldDelayWindowOrderingForEvent:event];
1773 - (void)mouseDown:(NSEvent *)event
1775 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
1776 // We don't want to pass them along to KHTML a second time.
1777 if ([event modifierFlags] & NSControlKeyMask) {
1781 _private->ignoringMouseDraggedEvents = NO;
1783 // Record the mouse down position so we can determine drag hysteresis.
1784 [_private->mouseDownEvent release];
1785 _private->mouseDownEvent = [event retain];
1787 // Don't do any mouseover while the mouse is down.
1788 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1790 // Let KHTML get a chance to deal with the event. This will call back to us
1791 // to start the autoscroll timer if appropriate.
1792 [[self _bridge] mouseDown:event];
1795 - (void)dragImage:(NSImage *)dragImage
1797 offset:(NSSize)offset
1798 event:(NSEvent *)event
1799 pasteboard:(NSPasteboard *)pasteboard
1801 slideBack:(BOOL)slideBack
1803 [self _stopAutoscrollTimer];
1805 _private->initiatedDrag = YES;
1806 [[self _webView] _setInitiatedDrag:YES];
1808 // Retain this view during the drag because it may be released before the drag ends.
1811 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
1814 - (void)mouseDragged:(NSEvent *)event
1816 if (!_private->ignoringMouseDraggedEvents) {
1817 [[self _bridge] mouseDragged:event];
1821 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
1823 if (_private->webCoreDragOp == NSDragOperationNone) {
1824 return (NSDragOperationGeneric | NSDragOperationCopy);
1826 return _private->webCoreDragOp;
1830 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
1832 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
1833 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
1834 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
1837 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1839 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
1840 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
1841 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
1843 _private->initiatedDrag = NO;
1844 [[self _webView] _setInitiatedDrag:NO];
1846 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
1847 _private->ignoringMouseDraggedEvents = YES;
1849 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
1850 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
1851 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
1852 location:windowMouseLoc
1853 modifierFlags:[[NSApp currentEvent] modifierFlags]
1854 timestamp:[NSDate timeIntervalSinceReferenceDate]
1855 windowNumber:[[self window] windowNumber]
1856 context:[[NSApp currentEvent] context]
1857 eventNumber:0 clickCount:0 pressure:0];
1858 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
1860 // Balance the previous retain from when the drag started.
1864 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
1866 ASSERT(_private->draggingImageURL);
1868 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
1871 // FIXME: Report an error if we fail to create a file.
1872 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
1873 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
1874 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
1875 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
1878 return [NSArray arrayWithObject:[path lastPathComponent]];
1881 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
1883 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
1884 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
1885 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
1886 if ([types count] == 0) {
1888 } else if ([types count] == 1 &&
1889 [types containsObject:NSFilenamesPboardType] &&
1890 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
1894 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
1895 NSDictionary *element = [self elementAtPoint:point];
1896 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
1897 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
1898 // Can't drag onto the selection being dragged.
1907 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
1909 NSDragOperation operation = NSDragOperationNone;
1911 if (actionMask & WebDragDestinationActionDHTML) {
1912 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
1914 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
1916 if ((actionMask & WebDragDestinationActionEdit) &&
1917 !_private->webCoreHandlingDrag
1918 && [self _canProcessDragWithDraggingInfo:draggingInfo])
1920 WebView *webView = [self _webView];
1921 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
1922 operation = (_private->initiatedDrag && [[self _bridge] isSelectionEditable]) ? NSDragOperationMove : NSDragOperationCopy;
1924 [[self _webView] removeDragCaret];
1930 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
1932 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
1933 [[self _webView] removeDragCaret];
1936 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
1938 WebView *webView = [self _webView];
1939 WebBridge *bridge = [self _bridge];
1940 if (_private->webCoreHandlingDrag) {
1941 ASSERT(actionMask & WebDragDestinationActionDHTML);
1942 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
1943 [bridge concludeDragForDraggingInfo:draggingInfo];
1945 } else if (actionMask & WebDragDestinationActionEdit) {
1946 BOOL didInsert = NO;
1947 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
1948 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:[draggingInfo draggingPasteboard] allowPlainText:YES];
1949 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
1950 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
1951 if (_private->initiatedDrag && [bridge isSelectionEditable]) {
1952 [bridge moveSelectionToDragCaret:fragment];
1954 [bridge setSelectionToDragCaret];
1955 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES];
1960 [webView removeDragCaret];
1966 - (NSDictionary *)elementAtPoint:(NSPoint)point
1968 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
1969 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
1971 // Convert URL strings to NSURLs
1972 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
1973 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
1975 WebFrameView *webFrameView = [self _web_parentWebFrameView];
1976 ASSERT(webFrameView);
1977 WebFrame *webFrame = [webFrameView webFrame];
1980 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
1981 if ([frameName length] == 0) {
1982 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
1984 WebFrame *wf = [webFrame findFrameNamed:frameName];
1986 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
1988 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
1991 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
1994 return [elementInfo autorelease];
1997 - (void)mouseUp:(NSEvent *)event
1999 [self _stopAutoscrollTimer];
2000 [[self _bridge] mouseUp:event];
2001 [self _updateMouseoverWithFakeEvent];
2004 - (void)mouseMovedNotification:(NSNotification *)notification
2006 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2009 - (BOOL)supportsTextEncoding
2014 - (NSView *)nextKeyView
2016 if (_private && _private->nextKeyViewAccessShouldMoveFocus && ![[self _bridge] inNextKeyViewOutsideWebFrameViews]) {
2017 _private->nextKeyViewAccessShouldMoveFocus = NO;
2018 return [[self _bridge] nextKeyView];
2021 return [super nextKeyView];
2024 - (NSView *)previousKeyView
2026 if (_private && _private->nextKeyViewAccessShouldMoveFocus) {
2027 _private->nextKeyViewAccessShouldMoveFocus = NO;
2028 return [[self _bridge] previousKeyView];
2031 return [super previousKeyView];
2034 - (NSView *)nextValidKeyView
2036 if (![self isHiddenOrHasHiddenAncestor]) {
2037 _private->nextKeyViewAccessShouldMoveFocus = YES;
2039 NSView *view = [super nextValidKeyView];
2040 _private->nextKeyViewAccessShouldMoveFocus = NO;
2044 - (NSView *)previousValidKeyView
2046 if (![self isHiddenOrHasHiddenAncestor]) {
2047 _private->nextKeyViewAccessShouldMoveFocus = YES;
2049 NSView *view = [super previousValidKeyView];
2050 _private->nextKeyViewAccessShouldMoveFocus = NO;
2054 - (BOOL)becomeFirstResponder
2057 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2058 switch ([[self window] keyViewSelectionDirection]) {
2059 case NSDirectSelection:
2061 case NSSelectingNext:
2062 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2064 case NSSelectingPrevious:
2065 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2070 [[self window] makeFirstResponder:view];
2072 [self setCaretVisible:YES];
2073 [self updateTextBackgroundColor];
2077 // This approach could be relaxed when dealing with 3228554.
2078 // Some alteration to the selection behavior was done to deal with 3672088.
2079 - (BOOL)resignFirstResponder
2081 BOOL resign = [super resignFirstResponder];
2083 _private->resigningFirstResponder = YES;
2084 if (![self maintainsInactiveSelection]) {
2085 if ([[self _webView] _isPerformingProgrammaticFocus]) {
2086 [self deselectText];
2092 [self setCaretVisible:NO];
2093 [self updateTextBackgroundColor];
2094 _private->resigningFirstResponder = NO;
2099 //------------------------------------------------------------------------------------
2100 // WebDocumentView protocol
2101 //------------------------------------------------------------------------------------
2102 - (void)setDataSource:(WebDataSource *)dataSource
2106 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2110 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2111 // pageWidth != 0 implies we will relayout to a new width
2112 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2114 WebFrame *frame = [self _frame];
2115 NSArray *subframes = [frame childFrames];
2116 unsigned n = [subframes count];
2118 for (i = 0; i != n; ++i) {
2119 WebFrame *subframe = [subframes objectAtIndex:i];
2120 WebFrameView *frameView = [subframe frameView];
2121 if ([[subframe dataSource] _isDocumentHTML]) {
2122 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2126 if (printing != _private->printing) {
2127 [_private->pageRects release];
2128 _private->pageRects = nil;
2129 _private->printing = printing;
2130 [self setNeedsToApplyStyles:YES];
2131 [self setNeedsLayout:YES];
2132 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2134 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2136 // Can't do this when starting printing or nested printing won't work, see 3491427.
2137 [self setNeedsDisplay:NO];
2142 // This is needed for the case where the webview is embedded in the view that's being printed.
2143 // It shouldn't be called when the webview is being printed directly.
2144 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2146 // This helps when we print as part of a larger print process.
2147 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2148 BOOL wasInPrintingMode = _private->printing;
2149 if (!wasInPrintingMode) {
2150 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2153 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2155 if (!wasInPrintingMode) {
2156 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2160 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2162 NSPrintInfo *printInfo = [printOperation printInfo];
2163 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2166 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2168 float viewWidth = NSWidth([self bounds]);
2169 if (viewWidth < 1) {
2170 ERROR("%@ has no width when printing", self);
2174 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2175 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2176 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2177 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2180 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2181 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2182 // if AppKit makes it SPI/API.
2183 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2185 return [self _scaleFactorForPrintOperation:printOperation];
2188 - (void)setPageWidthForPrinting:(float)pageWidth
2190 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2191 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2195 // Return the number of pages available for printing
2196 - (BOOL)knowsPageRange:(NSRangePointer)range {
2197 // Must do this explicit display here, because otherwise the view might redisplay while the print
2198 // sheet was up, using printer fonts (and looking different).
2199 [self displayIfNeeded];
2200 [[self window] setAutodisplay:NO];
2202 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2203 // according to the paper size
2204 float minLayoutWidth = 0.0;
2205 float maxLayoutWidth = 0.0;
2206 if (![[self _bridge] isFrameSet]) {
2207 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2208 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2209 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2211 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2213 // There is a theoretical chance that someone could do some drawing between here and endDocument,
2214 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2215 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2217 range->location = 1;
2218 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2219 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2220 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2221 [_private->pageRects release];
2222 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2223 printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2224 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2225 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2226 // a blank page (with correct-looking header and footer if that option is on), which matches
2227 // the behavior of IE and Camino at least.
2228 if ([newPageRects count] == 0) {
2229 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2231 _private->pageRects = [newPageRects retain];
2233 range->length = [_private->pageRects count];
2238 // Return the drawing rectangle for a particular page number
2239 - (NSRect)rectForPage:(int)page {
2240 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2243 // Calculate the vertical size of the view that fits on a single page
2244 - (float)_calculatePrintHeight {
2245 // Obtain the print info object for the current operation
2246 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
2248 // Calculate the page height in points
2249 NSSize paperSize = [pi paperSize];
2250 return paperSize.height - [pi topMargin] - [pi bottomMargin];
2253 - (void)drawPageBorderWithSize:(NSSize)borderSize
2255 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
2256 [[self _webView] _drawHeaderAndFooter];
2261 [super endDocument];
2262 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
2263 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2264 [[self window] setAutodisplay:YES];
2267 - (void)_updateTextSizeMultiplier
2269 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
2272 - (BOOL)performKeyEquivalent:(NSEvent *)event
2274 // Pass command-key combos through WebCore if there is a key binding available for
2275 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
2276 if ([self firstResponderIsSelfOrDescendantView] && [event _web_keyBindingManagerHasBinding]) {
2277 [[self _bridge] interceptKeyEvent:event toView:self];
2280 return [super performKeyEquivalent:event];
2283 - (void)keyDown:(NSEvent *)event
2285 BOOL intercepted = [[self _bridge] interceptKeyEvent:event toView:self];
2286 if (!intercepted || [event _web_isTabKeyEvent]) {
2287 [super keyDown:event];
2291 - (void)keyUp:(NSEvent *)event
2293 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2294 [super keyUp:event];
2298 - (id)accessibilityAttributeValue:(NSString*)attributeName
2300 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2301 id accTree = [[self _bridge] accessibilityTree];
2303 return [NSArray arrayWithObject: accTree];
2306 return [super accessibilityAttributeValue:attributeName];
2309 - (id)accessibilityHitTest:(NSPoint)point
2311 id accTree = [[self _bridge] accessibilityTree];
2313 NSPoint windowCoord = [[self window] convertScreenToBase: point];
2314 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2320 - (void)centerSelectionInVisibleArea:(id)sender
2322 // FIXME: Does this do the right thing when the selection is not a caret?
2323 [[self _bridge] ensureCaretVisible];
2326 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2328 WebBridge *bridge = [self _bridge];
2329 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2330 WebView *webView = [self _webView];
2331 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[bridge selectedDOMRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2332 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2336 - (void)moveBackward:(id)sender
2338 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2341 - (void)moveBackwardAndModifySelection:(id)sender
2343 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2346 - (void)moveDown:(id)sender
2348 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2351 - (void)moveDownAndModifySelection:(id)sender
2353 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2356 - (void)moveForward:(id)sender
2358 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2361 - (void)moveForwardAndModifySelection:(id)sender
2363 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2366 - (void)moveLeft:(id)sender
2368 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2371 - (void)moveLeftAndModifySelection:(id)sender
2373 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2376 - (void)moveRight:(id)sender
2378 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2381 - (void)moveRightAndModifySelection:(id)sender
2383 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2386 - (void)moveToBeginningOfDocument:(id)sender
2388 ERROR("unimplemented");
2391 - (void)moveToBeginningOfLine:(id)sender
2393 ERROR("unimplemented");
2396 - (void)moveToBeginningOfParagraph:(id)sender
2398 ERROR("unimplemented");
2401 - (void)moveToEndOfDocument:(id)sender
2403 ERROR("unimplemented");
2406 - (void)moveToEndOfLine:(id)sender
2408 ERROR("unimplemented");
2411 - (void)moveToEndOfParagraph:(id)sender
2413 ERROR("unimplemented");
2416 - (void)moveUp:(id)sender
2418 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
2421 - (void)moveUpAndModifySelection:(id)sender
2423 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
2426 - (void)moveWordBackward:(id)sender
2428 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
2431 - (void)moveWordBackwardAndModifySelection:(id)sender
2433 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
2436 - (void)moveWordForward:(id)sender
2438 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
2441 - (void)moveWordForwardAndModifySelection:(id)sender
2443 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
2446 - (void)moveWordLeft:(id)sender
2448 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
2451 - (void)moveWordLeftAndModifySelection:(id)sender
2453 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
2456 - (void)moveWordRight:(id)sender
2458 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
2461 - (void)moveWordRightAndModifySelection:(id)sender
2463 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
2466 - (void)pageDown:(id)sender
2468 ERROR("unimplemented");
2471 - (void)pageUp:(id)sender
2473 ERROR("unimplemented");
2476 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
2478 WebBridge *bridge = [self _bridge];
2479 DOMRange *range = [bridge selectedDOMRangeWithGranularity:granularity];
2480 if (range && ![range collapsed]) {
2481 WebView *webView = [self _webView];
2482 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[bridge selectedDOMRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2483 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
2488 - (void)selectParagraph:(id)sender
2490 [self _expandSelectionToGranularity:WebSelectByParagraph];
2493 - (void)selectLine:(id)sender
2495 [self _expandSelectionToGranularity:WebSelectByLine];
2498 - (void)selectWord:(id)sender
2500 [self _expandSelectionToGranularity:WebSelectByWord];
2503 - (void)copy:(id)sender
2505 if ([[self _bridge] tryDHTMLCopy]) {
2506 return; // DHTML did the whole operation
2509 if (![self _haveSelection]) {
2513 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
2516 - (void)cut:(id)sender
2518 if ([[self _bridge] tryDHTMLCut]) {
2519 return; // DHTML did the whole operation
2522 if (![self _haveSelection]) {
2527 [[self _bridge] deleteSelection];
2530 - (void)delete:(id)sender
2532 if (![self _haveSelection]) {
2536 [[self _bridge] deleteSelection];
2539 - (void)paste:(id)sender
2541 if ([[self _bridge] tryDHTMLPaste]) {
2542 return; // DHTML did the whole operation
2545 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
2548 - (void)copyFont:(id)sender
2550 ERROR("unimplemented");
2553 - (void)pasteFont:(id)sender
2555 ERROR("unimplemented");
2558 - (void)pasteAsPlainText:(id)sender
2560 NSString *text = [[NSPasteboard generalPasteboard] stringForType:NSStringPboardType];
2561 WebView *webView = [self _webView];
2562 WebBridge *bridge = [self _bridge];
2563 if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
2564 [bridge replaceSelectionWithText:text selectReplacement:NO];
2568 - (void)pasteAsRichText:(id)sender
2570 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
2573 - (DOMCSSStyleDeclaration *)_fontManagerOperationAsStyle
2575 WebBridge *bridge = [self _bridge];
2576 DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2578 NSFontManager *fm = [NSFontManager sharedFontManager];
2580 NSFont *a = [fm convertFont:[fm fontWithFamily:@"Helvetica" traits:0 weight:5 size:10]];
2581 NSFont *b = [fm convertFont:[fm fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12]];
2583 NSString *fa = [a familyName];
2584 NSString *fb = [b familyName];
2585 if ([fa isEqualToString:fb]) {
2586 [style setFontFamily:fa];
2589 int sa = [a pointSize];
2590 int sb = [b pointSize];
2592 [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
2595 int wa = [fm weightOfFont:a];
2596 int wb = [fm weightOfFont:b];
2599 [style setFontWeight:@"bold"];
2601 [style setFontWeight:@"normal"];
2605 BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
2606 BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
2609 [style setFontStyle:@"italic"];
2611 [style setFontStyle:@"normal"];
2618 - (void)changeFont:(id)sender
2620 DOMCSSStyleDeclaration *style = [self _fontManagerOperationAsStyle];
2621 WebView *webView = [self _webView];
2622 WebBridge *bridge = [self _bridge];
2623 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2624 [bridge applyStyle:style];
2628 - (void)changeAttributes:(id)sender
2630 ERROR("unimplemented");
2633 - (DOMCSSStyleDeclaration *)_colorPanelColorAsStyleUsingSelector:(SEL)selector
2635 WebBridge *bridge = [self _bridge];
2636 DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2637 NSColor *color = [[NSColorPanel sharedColorPanel] color];
2638 NSString *colorAsString = [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", [color redComponent]*255, [color greenComponent]*255, [color blueComponent]*255];
2639 ASSERT([style respondsToSelector:selector]);
2640 [style performSelector:selector withObject:colorAsString];
2645 - (void)_changeCSSColorUsingSelector:(SEL)selector inRange:(DOMRange *)range
2647 DOMCSSStyleDeclaration *style = [self _colorPanelColorAsStyleUsingSelector:selector];
2648 WebView *webView = [self _webView];
2649 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:range]) {
2650 [[self _bridge] applyStyle:style];
2654 - (DOMRange *)_entireDOMRange
2656 DOMDocument *document = [[self _bridge] DOMDocument];
2657 DOMRange *range = [document createRange];
2658 [range selectNode:[document documentElement]];
2662 - (void)changeDocumentBackgroundColor:(id)sender
2664 // Mimicking NSTextView, this method sets the background color for the
2665 // entire document. There is no NSTextView API for setting the background
2666 // color on the selected range only. Note that this method is currently
2667 // never called from the UI (see comment in changeColor:).
2668 // FIXME: this actually has no effect when called, probably due to 3654850. _entireDOMRange seems
2669 // to do the right thing because it works in startSpeaking:, and I know setBackgroundColor: does the
2670 // right thing because I tested it with [[self _bridge] selectedDOMRange].
2671 // FIXME: This won't actually apply the style to the entire range here, because it ends up calling
2672 // [bridge applyStyle:], which operates on the current selection. To make this work right, we'll
2673 // need to save off the selection, temporarily set it to the entire range, make the change, then
2674 // restore the old selection.
2675 [self _changeCSSColorUsingSelector:@selector(setBackgroundColor:) inRange:[self _entireDOMRange]];
2678 - (void)changeColor:(id)sender
2680 // FIXME: in NSTextView, this method calls changeDocumentBackgroundColor: when a
2681 // private call has earlier been made by [NSFontFontEffectsBox changeColor:], see 3674493.
2682 // AppKit will have to be revised to allow this to work with anything that isn't an
2683 // NSTextView. However, this might not be required for Tiger, since the background-color
2684 // changing box in the font panel doesn't work in Mail (3674481), though it does in TextEdit.
2685 [self _changeCSSColorUsingSelector:@selector(setColor:) inRange:[[self _bridge] selectedDOMRange]];
2688 - (void)_alignSelectionUsingCSSValue:(NSString *)CSSAlignmentValue
2690 // FIXME 3675191: This doesn't work yet. Maybe it's blocked by 3654850, or maybe something other than
2691 // just applyStyle: needs to be called for block-level attributes like this.
2692 WebBridge *bridge = [self _bridge];
2693 DOMCSSStyleDeclaration *style = [[bridge DOMDocument] createCSSStyleDeclaration];
2694 [style setTextAlign:CSSAlignmentValue];
2695 WebView *webView = [self _webView];
2696 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2697 [[self _bridge] applyStyle:style];
2701 - (void)alignCenter:(id)sender
2703 [self _alignSelectionUsingCSSValue:@"center"];
2706 - (void)alignJustified:(id)sender
2708 [self _alignSelectionUsingCSSValue:@"justify"];
2711 - (void)alignLeft:(id)sender
2713 [self _alignSelectionUsingCSSValue:@"left"];
2716 - (void)alignRight:(id)sender
2718 [self _alignSelectionUsingCSSValue:@"right"];
2721 - (void)indent:(id)sender
2723 ERROR("unimplemented");
2726 - (void)insertTab:(id)sender
2728 WebView *webView = [self _webView];
2729 WebBridge *bridge = [self _bridge];
2730 if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:@"\t" replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionPasted]) {
2731 [bridge insertText:@"\t"];
2735 - (void)insertBacktab:(id)sender
2737 // Doing nothing matches normal NSTextView behavior. If we ever use WebView for a field-editor-type purpose
2738 // we might add code here.
2741 - (void)insertNewline:(id)sender
2743 // Perhaps we should make this delegate call sensitive to the real DOM operation we actually do.
2744 WebView *webView = [self _webView];
2745 WebBridge *bridge = [self _bridge];
2746 if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:@"\n" replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
2747 [bridge insertNewline];
2751 - (void)insertParagraphSeparator:(id)sender
2753 // FIXME: Should this do something different?
2754 [self insertNewline:sender];
2757 - (void)changeCaseOfLetter:(id)sender
2759 ERROR("unimplemented");
2762 - (void)_changeWordCaseWithSelector:(SEL)selector
2764 WebView *webView = [self _webView];
2765 WebBridge *bridge = [self _bridge];
2766 [self selectWord:nil];
2767 NSString *word = [[bridge selectedString] performSelector:selector];
2768 // FIXME: Does this need a different action context other than "typed"?
2769 if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:word replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
2770 [bridge replaceSelectionWithText:word selectReplacement:NO];
2774 - (void)uppercaseWord:(id)sender
2776 [self _changeWordCaseWithSelector:@selector(uppercaseString)];
2779 - (void)lowercaseWord:(id)sender
2781 [self _changeWordCaseWithSelector:@selector(lowercaseString)];
2784 - (void)capitalizeWord:(id)sender
2786 [self _changeWordCaseWithSelector:@selector(capitalizedString)];
2789 - (void)deleteForward:(id)sender
2791 ERROR("unimplemented");
2794 - (void)deleteBackward:(id)sender
2796 WebBridge *bridge = [self _bridge];
2797 if ([bridge isSelectionEditable]) {
2798 WebView *webView = [self _webView];
2799 if ([[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:[bridge selectedDOMRange]]) {
2800 [bridge deleteKeyPressed];
2805 - (void)deleteBackwardByDecomposingPreviousCharacter:(id)sender
2807 ERROR("unimplemented");
2810 - (void)deleteWordForward:(id)sender
2812 [self moveWordForwardAndModifySelection:sender];
2813 [self delete:sender];
2816 - (void)deleteWordBackward:(id)sender
2818 [self moveWordBackwardAndModifySelection:sender];
2819 [self delete:sender];
2822 - (void)deleteToBeginningOfLine:(id)sender
2824 [self moveToBeginningOfLine:sender];
2825 [self delete:sender];
2828 - (void)deleteToEndOfLine:(id)sender
2830 [self moveToEndOfLine:sender];
2831 [self delete:sender];
2834 - (void)deleteToBeginningOfParagraph:(id)sender
2836 [self moveToBeginningOfParagraph:sender];
2837 [self delete:sender];
2840 - (void)deleteToEndOfParagraph:(id)sender
2842 [self moveToEndOfParagraph:sender];
2843 [self delete:sender];
2846 - (void)complete:(id)sender
2848 ERROR("unimplemented");
2851 - (void)checkSpelling:(id)sender
2854 NSTextStorage *text = _getTextStorage(self);
2855 NSTextViewSharedData *sharedData = _getSharedData(self);
2856 if (text && ([text length] > 0) && [self isSelectable]) {
2857 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2858 NSRange selCharRange = [self selectedRange];
2859 NSRange misspellCharRange = {0, 0}, grammarCharRange = {0, 0};
2861 NSArray *grammarRanges = nil, *grammarDescriptions = nil;
2863 if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
2865 misspellCharRange = [checker checkSpellingOfString:[text string] startingAt:NSMaxRange(selCharRange) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] wordCount:NULL];
2866 #if GRAMMAR_CHECKING
2867 grammarCharRange = [checker checkGrammarOfString:[text string] startingAt:NSMaxRange(selCharRange) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] ranges:&grammarRanges descriptions:&grammarDescriptions reconnectOnError:YES];
2870 if (misspellCharRange.length > 0 && (grammarCharRange.length == 0 || misspellCharRange.location <= grammarCharRange.location)) {
2871 // select the text and drive the panel
2872 [self setSelectedRange:misspellCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2873 if ([self isEditable]) {
2874 [self _addSpellingAttributeForRange:misspellCharRange];
2875 sharedData->_excludedSpellingCharRange = misspellCharRange;
2877 [self scrollRangeToVisible:misspellCharRange];
2878 [checker updateSpellingPanelWithMisspelledWord:[[text string] substringWithRange:misspellCharRange]];
2879 } else if (grammarCharRange.length > 0) {
2880 [self setSelectedRange:grammarCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2881 count = [grammarRanges count];
2882 if ([self isEditable]) {
2883 for (i = 0; i < count; i++) {
2884 NSRange range = [grammarRanges rangeAtIndex:i];
2885 range.location += grammarCharRange.location;
2886 [self _addSpellingAttributeForRange:range];
2887 [_getLayoutManager(self) addTemporaryAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[grammarDescriptions objectAtIndex:i], NSToolTipAttributeName, nil] forCharacterRange:range];
2890 [self scrollRangeToVisible:grammarCharRange];
2892 // Cause the beep to indicate there are no more misspellings.
2893 [checker updateSpellingPanelWithMisspelledWord:@""];
2899 - (void)showGuessPanel:(id)sender
2902 NSTextStorage *text = _getTextStorage(self);
2903 NSTextViewSharedData *sharedData = _getSharedData(self);
2904 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2905 if (text && ([text length] > 0) && [self isSelectable]) {
2906 NSRange selCharRange = [self selectedRange];
2907 NSRange misspellCharRange = {0, 0};
2908 if (checker && ![checker windowIsSpellingPanel:[self window]]) {
2909 misspellCharRange = [checker checkSpellingOfString:[text string] startingAt:((selCharRange.location > 0) ? (selCharRange.location - 1) : 0) language:nil wrap:YES inSpellDocumentWithTag:[self spellCheckerDocumentTag] wordCount:NULL];
2910 if (misspellCharRange.length) {
2911 // select the text and drive the panel
2912 [self setSelectedRange:misspellCharRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2913 if ([self isEditable]) {
2914 [self _addSpellingAttributeForRange:misspellCharRange];
2915 sharedData->_excludedSpellingCharRange = misspellCharRange;
2917 [self scrollRangeToVisible:misspellCharRange];
2918 [checker updateSpellingPanelWithMisspelledWord:[[text string] substringWithRange:misspellCharRange]];
2923 [[checker spellingPanel] orderFront:sender];
2930 - (void)_changeSpellingToWord:(NSString *)newWord {
2931 NSRange charRange = [self rangeForUserTextChange];
2932 if ([self isEditable] && charRange.location != NSNotFound) {
2933 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2934 if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
2936 // Don't correct to empty string.
2937 if ([newWord isEqualToString:@""]) return;
2939 if ([self shouldChangeTextInRange:charRange replacementString:newWord]) {
2940 [self replaceCharactersInRange:charRange withString:newWord];
2941 charRange.length = [newWord length];
2942 [self setSelectedRange:charRange affinity:NSSelectionAffinityUpstream stillSelecting:NO];
2943 [self didChangeText];
2948 - (void)_changeSpellingFromMenu:(id)sender {
2949 [self _changeSpellingToWord:[sender title]];
2952 - (void)changeSpelling:(id)sender {
2953 [self _changeSpellingToWord:[[sender selectedCell] stringValue]];
2956 - (void)ignoreSpelling:(id)sender {
2957 NSRange charRange = [self rangeForUserTextChange];
2958 if ([self isEditable]) {
2959 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2960 NSString *stringToIgnore;
2961 unsigned int length;
2963 if (!checker) return;
2965 stringToIgnore = [sender stringValue];
2966 length = [stringToIgnore length];
2967 if (stringToIgnore && length > 0) {
2968 [checker ignoreWord:stringToIgnore inSpellDocumentWithTag:[self spellCheckerDocumentTag]];
2969 if (length == charRange.length && [stringToIgnore isEqualToString:[[_getTextStorage(self) string] substringWithRange:charRange]]) {
2970 [self _removeSpellingAttributeForRange:charRange];
2976 - (void)_ignoreSpellingFromMenu:(id)sender {
2977 NSRange charRange = [self rangeForUserTextChange];
2978 if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
2979 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2980 if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
2981 [self _removeSpellingAttributeForRange:charRange];
2982 [checker ignoreWord:[[_getTextStorage(self) string] substringWithRange:charRange] inSpellDocumentWithTag:[self spellCheckerDocumentTag]];
2986 - (void)_learnSpellingFromMenu:(id)sender {
2987 NSRange charRange = [self rangeForUserTextChange];
2988 if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
2989 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
2990 if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
2991 [self _removeSpellingAttributeForRange:charRange];
2992 [checker learnWord:[[_getTextStorage(self) string] substringWithRange:charRange]];
2996 - (void)_forgetSpellingFromMenu:(id)sender {
2997 NSRange charRange = [self rangeForUserTextChange];
2998 if ([self isEditable] && charRange.location != NSNotFound && charRange.length > 0) {
2999 NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker];
3000 if (!checker || [checker windowIsSpellingPanel:[self window]]) return;
3001 [checker forgetWord:[[_getTextStorage(self) string] substringWithRange:charRange]];
3005 - (void)_openLinkFromMenu:(id)sender {
3006 NSTextStorage *text = _getTextStorage(self);
3007 NSRange charRange = [self selectedRange];
3008 if (charRange.location != NSNotFound && charRange.length > 0) {
3009 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
3011 [self clickedOnLink:link atIndex:charRange.location];
3013 NSString *string = [[text string] substringWithRange:charRange];
3014 link = [NSURL URLWithString:string];
3015 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
3022 - (void)performFindPanelAction:(id)sender
3024 ERROR("unimplemented");
3027 - (void)startSpeaking:(id)sender
3029 WebBridge *bridge = [self _bridge];
3030 DOMRange *range = [bridge selectedDOMRange];
3031 if (!range || [range collapsed]) {
3032 range = [self _entireDOMRange];
3034 [NSApp speakString:[bridge stringForRange:range]];
3037 - (void)stopSpeaking:(id)sender
3039 [NSApp stopSpeaking:sender];
3042 - (void)insertText:(NSString *)text
3044 WebBridge *bridge = [self _bridge];
3045 if ([bridge isSelectionEditable]) {
3046 WebView *webView = [self _webView];
3047 if ([[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:[bridge selectedDOMRange] givenAction:WebViewInsertActionTyped]) {
3048 [bridge insertText:text];
3055 @implementation WebHTMLView (WebTextSizing)
3057 - (void)_web_textSizeMultiplierChanged
3059 [self _updateTextSizeMultiplier];
3064 @implementation NSArray (WebHTMLView)
3066 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object
3068 NSEnumerator *enumerator = [self objectEnumerator];
3069 WebNetscapePluginEmbeddedView *view;
3070 while ((view = [enumerator nextObject]) != nil) {
3071 if ([view isKindOfClass:[WebNetscapePluginEmbeddedView class]]) {
3072 [view performSelector:selector withObject:object];
3079 @implementation WebElementOrTextFilter
3081 + (WebElementOrTextFilter *)filter
3083 if (!elementOrTextFilterInstance)
3084 elementOrTextFilterInstance = [[WebElementOrTextFilter alloc] init];
3085 return elementOrTextFilterInstance;
3088 - (short)acceptNode:(DOMNode *)n
3090 return ([n isKindOfClass:[DOMElement class]] || [n isKindOfClass:[DOMText class]]) ? DOM_FILTER_ACCEPT : DOM_FILTER_SKIP;
3095 @implementation WebHTMLView (WebInternal)
3097 - (void)_updateFontPanel
3099 // FIXME: NSTextView bails out if becoming or resigning first responder, for which it has ivar flags. Not
3100 // sure if we need to do something similar.
3102 WebBridge *bridge = [self _bridge];
3104 if (![bridge isSelectionEditable]) {
3108 NSWindow *window = [self window];
3109 // FIXME: is this first-responder check correct? What happens if a subframe is editable and is first responder?
3110 if ([NSApp keyWindow] != window || [window firstResponder] != self) {
3114 BOOL onlyOneFontInSelection = YES;
3117 if (![bridge haveSelection]) {
3118 font = [bridge fontForCurrentPosition];
3121 DOMRange *selection = [bridge selectedDOMRange];
3122 DOMNode *startContainer = [selection startContainer];
3123 DOMNode *endContainer = [selection endContainer];
3125 ASSERT(startContainer);
3126 ASSERT(endContainer);
3127 ASSERT([[WebElementOrTextFilter filter] acceptNode:startContainer] == DOM_FILTER_ACCEPT);
3128 ASSERT([[WebElementOrTextFilter filter] acceptNode:endContainer] == DOM_FILTER_ACCEPT);
3130 font = [bridge renderedFontForNode:startContainer];
3132 if (startContainer != endContainer) {
3133 DOMDocument *document = [bridge DOMDocument];
3134 DOMTreeWalker *treeWalker = [document createTreeWalker:document :DOM_SHOW_ALL :[WebElementOrTextFilter filter] :NO];
3135 DOMNode *node = startContainer;
3136 [treeWalker setCurrentNode:node];
3138 NSFont *otherFont = [bridge renderedFontForNode:node];
3139 if (![font isEqual:otherFont]) {
3140 onlyOneFontInSelection = NO;
3143 if (node == endContainer)
3145 node = [treeWalker nextNode];
3150 // FIXME: for now, return a bogus font that distinguishes the empty selection from the non-empty
3151 // selection. We should be able to remove this once the rest of this code works properly.
3153 if (![bridge haveSelection]) {
3154 font = [NSFont toolTipsFontOfSize:17];
3156 font = [NSFont menuFontOfSize:23];
3159 ASSERT(font != nil);
3161 NSFontManager *fm = [NSFontManager sharedFontManager];
3162 [fm setSelectedFont:font isMultiple:!onlyOneFontInSelection];
3163 // FIXME: we don't keep track of selected attributes, or set them on the font panel. This
3164 // appears to have no effect on the UI. E.g., underlined text in Mail or TextEdit is
3165 // not reflected in the font panel. Maybe someday this will change.
3168 - (unsigned int)_delegateDragSourceActionMask
3170 WebView *webView = [self _webView];
3171 NSPoint point = [webView convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
3172 _private->dragSourceActionMask = [[webView _UIDelegateForwarder] webView:webView dragSourceActionMaskForPoint:point];
3173 return _private->dragSourceActionMask;