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 // need to declare this because AppKit does not make it available as API or SPI
62 extern NSString *NSMarkedClauseSegmentAttributeName;
64 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
65 void _NSInitializeKillRing(void);
66 void _NSAppendToKillRing(NSString *);
67 void _NSPrependToKillRing(NSString *);
68 NSString *_NSYankFromKillRing(void);
69 NSString *_NSYankPreviousFromKillRing(void);
70 void _NSNewKillRingSequence(void);
71 void _NSSetKillRingToYankedState(void);
72 void _NSResetKillRingOperationFlag(void);
74 @interface NSView (AppKitSecretsIKnowAbout)
75 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
76 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
78 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
79 - (void)_propagateDirtyRectsToOpaqueAncestors;
82 @interface NSApplication (AppKitSecretsIKnowAbout)
83 - (void)speakString:(NSString *)string;
86 @interface NSWindow (AppKitSecretsIKnowAbout)
87 - (id)_newFirstResponderAfterResigning;
90 @interface NSAttributedString (AppKitSecretsIKnowAbout)
91 - (id)_initWithDOMRange:(DOMRange *)domRange;
92 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
95 @interface NSSpellChecker (CurrentlyPrivateForTextView)
96 - (void)learnWord:(NSString *)word;
99 // By imaging to a width a little wider than the available pixels,
100 // thin pages will be scaled down a little, matching the way they
101 // print in IE and Camino. This lets them use fewer sheets than they
102 // would otherwise, which is presumably why other browsers do this.
103 // Wide pages will be scaled down more than this.
104 #define PrintingMinimumShrinkFactor 1.25
106 // This number determines how small we are willing to reduce the page content
107 // in order to accommodate the widest line. If the page would have to be
108 // reduced smaller to make the widest line fit, we just clip instead (this
109 // behavior matches MacIE and Mozilla, at least)
110 #define PrintingMaximumShrinkFactor 2.0
112 #define AUTOSCROLL_INTERVAL 0.1
114 #define DRAG_LABEL_BORDER_X 4.0
115 #define DRAG_LABEL_BORDER_Y 2.0
116 #define DRAG_LABEL_RADIUS 5.0
117 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
119 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
120 #define MAX_DRAG_LABEL_WIDTH 320.0
122 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
123 #define DRAG_LINK_URL_FONT_SIZE 10.0
125 #ifndef OMIT_TIGER_FEATURES
126 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
129 // Any non-zero value will do, but using something recognizable might help us debug some day.
130 #define TRACKING_RECT_TAG 0xBADFACE
132 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
133 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
135 static BOOL forceRealHitTest = NO;
137 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
140 @interface WebHTMLView (WebHTMLViewFileInternal)
141 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
142 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
143 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
144 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
145 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
146 - (float)_calculatePrintHeight;
147 - (void)_updateTextSizeMultiplier;
148 - (DOMRange *)_selectedRange;
149 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
150 - (void)_deleteRange:(DOMRange *)range
151 preflight:(BOOL)preflight
152 killRing:(BOOL)killRing
153 prepend:(BOOL)prepend
154 smartDeleteOK:(BOOL)smartDeleteOK;
155 - (void)_deleteSelection;
156 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
159 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
160 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
163 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
164 - (void)_updateSelectionForInputManager;
165 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
168 @interface WebHTMLView (WebEditingStyleSupport)
169 - (DOMCSSStyleDeclaration *)_emptyStyle;
170 - (NSString *)_colorAsString:(NSColor *)color;
173 @interface NSView (WebHTMLViewFileInternal)
174 - (void)_web_setPrintingModeRecursive;
175 - (void)_web_clearPrintingModeRecursive;
176 - (void)_web_layoutIfNeededRecursive;
177 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
180 @interface NSMutableDictionary (WebHTMLViewFileInternal)
181 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
184 // Handles the complete: text command
185 @interface WebTextCompleteController : NSObject
189 NSWindow *_popupWindow;
190 NSTableView *_tableView;
191 NSArray *_completions;
192 NSString *_originalString;
195 - (id)initWithHTMLView:(WebHTMLView *)view;
196 - (void)doCompletion;
197 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
198 - (BOOL)filterKeyDown:(NSEvent *)event;
199 - (void)_reflectSelection;
202 @implementation WebHTMLViewPrivate
206 ASSERT(autoscrollTimer == nil);
207 ASSERT(autoscrollTriggerEvent == nil);
209 [mouseDownEvent release];
210 [draggingImageURL release];
211 [pluginController release];
213 [compController release];
214 [firstResponderAtMouseDownTime release];
221 @implementation WebHTMLView (WebHTMLViewFileInternal)
223 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
225 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
226 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
227 NSEnumerator *enumerator = [paths objectEnumerator];
230 while ((path = [enumerator nextObject]) != nil) {
231 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
232 if ([imageMIMETypes containsObject:MIMEType]) {
240 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
242 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
243 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
244 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
245 NSEnumerator *enumerator = [paths objectEnumerator];
246 WebDataSource *dataSource = [self _dataSource];
249 while ((path = [enumerator nextObject]) != nil) {
250 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
251 if ([imageMIMETypes containsObject:MIMEType]) {
252 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
253 URL:[NSURL fileURLWithPath:path]
258 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
264 return [fragment firstChild] != nil ? fragment : nil;
267 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
269 NSArray *types = [pasteboard types];
271 if ([types containsObject:WebArchivePboardType]) {
272 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
274 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
282 if ([types containsObject:NSFilenamesPboardType]) {
283 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
284 if (fragment != nil) {
291 if ([types containsObject:NSHTMLPboardType]) {
292 NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
293 // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
294 if ([HTMLString hasPrefix:@"Version:"]) {
295 NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
296 if (range.location != NSNotFound) {
297 HTMLString = [HTMLString substringFromIndex:range.location];
300 if ([HTMLString length] != 0) {
301 return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
305 if ([types containsObject:NSTIFFPboardType]) {
306 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
307 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
308 MIMEType:@"image/tiff"
311 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
316 if ([types containsObject:NSPICTPboardType]) {
317 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
318 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
319 MIMEType:@"image/pict"
322 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
327 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
328 NSAttributedString *string = nil;
329 if ([types containsObject:NSRTFDPboardType]) {
330 string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
332 if (string == nil && [types containsObject:NSRTFPboardType]) {
333 string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
336 NSArray *elements = [[NSArray alloc] initWithObjects:
337 // Omit style since we want style to be inline so the fragment can be easily inserted.
339 NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
340 elements, NSExcludedElementsDocumentAttribute,
341 self, @"WebResourceHandler", nil];
343 NSArray *subresources;
344 DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length])
345 document:[[self _bridge] DOMDocument]
346 documentAttributes:documentAttributes
347 subresources:&subresources];
348 [documentAttributes release];
354 if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
355 NSString *URLString = [URL _web_userVisibleString];
356 if ([URLString length] > 0) {
357 return [[self _bridge] documentFragmentWithText:URLString];
361 if (allowPlainText && [types containsObject:NSStringPboardType]) {
362 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
368 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
369 - (WebResource *)resourceForData:(NSData *)data preferredFilename:(NSString *)name
371 // This method is called by [NSAttributedString _documentFromRange::::]
372 // which uses the URL of the resource for the fragment that it returns.
373 NSString *extension = [name pathExtension];
374 NSString *MIMEType = nil;
375 if ([extension length] != 0) {
376 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
378 // Only support image resources.
379 if (MIMEType == nil || ![[[WebImageRendererFactory sharedFactory] supportedMIMETypes] containsObject:MIMEType]) {
382 NSURL *URL = [NSURL _web_URLWithUserTypedString:[NSString stringWithFormat:@"/%@", name] relativeToURL:[NSURL _web_uniqueWebDataURL]];
383 WebResource *resource = [[[WebResource alloc] initWithData:data
387 frameName:nil] autorelease];
388 [[self _dataSource] addSubresource:resource];
393 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
395 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText];
396 WebBridge *bridge = [self _bridge];
397 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
398 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
402 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
404 WebView *webView = [self _webView];
405 DOMNode *child = [fragment firstChild];
406 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
407 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
409 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
413 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
415 WebView *webView = [self _webView];
416 DOMRange *selectedRange = [self _selectedRange];
417 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
420 // Calculate the vertical size of the view that fits on a single page
421 - (float)_calculatePrintHeight
423 // Obtain the print info object for the current operation
424 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
426 // Calculate the page height in points
427 NSSize paperSize = [pi paperSize];
428 return paperSize.height - [pi topMargin] - [pi bottomMargin];
431 - (void)_updateTextSizeMultiplier
433 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
436 - (DOMRange *)_selectedRange
438 return [[self _bridge] selectedDOMRange];
441 - (BOOL)_shouldDeleteRange:(DOMRange *)range
443 if (range == nil || [range collapsed])
445 WebView *webView = [self _webView];
446 return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
449 - (void)_deleteRange:(DOMRange *)range
450 preflight:(BOOL)preflight
451 killRing:(BOOL)killRing
452 prepend:(BOOL)prepend
453 smartDeleteOK:(BOOL)smartDeleteOK
455 if (![self _shouldDeleteRange:range]) {
458 WebBridge *bridge = [self _bridge];
459 if (killRing && _private->startNewKillRingSequence) {
460 _NSNewKillRingSequence();
462 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityUpstream];
465 _NSPrependToKillRing([bridge selectedString]);
467 _NSAppendToKillRing([bridge selectedString]);
469 _private->startNewKillRingSequence = NO;
471 BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
472 [bridge deleteSelectionWithSmartDelete:smartDelete];
475 - (void)_deleteSelection
477 [self _deleteRange:[self _selectedRange]
484 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
486 return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
491 @implementation WebHTMLView (WebPrivate)
495 [WebImageRenderer stopAnimationsInView:self];
498 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
500 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
501 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
502 modifierFlags:[flagsChangedEvent modifierFlags]
503 timestamp:[flagsChangedEvent timestamp]
504 windowNumber:[flagsChangedEvent windowNumber]
505 context:[flagsChangedEvent context]
506 eventNumber:0 clickCount:0 pressure:0];
508 // Pretend it's a mouse move.
509 [[NSNotificationCenter defaultCenter]
510 postNotificationName:NSMouseMovedNotification object:self
511 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
514 - (void)_updateMouseoverWithFakeEvent
516 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
517 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
518 modifierFlags:[[NSApp currentEvent] modifierFlags]
519 timestamp:[NSDate timeIntervalSinceReferenceDate]
520 windowNumber:[[self window] windowNumber]
521 context:[[NSApp currentEvent] context]
522 eventNumber:0 clickCount:0 pressure:0];
524 [self _updateMouseoverWithEvent:fakeEvent];
527 - (void)_frameOrBoundsChanged
529 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
530 [self setNeedsLayout:YES];
531 [self setNeedsDisplay:YES];
532 [_private->compController endRevertingChange:NO moveLeft:NO];
535 NSPoint origin = [[self superview] bounds].origin;
536 if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
537 [[self _bridge] sendScrollEvent];
538 [_private->compController endRevertingChange:NO moveLeft:NO];
540 _private->lastScrollPosition = origin;
542 SEL selector = @selector(_updateMouseoverWithFakeEvent);
543 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
544 [self performSelector:selector withObject:nil afterDelay:0];
547 - (void)_setAsideSubviews
549 ASSERT(!_private->subviewsSetAside);
550 ASSERT(_private->savedSubviews == nil);
551 _private->savedSubviews = _subviews;
553 _private->subviewsSetAside = YES;
556 - (void)_restoreSubviews
558 ASSERT(_private->subviewsSetAside);
559 ASSERT(_subviews == nil);
560 _subviews = _private->savedSubviews;
561 _private->savedSubviews = nil;
562 _private->subviewsSetAside = NO;
565 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
566 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
567 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
568 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
569 // need to be redrawn (in case the layout causes some things to get dirtied).
570 - (void)_propagateDirtyRectsToOpaqueAncestors
572 if (![[self _webView] drawsBackground]) {
573 [self _web_layoutIfNeededRecursive];
575 [super _propagateDirtyRectsToOpaqueAncestors];
578 // Don't let AppKit even draw subviews. We take care of that.
579 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
581 // This helps when we print as part of a larger print process.
582 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
583 BOOL wasInPrintingMode = _private->printing;
584 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
585 if (wasInPrintingMode != isPrinting) {
587 [self _web_setPrintingModeRecursive];
589 [self _web_clearPrintingModeRecursive];
593 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
595 [self _setAsideSubviews];
596 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
597 rectIsVisibleRectForView:visibleView topView:topView];
598 [self _restoreSubviews];
600 if (wasInPrintingMode != isPrinting) {
601 if (wasInPrintingMode) {
602 [self _web_setPrintingModeRecursive];
604 [self _web_clearPrintingModeRecursive];
609 // Don't let AppKit even draw subviews. We take care of that.
610 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
612 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
614 BOOL wasInPrintingMode = _private->printing;
615 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
617 if (needToSetAsideSubviews) {
618 // This helps when we print as part of a larger print process.
619 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
620 if (wasInPrintingMode != isPrinting) {
622 [self _web_setPrintingModeRecursive];
624 [self _web_clearPrintingModeRecursive];
628 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
630 [self _setAsideSubviews];
633 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
635 if (needToSetAsideSubviews) {
636 if (wasInPrintingMode != isPrinting) {
637 if (wasInPrintingMode) {
638 [self _web_setPrintingModeRecursive];
640 [self _web_clearPrintingModeRecursive];
644 [self _restoreSubviews];
648 - (BOOL)_insideAnotherHTMLView
651 while ((view = [view superview])) {
652 if ([view isKindOfClass:[WebHTMLView class]]) {
659 - (void)scrollPoint:(NSPoint)point
661 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
662 // If we get called during the handling of a key down event, we assume the call came from
663 // NSTextView, and ignore it and use our own code to decide how to page up and page down
664 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
665 NSEvent *event = [[self window] currentEvent];
666 if ([event type] == NSKeyDown) {
667 const unichar pageUp = NSPageUpFunctionKey;
668 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
669 [self tryToPerform:@selector(scrollPageUp:) with:nil];
672 const unichar pageDown = NSPageDownFunctionKey;
673 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
674 [self tryToPerform:@selector(scrollPageDown:) with:nil];
679 [super scrollPoint:point];
682 - (NSView *)hitTest:(NSPoint)point
684 // WebHTMLView objects handle all left mouse clicks for objects inside them.
685 // That does not include left mouse clicks with the control key held down.
686 BOOL captureHitsOnSubviews;
687 if (forceRealHitTest) {
688 captureHitsOnSubviews = NO;
690 NSEvent *event = [[self window] currentEvent];
691 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
693 if (!captureHitsOnSubviews) {
694 return [super hitTest:point];
696 if ([[self superview] mouse:point inRect:[self frame]]) {
702 static WebHTMLView *lastHitView = nil;
704 - (void)_clearLastHitViewIfSelf
706 if (lastHitView == self) {
711 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
713 ASSERT(_private->trackingRectOwner == nil);
714 _private->trackingRectOwner = owner;
715 _private->trackingRectUserData = data;
716 return TRACKING_RECT_TAG;
719 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
721 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
722 ASSERT(_private->trackingRectOwner == nil);
723 _private->trackingRectOwner = owner;
724 _private->trackingRectUserData = data;
725 return TRACKING_RECT_TAG;
728 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
731 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
732 ASSERT(_private->trackingRectOwner == nil);
733 _private->trackingRectOwner = owner;
734 _private->trackingRectUserData = userDataList[0];
735 trackingNums[0] = TRACKING_RECT_TAG;
738 - (void)removeTrackingRect:(NSTrackingRectTag)tag
742 ASSERT(tag == TRACKING_RECT_TAG);
743 if (_private != nil) {
744 _private->trackingRectOwner = nil;
748 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
751 for (i = 0; i < count; ++i) {
755 ASSERT(tag == TRACKING_RECT_TAG);
756 if (_private != nil) {
757 _private->trackingRectOwner = nil;
762 - (void)_sendToolTipMouseExited
764 // Nothing matters except window, trackingNumber, and userData.
765 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
766 location:NSMakePoint(0, 0)
769 windowNumber:[[self window] windowNumber]
772 trackingNumber:TRACKING_RECT_TAG
773 userData:_private->trackingRectUserData];
774 [_private->trackingRectOwner mouseExited:fakeEvent];
777 - (void)_sendToolTipMouseEntered
779 // Nothing matters except window, trackingNumber, and userData.
780 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
781 location:NSMakePoint(0, 0)
784 windowNumber:[[self window] windowNumber]
787 trackingNumber:TRACKING_RECT_TAG
788 userData:_private->trackingRectUserData];
789 [_private->trackingRectOwner mouseEntered:fakeEvent];
792 - (void)_setToolTip:(NSString *)string
794 NSString *toolTip = [string length] == 0 ? nil : string;
795 NSString *oldToolTip = _private->toolTip;
796 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
800 [self _sendToolTipMouseExited];
801 [oldToolTip release];
803 _private->toolTip = [toolTip copy];
805 [self removeAllToolTips];
806 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
807 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
808 [self _sendToolTipMouseEntered];
812 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
814 return [[_private->toolTip copy] autorelease];
817 - (void)_updateMouseoverWithEvent:(NSEvent *)event
819 WebHTMLView *view = nil;
820 if ([event window] == [self window]) {
821 forceRealHitTest = YES;
822 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
823 forceRealHitTest = NO;
825 if ([hitView isKindOfClass:[WebHTMLView class]]) {
826 view = (WebHTMLView *)hitView;
829 hitView = [hitView superview];
833 if (lastHitView != view && lastHitView != nil) {
834 // If we are moving out of a view (or frame), let's pretend the mouse moved
835 // all the way out of that view. But we have to account for scrolling, because
836 // khtml doesn't understand our clipping.
837 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
838 float yScroll = visibleRect.origin.y;
839 float xScroll = visibleRect.origin.x;
841 event = [NSEvent mouseEventWithType:NSMouseMoved
842 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
843 modifierFlags:[[NSApp currentEvent] modifierFlags]
844 timestamp:[NSDate timeIntervalSinceReferenceDate]
845 windowNumber:[[self window] windowNumber]
846 context:[[NSApp currentEvent] context]
847 eventNumber:0 clickCount:0 pressure:0];
848 [[lastHitView _bridge] mouseMoved:event];
853 NSDictionary *element;
857 [[view _bridge] mouseMoved:event];
859 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
860 element = [view elementAtPoint:point];
863 // Have the web view send a message to the delegate so it can do status bar display.
864 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
866 // Set a tool tip; it won't show up right away but will if the user pauses.
867 NSString *newToolTip = nil;
868 if (_private->showsURLsInToolTips) {
869 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
871 if (newToolTip == nil) {
872 newToolTip = [element objectForKey:WebCoreElementTitleKey];
874 [self _setToolTip:newToolTip];
877 + (NSArray *)_insertablePasteboardTypes
879 static NSArray *types = nil;
881 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
882 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
883 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
888 + (NSArray *)_selectionPasteboardTypes
890 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
891 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
894 - (WebArchive *)_selectedArchive
898 double start = CFAbsoluteTimeGetCurrent();
900 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
902 double duration = CFAbsoluteTimeGetCurrent() - start;
903 LOG(Timing, "copying markup took %f seconds.", duration);
906 return [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
909 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
911 ASSERT([self _hasSelection]);
912 NSArray *types = [self pasteboardTypesForSelection];
913 [pasteboard declareTypes:types owner:nil];
914 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
917 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
919 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
921 BOOL drawURLString = YES;
922 BOOL clipURLString = NO, clipLabelString = NO;
924 NSString *label = [element objectForKey: WebElementLinkLabelKey];
925 NSString *urlString = [linkURL _web_userVisibleString];
932 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
933 toHaveTrait:NSBoldFontMask];
934 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
936 labelSize.width = [label _web_widthWithFont: labelFont];
937 labelSize.height = [labelFont ascender] - [labelFont descender];
938 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
939 labelSize.width = MAX_DRAG_LABEL_WIDTH;
940 clipLabelString = YES;
943 NSSize imageSize, urlStringSize;
944 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
945 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
947 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
948 urlStringSize.height = [urlFont ascender] - [urlFont descender];
949 imageSize.height += urlStringSize.height;
950 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
951 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
954 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
957 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
958 [dragImage lockFocus];
960 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
962 // Drag a rectangle with rounded corners/
963 NSBezierPath *path = [NSBezierPath bezierPath];
964 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
965 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
966 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
967 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
969 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
970 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
971 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
974 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
975 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
978 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
980 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
981 withTopColor:topColor bottomColor:bottomColor font:urlFont];
985 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
986 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
987 withTopColor:topColor bottomColor:bottomColor font:labelFont];
989 [dragImage unlockFocus];
994 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
996 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
997 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
999 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1000 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1001 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1003 [_private->draggingImageURL release];
1004 _private->draggingImageURL = nil;
1006 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1007 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
1008 NSImage *dragImage = nil;
1011 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1012 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1013 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1015 dragImage = wcDragImage;
1016 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1017 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1020 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1022 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1024 _private->dragOffset = wcDragLoc;
1027 WebView *webView = [self _webView];
1028 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1029 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
1030 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
1032 // note per kwebster, the offset arg below is always ignored in positioning the image
1033 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1035 if (!dhtmlWroteData) {
1036 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1037 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1038 ASSERT(imageElement != nil);
1039 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityUpstream];
1040 _private->draggingImageURL = [imageURL retain];
1041 source = [pasteboard _web_declareAndWriteDragImage:image
1042 URL:linkURL ? linkURL : imageURL
1043 title:[element objectForKey:WebElementImageAltStringKey]
1044 archive:[imageElement webArchive]
1047 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1048 if (dragImage == nil) {
1049 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1050 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1051 event:_private->mouseDownEvent
1052 pasteboard:pasteboard
1054 offset:&_private->dragOffset];
1056 [self dragImage:dragImage
1059 event:_private->mouseDownEvent
1060 pasteboard:pasteboard
1064 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1065 if (!dhtmlWroteData) {
1066 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1067 [pasteboard declareTypes:types owner:self];
1068 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1070 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1071 if (dragImage == nil) {
1072 dragImage = [self _dragImageForLinkElement:element];
1073 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1074 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1075 _private->dragOffset.x = offset.width;
1076 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1078 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1079 // a flash of the image at the mouseDown location when the drag starts.
1080 [self dragImage:dragImage
1083 event:mouseDraggedEvent
1084 pasteboard:pasteboard
1087 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1088 if (!dhtmlWroteData) {
1089 [self _writeSelectionToPasteboard:pasteboard];
1091 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1092 if (dragImage == nil) {
1093 dragImage = [[self _bridge] selectionImage];
1094 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1095 NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
1096 dragLoc = NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect));
1097 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1098 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1100 [self dragImage:dragImage
1103 event:_private->mouseDownEvent
1104 pasteboard:pasteboard
1107 } else if (srcIsDHTML) {
1108 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1109 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1110 if (dragImage == nil) {
1111 // WebCore should have given us an image, but we'll make one up
1112 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1113 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1114 NSSize imageSize = [dragImage size];
1115 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1116 _private->dragOffset.x = imageSize.width/2;
1117 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1119 [self dragImage:dragImage
1122 event:_private->mouseDownEvent
1123 pasteboard:pasteboard
1127 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1128 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1134 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1136 [self autoscroll:event];
1137 [self _startAutoscrollTimer:event];
1140 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1142 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1143 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1145 ASSERT([self _webView]);
1146 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1147 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1148 [[[self _webView] preferences] loadsImagesAutomatically] &&
1149 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1153 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1154 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1158 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1159 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1166 - (WebPluginController *)_pluginController
1168 return _private->pluginController;
1171 - (void)_web_setPrintingModeRecursive
1173 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1174 [super _web_setPrintingModeRecursive];
1177 - (void)_web_clearPrintingModeRecursive
1179 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1180 [super _web_clearPrintingModeRecursive];
1183 - (void)_layoutIfNeeded
1185 ASSERT(!_private->subviewsSetAside);
1187 if ([[self _bridge] needsLayout])
1188 _private->needsLayout = YES;
1189 if (_private->needsToApplyStyles || _private->needsLayout)
1193 - (void)_web_layoutIfNeededRecursive
1195 [self _layoutIfNeeded];
1196 [super _web_layoutIfNeededRecursive];
1199 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1201 ASSERT(!_private->subviewsSetAside);
1202 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1204 if (!testDirtyRect || [self needsDisplay]) {
1205 if (testDirtyRect) {
1206 NSRect dirtyRect = [self _dirtyRect];
1207 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1209 if (!NSIsEmptyRect(displayRect)) {
1210 [self _layoutIfNeeded];
1214 [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1217 - (NSRect)_selectionRect
1219 return [[self _bridge] selectionRect];
1222 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1224 if (_private->autoscrollTimer == nil) {
1225 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1226 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1227 _private->autoscrollTriggerEvent = [triggerEvent retain];
1231 - (void)_stopAutoscrollTimer
1233 NSTimer *timer = _private->autoscrollTimer;
1234 _private->autoscrollTimer = nil;
1235 [_private->autoscrollTriggerEvent release];
1236 _private->autoscrollTriggerEvent = nil;
1245 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1246 // a mouse up event.
1247 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1249 [self _stopAutoscrollTimer];
1253 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1254 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1255 modifierFlags:[[NSApp currentEvent] modifierFlags]
1256 timestamp:[NSDate timeIntervalSinceReferenceDate]
1257 windowNumber:[[self window] windowNumber]
1258 context:[[NSApp currentEvent] context]
1259 eventNumber:0 clickCount:0 pressure:0];
1260 [self mouseDragged:fakeEvent];
1265 // Copying can be done regardless of whether you can edit.
1266 return [self _hasSelection];
1271 return [self _hasSelection] && [self _isEditable];
1276 return [self _hasSelection] && [self _isEditable];
1281 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1286 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1289 - (BOOL)_hasSelection
1291 return [[self _bridge] selectionState] == WebSelectionStateRange;
1294 - (BOOL)_hasSelectionOrInsertionPoint
1296 return [[self _bridge] selectionState] != WebSelectionStateNone;
1301 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1304 - (BOOL)_isSelectionMisspelled
1306 NSString *selectedString = [self selectedString];
1307 unsigned length = [selectedString length];
1311 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1315 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1317 return range.length == length;
1320 - (NSArray *)_guessesForMisspelledSelection
1322 ASSERT([[self selectedString] length] != 0);
1323 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1326 - (void)_changeSpellingFromMenu:(id)sender
1328 ASSERT([[self selectedString] length] != 0);
1329 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1332 - (void)_ignoreSpellingFromMenu:(id)sender
1334 ASSERT([[self selectedString] length] != 0);
1335 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1338 - (void)_learnSpellingFromMenu:(id)sender
1340 ASSERT([[self selectedString] length] != 0);
1341 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1344 #if APPKIT_CODE_FOR_REFERENCE
1346 - (void)_openLinkFromMenu:(id)sender
1348 NSTextStorage *text = _getTextStorage(self);
1349 NSRange charRange = [self selectedRange];
1350 if (charRange.location != NSNotFound && charRange.length > 0) {
1351 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1353 [self clickedOnLink:link atIndex:charRange.location];
1355 NSString *string = [[text string] substringWithRange:charRange];
1356 link = [NSURL URLWithString:string];
1357 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1364 - (BOOL)_transparentBackground
1366 return _private->transparentBackground;
1369 - (void)_setTransparentBackground:(BOOL)f
1371 _private->transparentBackground = f;
1376 @implementation NSView (WebHTMLViewFileInternal)
1378 - (void)_web_setPrintingModeRecursive
1380 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1383 - (void)_web_clearPrintingModeRecursive
1385 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1388 - (void)_web_layoutIfNeededRecursive
1390 [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1393 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1395 unsigned index, count;
1396 for (index = 0, count = [_subviews count]; index < count; index++) {
1397 NSView *subview = [_subviews objectAtIndex:index];
1398 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1399 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1405 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1407 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1409 if (object == nil) {
1410 [self removeObjectForKey:key];
1412 [self setObject:object forKey:key];
1418 // The following is a workaround for
1419 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1420 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1421 // Since the category will be searched before the real class, we'll prevent the flag from being
1422 // set on the tool tip panel.
1424 @interface NSToolTipPanel : NSPanel
1427 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1430 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1432 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1434 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1440 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1443 @interface NSArray (WebHTMLView)
1444 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1447 @implementation WebHTMLView
1451 WebKitInitializeUnicode();
1452 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1453 returnTypes:[[self class] _insertablePasteboardTypes]];
1454 _NSInitializeKillRing();
1457 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1459 WebPreferences *preferences = [[self _webView] preferences];
1460 // Check for nil because we might not yet have an associated webView when this is called
1461 if (preferences == nil) {
1462 preferences = [WebPreferences standardPreferences];
1464 _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1467 - (id)initWithFrame:(NSRect)frame
1469 [super initWithFrame:frame];
1471 // Make all drawing go through us instead of subviews.
1472 if (NSAppKitVersionNumber >= 711) {
1473 [self _setDrawsOwnDescendants:YES];
1476 _private = [[WebHTMLViewPrivate alloc] init];
1478 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1479 _private->needsLayout = YES;
1480 [self _resetCachedWebPreferences:nil];
1481 [[NSNotificationCenter defaultCenter]
1482 addObserver:self selector:@selector(_resetCachedWebPreferences:)
1483 name:WebPreferencesChangedNotification object:nil];
1490 [self _clearLastHitViewIfSelf];
1492 [[NSNotificationCenter defaultCenter] removeObserver:self];
1493 [_private->pluginController destroyAllPlugins];
1501 [self _clearLastHitViewIfSelf];
1503 [[NSNotificationCenter defaultCenter] removeObserver:self];
1504 [_private->pluginController destroyAllPlugins];
1509 - (IBAction)takeFindStringFromSelection:(id)sender
1511 if (![self _hasSelection]) {
1516 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1519 - (NSArray *)pasteboardTypesForSelection
1521 if ([self _canSmartCopyOrDelete]) {
1522 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1523 [types addObject:WebSmartPastePboardType];
1526 return [[self class] _selectionPasteboardTypes];
1530 // This method is copied from NSTextView
1531 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
1533 NSRange attachmentRange;
1534 NSString *originalString = [originalAttributedString string];
1535 static NSString *attachmentCharString = nil;
1537 if (!attachmentCharString) {
1539 if (!attachmentCharString) {
1540 chars[0] = NSAttachmentCharacter;
1542 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
1546 attachmentRange = [originalString rangeOfString:attachmentCharString];
1547 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1548 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
1550 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
1551 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
1552 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
1554 return newAttributedString;
1556 return originalAttributedString;
1560 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1562 // Put HTML on the pasteboard.
1563 if ([types containsObject:WebArchivePboardType]) {
1564 WebArchive *archive = [self _selectedArchive];
1565 [pasteboard setData:[archive data] forType:WebArchivePboardType];
1568 // Put the attributed string on the pasteboard (RTF/RTFD format).
1569 NSAttributedString *attributedString = nil;
1570 if ([types containsObject:NSRTFDPboardType]) {
1571 attributedString = [self selectedAttributedString];
1572 if ([attributedString containsAttachments]) {
1573 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1574 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
1577 if ([types containsObject:NSRTFPboardType]) {
1578 if (attributedString == nil) {
1579 attributedString = [self selectedAttributedString];
1581 if ([attributedString containsAttachments]) {
1582 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
1584 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
1585 [pasteboard setData:RTFData forType:NSRTFPboardType];
1588 // Put plain string on the pasteboard.
1589 if ([types containsObject:NSStringPboardType]) {
1590 // Map to a plain old space because this is better for source code, other browsers do it,
1591 // and because HTML forces you to do this any time you want two spaces in a row.
1592 NSMutableString *s = [[self selectedString] mutableCopy];
1593 const unichar NonBreakingSpaceCharacter = 0xA0;
1594 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
1595 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
1596 [pasteboard setString:s forType:NSStringPboardType];
1600 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
1601 [pasteboard setData:nil forType:WebSmartPastePboardType];
1605 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1607 [pasteboard declareTypes:types owner:nil];
1608 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1612 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1614 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1618 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1620 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1622 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1625 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1628 - (void)selectAll:(id)sender
1633 - (void)jumpToSelection: sender
1635 [[self _bridge] jumpToSelection];
1638 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1640 SEL action = [item action];
1641 WebBridge *bridge = [self _bridge];
1643 if (action == @selector(cut:)) {
1644 return [bridge mayDHTMLCut] || [self _canDelete];
1645 } else if (action == @selector(copy:)) {
1646 return [bridge mayDHTMLCopy] || [self _canCopy];
1647 } else if (action == @selector(delete:)) {
1648 return [self _canDelete];
1649 } else if (action == @selector(paste:)) {
1650 return [bridge mayDHTMLPaste] || [self _canPaste];
1651 } else if (action == @selector(takeFindStringFromSelection:)) {
1652 return [self _hasSelection];
1653 } else if (action == @selector(jumpToSelection:)) {
1654 return [self _hasSelection];
1655 } else if (action == @selector(checkSpelling:)
1656 || action == @selector(showGuessPanel:)
1657 || action == @selector(changeSpelling:)
1658 || action == @selector(ignoreSpelling:)) {
1659 return [[self _bridge] isSelectionEditable];
1665 - (BOOL)acceptsFirstResponder
1667 // Don't accept first responder when we first click on this view.
1668 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1669 // Do accept first responder at any other time, for example from keyboard events,
1670 // or from calls back from WebCore once we begin mouse-down event handling.
1671 NSEvent *event = [NSApp currentEvent];
1672 if ([event type] == NSLeftMouseDown
1673 && !_private->handlingMouseDownEvent
1674 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1680 - (BOOL)maintainsInactiveSelection
1682 // This method helps to determing whether the view should maintain
1683 // an inactive selection when the view is not first responder.
1684 // Traditionally, these views have not maintained such selections,
1685 // clearing them when the view was not first responder. However,
1686 // to fix bugs like this one:
1687 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
1688 // when they're not firstResponder"
1689 // it was decided to add a switch to act more like an NSTextView.
1690 // For now, however, the view only acts in this way when the
1691 // web view is set to be editable. This will maintain traditional
1692 // behavior for WebKit clients dating back to before this change,
1693 // and will likely be a decent switch for the long term, since
1694 // clients to ste the web view to be editable probably want it
1695 // to act like a "regular" Cocoa view in terms of its selection
1697 if (![[self _webView] isEditable])
1700 id nextResponder = [[self window] _newFirstResponderAfterResigning];
1701 return !nextResponder || ![nextResponder isKindOfClass:[NSView class]] || ![nextResponder isDescendantOf:[self _webView]];
1704 - (void)addMouseMovedObserver
1706 // Always add a mouse move observer if the DB requested, or if we're the key window.
1707 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
1708 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
1709 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
1710 name:NSMouseMovedNotification object:nil];
1711 [self _frameOrBoundsChanged];
1715 - (void)removeMouseMovedObserver
1717 // Don't remove the observer if we're running the DB
1718 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
1721 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
1722 [[NSNotificationCenter defaultCenter] removeObserver:self
1723 name:NSMouseMovedNotification object:nil];
1726 - (void)updateFocusDisplay
1728 // This method does the job of updating the view based on the view's firstResponder-ness and
1729 // the window key-ness of the window containing this view. This involves three kinds of
1730 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
1732 // The three display attributes are as follows:
1734 // 1. The background color used to draw behind selected content (active | inactive color)
1735 // 2. Caret blinking (blinks | does not blink)
1736 // 3. The drawing of a focus ring around links in web pages.
1738 BOOL flag = !_private->resigningFirstResponder && [[self window] isKeyWindow] && [self _web_firstResponderCausesFocusDisplay];
1739 [[self _bridge] setDisplaysWithFocusAttributes:flag];
1742 - (void)addSuperviewObservers
1744 // We watch the bounds of our superview, so that we can do a layout when the size
1745 // of the superview changes. This is different from other scrollable things that don't
1746 // need this kind of thing because their layout doesn't change.
1748 // We need to pay attention to both height and width because our "layout" has to change
1749 // to extend the background the full height of the space and because some elements have
1750 // sizes that are based on the total size of the view.
1752 NSView *superview = [self superview];
1753 if (superview && [self window]) {
1754 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1755 name:NSViewFrameDidChangeNotification object:superview];
1756 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
1757 name:NSViewBoundsDidChangeNotification object:superview];
1761 - (void)removeSuperviewObservers
1763 NSView *superview = [self superview];
1764 if (superview && [self window]) {
1765 [[NSNotificationCenter defaultCenter] removeObserver:self
1766 name:NSViewFrameDidChangeNotification object:superview];
1767 [[NSNotificationCenter defaultCenter] removeObserver:self
1768 name:NSViewBoundsDidChangeNotification object:superview];
1772 - (void)addWindowObservers
1774 NSWindow *window = [self window];
1776 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
1777 name:NSWindowDidBecomeKeyNotification object:window];
1778 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
1779 name:NSWindowDidResignKeyNotification object:window];
1780 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
1781 name:NSWindowWillCloseNotification object:window];
1785 - (void)removeWindowObservers
1787 NSWindow *window = [self window];
1789 [[NSNotificationCenter defaultCenter] removeObserver:self
1790 name:NSWindowDidBecomeKeyNotification object:window];
1791 [[NSNotificationCenter defaultCenter] removeObserver:self
1792 name:NSWindowDidResignKeyNotification object:window];
1793 [[NSNotificationCenter defaultCenter] removeObserver:self
1794 name:NSWindowWillCloseNotification object:window];
1798 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
1800 [self removeSuperviewObservers];
1803 - (void)viewDidMoveToSuperview
1805 // Do this here in case the text size multiplier changed when a non-HTML
1806 // view was installed.
1807 if ([self superview] != nil) {
1808 [self _updateTextSizeMultiplier];
1809 [self addSuperviewObservers];
1813 - (void)viewWillMoveToWindow:(NSWindow *)window
1815 // Don't do anything if we aren't initialized. This happens
1816 // when decoding a WebView. When WebViews are decoded their subviews
1817 // are created by initWithCoder: and so won't be normally
1818 // initialized. The stub views are discarded by WebView.
1820 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
1821 [self removeMouseMovedObserver];
1822 [self removeWindowObservers];
1823 [self removeSuperviewObservers];
1824 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
1826 [[self _pluginController] stopAllPlugins];
1830 - (void)viewDidMoveToWindow
1832 // Don't do anything if we aren't initialized. This happens
1833 // when decoding a WebView. When WebViews are decoded their subviews
1834 // are created by initWithCoder: and so won't be normally
1835 // initialized. The stub views are discarded by WebView.
1837 [self _stopAutoscrollTimer];
1838 if ([self window]) {
1839 _private->lastScrollPosition = [[self superview] bounds].origin;
1840 [self addWindowObservers];
1841 [self addSuperviewObservers];
1842 [self addMouseMovedObserver];
1843 // Schedule this update, rather than making the call right now.
1844 // The reason is that placing the caret in the just-installed view requires
1845 // the HTML/XML document to be available on the WebCore side, but it is not
1846 // at the time this code is running. However, it will be there on the next
1847 // crank of the run loop. Doing this helps to make a blinking caret appear
1848 // in a new, empty window "automatic".
1849 [self performSelector:@selector(updateFocusDisplay) withObject:nil afterDelay:0];
1851 [[self _pluginController] startAllPlugins];
1853 _private->lastScrollPosition = NSZeroPoint;
1855 _private->inWindow = YES;
1857 // Reset when we are moved out of a window after being moved into one.
1858 // Without this check, we reset ourselves before we even start.
1859 // This is only needed because viewDidMoveToWindow is called even when
1860 // the window is not changing (bug in AppKit).
1861 if (_private->inWindow) {
1863 _private->inWindow = NO;
1869 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
1871 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
1874 - (void)viewDidMoveToHostWindow
1876 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
1880 - (void)addSubview:(NSView *)view
1882 [super addSubview:view];
1884 if ([WebPluginController isPlugInView:view]) {
1885 [[self _pluginController] addPlugin:view];
1889 - (void)reapplyStyles
1891 if (!_private->needsToApplyStyles) {
1896 double start = CFAbsoluteTimeGetCurrent();
1899 [[self _bridge] reapplyStylesForDeviceType:
1900 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
1903 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1904 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
1907 _private->needsToApplyStyles = NO;
1910 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
1911 // minPageWidth==0 implies a non-printing layout
1912 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
1914 [self reapplyStyles];
1916 // Ensure that we will receive mouse move events. Is this the best place to put this?
1917 [[self window] setAcceptsMouseMovedEvents: YES];
1918 [[self window] _setShouldPostEventNotifications: YES];
1920 if (!_private->needsLayout) {
1925 double start = CFAbsoluteTimeGetCurrent();
1928 LOG(View, "%@ doing layout", self);
1930 if (minPageWidth > 0.0) {
1931 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
1933 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
1935 _private->needsLayout = NO;
1937 if (!_private->printing) {
1938 // get size of the containing dynamic scrollview, so
1939 // appearance and disappearance of scrollbars will not show up
1941 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
1942 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
1943 [[self _bridge] sendResizeEvent];
1945 _private->laidOutAtLeastOnce = YES;
1946 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
1947 _private->lastLayoutFrameSize = newLayoutFrameSize;
1951 double thisTime = CFAbsoluteTimeGetCurrent() - start;
1952 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
1958 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
1961 - (NSMenu *)menuForEvent:(NSEvent *)event
1963 [_private->compController endRevertingChange:NO moveLeft:NO];
1965 if ([[self _bridge] sendContextMenuEvent:event]) {
1968 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
1969 NSDictionary *element = [self elementAtPoint:point];
1970 return [[self _webView] _menuForElement:element];
1973 // Search from the end of the currently selected location, or from the beginning of the
1974 // document if nothing is selected.
1975 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag;
1977 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag];
1980 - (DOMRange *)_documentRange
1982 return [[[self _bridge] DOMDocument] _documentRange];
1985 - (NSString *)string
1987 return [[self _bridge] stringForRange:[self _documentRange]];
1990 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
1992 NSAttributedString *attributedString = nil;
1993 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
1995 double start = CFAbsoluteTimeGetCurrent();
1997 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
1999 double duration = CFAbsoluteTimeGetCurrent() - start;
2000 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2003 return attributedString;
2006 - (NSAttributedString *)attributedString
2008 WebBridge *bridge = [self _bridge];
2009 DOMDocument *document = [bridge DOMDocument];
2010 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2011 if (attributedString == nil) {
2012 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2014 return attributedString;
2017 - (NSString *)selectedString
2019 return [[self _bridge] selectedString];
2022 - (NSAttributedString *)selectedAttributedString
2024 WebBridge *bridge = [self _bridge];
2025 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2026 if (attributedString == nil) {
2027 attributedString = [bridge selectedAttributedString];
2029 return attributedString;
2034 [[self _bridge] selectAll];
2037 // Remove the selection.
2040 [[self _bridge] deselectAll];
2043 - (void)deselectText
2045 [[self _bridge] deselectText];
2050 return [[self _webView] drawsBackground];
2053 - (void)setNeedsDisplay:(BOOL)flag
2055 LOG(View, "%@ flag = %d", self, (int)flag);
2056 [super setNeedsDisplay: flag];
2059 - (void)setNeedsLayout: (BOOL)flag
2061 LOG(View, "%@ flag = %d", self, (int)flag);
2062 _private->needsLayout = flag;
2066 - (void)setNeedsToApplyStyles: (BOOL)flag
2068 LOG(View, "%@ flag = %d", self, (int)flag);
2069 _private->needsToApplyStyles = flag;
2072 - (void)drawRect:(NSRect)rect
2074 LOG(View, "%@ drawing", self);
2076 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2077 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2078 // This does a better job of clipping out rects that are entirely outside the visible area.
2079 const NSRect *rects;
2081 [self getRectsBeingDrawn:&rects count:&count];
2083 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2084 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2085 // The reason for the workaround is that this method is called explicitly from the code
2086 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2090 for (i = 0; i < count; ++i) {
2091 rect = NSUnionRect(rect, rects[i]);
2093 if (rect.size.height == 0 || rect.size.width == 0) {
2098 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2099 if (subviewsWereSetAside) {
2100 [self _restoreSubviews];
2104 double start = CFAbsoluteTimeGetCurrent();
2107 [NSGraphicsContext saveGraphicsState];
2110 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2112 [(WebClipView *)[self superview] setAdditionalClip:rect];
2115 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2116 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2117 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2118 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2121 if ([self _transparentBackground]) {
2122 [[NSColor clearColor] set];
2126 //double start = CFAbsoluteTimeGetCurrent();
2127 [[self _bridge] drawRect:rect];
2128 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2130 if (textRendererFactoryIfCoalescing != nil) {
2131 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2134 [(WebClipView *)[self superview] resetAdditionalClip];
2136 [NSGraphicsContext restoreGraphicsState];
2138 [(WebClipView *)[self superview] resetAdditionalClip];
2139 [NSGraphicsContext restoreGraphicsState];
2140 ERROR("Exception caught while drawing: %@", localException);
2141 [localException raise];
2145 NSRect vframe = [self frame];
2146 [[NSColor blackColor] set];
2148 path = [NSBezierPath bezierPath];
2149 [path setLineWidth:(float)0.1];
2150 [path moveToPoint:NSMakePoint(0, 0)];
2151 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2154 path = [NSBezierPath bezierPath];
2155 [path setLineWidth:(float)0.1];
2156 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2157 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2163 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2164 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2167 if (subviewsWereSetAside) {
2168 [self _setAsideSubviews];
2172 // Turn off the additional clip while computing our visibleRect.
2173 - (NSRect)visibleRect
2175 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2176 return [super visibleRect];
2178 WebClipView *clipView = (WebClipView *)[self superview];
2180 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2181 if (!hasAdditionalClip) {
2182 return [super visibleRect];
2185 NSRect additionalClip = [clipView additionalClip];
2186 [clipView resetAdditionalClip];
2187 NSRect visibleRect = [super visibleRect];
2188 [clipView setAdditionalClip:additionalClip];
2197 - (void)windowDidBecomeKey:(NSNotification *)notification
2199 ASSERT([notification object] == [self window]);
2200 [self addMouseMovedObserver];
2201 [self updateFocusDisplay];
2204 - (void)windowDidResignKey: (NSNotification *)notification
2206 ASSERT([notification object] == [self window]);
2207 [_private->compController endRevertingChange:NO moveLeft:NO];
2208 [self removeMouseMovedObserver];
2209 [self updateFocusDisplay];
2212 - (void)windowWillClose:(NSNotification *)notification
2214 [_private->compController endRevertingChange:NO moveLeft:NO];
2215 [[self _pluginController] destroyAllPlugins];
2218 - (void)scrollWheel:(NSEvent *)event
2220 if (![[self _bridge] scrollOverflowWithScrollWheelEvent:event]) {
2221 [[self nextResponder] scrollWheel:event];
2225 - (BOOL)_isSelectionEvent:(NSEvent *)event
2227 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2228 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2231 - (void)_setMouseDownEvent:(NSEvent *)event
2233 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2235 if (event == _private->mouseDownEvent) {
2240 [_private->mouseDownEvent release];
2241 _private->mouseDownEvent = event;
2243 [_private->firstResponderAtMouseDownTime release];
2244 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2247 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2249 [self _setMouseDownEvent:event];
2251 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2254 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2255 // the purposes of this method we want to really query the deepest view, so we forward to it.
2256 forceRealHitTest = YES;
2257 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2258 forceRealHitTest = NO;
2260 if ([hitView isKindOfClass:[self class]]) {
2261 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2262 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2263 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2265 return [hitView acceptsFirstMouse:event];
2269 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2271 [self _setMouseDownEvent:event];
2273 // We hack AK's hitTest method to catch all events at the topmost WebHTMLView. However, for
2274 // the purposes of this method we want to really query the deepest view, so we forward to it.
2275 forceRealHitTest = YES;
2276 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
2277 forceRealHitTest = NO;
2279 if ([hitView isKindOfClass:[self class]]) {
2280 WebHTMLView *hitHTMLView = (WebHTMLView *)hitView;
2281 return [self _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2283 return [hitView shouldDelayWindowOrderingForEvent:event];
2287 - (void)mouseDown:(NSEvent *)event
2289 _private->handlingMouseDownEvent = YES;
2291 // Record the mouse down position so we can determine drag hysteresis.
2292 [self _setMouseDownEvent:event];
2294 // TEXTINPUT: if there is marked text and the current input
2295 // manager wants to handle mouse events, we need to make sure to
2296 // pass it to them. If not, then we need to notify the input
2297 // manager when the marked text is abandoned (user clicks outside
2300 [_private->compController endRevertingChange:NO moveLeft:NO];
2302 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2303 // We don't want to pass them along to KHTML a second time.
2304 if (!([event modifierFlags] & NSControlKeyMask)) {
2305 _private->ignoringMouseDraggedEvents = NO;
2307 // Don't do any mouseover while the mouse is down.
2308 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2310 // Let KHTML get a chance to deal with the event. This will call back to us
2311 // to start the autoscroll timer if appropriate.
2312 [[self _bridge] mouseDown:event];
2315 [_private->firstResponderAtMouseDownTime release];
2316 _private->firstResponderAtMouseDownTime = nil;
2318 _private->handlingMouseDownEvent = NO;
2321 - (void)dragImage:(NSImage *)dragImage
2323 offset:(NSSize)offset
2324 event:(NSEvent *)event
2325 pasteboard:(NSPasteboard *)pasteboard
2327 slideBack:(BOOL)slideBack
2329 [self _stopAutoscrollTimer];
2331 _private->initiatedDrag = YES;
2332 [[self _webView] _setInitiatedDrag:YES];
2334 // Retain this view during the drag because it may be released before the drag ends.
2337 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2340 - (void)mouseDragged:(NSEvent *)event
2342 // TEXTINPUT: if there is marked text and the current input
2343 // manager wants to handle mouse events, we need to make sure to
2346 if (!_private->ignoringMouseDraggedEvents) {
2347 [[self _bridge] mouseDragged:event];
2351 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2353 if (_private->webCoreDragOp == NSDragOperationNone) {
2354 return (NSDragOperationGeneric | NSDragOperationCopy);
2356 return _private->webCoreDragOp;
2360 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2362 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2363 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2364 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2367 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2369 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2370 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2371 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2373 _private->initiatedDrag = NO;
2374 [[self _webView] _setInitiatedDrag:NO];
2376 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2377 _private->ignoringMouseDraggedEvents = YES;
2379 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2380 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2381 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2382 location:windowMouseLoc
2383 modifierFlags:[[NSApp currentEvent] modifierFlags]
2384 timestamp:[NSDate timeIntervalSinceReferenceDate]
2385 windowNumber:[[self window] windowNumber]
2386 context:[[NSApp currentEvent] context]
2387 eventNumber:0 clickCount:0 pressure:0];
2388 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2390 // Balance the previous retain from when the drag started.
2394 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2396 ASSERT(_private->draggingImageURL);
2398 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2401 // FIXME: Report an error if we fail to create a file.
2402 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2403 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2404 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2405 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2408 return [NSArray arrayWithObject:[path lastPathComponent]];
2411 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2413 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2414 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2415 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2416 if ([types count] == 0) {
2418 } else if ([types count] == 1 &&
2419 [types containsObject:NSFilenamesPboardType] &&
2420 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2424 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2425 NSDictionary *element = [self elementAtPoint:point];
2426 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2427 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2428 // Can't drag onto the selection being dragged.
2439 return _private->initiatedDrag &&
2440 ([self _isEditable] && [self _hasSelection]) &&
2441 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2444 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2446 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2449 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2451 NSDragOperation operation = NSDragOperationNone;
2453 if (actionMask & WebDragDestinationActionDHTML) {
2454 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2456 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2458 if ((actionMask & WebDragDestinationActionEdit) &&
2459 !_private->webCoreHandlingDrag
2460 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2461 if ([self _isNSColorDrag:draggingInfo]) {
2462 operation = NSDragOperationGeneric;
2465 WebView *webView = [self _webView];
2466 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2467 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2470 [[self _webView] removeDragCaret];
2476 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2478 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2479 [[self _webView] removeDragCaret];
2482 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2484 WebView *webView = [self _webView];
2485 WebBridge *bridge = [self _bridge];
2486 if (_private->webCoreHandlingDrag) {
2487 ASSERT(actionMask & WebDragDestinationActionDHTML);
2488 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2489 [bridge concludeDragForDraggingInfo:draggingInfo];
2491 } else if (actionMask & WebDragDestinationActionEdit) {
2492 if ([self _isNSColorDrag:draggingInfo]) {
2493 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2496 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2497 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2498 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2499 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2500 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2506 BOOL didInsert = NO;
2507 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2508 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2509 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES];
2510 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2511 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2512 if ([self _isMoveDrag]) {
2513 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2514 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2516 [bridge setSelectionToDragCaret];
2517 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
2522 [webView removeDragCaret];
2529 - (NSDictionary *)elementAtPoint:(NSPoint)point
2531 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2532 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2534 // Convert URL strings to NSURLs
2535 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2536 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2538 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2539 ASSERT(webFrameView);
2540 WebFrame *webFrame = [webFrameView webFrame];
2543 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2544 if ([frameName length] == 0) {
2545 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2547 WebFrame *wf = [webFrame findFrameNamed:frameName];
2549 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2551 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2554 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2557 return [elementInfo autorelease];
2560 - (void)mouseUp:(NSEvent *)event
2562 // TEXTINPUT: if there is marked text and the current input
2563 // manager wants to handle mouse events, we need to make sure to
2566 [self _stopAutoscrollTimer];
2567 [[self _bridge] mouseUp:event];
2568 [self _updateMouseoverWithFakeEvent];
2571 - (void)mouseMovedNotification:(NSNotification *)notification
2573 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2576 - (BOOL)supportsTextEncoding
2581 - (NSView *)nextValidKeyView
2584 if (![self isHiddenOrHasHiddenAncestor]) {
2585 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2588 view = [super nextValidKeyView];
2593 - (NSView *)previousValidKeyView
2596 if (![self isHiddenOrHasHiddenAncestor]) {
2597 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2600 view = [super previousValidKeyView];
2605 - (BOOL)becomeFirstResponder
2608 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2609 switch ([[self window] keyViewSelectionDirection]) {
2610 case NSDirectSelection:
2612 case NSSelectingNext:
2613 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2615 case NSSelectingPrevious:
2616 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2621 [[self window] makeFirstResponder:view];
2623 [self updateFocusDisplay];
2624 _private->startNewKillRingSequence = YES;
2628 // This approach could be relaxed when dealing with 3228554.
2629 // Some alteration to the selection behavior was done to deal with 3672088.
2630 - (BOOL)resignFirstResponder
2632 BOOL resign = [super resignFirstResponder];
2634 [_private->compController endRevertingChange:NO moveLeft:NO];
2635 _private->resigningFirstResponder = YES;
2636 if (![self maintainsInactiveSelection]) {
2637 if ([[self _webView] _isPerformingProgrammaticFocus]) {
2638 [self deselectText];
2644 [self updateFocusDisplay];
2645 _private->resigningFirstResponder = NO;
2650 //------------------------------------------------------------------------------------
2651 // WebDocumentView protocol
2652 //------------------------------------------------------------------------------------
2653 - (void)setDataSource:(WebDataSource *)dataSource
2657 - (void)dataSourceUpdated:(WebDataSource *)dataSource
2661 // Does setNeedsDisplay:NO as a side effect when printing is ending.
2662 // pageWidth != 0 implies we will relayout to a new width
2663 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
2665 WebFrame *frame = [self _frame];
2666 NSArray *subframes = [frame childFrames];
2667 unsigned n = [subframes count];
2669 for (i = 0; i != n; ++i) {
2670 WebFrame *subframe = [subframes objectAtIndex:i];
2671 WebFrameView *frameView = [subframe frameView];
2672 if ([[subframe dataSource] _isDocumentHTML]) {
2673 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
2677 if (printing != _private->printing) {
2678 [_private->pageRects release];
2679 _private->pageRects = nil;
2680 _private->printing = printing;
2681 [self setNeedsToApplyStyles:YES];
2682 [self setNeedsLayout:YES];
2683 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2685 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
2687 // Can't do this when starting printing or nested printing won't work, see 3491427.
2688 [self setNeedsDisplay:NO];
2693 // This is needed for the case where the webview is embedded in the view that's being printed.
2694 // It shouldn't be called when the webview is being printed directly.
2695 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
2697 // This helps when we print as part of a larger print process.
2698 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
2699 BOOL wasInPrintingMode = _private->printing;
2700 if (!wasInPrintingMode) {
2701 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2704 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
2706 if (!wasInPrintingMode) {
2707 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
2711 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
2713 NSPrintInfo *printInfo = [printOperation printInfo];
2714 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
2717 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2719 float viewWidth = NSWidth([self bounds]);
2720 if (viewWidth < 1) {
2721 ERROR("%@ has no width when printing", self);
2725 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2726 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
2727 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
2728 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
2731 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
2732 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
2733 // if AppKit makes it SPI/API.
2734 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
2736 return [self _scaleFactorForPrintOperation:printOperation];
2739 - (void)setPageWidthForPrinting:(float)pageWidth
2741 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
2742 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
2746 // Return the number of pages available for printing
2747 - (BOOL)knowsPageRange:(NSRangePointer)range {
2748 // Must do this explicit display here, because otherwise the view might redisplay while the print
2749 // sheet was up, using printer fonts (and looking different).
2750 [self displayIfNeeded];
2751 [[self window] setAutodisplay:NO];
2753 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
2754 // according to the paper size
2755 float minLayoutWidth = 0.0;
2756 float maxLayoutWidth = 0.0;
2757 if (![[self _bridge] isFrameSet]) {
2758 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
2759 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
2760 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
2762 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
2764 // There is a theoretical chance that someone could do some drawing between here and endDocument,
2765 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
2766 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
2768 range->location = 1;
2769 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
2770 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
2771 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
2772 [_private->pageRects release];
2773 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
2774 printHeight:[self _calculatePrintHeight]/totalScaleFactor];
2775 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
2776 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
2777 // a blank page (with correct-looking header and footer if that option is on), which matches
2778 // the behavior of IE and Camino at least.
2779 if ([newPageRects count] == 0) {
2780 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
2782 _private->pageRects = [newPageRects retain];
2784 range->length = [_private->pageRects count];
2789 // Return the drawing rectangle for a particular page number
2790 - (NSRect)rectForPage:(int)page {
2791 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
2794 - (void)drawPageBorderWithSize:(NSSize)borderSize
2796 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
2797 [[self _webView] _drawHeaderAndFooter];
2800 - (void)beginDocument
2803 [super beginDocument];
2805 // Exception during [super beginDocument] means that endDocument will not get called,
2806 // so we need to clean up our "print mode" here.
2807 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2808 [[self window] setAutodisplay:YES];
2814 [super endDocument];
2815 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
2816 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
2817 [[self window] setAutodisplay:YES];
2820 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
2822 // Work around this bug:
2823 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
2824 [NSKeyBindingManager sharedKeyBindingManager];
2826 // Use the isEditable state to determine whether or not to process tab key events.
2827 // The idea here is that isEditable will be NO when this WebView is being used
2828 // in a browser, and we desire the behavior where tab moves to the next element
2829 // in tab order. If isEditable is YES, it is likely that the WebView is being
2830 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
2831 // in a text editor.
2832 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
2835 // Now process the key normally
2836 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
2840 - (void)keyDown:(NSEvent *)event
2842 BOOL callSuper = NO;
2844 _private->keyDownEvent = event;
2846 WebBridge *bridge = [self _bridge];
2847 if ([bridge interceptKeyEvent:event toView:self]) {
2848 // WebCore processed a key event, bail on any outstanding complete: UI
2849 [_private->compController endRevertingChange:YES moveLeft:NO];
2850 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
2851 // Consumed by complete: popup window
2853 // We're going to process a key event, bail on any outstanding complete: UI
2854 [_private->compController endRevertingChange:YES moveLeft:NO];
2855 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
2856 // Consumed by key bindings manager.
2862 [super keyDown:event];
2864 [NSCursor setHiddenUntilMouseMoves:YES];
2867 _private->keyDownEvent = nil;
2870 - (void)keyUp:(NSEvent *)event
2872 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
2873 [super keyUp:event];
2877 - (id)accessibilityAttributeValue:(NSString*)attributeName
2879 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
2880 id accTree = [[self _bridge] accessibilityTree];
2882 return [NSArray arrayWithObject: accTree];
2885 return [super accessibilityAttributeValue:attributeName];
2888 - (id)accessibilityFocusedUIElement
2890 id accTree = [[self _bridge] accessibilityTree];
2892 return [accTree accessibilityFocusedUIElement];
2897 - (id)accessibilityHitTest:(NSPoint)point
2899 id accTree = [[self _bridge] accessibilityTree];
2901 NSPoint windowCoord = [[self window] convertScreenToBase: point];
2902 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
2908 - (void)centerSelectionInVisibleArea:(id)sender
2910 [[self _bridge] centerSelectionInVisibleArea];
2913 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
2915 WebBridge *bridge = [self _bridge];
2916 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
2917 WebView *webView = [self _webView];
2918 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2919 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
2923 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
2925 WebBridge *bridge = [self _bridge];
2926 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
2927 WebView *webView = [self _webView];
2928 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
2929 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
2933 - (void)moveBackward:(id)sender
2935 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
2938 - (void)moveBackwardAndModifySelection:(id)sender
2940 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
2943 - (void)moveDown:(id)sender
2945 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
2948 - (void)moveDownAndModifySelection:(id)sender
2950 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
2953 - (void)moveForward:(id)sender
2955 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
2958 - (void)moveForwardAndModifySelection:(id)sender
2960 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
2963 - (void)moveLeft:(id)sender
2965 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
2968 - (void)moveLeftAndModifySelection:(id)sender
2970 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
2973 - (void)moveRight:(id)sender
2975 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
2978 - (void)moveRightAndModifySelection:(id)sender
2980 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
2983 - (void)moveToBeginningOfDocument:(id)sender
2985 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2988 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
2990 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
2993 - (void)moveToBeginningOfLine:(id)sender
2995 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
2998 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3000 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3003 - (void)moveToBeginningOfParagraph:(id)sender
3005 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3008 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3010 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3013 - (void)moveToEndOfDocument:(id)sender
3015 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3018 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3020 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3023 - (void)moveToEndOfLine:(id)sender
3025 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
3028 - (void)moveToEndOfLineAndModifySelection:(id)sender
3030 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
3033 - (void)moveToEndOfParagraph:(id)sender
3035 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3038 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3040 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3043 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3045 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
3048 - (void)moveParagraphForwardAndModifySelection:(id)sender
3050 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
3053 - (void)moveUp:(id)sender
3055 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
3058 - (void)moveUpAndModifySelection:(id)sender
3060 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3063 - (void)moveWordBackward:(id)sender
3065 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3068 - (void)moveWordBackwardAndModifySelection:(id)sender
3070 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3073 - (void)moveWordForward:(id)sender
3075 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3078 - (void)moveWordForwardAndModifySelection:(id)sender
3080 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3083 - (void)moveWordLeft:(id)sender
3085 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3088 - (void)moveWordLeftAndModifySelection:(id)sender
3090 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3093 - (void)moveWordRight:(id)sender
3095 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3098 - (void)moveWordRightAndModifySelection:(id)sender
3100 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3103 - (void)pageUp:(id)sender
3105 WebFrameView *frameView = [self _web_parentWebFrameView];
3106 if (frameView == nil)
3108 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3111 - (void)pageDown:(id)sender
3113 WebFrameView *frameView = [self _web_parentWebFrameView];
3114 if (frameView == nil)
3116 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3119 - (void)pageUpAndModifySelection:(id)sender
3121 WebFrameView *frameView = [self _web_parentWebFrameView];
3122 if (frameView == nil)
3124 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3127 - (void)pageDownAndModifySelection:(id)sender
3129 WebFrameView *frameView = [self _web_parentWebFrameView];
3130 if (frameView == nil)
3132 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3135 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3137 WebBridge *bridge = [self _bridge];
3138 DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3139 if (range && ![range collapsed]) {
3140 WebView *webView = [self _webView];
3141 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3142 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity]];
3147 - (void)selectParagraph:(id)sender
3149 [self _expandSelectionToGranularity:WebSelectByParagraph];
3152 - (void)selectLine:(id)sender
3154 [self _expandSelectionToGranularity:WebSelectByLine];
3157 - (void)selectWord:(id)sender
3159 [self _expandSelectionToGranularity:WebSelectByWord];
3162 - (void)copy:(id)sender
3164 if ([[self _bridge] tryDHTMLCopy]) {
3165 return; // DHTML did the whole operation
3167 if (![self _canCopy]) {
3171 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3174 - (void)delete:(id)sender
3176 if (![self _canDelete]) {
3180 [self _deleteSelection];
3183 - (void)cut:(id)sender
3185 WebBridge *bridge = [self _bridge];
3186 if ([bridge tryDHTMLCut]) {
3187 return; // DHTML did the whole operation
3189 if (![self _canCut]) {
3193 DOMRange *range = [self _selectedRange];
3194 if ([self _shouldDeleteRange:range]) {
3195 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3196 [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3200 - (void)paste:(id)sender
3202 if ([[self _bridge] tryDHTMLPaste]) {
3203 return; // DHTML did the whole operation
3205 if (![self _canPaste]) {
3208 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3211 - (NSData *)_selectionStartFontAttributesAsRTF
3213 NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3214 attributes:[[self _bridge] fontAttributesForSelectionStart]];
3215 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3220 - (NSDictionary *)_fontAttributesFromFontPasteboard
3222 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3223 if (fontPasteboard == nil)
3225 NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3226 if (data == nil || [data length] == 0)
3228 // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3229 NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3230 if (string == nil || [string length] == 0)
3232 return [string fontAttributesInRange:NSMakeRange(0, 1)];
3235 - (DOMCSSStyleDeclaration *)_emptyStyle
3237 return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3240 - (NSString *)_colorAsString:(NSColor *)color
3242 NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3243 // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3244 // of fancy color that can't be converted to RGB. Changing that to "transparent"
3245 // might not be great, but it's probably OK.
3246 if (rgbColor == nil)
3247 return @"transparent";
3248 float r = [rgbColor redComponent];
3249 float g = [rgbColor greenComponent];
3250 float b = [rgbColor blueComponent];
3251 float a = [rgbColor alphaComponent];
3253 return @"transparent";
3254 if (r == 0 && g == 0 && b == 0 && a == 1)
3256 if (r == 1 && g == 1 && b == 1 && a == 1)
3258 // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3260 return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3261 return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3264 - (NSString *)_shadowAsString:(NSShadow *)shadow
3268 NSSize offset = [shadow shadowOffset];
3269 float blurRadius = [shadow shadowBlurRadius];
3270 if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3272 NSColor *color = [shadow shadowColor];
3275 // FIXME: Handle non-integral values here?
3276 if (blurRadius == 0)
3277 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3278 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3281 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3283 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3285 NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3286 [style setBackgroundColor:[self _colorAsString:color]];
3288 NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3290 [style setFontFamily:@"Helvetica"];
3291 [style setFontSize:@"12px"];
3292 [style setFontWeight:@"normal"];
3293 [style setFontStyle:@"normal"];
3295 NSFontManager *fm = [NSFontManager sharedFontManager];
3296 [style setFontFamily:[font familyName]];
3297 [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3298 if ([fm weightOfFont:font] >= 9) {
3299 [style setFontWeight:@"bold"];
3301 [style setFontWeight:@"normal"];
3303 if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3304 [style setFontStyle:@"italic"];
3306 [style setFontStyle:@"normal"];
3310 color = [dictionary objectForKey:NSForegroundColorAttributeName];
3311 [style setColor:color ? [self _colorAsString:color] : @"black"];
3313 NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3314 [style setTextShadow:[self _shadowAsString:shadow]];
3316 // FIXME: NSStrikethroughStyleAttributeName
3318 int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3319 if (superscriptInt > 0)
3320 [style setVerticalAlign:@"super"];
3321 else if (superscriptInt < 0)
3322 [style setVerticalAlign:@"sub"];
3324 [style setVerticalAlign:@"baseline"];
3326 // FIXME: NSUnderlineStyleAttributeName
3331 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3333 if (style == nil || [style length] == 0 || ![self _canEdit])
3335 WebView *webView = [self _webView];
3336 WebBridge *bridge = [self _bridge];
3337 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3338 [bridge applyStyle:style withUndoAction:undoAction];
3344 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3345 [style setFontWeight:@"bold"];
3346 if ([[self _bridge] selectionStartHasStyle:style])
3347 [style setFontWeight:@"normal"];
3348 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3351 - (void)_toggleItalic
3353 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3354 [style setFontStyle:@"italic"];
3355 if ([[self _bridge] selectionStartHasStyle:style])
3356 [style setFontStyle:@"normal"];
3357 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3360 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3362 ASSERT([self _webView]);
3363 if (![[[self _webView] preferences] respectStandardStyleKeyEquivalents]) {
3367 if (![self _canEdit])
3370 NSString *string = [event charactersIgnoringModifiers];
3371 if ([string isEqualToString:@"b"]) {
3375 if ([string isEqualToString:@"i"]) {
3376 [self _toggleItalic];
3383 - (BOOL)performKeyEquivalent:(NSEvent *)event
3385 if ([self _handleStyleKeyEquivalent:event]) {
3389 // Pass command-key combos through WebCore if there is a key binding available for
3390 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3391 // But don't do it if we have already handled the event.
3392 if (event != _private->keyDownEvent
3393 && [self _web_firstResponderIsSelfOrDescendantView]
3394 && [[self _bridge] interceptKeyEvent:event toView:self]) {
3397 return [super performKeyEquivalent:event];
3400 - (void)copyFont:(id)sender
3402 // Put RTF with font attributes on the pasteboard.
3403 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3404 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3405 [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3406 [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3409 - (void)pasteFont:(id)sender
3411 // Read RTF with font attributes from the pasteboard.
3412 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3413 [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]] withUndoAction:WebUndoActionPasteFont];
3416 - (void)pasteAsPlainText:(id)sender
3418 if (![self _canEdit])
3421 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3422 NSString *text = [pasteboard stringForType:NSStringPboardType];
3423 WebBridge *bridge = [self _bridge];
3424 if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3425 [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3429 - (void)pasteAsRichText:(id)sender
3431 // Since rich text always beats plain text when both are on the pasteboard, it's not
3432 // clear how this is different from plain old paste.
3433 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3436 - (NSFont *)_originalFontA
3438 return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:5 size:10];
3441 - (NSFont *)_originalFontB
3443 return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:10 size:12];
3446 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3448 if (a == nil || b == nil)
3451 NSFontManager *fm = [NSFontManager sharedFontManager];
3453 NSFont *oa = [self _originalFontA];
3455 NSString *fa = [a familyName];
3456 NSString *fb = [b familyName];
3457 if ([fa isEqualToString:fb]) {
3458 [style setFontFamily:fa];
3461 int sa = [a pointSize];
3462 int sb = [b pointSize];
3463 int soa = [oa pointSize];
3465 [style setFontSize:[NSString stringWithFormat:@"%dpx", sa]];
3466 } else if (sa < soa) {
3467 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel smaller
3468 } else if (sa > soa) {
3469 // FIXME: set up a style to tell WebCore to make the font in the selection 1 pixel larger
3472 int wa = [fm weightOfFont:a];
3473 int wb = [fm weightOfFont:b];
3476 [style setFontWeight:@"bold"];
3478 [style setFontWeight:@"normal"];
3482 BOOL ia = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3483 BOOL ib = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;