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 [self _setToolTip:[element objectForKey:WebCoreElementTitleKey]];
828 + (NSArray *)_insertablePasteboardTypes
830 static NSArray *types = nil;
832 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
833 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
834 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
839 + (NSArray *)_selectionPasteboardTypes
841 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
842 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
845 - (WebArchive *)_selectedArchive
849 double start = CFAbsoluteTimeGetCurrent();
851 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
853 double duration = CFAbsoluteTimeGetCurrent() - start;
854 LOG(Timing, "copying markup took %f seconds.", duration);
857 return [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
860 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
862 ASSERT([self _hasSelection]);
863 NSArray *types = [self pasteboardTypesForSelection];
864 [pasteboard declareTypes:types owner:nil];
865 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
868 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
870 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
872 BOOL drawURLString = YES;
873 BOOL clipURLString = NO, clipLabelString = NO;
875 NSString *label = [element objectForKey: WebElementLinkLabelKey];
876 NSString *urlString = [linkURL _web_userVisibleString];
883 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
884 toHaveTrait:NSBoldFontMask];
885 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
887 labelSize.width = [label _web_widthWithFont: labelFont];
888 labelSize.height = [labelFont ascender] - [labelFont descender];
889 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
890 labelSize.width = MAX_DRAG_LABEL_WIDTH;
891 clipLabelString = YES;
894 NSSize imageSize, urlStringSize;
895 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
896 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
898 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
899 urlStringSize.height = [urlFont ascender] - [urlFont descender];
900 imageSize.height += urlStringSize.height;
901 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
902 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
905 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
908 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
909 [dragImage lockFocus];
911 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
913 // Drag a rectangle with rounded corners/
914 NSBezierPath *path = [NSBezierPath bezierPath];
915 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
916 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
917 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
918 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
920 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
921 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
922 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
925 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
926 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
929 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
931 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
932 withTopColor:topColor bottomColor:bottomColor font:urlFont];
936 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
937 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
938 withTopColor:topColor bottomColor:bottomColor font:labelFont];
940 [dragImage unlockFocus];
945 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
947 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
948 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
950 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
951 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
952 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
954 [_private->draggingImageURL release];
955 _private->draggingImageURL = nil;
957 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
958 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
959 NSImage *dragImage = nil;
962 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
963 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
964 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
966 dragImage = wcDragImage;
967 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
968 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
971 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
973 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
975 _private->dragOffset = wcDragLoc;
978 WebView *webView = [self _webView];
979 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
980 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
981 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
983 // note per kwebster, the offset arg below is always ignored in positioning the image
984 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
986 if (!dhtmlWroteData) {
987 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
988 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
989 ASSERT(imageElement != nil);
990 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityUpstream];
991 _private->draggingImageURL = [imageURL retain];
992 source = [pasteboard _web_declareAndWriteDragImage:image
993 URL:linkURL ? linkURL : imageURL
994 title:[element objectForKey:WebElementImageAltStringKey]
995 archive:[imageElement webArchive]
998 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
999 if (dragImage == nil) {
1000 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1001 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1002 event:_private->mouseDownEvent
1003 pasteboard:pasteboard
1005 offset:&_private->dragOffset];
1007 [self dragImage:dragImage
1010 event:_private->mouseDownEvent
1011 pasteboard:pasteboard
1015 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1016 if (!dhtmlWroteData) {
1017 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1018 [pasteboard declareTypes:types owner:self];
1019 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1021 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1022 if (dragImage == nil) {
1023 dragImage = [self _dragImageForLinkElement:element];
1024 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1025 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1026 _private->dragOffset.x = offset.width;
1027 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1029 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1030 // a flash of the image at the mouseDown location when the drag starts.
1031 [self dragImage:dragImage
1034 event:mouseDraggedEvent
1035 pasteboard:pasteboard
1038 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1039 if (!dhtmlWroteData) {
1040 [self _writeSelectionToPasteboard:pasteboard];
1042 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1043 if (dragImage == nil) {
1044 dragImage = [[self _bridge] selectionImage];
1045 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1046 NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
1047 dragLoc = NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect));
1048 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1049 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1051 [self dragImage:dragImage
1054 event:_private->mouseDownEvent
1055 pasteboard:pasteboard
1058 } else if (srcIsDHTML) {
1059 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1060 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1061 if (dragImage == nil) {
1062 // WebCore should have given us an image, but we'll make one up
1063 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1064 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1065 NSSize imageSize = [dragImage size];
1066 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1067 _private->dragOffset.x = imageSize.width/2;
1068 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1070 [self dragImage:dragImage
1073 event:_private->mouseDownEvent
1074 pasteboard:pasteboard
1078 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1079 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1085 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1087 [self autoscroll:event];
1088 [self _startAutoscrollTimer:event];
1091 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1093 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1094 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1096 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1097 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1098 [[WebPreferences standardPreferences] loadsImagesAutomatically] &&
1099 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1103 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1104 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1108 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1109 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1116 - (WebPluginController *)_pluginController
1118 return _private->pluginController;
1121 - (void)_web_setPrintingModeRecursive
1123 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1124 [super _web_setPrintingModeRecursive];
1127 - (void)_web_clearPrintingModeRecursive
1129 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1130 [super _web_clearPrintingModeRecursive];
1133 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1135 ASSERT(!_private->subviewsSetAside);
1136 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1138 if (!testDirtyRect || [self needsDisplay]) {
1139 if (testDirtyRect) {
1140 NSRect dirtyRect = [self _dirtyRect];
1141 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1143 if (!NSIsEmptyRect(displayRect)) {
1144 if ([[self _bridge] needsLayout])
1145 _private->needsLayout = YES;
1146 if (_private->needsToApplyStyles || _private->needsLayout)
1151 [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
1154 - (NSRect)_selectionRect
1156 return [[self _bridge] selectionRect];
1159 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1161 if (_private->autoscrollTimer == nil) {
1162 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1163 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1164 _private->autoscrollTriggerEvent = [triggerEvent retain];
1168 - (void)_stopAutoscrollTimer
1170 NSTimer *timer = _private->autoscrollTimer;
1171 _private->autoscrollTimer = nil;
1172 [_private->autoscrollTriggerEvent release];
1173 _private->autoscrollTriggerEvent = nil;
1182 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1183 // a mouse up event.
1184 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1186 [self _stopAutoscrollTimer];
1190 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1191 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1192 modifierFlags:[[NSApp currentEvent] modifierFlags]
1193 timestamp:[NSDate timeIntervalSinceReferenceDate]
1194 windowNumber:[[self window] windowNumber]
1195 context:[[NSApp currentEvent] context]
1196 eventNumber:0 clickCount:0 pressure:0];
1197 [self mouseDragged:fakeEvent];
1202 // Copying can be done regardless of whether you can edit.
1203 return [self _hasSelection];
1208 return [self _hasSelection] && [self _isEditable];
1213 return [self _hasSelection] && [self _isEditable];
1218 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1223 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1226 - (BOOL)_hasSelection
1228 return [[self _bridge] selectionState] == WebSelectionStateRange;
1231 - (BOOL)_hasSelectionOrInsertionPoint
1233 return [[self _bridge] selectionState] != WebSelectionStateNone;
1238 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1241 - (BOOL)_isSelectionMisspelled
1243 NSString *selectedString = [self selectedString];
1244 unsigned length = [selectedString length];
1248 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1252 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1254 return range.length == length;
1257 - (NSArray *)_guessesForMisspelledSelection
1259 ASSERT([[self selectedString] length] != 0);
1260 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1263 - (void)_changeSpellingFromMenu:(id)sender
1265 ASSERT([[self selectedString] length] != 0);
1266 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1269 - (void)_ignoreSpellingFromMenu:(id)sender
1271 ASSERT([[self selectedString] length] != 0);
1272 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1275 - (void)_learnSpellingFromMenu:(id)sender
1277 ASSERT([[self selectedString] length] != 0);
1278 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1281 #if APPKIT_CODE_FOR_REFERENCE
1283 - (void)_openLinkFromMenu:(id)sender
1285 NSTextStorage *text = _getTextStorage(self);
1286 NSRange charRange = [self selectedRange];
1287 if (charRange.location != NSNotFound && charRange.length > 0) {
1288 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1290 [self clickedOnLink:link atIndex:charRange.location];
1292 NSString *string = [[text string] substringWithRange:charRange];
1293 link = [NSURL URLWithString:string];
1294 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1301 - (BOOL)_transparentBackground
1303 return _private->transparentBackground;
1306 - (void)_setTransparentBackground:(BOOL)f
1308 _private->transparentBackground = f;
1313 @implementation NSView (WebHTMLViewFileInternal)
1315 - (void)_web_setPrintingModeRecursive
1317 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1320 - (void)_web_clearPrintingModeRecursive
1322 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1325 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1327 unsigned index, count;
1328 for (index = 0, count = [_subviews count]; index < count; index++) {
1329 NSView *subview = [_subviews objectAtIndex:index];
1330 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1331 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1337 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1339 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1341 if (object == nil) {
1342 [self removeObjectForKey:key];
1344 [self setObject:object forKey:key];
1350 // The following is a workaround for
1351 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1352 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1353 // Since the category will be searched before the real class, we'll prevent the flag from being
1354 // set on the tool tip panel.
1356 @interface NSToolTipPanel : NSPanel
1359 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1362 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1364 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1366 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1372 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1375 @interface NSArray (WebHTMLView)
1376 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1379 @implementation WebHTMLView
1383 WebKitInitializeUnicode();
1384 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1385 returnTypes:[[self class] _insertablePasteboardTypes]];
1386 _NSInitializeKillRing();
1389 - (id)initWithFrame:(NSRect)frame
1391 [super initWithFrame:frame];
1393 // Make all drawing go through us instead of subviews.
1394 if (NSAppKitVersionNumber >= 711) {
1395 [self _setDrawsOwnDescendants:YES];
1398 _private = [[WebHTMLViewPrivate alloc] init];
1400 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1401 _private->needsLayout = YES;
1408 [self _clearLastHitViewIfSelf];
1410 [[NSNotificationCenter defaultCenter] removeObserver:self];
1411 [_private->pluginController destroyAllPlugins];
1419 [self _clearLastHitViewIfSelf];
1421 [[NSNotificationCenter defaultCenter] removeObserver:self];
1422 [_private->pluginController destroyAllPlugins];
1427 - (IBAction)takeFindStringFromSelection:(id)sender
1429 if (![self _hasSelection]) {
1434 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1437 - (NSArray *)pasteboardTypesForSelection
1439 if ([self _canSmartCopyOrDelete]) {
1440 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1441 [types addObject:WebSmartPastePboardType];
1444 return [[self class] _selectionPasteboardTypes];
1448 // This method is copied from NSTextView
1449 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
1451 NSRange attachmentRange;
1452 NSString *originalString = [originalAttributedString string];
1453 static NSString *attachmentCharString = nil;
1455 if (!attachmentCharString) {
1457 if (!attachmentCharString) {
1458 chars[0] = NSAttachmentCharacter;
1460 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
1464 attachmentRange = [originalString rangeOfString:attachmentCharString];
1465 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1466 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
1468 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1469 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
1470 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
1472 return newAttributedString;
1474 return originalAttributedString;
1478 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1480 // Put HTML on the pasteboard.
1481 if ([types containsObject:WebArchivePboardType]) {
1482 WebArchive *archive = [self _selectedArchive];
1483 [pasteboard setData:[archive data] forType:WebArchivePboardType];
1486 // Put the attributed string on the pasteboard (RTF/RTFD format).
1487 NSAttributedString *attributedString = nil;
1488 if ([types containsObject:NSRTFDPboardType]) {
1489 attributedString = [self selectedAttributedString];
1490 if ([attributedString containsAttachments]) {
1491 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1492 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
1495 if ([types containsObject:NSRTFPboardType]) {
1496 if (attributedString == nil) {
1497 attributedString = [self selectedAttributedString];
1499 if ([attributedString containsAttachments]) {
1500 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
1502 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1503 [pasteboard setData:RTFData forType:NSRTFPboardType];
1506 // Put plain string on the pasteboard.
1507 if ([types containsObject:NSStringPboardType]) {
1508 // Map to a plain old space because this is better for source code, other browsers do it,
1509 // and because HTML forces you to do this any time you want two spaces in a row.
1510 NSMutableString *s = [[self selectedString] mutableCopy];
1511 const unichar NonBreakingSpaceCharacter = 0xA0;
1512 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1513 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1514 [pasteboard setString:s forType:NSStringPboardType];
1518 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
1519 [pasteboard setData:nil forType:WebSmartPastePboardType];
1523 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1525 [pasteboard declareTypes:types owner:nil];
1526 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1530 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1532 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1536 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1538 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1540 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1543 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1546 - (void)selectAll:(id)sender
1551 - (void)jumpToSelection: sender
1553 [[self _bridge] jumpToSelection];
1556 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1558 SEL action = [item action];
1559 WebBridge *bridge = [self _bridge];
1561 if (action == @selector(cut:)) {
1562 return [bridge mayDHTMLCut] || [self _canDelete];
1563 } else if (action == @selector(copy:)) {
1564 return [bridge mayDHTMLCopy] || [self _canCopy];
1565 } else if (action == @selector(delete:)) {
1566 return [self _canDelete];
1567 } else if (action == @selector(paste:)) {
1568 return [bridge mayDHTMLPaste] || [self _canPaste];
1569 } else if (action == @selector(takeFindStringFromSelection:)) {
1570 return [self _hasSelection];
1571 } else if (action == @selector(jumpToSelection:)) {
1572 return [self _hasSelection];
1573 } else if (action == @selector(checkSpelling:)
1574 || action == @selector(showGuessPanel:)
1575 || action == @selector(changeSpelling:)
1576 || action == @selector(ignoreSpelling:)) {
1577 return [[self _bridge] isSelectionEditable];
1583 - (BOOL)acceptsFirstResponder
1585 // Don't accept first responder when we first click on this view.
1586 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1587 // Do accept first responder at any other time, for example from keyboard events,
1588 // or from calls back from WebCore once we begin mouse-down event handling.
1589 NSEvent *event = [NSApp currentEvent];
1590 if ([event type] == NSLeftMouseDown
1591 && !_private->handlingMouseDownEvent
1592 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1598 - (BOOL)maintainsInactiveSelection
1600 // This method helps to determing whether the view should maintain
1601 // an inactive selection when the view is not first responder.
1602 // Traditionally, these views have not maintained such selections,
1603 // clearing them when the view was not first responder. However,
1604 // to fix bugs like this one:
1605 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
1606 // when they're not firstResponder"
1607 // it was decided to add a switch to act more like an NSTextView.
1608 // For now, however, the view only acts in this way when the
1609 // web view is set to be editable. This will maintain traditional
1610 // behavior for WebKit clients dating back to before this change,
1611 // and will likely be a decent switch for the long term, since
1612 // clients to ste the web view to be editable probably want it
1613 // to act like a "regular" Cocoa view in terms of its selection
1615 if (![[self _webView] isEditable])
1618 id nextResponder = [[self window] _newFirstResponderAfterResigning];
1619 return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1622 - (void)addMouseMovedObserver
1624 // Always add a mouse move observer if the DB requested, or if we're the key window.
1625 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1626 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1627 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1628 name:NSMouseMovedNotification object:nil];
1629 [self _frameOrBoundsChanged];
1633 - (void)removeMouseMovedObserver
1635 // Don't remove the observer if we're running the DB
1636 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1639 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1640 [[NSNotificationCenter defaultCenter] removeObserver:self
1641 name:NSMouseMovedNotification object:nil];
1644 - (void)updateFocusDisplay
1646 // This method does the job of updating the view based on the view's firstResponder-ness and
1647 // the window key-ness of the window containing this view. This involves three kinds of
1648 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
1650 // The three display attributes are as follows:
1652 // 1. The background color used to draw behind selected content (active | inactive color)
1653 // 2. Caret blinking (blinks | does not blink)
1654 // 3. The drawing of a focus ring around links in web pages.
1656 BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1657 [[self _bridge] setDisplaysWithFocusAttributes:flag];
1660 - (void)addSuperviewObservers
1662 // We watch the bounds of our superview, so that we can do a layout when the size
1663 // of the superview changes. This is different from other scrollable things that don't
1664 // need this kind of thing because their layout doesn't change.
1666 // We need to pay attention to both height and width because our "layout" has to change
1667 // to extend the background the full height of the space and because some elements have
1668 // sizes that are based on the total size of the view.
1670 NSView *superview = [self superview];
1671 if (superview && [self window]) {
1672 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1673 name:NSViewFrameDidChangeNotification object:superview];
1674 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1675 name:NSViewBoundsDidChangeNotification object:superview];
1679 - (void)removeSuperviewObservers
1681 NSView *superview = [self superview];
1682 if (superview && [self window]) {
1683 [[NSNotificationCenter defaultCenter] removeObserver:self
1684 name:NSViewFrameDidChangeNotification object:superview];
1685 [[NSNotificationCenter defaultCenter] removeObserver:self
1686 name:NSViewBoundsDidChangeNotification object:superview];
1690 - (void)addWindowObservers
1692 NSWindow *window = [self window];
1694 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1695 name:NSWindowDidBecomeKeyNotification object:window];
1696 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1697 name:NSWindowDidResignKeyNotification object:window];
1698 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1699 name:NSWindowWillCloseNotification object:window];
1703 - (void)removeWindowObservers
1705 NSWindow *window = [self window];
1707 [[NSNotificationCenter defaultCenter] removeObserver:self
1708 name:NSWindowDidBecomeKeyNotification object:window];
1709 [[NSNotificationCenter defaultCenter] removeObserver:self
1710 name:NSWindowDidResignKeyNotification object:window];
1711 [[NSNotificationCenter defaultCenter] removeObserver:self
1712 name:NSWindowWillCloseNotification object:window];
1716 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1718 [self removeSuperviewObservers];
1721 - (void)viewDidMoveToSuperview
1723 // Do this here in case the text size multiplier changed when a non-HTML
1724 // view was installed.
1725 if ([self superview] != nil) {
1726 [self _updateTextSizeMultiplier];
1727 [self addSuperviewObservers];
1731 - (void)viewWillMoveToWindow:(NSWindow *)window
1733 // Don't do anything if we aren't initialized. This happens
1734 // when decoding a WebView. When WebViews are decoded their subviews
1735 // are created by initWithCoder: and so won't be normally
1736 // initialized. The stub views are discarded by WebView.
1738 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1739 [self removeMouseMovedObserver];
1740 [self removeWindowObservers];
1741 [self removeSuperviewObservers];
1742 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1744 [[self _pluginController] stopAllPlugins];
1748 - (void)viewDidMoveToWindow
1750 // Don't do anything if we aren't initialized. This happens
1751 // when decoding a WebView. When WebViews are decoded their subviews
1752 // are created by initWithCoder: and so won't be normally
1753 // initialized. The stub views are discarded by WebView.
1755 [self _stopAutoscrollTimer];
1756 if ([self window]) {
1757 _private->lastScrollPosition = [[self superview] bounds].origin;
1758 [self addWindowObservers];
1759 [self addSuperviewObservers];
1760 [self addMouseMovedObserver];
1761 // Schedule this update, rather than making the call right now.
1762 // The reason is that placing the caret in the just-installed view requires
1763 // the HTML/XML document to be available on the WebCore side, but it is not
1764 // at the time this code is running. However, it will be there on the next
1765 // crank of the run loop. Doing this helps to make a blinking caret appear
1766 // in a new, empty window "automatic".
1767 [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1769 [[self _pluginController] startAllPlugins];
1771 _private->lastScrollPosition = NSZeroPoint;
1773 _private->inWindow = YES;
1775 // Reset when we are moved out of a window after being moved into one.
1776 // Without this check, we reset ourselves before we even start.
1777 // This is only needed because viewDidMoveToWindow is called even when
1778 // the window is not changing (bug in AppKit).
1779 if (_private->inWindow) {
1781 _private->inWindow = NO;
1787 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1789 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1792 - (void)viewDidMoveToHostWindow
1794 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1798 - (void)addSubview:(NSView *)view
1800 [super addSubview:view];
1802 if ([WebPluginController isPlugInView:view]) {
1803 [[self _pluginController] addPlugin:view];
1807 - (void)reapplyStyles
1809 if (!_private->needsToApplyStyles) {
1814 double start = CFAbsoluteTimeGetCurrent();
1817 [[self _bridge] reapplyStylesForDeviceType:
1818 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1821 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1822 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1825 _private->needsToApplyStyles = NO;
1828 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1829 // minPageWidth==0 implies a non-printing layout
1830 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1832 [self reapplyStyles];
1834 // Ensure that we will receive mouse move events. Is this the best place to put this?
1835 [[self window] setAcceptsMouseMovedEvents: YES];
1836 [[self window] _setShouldPostEventNotifications: YES];
1838 if (!_private->needsLayout) {
1843 double start = CFAbsoluteTimeGetCurrent();
1846 LOG(View, "%@ doing layout", self);
1848 if (minPageWidth > 0.0) {
1849 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1851 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1853 _private->needsLayout = NO;
1855 if (!_private->printing) {
1856 // get size of the containing dynamic scrollview, so
1857 // appearance and disappearance of scrollbars will not show up
1859 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1860 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1861 [[self _bridge] sendResizeEvent];
1863 _private->laidOutAtLeastOnce = YES;
1864 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1865 _private->lastLayoutFrameSize = newLayoutFrameSize;
1869 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1870 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1876 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1879 - (NSMenu *)menuForEvent:(NSEvent *)event
1881 [_private->compController endRevertingChange:NO moveLeft:NO];
1883 if ([[self _bridge] sendContextMenuEvent:event]) {
1886 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1887 NSDictionary *element = [self elementAtPoint:point];
1888 return [[self _webView] _menuForElement:element];
1891 // Search from the end of the currently selected location, or from the beginning of the
1892 // document if nothing is selected.
1893 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1895 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1898 - (DOMRange *)_documentRange
1900 return [[[self _bridge] DOMDocument] _documentRange];
1903 - (NSString *)string
1905 return [[self _bridge] stringForRange:[self _documentRange]];
1908 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
1910 NSAttributedString *attributedString = nil;
1911 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
1913 double start = CFAbsoluteTimeGetCurrent();
1915 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
1917 double duration = CFAbsoluteTimeGetCurrent() - start;
1918 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
1921 return attributedString;
1924 - (NSAttributedString *)attributedString
1926 WebBridge *bridge = [self _bridge];
1927 DOMDocument *document = [bridge DOMDocument];
1928 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
1929 if (attributedString == nil) {
1930 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
1932 return attributedString;
1935 - (NSString *)selectedString
1937 return [[self _bridge] selectedString];
1940 - (NSAttributedString *)selectedAttributedString
1942 WebBridge *bridge = [self _bridge];
1943 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
1944 if (attributedString == nil) {
1945 attributedString = [bridge selectedAttributedString];
1947 return attributedString;
1952 [[self _bridge] selectAll];
1955 // Remove the selection.
1958 [[self _bridge] deselectAll];
1961 - (void)deselectText
1963 [[self _bridge] deselectText];
1968 return [[self _webView] drawsBackground];
1971 - (void)setNeedsDisplay:(BOOL)flag
1973 LOG(View, "%@ flag = %d", self, (int)flag);
1974 [super setNeedsDisplay: flag];
1977 - (void)setNeedsLayout: (BOOL)flag
1979 LOG(View, "%@ flag = %d", self, (int)flag);
1980 _private->needsLayout = flag;
1984 - (void)setNeedsToApplyStyles: (BOOL)flag
1986 LOG(View, "%@ flag = %d", self, (int)flag);
1987 _private->needsToApplyStyles = flag;
1990 - (void)drawRect:(NSRect)rect
1992 LOG(View, "%@ drawing", self);
1994 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
1995 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
1996 // This does a better job of clipping out rects that are entirely outside the visible area.
1997 const NSRect *rects;
1999 [self getRectsBeingDrawn:&rects count:&count];
2001 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2002 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2003 // The reason for the workaround is that this method is called explicitly from the code
2004 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2008 for (i = 0; i < count; ++i) {
2009 rect = NSUnionRect(rect, rects[i]);
2011 if (rect.size.height == 0 || rect.size.width == 0) {
2016 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2017 if (subviewsWereSetAside) {
2018 [self _restoreSubviews];
2022 double start = CFAbsoluteTimeGetCurrent();
2025 [NSGraphicsContext saveGraphicsState];
2028 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2030 [(WebClipView *)[self superview] setAdditionalClip:rect];
2033 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2034 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2035 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2036 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2039 if ([self _transparentBackground]) {
2040 [[NSColor clearColor] set];
2044 //double start = CFAbsoluteTimeGetCurrent();
2045 [[self _bridge] drawRect:rect];
2046 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2048 if (textRendererFactoryIfCoalescing != nil) {
2049 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2052 [(WebClipView *)[self superview] resetAdditionalClip];
2054 [NSGraphicsContext restoreGraphicsState];
2056 [(WebClipView *)[self superview] resetAdditionalClip];
2057 [NSGraphicsContext restoreGraphicsState];
2058 ERROR("Exception caught while drawing: %@", localException);
2059 [localException raise];
2063 NSRect vframe = [self frame];
2064 [[NSColor blackColor] set];
2066 path = [NSBezierPath bezierPath];
2067 [path setLineWidth:(float)0.1];
2068 [path moveToPoint:NSMakePoint(0, 0)];
2069 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2072 path = [NSBezierPath bezierPath];
2073 [path setLineWidth:(float)0.1];
2074 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2075 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2081 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2082 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2085 if (subviewsWereSetAside) {
2086 [self _setAsideSubviews];
2090 // Turn off the additional clip while computing our visibleRect.
2091 - (NSRect)visibleRect
2093 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2094 return [super visibleRect];
2096 WebClipView *clipView = (WebClipView *)[self superview];
2098 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2099 if (!hasAdditionalClip) {
2100 return [super visibleRect];
2103 NSRect additionalClip = [clipView additionalClip];
2104 [clipView resetAdditionalClip];
2105 NSRect visibleRect = [super visibleRect];
2106 [clipView setAdditionalClip:additionalClip];
2115 - (void)windowDidBecomeKey:(NSNotification *)notification
2117 ASSERT([notification object] == [self window]);
2118 [self addMouseMovedObserver];
2119 [self updateFocusDisplay];
2122 - (void)windowDidResignKey: (NSNotification *)notification
2124 ASSERT([notification object] == [self window]);
2125 [_private->compController endRevertingChange:NO moveLeft:NO];
2126 [self removeMouseMovedObserver];
2127 [self updateFocusDisplay];
2130 - (void)windowWillClose:(NSNotification *)notification
2132 [_private->compController endRevertingChange:NO moveLeft:NO];
2133 [[self _pluginController] destroyAllPlugins];
2136 - (void)scrollWheel:(NSEvent *)event
2138 if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2139 [[self nextResponder] scrollWheel:event];
2143 - (BOOL)_isSelectionEvent:(NSEvent *)event
2145 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2146 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2149 - (void)_setMouseDownEvent:(NSEvent *)event
2151 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2153 if (event == _private->mouseDownEvent) {
2158 [_private->mouseDownEvent release];
2159 _private->mouseDownEvent = event;
2161 [_private->firstResponderAtMouseDownTime release];
2162 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2165 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2167 [self _setMouseDownEvent:event];
2169 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2172 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2173 // the purposes of this method we want to really query the deepest view, so we forward to it.
2174 forceRealHitTest = YES;
2175 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2176 forceRealHitTest = NO;
2178 if ([hitView isKindOfClass:[self class]]) {
2179 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2180 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2181 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2183 return [hitView acceptsFirstMouse:event];
2187 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2189 [self _setMouseDownEvent:event];
2191 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2192 // the purposes of this method we want to really query the deepest view, so we forward to it.
2193 forceRealHitTest = YES;
2194 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2195 forceRealHitTest = NO;
2197 if ([hitView isKindOfClass:[self class]]) {
2198 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2199 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2201 return [hitView shouldDelayWindowOrderingForEvent:event];
2205 - (void)mouseDown:(NSEvent *)event
2207 _private->handlingMouseDownEvent = YES;
2209 // Record the mouse down position so we can determine drag hysteresis.
2210 [self _setMouseDownEvent:event];
2212 // TEXTINPUT: if there is marked text and the current input
2213 // manager wants to handle mouse events, we need to make sure to
2214 // pass it to them. If not, then we need to notify the input
2215 // manager when the marked text is abandoned (user clicks outside
2218 [_private->compController endRevertingChange:NO moveLeft:NO];
2220 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2221 // We don't want to pass them along to KHTML a second time.
2222 if (!([event modifierFlags] & NSControlKeyMask)) {
2223 _private->ignoringMouseDraggedEvents = NO;
2225 // Don't do any mouseover while the mouse is down.
2226 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2228 // Let KHTML get a chance to deal with the event. This will call back to us
2229 // to start the autoscroll timer if appropriate.
2230 [[self _bridge] mouseDown:event];
2233 [_private->firstResponderAtMouseDownTime release];
2234 _private->firstResponderAtMouseDownTime = nil;
2236 _private->handlingMouseDownEvent = NO;
2239 - (void)dragImage:(NSImage *)dragImage
2241 offset:(NSSize)offset
2242 event:(NSEvent *)event
2243 pasteboard:(NSPasteboard *)pasteboard
2245 slideBack:(BOOL)slideBack
2247 [self _stopAutoscrollTimer];
2249 _private->initiatedDrag = YES;
2250 [[self _webView] _setInitiatedDrag:YES];
2252 // Retain this view during the drag because it may be released before the drag ends.
2255 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2258 - (void)mouseDragged:(NSEvent *)event
2260 // TEXTINPUT: if there is marked text and the current input
2261 // manager wants to handle mouse events, we need to make sure to
2264 if (!_private->ignoringMouseDraggedEvents) {
2265 [[self _bridge] mouseDragged:event];
2269 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2271 if (_private->webCoreDragOp == NSDragOperationNone) {
2272 return (NSDragOperationGeneric | NSDragOperationCopy);
2274 return _private->webCoreDragOp;
2278 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2280 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2281 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2282 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2285 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2287 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2288 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2289 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2291 _private->initiatedDrag = NO;
2292 [[self _webView] _setInitiatedDrag:NO];
2294 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2295 _private->ignoringMouseDraggedEvents = YES;
2297 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2298 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2299 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2300 location:windowMouseLoc
2301 modifierFlags:[[NSApp currentEvent] modifierFlags]
2302 timestamp:[NSDate timeIntervalSinceReferenceDate]
2303 windowNumber:[[self window] windowNumber]
2304 context:[[NSApp currentEvent] context]
2305 eventNumber:0 clickCount:0 pressure:0];
2306 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2308 // Balance the previous retain from when the drag started.
2312 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2314 ASSERT(_private->draggingImageURL);
2316 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2319 // FIXME: Report an error if we fail to create a file.
2320 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2321 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2322 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2323 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2326 return [NSArray arrayWithObject:[path lastPathComponent]];
2329 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2331 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2332 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2333 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2334 if ([types count] == 0) {
2336 } else if ([types count] == 1 &&
2337 [types containsObject:NSFilenamesPboardType] &&
2338 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2342 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2343 NSDictionary *element = [self elementAtPoint:point];
2344 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2345 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2346 // Can't drag onto the selection being dragged.
2357 return _private->initiatedDrag &&
2358 ([self _isEditable] && [self _hasSelection]) &&
2359 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2362 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2364 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2367 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2369 NSDragOperation operation = NSDragOperationNone;
2371 if (actionMask & WebDragDestinationActionDHTML) {
2372 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2374 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2376 if ((actionMask & WebDragDestinationActionEdit) &&
2377 !_private->webCoreHandlingDrag
2378 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2379 if ([self _isNSColorDrag:draggingInfo]) {
2380 operation = NSDragOperationGeneric;
2383 WebView *webView = [self _webView];
2384 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2385 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2388 [[self _webView] removeDragCaret];
2394 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2396 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2397 [[self _webView] removeDragCaret];
2400 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2402 WebView *webView = [self _webView];
2403 WebBridge *bridge = [self _bridge];
2404 if (_private->webCoreHandlingDrag) {
2405 ASSERT(actionMask & WebDragDestinationActionDHTML);
2406 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2407 [bridge concludeDragForDraggingInfo:draggingInfo];
2409 } else if (actionMask & WebDragDestinationActionEdit) {
2410 if ([self _isNSColorDrag:draggingInfo]) {
2411 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2414 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2415 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2416 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2417 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2418 [bridge applyStyle:style];
2424 BOOL didInsert = NO;
2425 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2426 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2427 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2428 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2429 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2430 if ([self _isMoveDrag]) {
2431 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2432 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2434 [bridge setSelectionToDragCaret];
2435 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2440 [webView removeDragCaret];
2447 - (NSDictionary *)elementAtPoint:(NSPoint)point
2449 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2450 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2452 // Convert URL strings to NSURLs
2453 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2454 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2456 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2457 ASSERT(webFrameView);
2458 WebFrame *webFrame = [webFrameView webFrame];
2461 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2462 if ([frameName length] == 0) {
2463 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2465 WebFrame *wf = [webFrame findFrameNamed:frameName];
2467 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2469 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2472 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2475 return [elementInfo autorelease];
2478 - (void)mouseUp:(NSEvent *)event
2480 // TEXTINPUT: if there is marked text and the current input
2481 // manager wants to handle mouse events, we need to make sure to
2484 [self _stopAutoscrollTimer];
2485 [[self _bridge] mouseUp:event];
2486 [self _updateMouseoverWithFakeEvent];
2489 - (void)mouseMovedNotification:(NSNotification *)notification
2491 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2494 - (BOOL)supportsTextEncoding
2499 - (NSView *)nextValidKeyView
2502 if (![self isHiddenOrHasHiddenAncestor]) {
2503 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2506 view = [super nextValidKeyView];
2511 - (NSView *)previousValidKeyView
2514 if (![self isHiddenOrHasHiddenAncestor]) {
2515 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2518 view = [super previousValidKeyView];
2523 - (BOOL)becomeFirstResponder
2526 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2527 switch ([[self window] keyViewSelectionDirection]) {
2528 case NSDirectSelection:
2530 case NSSelectingNext:
2531 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2533 case NSSelectingPrevious:
2534 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2539 [[self window] makeFirstResponder:view];
2541 [self updateFocusDisplay];
2542 _private->startNewKillRingSequence = YES;
2546 // This approach could be relaxed when dealing with 3228554.
2547 // Some alteration to the selection behavior was done to deal with 3672088.
2548 - (BOOL)resignFirstResponder
2550 BOOL resign = [super resignFirstResponder];
2552 [_private->compController endRevertingChange:NO moveLeft:NO];
2553 _private->resigningFirstResponder = YES;
2554 if (![self maintainsInactiveSelection]) {
2555 if ([[self _webView] _isPerformingProgrammaticFocus]) {
2556 [self deselectText];
2562 [self updateFocusDisplay];
2563 _private->resigningFirstResponder = NO;
2568 //------------------------------------------------------------------------------------
2569 // WebDocumentView protocol
2570 //------------------------------------------------------------------------------------
2571 - (void)setDataSource:(WebDataSource *)dataSource
2575 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2579 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2580 // pageWidth != 0 implies we will relayout to a new width
2581 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2583 WebFrame *frame = [self _frame];
2584 NSArray *subframes = [frame childFrames];
2585 unsigned n = [subframes count];
2587 for (i = 0; i != n; ++i) {
2588 WebFrame *subframe = [subframes objectAtIndex:i];
2589 WebFrameView *frameView = [subframe frameView];
2590 if ([[subframe dataSource] _isDocumentHTML]) {
2591 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2595 if (printing != _private->printing) {
2596 [_private->pageRects release];
2597 _private->pageRects = nil;
2598 _private->printing = printing;
2599 [self setNeedsToApplyStyles:YES];
2600 [self setNeedsLayout:YES];
2601 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2603 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2605 // Can't do this when starting printing or nested printing won't work, see 3491427.
2606 [self setNeedsDisplay:NO];
2611 // This is needed for the case where the webview is embedded in the view that's being printed.
2612 // It shouldn't be called when the webview is being printed directly.
2613 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2615 // This helps when we print as part of a larger print process.
2616 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2617 BOOL wasInPrintingMode = _private->printing;
2618 if (!wasInPrintingMode) {
2619 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2622 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2624 if (!wasInPrintingMode) {
2625 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2629 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2631 NSPrintInfo *printInfo = [printOperation printInfo];
2632 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2635 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2637 float viewWidth = NSWidth([self bounds]);
2638 if (viewWidth < 1) {
2639 ERROR("%@ has no width when printing", self);
2643 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2644 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2645 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2646 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2649 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2650 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2651 // if AppKit makes it SPI/API.
2652 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2654 return [self _scaleFactorForPrintOperation:printOperation];
2657 - (void)setPageWidthForPrinting:(float)pageWidth
2659 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2660 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2664 // Return the number of pages available for printing
2665 - (BOOL)knowsPageRange:(NSRangePointer)range {
2666 // Must do this explicit display here, because otherwise the view might redisplay while the print
2667 // sheet was up, using printer fonts (and looking different).
2668 [self displayIfNeeded];
2669 [[self window] setAutodisplay:NO];
2671 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2672 // according to the paper size
2673 float minLayoutWidth = 0.0;
2674 float maxLayoutWidth = 0.0;
2675 if (![[self _bridge] isFrameSet]) {
2676 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2677 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2678 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2680 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2682 // There is a theoretical chance that someone could do some drawing between here and endDocument,
2683 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2684 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2686 range->location = 1;
2687 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2688 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2689 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2690 [_private->pageRects release];
2691 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2692 printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2693 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2694 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2695 // a blank page (with correct-looking header and footer if that option is on), which matches
2696 // the behavior of IE and Camino at least.
2697 if ([newPageRects count] == 0) {
2698 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2700 _private->pageRects = [newPageRects retain];
2702 range->length = [_private->pageRects count];
2707 // Return the drawing rectangle for a particular page number
2708 - (NSRect)rectForPage:(int)page {
2709 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2712 - (void)drawPageBorderWithSize:(NSSize)borderSize
2714 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
2715 [[self _webView] _drawHeaderAndFooter];
2718 - (void)beginDocument
2721 [super beginDocument];
2723 // Exception during [super beginDocument] means that endDocument will not get called,
2724 // so we need to clean up our "print mode" here.
2725 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2726 [[self window] setAutodisplay:YES];
2732 [super endDocument];
2733 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
2734 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2735 [[self window] setAutodisplay:YES];
2738 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2740 // Work around this bug:
2741 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2742 [NSKeyBindingManager sharedKeyBindingManager];
2744 // Use the isEditable state to determine whether or not to process tab key events.
2745 // The idea here is that isEditable will be NO when this WebView is being used
2746 // in a browser, and we desire the behavior where tab moves to the next element
2747 // in tab order. If isEditable is YES, it is likely that the WebView is being
2748 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2749 // in a text editor.
2750 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
2753 // Now process the key normally
2754 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2758 - (void)keyDown:(NSEvent *)event
2760 BOOL callSuper = NO;
2762 _private->keyDownEvent = event;
2764 WebBridge *bridge = [self _bridge];
2765 if ([bridge interceptKeyEvent:event toView:self]) {
2766 // WebCore processed a key event, bail on any outstanding complete: UI
2767 [_private->compController endRevertingChange:YES moveLeft:NO];
2768 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2769 // Consumed by complete: popup window
2771 // We're going to process a key event, bail on any outstanding complete: UI
2772 [_private->compController endRevertingChange:YES moveLeft:NO];
2773 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2774 // Consumed by key bindings manager.
2780 [super keyDown:event];
2782 [NSCursor setHiddenUntilMouseMoves:YES];
2785 _private->keyDownEvent = nil;
2788 - (void)keyUp:(NSEvent *)event
2790 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2791 [super keyUp:event];
2795 - (id)accessibilityAttributeValue:(NSString*)attributeName
2797 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2798 id accTree = [[self _bridge] accessibilityTree];
2800 return [NSArray arrayWithObject: accTree];
2803 return [super accessibilityAttributeValue:attributeName];
2806 - (id)accessibilityHitTest:(NSPoint)point
2808 id accTree = [[self _bridge] accessibilityTree];
2810 NSPoint windowCoord = [[self window] convertScreenToBase: point];
2811 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2817 - (void)centerSelectionInVisibleArea:(id)sender
2819 [[self _bridge] centerSelectionInVisibleArea];
2822 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2824 WebBridge *bridge = [self _bridge];
2825 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2826 WebView *webView = [self _webView];
2827 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2828 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2832 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
2834 WebBridge *bridge = [self _bridge];
2835 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
2836 WebView *webView = [self _webView];
2837 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2838 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
2842 - (void)moveBackward:(id)sender
2844 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2847 - (void)moveBackwardAndModifySelection:(id)sender
2849 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2852 - (void)moveDown:(id)sender
2854 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2857 - (void)moveDownAndModifySelection:(id)sender
2859 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2862 - (void)moveForward:(id)sender
2864 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2867 - (void)moveForwardAndModifySelection:(id)sender
2869 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2872 - (void)moveLeft:(id)sender
2874 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2877 - (void)moveLeftAndModifySelection:(id)sender
2879 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2882 - (void)moveRight:(id)sender
2884 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2887 - (void)moveRightAndModifySelection:(id)sender
2889 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2892 - (void)moveToBeginningOfDocument:(id)sender
2894 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2897 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2899 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2902 - (void)moveToBeginningOfLine:(id)sender
2904 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2907 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
2909 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2912 - (void)moveToBeginningOfParagraph:(id)sender
2914 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2917 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
2919 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
2922 - (void)moveToEndOfDocument:(id)sender
2924 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2927 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
2929 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
2932 - (void)moveToEndOfLine:(id)sender
2934 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
2937 - (void)moveToEndOfLineAndModifySelection:(id)sender
2939 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
2942 - (void)moveToEndOfParagraph:(id)sender
2944 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2947 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
2949 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
2952 - (void)moveParagraphBackwardAndModifySelection:(id)sender
2954 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
2957 - (void)moveParagraphForwardAndModifySelection:(id)sender
2959 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
2962 - (void)moveUp:(id)sender
2964 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
2967 - (void)moveUpAndModifySelection:(id)sender
2969 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
2972 - (void)moveWordBackward:(id)sender
2974 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
2977 - (void)moveWordBackwardAndModifySelection:(id)sender
2979 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
2982 - (void)moveWordForward:(id)sender
2984 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
2987 - (void)moveWordForwardAndModifySelection:(id)sender
2989 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
2992 - (void)moveWordLeft:(id)sender
2994 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
2997 - (void)moveWordLeftAndModifySelection:(id)sender
2999 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3002 - (void)moveWordRight:(id)sender
3004 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3007 - (void)moveWordRightAndModifySelection:(id)sender
3009 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3012 - (void)pageUp:(id)sender
3014 WebFrameView *frameView = [self _web_parentWebFrameView];
3015 if (frameView == nil)
3017 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3020 - (void)pageDown:(id)sender
3022 WebFrameView *frameView = [self _web_parentWebFrameView];
3023 if (frameView == nil)
3025 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3028 - (void)pageUpAndModifySelection:(id)sender
3030 WebFrameView *frameView = [self _web_parentWebFrameView];
3031 if (frameView == nil)
3033 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3036 - (void)pageDownAndModifySelection:(id)sender
3038 WebFrameView *frameView = [self _web_parentWebFrameView];
3039 if (frameView == nil)
3041 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3044 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3046 WebBridge *bridge = [self _bridge];
3047 DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3048 if (range && ![range collapsed]) {
3049 WebView *webView = [self _webView];
3050 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3051 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
3056 - (void)selectParagraph:(id)sender
3058 [self _expandSelectionToGranularity:WebSelectByParagraph];
3061 - (void)selectLine:(id)sender
3063 [self _expandSelectionToGranularity:WebSelectByLine];
3066 - (void)selectWord:(id)sender
3068 [self _expandSelectionToGranularity:WebSelectByWord];
3071 - (void)copy:(id)sender
3073 if ([[self _bridge] tryDHTMLCopy]) {
3074 return; // DHTML did the whole operation
3076 if (![self _canCopy]) {
3080 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3083 - (void)delete:(id)sender
3085 if (![self _canDelete]) {
3089 [self _deleteSelection];
3092 - (void)cut:(id)sender
3094 WebBridge *bridge = [self _bridge];
3095 if ([bridge tryDHTMLCut]) {
3096 return; // DHTML did the whole operation
3098 if (![self _canCut]) {
3102 DOMRange *range = [self _selectedRange];
3103 if ([self _shouldDeleteRange:range]) {
3104 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3105 [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3109 - (void)paste:(id)sender
3111 if ([[self _bridge] tryDHTMLPaste]) {
3112 return; // DHTML did the whole operation
3114 if (![self _canPaste]) {
3117 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3120 - (NSData *)_selectionStartFontAttributesAsRTF
3122 NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3123 attributes:[[self _bridge] fontAttributesForSelectionStart]];
3124 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3129 - (NSDictionary *)_fontAttributesFromFontPasteboard
3131 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3132 if (fontPasteboard == nil)
3134 NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3135 if (data == nil || [data length] == 0)
3137 // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3138 NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3139 if (string == nil || [string length] == 0)
3141 return [string fontAttributesInRange:NSMakeRange(0, 1)];
3144 - (DOMCSSStyleDeclaration *)_emptyStyle
3146 return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3149 - (NSString *)_colorAsString:(NSColor *)color
3151 NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3152 // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3153 // of fancy color that can't be converted to RGB. Changing that to "transparent"
3154 // might not be great, but it's probably OK.
3155 if (rgbColor == nil)
3156 return @"transparent";
3157 float r = [rgbColor redComponent];
3158 float g = [rgbColor greenComponent];
3159 float b = [rgbColor blueComponent];
3160 float a = [rgbColor alphaComponent];
3162 return @"transparent";
3163 if (r == 0 && g == 0 && b == 0 && a == 1)
3165 if (r == 1 && g == 1 && b == 1 && a == 1)
3167 // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3169 return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3170 return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3173 - (NSString *)_shadowAsString:(NSShadow *)shadow
3177 NSSize offset = [shadow shadowOffset];
3178 float blurRadius = [shadow shadowBlurRadius];
3179 if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3181 NSColor *color = [shadow shadowColor];
3184 // FIXME: Handle non-integral values here?
3185 if (blurRadius == 0)
3186 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3187 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3190 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3192 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3194 NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3195 [style setBackgroundColor:[self _colorAsString:color]];
3197 NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3199 [style setFontFamily:@"Helvetica"];
3200 [style setFontSize:@"12px"];
3201 [style setFontWeight:@"normal"];
3202 [style setFontStyle:@"normal"];
3204 NSFontManager *fm = [NSFontManager sharedFontManager];
3205 [style setFontFamily:[font familyName]];
3206 [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3207 if ([fm weightOfFont:font] >= 9) {
3208 [style setFontWeight:@"bold"];
3210 [style setFontWeight:@"normal"];
3212 if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3213 [style setFontStyle:@"italic"];
3215 [style setFontStyle:@"normal"];
3219 color = [dictionary objectForKey:NSForegroundColorAttributeName];
3220 [style setColor:color ? [self _colorAsString:color] : @"black"];
3222 NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3223 [style setTextShadow:[self _shadowAsString:shadow]];
3225 // FIXME: NSStrikethroughStyleAttributeName
3227 int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3228 if (superscriptInt > 0)
3229 [style setVerticalAlign:@"super"];
3230 else if (superscriptInt < 0)
3231 [style setVerticalAlign:@"sub"];
3233 [style setVerticalAlign:@"baseline"];
3235 // FIXME: NSUnderlineStyleAttributeName
3240 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style
3242 if (style == nil || [style length] == 0 || ![self _canEdit])
3244 WebView *webView = [self _webView];
3245 WebBridge *bridge = [self _bridge];
3246 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3247 [bridge applyStyle:style];
3253 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3254 [style setFontWeight:@"bold"];
3255 if ([[self _bridge] selectionStartHasStyle:style])
3256 [style setFontWeight:@"normal"];
3257 [self _applyStyleToSelection:style];
3260 - (void)_toggleItalic
3262 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3263 [style setFontStyle:@"italic"];
3264 if ([[self _bridge] selectionStartHasStyle:style])
3265 [style setFontStyle:@"normal"];
3266 [self _applyStyleToSelection:style];
3269 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3271 if (![[WebPreferences standardPreferences] respectStandardStyleKeyEquivalents]) {
3275 if (![self _canEdit])
3278 NSString *string = [event charactersIgnoringModifiers];
3279 if ([string isEqualToString:@"b"]) {
3283 if ([string isEqualToString:@"i"]) {
3284 [self _toggleItalic];
3291 - (BOOL)performKeyEquivalent:(NSEvent *)event
3293 if ([self _handleStyleKeyEquivalent:event]) {
3297 // Pass command-key combos through WebCore if there is a key binding available for
3298 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3299 // But don't do it if we have already handled the event.
3300 if (event != _private->keyDownEvent
3301 && [self _web_firstResponderIsSelfOrDescendantView]
3302 && [[self _bridge] interceptKeyEvent:event toView:self]) {
3305 return [super performKeyEquivalent:event];
3308 - (void)copyFont:(id)sender
3310 // Put RTF with font attributes on the pasteboard.
3311 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3312 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3313 [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3314 [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3317 - (void)pasteFont:(id)sender
3319 // Read RTF with font attributes from the pasteboard.
3320 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3321 [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]]];
3324 - (void)pasteAsPlainText:(id)sender
3326 if (![self _canEdit])
3329 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3330 NSString *text = [pasteboard stringForType:NSStringPboardType];
3331 WebBridge *bridge = [self _bridge];
3332 if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3333 [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3337 - (void)pasteAsRichText:(id)sender
3339 // Since rich text always beats plain text when both are on the pasteboard, it's not
3340 // clear how this is different from plain old paste.
3341 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3344 - (NSFont *)_originalFontA
3346 return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:5 size:10];
3349 - (NSFont *)_originalFontB
3351 return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12];
3354 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3356 if (a == nil || b == nil)
3359 NSFontManager *fm = [NSFontManager sharedFontManager];
3361 NSFont *oa = [self _originalFontA];
3363 NSString *fa = [a familyName];
3364 NSString *fb = [b familyName];
3365 if ([fa isEqualToString:fb]) {
3366 [style setFontFamily:fa];
3369 int sa = [a pointSize];
3370 int sb = [b pointSize];
3371 int soa = [oa pointSize];
3373 [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
3374 } else if (sa < soa) {
3375 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel smaller
3376 } else if (sa > soa) {
3377 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel larger
3380 int wa = [fm weightOfFont:a];
3381 int wb = [fm weightOfFont:b];
3384 [style setFontWeight:@"bold"];
3386 [style setFontWeight:@"normal"];
3390 BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3391 BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3394 [style setFontStyle:@"italic"];
3396 [style setFontStyle:@"normal"];
3401 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3403 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3405 NSFontManager *fm = [NSFontManager sharedFontManager];
3407 NSFont *oa = [self _originalFontA];
3408 NSFont *ob = [self _originalFontB];
3409 [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
3414 - (void)changeFont:(id)sender
3416 [self _applyStyleToSelection:[self _styleFromFontManagerOperation]];
3419 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
3421 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3423 NSShadow *shadow = [[NSShadow alloc] init];
3424 [shadow setShadowOffset:NSMakeSize(1, 1)];
3426 NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
3427 [self _originalFontA], NSFontAttributeName,
3429 NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
3430 [NSColor blackColor], NSBackgroundColorAttributeName,
3431 [self _originalFontB], NSFontAttributeName,
3432 [NSColor whiteColor], NSForegroundColorAttributeName,
3433 shadow, NSShadowAttributeName,
3434 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
3435 [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
3436 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
3443 NSObliquenessAttributeName /* float; skew to be applied to glyphs, default 0: no skew */
3444 // font-style, but that is just an on-off switch
3446 NSExpansionAttributeName /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
3449 NSKernAttributeName /* float, amount to modify default kerning, if 0, kerning off */
3450 // letter-spacing? probably not good enough
3452 NSUnderlineColorAttributeName /* NSColor, default nil: same as foreground color */
3453 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
3454 // text-decoration-color?
3456 NSLigatureAttributeName /* int, default 1: default ligatures, 0: no ligatures, 2: all ligatures */
3457 NSBaselineOffsetAttributeName /* float, in points; offset from baseline, default 0 */
3458 NSStrokeWidthAttributeName /* float, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0) */
3459 NSStrokeColorAttributeName /* NSColor, default nil: same as foreground color */
3464 NSDictionary *a = [sender convertAttributes:oa];
3465 NSDictionary *b = [sender convertAttributes:ob];
3467 NSColor *ca = [a objectForKey:NSBackgroundColorAttributeName];
3468 NSColor *cb = [b objectForKey:NSBackgroundColorAttributeName];
3470 [style setBackgroundColor:[self _colorAsString:ca]];
3473 [self _addToStyle:style fontA:[a objectForKey:NSFontAttributeName] fontB:[b objectForKey:NSFontAttributeName]];
3475 ca = [a objectForKey:NSForegroundColorAttributeName];
3476 cb = [b objectForKey:NSForegroundColorAttributeName];
3478 [style setColor:[self _colorAsString:ca]];
3481 NSShadow *sha = [a objectForKey:NSShadowAttributeName];
3483 [style setTextShadow:[self _shadowAsString:sha]];
3484 } else if ([b objectForKey:NSShadowAttributeName] == nil) {
3485 [style setTextShadow:@"none"];