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/WebDOMOperationsPrivate.h>
17 #import <WebKit/WebEditingDelegate.h>
18 #import <WebKit/WebException.h>
19 #import <WebKit/WebFramePrivate.h>
20 #import <WebKit/WebFrameViewInternal.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/WebPreferencesPrivate.h>
38 #import <WebKit/WebResourcePrivate.h>
39 #import <WebKit/WebStringTruncator.h>
40 #import <WebKit/WebTextRenderer.h>
41 #import <WebKit/WebTextRendererFactory.h>
42 #import <WebKit/WebUIDelegatePrivate.h>
43 #import <WebKit/WebUnicode.h>
44 #import <WebKit/WebViewInternal.h>
45 #import <WebKit/WebViewPrivate.h>
47 #import <AppKit/NSAccessibility.h>
48 #import <AppKit/NSGraphicsContextPrivate.h>
49 #import <AppKit/NSResponder_Private.h>
51 #import <Foundation/NSFileManager_NSURLExtras.h>
52 #import <Foundation/NSURL_NSURLExtras.h>
53 #import <Foundation/NSURLFileTypeMappings.h>
55 #import <CoreGraphics/CGContextGState.h>
57 // Included to help work around this bug:
58 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
59 #import <AppKit/NSKeyBindingManager.h>
61 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
62 void _NSInitializeKillRing(void);
63 void _NSAppendToKillRing(NSString *);
64 void _NSPrependToKillRing(NSString *);
65 NSString *_NSYankFromKillRing(void);
66 NSString *_NSYankPreviousFromKillRing(void);
67 void _NSNewKillRingSequence(void);
68 void _NSSetKillRingToYankedState(void);
69 void _NSResetKillRingOperationFlag(void);
71 @interface NSView (AppKitSecretsIKnowAbout)
72 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
73 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
75 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
78 @interface NSApplication (AppKitSecretsIKnowAbout)
79 - (void)speakString:(NSString *)string;
82 @interface NSWindow (AppKitSecretsIKnowAbout)
83 - (id)_newFirstResponderAfterResigning;
86 @interface NSAttributedString (AppKitSecretsIKnowAbout)
87 - (id)_initWithDOMRange:(DOMRange *)domRange;
88 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
91 @interface NSSpellChecker (CurrentlyPrivateForTextView)
92 - (void)learnWord:(NSString *)word;
95 // By imaging to a width a little wider than the available pixels,
96 // thin pages will be scaled down a little, matching the way they
97 // print in IE and Camino. This lets them use fewer sheets than they
98 // would otherwise, which is presumably why other browsers do this.
99 // Wide pages will be scaled down more than this.
100 #define PrintingMinimumShrinkFactor 1.25
102 // This number determines how small we are willing to reduce the page content
103 // in order to accommodate the widest line. If the page would have to be
104 // reduced smaller to make the widest line fit, we just clip instead (this
105 // behavior matches MacIE and Mozilla, at least)
106 #define PrintingMaximumShrinkFactor 2.0
108 #define AUTOSCROLL_INTERVAL 0.1
110 #define DRAG_LABEL_BORDER_X 4.0
111 #define DRAG_LABEL_BORDER_Y 2.0
112 #define DRAG_LABEL_RADIUS 5.0
113 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
115 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
116 #define MAX_DRAG_LABEL_WIDTH 320.0
118 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
119 #define DRAG_LINK_URL_FONT_SIZE 10.0
121 #ifndef OMIT_TIGER_FEATURES
122 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
125 // Any non-zero value will do, but using something recognizable might help us debug some day.
126 #define TRACKING_RECT_TAG 0xBADFACE
128 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
129 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
131 static BOOL forceRealHitTest = NO;
133 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
136 @interface WebHTMLView (WebHTMLViewFileInternal)
137 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
138 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
139 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
140 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
141 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
142 - (float)_calculatePrintHeight;
143 - (void)_updateTextSizeMultiplier;
144 - (DOMRange *)_selectedRange;
145 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
146 - (void)_deleteRange:(DOMRange *)range
147 preflight:(BOOL)preflight
148 killRing:(BOOL)killRing
149 prepend:(BOOL)prepend
150 smartDeleteOK:(BOOL)smartDeleteOK;
151 - (void)_deleteSelection;
152 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
155 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
156 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
159 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
160 - (void)_updateSelectionForInputManager;
161 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
164 @interface WebHTMLView (WebEditingStyleSupport)
165 - (DOMCSSStyleDeclaration *)_emptyStyle;
166 - (NSString *)_colorAsString:(NSColor *)color;
169 @interface NSView (WebHTMLViewFileInternal)
170 - (void)_web_setPrintingModeRecursive;
171 - (void)_web_clearPrintingModeRecursive;
172 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
175 @interface NSMutableDictionary (WebHTMLViewFileInternal)
176 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
179 // Handles the complete: text command
180 @interface WebTextCompleteController : NSObject
184 NSWindow *_popupWindow;
185 NSTableView *_tableView;
186 NSArray *_completions;
187 NSString *_originalString;
190 - (id)initWithHTMLView:(WebHTMLView *)view;
191 - (void)doCompletion;
192 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
193 - (BOOL)filterKeyDown:(NSEvent *)event;
194 - (void)_reflectSelection;
197 @implementation WebHTMLViewPrivate
201 ASSERT(autoscrollTimer == nil);
202 ASSERT(autoscrollTriggerEvent == nil);
204 [mouseDownEvent release];
205 [draggingImageURL release];
206 [pluginController release];
208 [compController release];
209 [firstResponderAtMouseDownTime release];
216 @implementation WebHTMLView (WebHTMLViewFileInternal)
218 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
220 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
221 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
222 NSEnumerator *enumerator = [paths objectEnumerator];
225 while ((path = [enumerator nextObject]) != nil) {
226 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
227 if ([imageMIMETypes containsObject:MIMEType]) {
235 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
237 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
238 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
239 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
240 NSEnumerator *enumerator = [paths objectEnumerator];
241 WebDataSource *dataSource = [self _dataSource];
244 while ((path = [enumerator nextObject]) != nil) {
245 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
246 if ([imageMIMETypes containsObject:MIMEType]) {
247 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
248 URL:[NSURL fileURLWithPath:path]
253 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
259 return [fragment firstChild] != nil ? fragment : nil;
262 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
264 NSArray *types = [pasteboard types];
266 if ([types containsObject:WebArchivePboardType]) {
267 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
269 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
277 if ([types containsObject:NSFilenamesPboardType]) {
278 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
279 if (fragment != nil) {
286 if ([types containsObject:NSHTMLPboardType]) {
287 NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
288 // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
289 if ([HTMLString hasPrefix:@"Version:"]) {
290 NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
291 if (range.location != NSNotFound) {
292 HTMLString = [HTMLString substringFromIndex:range.location];
295 if ([HTMLString length] != 0) {
296 return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
300 if ([types containsObject:NSTIFFPboardType]) {
301 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
302 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
303 MIMEType:@"image/tiff"
306 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
311 if ([types containsObject:NSPICTPboardType]) {
312 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
313 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
314 MIMEType:@"image/pict"
317 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
322 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
323 NSAttributedString *string = nil;
324 if ([types containsObject:NSRTFDPboardType]) {
325 string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
327 if (string == nil && [types containsObject:NSRTFPboardType]) {
328 string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
331 NSArray *elements = [[NSArray alloc] initWithObjects:@"style", nil];
332 NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:elements, NSExcludedElementsDocumentAttribute, nil];
334 NSArray *subresources;
335 DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length])
336 document:[[self _bridge] DOMDocument]
337 documentAttributes:documentAttributes
338 subresources:&subresources];
339 [documentAttributes release];
342 if ([subresources count] != 0) {
343 [[self _dataSource] _addSubresources:subresources];
350 if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
351 NSString *URLString = [URL _web_userVisibleString];
352 if ([URLString length] > 0) {
353 return [[self _bridge] documentFragmentWithText:URLString];
357 if (allowPlainText && [types containsObject:NSStringPboardType]) {
358 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
364 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
366 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText];
367 WebBridge *bridge = [self _bridge];
368 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
369 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
373 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
375 WebView *webView = [self _webView];
376 DOMNode *child = [fragment firstChild];
377 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
378 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
380 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
384 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
386 WebView *webView = [self _webView];
387 DOMRange *selectedRange = [self _selectedRange];
388 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
391 // Calculate the vertical size of the view that fits on a single page
392 - (float)_calculatePrintHeight
394 // Obtain the print info object for the current operation
395 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
397 // Calculate the page height in points
398 NSSize paperSize = [pi paperSize];
399 return paperSize.height - [pi topMargin] - [pi bottomMargin];
402 - (void)_updateTextSizeMultiplier
404 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
407 - (DOMRange *)_selectedRange
409 return [[self _bridge] selectedDOMRange];
412 - (BOOL)_shouldDeleteRange:(DOMRange *)range
414 if (range == nil || [range collapsed])
416 WebView *webView = [self _webView];
417 return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
420 - (void)_deleteRange:(DOMRange *)range
421 preflight:(BOOL)preflight
422 killRing:(BOOL)killRing
423 prepend:(BOOL)prepend
424 smartDeleteOK:(BOOL)smartDeleteOK
426 if (![self _shouldDeleteRange:range]) {
429 WebBridge *bridge = [self _bridge];
430 if (killRing && _private->startNewKillRingSequence) {
431 _NSNewKillRingSequence();
433 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityUpstream];
436 _NSPrependToKillRing([bridge selectedString]);
438 _NSAppendToKillRing([bridge selectedString]);
440 _private->startNewKillRingSequence = NO;
442 BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
443 [bridge deleteSelectionWithSmartDelete:smartDelete];
446 - (void)_deleteSelection
448 [self _deleteRange:[self _selectedRange]
455 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
457 return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
462 @implementation WebHTMLView (WebPrivate)
466 [WebImageRenderer stopAnimationsInView:self];
469 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
471 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
472 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
473 modifierFlags:[flagsChangedEvent modifierFlags]
474 timestamp:[flagsChangedEvent timestamp]
475 windowNumber:[flagsChangedEvent windowNumber]
476 context:[flagsChangedEvent context]
477 eventNumber:0 clickCount:0 pressure:0];
479 // Pretend it's a mouse move.
480 [[NSNotificationCenter defaultCenter]
481 postNotificationName:NSMouseMovedNotification object:self
482 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
485 - (void)_updateMouseoverWithFakeEvent
487 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
488 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
489 modifierFlags:[[NSApp currentEvent] modifierFlags]
490 timestamp:[NSDate timeIntervalSinceReferenceDate]
491 windowNumber:[[self window] windowNumber]
492 context:[[NSApp currentEvent] context]
493 eventNumber:0 clickCount:0 pressure:0];
495 [self _updateMouseoverWithEvent:fakeEvent];
498 - (void)_frameOrBoundsChanged
500 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
501 [self setNeedsLayout:YES];
502 [self setNeedsDisplay:YES];
503 [_private->compController endRevertingChange:NO moveLeft:NO];
506 NSPoint origin = [[self superview] bounds].origin;
507 if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
508 [[self _bridge] sendScrollEvent];
509 [_private->compController endRevertingChange:NO moveLeft:NO];
511 _private->lastScrollPosition = origin;
513 SEL selector = @selector(_updateMouseoverWithFakeEvent);
514 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
515 [self performSelector:selector withObject:nil afterDelay:0];
518 - (void)_setAsideSubviews
520 ASSERT(!_private->subviewsSetAside);
521 ASSERT(_private->savedSubviews == nil);
522 _private->savedSubviews = _subviews;
524 _private->subviewsSetAside = YES;
527 - (void)_restoreSubviews
529 ASSERT(_private->subviewsSetAside);
530 ASSERT(_subviews == nil);
531 _subviews = _private->savedSubviews;
532 _private->savedSubviews = nil;
533 _private->subviewsSetAside = NO;
536 // Don't let AppKit even draw subviews. We take care of that.
537 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
539 // This helps when we print as part of a larger print process.
540 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
541 BOOL wasInPrintingMode = _private->printing;
542 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
543 if (wasInPrintingMode != isPrinting) {
545 [self _web_setPrintingModeRecursive];
547 [self _web_clearPrintingModeRecursive];
551 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
553 [self _setAsideSubviews];
554 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
555 rectIsVisibleRectForView:visibleView topView:topView];
556 [self _restoreSubviews];
558 if (wasInPrintingMode != isPrinting) {
559 if (wasInPrintingMode) {
560 [self _web_setPrintingModeRecursive];
562 [self _web_clearPrintingModeRecursive];
567 // Don't let AppKit even draw subviews. We take care of that.
568 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
570 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
572 BOOL wasInPrintingMode = _private->printing;
573 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
575 if (needToSetAsideSubviews) {
576 // This helps when we print as part of a larger print process.
577 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
578 if (wasInPrintingMode != isPrinting) {
580 [self _web_setPrintingModeRecursive];
582 [self _web_clearPrintingModeRecursive];
586 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
588 [self _setAsideSubviews];
591 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
593 if (needToSetAsideSubviews) {
594 if (wasInPrintingMode != isPrinting) {
595 if (wasInPrintingMode) {
596 [self _web_setPrintingModeRecursive];
598 [self _web_clearPrintingModeRecursive];
602 [self _restoreSubviews];
606 - (BOOL)_insideAnotherHTMLView
609 while ((view = [view superview])) {
610 if ([view isKindOfClass:[WebHTMLView class]]) {
617 - (void)scrollPoint:(NSPoint)point
619 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
620 // If we get called during the handling of a key down event, we assume the call came from
621 // NSTextView, and ignore it and use our own code to decide how to page up and page down
622 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
623 NSEvent *event = [[self window] currentEvent];
624 if ([event type] == NSKeyDown) {
625 const unichar pageUp = NSPageUpFunctionKey;
626 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
627 [self tryToPerform:@selector(scrollPageUp:) with:nil];
630 const unichar pageDown = NSPageDownFunctionKey;
631 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
632 [self tryToPerform:@selector(scrollPageDown:) with:nil];
637 [super scrollPoint:point];
640 - (NSView *)hitTest:(NSPoint)point
642 // WebHTMLView objects handle all left mouse clicks for objects inside them.
643 // That does not include left mouse clicks with the control key held down.
644 BOOL captureHitsOnSubviews;
645 if (forceRealHitTest) {
646 captureHitsOnSubviews = NO;
648 NSEvent *event = [[self window] currentEvent];
649 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
651 if (!captureHitsOnSubviews) {
652 return [super hitTest:point];
654 if ([[self superview] mouse:point inRect:[self frame]]) {
660 static WebHTMLView *lastHitView = nil;
662 - (void)_clearLastHitViewIfSelf
664 if (lastHitView == self) {
669 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
671 ASSERT(_private->trackingRectOwner == nil);
672 _private->trackingRectOwner = owner;
673 _private->trackingRectUserData = data;
674 return TRACKING_RECT_TAG;
677 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
679 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
680 ASSERT(_private->trackingRectOwner == nil);
681 _private->trackingRectOwner = owner;
682 _private->trackingRectUserData = data;
683 return TRACKING_RECT_TAG;
686 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
689 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
690 ASSERT(_private->trackingRectOwner == nil);
691 _private->trackingRectOwner = owner;
692 _private->trackingRectUserData = userDataList[0];
693 trackingNums[0] = TRACKING_RECT_TAG;
696 - (void)removeTrackingRect:(NSTrackingRectTag)tag
700 ASSERT(tag == TRACKING_RECT_TAG);
701 if (_private != nil) {
702 _private->trackingRectOwner = nil;
706 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
709 for (i = 0; i < count; ++i) {
713 ASSERT(tag == TRACKING_RECT_TAG);
714 if (_private != nil) {
715 _private->trackingRectOwner = nil;
720 - (void)_sendToolTipMouseExited
722 // Nothing matters except window, trackingNumber, and userData.
723 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
724 location:NSMakePoint(0, 0)
727 windowNumber:[[self window] windowNumber]
730 trackingNumber:TRACKING_RECT_TAG
731 userData:_private->trackingRectUserData];
732 [_private->trackingRectOwner mouseExited:fakeEvent];
735 - (void)_sendToolTipMouseEntered
737 // Nothing matters except window, trackingNumber, and userData.
738 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
739 location:NSMakePoint(0, 0)
742 windowNumber:[[self window] windowNumber]
745 trackingNumber:TRACKING_RECT_TAG
746 userData:_private->trackingRectUserData];
747 [_private->trackingRectOwner mouseEntered:fakeEvent];
750 - (void)_setToolTip:(NSString *)string
752 NSString *toolTip = [string length] == 0 ? nil : string;
753 NSString *oldToolTip = _private->toolTip;
754 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
758 [self _sendToolTipMouseExited];
759 [oldToolTip release];
761 _private->toolTip = [toolTip copy];
763 [self removeAllToolTips];
764 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
765 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
766 [self _sendToolTipMouseEntered];
770 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
772 return [[_private->toolTip copy] autorelease];
775 - (void)_updateMouseoverWithEvent:(NSEvent *)event
777 WebHTMLView *view = nil;
778 if ([event window] == [self window]) {
779 forceRealHitTest = YES;
780 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
781 forceRealHitTest = NO;
783 if ([hitView isKindOfClass:[WebHTMLView class]]) {
784 view = (WebHTMLView *)hitView;
787 hitView = [hitView superview];
791 if (lastHitView != view && lastHitView != nil) {
792 // If we are moving out of a view (or frame), let's pretend the mouse moved
793 // all the way out of that view. But we have to account for scrolling, because
794 // khtml doesn't understand our clipping.
795 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
796 float yScroll = visibleRect.origin.y;
797 float xScroll = visibleRect.origin.x;
799 event = [NSEvent mouseEventWithType:NSMouseMoved
800 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
801 modifierFlags:[[NSApp currentEvent] modifierFlags]
802 timestamp:[NSDate timeIntervalSinceReferenceDate]
803 windowNumber:[[self window] windowNumber]
804 context:[[NSApp currentEvent] context]
805 eventNumber:0 clickCount:0 pressure:0];
806 [[lastHitView _bridge] mouseMoved:event];
811 NSDictionary *element;
815 [[view _bridge] mouseMoved:event];
817 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
818 element = [view elementAtPoint:point];
821 // Have the web view send a message to the delegate so it can do status bar display.
822 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
824 // Set a tool tip; it won't show up right away but will if the user pauses.
825 NSString *newToolTip = nil;
826 if (_private->showsURLsInToolTips) {
827 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
829 if (newToolTip == nil) {
830 newToolTip = [element objectForKey:WebCoreElementTitleKey];
832 [self _setToolTip:newToolTip];
835 + (NSArray *)_insertablePasteboardTypes
837 static NSArray *types = nil;
839 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
840 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
841 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
846 + (NSArray *)_selectionPasteboardTypes
848 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
849 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
852 - (WebArchive *)_selectedArchive
856 double start = CFAbsoluteTimeGetCurrent();
858 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
860 double duration = CFAbsoluteTimeGetCurrent() - start;
861 LOG(Timing, "copying markup took %f seconds.", duration);
864 return [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
867 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
869 ASSERT([self _hasSelection]);
870 NSArray *types = [self pasteboardTypesForSelection];
871 [pasteboard declareTypes:types owner:nil];
872 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
875 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
877 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
879 BOOL drawURLString = YES;
880 BOOL clipURLString = NO, clipLabelString = NO;
882 NSString *label = [element objectForKey: WebElementLinkLabelKey];
883 NSString *urlString = [linkURL _web_userVisibleString];
890 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
891 toHaveTrait:NSBoldFontMask];
892 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
894 labelSize.width = [label _web_widthWithFont: labelFont];
895 labelSize.height = [labelFont ascender] - [labelFont descender];
896 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
897 labelSize.width = MAX_DRAG_LABEL_WIDTH;
898 clipLabelString = YES;
901 NSSize imageSize, urlStringSize;
902 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
903 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
905 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
906 urlStringSize.height = [urlFont ascender] - [urlFont descender];
907 imageSize.height += urlStringSize.height;
908 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
909 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
912 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
915 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
916 [dragImage lockFocus];
918 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
920 // Drag a rectangle with rounded corners/
921 NSBezierPath *path = [NSBezierPath bezierPath];
922 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
923 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
924 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
925 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
927 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
928 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
929 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
932 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
933 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
936 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
938 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
939 withTopColor:topColor bottomColor:bottomColor font:urlFont];
943 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
944 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
945 withTopColor:topColor bottomColor:bottomColor font:labelFont];
947 [dragImage unlockFocus];
952 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
954 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
955 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
957 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
958 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
959 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
961 [_private->draggingImageURL release];
962 _private->draggingImageURL = nil;
964 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
965 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
966 NSImage *dragImage = nil;
969 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
970 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
971 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
973 dragImage = wcDragImage;
974 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
975 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
978 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
980 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
982 _private->dragOffset = wcDragLoc;
985 WebView *webView = [self _webView];
986 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
987 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
988 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
990 // note per kwebster, the offset arg below is always ignored in positioning the image
991 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
993 if (!dhtmlWroteData) {
994 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
995 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
996 ASSERT(imageElement != nil);
997 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityUpstream];
998 _private->draggingImageURL = [imageURL retain];
999 source = [pasteboard _web_declareAndWriteDragImage:image
1000 URL:linkURL ? linkURL : imageURL
1001 title:[element objectForKey:WebElementImageAltStringKey]
1002 archive:[imageElement webArchive]
1005 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1006 if (dragImage == nil) {
1007 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1008 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1009 event:_private->mouseDownEvent
1010 pasteboard:pasteboard
1012 offset:&_private->dragOffset];
1014 [self dragImage:dragImage
1017 event:_private->mouseDownEvent
1018 pasteboard:pasteboard
1022 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1023 if (!dhtmlWroteData) {
1024 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1025 [pasteboard declareTypes:types owner:self];
1026 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1028 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1029 if (dragImage == nil) {
1030 dragImage = [self _dragImageForLinkElement:element];
1031 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1032 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1033 _private->dragOffset.x = offset.width;
1034 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1036 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1037 // a flash of the image at the mouseDown location when the drag starts.
1038 [self dragImage:dragImage
1041 event:mouseDraggedEvent
1042 pasteboard:pasteboard
1045 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1046 if (!dhtmlWroteData) {
1047 [self _writeSelectionToPasteboard:pasteboard];
1049 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1050 if (dragImage == nil) {
1051 dragImage = [[self _bridge] selectionImage];
1052 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1053 NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
1054 dragLoc = NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect));
1055 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1056 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1058 [self dragImage:dragImage
1061 event:_private->mouseDownEvent
1062 pasteboard:pasteboard
1065 } else if (srcIsDHTML) {
1066 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1067 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1068 if (dragImage == nil) {
1069 // WebCore should have given us an image, but we'll make one up
1070 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1071 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1072 NSSize imageSize = [dragImage size];
1073 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1074 _private->dragOffset.x = imageSize.width/2;
1075 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1077 [self dragImage:dragImage
1080 event:_private->mouseDownEvent
1081 pasteboard:pasteboard
1085 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1086 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1092 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1094 [self autoscroll:event];
1095 [self _startAutoscrollTimer:event];
1098 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1100 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1101 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1103 ASSERT([self _webView]);
1104 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1105 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1106 [[[self _webView] preferences] loadsImagesAutomatically] &&
1107 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1111 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1112 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1116 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1117 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1124 - (WebPluginController *)_pluginController
1126 return _private->pluginController;
1129 - (void)_web_setPrintingModeRecursive
1131 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1132 [super _web_setPrintingModeRecursive];
1135 - (void)_web_clearPrintingModeRecursive
1137 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1138 [super _web_clearPrintingModeRecursive];
1141 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1143 ASSERT(!_private->subviewsSetAside);
1144 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1146 if (!testDirtyRect || [self needsDisplay]) {
1147 if (testDirtyRect) {
1148 NSRect dirtyRect = [self _dirtyRect];
1149 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1151 if (!NSIsEmptyRect(displayRect)) {
1152 if ([[self _bridge] needsLayout])
1153 _private->needsLayout = YES;
1154 if (_private->needsToApplyStyles || _private->needsLayout)
1159 [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
1162 - (NSRect)_selectionRect
1164 return [[self _bridge] selectionRect];
1167 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1169 if (_private->autoscrollTimer == nil) {
1170 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1171 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1172 _private->autoscrollTriggerEvent = [triggerEvent retain];
1176 - (void)_stopAutoscrollTimer
1178 NSTimer *timer = _private->autoscrollTimer;
1179 _private->autoscrollTimer = nil;
1180 [_private->autoscrollTriggerEvent release];
1181 _private->autoscrollTriggerEvent = nil;
1190 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1191 // a mouse up event.
1192 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1194 [self _stopAutoscrollTimer];
1198 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1199 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1200 modifierFlags:[[NSApp currentEvent] modifierFlags]
1201 timestamp:[NSDate timeIntervalSinceReferenceDate]
1202 windowNumber:[[self window] windowNumber]
1203 context:[[NSApp currentEvent] context]
1204 eventNumber:0 clickCount:0 pressure:0];
1205 [self mouseDragged:fakeEvent];
1210 // Copying can be done regardless of whether you can edit.
1211 return [self _hasSelection];
1216 return [self _hasSelection] && [self _isEditable];
1221 return [self _hasSelection] && [self _isEditable];
1226 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1231 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1234 - (BOOL)_hasSelection
1236 return [[self _bridge] selectionState] == WebSelectionStateRange;
1239 - (BOOL)_hasSelectionOrInsertionPoint
1241 return [[self _bridge] selectionState] != WebSelectionStateNone;
1246 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1249 - (BOOL)_isSelectionMisspelled
1251 NSString *selectedString = [self selectedString];
1252 unsigned length = [selectedString length];
1256 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1260 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1262 return range.length == length;
1265 - (NSArray *)_guessesForMisspelledSelection
1267 ASSERT([[self selectedString] length] != 0);
1268 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1271 - (void)_changeSpellingFromMenu:(id)sender
1273 ASSERT([[self selectedString] length] != 0);
1274 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1277 - (void)_ignoreSpellingFromMenu:(id)sender
1279 ASSERT([[self selectedString] length] != 0);
1280 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1283 - (void)_learnSpellingFromMenu:(id)sender
1285 ASSERT([[self selectedString] length] != 0);
1286 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1289 #if APPKIT_CODE_FOR_REFERENCE
1291 - (void)_openLinkFromMenu:(id)sender
1293 NSTextStorage *text = _getTextStorage(self);
1294 NSRange charRange = [self selectedRange];
1295 if (charRange.location != NSNotFound && charRange.length > 0) {
1296 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1298 [self clickedOnLink:link atIndex:charRange.location];
1300 NSString *string = [[text string] substringWithRange:charRange];
1301 link = [NSURL URLWithString:string];
1302 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1309 - (BOOL)_transparentBackground
1311 return _private->transparentBackground;
1314 - (void)_setTransparentBackground:(BOOL)f
1316 _private->transparentBackground = f;
1321 @implementation NSView (WebHTMLViewFileInternal)
1323 - (void)_web_setPrintingModeRecursive
1325 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1328 - (void)_web_clearPrintingModeRecursive
1330 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1333 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1335 unsigned index, count;
1336 for (index = 0, count = [_subviews count]; index < count; index++) {
1337 NSView *subview = [_subviews objectAtIndex:index];
1338 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1339 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1345 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1347 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1349 if (object == nil) {
1350 [self removeObjectForKey:key];
1352 [self setObject:object forKey:key];
1358 // The following is a workaround for
1359 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1360 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1361 // Since the category will be searched before the real class, we'll prevent the flag from being
1362 // set on the tool tip panel.
1364 @interface NSToolTipPanel : NSPanel
1367 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1370 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1372 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1374 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1380 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1383 @interface NSArray (WebHTMLView)
1384 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1387 @implementation WebHTMLView
1391 WebKitInitializeUnicode();
1392 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1393 returnTypes:[[self class] _insertablePasteboardTypes]];
1394 _NSInitializeKillRing();
1397 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1399 WebPreferences *preferences = [[self _webView] preferences];
1400 // Check for nil because we might not yet have an associated webView when this is called
1401 if (preferences == nil) {
1402 preferences = [WebPreferences standardPreferences];
1404 _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1407 - (id)initWithFrame:(NSRect)frame
1409 [super initWithFrame:frame];
1411 // Make all drawing go through us instead of subviews.
1412 if (NSAppKitVersionNumber >= 711) {
1413 [self _setDrawsOwnDescendants:YES];
1416 _private = [[WebHTMLViewPrivate alloc] init];
1418 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1419 _private->needsLayout = YES;
1420 [self _resetCachedWebPreferences:nil];
1421 [[NSNotificationCenter defaultCenter]
1422 addObserver:self selector:@selector(_resetCachedWebPreferences:)
1423 name:WebPreferencesChangedNotification object:nil];
1430 [self _clearLastHitViewIfSelf];
1432 [[NSNotificationCenter defaultCenter] removeObserver:self];
1433 [_private->pluginController destroyAllPlugins];
1441 [self _clearLastHitViewIfSelf];
1443 [[NSNotificationCenter defaultCenter] removeObserver:self];
1444 [_private->pluginController destroyAllPlugins];
1449 - (IBAction)takeFindStringFromSelection:(id)sender
1451 if (![self _hasSelection]) {
1456 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1459 - (NSArray *)pasteboardTypesForSelection
1461 if ([self _canSmartCopyOrDelete]) {
1462 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1463 [types addObject:WebSmartPastePboardType];
1466 return [[self class] _selectionPasteboardTypes];
1470 // This method is copied from NSTextView
1471 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
1473 NSRange attachmentRange;
1474 NSString *originalString = [originalAttributedString string];
1475 static NSString *attachmentCharString = nil;
1477 if (!attachmentCharString) {
1479 if (!attachmentCharString) {
1480 chars[0] = NSAttachmentCharacter;
1482 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
1486 attachmentRange = [originalString rangeOfString:attachmentCharString];
1487 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1488 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
1490 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1491 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
1492 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
1494 return newAttributedString;
1496 return originalAttributedString;
1500 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1502 // Put HTML on the pasteboard.
1503 if ([types containsObject:WebArchivePboardType]) {
1504 WebArchive *archive = [self _selectedArchive];
1505 [pasteboard setData:[archive data] forType:WebArchivePboardType];
1508 // Put the attributed string on the pasteboard (RTF/RTFD format).
1509 NSAttributedString *attributedString = nil;
1510 if ([types containsObject:NSRTFDPboardType]) {
1511 attributedString = [self selectedAttributedString];
1512 if ([attributedString containsAttachments]) {
1513 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1514 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
1517 if ([types containsObject:NSRTFPboardType]) {
1518 if (attributedString == nil) {
1519 attributedString = [self selectedAttributedString];
1521 if ([attributedString containsAttachments]) {
1522 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
1524 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1525 [pasteboard setData:RTFData forType:NSRTFPboardType];
1528 // Put plain string on the pasteboard.
1529 if ([types containsObject:NSStringPboardType]) {
1530 // Map to a plain old space because this is better for source code, other browsers do it,
1531 // and because HTML forces you to do this any time you want two spaces in a row.
1532 NSMutableString *s = [[self selectedString] mutableCopy];
1533 const unichar NonBreakingSpaceCharacter = 0xA0;
1534 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1535 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1536 [pasteboard setString:s forType:NSStringPboardType];
1540 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
1541 [pasteboard setData:nil forType:WebSmartPastePboardType];
1545 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1547 [pasteboard declareTypes:types owner:nil];
1548 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1552 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1554 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1558 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1560 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1562 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1565 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1568 - (void)selectAll:(id)sender
1573 - (void)jumpToSelection: sender
1575 [[self _bridge] jumpToSelection];
1578 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1580 SEL action = [item action];
1581 WebBridge *bridge = [self _bridge];
1583 if (action == @selector(cut:)) {
1584 return [bridge mayDHTMLCut] || [self _canDelete];
1585 } else if (action == @selector(copy:)) {
1586 return [bridge mayDHTMLCopy] || [self _canCopy];
1587 } else if (action == @selector(delete:)) {
1588 return [self _canDelete];
1589 } else if (action == @selector(paste:)) {
1590 return [bridge mayDHTMLPaste] || [self _canPaste];
1591 } else if (action == @selector(takeFindStringFromSelection:)) {
1592 return [self _hasSelection];
1593 } else if (action == @selector(jumpToSelection:)) {
1594 return [self _hasSelection];
1595 } else if (action == @selector(checkSpelling:)
1596 || action == @selector(showGuessPanel:)
1597 || action == @selector(changeSpelling:)
1598 || action == @selector(ignoreSpelling:)) {
1599 return [[self _bridge] isSelectionEditable];
1605 - (BOOL)acceptsFirstResponder
1607 // Don't accept first responder when we first click on this view.
1608 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1609 // Do accept first responder at any other time, for example from keyboard events,
1610 // or from calls back from WebCore once we begin mouse-down event handling.
1611 NSEvent *event = [NSApp currentEvent];
1612 if ([event type] == NSLeftMouseDown
1613 && !_private->handlingMouseDownEvent
1614 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1620 - (BOOL)maintainsInactiveSelection
1622 // This method helps to determing whether the view should maintain
1623 // an inactive selection when the view is not first responder.
1624 // Traditionally, these views have not maintained such selections,
1625 // clearing them when the view was not first responder. However,
1626 // to fix bugs like this one:
1627 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
1628 // when they're not firstResponder"
1629 // it was decided to add a switch to act more like an NSTextView.
1630 // For now, however, the view only acts in this way when the
1631 // web view is set to be editable. This will maintain traditional
1632 // behavior for WebKit clients dating back to before this change,
1633 // and will likely be a decent switch for the long term, since
1634 // clients to ste the web view to be editable probably want it
1635 // to act like a "regular" Cocoa view in terms of its selection
1637 if (![[self _webView] isEditable])
1640 id nextResponder = [[self window] _newFirstResponderAfterResigning];
1641 return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1644 - (void)addMouseMovedObserver
1646 // Always add a mouse move observer if the DB requested, or if we're the key window.
1647 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1648 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1649 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1650 name:NSMouseMovedNotification object:nil];
1651 [self _frameOrBoundsChanged];
1655 - (void)removeMouseMovedObserver
1657 // Don't remove the observer if we're running the DB
1658 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1661 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1662 [[NSNotificationCenter defaultCenter] removeObserver:self
1663 name:NSMouseMovedNotification object:nil];
1666 - (void)updateFocusDisplay
1668 // This method does the job of updating the view based on the view's firstResponder-ness and
1669 // the window key-ness of the window containing this view. This involves three kinds of
1670 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
1672 // The three display attributes are as follows:
1674 // 1. The background color used to draw behind selected content (active | inactive color)
1675 // 2. Caret blinking (blinks | does not blink)
1676 // 3. The drawing of a focus ring around links in web pages.
1678 BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1679 [[self _bridge] setDisplaysWithFocusAttributes:flag];
1682 - (void)addSuperviewObservers
1684 // We watch the bounds of our superview, so that we can do a layout when the size
1685 // of the superview changes. This is different from other scrollable things that don't
1686 // need this kind of thing because their layout doesn't change.
1688 // We need to pay attention to both height and width because our "layout" has to change
1689 // to extend the background the full height of the space and because some elements have
1690 // sizes that are based on the total size of the view.
1692 NSView *superview = [self superview];
1693 if (superview && [self window]) {
1694 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1695 name:NSViewFrameDidChangeNotification object:superview];
1696 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1697 name:NSViewBoundsDidChangeNotification object:superview];
1701 - (void)removeSuperviewObservers
1703 NSView *superview = [self superview];
1704 if (superview && [self window]) {
1705 [[NSNotificationCenter defaultCenter] removeObserver:self
1706 name:NSViewFrameDidChangeNotification object:superview];
1707 [[NSNotificationCenter defaultCenter] removeObserver:self
1708 name:NSViewBoundsDidChangeNotification object:superview];
1712 - (void)addWindowObservers
1714 NSWindow *window = [self window];
1716 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1717 name:NSWindowDidBecomeKeyNotification object:window];
1718 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1719 name:NSWindowDidResignKeyNotification object:window];
1720 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1721 name:NSWindowWillCloseNotification object:window];
1725 - (void)removeWindowObservers
1727 NSWindow *window = [self window];
1729 [[NSNotificationCenter defaultCenter] removeObserver:self
1730 name:NSWindowDidBecomeKeyNotification object:window];
1731 [[NSNotificationCenter defaultCenter] removeObserver:self
1732 name:NSWindowDidResignKeyNotification object:window];
1733 [[NSNotificationCenter defaultCenter] removeObserver:self
1734 name:NSWindowWillCloseNotification object:window];
1738 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1740 [self removeSuperviewObservers];
1743 - (void)viewDidMoveToSuperview
1745 // Do this here in case the text size multiplier changed when a non-HTML
1746 // view was installed.
1747 if ([self superview] != nil) {
1748 [self _updateTextSizeMultiplier];
1749 [self addSuperviewObservers];
1753 - (void)viewWillMoveToWindow:(NSWindow *)window
1755 // Don't do anything if we aren't initialized. This happens
1756 // when decoding a WebView. When WebViews are decoded their subviews
1757 // are created by initWithCoder: and so won't be normally
1758 // initialized. The stub views are discarded by WebView.
1760 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1761 [self removeMouseMovedObserver];
1762 [self removeWindowObservers];
1763 [self removeSuperviewObservers];
1764 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1766 [[self _pluginController] stopAllPlugins];
1770 - (void)viewDidMoveToWindow
1772 // Don't do anything if we aren't initialized. This happens
1773 // when decoding a WebView. When WebViews are decoded their subviews
1774 // are created by initWithCoder: and so won't be normally
1775 // initialized. The stub views are discarded by WebView.
1777 [self _stopAutoscrollTimer];
1778 if ([self window]) {
1779 _private->lastScrollPosition = [[self superview] bounds].origin;
1780 [self addWindowObservers];
1781 [self addSuperviewObservers];
1782 [self addMouseMovedObserver];
1783 // Schedule this update, rather than making the call right now.
1784 // The reason is that placing the caret in the just-installed view requires
1785 // the HTML/XML document to be available on the WebCore side, but it is not
1786 // at the time this code is running. However, it will be there on the next
1787 // crank of the run loop. Doing this helps to make a blinking caret appear
1788 // in a new, empty window "automatic".
1789 [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1791 [[self _pluginController] startAllPlugins];
1793 _private->lastScrollPosition = NSZeroPoint;
1795 _private->inWindow = YES;
1797 // Reset when we are moved out of a window after being moved into one.
1798 // Without this check, we reset ourselves before we even start.
1799 // This is only needed because viewDidMoveToWindow is called even when
1800 // the window is not changing (bug in AppKit).
1801 if (_private->inWindow) {
1803 _private->inWindow = NO;
1809 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1811 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1814 - (void)viewDidMoveToHostWindow
1816 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1820 - (void)addSubview:(NSView *)view
1822 [super addSubview:view];
1824 if ([WebPluginController isPlugInView:view]) {
1825 [[self _pluginController] addPlugin:view];
1829 - (void)reapplyStyles
1831 if (!_private->needsToApplyStyles) {
1836 double start = CFAbsoluteTimeGetCurrent();
1839 [[self _bridge] reapplyStylesForDeviceType:
1840 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1843 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1844 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1847 _private->needsToApplyStyles = NO;
1850 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1851 // minPageWidth==0 implies a non-printing layout
1852 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1854 [self reapplyStyles];
1856 // Ensure that we will receive mouse move events. Is this the best place to put this?
1857 [[self window] setAcceptsMouseMovedEvents: YES];
1858 [[self window] _setShouldPostEventNotifications: YES];
1860 if (!_private->needsLayout) {
1865 double start = CFAbsoluteTimeGetCurrent();
1868 LOG(View, "%@ doing layout", self);
1870 if (minPageWidth > 0.0) {
1871 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1873 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1875 _private->needsLayout = NO;
1877 if (!_private->printing) {
1878 // get size of the containing dynamic scrollview, so
1879 // appearance and disappearance of scrollbars will not show up
1881 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1882 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1883 [[self _bridge] sendResizeEvent];
1885 _private->laidOutAtLeastOnce = YES;
1886 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1887 _private->lastLayoutFrameSize = newLayoutFrameSize;
1891 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1892 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1898 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1901 - (NSMenu *)menuForEvent:(NSEvent *)event
1903 [_private->compController endRevertingChange:NO moveLeft:NO];
1905 if ([[self _bridge] sendContextMenuEvent:event]) {
1908 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1909 NSDictionary *element = [self elementAtPoint:point];
1910 return [[self _webView] _menuForElement:element];
1913 // Search from the end of the currently selected location, or from the beginning of the
1914 // document if nothing is selected.
1915 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1917 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1920 - (DOMRange *)_documentRange
1922 return [[[self _bridge] DOMDocument] _documentRange];
1925 - (NSString *)string
1927 return [[self _bridge] stringForRange:[self _documentRange]];
1930 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
1932 NSAttributedString *attributedString = nil;
1933 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
1935 double start = CFAbsoluteTimeGetCurrent();
1937 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
1939 double duration = CFAbsoluteTimeGetCurrent() - start;
1940 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
1943 return attributedString;
1946 - (NSAttributedString *)attributedString
1948 WebBridge *bridge = [self _bridge];
1949 DOMDocument *document = [bridge DOMDocument];
1950 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
1951 if (attributedString == nil) {
1952 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
1954 return attributedString;
1957 - (NSString *)selectedString
1959 return [[self _bridge] selectedString];
1962 - (NSAttributedString *)selectedAttributedString
1964 WebBridge *bridge = [self _bridge];
1965 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
1966 if (attributedString == nil) {
1967 attributedString = [bridge selectedAttributedString];
1969 return attributedString;
1974 [[self _bridge] selectAll];
1977 // Remove the selection.
1980 [[self _bridge] deselectAll];
1983 - (void)deselectText
1985 [[self _bridge] deselectText];
1990 return [[self _webView] drawsBackground];
1993 - (void)setNeedsDisplay:(BOOL)flag
1995 LOG(View, "%@ flag = %d", self, (int)flag);
1996 [super setNeedsDisplay: flag];
1999 - (void)setNeedsLayout: (BOOL)flag
2001 LOG(View, "%@ flag = %d", self, (int)flag);
2002 _private->needsLayout = flag;
2006 - (void)setNeedsToApplyStyles: (BOOL)flag
2008 LOG(View, "%@ flag = %d", self, (int)flag);
2009 _private->needsToApplyStyles = flag;
2012 - (void)drawRect:(NSRect)rect
2014 LOG(View, "%@ drawing", self);
2016 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2017 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2018 // This does a better job of clipping out rects that are entirely outside the visible area.
2019 const NSRect *rects;
2021 [self getRectsBeingDrawn:&rects count:&count];
2023 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2024 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2025 // The reason for the workaround is that this method is called explicitly from the code
2026 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2030 for (i = 0; i < count; ++i) {
2031 rect = NSUnionRect(rect, rects[i]);
2033 if (rect.size.height == 0 || rect.size.width == 0) {
2038 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2039 if (subviewsWereSetAside) {
2040 [self _restoreSubviews];
2044 double start = CFAbsoluteTimeGetCurrent();
2047 [NSGraphicsContext saveGraphicsState];
2050 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2052 [(WebClipView *)[self superview] setAdditionalClip:rect];
2055 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2056 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2057 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2058 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2061 if ([self _transparentBackground]) {
2062 [[NSColor clearColor] set];
2066 //double start = CFAbsoluteTimeGetCurrent();
2067 [[self _bridge] drawRect:rect];
2068 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2070 if (textRendererFactoryIfCoalescing != nil) {
2071 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2074 [(WebClipView *)[self superview] resetAdditionalClip];
2076 [NSGraphicsContext restoreGraphicsState];
2078 [(WebClipView *)[self superview] resetAdditionalClip];
2079 [NSGraphicsContext restoreGraphicsState];
2080 ERROR("Exception caught while drawing: %@", localException);
2081 [localException raise];
2085 NSRect vframe = [self frame];
2086 [[NSColor blackColor] set];
2088 path = [NSBezierPath bezierPath];
2089 [path setLineWidth:(float)0.1];
2090 [path moveToPoint:NSMakePoint(0, 0)];
2091 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2094 path = [NSBezierPath bezierPath];
2095 [path setLineWidth:(float)0.1];
2096 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2097 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2103 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2104 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2107 if (subviewsWereSetAside) {
2108 [self _setAsideSubviews];
2112 // Turn off the additional clip while computing our visibleRect.
2113 - (NSRect)visibleRect
2115 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2116 return [super visibleRect];
2118 WebClipView *clipView = (WebClipView *)[self superview];
2120 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2121 if (!hasAdditionalClip) {
2122 return [super visibleRect];
2125 NSRect additionalClip = [clipView additionalClip];
2126 [clipView resetAdditionalClip];
2127 NSRect visibleRect = [super visibleRect];
2128 [clipView setAdditionalClip:additionalClip];
2137 - (void)windowDidBecomeKey:(NSNotification *)notification
2139 ASSERT([notification object] == [self window]);
2140 [self addMouseMovedObserver];
2141 [self updateFocusDisplay];
2144 - (void)windowDidResignKey: (NSNotification *)notification
2146 ASSERT([notification object] == [self window]);
2147 [_private->compController endRevertingChange:NO moveLeft:NO];
2148 [self removeMouseMovedObserver];
2149 [self updateFocusDisplay];
2152 - (void)windowWillClose:(NSNotification *)notification
2154 [_private->compController endRevertingChange:NO moveLeft:NO];
2155 [[self _pluginController] destroyAllPlugins];
2158 - (void)scrollWheel:(NSEvent *)event
2160 if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2161 [[self nextResponder] scrollWheel:event];
2165 - (BOOL)_isSelectionEvent:(NSEvent *)event
2167 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2168 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2171 - (void)_setMouseDownEvent:(NSEvent *)event
2173 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2175 if (event == _private->mouseDownEvent) {
2180 [_private->mouseDownEvent release];
2181 _private->mouseDownEvent = event;
2183 [_private->firstResponderAtMouseDownTime release];
2184 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2187 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2189 [self _setMouseDownEvent:event];
2191 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2194 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2195 // the purposes of this method we want to really query the deepest view, so we forward to it.
2196 forceRealHitTest = YES;
2197 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2198 forceRealHitTest = NO;
2200 if ([hitView isKindOfClass:[self class]]) {
2201 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2202 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2203 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2205 return [hitView acceptsFirstMouse:event];
2209 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2211 [self _setMouseDownEvent:event];
2213 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2214 // the purposes of this method we want to really query the deepest view, so we forward to it.
2215 forceRealHitTest = YES;
2216 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2217 forceRealHitTest = NO;
2219 if ([hitView isKindOfClass:[self class]]) {
2220 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2221 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2223 return [hitView shouldDelayWindowOrderingForEvent:event];
2227 - (void)mouseDown:(NSEvent *)event
2229 _private->handlingMouseDownEvent = YES;
2231 // Record the mouse down position so we can determine drag hysteresis.
2232 [self _setMouseDownEvent:event];
2234 // TEXTINPUT: if there is marked text and the current input
2235 // manager wants to handle mouse events, we need to make sure to
2236 // pass it to them. If not, then we need to notify the input
2237 // manager when the marked text is abandoned (user clicks outside
2240 [_private->compController endRevertingChange:NO moveLeft:NO];
2242 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2243 // We don't want to pass them along to KHTML a second time.
2244 if (!([event modifierFlags] & NSControlKeyMask)) {
2245 _private->ignoringMouseDraggedEvents = NO;
2247 // Don't do any mouseover while the mouse is down.
2248 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2250 // Let KHTML get a chance to deal with the event. This will call back to us
2251 // to start the autoscroll timer if appropriate.
2252 [[self _bridge] mouseDown:event];
2255 [_private->firstResponderAtMouseDownTime release];
2256 _private->firstResponderAtMouseDownTime = nil;
2258 _private->handlingMouseDownEvent = NO;
2261 - (void)dragImage:(NSImage *)dragImage
2263 offset:(NSSize)offset
2264 event:(NSEvent *)event
2265 pasteboard:(NSPasteboard *)pasteboard
2267 slideBack:(BOOL)slideBack
2269 [self _stopAutoscrollTimer];
2271 _private->initiatedDrag = YES;
2272 [[self _webView] _setInitiatedDrag:YES];
2274 // Retain this view during the drag because it may be released before the drag ends.
2277 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2280 - (void)mouseDragged:(NSEvent *)event
2282 // TEXTINPUT: if there is marked text and the current input
2283 // manager wants to handle mouse events, we need to make sure to
2286 if (!_private->ignoringMouseDraggedEvents) {
2287 [[self _bridge] mouseDragged:event];
2291 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2293 if (_private->webCoreDragOp == NSDragOperationNone) {
2294 return (NSDragOperationGeneric | NSDragOperationCopy);
2296 return _private->webCoreDragOp;
2300 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2302 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2303 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2304 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2307 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2309 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2310 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2311 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2313 _private->initiatedDrag = NO;
2314 [[self _webView] _setInitiatedDrag:NO];
2316 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2317 _private->ignoringMouseDraggedEvents = YES;
2319 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2320 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2321 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2322 location:windowMouseLoc
2323 modifierFlags:[[NSApp currentEvent] modifierFlags]
2324 timestamp:[NSDate timeIntervalSinceReferenceDate]
2325 windowNumber:[[self window] windowNumber]
2326 context:[[NSApp currentEvent] context]
2327 eventNumber:0 clickCount:0 pressure:0];
2328 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2330 // Balance the previous retain from when the drag started.
2334 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2336 ASSERT(_private->draggingImageURL);
2338 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2341 // FIXME: Report an error if we fail to create a file.
2342 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2343 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2344 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2345 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2348 return [NSArray arrayWithObject:[path lastPathComponent]];
2351 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2353 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2354 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2355 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2356 if ([types count] == 0) {
2358 } else if ([types count] == 1 &&
2359 [types containsObject:NSFilenamesPboardType] &&
2360 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2364 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2365 NSDictionary *element = [self elementAtPoint:point];
2366 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2367 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2368 // Can't drag onto the selection being dragged.
2379 return _private->initiatedDrag &&
2380 ([self _isEditable] && [self _hasSelection]) &&
2381 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2384 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2386 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2389 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2391 NSDragOperation operation = NSDragOperationNone;
2393 if (actionMask & WebDragDestinationActionDHTML) {
2394 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2396 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2398 if ((actionMask & WebDragDestinationActionEdit) &&
2399 !_private->webCoreHandlingDrag
2400 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2401 if ([self _isNSColorDrag:draggingInfo]) {
2402 operation = NSDragOperationGeneric;
2405 WebView *webView = [self _webView];
2406 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2407 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2410 [[self _webView] removeDragCaret];
2416 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2418 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2419 [[self _webView] removeDragCaret];
2422 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2424 WebView *webView = [self _webView];
2425 WebBridge *bridge = [self _bridge];
2426 if (_private->webCoreHandlingDrag) {
2427 ASSERT(actionMask & WebDragDestinationActionDHTML);
2428 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2429 [bridge concludeDragForDraggingInfo:draggingInfo];
2431 } else if (actionMask & WebDragDestinationActionEdit) {
2432 if ([self _isNSColorDrag:draggingInfo]) {
2433 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2436 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2437 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2438 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2439 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2440 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2446 BOOL didInsert = NO;
2447 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2448 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2449 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2450 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2451 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2452 if ([self _isMoveDrag]) {
2453 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2454 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2456 [bridge setSelectionToDragCaret];
2457 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2462 [webView removeDragCaret];
2469 - (NSDictionary *)elementAtPoint:(NSPoint)point
2471 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2472 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2474 // Convert URL strings to NSURLs
2475 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2476 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2478 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2479 ASSERT(webFrameView);
2480 WebFrame *webFrame = [webFrameView webFrame];
2483 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2484 if ([frameName length] == 0) {
2485 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2487 WebFrame *wf = [webFrame findFrameNamed:frameName];
2489 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2491 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2494 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2497 return [elementInfo autorelease];
2500 - (void)mouseUp:(NSEvent *)event
2502 // TEXTINPUT: if there is marked text and the current input
2503 // manager wants to handle mouse events, we need to make sure to
2506 [self _stopAutoscrollTimer];
2507 [[self _bridge] mouseUp:event];
2508 [self _updateMouseoverWithFakeEvent];
2511 - (void)mouseMovedNotification:(NSNotification *)notification
2513 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2516 - (BOOL)supportsTextEncoding
2521 - (NSView *)nextValidKeyView
2524 if (![self isHiddenOrHasHiddenAncestor]) {
2525 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2528 view = [super nextValidKeyView];
2533 - (NSView *)previousValidKeyView
2536 if (![self isHiddenOrHasHiddenAncestor]) {
2537 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2540 view = [super previousValidKeyView];
2545 - (BOOL)becomeFirstResponder
2548 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2549 switch ([[self window] keyViewSelectionDirection]) {
2550 case NSDirectSelection:
2552 case NSSelectingNext:
2553 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2555 case NSSelectingPrevious:
2556 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2561 [[self window] makeFirstResponder:view];
2563 [self updateFocusDisplay];
2564 _private->startNewKillRingSequence = YES;
2568 // This approach could be relaxed when dealing with 3228554.
2569 // Some alteration to the selection behavior was done to deal with 3672088.
2570 - (BOOL)resignFirstResponder
2572 BOOL resign = [super resignFirstResponder];
2574 [_private->compController endRevertingChange:NO moveLeft:NO];
2575 _private->resigningFirstResponder = YES;
2576 if (![self maintainsInactiveSelection]) {
2577 if ([[self _webView] _isPerformingProgrammaticFocus]) {
2578 [self deselectText];
2584 [self updateFocusDisplay];
2585 _private->resigningFirstResponder = NO;
2590 //------------------------------------------------------------------------------------
2591 // WebDocumentView protocol
2592 //------------------------------------------------------------------------------------
2593 - (void)setDataSource:(WebDataSource *)dataSource
2597 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2601 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2602 // pageWidth != 0 implies we will relayout to a new width
2603 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2605 WebFrame *frame = [self _frame];
2606 NSArray *subframes = [frame childFrames];
2607 unsigned n = [subframes count];
2609 for (i = 0; i != n; ++i) {
2610 WebFrame *subframe = [subframes objectAtIndex:i];
2611 WebFrameView *frameView = [subframe frameView];
2612 if ([[subframe dataSource] _isDocumentHTML]) {
2613 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2617 if (printing != _private->printing) {
2618 [_private->pageRects release];
2619 _private->pageRects = nil;
2620 _private->printing = printing;
2621 [self setNeedsToApplyStyles:YES];
2622 [self setNeedsLayout:YES];
2623 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2625 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2627 // Can't do this when starting printing or nested printing won't work, see 3491427.
2628 [self setNeedsDisplay:NO];
2633 // This is needed for the case where the webview is embedded in the view that's being printed.
2634 // It shouldn't be called when the webview is being printed directly.
2635 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2637 // This helps when we print as part of a larger print process.
2638 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2639 BOOL wasInPrintingMode = _private->printing;
2640 if (!wasInPrintingMode) {
2641 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2644 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2646 if (!wasInPrintingMode) {
2647 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2651 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2653 NSPrintInfo *printInfo = [printOperation printInfo];
2654 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2657 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2659 float viewWidth = NSWidth([self bounds]);
2660 if (viewWidth < 1) {
2661 ERROR("%@ has no width when printing", self);
2665 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2666 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2667 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2668 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2671 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2672 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2673 // if AppKit makes it SPI/API.
2674 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2676 return [self _scaleFactorForPrintOperation:printOperation];
2679 - (void)setPageWidthForPrinting:(float)pageWidth
2681 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2682 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2686 // Return the number of pages available for printing
2687 - (BOOL)knowsPageRange:(NSRangePointer)range {
2688 // Must do this explicit display here, because otherwise the view might redisplay while the print
2689 // sheet was up, using printer fonts (and looking different).
2690 [self displayIfNeeded];
2691 [[self window] setAutodisplay:NO];
2693 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2694 // according to the paper size
2695 float minLayoutWidth = 0.0;
2696 float maxLayoutWidth = 0.0;
2697 if (![[self _bridge] isFrameSet]) {
2698 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2699 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2700 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2702 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2704 // There is a theoretical chance that someone could do some drawing between here and endDocument,
2705 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2706 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2708 range->location = 1;
2709 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2710 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2711 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2712 [_private->pageRects release];
2713 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2714 printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2715 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2716 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2717 // a blank page (with correct-looking header and footer if that option is on), which matches
2718 // the behavior of IE and Camino at least.
2719 if ([newPageRects count] == 0) {
2720 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2722 _private->pageRects = [newPageRects retain];
2724 range->length = [_private->pageRects count];
2729 // Return the drawing rectangle for a particular page number
2730 - (NSRect)rectForPage:(int)page {
2731 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2734 - (void)drawPageBorderWithSize:(NSSize)borderSize
2736 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
2737 [[self _webView] _drawHeaderAndFooter];
2740 - (void)beginDocument
2743 [super beginDocument];
2745 // Exception during [super beginDocument] means that endDocument will not get called,
2746 // so we need to clean up our "print mode" here.
2747 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2748 [[self window] setAutodisplay:YES];
2754 [super endDocument];
2755 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
2756 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2757 [[self window] setAutodisplay:YES];
2760 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2762 // Work around this bug:
2763 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2764 [NSKeyBindingManager sharedKeyBindingManager];
2766 // Use the isEditable state to determine whether or not to process tab key events.
2767 // The idea here is that isEditable will be NO when this WebView is being used
2768 // in a browser, and we desire the behavior where tab moves to the next element
2769 // in tab order. If isEditable is YES, it is likely that the WebView is being
2770 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2771 // in a text editor.
2772 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
2775 // Now process the key normally
2776 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2780 - (void)keyDown:(NSEvent *)event
2782 BOOL callSuper = NO;
2784 _private->keyDownEvent = event;
2786 WebBridge *bridge = [self _bridge];
2787 if ([bridge interceptKeyEvent:event toView:self]) {
2788 // WebCore processed a key event, bail on any outstanding complete: UI
2789 [_private->compController endRevertingChange:YES moveLeft:NO];
2790 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2791 // Consumed by complete: popup window
2793 // We're going to process a key event, bail on any outstanding complete: UI
2794 [_private->compController endRevertingChange:YES moveLeft:NO];
2795 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2796 // Consumed by key bindings manager.
2802 [super keyDown:event];
2804 [NSCursor setHiddenUntilMouseMoves:YES];
2807 _private->keyDownEvent = nil;
2810 - (void)keyUp:(NSEvent *)event
2812 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2813 [super keyUp:event];
2817 - (id)accessibilityAttributeValue:(NSString*)attributeName
2819 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2820 id accTree = [[self _bridge] accessibilityTree];
2822 return [NSArray arrayWithObject: accTree];
2825 return [super accessibilityAttributeValue:attributeName];
2828 - (id)accessibilityFocusedUIElement
2830 id accTree = [[self _bridge] accessibilityTree];
2832 return [accTree accessibilityFocusedUIElement];
2837 - (id)accessibilityHitTest:(NSPoint)point
2839 id accTree = [[self _bridge] accessibilityTree];
2841 NSPoint windowCoord = [[self window] convertScreenToBase: point];
2842 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2848 - (void)centerSelectionInVisibleArea:(id)sender
2850 [[self _bridge] centerSelectionInVisibleArea];
2853 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2855 WebBridge *bridge = [self _bridge];
2856 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2857 WebView *webView = [self _webView];
2858 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2859 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2863 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
2865 WebBridge *bridge = [self _bridge];
2866 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
2867 WebView *webView = [self _webView];
2868 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2869 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
2873 - (void)moveBackward:(id)sender
2875 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2878 - (void)moveBackwardAndModifySelection:(id)sender
2880 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2883 - (void)moveDown:(id)sender
2885 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2888 - (void)moveDownAndModifySelection:(id)sender
2890 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2893 - (void)moveForward:(id)sender
2895 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2898 - (void)moveForwardAndModifySelection:(id)sender
2900 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2903 - (void)moveLeft:(id)sender
2905 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2908 - (void)moveLeftAndModifySelection:(id)sender
2910 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2913 - (void)moveRight:(id)sender
2915 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2918 - (void)moveRightAndModifySelection:(id)sender
2920 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2923 - (void)moveToBeginningOfDocument:(id)sender
2925 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2928 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2930 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2933 - (void)moveToBeginningOfLine:(id)sender
2935 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2938 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
2940 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2943 - (void)moveToBeginningOfParagraph:(id)sender
2945 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2948 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
2950 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2953 - (void)moveToEndOfDocument:(id)sender
2955 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2958 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
2960 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2963 - (void)moveToEndOfLine:(id)sender
2965 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
2968 - (void)moveToEndOfLineAndModifySelection:(id)sender
2970 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
2973 - (void)moveToEndOfParagraph:(id)sender
2975 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2978 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
2980 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2983 - (void)moveParagraphBackwardAndModifySelection:(id)sender
2985 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
2988 - (void)moveParagraphForwardAndModifySelection:(id)sender
2990 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
2993 - (void)moveUp:(id)sender
2995 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
2998 - (void)moveUpAndModifySelection:(id)sender
3000 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3003 - (void)moveWordBackward:(id)sender
3005 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3008 - (void)moveWordBackwardAndModifySelection:(id)sender
3010 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3013 - (void)moveWordForward:(id)sender
3015 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3018 - (void)moveWordForwardAndModifySelection:(id)sender
3020 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3023 - (void)moveWordLeft:(id)sender
3025 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3028 - (void)moveWordLeftAndModifySelection:(id)sender
3030 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3033 - (void)moveWordRight:(id)sender
3035 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3038 - (void)moveWordRightAndModifySelection:(id)sender
3040 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3043 - (void)pageUp:(id)sender
3045 WebFrameView *frameView = [self _web_parentWebFrameView];
3046 if (frameView == nil)
3048 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3051 - (void)pageDown:(id)sender
3053 WebFrameView *frameView = [self _web_parentWebFrameView];
3054 if (frameView == nil)
3056 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3059 - (void)pageUpAndModifySelection:(id)sender
3061 WebFrameView *frameView = [self _web_parentWebFrameView];
3062 if (frameView == nil)
3064 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3067 - (void)pageDownAndModifySelection:(id)sender
3069 WebFrameView *frameView = [self _web_parentWebFrameView];
3070 if (frameView == nil)
3072 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3075 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3077 WebBridge *bridge = [self _bridge];
3078 DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3079 if (range && ![range collapsed]) {
3080 WebView *webView = [self _webView];
3081 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3082 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
3087 - (void)selectParagraph:(id)sender
3089 [self _expandSelectionToGranularity:WebSelectByParagraph];
3092 - (void)selectLine:(id)sender
3094 [self _expandSelectionToGranularity:WebSelectByLine];
3097 - (void)selectWord:(id)sender
3099 [self _expandSelectionToGranularity:WebSelectByWord];
3102 - (void)copy:(id)sender
3104 if ([[self _bridge] tryDHTMLCopy]) {
3105 return; // DHTML did the whole operation
3107 if (![self _canCopy]) {
3111 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3114 - (void)delete:(id)sender
3116 if (![self _canDelete]) {
3120 [self _deleteSelection];
3123 - (void)cut:(id)sender
3125 WebBridge *bridge = [self _bridge];
3126 if ([bridge tryDHTMLCut]) {
3127 return; // DHTML did the whole operation
3129 if (![self _canCut]) {
3133 DOMRange *range = [self _selectedRange];
3134 if ([self _shouldDeleteRange:range]) {
3135 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3136 [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3140 - (void)paste:(id)sender
3142 if ([[self _bridge] tryDHTMLPaste]) {
3143 return; // DHTML did the whole operation
3145 if (![self _canPaste]) {
3148 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3151 - (NSData *)_selectionStartFontAttributesAsRTF
3153 NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3154 attributes:[[self _bridge] fontAttributesForSelectionStart]];
3155 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3160 - (NSDictionary *)_fontAttributesFromFontPasteboard
3162 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3163 if (fontPasteboard == nil)
3165 NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3166 if (data == nil || [data length] == 0)
3168 // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3169 NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3170 if (string == nil || [string length] == 0)
3172 return [string fontAttributesInRange:NSMakeRange(0, 1)];
3175 - (DOMCSSStyleDeclaration *)_emptyStyle
3177 return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3180 - (NSString *)_colorAsString:(NSColor *)color
3182 NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3183 // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3184 // of fancy color that can't be converted to RGB. Changing that to "transparent"
3185 // might not be great, but it's probably OK.
3186 if (rgbColor == nil)
3187 return @"transparent";
3188 float r = [rgbColor redComponent];
3189 float g = [rgbColor greenComponent];
3190 float b = [rgbColor blueComponent];
3191 float a = [rgbColor alphaComponent];
3193 return @"transparent";
3194 if (r == 0 && g == 0 && b == 0 && a == 1)
3196 if (r == 1 && g == 1 && b == 1 && a == 1)
3198 // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3200 return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3201 return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3204 - (NSString *)_shadowAsString:(NSShadow *)shadow
3208 NSSize offset = [shadow shadowOffset];
3209 float blurRadius = [shadow shadowBlurRadius];
3210 if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3212 NSColor *color = [shadow shadowColor];
3215 // FIXME: Handle non-integral values here?
3216 if (blurRadius == 0)
3217 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3218 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3221 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3223 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3225 NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3226 [style setBackgroundColor:[self _colorAsString:color]];
3228 NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3230 [style setFontFamily:@"Helvetica"];
3231 [style setFontSize:@"12px"];
3232 [style setFontWeight:@"normal"];
3233 [style setFontStyle:@"normal"];
3235 NSFontManager *fm = [NSFontManager sharedFontManager];
3236 [style setFontFamily:[font familyName]];
3237 [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3238 if ([fm weightOfFont:font] >= 9) {
3239 [style setFontWeight:@"bold"];
3241 [style setFontWeight:@"normal"];
3243 if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3244 [style setFontStyle:@"italic"];
3246 [style setFontStyle:@"normal"];
3250 color = [dictionary objectForKey:NSForegroundColorAttributeName];
3251 [style setColor:color ? [self _colorAsString:color] : @"black"];
3253 NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3254 [style setTextShadow:[self _shadowAsString:shadow]];
3256 // FIXME: NSStrikethroughStyleAttributeName
3258 int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3259 if (superscriptInt > 0)
3260 [style setVerticalAlign:@"super"];
3261 else if (superscriptInt < 0)
3262 [style setVerticalAlign:@"sub"];
3264 [style setVerticalAlign:@"baseline"];
3266 // FIXME: NSUnderlineStyleAttributeName
3271 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3273 if (style == nil || [style length] == 0 || ![self _canEdit])
3275 WebView *webView = [self _webView];
3276 WebBridge *bridge = [self _bridge];
3277 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3278 [bridge applyStyle:style withUndoAction:undoAction];
3284 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3285 [style setFontWeight:@"bold"];
3286 if ([[self _bridge] selectionStartHasStyle:style])
3287 [style setFontWeight:@"normal"];
3288 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3291 - (void)_toggleItalic
3293 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3294 [style setFontStyle:@"italic"];
3295 if ([[self _bridge] selectionStartHasStyle:style])
3296 [style setFontStyle:@"normal"];
3297 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3300 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3302 ASSERT([self _webView]);
3303 if (![[[self _webView] preferences] respectStandardStyleKeyEquivalents]) {
3307 if (![self _canEdit])
3310 NSString *string = [event charactersIgnoringModifiers];
3311 if ([string isEqualToString:@"b"]) {
3315 if ([string isEqualToString:@"i"]) {
3316 [self _toggleItalic];
3323 - (BOOL)performKeyEquivalent:(NSEvent *)event
3325 if ([self _handleStyleKeyEquivalent:event]) {
3329 // Pass command-key combos through WebCore if there is a key binding available for
3330 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3331 // But don't do it if we have already handled the event.
3332 if (event != _private->keyDownEvent
3333 && [self _web_firstResponderIsSelfOrDescendantView]
3334 && [[self _bridge] interceptKeyEvent:event toView:self]) {
3337 return [super performKeyEquivalent:event];
3340 - (void)copyFont:(id)sender
3342 // Put RTF with font attributes on the pasteboard.
3343 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3344 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3345 [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3346 [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3349 - (void)pasteFont:(id)sender
3351 // Read RTF with font attributes from the pasteboard.
3352 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3353 [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]] withUndoAction:WebUndoActionPasteFont];
3356 - (void)pasteAsPlainText:(id)sender
3358 if (![self _canEdit])
3361 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3362 NSString *text = [pasteboard stringForType:NSStringPboardType];
3363 WebBridge *bridge = [self _bridge];
3364 if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3365 [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3369 - (void)pasteAsRichText:(id)sender
3371 // Since rich text always beats plain text when both are on the pasteboard, it's not
3372 // clear how this is different from plain old paste.
3373 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3376 - (NSFont *)_originalFontA
3378 return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:5 size:10];
3381 - (NSFont *)_originalFontB
3383 return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12];
3386 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3388 if (a == nil || b == nil)
3391 NSFontManager *fm = [NSFontManager sharedFontManager];
3393 NSFont *oa = [self _originalFontA];
3395 NSString *fa = [a familyName];
3396 NSString *fb = [b familyName];
3397 if ([fa isEqualToString:fb]) {
3398 [style setFontFamily:fa];
3401 int sa = [a pointSize];
3402 int sb = [b pointSize];
3403 int soa = [oa pointSize];
3405 [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
3406 } else if (sa < soa) {
3407 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel smaller
3408 } else if (sa > soa) {
3409 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel larger
3412 int wa = [fm weightOfFont:a];
3413 int wb = [fm weightOfFont:b];
3416 [style setFontWeight:@"bold"];
3418 [style setFontWeight:@"normal"];
3422 BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3423 BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3426 [style setFontStyle:@"italic"];
3428 [style setFontStyle:@"normal"];
3433 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3435 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3437 NSFontManager *fm = [NSFontManager sharedFontManager];
3439 NSFont *oa = [self _originalFontA];
3440 NSFont *ob = [self _originalFontB];
3441 [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
3446 - (void)changeFont:(id)sender
3448 [self _applyStyleToSelection:[self _styleFromFontManagerOperation] withUndoAction:WebUndoActionSetFont];
3451 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
3453 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3455 NSShadow *shadow = [[NSShadow alloc] init];
3456 [shadow setShadowOffset:NSMakeSize(1, 1)];
3458 NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
3459 [self _originalFontA], NSFontAttributeName,
3461 NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
3462 [NSColor blackColor], NSBackgroundColorAttributeName,
3463 [self _originalFontB], NSFontAttributeName,
3464 [NSColor whiteColor], NSForegroundColorAttributeName,
3465 shadow, NSShadowAttributeName,
3466 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
3467 [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
3468 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
3475 NSObliquenessAttributeName /* float; skew to be applied to glyphs, default 0: no skew */
3476 // font-style, but that is just an on-off switch
3478 NSExpansionAttributeName /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
3481 NSKernAttributeName /* float, amount to modify default kerning, if 0, kerning off */
3482 // letter-spacing? probably not good enough
3484 NSUnderlineColorAttributeName /* NSColor, default nil: same as foreground color */
3485 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
3486 // text-decoration-color?
3488 NSLigatureAttributeName /* int, default 1: default ligatures, 0: no ligatures, 2: all ligature