3 Copyright 2002, Apple, Inc. All rights reserved.
6 #import <WebKit/WebHTMLView.h>
9 #import <WebKit/DOMExtensions.h>
10 #import <WebKit/DOMPrivate.h>
11 #import <WebKit/WebArchive.h>
12 #import <WebKit/WebBridge.h>
13 #import <WebKit/WebClipView.h>
14 #import <WebKit/WebDataProtocol.h>
15 #import <WebKit/WebDataSourcePrivate.h>
16 #import <WebKit/WebDocumentInternal.h>
17 #import <WebKit/WebDOMOperationsPrivate.h>
18 #import <WebKit/WebEditingDelegate.h>
19 #import <WebKit/WebException.h>
20 #import <WebKit/WebFramePrivate.h>
21 #import <WebKit/WebFrameViewInternal.h>
22 #import <WebKit/WebHTMLViewInternal.h>
23 #import <WebKit/WebHTMLRepresentationPrivate.h>
24 #import <WebKit/WebImageRenderer.h>
25 #import <WebKit/WebImageRendererFactory.h>
26 #import <WebKit/WebKitLogging.h>
27 #import <WebKit/WebKitNSStringExtras.h>
28 #import <WebKit/WebNetscapePluginEmbeddedView.h>
29 #import <WebKit/WebNSEventExtras.h>
30 #import <WebKit/WebNSImageExtras.h>
31 #import <WebKit/WebNSObjectExtras.h>
32 #import <WebKit/WebNSPasteboardExtras.h>
33 #import <WebKit/WebNSPrintOperationExtras.h>
34 #import <WebKit/WebNSURLExtras.h>
35 #import <WebKit/WebNSViewExtras.h>
36 #import <WebKit/WebPluginController.h>
37 #import <WebKit/WebPreferences.h>
38 #import <WebKit/WebPreferencesPrivate.h>
39 #import <WebKit/WebResourcePrivate.h>
40 #import <WebKit/WebStringTruncator.h>
41 #import <WebKit/WebTextRenderer.h>
42 #import <WebKit/WebTextRendererFactory.h>
43 #import <WebKit/WebUIDelegatePrivate.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/NSURLFileTypeMappings.h>
54 #import <CoreGraphics/CGContextGState.h>
56 // Included to help work around this bug:
57 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
58 #import <AppKit/NSKeyBindingManager.h>
60 // Included so usage of _NSSoftLinkingGetFrameworkFuncPtr will compile
61 #import <mach-o/dyld.h>
64 // need to declare this because AppKit does not make it available as API or SPI
65 extern NSString *NSMarkedClauseSegmentAttributeName;
66 extern NSString *NSTextInputReplacementRangeAttributeName;
68 // Kill ring calls. Would be better to use NSKillRing.h, but that's not available in SPI.
69 void _NSInitializeKillRing(void);
70 void _NSAppendToKillRing(NSString *);
71 void _NSPrependToKillRing(NSString *);
72 NSString *_NSYankFromKillRing(void);
73 NSString *_NSYankPreviousFromKillRing(void);
74 void _NSNewKillRingSequence(void);
75 void _NSSetKillRingToYankedState(void);
76 void _NSResetKillRingOperationFlag(void);
78 @interface NSView (AppKitSecretsIKnowAbout)
79 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView;
80 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
82 - (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
83 - (void)_propagateDirtyRectsToOpaqueAncestors;
86 @interface NSApplication (AppKitSecretsIKnowAbout)
87 - (void)speakString:(NSString *)string;
90 @interface NSWindow (AppKitSecretsIKnowAbout)
91 - (id)_newFirstResponderAfterResigning;
94 @interface NSAttributedString (AppKitSecretsIKnowAbout)
95 - (id)_initWithDOMRange:(DOMRange *)domRange;
96 - (DOMDocumentFragment *)_documentFromRange:(NSRange)range document:(DOMDocument *)document documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
99 @interface NSSpellChecker (CurrentlyPrivateForTextView)
100 - (void)learnWord:(NSString *)word;
103 // By imaging to a width a little wider than the available pixels,
104 // thin pages will be scaled down a little, matching the way they
105 // print in IE and Camino. This lets them use fewer sheets than they
106 // would otherwise, which is presumably why other browsers do this.
107 // Wide pages will be scaled down more than this.
108 #define PrintingMinimumShrinkFactor 1.25
110 // This number determines how small we are willing to reduce the page content
111 // in order to accommodate the widest line. If the page would have to be
112 // reduced smaller to make the widest line fit, we just clip instead (this
113 // behavior matches MacIE and Mozilla, at least)
114 #define PrintingMaximumShrinkFactor 2.0
116 #define AUTOSCROLL_INTERVAL 0.1
118 #define DRAG_LABEL_BORDER_X 4.0
119 #define DRAG_LABEL_BORDER_Y 2.0
120 #define DRAG_LABEL_RADIUS 5.0
121 #define DRAG_LABEL_BORDER_Y_OFFSET 2.0
123 #define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP 120.0
124 #define MAX_DRAG_LABEL_WIDTH 320.0
126 #define DRAG_LINK_LABEL_FONT_SIZE 11.0
127 #define DRAG_LINK_URL_FONT_SIZE 10.0
129 #ifndef OMIT_TIGER_FEATURES
130 #define USE_APPKIT_FOR_ATTRIBUTED_STRINGS
133 // Any non-zero value will do, but using something recognizable might help us debug some day.
134 #define TRACKING_RECT_TAG 0xBADFACE
136 // FIXME: This constant is copied from AppKit's _NXSmartPaste constant.
137 #define WebSmartPastePboardType @"NeXT smart paste pasteboard type"
139 #define STANDARD_WEIGHT 5
140 #define MIN_BOLD_WEIGHT 9
141 #define STANDARD_BOLD_WEIGHT 10
144 deleteSelectionAction,
146 forwardDeleteKeyAction
149 static BOOL forceRealHitTest = NO;
151 // Used to avoid linking with ApplicationServices framework for _DCMDictionaryServiceWindowShow
152 void *_NSSoftLinkingGetFrameworkFuncPtr(NSString *inUmbrellaFrameworkName,
153 NSString *inFrameworkName,
154 const char *inFuncName,
155 const struct mach_header **ioCachedFrameworkImageHeaderPtr);
158 @interface WebHTMLView (WebTextSizing) <_web_WebDocumentTextSizing>
161 @interface WebHTMLView (WebHTMLViewFileInternal)
162 - (BOOL)_imageExistsAtPaths:(NSArray *)paths;
163 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText;
164 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText;
165 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action;
166 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action;
167 - (float)_calculatePrintHeight;
168 - (void)_updateTextSizeMultiplier;
169 - (DOMRange *)_selectedRange;
170 - (BOOL)_shouldDeleteRange:(DOMRange *)range;
171 - (void)_deleteRange:(DOMRange *)range
172 killRing:(BOOL)killRing
173 prepend:(BOOL)prepend
174 smartDeleteOK:(BOOL)smartDeleteOK
175 deletionAction:(WebDeletionAction)deletionAction;
176 - (void)_deleteSelection;
177 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard;
178 - (NSView *)_hitViewForEvent:(NSEvent *)event;
179 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString;
182 @interface WebHTMLView (WebForwardDeclaration) // FIXME: Put this in a normal category and stop doing the forward declaration trick.
183 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize;
186 @interface WebHTMLView (WebNSTextInputSupport) <NSTextInput>
187 - (void)_updateSelectionForInputManager;
188 - (void)_insertText:(NSString *)text selectInsertedText:(BOOL)selectText;
191 @interface WebHTMLView (WebEditingStyleSupport)
192 - (DOMCSSStyleDeclaration *)_emptyStyle;
193 - (NSString *)_colorAsString:(NSColor *)color;
196 @interface NSView (WebHTMLViewFileInternal)
197 - (void)_web_setPrintingModeRecursive;
198 - (void)_web_clearPrintingModeRecursive;
199 - (void)_web_layoutIfNeededRecursive;
200 - (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
203 @interface NSMutableDictionary (WebHTMLViewFileInternal)
204 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
207 // Handles the complete: text command
208 @interface WebTextCompleteController : NSObject
212 NSWindow *_popupWindow;
213 NSTableView *_tableView;
214 NSArray *_completions;
215 NSString *_originalString;
218 - (id)initWithHTMLView:(WebHTMLView *)view;
219 - (void)doCompletion;
220 - (void)endRevertingChange:(BOOL)revertChange moveLeft:(BOOL)goLeft;
221 - (BOOL)filterKeyDown:(NSEvent *)event;
222 - (void)_reflectSelection;
225 @implementation WebHTMLViewPrivate
229 ASSERT(autoscrollTimer == nil);
230 ASSERT(autoscrollTriggerEvent == nil);
232 [mouseDownEvent release];
233 [draggingImageURL release];
234 [pluginController release];
236 [compController release];
237 [firstResponderAtMouseDownTime release];
244 @implementation WebHTMLView (WebHTMLViewFileInternal)
246 - (BOOL)_imageExistsAtPaths:(NSArray *)paths
248 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
249 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
250 NSEnumerator *enumerator = [paths objectEnumerator];
253 while ((path = [enumerator nextObject]) != nil) {
254 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
255 if ([imageMIMETypes containsObject:MIMEType]) {
263 - (DOMDocumentFragment *)_documentFragmentWithPaths:(NSArray *)paths
265 DOMDocumentFragment *fragment = [[[self _bridge] DOMDocument] createDocumentFragment];
266 NSURLFileTypeMappings *mappings = [NSURLFileTypeMappings sharedMappings];
267 NSArray *imageMIMETypes = [[WebImageRendererFactory sharedFactory] supportedMIMETypes];
268 NSEnumerator *enumerator = [paths objectEnumerator];
269 WebDataSource *dataSource = [self _dataSource];
272 while ((path = [enumerator nextObject]) != nil) {
273 NSString *MIMEType = [mappings MIMETypeForExtension:[path pathExtension]];
274 if ([imageMIMETypes containsObject:MIMEType]) {
275 WebResource *resource = [[WebResource alloc] initWithData:[NSData dataWithContentsOfFile:path]
276 URL:[NSURL fileURLWithPath:path]
281 [fragment appendChild:[dataSource _imageElementWithImageResource:resource]];
287 return [fragment firstChild] != nil ? fragment : nil;
290 + (NSArray *)_excludedElementsForAttributedStringConversion
292 static NSArray *elements = nil;
293 if (elements == nil) {
294 elements = [[NSArray alloc] initWithObjects:
295 // Omit style since we want style to be inline so the fragment can be easily inserted.
297 // Omit xml so the result is not XHTML.
299 // Omit tags that will get stripped when converted to a fragment anyway.
300 @"doctype", @"html", @"head", @"body",
301 // Omit deprecated tags.
302 @"applet", @"basefont", @"center", @"dir", @"font", @"isindex", @"menu", @"s", @"strike", @"u",
303 // Omit object so no file attachments are part of the fragment.
309 - (DOMDocumentFragment *)_documentFragmentFromPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText chosePlainText:(BOOL *)chosePlainText
311 NSArray *types = [pasteboard types];
312 *chosePlainText = NO;
314 if ([types containsObject:WebArchivePboardType]) {
315 WebArchive *archive = [[WebArchive alloc] initWithData:[pasteboard dataForType:WebArchivePboardType]];
317 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithArchive:archive];
325 if ([types containsObject:NSFilenamesPboardType]) {
326 DOMDocumentFragment *fragment = [self _documentFragmentWithPaths:[pasteboard propertyListForType:NSFilenamesPboardType]];
327 if (fragment != nil) {
334 if ([types containsObject:NSHTMLPboardType]) {
335 NSString *HTMLString = [pasteboard stringForType:NSHTMLPboardType];
336 // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785.
337 if ([HTMLString hasPrefix:@"Version:"]) {
338 NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch];
339 if (range.location != NSNotFound) {
340 HTMLString = [HTMLString substringFromIndex:range.location];
343 if ([HTMLString length] != 0) {
344 return [[self _bridge] documentFragmentWithMarkupString:HTMLString baseURLString:nil];
348 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
349 NSAttributedString *string = nil;
350 if ([types containsObject:NSRTFDPboardType]) {
351 string = [[NSAttributedString alloc] initWithRTFD:[pasteboard dataForType:NSRTFDPboardType] documentAttributes:NULL];
353 if (string == nil && [types containsObject:NSRTFPboardType]) {
354 string = [[NSAttributedString alloc] initWithRTF:[pasteboard dataForType:NSRTFPboardType] documentAttributes:NULL];
357 NSDictionary *documentAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
358 [[self class] _excludedElementsForAttributedStringConversion], NSExcludedElementsDocumentAttribute,
359 self, @"WebResourceHandler", nil];
360 NSArray *subresources;
361 DOMDocumentFragment *fragment = [string _documentFromRange:NSMakeRange(0, [string length])
362 document:[[self _bridge] DOMDocument]
363 documentAttributes:documentAttributes
364 subresources:&subresources];
365 [documentAttributes release];
371 if ([types containsObject:NSTIFFPboardType]) {
372 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSTIFFPboardType]
373 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.tiff"]
374 MIMEType:@"image/tiff"
377 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
382 if ([types containsObject:NSPICTPboardType]) {
383 WebResource *resource = [[WebResource alloc] initWithData:[pasteboard dataForType:NSPICTPboardType]
384 URL:[NSURL _web_uniqueWebDataURLWithRelativeString:@"/image.pict"]
385 MIMEType:@"image/pict"
388 DOMDocumentFragment *fragment = [[self _dataSource] _documentFragmentWithImageResource:resource];
393 if ((URL = [NSURL URLFromPasteboard:pasteboard])) {
394 NSString *URLString = [URL _web_userVisibleString];
395 if ([URLString length] > 0) {
396 return [[self _bridge] documentFragmentWithText:URLString];
400 if (allowPlainText && [types containsObject:NSStringPboardType]) {
401 *chosePlainText = YES;
402 return [[self _bridge] documentFragmentWithText:[pasteboard stringForType:NSStringPboardType]];
408 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
409 - (WebResource *)resourceForData:(NSData *)data preferredFilename:(NSString *)name
411 // This method is called by [NSAttributedString _documentFromRange::::]
412 // which uses the URL of the resource for the fragment that it returns.
413 NSString *extension = [name pathExtension];
414 NSString *MIMEType = nil;
415 if ([extension length] != 0) {
416 MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
418 // Only support image resources.
419 if (MIMEType == nil || ![[[WebImageRendererFactory sharedFactory] supportedMIMETypes] containsObject:MIMEType]) {
422 NSURL *URL = [NSURL _web_URLWithUserTypedString:[NSString stringWithFormat:@"/%@", name] relativeToURL:[NSURL _web_uniqueWebDataURL]];
423 WebResource *resource = [[[WebResource alloc] initWithData:data
427 frameName:nil] autorelease];
428 [[self _dataSource] addSubresource:resource];
433 - (void)_pasteWithPasteboard:(NSPasteboard *)pasteboard allowPlainText:(BOOL)allowPlainText
436 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:allowPlainText chosePlainText:&chosePlainText];
437 WebBridge *bridge = [self _bridge];
438 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[self _selectedRange] givenAction:WebViewInsertActionPasted]) {
439 [bridge replaceSelectionWithFragment:fragment selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
443 - (BOOL)_shouldInsertFragment:(DOMDocumentFragment *)fragment replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
445 WebView *webView = [self _webView];
446 DOMNode *child = [fragment firstChild];
447 if ([fragment lastChild] == child && [child isKindOfClass:[DOMCharacterData class]]) {
448 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:[(DOMCharacterData *)child data] replacingDOMRange:range givenAction:action];
450 return [[webView _editingDelegateForwarder] webView:webView shouldInsertNode:fragment replacingDOMRange:range givenAction:action];
454 - (BOOL)_shouldReplaceSelectionWithText:(NSString *)text givenAction:(WebViewInsertAction)action
456 WebView *webView = [self _webView];
457 DOMRange *selectedRange = [self _selectedRange];
458 return [[webView _editingDelegateForwarder] webView:webView shouldInsertText:text replacingDOMRange:selectedRange givenAction:action];
461 // Calculate the vertical size of the view that fits on a single page
462 - (float)_calculatePrintHeight
464 // Obtain the print info object for the current operation
465 NSPrintInfo *pi = [[NSPrintOperation currentOperation] printInfo];
467 // Calculate the page height in points
468 NSSize paperSize = [pi paperSize];
469 return paperSize.height - [pi topMargin] - [pi bottomMargin];
472 - (void)_updateTextSizeMultiplier
474 [[self _bridge] setTextSizeMultiplier:[[self _webView] textSizeMultiplier]];
477 - (DOMRange *)_selectedRange
479 return [[self _bridge] selectedDOMRange];
482 - (BOOL)_shouldDeleteRange:(DOMRange *)range
484 if (range == nil || [range collapsed])
487 if (![[self _bridge] canDeleteRange:range])
490 WebView *webView = [self _webView];
491 return [[webView _editingDelegateForwarder] webView:webView shouldDeleteDOMRange:range];
494 - (void)_deleteRange:(DOMRange *)range
495 killRing:(BOOL)killRing
496 prepend:(BOOL)prepend
497 smartDeleteOK:(BOOL)smartDeleteOK
498 deletionAction:(WebDeletionAction)deletionAction
500 if (![self _shouldDeleteRange:range]) {
504 WebBridge *bridge = [self _bridge];
505 BOOL smartDelete = smartDeleteOK ? [self _canSmartCopyOrDelete] : NO;
507 BOOL startNewKillRingSequence = _private->startNewKillRingSequence;
510 if (startNewKillRingSequence) {
511 _NSNewKillRingSequence();
513 NSString *string = [bridge stringForRange:range];
515 _NSPrependToKillRing(string);
517 _NSAppendToKillRing(string);
519 startNewKillRingSequence = NO;
522 switch (deletionAction) {
523 case deleteSelectionAction:
524 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:YES];
525 [bridge deleteSelectionWithSmartDelete:smartDelete];
527 case deleteKeyAction:
528 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
529 [bridge deleteKeyPressedWithSmartDelete:smartDelete];
531 case forwardDeleteKeyAction:
532 [bridge setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream closeTyping:NO];
533 [bridge forwardDeleteKeyPressedWithSmartDelete:smartDelete];
537 _private->startNewKillRingSequence = startNewKillRingSequence;
540 - (void)_deleteSelection
542 [self _deleteRange:[self _selectedRange]
546 deletionAction:deleteSelectionAction];
549 - (BOOL)_canSmartReplaceWithPasteboard:(NSPasteboard *)pasteboard
551 return [[self _webView] smartInsertDeleteEnabled] && [[pasteboard types] containsObject:WebSmartPastePboardType];
554 - (NSView *)_hitViewForEvent:(NSEvent *)event
556 // Usually, we hack AK's hitTest method to catch all events at the topmost WebHTMLView.
557 // Callers of this method, however, want to query the deepest view instead.
558 forceRealHitTest = YES;
559 NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
560 forceRealHitTest = NO;
564 // This method is copied from NSTextView
565 - (NSAttributedString *)_stripAttachmentCharactersFromAttributedString:(NSAttributedString *)originalAttributedString
567 NSRange attachmentRange;
568 NSString *originalString = [originalAttributedString string];
569 static NSString *attachmentCharString = nil;
571 if (!attachmentCharString) {
573 if (!attachmentCharString) {
574 chars[0] = NSAttachmentCharacter;
576 attachmentCharString = [[NSString alloc] initWithCharacters:chars length:1];
580 attachmentRange = [originalString rangeOfString:attachmentCharString];
581 if (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
582 NSMutableAttributedString *newAttributedString = [[originalAttributedString mutableCopyWithZone:NULL] autorelease];
584 while (attachmentRange.location != NSNotFound && attachmentRange.length > 0) {
585 [newAttributedString replaceCharactersInRange:attachmentRange withString:@""];
586 attachmentRange = [[newAttributedString string] rangeOfString:attachmentCharString];
588 return newAttributedString;
590 return originalAttributedString;
594 - (void)_writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard cachedAttributedString:(NSAttributedString *)attributedString
596 // Put HTML on the pasteboard.
597 if ([types containsObject:WebArchivePboardType]) {
598 WebArchive *archive = [self _selectedArchive];
599 [pasteboard setData:[archive data] forType:WebArchivePboardType];
602 // Put the attributed string on the pasteboard (RTF/RTFD format).
603 if ([types containsObject:NSRTFDPboardType]) {
604 if (attributedString == nil) {
605 attributedString = [self selectedAttributedString];
607 NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
608 [pasteboard setData:RTFDData forType:NSRTFDPboardType];
610 if ([types containsObject:NSRTFPboardType]) {
611 if (attributedString == nil) {
612 attributedString = [self selectedAttributedString];
614 if ([attributedString containsAttachments]) {
615 attributedString = [self _stripAttachmentCharactersFromAttributedString:attributedString];
617 NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
618 [pasteboard setData:RTFData forType:NSRTFPboardType];
621 // Put plain string on the pasteboard.
622 if ([types containsObject:NSStringPboardType]) {
623 // Map to a plain old space because this is better for source code, other browsers do it,
624 // and because HTML forces you to do this any time you want two spaces in a row.
625 NSMutableString *s = [[self selectedString] mutableCopy];
626 const unichar NonBreakingSpaceCharacter = 0xA0;
627 NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&NonBreakingSpaceCharacter length:1];
628 [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])];
629 [pasteboard setString:s forType:NSStringPboardType];
633 if ([self _canSmartCopyOrDelete] && [types containsObject:WebSmartPastePboardType]) {
634 [pasteboard setData:nil forType:WebSmartPastePboardType];
640 @implementation WebHTMLView (WebPrivate)
644 [WebImageRenderer stopAnimationsInView:self];
647 + (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
649 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
650 location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
651 modifierFlags:[flagsChangedEvent modifierFlags]
652 timestamp:[flagsChangedEvent timestamp]
653 windowNumber:[flagsChangedEvent windowNumber]
654 context:[flagsChangedEvent context]
655 eventNumber:0 clickCount:0 pressure:0];
657 // Pretend it's a mouse move.
658 [[NSNotificationCenter defaultCenter]
659 postNotificationName:NSMouseMovedNotification object:self
660 userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
663 - (void)_updateMouseoverWithFakeEvent
665 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
666 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
667 modifierFlags:[[NSApp currentEvent] modifierFlags]
668 timestamp:[NSDate timeIntervalSinceReferenceDate]
669 windowNumber:[[self window] windowNumber]
670 context:[[NSApp currentEvent] context]
671 eventNumber:0 clickCount:0 pressure:0];
673 [self _updateMouseoverWithEvent:fakeEvent];
676 - (void)_frameOrBoundsChanged
678 if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
679 [self setNeedsLayout:YES];
680 [self setNeedsDisplay:YES];
681 [_private->compController endRevertingChange:NO moveLeft:NO];
684 NSPoint origin = [[self superview] bounds].origin;
685 if (!NSEqualPoints(_private->lastScrollPosition, origin)) {
686 [[self _bridge] sendScrollEvent];
687 [_private->compController endRevertingChange:NO moveLeft:NO];
689 _private->lastScrollPosition = origin;
691 SEL selector = @selector(_updateMouseoverWithFakeEvent);
692 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
693 [self performSelector:selector withObject:nil afterDelay:0];
696 - (void)_setAsideSubviews
698 ASSERT(!_private->subviewsSetAside);
699 ASSERT(_private->savedSubviews == nil);
700 _private->savedSubviews = _subviews;
702 _private->subviewsSetAside = YES;
705 - (void)_restoreSubviews
707 ASSERT(_private->subviewsSetAside);
708 ASSERT(_subviews == nil);
709 _subviews = _private->savedSubviews;
710 _private->savedSubviews = nil;
711 _private->subviewsSetAside = NO;
714 // This is called when we are about to draw, but before our dirty rect is propagated to our ancestors.
715 // That's the perfect time to do a layout, except that ideally we'd want to be sure that we're dirty
716 // before doing it. As a compromise, when we're opaque we do the layout only when actually asked to
717 // draw, but when we're transparent we do the layout at this stage so views behind us know that they
718 // need to be redrawn (in case the layout causes some things to get dirtied).
719 - (void)_propagateDirtyRectsToOpaqueAncestors
721 if (![[self _webView] drawsBackground]) {
722 [self _web_layoutIfNeededRecursive];
724 [super _propagateDirtyRectsToOpaqueAncestors];
727 // Don't let AppKit even draw subviews. We take care of that.
728 - (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView topView:(BOOL)topView
730 // This helps when we print as part of a larger print process.
731 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
732 BOOL wasInPrintingMode = _private->printing;
733 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
734 if (wasInPrintingMode != isPrinting) {
736 [self _web_setPrintingModeRecursive];
738 [self _web_clearPrintingModeRecursive];
742 [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
744 [self _setAsideSubviews];
745 [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
746 rectIsVisibleRectForView:visibleView topView:topView];
747 [self _restoreSubviews];
749 if (wasInPrintingMode != isPrinting) {
750 if (wasInPrintingMode) {
751 [self _web_setPrintingModeRecursive];
753 [self _web_clearPrintingModeRecursive];
758 // Don't let AppKit even draw subviews. We take care of that.
759 - (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
761 BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
763 BOOL wasInPrintingMode = _private->printing;
764 BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
766 if (needToSetAsideSubviews) {
767 // This helps when we print as part of a larger print process.
768 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
769 if (wasInPrintingMode != isPrinting) {
771 [self _web_setPrintingModeRecursive];
773 [self _web_clearPrintingModeRecursive];
777 NSRect boundsBeforeLayout = [self bounds];
778 [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
780 // If layout changes the view's bounds, then we need to recompute the visRect.
781 // That's because the visRect passed to us was based on the bounds at the time
782 // we were called. This method is only displayed to draw "all", so it's safe
783 // to just call visibleRect to compute the entire rectangle.
784 if (!NSEqualRects(boundsBeforeLayout, [self bounds])) {
785 visRect = [self visibleRect];
788 [self _setAsideSubviews];
791 [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
793 if (needToSetAsideSubviews) {
794 if (wasInPrintingMode != isPrinting) {
795 if (wasInPrintingMode) {
796 [self _web_setPrintingModeRecursive];
798 [self _web_clearPrintingModeRecursive];
802 [self _restoreSubviews];
806 - (BOOL)_insideAnotherHTMLView
809 while ((view = [view superview])) {
810 if ([view isKindOfClass:[WebHTMLView class]]) {
817 - (void)scrollPoint:(NSPoint)point
819 // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
820 // If we get called during the handling of a key down event, we assume the call came from
821 // NSTextView, and ignore it and use our own code to decide how to page up and page down
822 // We are smarter about how far to scroll, and we have "superview scrolling" logic.
823 NSEvent *event = [[self window] currentEvent];
824 if ([event type] == NSKeyDown) {
825 const unichar pageUp = NSPageUpFunctionKey;
826 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
827 [self tryToPerform:@selector(scrollPageUp:) with:nil];
830 const unichar pageDown = NSPageDownFunctionKey;
831 if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
832 [self tryToPerform:@selector(scrollPageDown:) with:nil];
837 [super scrollPoint:point];
840 - (NSView *)hitTest:(NSPoint)point
842 // WebHTMLView objects handle all left mouse clicks for objects inside them.
843 // That does not include left mouse clicks with the control key held down.
844 BOOL captureHitsOnSubviews;
845 if (forceRealHitTest) {
846 captureHitsOnSubviews = NO;
848 NSEvent *event = [[self window] currentEvent];
849 captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
851 if (!captureHitsOnSubviews) {
852 return [super hitTest:point];
854 if ([[self superview] mouse:point inRect:[self frame]]) {
860 static WebHTMLView *lastHitView = nil;
862 - (void)_clearLastHitViewIfSelf
864 if (lastHitView == self) {
869 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
871 ASSERT(_private->trackingRectOwner == nil);
872 _private->trackingRectOwner = owner;
873 _private->trackingRectUserData = data;
874 return TRACKING_RECT_TAG;
877 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
879 ASSERT(tag == 0 || tag == TRACKING_RECT_TAG);
880 ASSERT(_private->trackingRectOwner == nil);
881 _private->trackingRectOwner = owner;
882 _private->trackingRectUserData = data;
883 return TRACKING_RECT_TAG;
886 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
889 ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG);
890 ASSERT(_private->trackingRectOwner == nil);
891 _private->trackingRectOwner = owner;
892 _private->trackingRectUserData = userDataList[0];
893 trackingNums[0] = TRACKING_RECT_TAG;
896 - (void)removeTrackingRect:(NSTrackingRectTag)tag
900 ASSERT(tag == TRACKING_RECT_TAG);
901 if (_private != nil) {
902 _private->trackingRectOwner = nil;
906 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
909 for (i = 0; i < count; ++i) {
913 ASSERT(tag == TRACKING_RECT_TAG);
914 if (_private != nil) {
915 _private->trackingRectOwner = nil;
920 - (void)_sendToolTipMouseExited
922 // Nothing matters except window, trackingNumber, and userData.
923 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
924 location:NSMakePoint(0, 0)
927 windowNumber:[[self window] windowNumber]
930 trackingNumber:TRACKING_RECT_TAG
931 userData:_private->trackingRectUserData];
932 [_private->trackingRectOwner mouseExited:fakeEvent];
935 - (void)_sendToolTipMouseEntered
937 // Nothing matters except window, trackingNumber, and userData.
938 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
939 location:NSMakePoint(0, 0)
942 windowNumber:[[self window] windowNumber]
945 trackingNumber:TRACKING_RECT_TAG
946 userData:_private->trackingRectUserData];
947 [_private->trackingRectOwner mouseEntered:fakeEvent];
950 - (void)_setToolTip:(NSString *)string
952 NSString *toolTip = [string length] == 0 ? nil : string;
953 NSString *oldToolTip = _private->toolTip;
954 if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
958 [self _sendToolTipMouseExited];
959 [oldToolTip release];
961 _private->toolTip = [toolTip copy];
963 [self removeAllToolTips];
964 NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
965 [self addToolTipRect:wideOpenRect owner:self userData:NULL];
966 [self _sendToolTipMouseEntered];
970 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
972 return [[_private->toolTip copy] autorelease];
975 - (void)_updateMouseoverWithEvent:(NSEvent *)event
979 WebHTMLView *view = nil;
980 if ([event window] == [self window]) {
981 NSView *hitView = [self _hitViewForEvent:event];
983 if ([hitView isKindOfClass:[WebHTMLView class]]) {
984 view = (WebHTMLView *)hitView;
987 hitView = [hitView superview];
991 if (lastHitView != view && lastHitView != nil) {
992 // If we are moving out of a view (or frame), let's pretend the mouse moved
993 // all the way out of that view. But we have to account for scrolling, because
994 // khtml doesn't understand our clipping.
995 NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
996 float yScroll = visibleRect.origin.y;
997 float xScroll = visibleRect.origin.x;
999 event = [NSEvent mouseEventWithType:NSMouseMoved
1000 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
1001 modifierFlags:[[NSApp currentEvent] modifierFlags]
1002 timestamp:[NSDate timeIntervalSinceReferenceDate]
1003 windowNumber:[[self window] windowNumber]
1004 context:[[NSApp currentEvent] context]
1005 eventNumber:0 clickCount:0 pressure:0];
1006 [[lastHitView _bridge] mouseMoved:event];
1011 NSDictionary *element;
1015 [[view _bridge] mouseMoved:event];
1017 NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
1018 element = [view elementAtPoint:point];
1021 // Have the web view send a message to the delegate so it can do status bar display.
1022 [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
1024 // Set a tool tip; it won't show up right away but will if the user pauses.
1025 NSString *newToolTip = nil;
1026 if (_private->showsURLsInToolTips) {
1027 newToolTip = [[element objectForKey:WebCoreElementLinkURLKey] _web_userVisibleString];
1029 if (newToolTip == nil) {
1030 newToolTip = [element objectForKey:WebCoreElementTitleKey];
1032 [self _setToolTip:newToolTip];
1037 + (NSArray *)_insertablePasteboardTypes
1039 static NSArray *types = nil;
1041 types = [[NSArray alloc] initWithObjects:WebArchivePboardType, NSHTMLPboardType,
1042 NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSURLPboardType,
1043 NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, NSColorPboardType, nil];
1048 + (NSArray *)_selectionPasteboardTypes
1050 // FIXME: We should put data for NSHTMLPboardType on the pasteboard but Microsoft Excel doesn't like our format of HTML (3640423).
1051 return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
1054 - (WebArchive *)_selectedArchive
1058 double start = CFAbsoluteTimeGetCurrent();
1060 NSString *markupString = [[self _bridge] markupStringFromRange:[self _selectedRange] nodes:&nodes];
1062 double duration = CFAbsoluteTimeGetCurrent() - start;
1063 LOG(Timing, "copying markup took %f seconds.", duration);
1066 WebArchive *archive = [[self _dataSource] _archiveWithMarkupString:markupString nodes:nodes];
1068 if ([[self _bridge] isFrameSet]) {
1069 // Wrap the frameset document in an iframe so it can be pasted into
1070 // another document (which will have a body or frameset of its own).
1071 NSString *iframeMarkup = [[NSString alloc] initWithFormat:@"<iframe frameborder=\"no\" marginwidth=\"0\" marginheight=\"0\" width=\"98%%\" height=\"98%%\" src=\"%@\"></iframe>", [[[self _dataSource] response] URL]];
1072 WebResource *iframeResource = [[WebResource alloc] initWithData:[iframeMarkup dataUsingEncoding:NSUTF8StringEncoding]
1073 URL:[NSURL URLWithString:@"about:blank"]
1074 MIMEType:@"text/html"
1075 textEncodingName:@"UTF-8"
1078 NSArray *subframeArchives = [NSArray arrayWithObject:archive];
1079 archive = [[[WebArchive alloc] initWithMainResource:iframeResource subresources:nil subframeArchives:subframeArchives] autorelease];
1081 [iframeResource release];
1082 [iframeMarkup release];
1088 - (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
1090 ASSERT([self _hasSelection]);
1091 NSArray *types = [self pasteboardTypesForSelection];
1093 // Don't write RTFD to the pasteboard when the copied attributed string has no attachments.
1094 NSAttributedString *attributedString = [self selectedAttributedString];
1095 NSMutableArray *mutableTypes = nil;
1096 if (![attributedString containsAttachments]) {
1097 mutableTypes = [types mutableCopy];
1098 [mutableTypes removeObject:NSRTFDPboardType];
1099 types = mutableTypes;
1102 [pasteboard declareTypes:types owner:nil];
1103 [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:attributedString];
1104 [mutableTypes release];
1107 - (NSImage *)_dragImageForLinkElement:(NSDictionary *)element
1109 NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
1111 BOOL drawURLString = YES;
1112 BOOL clipURLString = NO, clipLabelString = NO;
1114 NSString *label = [element objectForKey: WebElementLinkLabelKey];
1115 NSString *urlString = [linkURL _web_userVisibleString];
1122 NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
1123 toHaveTrait:NSBoldFontMask];
1124 NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
1126 labelSize.width = [label _web_widthWithFont: labelFont];
1127 labelSize.height = [labelFont ascender] - [labelFont descender];
1128 if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
1129 labelSize.width = MAX_DRAG_LABEL_WIDTH;
1130 clipLabelString = YES;
1133 NSSize imageSize, urlStringSize;
1134 imageSize.width = labelSize.width + DRAG_LABEL_BORDER_X * 2;
1135 imageSize.height = labelSize.height + DRAG_LABEL_BORDER_Y * 2;
1136 if (drawURLString) {
1137 urlStringSize.width = [urlString _web_widthWithFont: urlFont];
1138 urlStringSize.height = [urlFont ascender] - [urlFont descender];
1139 imageSize.height += urlStringSize.height;
1140 if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
1141 imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
1142 clipURLString = YES;
1144 imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
1147 NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
1148 [dragImage lockFocus];
1150 [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
1152 // Drag a rectangle with rounded corners/
1153 NSBezierPath *path = [NSBezierPath bezierPath];
1154 [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1155 [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1156 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1157 [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
1159 [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
1160 [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1161 [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
1164 NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
1165 NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
1166 if (drawURLString) {
1168 urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
1170 [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender])
1171 withTopColor:topColor bottomColor:bottomColor font:urlFont];
1174 if (clipLabelString)
1175 label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
1176 [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
1177 withTopColor:topColor bottomColor:bottomColor font:labelFont];
1179 [dragImage unlockFocus];
1184 - (BOOL)_startDraggingImage:(NSImage *)wcDragImage at:(NSPoint)wcDragLoc operation:(NSDragOperation)op event:(NSEvent *)mouseDraggedEvent sourceIsDHTML:(BOOL)srcIsDHTML DHTMLWroteData:(BOOL)dhtmlWroteData
1186 NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
1187 NSDictionary *element = [self elementAtPoint:mouseDownPoint];
1189 NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
1190 NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
1191 BOOL isSelected = [[element objectForKey:WebElementIsSelectedKey] boolValue];
1193 [_private->draggingImageURL release];
1194 _private->draggingImageURL = nil;
1196 NSPoint mouseDraggedPoint = [self convertPoint:[mouseDraggedEvent locationInWindow] fromView:nil];
1197 _private->webCoreDragOp = op; // will be DragNone if WebCore doesn't care
1198 NSImage *dragImage = nil;
1199 NSPoint dragLoc = { 0, 0 }; // quiet gcc 4.0 warning
1201 // We allow WebCore to override the drag image, even if its a link, image or text we're dragging.
1202 // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
1203 // We could verify that ActionDHTML is allowed, although WebCore does claim to respect the action.
1205 dragImage = wcDragImage;
1206 // wcDragLoc is the cursor position relative to the lower-left corner of the image.
1207 // We add in the Y dimension because we are a flipped view, so adding moves the image down.
1210 dragLoc = NSMakePoint(mouseDraggedPoint.x - wcDragLoc.x, mouseDraggedPoint.y + wcDragLoc.y);
1212 dragLoc = NSMakePoint(mouseDownPoint.x - wcDragLoc.x, mouseDownPoint.y + wcDragLoc.y);
1214 _private->dragOffset = wcDragLoc;
1217 WebView *webView = [self _webView];
1218 NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1219 WebImageRenderer *image = [element objectForKey:WebElementImageKey];
1220 BOOL startedDrag = YES; // optimism - we almost always manage to start the drag
1222 // note per kwebster, the offset arg below is always ignored in positioning the image
1223 if (imageURL != nil && image != nil && (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1225 if (!dhtmlWroteData) {
1226 // Select the image when it is dragged. This allows the image to be moved via MoveSelectionCommandImpl and this matches NSTextView's behavior.
1227 DOMHTMLElement *imageElement = [element objectForKey:WebElementDOMNodeKey];
1228 ASSERT(imageElement != nil);
1229 [webView setSelectedDOMRange:[[[self _bridge] DOMDocument] _createRangeWithNode:imageElement] affinity:NSSelectionAffinityDownstream];
1230 _private->draggingImageURL = [imageURL retain];
1231 source = [pasteboard _web_declareAndWriteDragImage:image
1232 URL:linkURL ? linkURL : imageURL
1233 title:[element objectForKey:WebElementImageAltStringKey]
1234 archive:[imageElement webArchive]
1237 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionImage fromPoint:mouseDownPoint withPasteboard:pasteboard];
1238 if (dragImage == nil) {
1239 [self _web_dragImage:[element objectForKey:WebElementImageKey]
1240 rect:[[element objectForKey:WebElementImageRectKey] rectValue]
1241 event:_private->mouseDownEvent
1242 pasteboard:pasteboard
1244 offset:&_private->dragOffset];
1246 [self dragImage:dragImage
1249 event:_private->mouseDownEvent
1250 pasteboard:pasteboard
1254 } else if (linkURL && (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1255 if (!dhtmlWroteData) {
1256 NSArray *types = [NSPasteboard _web_writableTypesForURL];
1257 [pasteboard declareTypes:types owner:self];
1258 [pasteboard _web_writeURL:linkURL andTitle:[element objectForKey:WebElementLinkLabelKey] types:types];
1260 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionLink fromPoint:mouseDownPoint withPasteboard:pasteboard];
1261 if (dragImage == nil) {
1262 dragImage = [self _dragImageForLinkElement:element];
1263 NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
1264 dragLoc = NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height);
1265 _private->dragOffset.x = offset.width;
1266 _private->dragOffset.y = -offset.height; // inverted because we are flipped
1268 // HACK: We should pass the mouseDown event instead of the mouseDragged! This hack gets rid of
1269 // a flash of the image at the mouseDown location when the drag starts.
1270 [self dragImage:dragImage
1273 event:mouseDraggedEvent
1274 pasteboard:pasteboard
1277 } else if (isSelected && (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1278 if (!dhtmlWroteData) {
1279 [self _writeSelectionToPasteboard:pasteboard];
1281 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionSelection fromPoint:mouseDownPoint withPasteboard:pasteboard];
1282 if (dragImage == nil) {
1283 dragImage = [self _selectionDraggingImage];
1284 NSRect draggingRect = [self _selectionDraggingRect];
1285 dragLoc = NSMakePoint(NSMinX(draggingRect), NSMaxY(draggingRect));
1286 _private->dragOffset.x = mouseDownPoint.x - dragLoc.x;
1287 _private->dragOffset.y = dragLoc.y - mouseDownPoint.y; // inverted because we are flipped
1289 [self dragImage:dragImage
1292 event:_private->mouseDownEvent
1293 pasteboard:pasteboard
1296 } else if (srcIsDHTML) {
1297 ASSERT(_private->dragSourceActionMask & WebDragSourceActionDHTML);
1298 [[webView _UIDelegateForwarder] webView:webView willPerformDragSourceAction:WebDragSourceActionDHTML fromPoint:mouseDownPoint withPasteboard:pasteboard];
1299 if (dragImage == nil) {
1300 // WebCore should have given us an image, but we'll make one up
1301 NSString *imagePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"missing_image" ofType:@"tiff"];
1302 dragImage = [[[NSImage alloc] initWithContentsOfFile:imagePath] autorelease];
1303 NSSize imageSize = [dragImage size];
1304 dragLoc = NSMakePoint(mouseDownPoint.x - imageSize.width/2, mouseDownPoint.y + imageSize.height/2);
1305 _private->dragOffset.x = imageSize.width/2;
1306 _private->dragOffset.y = imageSize.height/2; // inverted because we are flipped
1308 [self dragImage:dragImage
1311 event:_private->mouseDownEvent
1312 pasteboard:pasteboard
1316 // Only way I know if to get here is if the original element clicked on in the mousedown is no longer
1317 // under the mousedown point, so linkURL, imageURL and isSelected are all false/nil.
1323 - (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
1325 [self autoscroll:event];
1326 [self _startAutoscrollTimer:event];
1329 - (BOOL)_mayStartDragAtEventLocation:(NSPoint)location
1331 NSPoint mouseDownPoint = [self convertPoint:location fromView:nil];
1332 NSDictionary *mouseDownElement = [self elementAtPoint:mouseDownPoint];
1334 ASSERT([self _webView]);
1335 if ([mouseDownElement objectForKey: WebElementImageKey] != nil &&
1336 [mouseDownElement objectForKey: WebElementImageURLKey] != nil &&
1337 [[[self _webView] preferences] loadsImagesAutomatically] &&
1338 (_private->dragSourceActionMask & WebDragSourceActionImage)) {
1342 if ([mouseDownElement objectForKey:WebElementLinkURLKey] != nil &&
1343 (_private->dragSourceActionMask & WebDragSourceActionLink)) {
1347 if ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
1348 (_private->dragSourceActionMask & WebDragSourceActionSelection)) {
1355 - (WebPluginController *)_pluginController
1357 return _private->pluginController;
1360 - (void)_web_setPrintingModeRecursive
1362 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1363 [super _web_setPrintingModeRecursive];
1366 - (void)_web_clearPrintingModeRecursive
1368 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
1369 [super _web_clearPrintingModeRecursive];
1372 - (void)_layoutIfNeeded
1374 ASSERT(!_private->subviewsSetAside);
1376 if ([[self _bridge] needsLayout])
1377 _private->needsLayout = YES;
1378 if (_private->needsToApplyStyles || _private->needsLayout)
1382 - (void)_web_layoutIfNeededRecursive
1384 [self _layoutIfNeeded];
1385 [super _web_layoutIfNeededRecursive];
1388 - (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
1390 ASSERT(!_private->subviewsSetAside);
1391 displayRect = NSIntersectionRect(displayRect, [self bounds]);
1393 if (!testDirtyRect || [self needsDisplay]) {
1394 if (testDirtyRect) {
1395 NSRect dirtyRect = [self _dirtyRect];
1396 displayRect = NSIntersectionRect(displayRect, dirtyRect);
1398 if (!NSIsEmptyRect(displayRect)) {
1399 [self _layoutIfNeeded];
1403 [super _web_layoutIfNeededRecursive:displayRect testDirtyRect:NO];
1406 - (NSRect)_selectionRect
1408 return [[self _bridge] selectionRect];
1411 - (void)_startAutoscrollTimer: (NSEvent *)triggerEvent
1413 if (_private->autoscrollTimer == nil) {
1414 _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
1415 target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
1416 _private->autoscrollTriggerEvent = [triggerEvent retain];
1420 - (void)_stopAutoscrollTimer
1422 NSTimer *timer = _private->autoscrollTimer;
1423 _private->autoscrollTimer = nil;
1424 [_private->autoscrollTriggerEvent release];
1425 _private->autoscrollTriggerEvent = nil;
1434 // Guarantee that the autoscroll timer is invalidated, even if we don't receive
1435 // a mouse up event.
1436 PSstilldown([_private->autoscrollTriggerEvent eventNumber], &isStillDown);
1438 [self _stopAutoscrollTimer];
1442 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
1443 location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
1444 modifierFlags:[[NSApp currentEvent] modifierFlags]
1445 timestamp:[NSDate timeIntervalSinceReferenceDate]
1446 windowNumber:[[self window] windowNumber]
1447 context:[[NSApp currentEvent] context]
1448 eventNumber:0 clickCount:0 pressure:0];
1449 [self mouseDragged:fakeEvent];
1454 // Copying can be done regardless of whether you can edit.
1455 return [self _hasSelection];
1460 return [self _hasSelection] && [self _isEditable];
1465 return [self _hasSelection] && [self _isEditable];
1470 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1475 return [self _hasSelectionOrInsertionPoint] && [self _isEditable];
1478 - (BOOL)_hasSelection
1480 return [[self _bridge] selectionState] == WebSelectionStateRange;
1483 - (BOOL)_hasSelectionOrInsertionPoint
1485 return [[self _bridge] selectionState] != WebSelectionStateNone;
1490 return [[self _webView] isEditable] || [[self _bridge] isSelectionEditable];
1493 - (BOOL)_isSelectionMisspelled
1495 NSString *selectedString = [self selectedString];
1496 unsigned length = [selectedString length];
1500 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:selectedString
1504 inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]
1506 return range.length == length;
1509 - (NSArray *)_guessesForMisspelledSelection
1511 ASSERT([[self selectedString] length] != 0);
1512 return [[NSSpellChecker sharedSpellChecker] guessesForWord:[self selectedString]];
1515 - (void)_changeSpellingFromMenu:(id)sender
1517 ASSERT([[self selectedString] length] != 0);
1518 [[self _bridge] replaceSelectionWithText:[sender title] selectReplacement:YES smartReplace:NO];
1521 - (void)_ignoreSpellingFromMenu:(id)sender
1523 ASSERT([[self selectedString] length] != 0);
1524 [[NSSpellChecker sharedSpellChecker] ignoreWord:[self selectedString] inSpellDocumentWithTag:[[self _webView] spellCheckerDocumentTag]];
1527 - (void)_learnSpellingFromMenu:(id)sender
1529 ASSERT([[self selectedString] length] != 0);
1530 [[NSSpellChecker sharedSpellChecker] learnWord:[self selectedString]];
1533 #ifndef OMIT_TIGER_FEATURES
1534 - (void)_searchWithGoogleFromMenu:(id)sender
1536 // This should only be called when there's a selection, but play it safe.
1537 if (![self _hasSelection]) {
1541 NSPasteboard *pboard = [NSPasteboard pasteboardWithUniqueName];
1542 if ([self writeSelectionToPasteboard:pboard types:[NSArray arrayWithObject:NSStringPboardType]]) {
1543 // FIXME: seems fragile to use the service by name, but this is what AppKit does
1544 NSPerformService(@"Search With Google", pboard);
1548 - (void)_searchWithSpotlightFromMenu:(id)sender
1550 // This should only be called when there's a selection, but play it safe.
1551 if (![self _hasSelection]) {
1555 (void)HISearchWindowShow((CFStringRef)[self selectedString], kNilOptions);
1557 - (void)_lookUpInDictionaryFromMenu:(id)sender
1559 // This should only be called when there's a selection, but play it safe.
1560 if (![self _hasSelection]) {
1564 // Soft link to dictionary-display function to avoid linking another framework (ApplicationServices/LangAnalysis)
1565 static OSStatus (*__dictionaryServiceWindowShow)(id inWordString, NSRect inWordBoundary, UInt16 inLineDirection) = NULL;
1566 static const struct mach_header *frameworkImageHeader = NULL;
1567 static BOOL lookedForFunction = NO;
1568 if (!lookedForFunction) {
1569 __dictionaryServiceWindowShow = _NSSoftLinkingGetFrameworkFuncPtr(@"ApplicationServices", @"LangAnalysis", "_DCMDictionaryServiceWindowShow", &frameworkImageHeader);
1570 lookedForFunction = YES;
1572 if (!__dictionaryServiceWindowShow) {
1573 ERROR("Couldn't find _DCMDictionaryServiceWindowShow");
1577 // FIXME: must check for right-to-left here
1578 NSWritingDirection writingDirection = NSWritingDirectionLeftToRight;
1580 NSAttributedString *attrString = [self selectedAttributedString];
1581 // FIXME: the dictionary API expects the rect for the first line of selection. Passing
1582 // the rect for the entire selection, as we do here, positions the pop-up window near
1583 // the bottom of the selection rather than at the selected word.
1584 NSRect rect = [self convertRect:[[self _bridge] visibleSelectionRect] toView:nil];
1585 rect.origin = [[self window] convertBaseToScreen:rect.origin];
1586 NSData *data = [attrString RTFFromRange:NSMakeRange(0, [attrString length]) documentAttributes:nil];
1587 (void)__dictionaryServiceWindowShow(data, rect, (writingDirection == NSWritingDirectionRightToLeft) ? 1 : 0);
1591 #if APPKIT_CODE_FOR_REFERENCE
1593 - (void)_openLinkFromMenu:(id)sender
1595 NSTextStorage *text = _getTextStorage(self);
1596 NSRange charRange = [self selectedRange];
1597 if (charRange.location != NSNotFound && charRange.length > 0) {
1598 id link = [text attribute:NSLinkAttributeName atIndex:charRange.location effectiveRange:NULL];
1600 [self clickedOnLink:link atIndex:charRange.location];
1602 NSString *string = [[text string] substringWithRange:charRange];
1603 link = [NSURL URLWithString:string];
1604 if (link) [[NSWorkspace sharedWorkspace] openURL:link];
1611 - (BOOL)_transparentBackground
1613 return _private->transparentBackground;
1616 - (void)_setTransparentBackground:(BOOL)f
1618 _private->transparentBackground = f;
1621 - (NSImage *)_selectionDraggingImage
1623 if ([self _hasSelection]) {
1624 NSImage *dragImage = [[self _bridge] selectionImage];
1625 [dragImage _web_dissolveToFraction:WebDragImageAlpha];
1631 - (NSRect)_selectionDraggingRect
1633 if ([self _hasSelection]) {
1634 return [[self _bridge] visibleSelectionRect];
1641 @implementation NSView (WebHTMLViewFileInternal)
1643 - (void)_web_setPrintingModeRecursive
1645 [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
1648 - (void)_web_clearPrintingModeRecursive
1650 [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
1653 - (void)_web_layoutIfNeededRecursive
1655 [_subviews makeObjectsPerformSelector:@selector(_web_layoutIfNeededRecursive)];
1658 - (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
1660 unsigned index, count;
1661 for (index = 0, count = [_subviews count]; index < count; index++) {
1662 NSView *subview = [_subviews objectAtIndex:index];
1663 NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
1664 [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
1670 @implementation NSMutableDictionary (WebHTMLViewFileInternal)
1672 - (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
1674 if (object == nil) {
1675 [self removeObjectForKey:key];
1677 [self setObject:object forKey:key];
1683 // The following is a workaround for
1684 // <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
1685 // The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
1686 // Since the category will be searched before the real class, we'll prevent the flag from being
1687 // set on the tool tip panel.
1689 @interface NSToolTipPanel : NSPanel
1692 @interface NSToolTipPanel (WebHTMLViewFileInternal)
1695 @implementation NSToolTipPanel (WebHTMLViewFileInternal)
1697 - (void)setAcceptsMouseMovedEvents:(BOOL)flag
1699 // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
1705 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
1708 @interface NSArray (WebHTMLView)
1709 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
1712 @implementation WebHTMLView
1716 [NSApp registerServicesMenuSendTypes:[[self class] _selectionPasteboardTypes]
1717 returnTypes:[[self class] _insertablePasteboardTypes]];
1718 _NSInitializeKillRing();
1721 - (void)_resetCachedWebPreferences:(NSNotification *)ignored
1723 WebPreferences *preferences = [[self _webView] preferences];
1724 // Check for nil because we might not yet have an associated webView when this is called
1725 if (preferences == nil) {
1726 preferences = [WebPreferences standardPreferences];
1728 _private->showsURLsInToolTips = [preferences showsURLsInToolTips];
1731 - (id)initWithFrame:(NSRect)frame
1733 [super initWithFrame:frame];
1735 // Make all drawing go through us instead of subviews.
1736 if (NSAppKitVersionNumber >= 711) {
1737 [self _setDrawsOwnDescendants:YES];
1740 _private = [[WebHTMLViewPrivate alloc] init];
1742 _private->pluginController = [[WebPluginController alloc] initWithDocumentView:self];
1743 _private->needsLayout = YES;
1744 [self _resetCachedWebPreferences:nil];
1745 [[NSNotificationCenter defaultCenter]
1746 addObserver:self selector:@selector(_resetCachedWebPreferences:)
1747 name:WebPreferencesChangedNotification object:nil];
1754 [self _clearLastHitViewIfSelf];
1756 [[NSNotificationCenter defaultCenter] removeObserver:self];
1757 [_private->pluginController destroyAllPlugins];
1765 [self _clearLastHitViewIfSelf];
1767 [[NSNotificationCenter defaultCenter] removeObserver:self];
1768 [_private->pluginController destroyAllPlugins];
1773 - (IBAction)takeFindStringFromSelection:(id)sender
1775 if (![self _hasSelection]) {
1780 [NSPasteboard _web_setFindPasteboardString:[self selectedString] withOwner:self];
1783 - (NSArray *)pasteboardTypesForSelection
1785 if ([self _canSmartCopyOrDelete]) {
1786 NSMutableArray *types = [[[[self class] _selectionPasteboardTypes] mutableCopy] autorelease];
1787 [types addObject:WebSmartPastePboardType];
1790 return [[self class] _selectionPasteboardTypes];
1794 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
1796 [self _writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard cachedAttributedString:nil];
1799 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
1801 [pasteboard declareTypes:types owner:nil];
1802 [self writeSelectionWithPasteboardTypes:types toPasteboard:pasteboard];
1806 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard
1808 [self _pasteWithPasteboard:pasteboard allowPlainText:YES];
1812 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
1814 if (sendType != nil && [[self pasteboardTypesForSelection] containsObject:sendType] && [self _hasSelection]) {
1816 } else if (returnType != nil && [[[self class] _insertablePasteboardTypes] containsObject:returnType] && [self _isEditable]) {
1819 return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType];
1822 - (void)selectAll:(id)sender
1827 - (void)jumpToSelection:(id)sender
1829 [[self _bridge] jumpToSelection];
1832 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
1834 SEL action = [item action];
1835 WebBridge *bridge = [self _bridge];
1837 if (action == @selector(alignCenter:)
1838 || action == @selector(alignLeft:)
1839 || action == @selector(alignJustified:)
1840 || action == @selector(alignRight:)
1841 || action == @selector(changeAttributes:)
1842 || action == @selector(changeBaseWritingDirection:) // FIXME: check menu item based on writing direction
1843 || action == @selector(changeColor:)
1844 || action == @selector(changeFont:)
1845 || action == @selector(changeSpelling:)
1846 || action == @selector(_changeSpellingFromMenu:)
1847 || action == @selector(checkSpelling:)
1848 || action == @selector(complete:)
1849 || action == @selector(deleteBackward:)
1850 || action == @selector(deleteBackwardByDecomposingPreviousCharacter:)
1851 || action == @selector(deleteForward:)
1852 || action == @selector(deleteToBeginningOfLine:)
1853 || action == @selector(deleteToBeginningOfParagraph:)
1854 || action == @selector(deleteToEndOfLine:)
1855 || action == @selector(deleteToEndOfParagraph:)
1856 || action == @selector(deleteToMark:)
1857 || action == @selector(deleteWordBackward:)
1858 || action == @selector(deleteWordForward:)
1859 || action == @selector(insertBacktab:)
1860 || action == @selector(insertLineBreak:)
1861 || action == @selector(insertNewline:)
1862 || action == @selector(insertNewlineIgnoringFieldEditor:)
1863 || action == @selector(insertParagraphSeparator:)
1864 || action == @selector(insertTab:)
1865 || action == @selector(insertTabIgnoringFieldEditor:)
1866 || action == @selector(moveBackward:)
1867 || action == @selector(moveBackwardAndModifySelection:)
1868 || action == @selector(moveDown:)
1869 || action == @selector(moveDownAndModifySelection:)
1870 || action == @selector(moveForward:)
1871 || action == @selector(moveForwardAndModifySelection:)
1872 || action == @selector(moveLeft:)
1873 || action == @selector(moveLeftAndModifySelection:)
1874 || action == @selector(moveParagraphBackwardAndModifySelection:)
1875 || action == @selector(moveParagraphForwardAndModifySelection:)
1876 || action == @selector(moveRight:)
1877 || action == @selector(moveRightAndModifySelection:)
1878 || action == @selector(moveToBeginningOfDocument:)
1879 || action == @selector(moveToBeginningOfDocumentAndModifySelection:)
1880 || action == @selector(moveToBeginningOfLine:)
1881 || action == @selector(moveToBeginningOfLineAndModifySelection:)
1882 || action == @selector(moveToBeginningOfParagraph:)
1883 || action == @selector(moveToBeginningOfParagraphAndModifySelection:)
1884 || action == @selector(moveToEndOfDocument:)
1885 || action == @selector(moveToEndOfDocumentAndModifySelection:)
1886 || action == @selector(moveToEndOfLine:)
1887 || action == @selector(moveToEndOfLineAndModifySelection:)
1888 || action == @selector(moveToEndOfParagraph:)
1889 || action == @selector(moveToEndOfParagraphAndModifySelection:)
1890 || action == @selector(moveUp:)
1891 || action == @selector(moveUpAndModifySelection:)
1892 || action == @selector(moveWordBackward:)
1893 || action == @selector(moveWordBackwardAndModifySelection:)
1894 || action == @selector(moveWordForward:)
1895 || action == @selector(moveWordForwardAndModifySelection:)
1896 || action == @selector(moveWordLeft:)
1897 || action == @selector(moveWordLeftAndModifySelection:)
1898 || action == @selector(moveWordRight:)
1899 || action == @selector(moveWordRightAndModifySelection:)
1900 || action == @selector(pageDown:)
1901 || action == @selector(pageDownAndModifySelection:)
1902 || action == @selector(pageUp:)
1903 || action == @selector(pageUpAndModifySelection:)
1904 || action == @selector(pasteFont:)
1905 || action == @selector(showGuessPanel:)
1906 || action == @selector(toggleBaseWritingDirection:)
1907 || action == @selector(transpose:)
1908 || action == @selector(yank:)
1909 || action == @selector(yankAndSelect:)) {
1910 return [self _canEdit];
1911 } else if (action == @selector(capitalizeWord:)
1912 || action == @selector(lowercaseWord:)
1913 || action == @selector(uppercaseWord:)) {
1914 return [self _hasSelection] && [self _isEditable];
1915 } else if (action == @selector(centerSelectionInVisibleArea:)
1916 || action == @selector(copyFont:)
1917 || action == @selector(setMark:)) {
1918 return [self _hasSelectionOrInsertionPoint];
1919 } else if (action == @selector(changeDocumentBackgroundColor:)) {
1920 return [[self _webView] isEditable];
1921 } else if (action == @selector(copy:)) {
1922 return [bridge mayDHTMLCopy] || [self _canCopy];
1923 } else if (action == @selector(cut:)) {
1924 return [bridge mayDHTMLCut] || [self _canDelete];
1925 } else if (action == @selector(delete:)) {
1926 return [self _canDelete];
1927 } else if (action == @selector(_ignoreSpellingFromMenu:)
1928 || action == @selector(jumpToSelection:)
1929 || action == @selector(_learnSpellingFromMenu:)
1930 || action == @selector(takeFindStringFromSelection:)) {
1931 return [self _hasSelection];
1932 } else if (action == @selector(paste:) || action == @selector(pasteAsPlainText:) || action == @selector(pasteAsRichText:)) {
1933 return [bridge mayDHTMLPaste] || [self _canPaste];
1934 } else if (action == @selector(performFindPanelAction:)) {
1935 // FIXME: Not yet implemented.
1937 } else if (action == @selector(selectToMark:)
1938 || action == @selector(swapWithMark:)) {
1939 return [self _hasSelectionOrInsertionPoint] && [[self _bridge] markDOMRange] != nil;
1940 } else if (action == @selector(subscript:)) {
1941 NSMenuItem *menuItem = (NSMenuItem *)item;
1942 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1943 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1944 [style setVerticalAlign:@"sub"];
1945 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1947 return [self _canEdit];
1948 } else if (action == @selector(superscript:)) {
1949 NSMenuItem *menuItem = (NSMenuItem *)item;
1950 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1951 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1952 [style setVerticalAlign:@"super"];
1953 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1955 return [self _canEdit];
1956 } else if (action == @selector(underline:)) {
1957 NSMenuItem *menuItem = (NSMenuItem *)item;
1958 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1959 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1960 [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
1961 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1963 return [self _canEdit];
1964 } else if (action == @selector(unscript:)) {
1965 NSMenuItem *menuItem = (NSMenuItem *)item;
1966 if ([menuItem isKindOfClass:[NSMenuItem class]]) {
1967 DOMCSSStyleDeclaration *style = [self _emptyStyle];
1968 [style setVerticalAlign:@"baseline"];
1969 [menuItem setState:[[self _bridge] selectionHasStyle:style]];
1971 return [self _canEdit];
1972 #ifndef OMIT_TIGER_FEATURES
1973 } else if (action == @selector(_searchWithSpotlightFromMenu:)
1974 || action == @selector(_searchWithGoogleFromMenu:)
1975 || action == @selector(_lookUpInDictionaryFromMenu:)) {
1976 return [self _hasSelection];
1983 - (BOOL)acceptsFirstResponder
1985 // Don't accept first responder when we first click on this view.
1986 // We have to pass the event down through WebCore first to be sure we don't hit a subview.
1987 // Do accept first responder at any other time, for example from keyboard events,
1988 // or from calls back from WebCore once we begin mouse-down event handling.
1989 NSEvent *event = [NSApp currentEvent];
1990 if ([event type] == NSLeftMouseDown
1991 && !_private->handlingMouseDownEvent
1992 && NSPointInRect([event locationInWindow], [self convertRect:[self visibleRect] toView:nil])) {
1998 - (BOOL)maintainsInactiveSelection
2000 // This method helps to determing whether the view should maintain
2001 // an inactive selection when the view is not first responder.
2002 // Traditionally, these views have not maintained such selections,
2003 // clearing them when the view was not first responder. However,
2004 // to fix bugs like this one:
2005 // <rdar://problem/3672088>: "Editable WebViews should maintain a selection even
2006 // when they're not firstResponder"
2007 // it was decided to add a switch to act more like an NSTextView.
2008 // For now, however, the view only acts in this way when the
2009 // web view is set to be editable. This will maintain traditional
2010 // behavior for WebKit clients dating back to before this change,
2011 // and will likely be a decent switch for the long term, since
2012 // clients to ste the web view to be editable probably want it
2013 // to act like a "regular" Cocoa view in terms of its selection
2015 id nextResponder = [[self window] _newFirstResponderAfterResigning];
2017 // Predict the case where we are losing first responder status only to
2018 // gain it back again. Want to keep the selection in that case.
2019 if ([nextResponder isKindOfClass:[NSScrollView class]]) {
2020 id contentView = [nextResponder contentView];
2022 nextResponder = contentView;
2025 if ([nextResponder isKindOfClass:[NSClipView class]]) {
2026 id documentView = [nextResponder documentView];
2028 nextResponder = documentView;
2032 if (nextResponder == self)
2035 if (![[self _webView] maintainsInactiveSelection])
2038 // editable views lose selection when losing first responder status
2039 // to a widget in the same page, but not otherwise
2040 BOOL loseSelection = [nextResponder isKindOfClass:[NSView class]]
2041 && [nextResponder isDescendantOf:[self _webView]];
2043 return !loseSelection;
2046 - (void)addMouseMovedObserver
2048 // Always add a mouse move observer if the DB requested, or if we're the key window.
2049 if (([[self window] isKeyWindow] && ![self _insideAnotherHTMLView]) ||
2050 [[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows]){
2051 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mouseMovedNotification:)
2052 name:NSMouseMovedNotification object:nil];
2053 [self _frameOrBoundsChanged];
2057 - (void)removeMouseMovedObserver
2059 // Don't remove the observer if we're running the DB
2060 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows])
2063 [[self _webView] _mouseDidMoveOverElement:nil modifierFlags:0];
2064 [[NSNotificationCenter defaultCenter] removeObserver:self
2065 name:NSMouseMovedNotification object:nil];
2068 - (void)updateFocusState
2070 // This method does the job of updating the view based on the view's firstResponder-ness and
2071 // the window key-ness of the window containing this view. This involves three kinds of
2072 // drawing updates right now, all handled in WebCore in response to the call over the bridge.
2074 // The three display attributes are as follows:
2076 // 1. The background color used to draw behind selected content (active | inactive color)
2077 // 2. Caret blinking (blinks | does not blink)
2078 // 3. The drawing of a focus ring around links in web pages.
2080 // Also, this is responsible for letting the bridge know if the window has gained or lost focus
2081 // so we can send focus and blur events.
2083 WebBridge *bridge = [self _bridge];
2084 BOOL windowIsKey = [[self window] isKeyWindow];
2086 BOOL flag = !_private->resigningFirstResponder && windowIsKey && [self _web_firstResponderCausesFocusDisplay];
2087 [bridge setDisplaysWithFocusAttributes:flag];
2089 [bridge setWindowHasFocus:windowIsKey];
2092 - (void)addSuperviewObservers
2094 // We watch the bounds of our superview, so that we can do a layout when the size
2095 // of the superview changes. This is different from other scrollable things that don't
2096 // need this kind of thing because their layout doesn't change.
2098 // We need to pay attention to both height and width because our "layout" has to change
2099 // to extend the background the full height of the space and because some elements have
2100 // sizes that are based on the total size of the view.
2102 NSView *superview = [self superview];
2103 if (superview && [self window]) {
2104 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
2105 name:NSViewFrameDidChangeNotification object:superview];
2106 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_frameOrBoundsChanged)
2107 name:NSViewBoundsDidChangeNotification object:superview];
2111 - (void)removeSuperviewObservers
2113 NSView *superview = [self superview];
2114 if (superview && [self window]) {
2115 [[NSNotificationCenter defaultCenter] removeObserver:self
2116 name:NSViewFrameDidChangeNotification object:superview];
2117 [[NSNotificationCenter defaultCenter] removeObserver:self
2118 name:NSViewBoundsDidChangeNotification object:superview];
2122 - (void)addWindowObservers
2124 NSWindow *window = [self window];
2126 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeKey:)
2127 name:NSWindowDidBecomeKeyNotification object:window];
2128 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:)
2129 name:NSWindowDidResignKeyNotification object:window];
2130 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:)
2131 name:NSWindowWillCloseNotification object:window];
2135 - (void)removeWindowObservers
2137 NSWindow *window = [self window];
2139 [[NSNotificationCenter defaultCenter] removeObserver:self
2140 name:NSWindowDidBecomeKeyNotification object:window];
2141 [[NSNotificationCenter defaultCenter] removeObserver:self
2142 name:NSWindowDidResignKeyNotification object:window];
2143 [[NSNotificationCenter defaultCenter] removeObserver:self
2144 name:NSWindowWillCloseNotification object:window];
2148 - (void)viewWillMoveToSuperview:(NSView *)newSuperview
2150 [self removeSuperviewObservers];
2153 - (void)viewDidMoveToSuperview
2155 // Do this here in case the text size multiplier changed when a non-HTML
2156 // view was installed.
2157 if ([self superview] != nil) {
2158 [self _updateTextSizeMultiplier];
2159 [self addSuperviewObservers];
2163 - (void)viewWillMoveToWindow:(NSWindow *)window
2165 // Don't do anything if we aren't initialized. This happens
2166 // when decoding a WebView. When WebViews are decoded their subviews
2167 // are created by initWithCoder: and so won't be normally
2168 // initialized. The stub views are discarded by WebView.
2170 // FIXME: Some of these calls may not work because this view may be already removed from it's superview.
2171 [self removeMouseMovedObserver];
2172 [self removeWindowObservers];
2173 [self removeSuperviewObservers];
2174 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2176 [[self _pluginController] stopAllPlugins];
2180 - (void)viewDidMoveToWindow
2182 // Don't do anything if we aren't initialized. This happens
2183 // when decoding a WebView. When WebViews are decoded their subviews
2184 // are created by initWithCoder: and so won't be normally
2185 // initialized. The stub views are discarded by WebView.
2187 [self _stopAutoscrollTimer];
2188 if ([self window]) {
2189 _private->lastScrollPosition = [[self superview] bounds].origin;
2190 [self addWindowObservers];
2191 [self addSuperviewObservers];
2192 [self addMouseMovedObserver];
2194 // Schedule this update, rather than making the call right now.
2195 // The reason is that placing the caret in the just-installed view requires
2196 // the HTML/XML document to be available on the WebCore side, but it is not
2197 // at the time this code is running. However, it will be there on the next
2198 // crank of the run loop. Doing this helps to make a blinking caret appear
2199 // in a new, empty window "automatic".
2200 [self performSelector:@selector(updateFocusState) withObject:nil afterDelay:0];
2202 [[self _pluginController] startAllPlugins];
2204 _private->lastScrollPosition = NSZeroPoint;
2206 _private->inWindow = YES;
2208 // Reset when we are moved out of a window after being moved into one.
2209 // Without this check, we reset ourselves before we even start.
2210 // This is only needed because viewDidMoveToWindow is called even when
2211 // the window is not changing (bug in AppKit).
2212 if (_private->inWindow) {
2214 _private->inWindow = NO;
2220 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
2222 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewWillMoveToHostWindow:) withObject:hostWindow];
2225 - (void)viewDidMoveToHostWindow
2227 [[self subviews] _web_makePluginViewsPerformSelector:@selector(viewDidMoveToHostWindow) withObject:nil];
2231 - (void)addSubview:(NSView *)view
2233 [super addSubview:view];
2235 if ([WebPluginController isPlugInView:view]) {
2236 [[self _pluginController] addPlugin:view];
2240 - (void)reapplyStyles
2242 if (!_private->needsToApplyStyles) {
2247 double start = CFAbsoluteTimeGetCurrent();
2250 [[self _bridge] reapplyStylesForDeviceType:
2251 _private->printing ? WebCoreDevicePrinter : WebCoreDeviceScreen];
2254 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2255 LOG(Timing, "%s apply style seconds = %f", [self URL], thisTime);
2258 _private->needsToApplyStyles = NO;
2261 // Do a layout, but set up a new fixed width for the purposes of doing printing layout.
2262 // minPageWidth==0 implies a non-printing layout
2263 - (void)layoutToMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)adjustViewSize
2265 [self reapplyStyles];
2267 // Ensure that we will receive mouse move events. Is this the best place to put this?
2268 [[self window] setAcceptsMouseMovedEvents: YES];
2269 [[self window] _setShouldPostEventNotifications: YES];
2271 if (!_private->needsLayout) {
2276 double start = CFAbsoluteTimeGetCurrent();
2279 LOG(View, "%@ doing layout", self);
2281 if (minPageWidth > 0.0) {
2282 [[self _bridge] forceLayoutWithMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
2284 [[self _bridge] forceLayoutAdjustingViewSize:adjustViewSize];
2286 _private->needsLayout = NO;
2288 if (!_private->printing) {
2289 // get size of the containing dynamic scrollview, so
2290 // appearance and disappearance of scrollbars will not show up
2292 NSSize newLayoutFrameSize = [[[self superview] superview] frame].size;
2293 if (_private->laidOutAtLeastOnce && !NSEqualSizes(_private->lastLayoutFrameSize, newLayoutFrameSize)) {
2294 [[self _bridge] sendResizeEvent];
2296 _private->laidOutAtLeastOnce = YES;
2297 _private->lastLayoutSize = [(NSClipView *)[self superview] documentVisibleRect].size;
2298 _private->lastLayoutFrameSize = newLayoutFrameSize;
2302 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2303 LOG(Timing, "%s layout seconds = %f", [self URL], thisTime);
2309 [self layoutToMinimumPageWidth:0.0 maximumPageWidth:0.0 adjustingViewSize:NO];
2312 - (NSMenu *)menuForEvent:(NSEvent *)event
2314 [_private->compController endRevertingChange:NO moveLeft:NO];
2316 if ([[self _bridge] sendContextMenuEvent:event]) {
2319 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2320 NSDictionary *element = [self elementAtPoint:point];
2321 return [[self _webView] _menuForElement:element];
2324 // Search from the end of the currently selected location, or from the beginning of the
2325 // document if nothing is selected.
2326 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
2328 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:NO];
2331 // Private method that adds a findInSelection parameter; might be public someday
2332 // FIXME: this is currently discovered using respondsToSelector; no SPI or API yet
2333 // FIXME: this needs to be done for other WebDocumentSearching implementors also, such as
2334 // WebPDFView and WebSearchableTextView
2335 - (BOOL)_searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag findInSelection:(BOOL)inSelectionFlag
2337 return [[self _bridge] searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag findInSelection:inSelectionFlag];
2340 - (DOMRange *)_documentRange
2342 return [[[self _bridge] DOMDocument] _documentRange];
2345 - (NSString *)string
2347 return [[self _bridge] stringForRange:[self _documentRange]];
2350 - (NSAttributedString *)_attributeStringFromDOMRange:(DOMRange *)range
2352 NSAttributedString *attributedString = nil;
2353 #ifdef USE_APPKIT_FOR_ATTRIBUTED_STRINGS
2355 double start = CFAbsoluteTimeGetCurrent();
2357 attributedString = [[[NSAttributedString alloc] _initWithDOMRange:range] autorelease];
2359 double duration = CFAbsoluteTimeGetCurrent() - start;
2360 LOG(Timing, "creating attributed string from selection took %f seconds.", duration);
2363 return attributedString;
2366 - (NSAttributedString *)attributedString
2368 WebBridge *bridge = [self _bridge];
2369 DOMDocument *document = [bridge DOMDocument];
2370 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[document _documentRange]];
2371 if (attributedString == nil) {
2372 attributedString = [bridge attributedStringFrom:document startOffset:0 to:nil endOffset:0];
2374 return attributedString;
2377 - (NSString *)selectedString
2379 return [[self _bridge] selectedString];
2382 - (NSAttributedString *)selectedAttributedString
2384 WebBridge *bridge = [self _bridge];
2385 NSAttributedString *attributedString = [self _attributeStringFromDOMRange:[self _selectedRange]];
2386 if (attributedString == nil) {
2387 attributedString = [bridge selectedAttributedString];
2389 return attributedString;
2394 [[self _bridge] selectAll];
2397 // Remove the selection.
2400 [[self _bridge] deselectAll];
2403 - (void)deselectText
2405 [[self _bridge] deselectText];
2410 return [[self _webView] drawsBackground];
2413 - (void)setNeedsDisplay:(BOOL)flag
2415 LOG(View, "%@ flag = %d", self, (int)flag);
2416 [super setNeedsDisplay: flag];
2419 - (void)setNeedsLayout: (BOOL)flag
2421 LOG(View, "%@ flag = %d", self, (int)flag);
2422 _private->needsLayout = flag;
2426 - (void)setNeedsToApplyStyles: (BOOL)flag
2428 LOG(View, "%@ flag = %d", self, (int)flag);
2429 _private->needsToApplyStyles = flag;
2432 - (void)drawRect:(NSRect)rect
2434 LOG(View, "%@ drawing", self);
2436 // Work around AppKit bug <rdar://problem/3875305> rect passed to drawRect: is too large.
2437 // Ignore the passed-in rect and instead union in the rectangles from getRectsBeingDrawn.
2438 // This does a better job of clipping out rects that are entirely outside the visible area.
2439 const NSRect *rects;
2441 [self getRectsBeingDrawn:&rects count:&count];
2443 // If count == 0 here, use the rect passed in for drawing. This is a workaround for:
2444 // <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
2445 // The reason for the workaround is that this method is called explicitly from the code
2446 // to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
2450 for (i = 0; i < count; ++i) {
2451 rect = NSUnionRect(rect, rects[i]);
2453 if (rect.size.height == 0 || rect.size.width == 0) {
2458 BOOL subviewsWereSetAside = _private->subviewsSetAside;
2459 if (subviewsWereSetAside) {
2460 [self _restoreSubviews];
2464 double start = CFAbsoluteTimeGetCurrent();
2467 [NSGraphicsContext saveGraphicsState];
2470 ASSERT([[self superview] isKindOfClass:[WebClipView class]]);
2472 [(WebClipView *)[self superview] setAdditionalClip:rect];
2475 WebTextRendererFactory *textRendererFactoryIfCoalescing = nil;
2476 if ([WebTextRenderer shouldBufferTextDrawing] && [NSView focusView]) {
2477 textRendererFactoryIfCoalescing = [WebTextRendererFactory sharedFactory];
2478 [textRendererFactoryIfCoalescing startCoalesceTextDrawing];
2481 if ([self _transparentBackground]) {
2482 [[NSColor clearColor] set];
2486 //double start = CFAbsoluteTimeGetCurrent();
2487 [[self _bridge] drawRect:rect];
2488 //LOG(Timing, "draw time %e", CFAbsoluteTimeGetCurrent() - start);
2490 if (textRendererFactoryIfCoalescing != nil) {
2491 [textRendererFactoryIfCoalescing endCoalesceTextDrawing];
2494 [(WebClipView *)[self superview] resetAdditionalClip];
2496 [NSGraphicsContext restoreGraphicsState];
2498 [(WebClipView *)[self superview] resetAdditionalClip];
2499 [NSGraphicsContext restoreGraphicsState];
2500 ERROR("Exception caught while drawing: %@", localException);
2501 [localException raise];
2505 NSRect vframe = [self frame];
2506 [[NSColor blackColor] set];
2508 path = [NSBezierPath bezierPath];
2509 [path setLineWidth:(float)0.1];
2510 [path moveToPoint:NSMakePoint(0, 0)];
2511 [path lineToPoint:NSMakePoint(vframe.size.width, vframe.size.height)];
2514 path = [NSBezierPath bezierPath];
2515 [path setLineWidth:(float)0.1];
2516 [path moveToPoint:NSMakePoint(0, vframe.size.height)];
2517 [path lineToPoint:NSMakePoint(vframe.size.width, 0)];
2523 double thisTime = CFAbsoluteTimeGetCurrent() - start;
2524 LOG(Timing, "%s draw seconds = %f", widget->part()->baseURL().URL().latin1(), thisTime);
2527 if (subviewsWereSetAside) {
2528 [self _setAsideSubviews];
2532 // Turn off the additional clip while computing our visibleRect.
2533 - (NSRect)visibleRect
2535 if (!([[self superview] isKindOfClass:[WebClipView class]]))
2536 return [super visibleRect];
2538 WebClipView *clipView = (WebClipView *)[self superview];
2540 BOOL hasAdditionalClip = [clipView hasAdditionalClip];
2541 if (!hasAdditionalClip) {
2542 return [super visibleRect];
2545 NSRect additionalClip = [clipView additionalClip];
2546 [clipView resetAdditionalClip];
2547 NSRect visibleRect = [super visibleRect];
2548 [clipView setAdditionalClip:additionalClip];
2557 - (void)windowDidBecomeKey:(NSNotification *)notification
2559 ASSERT([notification object] == [self window]);
2560 [self addMouseMovedObserver];
2561 [self updateFocusState];
2564 - (void)windowDidResignKey: (NSNotification *)notification
2566 ASSERT([notification object] == [self window]);
2567 [_private->compController endRevertingChange:NO moveLeft:NO];
2568 [self removeMouseMovedObserver];
2569 [self updateFocusState];
2572 - (void)windowWillClose:(NSNotification *)notification
2574 [_private->compController endRevertingChange:NO moveLeft:NO];
2575 [[self _pluginController] destroyAllPlugins];
2578 - (void)scrollWheel:(NSEvent *)event
2582 if (![[self _bridge] sendScrollWheelEvent:event]) {
2583 [[self nextResponder] scrollWheel:event];
2589 - (BOOL)_isSelectionEvent:(NSEvent *)event
2591 NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
2592 return [[[self elementAtPoint:point] objectForKey:WebElementIsSelectedKey] boolValue];
2595 - (void)_setMouseDownEvent:(NSEvent *)event
2597 ASSERT([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown);
2599 if (event == _private->mouseDownEvent) {
2604 [_private->mouseDownEvent release];
2605 _private->mouseDownEvent = event;
2607 [_private->firstResponderAtMouseDownTime release];
2608 _private->firstResponderAtMouseDownTime = [[[self window] firstResponder] retain];
2611 - (BOOL)acceptsFirstMouse:(NSEvent *)event
2613 NSView *hitView = [self _hitViewForEvent:event];
2614 WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2615 [hitHTMLView _setMouseDownEvent:event];
2617 if ([[self _webView] _dashboardBehavior:WebDashboardBehaviorAlwaysAcceptsFirstMouse])
2620 if (hitHTMLView != nil) {
2621 [[hitHTMLView _bridge] setActivationEventNumber:[event eventNumber]];
2622 return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2624 return [hitView acceptsFirstMouse:event];
2628 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
2630 NSView *hitView = [self _hitViewForEvent:event];
2631 WebHTMLView *hitHTMLView = [hitView isKindOfClass:[self class]] ? (WebHTMLView *)hitView : nil;
2632 if (hitHTMLView != nil) {
2633 [hitHTMLView _setMouseDownEvent:event];
2634 return [hitHTMLView _isSelectionEvent:event] ? [[hitHTMLView _bridge] eventMayStartDrag:event] : NO;
2636 return [hitView shouldDelayWindowOrderingForEvent:event];
2640 - (void)mouseDown:(NSEvent *)event
2644 _private->handlingMouseDownEvent = YES;
2646 // Record the mouse down position so we can determine drag hysteresis.
2647 [self _setMouseDownEvent:event];
2649 // TEXTINPUT: if there is marked text and the current input
2650 // manager wants to handle mouse events, we need to make sure to
2651 // pass it to them. If not, then we need to notify the input
2652 // manager when the marked text is abandoned (user clicks outside
2655 [_private->compController endRevertingChange:NO moveLeft:NO];
2657 // If the web page handles the context menu event and menuForEvent: returns nil, we'll get control click events here.
2658 // We don't want to pass them along to KHTML a second time.
2659 if (!([event modifierFlags] & NSControlKeyMask)) {
2660 _private->ignoringMouseDraggedEvents = NO;
2662 // Don't do any mouseover while the mouse is down.
2663 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_updateMouseoverWithFakeEvent) object:nil];
2665 // Let KHTML get a chance to deal with the event. This will call back to us
2666 // to start the autoscroll timer if appropriate.
2667 [[self _bridge] mouseDown:event];
2670 [_private->firstResponderAtMouseDownTime release];
2671 _private->firstResponderAtMouseDownTime = nil;
2673 _private->handlingMouseDownEvent = NO;
2678 - (void)dragImage:(NSImage *)dragImage
2680 offset:(NSSize)offset
2681 event:(NSEvent *)event
2682 pasteboard:(NSPasteboard *)pasteboard
2684 slideBack:(BOOL)slideBack
2686 [self _stopAutoscrollTimer];
2688 _private->initiatedDrag = YES;
2689 [[self _webView] _setInitiatedDrag:YES];
2691 // Retain this view during the drag because it may be released before the drag ends.
2694 [super dragImage:dragImage at:at offset:offset event:event pasteboard:pasteboard source:source slideBack:slideBack];
2697 - (void)mouseDragged:(NSEvent *)event
2701 // TEXTINPUT: if there is marked text and the current input
2702 // manager wants to handle mouse events, we need to make sure to
2705 if (!_private->ignoringMouseDraggedEvents) {
2706 [[self _bridge] mouseDragged:event];
2712 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2714 if (_private->webCoreDragOp == NSDragOperationNone) {
2715 return (NSDragOperationGeneric | NSDragOperationCopy);
2717 return _private->webCoreDragOp;
2721 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenLoc
2723 NSPoint windowImageLoc = [[self window] convertScreenToBase:screenLoc];
2724 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2725 [[self _bridge] dragSourceMovedTo:windowMouseLoc];
2728 - (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
2730 NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint];
2731 NSPoint windowMouseLoc = NSMakePoint(windowImageLoc.x + _private->dragOffset.x, windowImageLoc.y + _private->dragOffset.y);
2732 [[self _bridge] dragSourceEndedAt:windowMouseLoc operation:operation];
2734 _private->initiatedDrag = NO;
2735 [[self _webView] _setInitiatedDrag:NO];
2737 // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event.
2738 _private->ignoringMouseDraggedEvents = YES;
2740 // Once the dragging machinery kicks in, we no longer get mouse drags or the up event.
2741 // khtml expects to get balanced down/up's, so we must fake up a mouseup.
2742 NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp
2743 location:windowMouseLoc
2744 modifierFlags:[[NSApp currentEvent] modifierFlags]
2745 timestamp:[NSDate timeIntervalSinceReferenceDate]
2746 windowNumber:[[self window] windowNumber]
2747 context:[[NSApp currentEvent] context]
2748 eventNumber:0 clickCount:0 pressure:0];
2749 [self mouseUp:fakeEvent]; // This will also update the mouseover state.
2751 // Balance the previous retain from when the drag started.
2755 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
2757 ASSERT(_private->draggingImageURL);
2759 NSFileWrapper *wrapper = [[self _dataSource] _fileWrapperForURL:_private->draggingImageURL];
2762 // FIXME: Report an error if we fail to create a file.
2763 NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper preferredFilename]];
2764 path = [[NSFileManager defaultManager] _web_pathWithUniqueFilenameForPath:path];
2765 if (![wrapper writeToFile:path atomically:NO updateFilenames:YES]) {
2766 ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]");
2769 return [NSArray arrayWithObject:[path lastPathComponent]];
2772 - (BOOL)_canProcessDragWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2774 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2775 NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]];
2776 [types intersectSet:[NSSet setWithArray:[WebHTMLView _insertablePasteboardTypes]]];
2777 if ([types count] == 0) {
2779 } else if ([types count] == 1 &&
2780 [types containsObject:NSFilenamesPboardType] &&
2781 ![self _imageExistsAtPaths:[pasteboard propertyListForType:NSFilenamesPboardType]]) {
2785 NSPoint point = [self convertPoint:[draggingInfo draggingLocation] fromView:nil];
2786 NSDictionary *element = [self elementAtPoint:point];
2787 if ([[self _webView] isEditable] || [[element objectForKey:WebElementDOMNodeKey] isContentEditable]) {
2788 if (_private->initiatedDrag && [[element objectForKey:WebElementIsSelectedKey] boolValue]) {
2789 // Can't drag onto the selection being dragged.
2800 return _private->initiatedDrag &&
2801 ([self _isEditable] && [self _hasSelection]) &&
2802 ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) == 0;
2805 - (BOOL)_isNSColorDrag:(id <NSDraggingInfo>)draggingInfo
2807 return ([[[draggingInfo draggingPasteboard] types] containsObject:NSColorPboardType]);
2810 - (NSDragOperation)draggingUpdatedWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2812 NSDragOperation operation = NSDragOperationNone;
2814 if (actionMask & WebDragDestinationActionDHTML) {
2815 operation = [[self _bridge] dragOperationForDraggingInfo:draggingInfo];
2817 _private->webCoreHandlingDrag = (operation != NSDragOperationNone);
2819 if ((actionMask & WebDragDestinationActionEdit) &&
2820 !_private->webCoreHandlingDrag
2821 && [self _canProcessDragWithDraggingInfo:draggingInfo]) {
2822 if ([self _isNSColorDrag:draggingInfo]) {
2823 operation = NSDragOperationGeneric;
2826 WebView *webView = [self _webView];
2827 [webView moveDragCaretToPoint:[webView convertPoint:[draggingInfo draggingLocation] fromView:nil]];
2828 operation = [self _isMoveDrag] ? NSDragOperationMove : NSDragOperationCopy;
2831 [[self _webView] removeDragCaret];
2837 - (void)draggingCancelledWithDraggingInfo:(id <NSDraggingInfo>)draggingInfo
2839 [[self _bridge] dragExitedWithDraggingInfo:draggingInfo];
2840 [[self _webView] removeDragCaret];
2843 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)draggingInfo actionMask:(unsigned int)actionMask
2845 WebView *webView = [self _webView];
2846 WebBridge *bridge = [self _bridge];
2847 if (_private->webCoreHandlingDrag) {
2848 ASSERT(actionMask & WebDragDestinationActionDHTML);
2849 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionDHTML forDraggingInfo:draggingInfo];
2850 [bridge concludeDragForDraggingInfo:draggingInfo];
2852 } else if (actionMask & WebDragDestinationActionEdit) {
2853 if ([self _isNSColorDrag:draggingInfo]) {
2854 NSColor *color = [NSColor colorFromPasteboard:[draggingInfo draggingPasteboard]];
2857 DOMCSSStyleDeclaration *style = [self _emptyStyle];
2858 [style setProperty:@"color" :[self _colorAsString:color] :@""];
2859 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[bridge selectedDOMRange]]) {
2860 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2861 [bridge applyStyle:style withUndoAction:WebUndoActionSetColor];
2867 BOOL didInsert = NO;
2868 if ([self _canProcessDragWithDraggingInfo:draggingInfo]) {
2869 NSPasteboard *pasteboard = [draggingInfo draggingPasteboard];
2870 BOOL chosePlainText;
2871 DOMDocumentFragment *fragment = [self _documentFragmentFromPasteboard:pasteboard allowPlainText:YES chosePlainText:&chosePlainText];
2872 if (fragment && [self _shouldInsertFragment:fragment replacingDOMRange:[bridge dragCaretDOMRange] givenAction:WebViewInsertActionDropped]) {
2873 [[webView _UIDelegateForwarder] webView:webView willPerformDragDestinationAction:WebDragDestinationActionEdit forDraggingInfo:draggingInfo];
2874 if ([self _isMoveDrag]) {
2875 BOOL smartMove = [[self _bridge] selectionGranularity] == WebSelectByWord && [self _canSmartReplaceWithPasteboard:pasteboard];
2876 [bridge moveSelectionToDragCaret:fragment smartMove:smartMove];
2878 [bridge setSelectionToDragCaret];
2879 [bridge replaceSelectionWithFragment:fragment selectReplacement:YES smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard] matchStyle:chosePlainText];
2884 [webView removeDragCaret];
2891 - (NSDictionary *)elementAtPoint:(NSPoint)point
2893 NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
2894 NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
2896 // Convert URL strings to NSURLs
2897 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
2898 [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
2900 WebFrameView *webFrameView = [self _web_parentWebFrameView];
2901 ASSERT(webFrameView);
2902 WebFrame *webFrame = [webFrameView webFrame];
2905 NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
2906 if ([frameName length] == 0) {
2907 [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
2909 WebFrame *wf = [webFrame findFrameNamed:frameName];
2911 [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
2913 [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
2916 [elementInfo setObject:webFrame forKey:WebElementFrameKey];
2919 return [elementInfo autorelease];
2922 - (void)mouseUp:(NSEvent *)event
2924 // TEXTINPUT: if there is marked text and the current input
2925 // manager wants to handle mouse events, we need to make sure to
2930 [self _stopAutoscrollTimer];
2931 [[self _bridge] mouseUp:event];
2932 [self _updateMouseoverWithFakeEvent];
2937 - (void)mouseMovedNotification:(NSNotification *)notification
2939 [self _updateMouseoverWithEvent:[[notification userInfo] objectForKey:@"NSEvent"]];
2942 - (BOOL)supportsTextEncoding
2947 - (NSView *)nextValidKeyView
2950 BOOL lookInsideWebFrameViews = YES;
2951 if ([self isHiddenOrHasHiddenAncestor]) {
2952 lookInsideWebFrameViews = NO;
2953 } else if ([self _frame] == [[self _webView] mainFrame]) {
2954 // Check for case where first responder is last frame in a frameset, and we are
2955 // the top-level documentView.
2956 NSResponder *firstResponder = [[self window] firstResponder];
2957 if ((firstResponder != self) && [firstResponder isKindOfClass:[WebHTMLView class]] && ([(NSView *)firstResponder nextKeyView] == nil)) {
2958 lookInsideWebFrameViews = NO;
2962 if (lookInsideWebFrameViews) {
2963 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
2967 view = [super nextValidKeyView];
2968 // If there's no next view wired up, we must be in the last subframe.
2969 // There's no direct link to the next valid key view; get it from the bridge.
2970 // Note that view == self here when nextKeyView returns nil, due to AppKit oddness.
2971 // We'll check for both nil and self in case the AppKit oddness goes away.
2972 // WebFrameView has this same kind of logic for the previousValidKeyView case.
2973 if (view == nil || view == self) {
2974 ASSERT([self _frame] != [[self _webView] mainFrame]);
2975 ASSERT(lookInsideWebFrameViews);
2976 view = [[self _bridge] nextValidKeyViewOutsideWebFrameViews];
2983 - (NSView *)previousValidKeyView
2986 if (![self isHiddenOrHasHiddenAncestor]) {
2987 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
2990 view = [super previousValidKeyView];
2995 - (BOOL)becomeFirstResponder
2998 if (![[self _webView] _isPerformingProgrammaticFocus]) {
2999 switch ([[self window] keyViewSelectionDirection]) {
3000 case NSDirectSelection:
3002 case NSSelectingNext:
3003 view = [[self _bridge] nextKeyViewInsideWebFrameViews];
3005 case NSSelectingPrevious:
3006 view = [[self _bridge] previousKeyViewInsideWebFrameViews];
3011 [[self window] makeFirstResponder:view];
3013 [self updateFocusState];
3014 [self _updateFontPanel];
3015 _private->startNewKillRingSequence = YES;
3019 // This approach could be relaxed when dealing with 3228554.
3020 // Some alteration to the selection behavior was done to deal with 3672088.
3021 - (BOOL)resignFirstResponder
3023 BOOL resign = [super resignFirstResponder];
3025 [_private->compController endRevertingChange:NO moveLeft:NO];
3026 _private->resigningFirstResponder = YES;
3027 if (![self maintainsInactiveSelection]) {
3028 if ([[self _webView] _isPerformingProgrammaticFocus]) {
3029 [self deselectText];
3035 [self updateFocusState];
3036 _private->resigningFirstResponder = NO;
3041 //------------------------------------------------------------------------------------
3042 // WebDocumentView protocol
3043 //------------------------------------------------------------------------------------
3044 - (void)setDataSource:(WebDataSource *)dataSource
3048 - (void)dataSourceUpdated:(WebDataSource *)dataSource
3052 // Does setNeedsDisplay:NO as a side effect when printing is ending.
3053 // pageWidth != 0 implies we will relayout to a new width
3054 - (void)_setPrinting:(BOOL)printing minimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustViewSize:(BOOL)adjustViewSize
3056 WebFrame *frame = [self _frame];
3057 NSArray *subframes = [frame childFrames];
3058 unsigned n = [subframes count];
3060 for (i = 0; i != n; ++i) {
3061 WebFrame *subframe = [subframes objectAtIndex:i];
3062 WebFrameView *frameView = [subframe frameView];
3063 if ([[subframe dataSource] _isDocumentHTML]) {
3064 [(WebHTMLView *)[frameView documentView] _setPrinting:printing minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:adjustViewSize];
3068 if (printing != _private->printing) {
3069 [_private->pageRects release];
3070 _private->pageRects = nil;
3071 _private->printing = printing;
3072 [self setNeedsToApplyStyles:YES];
3073 [self setNeedsLayout:YES];
3074 [self layoutToMinimumPageWidth:minPageWidth maximumPageWidth:maxPageWidth adjustingViewSize:adjustViewSize];
3076 // Can't do this when starting printing or nested printing won't work, see 3491427.
3077 [self setNeedsDisplay:NO];
3082 - (BOOL)canPrintHeadersAndFooters
3087 // This is needed for the case where the webview is embedded in the view that's being printed.
3088 // It shouldn't be called when the webview is being printed directly.
3089 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
3091 // This helps when we print as part of a larger print process.
3092 // If the WebHTMLView itself is what we're printing, then we will never have to do this.
3093 BOOL wasInPrintingMode = _private->printing;
3094 if (!wasInPrintingMode) {
3095 [self _setPrinting:YES minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3098 [[self _bridge] adjustPageHeightNew:newBottom top:oldTop bottom:oldBottom limit:bottomLimit];
3100 if (!wasInPrintingMode) {
3101 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:NO];
3105 - (float)_availablePaperWidthForPrintOperation:(NSPrintOperation *)printOperation
3107 NSPrintInfo *printInfo = [printOperation printInfo];
3108 return [printInfo paperSize].width - [printInfo leftMargin] - [printInfo rightMargin];
3111 - (float)_scaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3113 float viewWidth = NSWidth([self bounds]);
3114 if (viewWidth < 1) {
3115 ERROR("%@ has no width when printing", self);
3119 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3120 float maxShrinkToFitScaleFactor = 1/PrintingMaximumShrinkFactor;
3121 float shrinkToFitScaleFactor = [self _availablePaperWidthForPrintOperation:printOperation]/viewWidth;
3122 return userScaleFactor * MAX(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
3125 // FIXME 3491344: This is a secret AppKit-internal method that we need to override in order
3126 // to get our shrink-to-fit to work with a custom pagination scheme. We can do this better
3127 // if AppKit makes it SPI/API.
3128 - (float)_provideTotalScaleFactorForPrintOperation:(NSPrintOperation *)printOperation
3130 return [self _scaleFactorForPrintOperation:printOperation];
3133 // This is used for Carbon printing. At some point we might want to make this public API.
3134 - (void)setPageWidthForPrinting:(float)pageWidth
3136 [self _setPrinting:NO minimumPageWidth:0. maximumPageWidth:0. adjustViewSize:NO];
3137 [self _setPrinting:YES minimumPageWidth:pageWidth maximumPageWidth:pageWidth adjustViewSize:YES];
3141 // Return the number of pages available for printing
3142 - (BOOL)knowsPageRange:(NSRangePointer)range {
3143 // Must do this explicit display here, because otherwise the view might redisplay while the print
3144 // sheet was up, using printer fonts (and looking different).
3145 [self displayIfNeeded];
3146 [[self window] setAutodisplay:NO];
3148 // If we are a frameset just print with the layout we have onscreen, otherwise relayout
3149 // according to the paper size
3150 float minLayoutWidth = 0.0;
3151 float maxLayoutWidth = 0.0;
3152 if (![[self _bridge] isFrameSet]) {
3153 float paperWidth = [self _availablePaperWidthForPrintOperation:[NSPrintOperation currentOperation]];
3154 minLayoutWidth = paperWidth*PrintingMinimumShrinkFactor;
3155 maxLayoutWidth = paperWidth*PrintingMaximumShrinkFactor;
3157 [self _setPrinting:YES minimumPageWidth:minLayoutWidth maximumPageWidth:maxLayoutWidth adjustViewSize:YES]; // will relayout
3158 [[self _webView] _adjustPrintingMarginsForHeaderAndFooter];
3160 // There is a theoretical chance that someone could do some drawing between here and endDocument,
3161 // if something caused setNeedsDisplay after this point. If so, it's not a big tragedy, because
3162 // you'd simply see the printer fonts on screen. As of this writing, this does not happen with Safari.
3164 range->location = 1;
3165 NSPrintOperation *printOperation = [NSPrintOperation currentOperation];
3166 float totalScaleFactor = [self _scaleFactorForPrintOperation:printOperation];
3167 float userScaleFactor = [printOperation _web_pageSetupScaleFactor];
3168 [_private->pageRects release];
3169 NSArray *newPageRects = [[self _bridge] computePageRectsWithPrintWidthScaleFactor:userScaleFactor
3170 printHeight:floorf([self _calculatePrintHeight]/totalScaleFactor)];
3171 // AppKit gets all messed up if you give it a zero-length page count (see 3576334), so if we
3172 // hit that case we'll pass along a degenerate 1 pixel square to print. This will print
3173 // a blank page (with correct-looking header and footer if that option is on), which matches
3174 // the behavior of IE and Camino at least.
3175 if ([newPageRects count] == 0) {
3176 newPageRects = [NSArray arrayWithObject:[NSValue valueWithRect: NSMakeRect(0, 0, 1, 1)]];
3178 _private->pageRects = [newPageRects retain];
3180 range->length = [_private->pageRects count];
3185 // Return the drawing rectangle for a particular page number
3186 - (NSRect)rectForPage:(int)page {
3187 return [[_private->pageRects objectAtIndex: (page-1)] rectValue];
3190 - (void)drawPageBorderWithSize:(NSSize)borderSize
3192 ASSERT(NSEqualSizes(borderSize, [[[NSPrintOperation currentOperation] printInfo] paperSize]));
3193 [[self _webView] _drawHeaderAndFooter];
3196 - (void)beginDocument
3199 [super beginDocument];
3201 // Exception during [super beginDocument] means that endDocument will not get called,
3202 // so we need to clean up our "print mode" here.
3203 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3204 [[self window] setAutodisplay:YES];
3210 [super endDocument];
3211 // Note sadly at this point [NSGraphicsContext currentContextDrawingToScreen] is still NO
3212 [self _setPrinting:NO minimumPageWidth:0.0 maximumPageWidth:0.0 adjustViewSize:YES];
3213 [[self window] setAutodisplay:YES];
3216 - (BOOL)_interceptEditingKeyEvent:(NSEvent *)event
3218 // Work around this bug:
3219 // <rdar://problem/3630640>: "Calling interpretKeyEvents: in a custom text view can fail to process keys right after app startup"
3220 [NSKeyBindingManager sharedKeyBindingManager];
3222 // Use the isEditable state to determine whether or not to process tab key events.
3223 // The idea here is that isEditable will be NO when this WebView is being used
3224 // in a browser, and we desire the behavior where tab moves to the next element
3225 // in tab order. If isEditable is YES, it is likely that the WebView is being
3226 // embedded as the whole view, as in Mail, and tabs should input tabs as expected
3227 // in a text editor.
3228 if (![[self _webView] isEditable] && [event _web_isTabKeyEvent])
3231 // Now process the key normally
3232 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
3236 - (void)keyDown:(NSEvent *)event
3240 BOOL callSuper = NO;
3242 _private->keyDownEvent = event;
3244 WebBridge *bridge = [self _bridge];
3245 if ([bridge interceptKeyEvent:event toView:self]) {
3246 // WebCore processed a key event, bail on any outstanding complete: UI
3247 [_private->compController endRevertingChange:YES moveLeft:NO];
3248 } else if (_private->compController && [_private->compController filterKeyDown:event]) {
3249 // Consumed by complete: popup window
3251 // We're going to process a key event, bail on any outstanding complete: UI
3252 [_private->compController endRevertingChange:YES moveLeft:NO];
3253 if ([self _canEdit] && [self _interceptEditingKeyEvent:event]) {
3254 // Consumed by key bindings manager.
3260 [super keyDown:event];
3262 [NSCursor setHiddenUntilMouseMoves:YES];
3265 _private->keyDownEvent = nil;
3270 - (void)keyUp:(NSEvent *)event
3274 if (![[self _bridge] interceptKeyEvent:event toView:self]) {
3275 [super keyUp:event];
3281 - (id)accessibilityAttributeValue:(NSString*)attributeName
3283 if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
3284 id accTree = [[self _bridge] accessibilityTree];
3286 return [NSArray arrayWithObject: accTree];
3289 return [super accessibilityAttributeValue:attributeName];
3292 - (id)accessibilityFocusedUIElement
3294 id accTree = [[self _bridge] accessibilityTree];
3296 return [accTree accessibilityFocusedUIElement];
3301 - (id)accessibilityHitTest:(NSPoint)point
3303 id accTree = [[self _bridge] accessibilityTree];
3305 NSPoint windowCoord = [[self window] convertScreenToBase: point];
3306 return [accTree accessibilityHitTest: [self convertPoint:windowCoord fromView:nil]];
3312 - (id)_accessibilityParentForSubview:(NSView *)subview
3314 id accTree = [[self _bridge] accessibilityTree];
3318 id parent = [accTree _accessibilityParentForSubview:subview];
3325 - (void)centerSelectionInVisibleArea:(id)sender
3327 [[self _bridge] centerSelectionInVisibleArea];
3330 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
3332 WebBridge *bridge = [self _bridge];
3333 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration direction:direction granularity:granularity];
3334 WebView *webView = [self _webView];
3335 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3336 [bridge alterCurrentSelection:alteration direction:direction granularity:granularity];
3340 - (void)_alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
3342 WebBridge *bridge = [self _bridge];
3343 DOMRange *proposedRange = [bridge rangeByAlteringCurrentSelection:alteration verticalDistance:verticalDistance];
3344 WebView *webView = [self _webView];
3345 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:proposedRange affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3346 [bridge alterCurrentSelection:alteration verticalDistance:verticalDistance];
3350 - (void)moveBackward:(id)sender
3352 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByCharacter];
3355 - (void)moveBackwardAndModifySelection:(id)sender
3357 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByCharacter];
3360 - (void)moveDown:(id)sender
3362 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByLine];
3365 - (void)moveDownAndModifySelection:(id)sender
3367 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByLine];
3370 - (void)moveForward:(id)sender
3372 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByCharacter];
3375 - (void)moveForwardAndModifySelection:(id)sender
3377 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByCharacter];
3380 - (void)moveLeft:(id)sender
3382 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByCharacter];
3385 - (void)moveLeftAndModifySelection:(id)sender
3387 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByCharacter];
3390 - (void)moveRight:(id)sender
3392 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByCharacter];
3395 - (void)moveRightAndModifySelection:(id)sender
3397 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByCharacter];
3400 - (void)moveToBeginningOfDocument:(id)sender
3402 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3405 - (void)moveToBeginningOfDocumentAndModifySelection:(id)sender
3407 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToDocumentBoundary];
3410 - (void)moveToBeginningOfLine:(id)sender
3412 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3415 - (void)moveToBeginningOfLineAndModifySelection:(id)sender
3417 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToLineBoundary];
3420 - (void)moveToBeginningOfParagraph:(id)sender
3422 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3425 - (void)moveToBeginningOfParagraphAndModifySelection:(id)sender
3427 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectToParagraphBoundary];
3430 - (void)moveToEndOfDocument:(id)sender
3432 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3435 - (void)moveToEndOfDocumentAndModifySelection:(id)sender
3437 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToDocumentBoundary];
3440 - (void)moveToEndOfLine:(id)sender
3442 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToLineBoundary];
3445 - (void)moveToEndOfLineAndModifySelection:(id)sender
3447 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToLineBoundary];
3450 - (void)moveToEndOfParagraph:(id)sender
3452 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3455 - (void)moveToEndOfParagraphAndModifySelection:(id)sender
3457 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectToParagraphBoundary];
3460 - (void)moveParagraphBackwardAndModifySelection:(id)sender
3462 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByParagraph];
3465 - (void)moveParagraphForwardAndModifySelection:(id)sender
3467 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByParagraph];
3470 - (void)moveUp:(id)sender
3472 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByLine];
3475 - (void)moveUpAndModifySelection:(id)sender
3477 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByLine];
3480 - (void)moveWordBackward:(id)sender
3482 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectBackward granularity:WebSelectByWord];
3485 - (void)moveWordBackwardAndModifySelection:(id)sender
3487 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectBackward granularity:WebSelectByWord];
3490 - (void)moveWordForward:(id)sender
3492 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectForward granularity:WebSelectByWord];
3495 - (void)moveWordForwardAndModifySelection:(id)sender
3497 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectForward granularity:WebSelectByWord];
3500 - (void)moveWordLeft:(id)sender
3502 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectLeft granularity:WebSelectByWord];
3505 - (void)moveWordLeftAndModifySelection:(id)sender
3507 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectLeft granularity:WebSelectByWord];
3510 - (void)moveWordRight:(id)sender
3512 [self _alterCurrentSelection:WebSelectByMoving direction:WebSelectRight granularity:WebSelectByWord];
3515 - (void)moveWordRightAndModifySelection:(id)sender
3517 [self _alterCurrentSelection:WebSelectByExtending direction:WebSelectRight granularity:WebSelectByWord];
3520 - (void)pageUp:(id)sender
3522 WebFrameView *frameView = [self _web_parentWebFrameView];
3523 if (frameView == nil)
3525 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:-[frameView _verticalPageScrollDistance]];
3528 - (void)pageDown:(id)sender
3530 WebFrameView *frameView = [self _web_parentWebFrameView];
3531 if (frameView == nil)
3533 [self _alterCurrentSelection:WebSelectByMoving verticalDistance:[frameView _verticalPageScrollDistance]];
3536 - (void)pageUpAndModifySelection:(id)sender
3538 WebFrameView *frameView = [self _web_parentWebFrameView];
3539 if (frameView == nil)
3541 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:-[frameView _verticalPageScrollDistance]];
3544 - (void)pageDownAndModifySelection:(id)sender
3546 WebFrameView *frameView = [self _web_parentWebFrameView];
3547 if (frameView == nil)
3549 [self _alterCurrentSelection:WebSelectByExtending verticalDistance:[frameView _verticalPageScrollDistance]];
3552 - (void)_expandSelectionToGranularity:(WebSelectionGranularity)granularity
3554 WebBridge *bridge = [self _bridge];
3555 DOMRange *range = [bridge rangeByExpandingSelectionWithGranularity:granularity];
3556 if (range && ![range collapsed]) {
3557 WebView *webView = [self _webView];
3558 if ([[webView _editingDelegateForwarder] webView:webView shouldChangeSelectedDOMRange:[self _selectedRange] toDOMRange:range affinity:[bridge selectionAffinity] stillSelecting:NO]) {
3559 [bridge setSelectedDOMRange:range affinity:[bridge selectionAffinity] closeTyping:YES];
3564 - (void)selectParagraph:(id)sender
3566 [self _expandSelectionToGranularity:WebSelectByParagraph];
3569 - (void)selectLine:(id)sender
3571 [self _expandSelectionToGranularity:WebSelectByLine];
3574 - (void)selectWord:(id)sender
3576 [self _expandSelectionToGranularity:WebSelectByWord];
3579 - (void)copy:(id)sender
3581 if ([[self _bridge] tryDHTMLCopy]) {
3582 return; // DHTML did the whole operation
3584 if (![self _canCopy]) {
3588 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3591 - (void)delete:(id)sender
3593 if (![self _canDelete]) {
3597 [self _deleteSelection];
3600 - (void)cut:(id)sender
3602 WebBridge *bridge = [self _bridge];
3603 if ([bridge tryDHTMLCut]) {
3604 return; // DHTML did the whole operation
3606 if (![self _canCut]) {
3610 DOMRange *range = [self _selectedRange];
3611 if ([self _shouldDeleteRange:range]) {
3612 [self _writeSelectionToPasteboard:[NSPasteboard generalPasteboard]];
3613 [bridge deleteSelectionWithSmartDelete:[self _canSmartCopyOrDelete]];
3617 - (void)paste:(id)sender
3619 if ([[self _bridge] tryDHTMLPaste]) {
3620 return; // DHTML did the whole operation
3622 if (![self _canPaste]) {
3625 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:YES];
3628 - (NSData *)_selectionStartFontAttributesAsRTF
3630 NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"x"
3631 attributes:[[self _bridge] fontAttributesForSelectionStart]];
3632 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length]) documentAttributes:nil];
3637 - (NSDictionary *)_fontAttributesFromFontPasteboard
3639 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3640 if (fontPasteboard == nil)
3642 NSData *data = [fontPasteboard dataForType:NSFontPboardType];
3643 if (data == nil || [data length] == 0)
3645 // NSTextView does something more efficient by parsing the attributes only, but that's not available in API.
3646 NSAttributedString *string = [[[NSAttributedString alloc] initWithRTF:data documentAttributes:NULL] autorelease];
3647 if (string == nil || [string length] == 0)
3649 return [string fontAttributesInRange:NSMakeRange(0, 1)];
3652 - (DOMCSSStyleDeclaration *)_emptyStyle
3654 return [[[self _bridge] DOMDocument] createCSSStyleDeclaration];
3657 - (NSString *)_colorAsString:(NSColor *)color
3659 NSColor *rgbColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
3660 // FIXME: If color is non-nil and rgbColor is nil, that means we got some kind
3661 // of fancy color that can't be converted to RGB. Changing that to "transparent"
3662 // might not be great, but it's probably OK.
3663 if (rgbColor == nil)
3664 return @"transparent";
3665 float r = [rgbColor redComponent];
3666 float g = [rgbColor greenComponent];
3667 float b = [rgbColor blueComponent];
3668 float a = [rgbColor alphaComponent];
3670 return @"transparent";
3671 if (r == 0 && g == 0 && b == 0 && a == 1)
3673 if (r == 1 && g == 1 && b == 1 && a == 1)
3675 // FIXME: Lots more named colors. Maybe we could use the table in WebCore?
3677 return [NSString stringWithFormat:@"rgb(%.0f,%.0f,%.0f)", r * 255, g * 255, b * 255];
3678 return [NSString stringWithFormat:@"rgba(%.0f,%.0f,%.0f,%f)", r * 255, g * 255, b * 255, a];
3681 - (NSString *)_shadowAsString:(NSShadow *)shadow
3685 NSSize offset = [shadow shadowOffset];
3686 float blurRadius = [shadow shadowBlurRadius];
3687 if (offset.width == 0 && offset.height == 0 && blurRadius == 0)
3689 NSColor *color = [shadow shadowColor];
3692 // FIXME: Handle non-integral values here?
3693 if (blurRadius == 0)
3694 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height];
3695 return [NSString stringWithFormat:@"%@ %.0fpx %.0fpx %.0fpx", [self _colorAsString:color], offset.width, offset.height, blurRadius];
3698 - (DOMCSSStyleDeclaration *)_styleFromFontAttributes:(NSDictionary *)dictionary
3700 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3702 NSColor *color = [dictionary objectForKey:NSBackgroundColorAttributeName];
3703 [style setBackgroundColor:[self _colorAsString:color]];
3705 NSFont *font = [dictionary objectForKey:NSFontAttributeName];
3707 [style setFontFamily:@"Helvetica"];
3708 [style setFontSize:@"12px"];
3709 [style setFontWeight:@"normal"];
3710 [style setFontStyle:@"normal"];
3712 NSFontManager *fm = [NSFontManager sharedFontManager];
3713 // FIXME: Need more sophisticated escaping code if we want to handle family names
3714 // with characters like single quote or backslash in their names.
3715 [style setFontFamily:[NSString stringWithFormat:@"'%@'", [font familyName]]];
3716 [style setFontSize:[NSString stringWithFormat:@"%0.fpx", [font pointSize]]];
3717 if ([fm weightOfFont:font] >= MIN_BOLD_WEIGHT) {
3718 [style setFontWeight:@"bold"];
3720 [style setFontWeight:@"normal"];
3722 if (([fm traitsOfFont:font] & NSItalicFontMask) != 0) {
3723 [style setFontStyle:@"italic"];
3725 [style setFontStyle:@"normal"];
3729 color = [dictionary objectForKey:NSForegroundColorAttributeName];
3730 [style setColor:color ? [self _colorAsString:color] : @"black"];
3732 NSShadow *shadow = [dictionary objectForKey:NSShadowAttributeName];
3733 [style setTextShadow:[self _shadowAsString:shadow]];
3735 int strikethroughInt = [[dictionary objectForKey:NSStrikethroughStyleAttributeName] intValue];
3737 int superscriptInt = [[dictionary objectForKey:NSSuperscriptAttributeName] intValue];
3738 if (superscriptInt > 0)
3739 [style setVerticalAlign:@"super"];
3740 else if (superscriptInt < 0)
3741 [style setVerticalAlign:@"sub"];
3743 [style setVerticalAlign:@"baseline"];
3744 int underlineInt = [[dictionary objectForKey:NSUnderlineStyleAttributeName] intValue];
3745 // FIXME: Underline wins here if we have both (see bug 3790443).
3746 if (strikethroughInt == NSUnderlineStyleNone && underlineInt == NSUnderlineStyleNone)
3747 [style setProperty:@"-khtml-text-decorations-in-effect" :@"none" :@""];
3748 else if (underlineInt == NSUnderlineStyleNone)
3749 [style setProperty:@"-khtml-text-decorations-in-effect" :@"line-through" :@""];
3751 [style setProperty:@"-khtml-text-decorations-in-effect" :@"underline" :@""];
3756 - (void)_applyStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3758 if (style == nil || [style length] == 0 || ![self _canEdit])
3760 WebView *webView = [self _webView];
3761 WebBridge *bridge = [self _bridge];
3762 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3763 [bridge applyStyle:style withUndoAction:undoAction];
3767 - (void)_applyParagraphStyleToSelection:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
3769 if (style == nil || [style length] == 0 || ![self _canEdit])
3771 WebView *webView = [self _webView];
3772 WebBridge *bridge = [self _bridge];
3773 if ([[webView _editingDelegateForwarder] webView:webView shouldApplyStyle:style toElementsInDOMRange:[self _selectedRange]]) {
3774 [bridge applyParagraphStyle:style withUndoAction:undoAction];
3780 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3781 [style setFontWeight:@"bold"];
3782 if ([[self _bridge] selectionStartHasStyle:style])
3783 [style setFontWeight:@"normal"];
3784 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3787 - (void)_toggleItalic
3789 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3790 [style setFontStyle:@"italic"];
3791 if ([[self _bridge] selectionStartHasStyle:style])
3792 [style setFontStyle:@"normal"];
3793 [self _applyStyleToSelection:style withUndoAction:WebUndoActionSetFont];
3796 - (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event
3798 ASSERT([self _webView]);
3799 if (![[[self _webView] preferences] respectStandardStyleKeyEquivalents]) {
3803 if (![self _canEdit])
3806 NSString *string = [event charactersIgnoringModifiers];
3807 if ([string isEqualToString:@"b"]) {
3811 if ([string isEqualToString:@"i"]) {
3812 [self _toggleItalic];
3819 - (BOOL)performKeyEquivalent:(NSEvent *)event
3821 if ([self _handleStyleKeyEquivalent:event]) {
3829 // Pass command-key combos through WebCore if there is a key binding available for
3830 // this event. This lets web pages have a crack at intercepting command-modified keypresses.
3831 // But don't do it if we have already handled the event.
3832 if (event != _private->keyDownEvent
3833 && [self _web_firstResponderIsSelfOrDescendantView]
3834 && [[self _bridge] interceptKeyEvent:event toView:self]) {
3839 ret = [super performKeyEquivalent:event];
3846 - (void)copyFont:(id)sender
3848 // Put RTF with font attributes on the pasteboard.
3849 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3850 NSPasteboard *fontPasteboard = [NSPasteboard pasteboardWithName:NSFontPboard];
3851 [fontPasteboard declareTypes:[NSArray arrayWithObject:NSFontPboardType] owner:nil];
3852 [fontPasteboard setData:[self _selectionStartFontAttributesAsRTF] forType:NSFontPboardType];
3855 - (void)pasteFont:(id)sender
3857 // Read RTF with font attributes from the pasteboard.
3858 // Maybe later we should add a pasteboard type that contains CSS text for "native" copy and paste font.
3859 [self _applyStyleToSelection:[self _styleFromFontAttributes:[self _fontAttributesFromFontPasteboard]] withUndoAction:WebUndoActionPasteFont];
3862 - (void)pasteAsPlainText:(id)sender
3864 if (![self _canEdit])
3867 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
3868 NSString *text = [pasteboard stringForType:NSStringPboardType];
3869 WebBridge *bridge = [self _bridge];
3870 if ([self _shouldReplaceSelectionWithText:text givenAction:WebViewInsertActionPasted]) {
3871 [bridge replaceSelectionWithText:text selectReplacement:NO smartReplace:[self _canSmartReplaceWithPasteboard:pasteboard]];
3875 - (void)pasteAsRichText:(id)sender
3877 // Since rich text always beats plain text when both are on the pasteboard, it's not
3878 // clear how this is different from plain old paste.
3879 [self _pasteWithPasteboard:[NSPasteboard generalPasteboard] allowPlainText:NO];
3882 - (NSFont *)_originalFontA
3884 return [[NSFontManager sharedFontManager] fontWithFamily:@"Helvetica" traits:0 weight:STANDARD_WEIGHT size:10];
3887 - (NSFont *)_originalFontB
3889 return [[NSFontManager sharedFontManager] fontWithFamily:@"Times" traits:(NSBoldFontMask | NSItalicFontMask) weight:STANDARD_BOLD_WEIGHT size:12];
3892 - (void)_addToStyle:(DOMCSSStyleDeclaration *)style fontA:(NSFont *)a fontB:(NSFont *)b
3894 // Since there's no way to directly ask NSFontManager what style change it's going to do
3895 // we instead pass two "specimen" fonts to it and let it change them. We then deduce what
3896 // style change it was doing by looking at what happened to each of the two fonts.
3897 // So if it was making the text bold, both fonts will be bold after the fact.
3899 if (a == nil || b == nil)
3902 NSFontManager *fm = [NSFontManager sharedFontManager];
3904 NSFont *oa = [self _originalFontA];
3906 NSString *aFamilyName = [a familyName];
3907 NSString *bFamilyName = [b familyName];
3909 int aPointSize = [a pointSize];
3910 int bPointSize = [b pointSize];
3912 int aWeight = [fm weightOfFont:a];
3913 int bWeight = [fm weightOfFont:b];
3915 BOOL aIsBold = aWeight >= MIN_BOLD_WEIGHT;
3917 BOOL aIsItalic = ([fm traitsOfFont:a] & NSItalicFontMask) != 0;
3918 BOOL bIsItalic = ([fm traitsOfFont:b] & NSItalicFontMask) != 0;
3920 if ([aFamilyName isEqualToString:bFamilyName]) {
3921 NSString *familyNameForCSS = aFamilyName;
3923 // The family name may not be specific enough to get us the font specified.
3924 // In some cases, the only way to get exactly what we are looking for is to use
3925 // the Postscript name.
3927 // Find the font the same way the rendering code would later if it encountered this CSS.
3928 WebTextRendererFactory *factory = [WebTextRendererFactory sharedFactory];
3929 NSFontTraitMask traits = 0;
3931 traits |= NSBoldFontMask;
3933 traits |= NSItalicFontMask;
3934 NSFont *foundFont = [factory cachedFontFromFamily:aFamilyName traits:traits size:aPointSize];
3936 // If we don't find a font with the same Postscript name, then we'll have to use the
3937 // Postscript name to make the CSS specific enough.
3938 if (![[foundFont fontName] isEqualToString:[a fontName]]) {
3939 familyNameForCSS = [a fontName];
3942 // FIXME: Need more sophisticated escaping code if we want to handle family names
3943 // with characters like single quote or backslash in their names.
3944 [style setFontFamily:[NSString stringWithFormat:@"'%@'", familyNameForCSS]];
3947 int soa = [oa pointSize];
3948 if (aPointSize == bPointSize) {
3949 [style setFontSize:[NSString stringWithFormat:@"%dpx", aPointSize]];
3950 } else if (aPointSize < soa) {
3951 [style _setFontSizeDelta:@"-1px"];
3952 } else if (aPointSize > soa) {
3953 [style _setFontSizeDelta:@"1px"];
3956 if (aWeight == bWeight) {
3958 [style setFontWeight:@"bold"];
3960 [style setFontWeight:@"normal"];
3964 if (aIsItalic == bIsItalic) {
3966 [style setFontStyle:@"italic"];
3968 [style setFontStyle:@"normal"];
3973 - (DOMCSSStyleDeclaration *)_styleFromFontManagerOperation
3975 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3977 NSFontManager *fm = [NSFontManager sharedFontManager];
3979 NSFont *oa = [self _originalFontA];
3980 NSFont *ob = [self _originalFontB];
3981 [self _addToStyle:style fontA:[fm convertFont:oa] fontB:[fm convertFont:ob]];
3986 - (void)changeFont:(id)sender
3988 [self _applyStyleToSelection:[self _styleFromFontManagerOperation] withUndoAction:WebUndoActionSetFont];
3991 - (DOMCSSStyleDeclaration *)_styleForAttributeChange:(id)sender
3993 DOMCSSStyleDeclaration *style = [self _emptyStyle];
3995 NSShadow *shadow = [[NSShadow alloc] init];
3996 [shadow setShadowOffset:NSMakeSize(1, 1)];
3998 NSDictionary *oa = [NSDictionary dictionaryWithObjectsAndKeys:
3999 [self _originalFontA], NSFontAttributeName,
4001 NSDictionary *ob = [NSDictionary dictionaryWithObjectsAndKeys:
4002 [NSColor blackColor], NSBackgroundColorAttributeName,
4003 [self _originalFontB], NSFontAttributeName,
4004 [NSColor whiteColor], NSForegroundColorAttributeName,
4005 shadow, NSShadowAttributeName,
4006 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName,
4007 [NSNumber numberWithInt:1], NSSuperscriptAttributeName,
4008 [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
4015 NSObliquenessAttributeName /* float; skew to be applied to glyphs, default 0: no skew */
4016 // font-style, but that is just an on-off switch
4018 NSExpansionAttributeName /* float; log of expansion factor to be applied to glyphs, default 0: no expansion */
4021 NSKernAttributeName /* float, amount to modify default kerning, if 0, kerning off */
4022 // letter-spacing? probably not good enough
4024 NSUnderlineColorAttributeName /* NSColor, default nil: same as foreground color */
4025 NSStrikethroughColorAttributeName /* NSColor, default nil: same as foreground color */
4026 // text-decoration-color?
4028 NSLigatureAttributeName /* int, default 1: default ligatures, 0: no ligatures, 2: all ligatures */
4029 NSBaselineOffsetAttributeName /* float, in points; offset from baseline, default 0 */
4030 NSStrokeWidthAttributeName /* float, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0) */
4031 NSStrokeColorAttributeName /* NSColor, default nil: same as foreground color */
4036 NSDictionary *a = [sender convertAttributes:oa];
4037 NSDictionary *b = [sender convertAttributes:ob];
4039 NSColor *ca = [a objectForKey:NSBackgroundColorAttributeName];
4040 NSColor *cb = [b objectForKey:NSBackgroundColorAttributeName];
4042 [style setBackgroundColor:[self _colorAsString:ca]];
4045 [self _addToStyle:style fontA:[a ob